cmNinjaTargetGenerator.cxx 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmNinjaTargetGenerator.h"
  4. #include "cm_jsoncpp_value.h"
  5. #include "cm_jsoncpp_writer.h"
  6. #include <algorithm>
  7. #include <assert.h>
  8. #include <iterator>
  9. #include <map>
  10. #include <memory> // IWYU pragma: keep
  11. #include <sstream>
  12. #include <utility>
  13. #include "cmAlgorithms.h"
  14. #include "cmComputeLinkInformation.h"
  15. #include "cmCustomCommandGenerator.h"
  16. #include "cmGeneratedFileStream.h"
  17. #include "cmGeneratorExpression.h"
  18. #include "cmGeneratorTarget.h"
  19. #include "cmGlobalNinjaGenerator.h"
  20. #include "cmListFileCache.h" // for BT
  21. #include "cmLocalGenerator.h"
  22. #include "cmLocalNinjaGenerator.h"
  23. #include "cmMakefile.h"
  24. #include "cmNinjaNormalTargetGenerator.h"
  25. #include "cmNinjaUtilityTargetGenerator.h"
  26. #include "cmOutputConverter.h"
  27. #include "cmRulePlaceholderExpander.h"
  28. #include "cmSourceFile.h"
  29. #include "cmState.h"
  30. #include "cmStateTypes.h"
  31. #include "cmSystemTools.h"
  32. #include "cmake.h"
  33. cmNinjaTargetGenerator* cmNinjaTargetGenerator::New(cmGeneratorTarget* target)
  34. {
  35. switch (target->GetType()) {
  36. case cmStateEnums::EXECUTABLE:
  37. case cmStateEnums::SHARED_LIBRARY:
  38. case cmStateEnums::STATIC_LIBRARY:
  39. case cmStateEnums::MODULE_LIBRARY:
  40. case cmStateEnums::OBJECT_LIBRARY:
  41. return new cmNinjaNormalTargetGenerator(target);
  42. case cmStateEnums::UTILITY:
  43. case cmStateEnums::GLOBAL_TARGET:
  44. return new cmNinjaUtilityTargetGenerator(target);
  45. default:
  46. return nullptr;
  47. }
  48. }
  49. cmNinjaTargetGenerator::cmNinjaTargetGenerator(cmGeneratorTarget* target)
  50. : cmCommonTargetGenerator(target)
  51. , MacOSXContentGenerator(nullptr)
  52. , OSXBundleGenerator(nullptr)
  53. , LocalGenerator(
  54. static_cast<cmLocalNinjaGenerator*>(target->GetLocalGenerator()))
  55. {
  56. MacOSXContentGenerator = new MacOSXContentGeneratorType(this);
  57. }
  58. cmNinjaTargetGenerator::~cmNinjaTargetGenerator()
  59. {
  60. delete this->MacOSXContentGenerator;
  61. }
  62. cmGeneratedFileStream& cmNinjaTargetGenerator::GetBuildFileStream() const
  63. {
  64. return *this->GetGlobalGenerator()->GetBuildFileStream();
  65. }
  66. cmGeneratedFileStream& cmNinjaTargetGenerator::GetRulesFileStream() const
  67. {
  68. return *this->GetGlobalGenerator()->GetRulesFileStream();
  69. }
  70. cmGlobalNinjaGenerator* cmNinjaTargetGenerator::GetGlobalGenerator() const
  71. {
  72. return this->LocalGenerator->GetGlobalNinjaGenerator();
  73. }
  74. std::string cmNinjaTargetGenerator::LanguageCompilerRule(
  75. const std::string& lang) const
  76. {
  77. return lang + "_COMPILER__" +
  78. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName());
  79. }
  80. std::string cmNinjaTargetGenerator::LanguagePreprocessRule(
  81. std::string const& lang) const
  82. {
  83. return lang + "_PREPROCESS__" +
  84. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName());
  85. }
  86. bool cmNinjaTargetGenerator::NeedExplicitPreprocessing(
  87. std::string const& lang) const
  88. {
  89. return lang == "Fortran";
  90. }
  91. std::string cmNinjaTargetGenerator::LanguageDyndepRule(
  92. const std::string& lang) const
  93. {
  94. return lang + "_DYNDEP__" +
  95. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName());
  96. }
  97. bool cmNinjaTargetGenerator::NeedDyndep(std::string const& lang) const
  98. {
  99. return lang == "Fortran";
  100. }
  101. std::string cmNinjaTargetGenerator::OrderDependsTargetForTarget()
  102. {
  103. return "cmake_object_order_depends_target_" + this->GetTargetName();
  104. }
  105. // TODO: Most of the code is picked up from
  106. // void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink),
  107. // void cmMakefileTargetGenerator::WriteTargetLanguageFlags()
  108. // Refactor it.
  109. std::string cmNinjaTargetGenerator::ComputeFlagsForObject(
  110. cmSourceFile const* source, const std::string& language)
  111. {
  112. std::string flags = this->GetFlags(language);
  113. // Add Fortran format flags.
  114. if (language == "Fortran") {
  115. this->AppendFortranFormatFlags(flags, *source);
  116. }
  117. // Add source file specific flags.
  118. cmGeneratorExpressionInterpreter genexInterpreter(
  119. this->LocalGenerator, this->LocalGenerator->GetConfigName(),
  120. this->GeneratorTarget, language);
  121. const std::string COMPILE_FLAGS("COMPILE_FLAGS");
  122. if (const char* cflags = source->GetProperty(COMPILE_FLAGS)) {
  123. this->LocalGenerator->AppendFlags(
  124. flags, genexInterpreter.Evaluate(cflags, COMPILE_FLAGS));
  125. }
  126. const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
  127. if (const char* coptions = source->GetProperty(COMPILE_OPTIONS)) {
  128. this->LocalGenerator->AppendCompileOptions(
  129. flags, genexInterpreter.Evaluate(coptions, COMPILE_OPTIONS));
  130. }
  131. return flags;
  132. }
  133. void cmNinjaTargetGenerator::AddIncludeFlags(std::string& languageFlags,
  134. std::string const& language)
  135. {
  136. std::vector<std::string> includes;
  137. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  138. language, this->GetConfigName());
  139. // Add include directory flags.
  140. std::string includeFlags = this->LocalGenerator->GetIncludeFlags(
  141. includes, this->GeneratorTarget, language,
  142. language == "RC", // full include paths for RC needed by cmcldeps
  143. false, this->GetConfigName());
  144. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  145. std::replace(includeFlags.begin(), includeFlags.end(), '\\', '/');
  146. }
  147. this->LocalGenerator->AppendFlags(languageFlags, includeFlags);
  148. }
  149. bool cmNinjaTargetGenerator::NeedDepTypeMSVC(const std::string& lang) const
  150. {
  151. return (this->GetMakefile()->GetSafeDefinition("CMAKE_NINJA_DEPTYPE_" +
  152. lang) == "msvc");
  153. }
  154. // TODO: Refactor with
  155. // void cmMakefileTargetGenerator::WriteTargetLanguageFlags().
  156. std::string cmNinjaTargetGenerator::ComputeDefines(cmSourceFile const* source,
  157. const std::string& language)
  158. {
  159. std::set<std::string> defines;
  160. const std::string config = this->LocalGenerator->GetConfigName();
  161. cmGeneratorExpressionInterpreter genexInterpreter(
  162. this->LocalGenerator, config, this->GeneratorTarget, language);
  163. const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
  164. if (const char* compile_defs = source->GetProperty(COMPILE_DEFINITIONS)) {
  165. this->LocalGenerator->AppendDefines(
  166. defines, genexInterpreter.Evaluate(compile_defs, COMPILE_DEFINITIONS));
  167. }
  168. std::string defPropName = "COMPILE_DEFINITIONS_";
  169. defPropName += cmSystemTools::UpperCase(config);
  170. if (const char* config_compile_defs = source->GetProperty(defPropName)) {
  171. this->LocalGenerator->AppendDefines(
  172. defines,
  173. genexInterpreter.Evaluate(config_compile_defs, COMPILE_DEFINITIONS));
  174. }
  175. std::string definesString = this->GetDefines(language);
  176. this->LocalGenerator->JoinDefines(defines, definesString, language);
  177. return definesString;
  178. }
  179. std::string cmNinjaTargetGenerator::ComputeIncludes(
  180. cmSourceFile const* source, const std::string& language)
  181. {
  182. std::vector<std::string> includes;
  183. const std::string config = this->LocalGenerator->GetConfigName();
  184. cmGeneratorExpressionInterpreter genexInterpreter(
  185. this->LocalGenerator, config, this->GeneratorTarget, language);
  186. const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
  187. if (const char* cincludes = source->GetProperty(INCLUDE_DIRECTORIES)) {
  188. this->LocalGenerator->AppendIncludeDirectories(
  189. includes, genexInterpreter.Evaluate(cincludes, INCLUDE_DIRECTORIES),
  190. *source);
  191. }
  192. std::string includesString = this->LocalGenerator->GetIncludeFlags(
  193. includes, this->GeneratorTarget, language, true, false, config);
  194. this->LocalGenerator->AppendFlags(includesString,
  195. this->GetIncludes(language));
  196. return includesString;
  197. }
  198. cmNinjaDeps cmNinjaTargetGenerator::ComputeLinkDeps(
  199. const std::string& linkLanguage) const
  200. {
  201. // Static libraries never depend on other targets for linking.
  202. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  203. this->GeneratorTarget->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  204. return cmNinjaDeps();
  205. }
  206. cmComputeLinkInformation* cli =
  207. this->GeneratorTarget->GetLinkInformation(this->GetConfigName());
  208. if (!cli) {
  209. return cmNinjaDeps();
  210. }
  211. const std::vector<std::string>& deps = cli->GetDepends();
  212. cmNinjaDeps result(deps.size());
  213. std::transform(deps.begin(), deps.end(), result.begin(), MapToNinjaPath());
  214. // Add a dependency on the link definitions file, if any.
  215. if (cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  216. this->GeneratorTarget->GetModuleDefinitionInfo(
  217. this->GetConfigName())) {
  218. for (cmSourceFile const* src : mdi->Sources) {
  219. result.push_back(this->ConvertToNinjaPath(src->GetFullPath()));
  220. }
  221. }
  222. // Add a dependency on user-specified manifest files, if any.
  223. std::vector<cmSourceFile const*> manifest_srcs;
  224. this->GeneratorTarget->GetManifests(manifest_srcs, this->ConfigName);
  225. for (cmSourceFile const* manifest_src : manifest_srcs) {
  226. result.push_back(this->ConvertToNinjaPath(manifest_src->GetFullPath()));
  227. }
  228. // Add user-specified dependencies.
  229. std::vector<std::string> linkDeps;
  230. this->GeneratorTarget->GetLinkDepends(linkDeps, this->ConfigName,
  231. linkLanguage);
  232. std::transform(linkDeps.begin(), linkDeps.end(), std::back_inserter(result),
  233. MapToNinjaPath());
  234. return result;
  235. }
  236. std::string cmNinjaTargetGenerator::GetSourceFilePath(
  237. cmSourceFile const* source) const
  238. {
  239. return ConvertToNinjaPath(source->GetFullPath());
  240. }
  241. std::string cmNinjaTargetGenerator::GetObjectFilePath(
  242. cmSourceFile const* source) const
  243. {
  244. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  245. if (!path.empty()) {
  246. path += "/";
  247. }
  248. std::string const& objectName = this->GeneratorTarget->GetObjectName(source);
  249. path += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  250. path += "/";
  251. path += objectName;
  252. return path;
  253. }
  254. std::string cmNinjaTargetGenerator::GetPreprocessedFilePath(
  255. cmSourceFile const* source) const
  256. {
  257. // Choose an extension to compile already-preprocessed source.
  258. std::string ppExt = source->GetExtension();
  259. if (cmHasLiteralPrefix(ppExt, "F")) {
  260. // Some Fortran compilers automatically enable preprocessing for
  261. // upper-case extensions. Since the source is already preprocessed,
  262. // use a lower-case extension.
  263. ppExt = cmSystemTools::LowerCase(ppExt);
  264. }
  265. if (ppExt == "fpp") {
  266. // Some Fortran compilers automatically enable preprocessing for
  267. // the ".fpp" extension. Since the source is already preprocessed,
  268. // use the ".f" extension.
  269. ppExt = "f";
  270. }
  271. // Take the object file name and replace the extension.
  272. std::string const& objName = this->GeneratorTarget->GetObjectName(source);
  273. std::string const& objExt =
  274. this->GetGlobalGenerator()->GetLanguageOutputExtension(*source);
  275. assert(objName.size() >= objExt.size());
  276. std::string const ppName =
  277. objName.substr(0, objName.size() - objExt.size()) + "-pp." + ppExt;
  278. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  279. if (!path.empty()) {
  280. path += "/";
  281. }
  282. path += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  283. path += "/";
  284. path += ppName;
  285. return path;
  286. }
  287. std::string cmNinjaTargetGenerator::GetDyndepFilePath(
  288. std::string const& lang) const
  289. {
  290. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  291. if (!path.empty()) {
  292. path += "/";
  293. }
  294. path += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  295. path += "/";
  296. path += lang;
  297. path += ".dd";
  298. return path;
  299. }
  300. std::string cmNinjaTargetGenerator::GetTargetDependInfoPath(
  301. std::string const& lang) const
  302. {
  303. std::string path = this->Makefile->GetCurrentBinaryDirectory();
  304. path += "/";
  305. path += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  306. path += "/" + lang + "DependInfo.json";
  307. return path;
  308. }
  309. std::string cmNinjaTargetGenerator::GetTargetOutputDir() const
  310. {
  311. std::string dir = this->GeneratorTarget->GetDirectory(this->GetConfigName());
  312. return ConvertToNinjaPath(dir);
  313. }
  314. std::string cmNinjaTargetGenerator::GetTargetFilePath(
  315. const std::string& name) const
  316. {
  317. std::string path = this->GetTargetOutputDir();
  318. if (path.empty() || path == ".") {
  319. return name;
  320. }
  321. path += "/";
  322. path += name;
  323. return path;
  324. }
  325. std::string cmNinjaTargetGenerator::GetTargetName() const
  326. {
  327. return this->GeneratorTarget->GetName();
  328. }
  329. bool cmNinjaTargetGenerator::SetMsvcTargetPdbVariable(cmNinjaVars& vars) const
  330. {
  331. cmMakefile* mf = this->GetMakefile();
  332. if (mf->GetDefinition("MSVC_C_ARCHITECTURE_ID") ||
  333. mf->GetDefinition("MSVC_CXX_ARCHITECTURE_ID") ||
  334. mf->GetDefinition("MSVC_CUDA_ARCHITECTURE_ID")) {
  335. std::string pdbPath;
  336. std::string compilePdbPath = this->ComputeTargetCompilePDB();
  337. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
  338. this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  339. this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  340. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  341. pdbPath = this->GeneratorTarget->GetPDBDirectory(this->GetConfigName());
  342. pdbPath += "/";
  343. pdbPath += this->GeneratorTarget->GetPDBName(this->GetConfigName());
  344. }
  345. vars["TARGET_PDB"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  346. ConvertToNinjaPath(pdbPath), cmOutputConverter::SHELL);
  347. vars["TARGET_COMPILE_PDB"] =
  348. this->GetLocalGenerator()->ConvertToOutputFormat(
  349. ConvertToNinjaPath(compilePdbPath), cmOutputConverter::SHELL);
  350. EnsureParentDirectoryExists(pdbPath);
  351. EnsureParentDirectoryExists(compilePdbPath);
  352. return true;
  353. }
  354. return false;
  355. }
  356. void cmNinjaTargetGenerator::WriteLanguageRules(const std::string& language)
  357. {
  358. #ifdef NINJA_GEN_VERBOSE_FILES
  359. this->GetRulesFileStream() << "# Rules for language " << language << "\n\n";
  360. #endif
  361. this->WriteCompileRule(language);
  362. }
  363. void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
  364. {
  365. cmRulePlaceholderExpander::RuleVariables vars;
  366. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  367. vars.CMTargetType =
  368. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType());
  369. vars.Language = lang.c_str();
  370. vars.Source = "$in";
  371. vars.Object = "$out";
  372. vars.Defines = "$DEFINES";
  373. vars.Includes = "$INCLUDES";
  374. vars.TargetPDB = "$TARGET_PDB";
  375. vars.TargetCompilePDB = "$TARGET_COMPILE_PDB";
  376. vars.ObjectDir = "$OBJECT_DIR";
  377. vars.ObjectFileDir = "$OBJECT_FILE_DIR";
  378. if (lang == "Swift") {
  379. vars.SwiftAuxiliarySources = "$SWIFT_AUXILIARY_SOURCES";
  380. vars.SwiftModuleName = "$SWIFT_MODULE_NAME";
  381. }
  382. // For some cases we do an explicit preprocessor invocation.
  383. bool const explicitPP = this->NeedExplicitPreprocessing(lang);
  384. bool const needDyndep = this->NeedDyndep(lang);
  385. cmMakefile* mf = this->GetMakefile();
  386. std::string flags = "$FLAGS";
  387. std::string responseFlag;
  388. bool const lang_supports_response = !(lang == "RC" || lang == "CUDA");
  389. if (lang_supports_response && this->ForceResponseFile()) {
  390. std::string const responseFlagVar =
  391. "CMAKE_" + lang + "_RESPONSE_FILE_FLAG";
  392. responseFlag = this->Makefile->GetSafeDefinition(responseFlagVar);
  393. if (responseFlag.empty()) {
  394. responseFlag = "@";
  395. }
  396. }
  397. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  398. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  399. std::string const tdi = this->GetLocalGenerator()->ConvertToOutputFormat(
  400. ConvertToNinjaPath(this->GetTargetDependInfoPath(lang)),
  401. cmLocalGenerator::SHELL);
  402. std::string launcher;
  403. const char* val = this->GetLocalGenerator()->GetRuleLauncher(
  404. this->GetGeneratorTarget(), "RULE_LAUNCH_COMPILE");
  405. if (val && *val) {
  406. launcher = val;
  407. launcher += " ";
  408. }
  409. if (explicitPP) {
  410. // Lookup the explicit preprocessing rule.
  411. std::string const ppVar = "CMAKE_" + lang + "_PREPROCESS_SOURCE";
  412. std::string const ppCmd =
  413. this->GetMakefile()->GetRequiredDefinition(ppVar);
  414. // Explicit preprocessing always uses a depfile.
  415. std::string const ppDeptype; // no deps= for multiple outputs
  416. std::string const ppDepfile = "$DEP_FILE";
  417. cmRulePlaceholderExpander::RuleVariables ppVars;
  418. ppVars.CMTargetName = vars.CMTargetName;
  419. ppVars.CMTargetType = vars.CMTargetType;
  420. ppVars.Language = vars.Language;
  421. ppVars.Object = "$out"; // for RULE_LAUNCH_COMPILE
  422. ppVars.PreprocessedSource = "$out";
  423. ppVars.DependencyFile = ppDepfile.c_str();
  424. // Preprocessing uses the original source,
  425. // compilation uses preprocessed output.
  426. ppVars.Source = vars.Source;
  427. vars.Source = "$in";
  428. // Preprocessing and compilation use the same flags.
  429. std::string ppFlags = flags;
  430. // Move preprocessor definitions to the preprocessor rule.
  431. ppVars.Defines = vars.Defines;
  432. vars.Defines = "";
  433. // Copy include directories to the preprocessor rule. The Fortran
  434. // compilation rule still needs them for the INCLUDE directive.
  435. ppVars.Includes = vars.Includes;
  436. // If using a response file, move defines, includes, and flags into it.
  437. std::string ppRspFile;
  438. std::string ppRspContent;
  439. if (!responseFlag.empty()) {
  440. ppRspFile = "$RSP_FILE";
  441. ppRspContent = std::string(" ") + ppVars.Defines + " " +
  442. ppVars.Includes + " " + ppFlags;
  443. ppFlags = responseFlag + ppRspFile;
  444. ppVars.Defines = "";
  445. ppVars.Includes = "";
  446. }
  447. ppVars.Flags = ppFlags.c_str();
  448. // Rule for preprocessing source file.
  449. std::vector<std::string> ppCmds;
  450. cmSystemTools::ExpandListArgument(ppCmd, ppCmds);
  451. for (std::string& i : ppCmds) {
  452. i = launcher + i;
  453. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  454. i, ppVars);
  455. }
  456. // Run CMake dependency scanner on preprocessed output.
  457. std::string const cmake = this->GetLocalGenerator()->ConvertToOutputFormat(
  458. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  459. ppCmds.push_back(
  460. cmake +
  461. " -E cmake_ninja_depends"
  462. " --tdi=" +
  463. tdi +
  464. " --pp=$out"
  465. " --dep=$DEP_FILE" +
  466. (needDyndep ? " --obj=$OBJ_FILE --ddi=$DYNDEP_INTERMEDIATE_FILE" : ""));
  467. std::string const ppCmdLine =
  468. this->GetLocalGenerator()->BuildCommandLine(ppCmds);
  469. // Write the rule for preprocessing file of the given language.
  470. std::ostringstream ppComment;
  471. ppComment << "Rule for preprocessing " << lang << " files.";
  472. std::ostringstream ppDesc;
  473. ppDesc << "Building " << lang << " preprocessed $out";
  474. this->GetGlobalGenerator()->AddRule(
  475. this->LanguagePreprocessRule(lang), ppCmdLine, ppDesc.str(),
  476. ppComment.str(), ppDepfile, ppDeptype, ppRspFile, ppRspContent,
  477. /*restat*/ "",
  478. /*generator*/ false);
  479. }
  480. if (needDyndep) {
  481. // Write the rule for ninja dyndep file generation.
  482. std::vector<std::string> ddCmds;
  483. // Command line length is almost always limited -> use response file for
  484. // dyndep rules
  485. std::string ddRspFile = "$out.rsp";
  486. std::string ddRspContent = "$in";
  487. std::string ddInput = "@" + ddRspFile;
  488. // Run CMake dependency scanner on preprocessed output.
  489. std::string const cmake = this->GetLocalGenerator()->ConvertToOutputFormat(
  490. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  491. ddCmds.push_back(cmake +
  492. " -E cmake_ninja_dyndep"
  493. " --tdi=" +
  494. tdi +
  495. " --dd=$out"
  496. " " +
  497. ddInput);
  498. std::string const ddCmdLine =
  499. this->GetLocalGenerator()->BuildCommandLine(ddCmds);
  500. std::ostringstream ddComment;
  501. ddComment << "Rule to generate ninja dyndep files for " << lang << ".";
  502. std::ostringstream ddDesc;
  503. ddDesc << "Generating " << lang << " dyndep file $out";
  504. this->GetGlobalGenerator()->AddRule(
  505. this->LanguageDyndepRule(lang), ddCmdLine, ddDesc.str(), ddComment.str(),
  506. /*depfile*/ "",
  507. /*deps*/ "", ddRspFile, ddRspContent,
  508. /*restat*/ "",
  509. /*generator*/ false);
  510. }
  511. // If using a response file, move defines, includes, and flags into it.
  512. std::string rspfile;
  513. std::string rspcontent;
  514. if (!responseFlag.empty()) {
  515. rspfile = "$RSP_FILE";
  516. rspcontent =
  517. std::string(" ") + vars.Defines + " " + vars.Includes + " " + flags;
  518. flags = responseFlag + rspfile;
  519. vars.Defines = "";
  520. vars.Includes = "";
  521. }
  522. // Tell ninja dependency format so all deps can be loaded into a database
  523. std::string deptype;
  524. std::string depfile;
  525. std::string cldeps;
  526. if (explicitPP) {
  527. // The explicit preprocessing step will handle dependency scanning.
  528. } else if (this->NeedDepTypeMSVC(lang)) {
  529. deptype = "msvc";
  530. depfile.clear();
  531. flags += " /showIncludes";
  532. } else if (mf->IsOn("CMAKE_NINJA_CMCLDEPS_" + lang)) {
  533. // For the MS resource compiler we need cmcldeps, but skip dependencies
  534. // for source-file try_compile cases because they are always fresh.
  535. if (!mf->GetIsSourceFileTryCompile()) {
  536. deptype = "gcc";
  537. depfile = "$DEP_FILE";
  538. const std::string cl = mf->GetDefinition("CMAKE_C_COMPILER")
  539. ? mf->GetSafeDefinition("CMAKE_C_COMPILER")
  540. : mf->GetSafeDefinition("CMAKE_CXX_COMPILER");
  541. cldeps = "\"";
  542. cldeps += cmSystemTools::GetCMClDepsCommand();
  543. cldeps += "\" " + lang + " " + vars.Source + " $DEP_FILE $out \"";
  544. cldeps += mf->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX");
  545. cldeps += "\" \"" + cl + "\" ";
  546. }
  547. } else {
  548. deptype = "gcc";
  549. const char* langdeptype = mf->GetDefinition("CMAKE_NINJA_DEPTYPE_" + lang);
  550. if (langdeptype) {
  551. deptype = langdeptype;
  552. }
  553. depfile = "$DEP_FILE";
  554. const std::string flagsName = "CMAKE_DEPFILE_FLAGS_" + lang;
  555. std::string depfileFlags = mf->GetSafeDefinition(flagsName);
  556. if (!depfileFlags.empty()) {
  557. cmSystemTools::ReplaceString(depfileFlags, "<DEPFILE>", "$DEP_FILE");
  558. cmSystemTools::ReplaceString(depfileFlags, "<OBJECT>", "$out");
  559. cmSystemTools::ReplaceString(depfileFlags, "<CMAKE_C_COMPILER>",
  560. mf->GetDefinition("CMAKE_C_COMPILER"));
  561. flags += " " + depfileFlags;
  562. }
  563. }
  564. vars.Flags = flags.c_str();
  565. vars.DependencyFile = depfile.c_str();
  566. // Rule for compiling object file.
  567. std::vector<std::string> compileCmds;
  568. if (lang == "CUDA") {
  569. std::string cmdVar;
  570. if (this->GeneratorTarget->GetPropertyAsBool(
  571. "CUDA_SEPARABLE_COMPILATION")) {
  572. cmdVar = std::string("CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION");
  573. } else if (this->GeneratorTarget->GetPropertyAsBool(
  574. "CUDA_PTX_COMPILATION")) {
  575. cmdVar = std::string("CMAKE_CUDA_COMPILE_PTX_COMPILATION");
  576. } else {
  577. cmdVar = std::string("CMAKE_CUDA_COMPILE_WHOLE_COMPILATION");
  578. }
  579. std::string compileCmd = mf->GetRequiredDefinition(cmdVar);
  580. cmSystemTools::ExpandListArgument(compileCmd, compileCmds);
  581. } else {
  582. const std::string cmdVar =
  583. std::string("CMAKE_") + lang + "_COMPILE_OBJECT";
  584. std::string compileCmd = mf->GetRequiredDefinition(cmdVar);
  585. cmSystemTools::ExpandListArgument(compileCmd, compileCmds);
  586. }
  587. // See if we need to use a compiler launcher like ccache or distcc
  588. std::string compilerLauncher;
  589. if (!compileCmds.empty() &&
  590. (lang == "C" || lang == "CXX" || lang == "Fortran" || lang == "CUDA")) {
  591. std::string const clauncher_prop = lang + "_COMPILER_LAUNCHER";
  592. const char* clauncher = this->GeneratorTarget->GetProperty(clauncher_prop);
  593. if (clauncher && *clauncher) {
  594. compilerLauncher = clauncher;
  595. }
  596. }
  597. // Maybe insert an include-what-you-use runner.
  598. if (!compileCmds.empty() && (lang == "C" || lang == "CXX")) {
  599. std::string const iwyu_prop = lang + "_INCLUDE_WHAT_YOU_USE";
  600. const char* iwyu = this->GeneratorTarget->GetProperty(iwyu_prop);
  601. std::string const tidy_prop = lang + "_CLANG_TIDY";
  602. const char* tidy = this->GeneratorTarget->GetProperty(tidy_prop);
  603. std::string const cpplint_prop = lang + "_CPPLINT";
  604. const char* cpplint = this->GeneratorTarget->GetProperty(cpplint_prop);
  605. std::string const cppcheck_prop = lang + "_CPPCHECK";
  606. const char* cppcheck = this->GeneratorTarget->GetProperty(cppcheck_prop);
  607. if ((iwyu && *iwyu) || (tidy && *tidy) || (cpplint && *cpplint) ||
  608. (cppcheck && *cppcheck)) {
  609. std::string run_iwyu = this->GetLocalGenerator()->ConvertToOutputFormat(
  610. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  611. run_iwyu += " -E __run_co_compile";
  612. if (!compilerLauncher.empty()) {
  613. // In __run_co_compile case the launcher command is supplied
  614. // via --launcher=<maybe-list> and consumed
  615. run_iwyu += " --launcher=";
  616. run_iwyu += this->LocalGenerator->EscapeForShell(compilerLauncher);
  617. compilerLauncher.clear();
  618. }
  619. if (iwyu && *iwyu) {
  620. run_iwyu += " --iwyu=";
  621. run_iwyu += this->GetLocalGenerator()->EscapeForShell(iwyu);
  622. }
  623. if (tidy && *tidy) {
  624. run_iwyu += " --tidy=";
  625. run_iwyu += this->GetLocalGenerator()->EscapeForShell(tidy);
  626. }
  627. if (cpplint && *cpplint) {
  628. run_iwyu += " --cpplint=";
  629. run_iwyu += this->GetLocalGenerator()->EscapeForShell(cpplint);
  630. }
  631. if (cppcheck && *cppcheck) {
  632. run_iwyu += " --cppcheck=";
  633. run_iwyu += this->GetLocalGenerator()->EscapeForShell(cppcheck);
  634. }
  635. if ((tidy && *tidy) || (cpplint && *cpplint) ||
  636. (cppcheck && *cppcheck)) {
  637. run_iwyu += " --source=$in";
  638. }
  639. run_iwyu += " -- ";
  640. compileCmds.front().insert(0, run_iwyu);
  641. }
  642. }
  643. // If compiler launcher was specified and not consumed above, it
  644. // goes to the beginning of the command line.
  645. if (!compileCmds.empty() && !compilerLauncher.empty()) {
  646. std::vector<std::string> args;
  647. cmSystemTools::ExpandListArgument(compilerLauncher, args, true);
  648. for (std::string& i : args) {
  649. i = this->LocalGenerator->EscapeForShell(i);
  650. }
  651. compileCmds.front().insert(0, cmJoin(args, " ") + " ");
  652. }
  653. if (!compileCmds.empty()) {
  654. compileCmds.front().insert(0, cldeps);
  655. }
  656. for (std::string& i : compileCmds) {
  657. i = launcher + i;
  658. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  659. vars);
  660. }
  661. std::string cmdLine =
  662. this->GetLocalGenerator()->BuildCommandLine(compileCmds);
  663. // Write the rule for compiling file of the given language.
  664. std::ostringstream comment;
  665. comment << "Rule for compiling " << lang << " files.";
  666. std::ostringstream description;
  667. description << "Building " << lang << " object $out";
  668. this->GetGlobalGenerator()->AddRule(
  669. this->LanguageCompilerRule(lang), cmdLine, description.str(),
  670. comment.str(), depfile, deptype, rspfile, rspcontent,
  671. /*restat*/ "",
  672. /*generator*/ false);
  673. }
  674. void cmNinjaTargetGenerator::WriteObjectBuildStatements()
  675. {
  676. // Write comments.
  677. cmGlobalNinjaGenerator::WriteDivider(this->GetBuildFileStream());
  678. this->GetBuildFileStream()
  679. << "# Object build statements for "
  680. << cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType())
  681. << " target " << this->GetTargetName() << "\n\n";
  682. std::string config = this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
  683. std::vector<cmSourceFile const*> customCommands;
  684. this->GeneratorTarget->GetCustomCommands(customCommands, config);
  685. for (cmSourceFile const* sf : customCommands) {
  686. cmCustomCommand const* cc = sf->GetCustomCommand();
  687. this->GetLocalGenerator()->AddCustomCommandTarget(
  688. cc, this->GetGeneratorTarget());
  689. // Record the custom commands for this target. The container is used
  690. // in WriteObjectBuildStatement when called in a loop below.
  691. this->CustomCommands.push_back(cc);
  692. }
  693. std::vector<cmSourceFile const*> headerSources;
  694. this->GeneratorTarget->GetHeaderSources(headerSources, config);
  695. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  696. headerSources, this->MacOSXContentGenerator);
  697. std::vector<cmSourceFile const*> extraSources;
  698. this->GeneratorTarget->GetExtraSources(extraSources, config);
  699. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  700. extraSources, this->MacOSXContentGenerator);
  701. std::vector<cmSourceFile const*> externalObjects;
  702. this->GeneratorTarget->GetExternalObjects(externalObjects, config);
  703. for (cmSourceFile const* sf : externalObjects) {
  704. this->Objects.push_back(this->GetSourceFilePath(sf));
  705. }
  706. cmNinjaDeps orderOnlyDeps;
  707. this->GetLocalGenerator()->AppendTargetDepends(
  708. this->GeneratorTarget, orderOnlyDeps, DependOnTargetOrdering);
  709. // Add order-only dependencies on other files associated with the target.
  710. orderOnlyDeps.insert(orderOnlyDeps.end(), this->ExtraFiles.begin(),
  711. this->ExtraFiles.end());
  712. // Add order-only dependencies on custom command outputs.
  713. for (cmCustomCommand const* cc : this->CustomCommands) {
  714. cmCustomCommandGenerator ccg(*cc, this->GetConfigName(),
  715. this->GetLocalGenerator());
  716. const std::vector<std::string>& ccoutputs = ccg.GetOutputs();
  717. const std::vector<std::string>& ccbyproducts = ccg.GetByproducts();
  718. std::transform(ccoutputs.begin(), ccoutputs.end(),
  719. std::back_inserter(orderOnlyDeps), MapToNinjaPath());
  720. std::transform(ccbyproducts.begin(), ccbyproducts.end(),
  721. std::back_inserter(orderOnlyDeps), MapToNinjaPath());
  722. }
  723. std::sort(orderOnlyDeps.begin(), orderOnlyDeps.end());
  724. orderOnlyDeps.erase(std::unique(orderOnlyDeps.begin(), orderOnlyDeps.end()),
  725. orderOnlyDeps.end());
  726. // The phony target must depend on at least one input or ninja will explain
  727. // that "output ... of phony edge with no inputs doesn't exist" and consider
  728. // the phony output "dirty".
  729. if (orderOnlyDeps.empty()) {
  730. // Any path that always exists will work here. It would be nice to
  731. // use just "." but that is not supported by Ninja < 1.7.
  732. std::string tgtDir;
  733. tgtDir += this->LocalGenerator->GetCurrentBinaryDirectory();
  734. tgtDir += "/";
  735. tgtDir += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  736. orderOnlyDeps.push_back(this->ConvertToNinjaPath(tgtDir));
  737. }
  738. {
  739. cmNinjaDeps orderOnlyTarget;
  740. orderOnlyTarget.push_back(this->OrderDependsTargetForTarget());
  741. this->GetGlobalGenerator()->WritePhonyBuild(
  742. this->GetBuildFileStream(),
  743. "Order-only phony target for " + this->GetTargetName(), orderOnlyTarget,
  744. cmNinjaDeps(), cmNinjaDeps(), orderOnlyDeps);
  745. }
  746. std::vector<cmSourceFile const*> objectSources;
  747. this->GeneratorTarget->GetObjectSources(objectSources, config);
  748. for (cmSourceFile const* sf : objectSources) {
  749. this->WriteObjectBuildStatement(sf);
  750. }
  751. if (!this->DDIFiles.empty()) {
  752. std::string const ddComment;
  753. std::string const ddRule = this->LanguageDyndepRule("Fortran");
  754. cmNinjaDeps ddOutputs;
  755. cmNinjaDeps ddImplicitOuts;
  756. cmNinjaDeps const& ddExplicitDeps = this->DDIFiles;
  757. cmNinjaDeps ddImplicitDeps;
  758. cmNinjaDeps ddOrderOnlyDeps;
  759. cmNinjaVars ddVars;
  760. this->WriteTargetDependInfo("Fortran");
  761. ddOutputs.push_back(this->GetDyndepFilePath("Fortran"));
  762. // Make sure dyndep files for all our dependencies have already
  763. // been generated so that the 'FortranModules.json' files they
  764. // produced as side-effects are available for us to read.
  765. // Ideally we should depend on the 'FortranModules.json' files
  766. // from our dependencies directly, but we don't know which of
  767. // our dependencies produces them. Fixing this will require
  768. // refactoring the Ninja generator to generate targets in
  769. // dependency order so that we can collect the needed information.
  770. this->GetLocalGenerator()->AppendTargetDepends(
  771. this->GeneratorTarget, ddOrderOnlyDeps, DependOnTargetArtifact);
  772. this->GetGlobalGenerator()->WriteBuild(
  773. this->GetBuildFileStream(), ddComment, ddRule, ddOutputs, ddImplicitOuts,
  774. ddExplicitDeps, ddImplicitDeps, ddOrderOnlyDeps, ddVars);
  775. }
  776. this->GetBuildFileStream() << "\n";
  777. }
  778. void cmNinjaTargetGenerator::WriteObjectBuildStatement(
  779. cmSourceFile const* source)
  780. {
  781. std::string const language = source->GetLanguage();
  782. std::string const sourceFileName =
  783. language == "RC" ? source->GetFullPath() : this->GetSourceFilePath(source);
  784. std::string const objectDir =
  785. this->ConvertToNinjaPath(this->GeneratorTarget->GetSupportDirectory());
  786. std::string const objectFileName =
  787. this->ConvertToNinjaPath(this->GetObjectFilePath(source));
  788. std::string const objectFileDir =
  789. cmSystemTools::GetFilenamePath(objectFileName);
  790. bool const lang_supports_response =
  791. !(language == "RC" || language == "CUDA");
  792. int const commandLineLengthLimit =
  793. ((lang_supports_response && this->ForceResponseFile())) ? -1 : 0;
  794. cmNinjaVars vars;
  795. vars["FLAGS"] = this->ComputeFlagsForObject(source, language);
  796. vars["DEFINES"] = this->ComputeDefines(source, language);
  797. vars["INCLUDES"] = this->ComputeIncludes(source, language);
  798. if (language == "Swift") {
  799. // The swift compiler needs all the sources besides the one being compiled
  800. // in order to do the type checking. List all these "auxiliary" sources.
  801. std::string aux_sources;
  802. cmGeneratorTarget::KindedSources const& sources =
  803. this->GeneratorTarget->GetKindedSources(this->GetConfigName());
  804. for (cmGeneratorTarget::SourceAndKind const& src : sources.Sources) {
  805. if (src.Source.Value == source) {
  806. continue;
  807. }
  808. aux_sources += " " + this->GetSourceFilePath(src.Source.Value);
  809. }
  810. vars["SWIFT_AUXILIARY_SOURCES"] = aux_sources;
  811. if (const char* name =
  812. this->GeneratorTarget->GetProperty("SWIFT_MODULE_NAME")) {
  813. vars["SWIFT_MODULE_NAME"] = name;
  814. } else {
  815. vars["SWIFT_MODULE_NAME"] = this->GeneratorTarget->GetName();
  816. }
  817. }
  818. if (!this->NeedDepTypeMSVC(language)) {
  819. bool replaceExt(false);
  820. if (!language.empty()) {
  821. std::string repVar = "CMAKE_";
  822. repVar += language;
  823. repVar += "_DEPFILE_EXTENSION_REPLACE";
  824. replaceExt = this->Makefile->IsOn(repVar);
  825. }
  826. if (!replaceExt) {
  827. // use original code
  828. vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  829. objectFileName + ".d", cmOutputConverter::SHELL);
  830. } else {
  831. // Replace the original source file extension with the
  832. // depend file extension.
  833. std::string dependFileName =
  834. cmSystemTools::GetFilenameWithoutLastExtension(objectFileName) + ".d";
  835. vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  836. objectFileDir + "/" + dependFileName, cmOutputConverter::SHELL);
  837. }
  838. }
  839. this->ExportObjectCompileCommand(
  840. language, sourceFileName, objectDir, objectFileName, objectFileDir,
  841. vars["FLAGS"], vars["DEFINES"], vars["INCLUDES"]);
  842. std::string comment;
  843. std::string rule = this->LanguageCompilerRule(language);
  844. cmNinjaDeps outputs;
  845. outputs.push_back(objectFileName);
  846. // Add this object to the list of object files.
  847. this->Objects.push_back(objectFileName);
  848. cmNinjaDeps explicitDeps;
  849. explicitDeps.push_back(sourceFileName);
  850. cmNinjaDeps implicitDeps;
  851. if (const char* objectDeps = source->GetProperty("OBJECT_DEPENDS")) {
  852. std::vector<std::string> depList;
  853. cmSystemTools::ExpandListArgument(objectDeps, depList);
  854. for (std::string& odi : depList) {
  855. if (cmSystemTools::FileIsFullPath(odi)) {
  856. odi = cmSystemTools::CollapseFullPath(odi);
  857. }
  858. }
  859. std::transform(depList.begin(), depList.end(),
  860. std::back_inserter(implicitDeps), MapToNinjaPath());
  861. }
  862. cmNinjaDeps orderOnlyDeps;
  863. orderOnlyDeps.push_back(this->OrderDependsTargetForTarget());
  864. // If the source file is GENERATED and does not have a custom command
  865. // (either attached to this source file or another one), assume that one of
  866. // the target dependencies, OBJECT_DEPENDS or header file custom commands
  867. // will rebuild the file.
  868. if (source->GetPropertyAsBool("GENERATED") &&
  869. !source->GetPropertyAsBool("__CMAKE_GENERATED_BY_CMAKE") &&
  870. !source->GetCustomCommand() &&
  871. !this->GetGlobalGenerator()->HasCustomCommandOutput(sourceFileName)) {
  872. this->GetGlobalGenerator()->AddAssumedSourceDependencies(sourceFileName,
  873. orderOnlyDeps);
  874. }
  875. // For some cases we need to generate a ninja dyndep file.
  876. bool const needDyndep = this->NeedDyndep(language);
  877. // For some cases we do an explicit preprocessor invocation.
  878. bool const explicitPP = this->NeedExplicitPreprocessing(language);
  879. if (explicitPP) {
  880. std::string const ppComment;
  881. std::string const ppRule = this->LanguagePreprocessRule(language);
  882. cmNinjaDeps ppOutputs;
  883. cmNinjaDeps ppImplicitOuts;
  884. cmNinjaDeps ppExplicitDeps;
  885. cmNinjaDeps ppImplicitDeps;
  886. cmNinjaDeps ppOrderOnlyDeps;
  887. cmNinjaVars ppVars;
  888. std::string const ppFileName =
  889. this->ConvertToNinjaPath(this->GetPreprocessedFilePath(source));
  890. ppOutputs.push_back(ppFileName);
  891. // Move compilation dependencies to the preprocessing build statement.
  892. std::swap(ppExplicitDeps, explicitDeps);
  893. std::swap(ppImplicitDeps, implicitDeps);
  894. std::swap(ppOrderOnlyDeps, orderOnlyDeps);
  895. std::swap(ppVars["IN_ABS"], vars["IN_ABS"]);
  896. // The actual compilation will now use the preprocessed source.
  897. explicitDeps.push_back(ppFileName);
  898. // Preprocessing and compilation generally use the same flags.
  899. ppVars["FLAGS"] = vars["FLAGS"];
  900. // In case compilation requires flags that are incompatible with
  901. // preprocessing, include them here.
  902. std::string const postFlag =
  903. this->Makefile->GetSafeDefinition("CMAKE_Fortran_POSTPROCESS_FLAG");
  904. this->LocalGenerator->AppendFlags(vars["FLAGS"], postFlag);
  905. // Move preprocessor definitions to the preprocessor build statement.
  906. std::swap(ppVars["DEFINES"], vars["DEFINES"]);
  907. // Copy include directories to the preprocessor build statement. The
  908. // Fortran compilation build statement still needs them for the INCLUDE
  909. // directive.
  910. ppVars["INCLUDES"] = vars["INCLUDES"];
  911. // Prepend source file's original directory as an include directory
  912. // so e.g. Fortran INCLUDE statements can look for files in it.
  913. std::vector<std::string> sourceDirectory;
  914. sourceDirectory.push_back(
  915. cmSystemTools::GetParentDirectory(source->GetFullPath()));
  916. std::string sourceDirectoryFlag = this->LocalGenerator->GetIncludeFlags(
  917. sourceDirectory, this->GeneratorTarget, language, false, false,
  918. this->GetConfigName());
  919. vars["INCLUDES"] = sourceDirectoryFlag + " " + vars["INCLUDES"];
  920. // Explicit preprocessing always uses a depfile.
  921. ppVars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  922. ppFileName + ".d", cmOutputConverter::SHELL);
  923. // The actual compilation does not need a depfile because it
  924. // depends on the already-preprocessed source.
  925. vars.erase("DEP_FILE");
  926. if (needDyndep) {
  927. // Tell dependency scanner the object file that will result from
  928. // compiling the preprocessed source.
  929. ppVars["OBJ_FILE"] = objectFileName;
  930. // Tell dependency scanner where to store dyndep intermediate results.
  931. std::string const ddiFile = ppFileName + ".ddi";
  932. ppVars["DYNDEP_INTERMEDIATE_FILE"] = ddiFile;
  933. ppImplicitOuts.push_back(ddiFile);
  934. this->DDIFiles.push_back(ddiFile);
  935. }
  936. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  937. ppVars);
  938. std::string const ppRspFile = ppFileName + ".rsp";
  939. this->GetGlobalGenerator()->WriteBuild(
  940. this->GetBuildFileStream(), ppComment, ppRule, ppOutputs, ppImplicitOuts,
  941. ppExplicitDeps, ppImplicitDeps, ppOrderOnlyDeps, ppVars, ppRspFile,
  942. commandLineLengthLimit);
  943. }
  944. if (needDyndep) {
  945. std::string const dyndep = this->GetDyndepFilePath(language);
  946. orderOnlyDeps.push_back(dyndep);
  947. vars["dyndep"] = dyndep;
  948. }
  949. EnsureParentDirectoryExists(objectFileName);
  950. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  951. objectDir, cmOutputConverter::SHELL);
  952. vars["OBJECT_FILE_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  953. objectFileDir, cmOutputConverter::SHELL);
  954. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  955. vars);
  956. this->SetMsvcTargetPdbVariable(vars);
  957. std::string const rspfile = objectFileName + ".rsp";
  958. this->GetGlobalGenerator()->WriteBuild(
  959. this->GetBuildFileStream(), comment, rule, outputs,
  960. /*implicitOuts=*/cmNinjaDeps(), explicitDeps, implicitDeps, orderOnlyDeps,
  961. vars, rspfile, commandLineLengthLimit);
  962. if (const char* objectOutputs = source->GetProperty("OBJECT_OUTPUTS")) {
  963. std::vector<std::string> outputList;
  964. cmSystemTools::ExpandListArgument(objectOutputs, outputList);
  965. std::transform(outputList.begin(), outputList.end(), outputList.begin(),
  966. MapToNinjaPath());
  967. this->GetGlobalGenerator()->WritePhonyBuild(this->GetBuildFileStream(),
  968. "Additional output files.",
  969. outputList, outputs);
  970. }
  971. }
  972. void cmNinjaTargetGenerator::WriteTargetDependInfo(std::string const& lang)
  973. {
  974. Json::Value tdi(Json::objectValue);
  975. tdi["language"] = lang;
  976. tdi["compiler-id"] =
  977. this->Makefile->GetSafeDefinition("CMAKE_" + lang + "_COMPILER_ID");
  978. if (lang == "Fortran") {
  979. std::string mod_dir = this->GeneratorTarget->GetFortranModuleDirectory(
  980. this->Makefile->GetHomeOutputDirectory());
  981. if (mod_dir.empty()) {
  982. mod_dir = this->Makefile->GetCurrentBinaryDirectory();
  983. }
  984. tdi["module-dir"] = mod_dir;
  985. }
  986. tdi["dir-cur-bld"] = this->Makefile->GetCurrentBinaryDirectory();
  987. tdi["dir-cur-src"] = this->Makefile->GetCurrentSourceDirectory();
  988. tdi["dir-top-bld"] = this->Makefile->GetHomeOutputDirectory();
  989. tdi["dir-top-src"] = this->Makefile->GetHomeDirectory();
  990. Json::Value& tdi_include_dirs = tdi["include-dirs"] = Json::arrayValue;
  991. std::vector<std::string> includes;
  992. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  993. lang, this->GetConfigName());
  994. for (std::string const& i : includes) {
  995. // Convert the include directories the same way we do for -I flags.
  996. // See upstream ninja issue 1251.
  997. tdi_include_dirs.append(this->ConvertToNinjaPath(i));
  998. }
  999. Json::Value& tdi_linked_target_dirs = tdi["linked-target-dirs"] =
  1000. Json::arrayValue;
  1001. std::vector<std::string> linked = this->GetLinkedTargetDirectories();
  1002. for (std::string const& l : linked) {
  1003. tdi_linked_target_dirs.append(l);
  1004. }
  1005. std::string const tdin = this->GetTargetDependInfoPath(lang);
  1006. cmGeneratedFileStream tdif(tdin);
  1007. tdif << tdi;
  1008. }
  1009. void cmNinjaTargetGenerator::ExportObjectCompileCommand(
  1010. std::string const& language, std::string const& sourceFileName,
  1011. std::string const& objectDir, std::string const& objectFileName,
  1012. std::string const& objectFileDir, std::string const& flags,
  1013. std::string const& defines, std::string const& includes)
  1014. {
  1015. if (!this->Makefile->IsOn("CMAKE_EXPORT_COMPILE_COMMANDS")) {
  1016. return;
  1017. }
  1018. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  1019. compileObjectVars.Language = language.c_str();
  1020. std::string escapedSourceFileName = sourceFileName;
  1021. if (!cmSystemTools::FileIsFullPath(sourceFileName)) {
  1022. escapedSourceFileName =
  1023. cmSystemTools::CollapseFullPath(escapedSourceFileName,
  1024. this->GetGlobalGenerator()
  1025. ->GetCMakeInstance()
  1026. ->GetHomeOutputDirectory());
  1027. }
  1028. escapedSourceFileName = this->LocalGenerator->ConvertToOutputFormat(
  1029. escapedSourceFileName, cmOutputConverter::SHELL);
  1030. compileObjectVars.Source = escapedSourceFileName.c_str();
  1031. compileObjectVars.Object = objectFileName.c_str();
  1032. compileObjectVars.ObjectDir = objectDir.c_str();
  1033. compileObjectVars.ObjectFileDir = objectFileDir.c_str();
  1034. compileObjectVars.Flags = flags.c_str();
  1035. compileObjectVars.Defines = defines.c_str();
  1036. compileObjectVars.Includes = includes.c_str();
  1037. // Rule for compiling object file.
  1038. std::vector<std::string> compileCmds;
  1039. if (language == "CUDA") {
  1040. std::string cmdVar;
  1041. if (this->GeneratorTarget->GetPropertyAsBool(
  1042. "CUDA_SEPARABLE_COMPILATION")) {
  1043. cmdVar = std::string("CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION");
  1044. } else if (this->GeneratorTarget->GetPropertyAsBool(
  1045. "CUDA_PTX_COMPILATION")) {
  1046. cmdVar = std::string("CMAKE_CUDA_COMPILE_PTX_COMPILATION");
  1047. } else {
  1048. cmdVar = std::string("CMAKE_CUDA_COMPILE_WHOLE_COMPILATION");
  1049. }
  1050. std::string compileCmd =
  1051. this->GetMakefile()->GetRequiredDefinition(cmdVar);
  1052. cmSystemTools::ExpandListArgument(compileCmd, compileCmds);
  1053. } else {
  1054. const std::string cmdVar =
  1055. std::string("CMAKE_") + language + "_COMPILE_OBJECT";
  1056. std::string compileCmd =
  1057. this->GetMakefile()->GetRequiredDefinition(cmdVar);
  1058. cmSystemTools::ExpandListArgument(compileCmd, compileCmds);
  1059. }
  1060. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  1061. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  1062. for (std::string& i : compileCmds) {
  1063. // no launcher for CMAKE_EXPORT_COMPILE_COMMANDS
  1064. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  1065. compileObjectVars);
  1066. }
  1067. std::string cmdLine =
  1068. this->GetLocalGenerator()->BuildCommandLine(compileCmds);
  1069. this->GetGlobalGenerator()->AddCXXCompileCommand(cmdLine, sourceFileName);
  1070. }
  1071. void cmNinjaTargetGenerator::EnsureDirectoryExists(
  1072. const std::string& path) const
  1073. {
  1074. if (cmSystemTools::FileIsFullPath(path)) {
  1075. cmSystemTools::MakeDirectory(path);
  1076. } else {
  1077. cmGlobalNinjaGenerator* gg = this->GetGlobalGenerator();
  1078. std::string fullPath =
  1079. std::string(gg->GetCMakeInstance()->GetHomeOutputDirectory());
  1080. // Also ensures their is a trailing slash.
  1081. gg->StripNinjaOutputPathPrefixAsSuffix(fullPath);
  1082. fullPath += path;
  1083. cmSystemTools::MakeDirectory(fullPath);
  1084. }
  1085. }
  1086. void cmNinjaTargetGenerator::EnsureParentDirectoryExists(
  1087. const std::string& path) const
  1088. {
  1089. EnsureDirectoryExists(cmSystemTools::GetParentDirectory(path));
  1090. }
  1091. void cmNinjaTargetGenerator::MacOSXContentGeneratorType::operator()(
  1092. cmSourceFile const& source, const char* pkgloc)
  1093. {
  1094. // Skip OS X content when not building a Framework or Bundle.
  1095. if (!this->Generator->GetGeneratorTarget()->IsBundleOnApple()) {
  1096. return;
  1097. }
  1098. std::string macdir =
  1099. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(pkgloc);
  1100. // Get the input file location.
  1101. std::string input = source.GetFullPath();
  1102. input = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(input);
  1103. // Get the output file location.
  1104. std::string output = macdir;
  1105. output += "/";
  1106. output += cmSystemTools::GetFilenameName(input);
  1107. output = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(output);
  1108. // Write a build statement to copy the content into the bundle.
  1109. this->Generator->GetGlobalGenerator()->WriteMacOSXContentBuild(input,
  1110. output);
  1111. // Add as a dependency to the target so that it gets called.
  1112. this->Generator->ExtraFiles.push_back(std::move(output));
  1113. }
  1114. void cmNinjaTargetGenerator::addPoolNinjaVariable(
  1115. const std::string& pool_property, cmGeneratorTarget* target,
  1116. cmNinjaVars& vars)
  1117. {
  1118. const char* pool = target->GetProperty(pool_property);
  1119. if (pool) {
  1120. vars["pool"] = pool;
  1121. }
  1122. }
  1123. bool cmNinjaTargetGenerator::ForceResponseFile()
  1124. {
  1125. static std::string const forceRspFile = "CMAKE_NINJA_FORCE_RESPONSE_FILE";
  1126. return (this->GetMakefile()->IsDefinitionSet(forceRspFile) ||
  1127. cmSystemTools::HasEnv(forceRspFile));
  1128. }