cmNinjaTargetGenerator.cxx 51 KB

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