cmNinjaTargetGenerator.cxx 44 KB

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