cmNinjaTargetGenerator.cxx 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851
  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 <algorithm>
  5. #include <array>
  6. #include <cassert>
  7. #include <functional>
  8. #include <iterator>
  9. #include <map>
  10. #include <ostream>
  11. #include <type_traits>
  12. #include <unordered_map>
  13. #include <unordered_set>
  14. #include <utility>
  15. #include <cm/memory>
  16. #include <cm/string_view>
  17. #include <cmext/algorithm>
  18. #include <cmext/string_view>
  19. #include <cm3p/json/value.h>
  20. #include <cm3p/json/writer.h>
  21. #include "cmComputeLinkInformation.h"
  22. #include "cmCustomCommandGenerator.h"
  23. #include "cmDyndepCollation.h"
  24. #include "cmFileSet.h"
  25. #include "cmGeneratedFileStream.h"
  26. #include "cmGeneratorExpression.h"
  27. #include "cmGeneratorTarget.h"
  28. #include "cmGlobalNinjaGenerator.h"
  29. #include "cmList.h"
  30. #include "cmLocalGenerator.h"
  31. #include "cmLocalNinjaGenerator.h"
  32. #include "cmMakefile.h"
  33. #include "cmMessageType.h"
  34. #include "cmNinjaNormalTargetGenerator.h"
  35. #include "cmNinjaUtilityTargetGenerator.h"
  36. #include "cmOutputConverter.h"
  37. #include "cmRange.h"
  38. #include "cmRulePlaceholderExpander.h"
  39. #include "cmSourceFile.h"
  40. #include "cmState.h"
  41. #include "cmStateTypes.h"
  42. #include "cmStringAlgorithms.h"
  43. #include "cmSystemTools.h"
  44. #include "cmTarget.h"
  45. #include "cmValue.h"
  46. #include "cmake.h"
  47. std::unique_ptr<cmNinjaTargetGenerator> cmNinjaTargetGenerator::New(
  48. cmGeneratorTarget* target)
  49. {
  50. switch (target->GetType()) {
  51. case cmStateEnums::EXECUTABLE:
  52. case cmStateEnums::SHARED_LIBRARY:
  53. case cmStateEnums::STATIC_LIBRARY:
  54. case cmStateEnums::MODULE_LIBRARY:
  55. case cmStateEnums::OBJECT_LIBRARY:
  56. return cm::make_unique<cmNinjaNormalTargetGenerator>(target);
  57. case cmStateEnums::UTILITY:
  58. case cmStateEnums::INTERFACE_LIBRARY:
  59. case cmStateEnums::GLOBAL_TARGET:
  60. return cm::make_unique<cmNinjaUtilityTargetGenerator>(target);
  61. default:
  62. return std::unique_ptr<cmNinjaTargetGenerator>();
  63. }
  64. }
  65. cmNinjaTargetGenerator::cmNinjaTargetGenerator(cmGeneratorTarget* target)
  66. : cmCommonTargetGenerator(target)
  67. , OSXBundleGenerator(nullptr)
  68. , LocalGenerator(
  69. static_cast<cmLocalNinjaGenerator*>(target->GetLocalGenerator()))
  70. {
  71. for (auto const& fileConfig :
  72. target->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig)) {
  73. this->Configs[fileConfig].MacOSXContentGenerator =
  74. cm::make_unique<MacOSXContentGeneratorType>(this, fileConfig);
  75. }
  76. }
  77. cmNinjaTargetGenerator::~cmNinjaTargetGenerator() = default;
  78. cmGeneratedFileStream& cmNinjaTargetGenerator::GetImplFileStream(
  79. const std::string& config) const
  80. {
  81. return *this->GetGlobalGenerator()->GetImplFileStream(config);
  82. }
  83. cmGeneratedFileStream& cmNinjaTargetGenerator::GetCommonFileStream() const
  84. {
  85. return *this->GetGlobalGenerator()->GetCommonFileStream();
  86. }
  87. cmGeneratedFileStream& cmNinjaTargetGenerator::GetRulesFileStream() const
  88. {
  89. return *this->GetGlobalGenerator()->GetRulesFileStream();
  90. }
  91. cmGlobalNinjaGenerator* cmNinjaTargetGenerator::GetGlobalGenerator() const
  92. {
  93. return this->LocalGenerator->GetGlobalNinjaGenerator();
  94. }
  95. std::string cmNinjaTargetGenerator::LanguageCompilerRule(
  96. const std::string& lang, const std::string& config,
  97. WithScanning withScanning) const
  98. {
  99. return cmStrCat(
  100. lang, "_COMPILER__",
  101. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  102. withScanning == WithScanning::Yes ? "_scanned_" : "_unscanned_", config);
  103. }
  104. std::string cmNinjaTargetGenerator::LanguagePreprocessAndScanRule(
  105. std::string const& lang, const std::string& config) const
  106. {
  107. return cmStrCat(
  108. lang, "_PREPROCESS_SCAN__",
  109. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  110. '_', config);
  111. }
  112. std::string cmNinjaTargetGenerator::LanguageScanRule(
  113. std::string const& lang, const std::string& config) const
  114. {
  115. return cmStrCat(
  116. lang, "_SCAN__",
  117. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  118. '_', config);
  119. }
  120. bool cmNinjaTargetGenerator::NeedExplicitPreprocessing(
  121. std::string const& lang) const
  122. {
  123. return lang == "Fortran";
  124. }
  125. bool cmNinjaTargetGenerator::CompileWithDefines(std::string const& lang) const
  126. {
  127. return this->Makefile->IsOn(
  128. cmStrCat("CMAKE_", lang, "_COMPILE_WITH_DEFINES"));
  129. }
  130. std::string cmNinjaTargetGenerator::LanguageDyndepRule(
  131. const std::string& lang, const std::string& config) const
  132. {
  133. return cmStrCat(
  134. lang, "_DYNDEP__",
  135. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  136. '_', config);
  137. }
  138. std::string cmNinjaTargetGenerator::OrderDependsTargetForTarget(
  139. const std::string& config)
  140. {
  141. return this->GetGlobalGenerator()->OrderDependsTargetForTarget(
  142. this->GeneratorTarget, config);
  143. }
  144. // TODO: Most of the code is picked up from
  145. // void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink),
  146. // void cmMakefileTargetGenerator::WriteTargetLanguageFlags()
  147. // Refactor it.
  148. std::string cmNinjaTargetGenerator::ComputeFlagsForObject(
  149. cmSourceFile const* source, const std::string& language,
  150. const std::string& config)
  151. {
  152. std::unordered_map<std::string, std::string> pchSources;
  153. std::vector<std::string> architectures =
  154. this->GeneratorTarget->GetAppleArchs(config, language);
  155. if (architectures.empty()) {
  156. architectures.emplace_back();
  157. }
  158. std::string filterArch;
  159. for (const std::string& arch : architectures) {
  160. const std::string pchSource =
  161. this->GeneratorTarget->GetPchSource(config, language, arch);
  162. if (pchSource == source->GetFullPath()) {
  163. filterArch = arch;
  164. }
  165. if (!pchSource.empty()) {
  166. pchSources.insert(std::make_pair(pchSource, arch));
  167. }
  168. }
  169. std::string flags;
  170. // Explicitly add the explicit language flag before any other flag
  171. // so user flags can override it.
  172. this->GeneratorTarget->AddExplicitLanguageFlags(flags, *source);
  173. if (!flags.empty()) {
  174. flags += " ";
  175. }
  176. flags += this->GetFlags(language, config, filterArch);
  177. // Add Fortran format flags.
  178. if (language == "Fortran") {
  179. this->AppendFortranFormatFlags(flags, *source);
  180. this->AppendFortranPreprocessFlags(flags, *source,
  181. PreprocessFlagsRequired::NO);
  182. }
  183. // Add source file specific flags.
  184. cmGeneratorExpressionInterpreter genexInterpreter(
  185. this->LocalGenerator, config, this->GeneratorTarget, language);
  186. const std::string COMPILE_FLAGS("COMPILE_FLAGS");
  187. if (cmValue cflags = source->GetProperty(COMPILE_FLAGS)) {
  188. this->LocalGenerator->AppendFlags(
  189. flags, genexInterpreter.Evaluate(*cflags, COMPILE_FLAGS));
  190. }
  191. const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
  192. if (cmValue coptions = source->GetProperty(COMPILE_OPTIONS)) {
  193. this->LocalGenerator->AppendCompileOptions(
  194. flags, genexInterpreter.Evaluate(*coptions, COMPILE_OPTIONS));
  195. }
  196. // Add precompile headers compile options.
  197. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  198. std::string pchOptions;
  199. auto pchIt = pchSources.find(source->GetFullPath());
  200. if (pchIt != pchSources.end()) {
  201. pchOptions = this->GeneratorTarget->GetPchCreateCompileOptions(
  202. config, language, pchIt->second);
  203. } else {
  204. pchOptions =
  205. this->GeneratorTarget->GetPchUseCompileOptions(config, language);
  206. }
  207. this->LocalGenerator->AppendCompileOptions(
  208. flags, genexInterpreter.Evaluate(pchOptions, COMPILE_OPTIONS));
  209. }
  210. auto const* fs = this->GeneratorTarget->GetFileSetForSource(config, source);
  211. if (fs &&
  212. (fs->GetType() == "CXX_MODULES"_s ||
  213. fs->GetType() == "CXX_MODULE_HEADER_UNITS"_s)) {
  214. if (source->GetLanguage() != "CXX"_s) {
  215. this->GetMakefile()->IssueMessage(
  216. MessageType::FATAL_ERROR,
  217. cmStrCat("Target \"", this->GeneratorTarget->Target->GetName(),
  218. "\" contains the source\n ", source->GetFullPath(),
  219. "\nin a file set of type \"", fs->GetType(),
  220. R"(" but the source is not classified as a "CXX" source.)"));
  221. }
  222. }
  223. return flags;
  224. }
  225. void cmNinjaTargetGenerator::AddIncludeFlags(std::string& languageFlags,
  226. std::string const& language,
  227. const std::string& config)
  228. {
  229. std::vector<std::string> includes;
  230. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  231. language, config);
  232. // Add include directory flags.
  233. std::string includeFlags = this->LocalGenerator->GetIncludeFlags(
  234. includes, this->GeneratorTarget, language, config, false);
  235. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  236. std::replace(includeFlags.begin(), includeFlags.end(), '\\', '/');
  237. }
  238. this->LocalGenerator->AppendFlags(languageFlags, includeFlags);
  239. }
  240. // TODO: Refactor with
  241. // void cmMakefileTargetGenerator::WriteTargetLanguageFlags().
  242. std::string cmNinjaTargetGenerator::ComputeDefines(cmSourceFile const* source,
  243. const std::string& language,
  244. const std::string& config)
  245. {
  246. std::set<std::string> defines;
  247. cmGeneratorExpressionInterpreter genexInterpreter(
  248. this->LocalGenerator, config, this->GeneratorTarget, language);
  249. // Seriously??
  250. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  251. defines.insert(cmStrCat("CMAKE_INTDIR=\"", config, '"'));
  252. }
  253. const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
  254. if (cmValue compile_defs = source->GetProperty(COMPILE_DEFINITIONS)) {
  255. this->LocalGenerator->AppendDefines(
  256. defines, genexInterpreter.Evaluate(*compile_defs, COMPILE_DEFINITIONS));
  257. }
  258. std::string defPropName =
  259. cmStrCat("COMPILE_DEFINITIONS_", cmSystemTools::UpperCase(config));
  260. if (cmValue config_compile_defs = source->GetProperty(defPropName)) {
  261. this->LocalGenerator->AppendDefines(
  262. defines,
  263. genexInterpreter.Evaluate(*config_compile_defs, COMPILE_DEFINITIONS));
  264. }
  265. std::string definesString = this->GetDefines(language, config);
  266. this->LocalGenerator->JoinDefines(defines, definesString, language);
  267. return definesString;
  268. }
  269. std::string cmNinjaTargetGenerator::ComputeIncludes(
  270. cmSourceFile const* source, const std::string& language,
  271. const std::string& config)
  272. {
  273. std::vector<std::string> includes;
  274. cmGeneratorExpressionInterpreter genexInterpreter(
  275. this->LocalGenerator, config, this->GeneratorTarget, language);
  276. const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
  277. if (cmValue cincludes = source->GetProperty(INCLUDE_DIRECTORIES)) {
  278. this->LocalGenerator->AppendIncludeDirectories(
  279. includes, genexInterpreter.Evaluate(*cincludes, INCLUDE_DIRECTORIES),
  280. *source);
  281. }
  282. std::string includesString = this->LocalGenerator->GetIncludeFlags(
  283. includes, this->GeneratorTarget, language, config, false);
  284. this->LocalGenerator->AppendFlags(includesString,
  285. this->GetIncludes(language, config));
  286. return includesString;
  287. }
  288. cmNinjaDeps cmNinjaTargetGenerator::ComputeLinkDeps(
  289. const std::string& linkLanguage, const std::string& config,
  290. bool ignoreType) const
  291. {
  292. // Static libraries never depend on other targets for linking.
  293. if (!ignoreType &&
  294. (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  295. this->GeneratorTarget->GetType() == cmStateEnums::OBJECT_LIBRARY)) {
  296. return cmNinjaDeps();
  297. }
  298. cmComputeLinkInformation* cli =
  299. this->GeneratorTarget->GetLinkInformation(config);
  300. if (!cli) {
  301. return cmNinjaDeps();
  302. }
  303. const std::vector<std::string>& deps = cli->GetDepends();
  304. cmNinjaDeps result(deps.size());
  305. std::transform(deps.begin(), deps.end(), result.begin(),
  306. this->MapToNinjaPath());
  307. // Add a dependency on the link definitions file, if any.
  308. if (cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  309. this->GeneratorTarget->GetModuleDefinitionInfo(config)) {
  310. for (cmSourceFile const* src : mdi->Sources) {
  311. result.push_back(this->ConvertToNinjaPath(src->GetFullPath()));
  312. }
  313. }
  314. // Add a dependency on user-specified manifest files, if any.
  315. std::vector<cmSourceFile const*> manifest_srcs;
  316. this->GeneratorTarget->GetManifests(manifest_srcs, config);
  317. for (cmSourceFile const* manifest_src : manifest_srcs) {
  318. result.push_back(this->ConvertToNinjaPath(manifest_src->GetFullPath()));
  319. }
  320. // Add user-specified dependencies.
  321. std::vector<std::string> linkDeps;
  322. this->GeneratorTarget->GetLinkDepends(linkDeps, config, linkLanguage);
  323. std::transform(linkDeps.begin(), linkDeps.end(), std::back_inserter(result),
  324. this->MapToNinjaPath());
  325. return result;
  326. }
  327. std::string cmNinjaTargetGenerator::GetCompiledSourceNinjaPath(
  328. cmSourceFile const* source) const
  329. {
  330. // Pass source files to the compiler by absolute path.
  331. return this->ConvertToNinjaAbsPath(source->GetFullPath());
  332. }
  333. std::string cmNinjaTargetGenerator::GetObjectFilePath(
  334. cmSourceFile const* source, const std::string& config) const
  335. {
  336. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  337. if (!path.empty()) {
  338. path += '/';
  339. }
  340. std::string const& objectName = this->GeneratorTarget->GetObjectName(source);
  341. path += cmStrCat(
  342. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  343. this->GetGlobalGenerator()->ConfigDirectory(config), '/', objectName);
  344. return path;
  345. }
  346. std::string cmNinjaTargetGenerator::GetClangTidyReplacementsFilePath(
  347. std::string const& directory, cmSourceFile const& source,
  348. std::string const& config) const
  349. {
  350. auto path = this->LocalGenerator->GetHomeRelativeOutputPath();
  351. if (!path.empty()) {
  352. path += '/';
  353. }
  354. path = cmStrCat(directory, '/', path);
  355. auto const& objectName = this->GeneratorTarget->GetObjectName(&source);
  356. path =
  357. cmStrCat(std::move(path),
  358. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  359. this->GetGlobalGenerator()->ConfigDirectory(config), '/',
  360. objectName, ".yaml");
  361. return path;
  362. }
  363. std::string cmNinjaTargetGenerator::GetPreprocessedFilePath(
  364. cmSourceFile const* source, const std::string& config) const
  365. {
  366. // Choose an extension to compile already-preprocessed source.
  367. std::string ppExt = source->GetExtension();
  368. if (cmHasLiteralPrefix(ppExt, "F")) {
  369. // Some Fortran compilers automatically enable preprocessing for
  370. // upper-case extensions. Since the source is already preprocessed,
  371. // use a lower-case extension.
  372. ppExt = cmSystemTools::LowerCase(ppExt);
  373. }
  374. if (ppExt == "fpp") {
  375. // Some Fortran compilers automatically enable preprocessing for
  376. // the ".fpp" extension. Since the source is already preprocessed,
  377. // use the ".f" extension.
  378. ppExt = "f";
  379. }
  380. // Take the object file name and replace the extension.
  381. std::string const& objName = this->GeneratorTarget->GetObjectName(source);
  382. std::string const& objExt =
  383. this->GetGlobalGenerator()->GetLanguageOutputExtension(*source);
  384. assert(objName.size() >= objExt.size());
  385. std::string const ppName =
  386. cmStrCat(objName.substr(0, objName.size() - objExt.size()), "-pp.", ppExt);
  387. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  388. if (!path.empty()) {
  389. path += '/';
  390. }
  391. path +=
  392. cmStrCat(this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  393. this->GetGlobalGenerator()->ConfigDirectory(config), '/', ppName);
  394. return path;
  395. }
  396. std::string cmNinjaTargetGenerator::GetDyndepFilePath(
  397. std::string const& lang, const std::string& config) const
  398. {
  399. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  400. if (!path.empty()) {
  401. path += '/';
  402. }
  403. path += cmStrCat(
  404. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  405. this->GetGlobalGenerator()->ConfigDirectory(config), '/', lang, ".dd");
  406. return path;
  407. }
  408. std::string cmNinjaTargetGenerator::GetTargetDependInfoPath(
  409. std::string const& lang, const std::string& config) const
  410. {
  411. std::string path =
  412. cmStrCat(this->Makefile->GetCurrentBinaryDirectory(), '/',
  413. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  414. this->GetGlobalGenerator()->ConfigDirectory(config), '/', lang,
  415. "DependInfo.json");
  416. return path;
  417. }
  418. std::string cmNinjaTargetGenerator::GetTargetOutputDir(
  419. const std::string& config) const
  420. {
  421. std::string dir = this->GeneratorTarget->GetDirectory(config);
  422. return this->ConvertToNinjaPath(dir);
  423. }
  424. std::string cmNinjaTargetGenerator::GetTargetFilePath(
  425. const std::string& name, const std::string& config) const
  426. {
  427. std::string path = this->GetTargetOutputDir(config);
  428. if (path.empty() || path == ".") {
  429. return name;
  430. }
  431. path += cmStrCat('/', name);
  432. return path;
  433. }
  434. std::string cmNinjaTargetGenerator::GetTargetName() const
  435. {
  436. return this->GeneratorTarget->GetName();
  437. }
  438. bool cmNinjaTargetGenerator::SetMsvcTargetPdbVariable(
  439. cmNinjaVars& vars, const std::string& config) const
  440. {
  441. cmMakefile* mf = this->GetMakefile();
  442. if (mf->GetDefinition("MSVC_C_ARCHITECTURE_ID") ||
  443. mf->GetDefinition("MSVC_CXX_ARCHITECTURE_ID") ||
  444. mf->GetDefinition("MSVC_CUDA_ARCHITECTURE_ID")) {
  445. std::string pdbPath;
  446. std::string compilePdbPath = this->ComputeTargetCompilePDB(config);
  447. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
  448. this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  449. this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  450. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  451. pdbPath = cmStrCat(this->GeneratorTarget->GetPDBDirectory(config), '/',
  452. this->GeneratorTarget->GetPDBName(config));
  453. }
  454. vars["TARGET_PDB"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  455. this->ConvertToNinjaPath(pdbPath), cmOutputConverter::SHELL);
  456. vars["TARGET_COMPILE_PDB"] =
  457. this->GetLocalGenerator()->ConvertToOutputFormat(
  458. this->ConvertToNinjaPath(compilePdbPath), cmOutputConverter::SHELL);
  459. this->EnsureParentDirectoryExists(pdbPath);
  460. this->EnsureParentDirectoryExists(compilePdbPath);
  461. return true;
  462. }
  463. return false;
  464. }
  465. void cmNinjaTargetGenerator::WriteLanguageRules(const std::string& language,
  466. const std::string& config)
  467. {
  468. #ifdef NINJA_GEN_VERBOSE_FILES
  469. this->GetRulesFileStream() << "# Rules for language " << language << "\n\n";
  470. #endif
  471. this->WriteCompileRule(language, config);
  472. }
  473. namespace {
  474. // Create the command to run the dependency scanner
  475. std::string GetScanCommand(cm::string_view cmakeCmd, cm::string_view tdi,
  476. cm::string_view lang, cm::string_view srcFile,
  477. cm::string_view ddiFile)
  478. {
  479. return cmStrCat(cmakeCmd, " -E cmake_ninja_depends --tdi=", tdi,
  480. " --lang=", lang, " --src=", srcFile, " --out=$out",
  481. " --dep=$DEP_FILE --obj=$OBJ_FILE --ddi=", ddiFile);
  482. }
  483. // Helper function to create dependency scanning rule that may or may
  484. // not perform explicit preprocessing too.
  485. cmNinjaRule GetScanRule(
  486. std::string const& ruleName, std::string const& ppFileName,
  487. std::string const& deptype,
  488. cmRulePlaceholderExpander::RuleVariables const& vars,
  489. const std::string& responseFlag, const std::string& flags,
  490. cmRulePlaceholderExpander* const rulePlaceholderExpander,
  491. cmLocalNinjaGenerator* generator, std::vector<std::string> scanCmds,
  492. const std::string& outputConfig)
  493. {
  494. cmNinjaRule rule(ruleName);
  495. // Scanning always uses a depfile for preprocessor dependencies.
  496. if (deptype == "msvc"_s) {
  497. rule.DepType = deptype;
  498. rule.DepFile.clear();
  499. } else {
  500. rule.DepType.clear(); // no deps= for multiple outputs
  501. rule.DepFile = "$DEP_FILE";
  502. }
  503. cmRulePlaceholderExpander::RuleVariables scanVars;
  504. scanVars.CMTargetName = vars.CMTargetName;
  505. scanVars.CMTargetType = vars.CMTargetType;
  506. scanVars.Language = vars.Language;
  507. scanVars.Object = "$OBJ_FILE";
  508. scanVars.PreprocessedSource = ppFileName.c_str();
  509. scanVars.DynDepFile = "$DYNDEP_INTERMEDIATE_FILE";
  510. scanVars.DependencyFile = rule.DepFile.c_str();
  511. scanVars.DependencyTarget = "$out";
  512. // Scanning needs the same preprocessor settings as direct compilation would.
  513. scanVars.Source = vars.Source;
  514. scanVars.Defines = vars.Defines;
  515. scanVars.Includes = vars.Includes;
  516. // Scanning needs the compilation flags too.
  517. std::string scanFlags = flags;
  518. // If using a response file, move defines, includes, and flags into it.
  519. if (!responseFlag.empty()) {
  520. rule.RspFile = "$RSP_FILE";
  521. rule.RspContent =
  522. cmStrCat(' ', scanVars.Defines, ' ', scanVars.Includes, ' ', scanFlags);
  523. scanFlags = cmStrCat(responseFlag, rule.RspFile);
  524. scanVars.Defines = "";
  525. scanVars.Includes = "";
  526. }
  527. scanVars.Flags = scanFlags.c_str();
  528. // Rule for scanning a source file.
  529. for (std::string& scanCmd : scanCmds) {
  530. rulePlaceholderExpander->ExpandRuleVariables(generator, scanCmd, scanVars);
  531. }
  532. rule.Command =
  533. generator->BuildCommandLine(scanCmds, outputConfig, outputConfig);
  534. return rule;
  535. }
  536. }
  537. void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang,
  538. const std::string& config)
  539. {
  540. // For some cases we scan to dynamically discover dependencies.
  541. bool const needDyndep = this->GetGeneratorTarget()->NeedDyndep(lang, config);
  542. if (needDyndep) {
  543. this->WriteCompileRule(lang, config, WithScanning::Yes);
  544. }
  545. this->WriteCompileRule(lang, config, WithScanning::No);
  546. }
  547. void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang,
  548. const std::string& config,
  549. WithScanning withScanning)
  550. {
  551. cmRulePlaceholderExpander::RuleVariables vars;
  552. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  553. vars.CMTargetType =
  554. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()).c_str();
  555. vars.Language = lang.c_str();
  556. vars.Source = "$in";
  557. vars.Object = "$out";
  558. vars.Defines = "$DEFINES";
  559. vars.Includes = "$INCLUDES";
  560. vars.TargetPDB = "$TARGET_PDB";
  561. vars.TargetCompilePDB = "$TARGET_COMPILE_PDB";
  562. vars.ObjectDir = "$OBJECT_DIR";
  563. vars.ObjectFileDir = "$OBJECT_FILE_DIR";
  564. vars.CudaCompileMode = "$CUDA_COMPILE_MODE";
  565. vars.ISPCHeader = "$ISPC_HEADER_FILE";
  566. cmMakefile* mf = this->GetMakefile();
  567. // For some cases we scan to dynamically discover dependencies.
  568. bool const compilationPreprocesses = !this->NeedExplicitPreprocessing(lang);
  569. std::string flags = "$FLAGS";
  570. std::string responseFlag;
  571. bool const lang_supports_response = lang != "RC";
  572. if (lang_supports_response && this->ForceResponseFile()) {
  573. std::string const responseFlagVar =
  574. cmStrCat("CMAKE_", lang, "_RESPONSE_FILE_FLAG");
  575. responseFlag = this->Makefile->GetSafeDefinition(responseFlagVar);
  576. if (responseFlag.empty() && lang != "CUDA") {
  577. responseFlag = "@";
  578. }
  579. }
  580. std::string const modmapFormatVar =
  581. cmStrCat("CMAKE_EXPERIMENTAL_", lang, "_MODULE_MAP_FORMAT");
  582. std::string const modmapFormat =
  583. this->Makefile->GetSafeDefinition(modmapFormatVar);
  584. auto rulePlaceholderExpander =
  585. this->GetLocalGenerator()->CreateRulePlaceholderExpander();
  586. std::string const tdi = this->GetLocalGenerator()->ConvertToOutputFormat(
  587. this->ConvertToNinjaPath(this->GetTargetDependInfoPath(lang, config)),
  588. cmLocalGenerator::SHELL);
  589. std::string launcher;
  590. std::string val = this->GetLocalGenerator()->GetRuleLauncher(
  591. this->GetGeneratorTarget(), "RULE_LAUNCH_COMPILE", config);
  592. if (cmNonempty(val)) {
  593. launcher = cmStrCat(val, ' ');
  594. }
  595. std::string const cmakeCmd =
  596. this->GetLocalGenerator()->ConvertToOutputFormat(
  597. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  598. if (withScanning == WithScanning::Yes) {
  599. const auto& scanDepType = this->GetMakefile()->GetSafeDefinition(
  600. cmStrCat("CMAKE_EXPERIMENTAL_", lang, "_SCANDEP_DEPFILE_FORMAT"));
  601. // Rule to scan dependencies of sources that need preprocessing.
  602. {
  603. cmList scanCommands;
  604. std::string scanRuleName;
  605. std::string ppFileName;
  606. if (compilationPreprocesses) {
  607. scanRuleName = this->LanguageScanRule(lang, config);
  608. ppFileName = "$PREPROCESSED_OUTPUT_FILE";
  609. std::string const& scanCommand = mf->GetRequiredDefinition(
  610. cmStrCat("CMAKE_EXPERIMENTAL_", lang, "_SCANDEP_SOURCE"));
  611. scanCommands.assign(scanCommand);
  612. for (auto& i : scanCommands) {
  613. i = cmStrCat(launcher, i);
  614. }
  615. } else {
  616. scanRuleName = this->LanguagePreprocessAndScanRule(lang, config);
  617. ppFileName = "$out";
  618. std::string const& ppCommmand = mf->GetRequiredDefinition(
  619. cmStrCat("CMAKE_", lang, "_PREPROCESS_SOURCE"));
  620. scanCommands.assign(ppCommmand);
  621. for (auto& i : scanCommands) {
  622. i = cmStrCat(launcher, i);
  623. }
  624. scanCommands.emplace_back(GetScanCommand(cmakeCmd, tdi, lang, "$out",
  625. "$DYNDEP_INTERMEDIATE_FILE"));
  626. }
  627. auto scanRule = GetScanRule(
  628. scanRuleName, ppFileName, scanDepType, vars, responseFlag, flags,
  629. rulePlaceholderExpander.get(), this->GetLocalGenerator(),
  630. std::move(scanCommands), config);
  631. scanRule.Comment =
  632. cmStrCat("Rule for generating ", lang, " dependencies.");
  633. if (compilationPreprocesses) {
  634. scanRule.Description =
  635. cmStrCat("Scanning $in for ", lang, " dependencies");
  636. } else {
  637. scanRule.Description =
  638. cmStrCat("Building ", lang, " preprocessed $out");
  639. }
  640. this->GetGlobalGenerator()->AddRule(scanRule);
  641. }
  642. if (!compilationPreprocesses) {
  643. // Compilation will not preprocess, so it does not need the defines
  644. // unless the compiler wants them for some other purpose.
  645. if (!this->CompileWithDefines(lang)) {
  646. vars.Defines = "";
  647. }
  648. // Rule to scan dependencies of sources that do not need preprocessing.
  649. std::string const& scanRuleName = this->LanguageScanRule(lang, config);
  650. std::vector<std::string> scanCommands;
  651. scanCommands.emplace_back(
  652. GetScanCommand(cmakeCmd, tdi, lang, "$in", "$out"));
  653. auto scanRule =
  654. GetScanRule(scanRuleName, "", scanDepType, vars, "", flags,
  655. rulePlaceholderExpander.get(), this->GetLocalGenerator(),
  656. std::move(scanCommands), config);
  657. // Write the rule for generating dependencies for the given language.
  658. scanRule.Comment = cmStrCat("Rule for generating ", lang,
  659. " dependencies on non-preprocessed files.");
  660. scanRule.Description =
  661. cmStrCat("Generating ", lang, " dependencies for $in");
  662. this->GetGlobalGenerator()->AddRule(scanRule);
  663. }
  664. // Write the rule for ninja dyndep file generation.
  665. cmNinjaRule rule(this->LanguageDyndepRule(lang, config));
  666. // Command line length is almost always limited -> use response file for
  667. // dyndep rules
  668. rule.RspFile = "$out.rsp";
  669. rule.RspContent = "$in";
  670. // Run CMake dependency scanner on the source file (using the preprocessed
  671. // source if that was performed).
  672. std::string ddModmapArg;
  673. if (!modmapFormat.empty()) {
  674. ddModmapArg += cmStrCat(" --modmapfmt=", modmapFormat);
  675. }
  676. {
  677. std::vector<std::string> ddCmds;
  678. {
  679. std::string ccmd = cmStrCat(
  680. cmakeCmd, " -E cmake_ninja_dyndep --tdi=", tdi, " --lang=", lang,
  681. ddModmapArg, " --dd=$out @", rule.RspFile);
  682. ddCmds.emplace_back(std::move(ccmd));
  683. }
  684. rule.Command =
  685. this->GetLocalGenerator()->BuildCommandLine(ddCmds, config, config);
  686. }
  687. rule.Comment =
  688. cmStrCat("Rule to generate ninja dyndep files for ", lang, '.');
  689. rule.Description = cmStrCat("Generating ", lang, " dyndep file $out");
  690. this->GetGlobalGenerator()->AddRule(rule);
  691. }
  692. cmNinjaRule rule(this->LanguageCompilerRule(lang, config, withScanning));
  693. // If using a response file, move defines, includes, and flags into it.
  694. if (!responseFlag.empty()) {
  695. rule.RspFile = "$RSP_FILE";
  696. rule.RspContent =
  697. cmStrCat(' ', vars.Defines, ' ', vars.Includes, ' ', flags);
  698. flags = cmStrCat(responseFlag, rule.RspFile);
  699. vars.Defines = "";
  700. vars.Includes = "";
  701. }
  702. // Tell ninja dependency format so all deps can be loaded into a database
  703. std::string cldeps;
  704. if (!compilationPreprocesses) {
  705. // The compiler will not do preprocessing, so it has no such dependencies.
  706. } else if (mf->IsOn(cmStrCat("CMAKE_NINJA_CMCLDEPS_", lang))) {
  707. // For the MS resource compiler we need cmcldeps, but skip dependencies
  708. // for source-file try_compile cases because they are always fresh.
  709. if (!mf->GetIsSourceFileTryCompile()) {
  710. rule.DepType = "gcc";
  711. rule.DepFile = "$DEP_FILE";
  712. cmValue d = mf->GetDefinition("CMAKE_C_COMPILER");
  713. const std::string cl =
  714. d ? *d : mf->GetSafeDefinition("CMAKE_CXX_COMPILER");
  715. std::string cmcldepsPath;
  716. cmSystemTools::GetShortPath(cmSystemTools::GetCMClDepsCommand(),
  717. cmcldepsPath);
  718. cldeps = cmStrCat(cmcldepsPath, ' ', lang, ' ', vars.Source,
  719. " $DEP_FILE $out \"",
  720. mf->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX"),
  721. "\" \"", cl, "\" ");
  722. }
  723. } else {
  724. const auto& depType = this->GetMakefile()->GetSafeDefinition(
  725. cmStrCat("CMAKE_", lang, "_DEPFILE_FORMAT"));
  726. if (depType == "msvc"_s) {
  727. rule.DepType = "msvc";
  728. rule.DepFile.clear();
  729. } else {
  730. rule.DepType = "gcc";
  731. rule.DepFile = "$DEP_FILE";
  732. }
  733. vars.DependencyFile = rule.DepFile.c_str();
  734. vars.DependencyTarget = "$out";
  735. const std::string flagsName = cmStrCat("CMAKE_DEPFILE_FLAGS_", lang);
  736. std::string depfileFlags = mf->GetSafeDefinition(flagsName);
  737. if (!depfileFlags.empty()) {
  738. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  739. depfileFlags, vars);
  740. flags += cmStrCat(' ', depfileFlags);
  741. }
  742. }
  743. if (withScanning == WithScanning::Yes && !modmapFormat.empty()) {
  744. std::string modmapFlags = mf->GetRequiredDefinition(
  745. cmStrCat("CMAKE_EXPERIMENTAL_", lang, "_MODULE_MAP_FLAG"));
  746. cmSystemTools::ReplaceString(modmapFlags, "<MODULE_MAP_FILE>",
  747. "$DYNDEP_MODULE_MAP_FILE");
  748. flags += cmStrCat(' ', modmapFlags);
  749. }
  750. vars.Flags = flags.c_str();
  751. vars.DependencyFile = rule.DepFile.c_str();
  752. std::string cudaCompileMode;
  753. if (lang == "CUDA") {
  754. if (this->GeneratorTarget->GetPropertyAsBool(
  755. "CUDA_SEPARABLE_COMPILATION")) {
  756. const std::string& rdcFlag =
  757. this->Makefile->GetRequiredDefinition("_CMAKE_CUDA_RDC_FLAG");
  758. cudaCompileMode = cmStrCat(cudaCompileMode, rdcFlag, " ");
  759. }
  760. static std::array<cm::string_view, 4> const compileModes{
  761. { "PTX"_s, "CUBIN"_s, "FATBIN"_s, "OPTIX"_s }
  762. };
  763. bool useNormalCompileMode = true;
  764. for (cm::string_view mode : compileModes) {
  765. auto propName = cmStrCat("CUDA_", mode, "_COMPILATION");
  766. auto defName = cmStrCat("_CMAKE_CUDA_", mode, "_FLAG");
  767. if (this->GeneratorTarget->GetPropertyAsBool(propName)) {
  768. const std::string& flag =
  769. this->Makefile->GetRequiredDefinition(defName);
  770. cudaCompileMode = cmStrCat(cudaCompileMode, flag);
  771. useNormalCompileMode = false;
  772. break;
  773. }
  774. }
  775. if (useNormalCompileMode) {
  776. const std::string& wholeFlag =
  777. this->Makefile->GetRequiredDefinition("_CMAKE_CUDA_WHOLE_FLAG");
  778. cudaCompileMode = cmStrCat(cudaCompileMode, wholeFlag);
  779. }
  780. vars.CudaCompileMode = cudaCompileMode.c_str();
  781. }
  782. // Rule for compiling object file.
  783. const std::string cmdVar = cmStrCat("CMAKE_", lang, "_COMPILE_OBJECT");
  784. const std::string& compileCmd = mf->GetRequiredDefinition(cmdVar);
  785. cmList compileCmds(compileCmd);
  786. if (!compileCmds.empty()) {
  787. compileCmds.front().insert(0, "${CODE_CHECK}");
  788. compileCmds.front().insert(0, "${LAUNCHER}");
  789. }
  790. if (!compileCmds.empty()) {
  791. compileCmds.front().insert(0, cldeps);
  792. }
  793. const auto& extraCommands = this->GetMakefile()->GetSafeDefinition(
  794. cmStrCat("CMAKE_", lang, "_DEPENDS_EXTRA_COMMANDS"));
  795. if (!extraCommands.empty()) {
  796. compileCmds.append(extraCommands);
  797. }
  798. for (auto& i : compileCmds) {
  799. i = cmStrCat(launcher, i);
  800. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  801. vars);
  802. }
  803. rule.Command =
  804. this->GetLocalGenerator()->BuildCommandLine(compileCmds, config, config);
  805. // Write the rule for compiling file of the given language.
  806. rule.Comment = cmStrCat("Rule for compiling ", lang, " files.");
  807. rule.Description = cmStrCat("Building ", lang, " object $out");
  808. this->GetGlobalGenerator()->AddRule(rule);
  809. }
  810. void cmNinjaTargetGenerator::WriteObjectBuildStatements(
  811. const std::string& config, const std::string& fileConfig,
  812. bool firstForConfig)
  813. {
  814. this->GeneratorTarget->CheckCxxModuleStatus(config);
  815. // Write comments.
  816. cmGlobalNinjaGenerator::WriteDivider(this->GetImplFileStream(fileConfig));
  817. this->GetImplFileStream(fileConfig)
  818. << "# Object build statements for "
  819. << cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType())
  820. << " target " << this->GetTargetName() << "\n\n";
  821. {
  822. std::vector<cmSourceFile const*> customCommands;
  823. this->GeneratorTarget->GetCustomCommands(customCommands, config);
  824. for (cmSourceFile const* sf : customCommands) {
  825. cmCustomCommand const* cc = sf->GetCustomCommand();
  826. this->GetLocalGenerator()->AddCustomCommandTarget(
  827. cc, this->GetGeneratorTarget());
  828. // Record the custom commands for this target. The container is used
  829. // in WriteObjectBuildStatement when called in a loop below.
  830. this->Configs[config].CustomCommands.push_back(cc);
  831. }
  832. }
  833. {
  834. std::vector<cmSourceFile const*> headerSources;
  835. this->GeneratorTarget->GetHeaderSources(headerSources, config);
  836. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  837. headerSources, this->Configs[fileConfig].MacOSXContentGenerator.get(),
  838. config);
  839. }
  840. {
  841. std::vector<cmSourceFile const*> extraSources;
  842. this->GeneratorTarget->GetExtraSources(extraSources, config);
  843. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  844. extraSources, this->Configs[fileConfig].MacOSXContentGenerator.get(),
  845. config);
  846. }
  847. if (firstForConfig) {
  848. cmValue pchExtension =
  849. this->GetMakefile()->GetDefinition("CMAKE_PCH_EXTENSION");
  850. std::vector<cmSourceFile const*> externalObjects;
  851. this->GeneratorTarget->GetExternalObjects(externalObjects, config);
  852. for (cmSourceFile const* sf : externalObjects) {
  853. auto objectFileName = this->GetGlobalGenerator()->ExpandCFGIntDir(
  854. this->ConvertToNinjaPath(sf->GetFullPath()), config);
  855. if (!cmHasSuffix(objectFileName, pchExtension)) {
  856. this->Configs[config].Objects.push_back(objectFileName);
  857. }
  858. }
  859. }
  860. {
  861. cmNinjaBuild build("phony");
  862. build.Comment =
  863. cmStrCat("Order-only phony target for ", this->GetTargetName());
  864. build.Outputs.push_back(this->OrderDependsTargetForTarget(config));
  865. cmNinjaDeps& orderOnlyDeps = build.OrderOnlyDeps;
  866. this->GetLocalGenerator()->AppendTargetDepends(
  867. this->GeneratorTarget, orderOnlyDeps, config, fileConfig,
  868. DependOnTargetOrdering);
  869. // Add order-only dependencies on other files associated with the target.
  870. cm::append(orderOnlyDeps, this->Configs[config].ExtraFiles);
  871. // Add order-only dependencies on custom command outputs.
  872. for (cmCustomCommand const* cc : this->Configs[config].CustomCommands) {
  873. cmCustomCommandGenerator ccg(*cc, config, this->GetLocalGenerator());
  874. const std::vector<std::string>& ccoutputs = ccg.GetOutputs();
  875. const std::vector<std::string>& ccbyproducts = ccg.GetByproducts();
  876. std::transform(ccoutputs.begin(), ccoutputs.end(),
  877. std::back_inserter(orderOnlyDeps),
  878. this->MapToNinjaPath());
  879. std::transform(ccbyproducts.begin(), ccbyproducts.end(),
  880. std::back_inserter(orderOnlyDeps),
  881. this->MapToNinjaPath());
  882. }
  883. std::sort(orderOnlyDeps.begin(), orderOnlyDeps.end());
  884. orderOnlyDeps.erase(
  885. std::unique(orderOnlyDeps.begin(), orderOnlyDeps.end()),
  886. orderOnlyDeps.end());
  887. // The phony target must depend on at least one input or ninja will explain
  888. // that "output ... of phony edge with no inputs doesn't exist" and
  889. // consider the phony output "dirty".
  890. if (orderOnlyDeps.empty()) {
  891. // Any path that always exists will work here. It would be nice to
  892. // use just "." but that is not supported by Ninja < 1.7.
  893. std::string tgtDir = cmStrCat(
  894. this->LocalGenerator->GetCurrentBinaryDirectory(), '/',
  895. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget));
  896. orderOnlyDeps.push_back(this->ConvertToNinjaPath(tgtDir));
  897. }
  898. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  899. build);
  900. }
  901. {
  902. std::vector<cmSourceFile const*> objectSources;
  903. this->GeneratorTarget->GetObjectSources(objectSources, config);
  904. for (cmSourceFile const* sf : objectSources) {
  905. this->WriteObjectBuildStatement(sf, config, fileConfig, firstForConfig);
  906. }
  907. }
  908. for (auto const& langScanningFiles : this->Configs[config].ScanningInfo) {
  909. std::string const& language = langScanningFiles.first;
  910. std::vector<ScanningFiles> const& scanningFiles = langScanningFiles.second;
  911. cmNinjaBuild build(this->LanguageDyndepRule(language, config));
  912. build.Outputs.push_back(this->GetDyndepFilePath(language, config));
  913. build.ImplicitOuts.push_back(
  914. cmStrCat(this->Makefile->GetCurrentBinaryDirectory(), '/',
  915. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  916. this->GetGlobalGenerator()->ConfigDirectory(config), '/',
  917. language, "Modules.json"));
  918. for (auto const& scanFiles : scanningFiles) {
  919. if (!scanFiles.ScanningOutput.empty()) {
  920. build.ExplicitDeps.push_back(scanFiles.ScanningOutput);
  921. }
  922. if (!scanFiles.ModuleMapFile.empty()) {
  923. build.ImplicitOuts.push_back(scanFiles.ModuleMapFile);
  924. }
  925. }
  926. this->WriteTargetDependInfo(language, config);
  927. for (std::string const& l :
  928. this->GetLinkedTargetDirectories(language, config)) {
  929. build.ImplicitDeps.push_back(cmStrCat(l, '/', language, "Modules.json"));
  930. }
  931. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  932. build);
  933. }
  934. this->GetImplFileStream(fileConfig) << "\n";
  935. }
  936. void cmNinjaTargetGenerator::GenerateSwiftOutputFileMap(
  937. const std::string& config, std::string& flags)
  938. {
  939. if (this->Configs[config].SwiftOutputMap.empty()) {
  940. return;
  941. }
  942. std::string const targetSwiftDepsPath = [this, config]() -> std::string {
  943. cmGeneratorTarget const* target = this->GeneratorTarget;
  944. if (cmValue name = target->GetProperty("Swift_DEPENDENCIES_FILE")) {
  945. return *name;
  946. }
  947. return this->ConvertToNinjaPath(cmStrCat(target->GetSupportDirectory(),
  948. '/', config, '/',
  949. target->GetName(), ".swiftdeps"));
  950. }();
  951. std::string mapFilePath =
  952. cmStrCat(this->GeneratorTarget->GetSupportDirectory(), '/', config, '/',
  953. "output-file-map.json");
  954. // build the global target dependencies
  955. // https://github.com/apple/swift/blob/master/docs/Driver.md#output-file-maps
  956. Json::Value deps(Json::objectValue);
  957. deps["swift-dependencies"] = targetSwiftDepsPath;
  958. this->Configs[config].SwiftOutputMap[""] = deps;
  959. cmGeneratedFileStream output(mapFilePath);
  960. output << this->Configs[config].SwiftOutputMap;
  961. // Add flag
  962. this->LocalGenerator->AppendFlags(flags, "-output-file-map");
  963. this->LocalGenerator->AppendFlagEscape(flags,
  964. ConvertToNinjaPath(mapFilePath));
  965. }
  966. namespace {
  967. cmNinjaBuild GetScanBuildStatement(const std::string& ruleName,
  968. const std::string& ppFileName,
  969. bool compilePP, bool compilePPWithDefines,
  970. bool compilationPreprocesses,
  971. cmNinjaBuild& objBuild, cmNinjaVars& vars,
  972. const std::string& objectFileName,
  973. cmLocalGenerator* lg)
  974. {
  975. cmNinjaBuild scanBuild(ruleName);
  976. scanBuild.RspFile = "$out.rsp";
  977. if (compilePP) {
  978. // Move compilation dependencies to the scan/preprocessing build statement.
  979. std::swap(scanBuild.ExplicitDeps, objBuild.ExplicitDeps);
  980. std::swap(scanBuild.ImplicitDeps, objBuild.ImplicitDeps);
  981. std::swap(scanBuild.OrderOnlyDeps, objBuild.OrderOnlyDeps);
  982. std::swap(scanBuild.Variables["IN_ABS"], vars["IN_ABS"]);
  983. // The actual compilation will now use the preprocessed source.
  984. objBuild.ExplicitDeps.push_back(ppFileName);
  985. } else {
  986. // Copy compilation dependencies to the scan/preprocessing build statement.
  987. scanBuild.ExplicitDeps = objBuild.ExplicitDeps;
  988. scanBuild.ImplicitDeps = objBuild.ImplicitDeps;
  989. scanBuild.OrderOnlyDeps = objBuild.OrderOnlyDeps;
  990. scanBuild.Variables["IN_ABS"] = vars["IN_ABS"];
  991. }
  992. // Scanning and compilation generally use the same flags.
  993. scanBuild.Variables["FLAGS"] = vars["FLAGS"];
  994. if (compilePP && !compilePPWithDefines) {
  995. // Move preprocessor definitions to the scan/preprocessor build statement.
  996. std::swap(scanBuild.Variables["DEFINES"], vars["DEFINES"]);
  997. } else {
  998. // Copy preprocessor definitions to the scan/preprocessor build statement.
  999. scanBuild.Variables["DEFINES"] = vars["DEFINES"];
  1000. }
  1001. // Copy include directories to the preprocessor build statement. The
  1002. // Fortran compilation build statement still needs them for the INCLUDE
  1003. // directive.
  1004. scanBuild.Variables["INCLUDES"] = vars["INCLUDES"];
  1005. // Tell dependency scanner the object file that will result from
  1006. // compiling the source.
  1007. scanBuild.Variables["OBJ_FILE"] = objectFileName;
  1008. // Tell dependency scanner where to store dyndep intermediate results.
  1009. std::string const& ddiFile = cmStrCat(objectFileName, ".ddi");
  1010. scanBuild.Variables["DYNDEP_INTERMEDIATE_FILE"] = ddiFile;
  1011. // Outputs of the scan/preprocessor build statement.
  1012. if (compilePP) {
  1013. scanBuild.Outputs.push_back(ppFileName);
  1014. scanBuild.ImplicitOuts.push_back(ddiFile);
  1015. } else {
  1016. scanBuild.Outputs.push_back(ddiFile);
  1017. scanBuild.Variables["PREPROCESSED_OUTPUT_FILE"] = ppFileName;
  1018. if (!compilationPreprocesses) {
  1019. // Compilation does not preprocess and we are not compiling an
  1020. // already-preprocessed source. Make compilation depend on the scan
  1021. // results to honor implicit dependencies discovered during scanning
  1022. // (such as Fortran INCLUDE directives).
  1023. objBuild.ImplicitDeps.emplace_back(ddiFile);
  1024. }
  1025. }
  1026. // Scanning always provides a depfile for preprocessor dependencies. This
  1027. // variable is unused in `msvc`-deptype scanners.
  1028. std::string const& depFileName = cmStrCat(scanBuild.Outputs.front(), ".d");
  1029. scanBuild.Variables["DEP_FILE"] =
  1030. lg->ConvertToOutputFormat(depFileName, cmOutputConverter::SHELL);
  1031. if (compilePP) {
  1032. // The actual compilation does not need a depfile because it
  1033. // depends on the already-preprocessed source.
  1034. vars.erase("DEP_FILE");
  1035. }
  1036. return scanBuild;
  1037. }
  1038. }
  1039. void cmNinjaTargetGenerator::WriteObjectBuildStatement(
  1040. cmSourceFile const* source, const std::string& config,
  1041. const std::string& fileConfig, bool firstForConfig)
  1042. {
  1043. std::string const language = source->GetLanguage();
  1044. std::string const sourceFilePath = this->GetCompiledSourceNinjaPath(source);
  1045. std::string const objectDir = this->ConvertToNinjaPath(
  1046. cmStrCat(this->GeneratorTarget->GetSupportDirectory(),
  1047. this->GetGlobalGenerator()->ConfigDirectory(config)));
  1048. std::string const objectFileName =
  1049. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1050. std::string const objectFileDir =
  1051. cmSystemTools::GetFilenamePath(objectFileName);
  1052. std::string cmakeVarLang = cmStrCat("CMAKE_", language);
  1053. // build response file name
  1054. std::string cmakeLinkVar = cmStrCat(cmakeVarLang, "_RESPONSE_FILE_FLAG");
  1055. cmValue flag = this->GetMakefile()->GetDefinition(cmakeLinkVar);
  1056. bool const lang_supports_response =
  1057. !(language == "RC" || (language == "CUDA" && !flag));
  1058. int const commandLineLengthLimit =
  1059. ((lang_supports_response && this->ForceResponseFile())) ? -1 : 0;
  1060. bool const needDyndep =
  1061. this->GeneratorTarget->NeedDyndepForSource(language, config, source);
  1062. cmNinjaBuild objBuild(this->LanguageCompilerRule(
  1063. language, config, needDyndep ? WithScanning::Yes : WithScanning::No));
  1064. cmNinjaVars& vars = objBuild.Variables;
  1065. vars["FLAGS"] = this->ComputeFlagsForObject(source, language, config);
  1066. vars["DEFINES"] = this->ComputeDefines(source, language, config);
  1067. vars["INCLUDES"] = this->ComputeIncludes(source, language, config);
  1068. auto const cmakeCmd = this->GetLocalGenerator()->ConvertToOutputFormat(
  1069. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  1070. auto compilerLauncher = this->GetCompilerLauncher(language, config);
  1071. vars["CODE_CHECK"] =
  1072. this->GenerateCodeCheckRules(*source, compilerLauncher, cmakeCmd, config,
  1073. [this](std::string const& path) {
  1074. return this->ConvertToNinjaPath(path);
  1075. });
  1076. // If compiler launcher was specified and not consumed above, it
  1077. // goes to the beginning of the command line.
  1078. if (!compilerLauncher.empty()) {
  1079. cmList args{ compilerLauncher, cmList::EmptyElements::Yes };
  1080. if (!args.empty()) {
  1081. args[0] = this->LocalGenerator->ConvertToOutputFormat(
  1082. args[0], cmOutputConverter::SHELL);
  1083. for (std::string& i : cmMakeRange(args.begin() + 1, args.end())) {
  1084. i = this->LocalGenerator->EscapeForShell(i);
  1085. }
  1086. vars["LAUNCHER"] = args.join(" ") + " ";
  1087. }
  1088. }
  1089. if (this->GetMakefile()->GetSafeDefinition(
  1090. cmStrCat("CMAKE_", language, "_DEPFILE_FORMAT")) != "msvc"_s) {
  1091. bool replaceExt(false);
  1092. if (!language.empty()) {
  1093. std::string repVar =
  1094. cmStrCat("CMAKE_", language, "_DEPFILE_EXTENSION_REPLACE");
  1095. replaceExt = this->Makefile->IsOn(repVar);
  1096. }
  1097. if (!replaceExt) {
  1098. // use original code
  1099. vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1100. cmStrCat(objectFileName, ".d"), cmOutputConverter::SHELL);
  1101. } else {
  1102. // Replace the original source file extension with the
  1103. // depend file extension.
  1104. std::string dependFileName = cmStrCat(
  1105. cmSystemTools::GetFilenameWithoutLastExtension(objectFileName), ".d");
  1106. vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1107. cmStrCat(objectFileDir, '/', dependFileName),
  1108. cmOutputConverter::SHELL);
  1109. }
  1110. }
  1111. if (firstForConfig) {
  1112. this->ExportObjectCompileCommand(
  1113. language, sourceFilePath, objectDir, objectFileName, objectFileDir,
  1114. vars["FLAGS"], vars["DEFINES"], vars["INCLUDES"], config);
  1115. }
  1116. objBuild.Outputs.push_back(objectFileName);
  1117. if (firstForConfig) {
  1118. cmValue pchExtension =
  1119. this->GetMakefile()->GetDefinition("CMAKE_PCH_EXTENSION");
  1120. if (!cmHasSuffix(objectFileName, pchExtension)) {
  1121. // Add this object to the list of object files.
  1122. this->Configs[config].Objects.push_back(objectFileName);
  1123. }
  1124. }
  1125. objBuild.ExplicitDeps.push_back(sourceFilePath);
  1126. // Add precompile headers dependencies
  1127. std::vector<std::string> depList;
  1128. std::vector<std::string> architectures =
  1129. this->GeneratorTarget->GetAppleArchs(config, language);
  1130. if (architectures.empty()) {
  1131. architectures.emplace_back();
  1132. }
  1133. std::unordered_set<std::string> pchSources;
  1134. for (const std::string& arch : architectures) {
  1135. const std::string pchSource =
  1136. this->GeneratorTarget->GetPchSource(config, language, arch);
  1137. if (!pchSource.empty()) {
  1138. pchSources.insert(pchSource);
  1139. }
  1140. }
  1141. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  1142. for (const std::string& arch : architectures) {
  1143. depList.push_back(
  1144. this->GeneratorTarget->GetPchHeader(config, language, arch));
  1145. if (pchSources.find(source->GetFullPath()) == pchSources.end()) {
  1146. depList.push_back(
  1147. this->GeneratorTarget->GetPchFile(config, language, arch));
  1148. }
  1149. }
  1150. }
  1151. if (cmValue objectDeps = source->GetProperty("OBJECT_DEPENDS")) {
  1152. cmList objDepList{ *objectDeps };
  1153. std::copy(objDepList.begin(), objDepList.end(),
  1154. std::back_inserter(depList));
  1155. }
  1156. if (!depList.empty()) {
  1157. for (std::string& odi : depList) {
  1158. if (cmSystemTools::FileIsFullPath(odi)) {
  1159. odi = cmSystemTools::CollapseFullPath(odi);
  1160. }
  1161. }
  1162. std::transform(depList.begin(), depList.end(),
  1163. std::back_inserter(objBuild.ImplicitDeps),
  1164. this->MapToNinjaPath());
  1165. }
  1166. objBuild.OrderOnlyDeps.push_back(this->OrderDependsTargetForTarget(config));
  1167. // If the source file is GENERATED and does not have a custom command
  1168. // (either attached to this source file or another one), assume that one of
  1169. // the target dependencies, OBJECT_DEPENDS or header file custom commands
  1170. // will rebuild the file.
  1171. if (source->GetIsGenerated() &&
  1172. !source->GetPropertyAsBool("__CMAKE_GENERATED_BY_CMAKE") &&
  1173. !source->GetCustomCommand() &&
  1174. !this->GetGlobalGenerator()->HasCustomCommandOutput(sourceFilePath)) {
  1175. this->GetGlobalGenerator()->AddAssumedSourceDependencies(
  1176. sourceFilePath, objBuild.OrderOnlyDeps);
  1177. }
  1178. // For some cases we scan to dynamically discover dependencies.
  1179. bool const compilationPreprocesses =
  1180. !this->NeedExplicitPreprocessing(language);
  1181. std::string modmapFormat;
  1182. if (needDyndep) {
  1183. std::string const modmapFormatVar =
  1184. cmStrCat("CMAKE_EXPERIMENTAL_", language, "_MODULE_MAP_FORMAT");
  1185. modmapFormat = this->Makefile->GetSafeDefinition(modmapFormatVar);
  1186. }
  1187. if (needDyndep) {
  1188. // If source/target has preprocessing turned off, we still need to
  1189. // generate an explicit dependency step
  1190. const auto srcpp = source->GetSafeProperty("Fortran_PREPROCESS");
  1191. cmOutputConverter::FortranPreprocess preprocess =
  1192. cmOutputConverter::GetFortranPreprocess(srcpp);
  1193. if (preprocess == cmOutputConverter::FortranPreprocess::Unset) {
  1194. const auto& tgtpp =
  1195. this->GeneratorTarget->GetSafeProperty("Fortran_PREPROCESS");
  1196. preprocess = cmOutputConverter::GetFortranPreprocess(tgtpp);
  1197. }
  1198. bool const compilePP = !compilationPreprocesses &&
  1199. (preprocess != cmOutputConverter::FortranPreprocess::NotNeeded);
  1200. bool const compilePPWithDefines =
  1201. compilePP && this->CompileWithDefines(language);
  1202. std::string scanRuleName;
  1203. std::string ppFileName;
  1204. if (compilePP) {
  1205. scanRuleName = this->LanguagePreprocessAndScanRule(language, config);
  1206. ppFileName = this->ConvertToNinjaPath(
  1207. this->GetPreprocessedFilePath(source, config));
  1208. } else {
  1209. scanRuleName = this->LanguageScanRule(language, config);
  1210. ppFileName = cmStrCat(objectFileName, ".ddi.i");
  1211. }
  1212. cmNinjaBuild ppBuild = GetScanBuildStatement(
  1213. scanRuleName, ppFileName, compilePP, compilePPWithDefines,
  1214. compilationPreprocesses, objBuild, vars, objectFileName,
  1215. this->LocalGenerator);
  1216. if (compilePP) {
  1217. // In case compilation requires flags that are incompatible with
  1218. // preprocessing, include them here.
  1219. std::string const& postFlag = this->Makefile->GetSafeDefinition(
  1220. cmStrCat("CMAKE_", language, "_POSTPROCESS_FLAG"));
  1221. this->LocalGenerator->AppendFlags(vars["FLAGS"], postFlag);
  1222. // Prepend source file's original directory as an include directory
  1223. // so e.g. Fortran INCLUDE statements can look for files in it.
  1224. std::vector<std::string> sourceDirectory;
  1225. sourceDirectory.push_back(
  1226. cmSystemTools::GetParentDirectory(source->GetFullPath()));
  1227. std::string sourceDirectoryFlag = this->LocalGenerator->GetIncludeFlags(
  1228. sourceDirectory, this->GeneratorTarget, language, config, false);
  1229. vars["INCLUDES"] = cmStrCat(sourceDirectoryFlag, ' ', vars["INCLUDES"]);
  1230. }
  1231. ScanningFiles scanningFiles;
  1232. if (firstForConfig) {
  1233. scanningFiles.ScanningOutput = cmStrCat(objectFileName, ".ddi");
  1234. }
  1235. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1236. ppBuild.Variables);
  1237. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1238. ppBuild, commandLineLengthLimit);
  1239. std::string const dyndep = this->GetDyndepFilePath(language, config);
  1240. objBuild.OrderOnlyDeps.push_back(dyndep);
  1241. vars["dyndep"] = dyndep;
  1242. if (!modmapFormat.empty()) {
  1243. // XXX(modmap): If changing this path construction, change
  1244. // `cmGlobalNinjaGenerator::WriteDyndep` to expect the corresponding file
  1245. // path.
  1246. std::string ddModmapFile = cmStrCat(objectFileName, ".modmap");
  1247. vars["DYNDEP_MODULE_MAP_FILE"] = ddModmapFile;
  1248. objBuild.OrderOnlyDeps.push_back(ddModmapFile);
  1249. scanningFiles.ModuleMapFile = std::move(ddModmapFile);
  1250. }
  1251. if (!scanningFiles.IsEmpty()) {
  1252. this->Configs[config].ScanningInfo[language].emplace_back(scanningFiles);
  1253. }
  1254. }
  1255. this->EnsureParentDirectoryExists(objectFileName);
  1256. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1257. objectDir, cmOutputConverter::SHELL);
  1258. vars["OBJECT_FILE_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1259. objectFileDir, cmOutputConverter::SHELL);
  1260. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1261. vars);
  1262. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  1263. auto pchIt = pchSources.find(source->GetFullPath());
  1264. if (pchIt != pchSources.end()) {
  1265. this->addPoolNinjaVariable("JOB_POOL_PRECOMPILE_HEADER",
  1266. this->GetGeneratorTarget(), vars);
  1267. }
  1268. }
  1269. this->SetMsvcTargetPdbVariable(vars, config);
  1270. objBuild.RspFile = cmStrCat(objectFileName, ".rsp");
  1271. if (language == "ISPC") {
  1272. std::string const& objectName =
  1273. this->GeneratorTarget->GetObjectName(source);
  1274. std::string ispcSource =
  1275. cmSystemTools::GetFilenameWithoutLastExtension(objectName);
  1276. ispcSource = cmSystemTools::GetFilenameWithoutLastExtension(ispcSource);
  1277. cmValue ispcSuffixProp =
  1278. this->GeneratorTarget->GetProperty("ISPC_HEADER_SUFFIX");
  1279. assert(ispcSuffixProp);
  1280. std::string ispcHeaderDirectory =
  1281. this->GeneratorTarget->GetObjectDirectory(config);
  1282. if (cmValue prop =
  1283. this->GeneratorTarget->GetProperty("ISPC_HEADER_DIRECTORY")) {
  1284. ispcHeaderDirectory =
  1285. cmStrCat(this->LocalGenerator->GetBinaryDirectory(), '/', *prop);
  1286. }
  1287. std::string ispcHeader =
  1288. cmStrCat(ispcHeaderDirectory, '/', ispcSource, *ispcSuffixProp);
  1289. ispcHeader = this->ConvertToNinjaPath(ispcHeader);
  1290. // Make sure ninja knows what command generates the header
  1291. objBuild.ImplicitOuts.push_back(ispcHeader);
  1292. // Make sure ninja knows how to clean the generated header
  1293. this->GetGlobalGenerator()->AddAdditionalCleanFile(ispcHeader, config);
  1294. auto ispcSuffixes =
  1295. detail::ComputeISPCObjectSuffixes(this->GeneratorTarget);
  1296. if (ispcSuffixes.size() > 1) {
  1297. std::string rootObjectDir =
  1298. this->GeneratorTarget->GetObjectDirectory(config);
  1299. auto ispcSideEfffectObjects = detail::ComputeISPCExtraObjects(
  1300. objectName, rootObjectDir, ispcSuffixes);
  1301. for (auto sideEffect : ispcSideEfffectObjects) {
  1302. sideEffect = this->ConvertToNinjaPath(sideEffect);
  1303. objBuild.ImplicitOuts.emplace_back(sideEffect);
  1304. this->GetGlobalGenerator()->AddAdditionalCleanFile(sideEffect, config);
  1305. }
  1306. }
  1307. vars["ISPC_HEADER_FILE"] =
  1308. this->GetLocalGenerator()->ConvertToOutputFormat(
  1309. ispcHeader, cmOutputConverter::SHELL);
  1310. } else {
  1311. auto headers = this->GeneratorTarget->GetGeneratedISPCHeaders(config);
  1312. if (!headers.empty()) {
  1313. std::transform(headers.begin(), headers.end(), headers.begin(),
  1314. this->MapToNinjaPath());
  1315. objBuild.OrderOnlyDeps.insert(objBuild.OrderOnlyDeps.end(),
  1316. headers.begin(), headers.end());
  1317. }
  1318. }
  1319. if (language == "Swift") {
  1320. this->EmitSwiftDependencyInfo(source, config);
  1321. } else {
  1322. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1323. objBuild, commandLineLengthLimit);
  1324. }
  1325. if (cmValue objectOutputs = source->GetProperty("OBJECT_OUTPUTS")) {
  1326. std::string evaluatedObjectOutputs = cmGeneratorExpression::Evaluate(
  1327. *objectOutputs, this->LocalGenerator, config);
  1328. if (!evaluatedObjectOutputs.empty()) {
  1329. cmNinjaBuild build("phony");
  1330. build.Comment = "Additional output files.";
  1331. build.Outputs = cmList{ evaluatedObjectOutputs }.data();
  1332. std::transform(build.Outputs.begin(), build.Outputs.end(),
  1333. build.Outputs.begin(), this->MapToNinjaPath());
  1334. build.ExplicitDeps = objBuild.Outputs;
  1335. this->GetGlobalGenerator()->WriteBuild(
  1336. this->GetImplFileStream(fileConfig), build);
  1337. }
  1338. }
  1339. }
  1340. void cmNinjaTargetGenerator::WriteTargetDependInfo(std::string const& lang,
  1341. const std::string& config)
  1342. {
  1343. Json::Value tdi(Json::objectValue);
  1344. tdi["language"] = lang;
  1345. tdi["compiler-id"] = this->Makefile->GetSafeDefinition(
  1346. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  1347. tdi["compiler-simulate-id"] = this->Makefile->GetSafeDefinition(
  1348. cmStrCat("CMAKE_", lang, "_SIMULATE_ID"));
  1349. tdi["compiler-frontend-variant"] = this->Makefile->GetSafeDefinition(
  1350. cmStrCat("CMAKE_", lang, "_COMPILER_FRONTEND_VARIANT"));
  1351. std::string mod_dir;
  1352. if (lang == "Fortran") {
  1353. mod_dir = this->GeneratorTarget->GetFortranModuleDirectory(
  1354. this->Makefile->GetHomeOutputDirectory());
  1355. } else if (lang == "CXX") {
  1356. mod_dir = this->GetGlobalGenerator()->ExpandCFGIntDir(
  1357. cmSystemTools::CollapseFullPath(this->GeneratorTarget->ObjectDirectory),
  1358. config);
  1359. }
  1360. if (mod_dir.empty()) {
  1361. mod_dir = this->Makefile->GetCurrentBinaryDirectory();
  1362. }
  1363. tdi["module-dir"] = mod_dir;
  1364. if (lang == "Fortran") {
  1365. tdi["submodule-sep"] =
  1366. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
  1367. tdi["submodule-ext"] =
  1368. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
  1369. } else if (lang == "CXX") {
  1370. // No extra information necessary.
  1371. }
  1372. tdi["dir-cur-bld"] = this->Makefile->GetCurrentBinaryDirectory();
  1373. tdi["dir-cur-src"] = this->Makefile->GetCurrentSourceDirectory();
  1374. tdi["dir-top-bld"] = this->Makefile->GetHomeOutputDirectory();
  1375. tdi["dir-top-src"] = this->Makefile->GetHomeDirectory();
  1376. Json::Value& tdi_include_dirs = tdi["include-dirs"] = Json::arrayValue;
  1377. std::vector<std::string> includes;
  1378. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  1379. lang, config);
  1380. for (std::string const& i : includes) {
  1381. // Convert the include directories the same way we do for -I flags.
  1382. // See upstream ninja issue 1251.
  1383. tdi_include_dirs.append(this->ConvertToNinjaPath(i));
  1384. }
  1385. Json::Value& tdi_linked_target_dirs = tdi["linked-target-dirs"] =
  1386. Json::arrayValue;
  1387. for (std::string const& l : this->GetLinkedTargetDirectories(lang, config)) {
  1388. tdi_linked_target_dirs.append(l);
  1389. }
  1390. cmDyndepGeneratorCallbacks cb;
  1391. cb.ObjectFilePath = [this](cmSourceFile const* sf, std::string const& cnf) {
  1392. return this->GetObjectFilePath(sf, cnf);
  1393. };
  1394. #if !defined(CMAKE_BOOTSTRAP)
  1395. cmDyndepCollation::AddCollationInformation(tdi, this->GeneratorTarget,
  1396. config, cb);
  1397. #endif
  1398. std::string const tdin = this->GetTargetDependInfoPath(lang, config);
  1399. cmGeneratedFileStream tdif(tdin);
  1400. tdif << tdi;
  1401. }
  1402. void cmNinjaTargetGenerator::EmitSwiftDependencyInfo(
  1403. cmSourceFile const* source, const std::string& config)
  1404. {
  1405. std::string const sourceFilePath = this->GetCompiledSourceNinjaPath(source);
  1406. std::string const objectFilePath =
  1407. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1408. std::string const swiftDepsPath = [source, objectFilePath]() -> std::string {
  1409. if (cmValue name = source->GetProperty("Swift_DEPENDENCIES_FILE")) {
  1410. return *name;
  1411. }
  1412. return cmStrCat(objectFilePath, ".swiftdeps");
  1413. }();
  1414. std::string const swiftDiaPath = [source, objectFilePath]() -> std::string {
  1415. if (cmValue name = source->GetProperty("Swift_DIAGNOSTICS_FILE")) {
  1416. return *name;
  1417. }
  1418. return cmStrCat(objectFilePath, ".dia");
  1419. }();
  1420. std::string const makeDepsPath = [this, source, config]() -> std::string {
  1421. cmLocalNinjaGenerator const* local = this->GetLocalGenerator();
  1422. std::string const objectFileName =
  1423. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1424. std::string const objectFileDir =
  1425. cmSystemTools::GetFilenamePath(objectFileName);
  1426. if (this->Makefile->IsOn("CMAKE_Swift_DEPFLE_EXTNSION_REPLACE")) {
  1427. std::string dependFileName = cmStrCat(
  1428. cmSystemTools::GetFilenameWithoutLastExtension(objectFileName), ".d");
  1429. return local->ConvertToOutputFormat(
  1430. cmStrCat(objectFileDir, '/', dependFileName),
  1431. cmOutputConverter::SHELL);
  1432. }
  1433. return local->ConvertToOutputFormat(cmStrCat(objectFileName, ".d"),
  1434. cmOutputConverter::SHELL);
  1435. }();
  1436. // build the source file mapping
  1437. // https://github.com/apple/swift/blob/master/docs/Driver.md#output-file-maps
  1438. Json::Value entry = Json::Value(Json::objectValue);
  1439. entry["object"] = objectFilePath;
  1440. entry["dependencies"] = makeDepsPath;
  1441. entry["swift-dependencies"] = swiftDepsPath;
  1442. entry["diagnostics"] = swiftDiaPath;
  1443. this->Configs[config].SwiftOutputMap[sourceFilePath] = entry;
  1444. }
  1445. void cmNinjaTargetGenerator::ExportObjectCompileCommand(
  1446. std::string const& language, std::string const& sourceFileName,
  1447. std::string const& objectDir, std::string const& objectFileName,
  1448. std::string const& objectFileDir, std::string const& flags,
  1449. std::string const& defines, std::string const& includes,
  1450. std::string const& outputConfig)
  1451. {
  1452. if (!this->GeneratorTarget->GetPropertyAsBool("EXPORT_COMPILE_COMMANDS")) {
  1453. return;
  1454. }
  1455. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  1456. compileObjectVars.Language = language.c_str();
  1457. std::string escapedSourceFileName = sourceFileName;
  1458. if (!cmSystemTools::FileIsFullPath(sourceFileName)) {
  1459. escapedSourceFileName =
  1460. cmSystemTools::CollapseFullPath(escapedSourceFileName,
  1461. this->GetGlobalGenerator()
  1462. ->GetCMakeInstance()
  1463. ->GetHomeOutputDirectory());
  1464. }
  1465. escapedSourceFileName = this->LocalGenerator->ConvertToOutputFormat(
  1466. escapedSourceFileName, cmOutputConverter::SHELL);
  1467. compileObjectVars.Source = escapedSourceFileName.c_str();
  1468. compileObjectVars.Object = objectFileName.c_str();
  1469. compileObjectVars.ObjectDir = objectDir.c_str();
  1470. compileObjectVars.ObjectFileDir = objectFileDir.c_str();
  1471. compileObjectVars.Flags = flags.c_str();
  1472. compileObjectVars.Defines = defines.c_str();
  1473. compileObjectVars.Includes = includes.c_str();
  1474. // Rule for compiling object file.
  1475. std::string cudaCompileMode;
  1476. if (language == "CUDA") {
  1477. if (this->GeneratorTarget->GetPropertyAsBool(
  1478. "CUDA_SEPARABLE_COMPILATION")) {
  1479. const std::string& rdcFlag =
  1480. this->Makefile->GetRequiredDefinition("_CMAKE_CUDA_RDC_FLAG");
  1481. cudaCompileMode = cmStrCat(cudaCompileMode, rdcFlag, " ");
  1482. }
  1483. static std::array<cm::string_view, 4> const compileModes{
  1484. { "PTX"_s, "CUBIN"_s, "FATBIN"_s, "OPTIX"_s }
  1485. };
  1486. bool useNormalCompileMode = true;
  1487. for (cm::string_view mode : compileModes) {
  1488. auto propName = cmStrCat("CUDA_", mode, "_COMPILATION");
  1489. auto defName = cmStrCat("_CMAKE_CUDA_", mode, "_FLAG");
  1490. if (this->GeneratorTarget->GetPropertyAsBool(propName)) {
  1491. const std::string& flag =
  1492. this->Makefile->GetRequiredDefinition(defName);
  1493. cudaCompileMode = cmStrCat(cudaCompileMode, flag);
  1494. useNormalCompileMode = false;
  1495. break;
  1496. }
  1497. }
  1498. if (useNormalCompileMode) {
  1499. const std::string& wholeFlag =
  1500. this->Makefile->GetRequiredDefinition("_CMAKE_CUDA_WHOLE_FLAG");
  1501. cudaCompileMode = cmStrCat(cudaCompileMode, wholeFlag);
  1502. }
  1503. compileObjectVars.CudaCompileMode = cudaCompileMode.c_str();
  1504. }
  1505. const std::string cmdVar = cmStrCat("CMAKE_", language, "_COMPILE_OBJECT");
  1506. const std::string& compileCmd =
  1507. this->Makefile->GetRequiredDefinition(cmdVar);
  1508. cmList compileCmds(compileCmd);
  1509. auto rulePlaceholderExpander =
  1510. this->GetLocalGenerator()->CreateRulePlaceholderExpander();
  1511. for (auto& i : compileCmds) {
  1512. // no launcher for CMAKE_EXPORT_COMPILE_COMMANDS
  1513. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  1514. compileObjectVars);
  1515. }
  1516. std::string cmdLine = this->GetLocalGenerator()->BuildCommandLine(
  1517. compileCmds, outputConfig, outputConfig);
  1518. this->GetGlobalGenerator()->AddCXXCompileCommand(cmdLine, sourceFileName,
  1519. objectFileName);
  1520. }
  1521. void cmNinjaTargetGenerator::AdditionalCleanFiles(const std::string& config)
  1522. {
  1523. if (cmValue prop_value =
  1524. this->GeneratorTarget->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  1525. cmLocalNinjaGenerator* lg = this->LocalGenerator;
  1526. cmList cleanFiles(cmGeneratorExpression::Evaluate(*prop_value, lg, config,
  1527. this->GeneratorTarget));
  1528. std::string const& binaryDir = lg->GetCurrentBinaryDirectory();
  1529. cmGlobalNinjaGenerator* gg = lg->GetGlobalNinjaGenerator();
  1530. for (auto const& cleanFile : cleanFiles) {
  1531. // Support relative paths
  1532. gg->AddAdditionalCleanFile(
  1533. cmSystemTools::CollapseFullPath(cleanFile, binaryDir), config);
  1534. }
  1535. }
  1536. }
  1537. cmNinjaDeps cmNinjaTargetGenerator::GetObjects(const std::string& config) const
  1538. {
  1539. auto const it = this->Configs.find(config);
  1540. if (it != this->Configs.end()) {
  1541. return it->second.Objects;
  1542. }
  1543. return {};
  1544. }
  1545. void cmNinjaTargetGenerator::EnsureDirectoryExists(
  1546. const std::string& path) const
  1547. {
  1548. if (cmSystemTools::FileIsFullPath(path)) {
  1549. cmSystemTools::MakeDirectory(path);
  1550. } else {
  1551. cmGlobalNinjaGenerator* gg = this->GetGlobalGenerator();
  1552. std::string fullPath = gg->GetCMakeInstance()->GetHomeOutputDirectory();
  1553. // Also ensures there is a trailing slash.
  1554. gg->StripNinjaOutputPathPrefixAsSuffix(fullPath);
  1555. fullPath += path;
  1556. cmSystemTools::MakeDirectory(fullPath);
  1557. }
  1558. }
  1559. void cmNinjaTargetGenerator::EnsureParentDirectoryExists(
  1560. const std::string& path) const
  1561. {
  1562. this->EnsureDirectoryExists(cmSystemTools::GetParentDirectory(path));
  1563. }
  1564. void cmNinjaTargetGenerator::MacOSXContentGeneratorType::operator()(
  1565. cmSourceFile const& source, const char* pkgloc, const std::string& config)
  1566. {
  1567. // Skip OS X content when not building a Framework or Bundle.
  1568. if (!this->Generator->GetGeneratorTarget()->IsBundleOnApple()) {
  1569. return;
  1570. }
  1571. std::string macdir =
  1572. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(pkgloc,
  1573. config);
  1574. // Reject files that collide with files from the Ninja file's native config.
  1575. if (config != this->FileConfig) {
  1576. std::string nativeMacdir =
  1577. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(
  1578. pkgloc, this->FileConfig);
  1579. if (macdir == nativeMacdir) {
  1580. return;
  1581. }
  1582. }
  1583. // Get the input file location.
  1584. std::string input = source.GetFullPath();
  1585. input = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(input);
  1586. // Get the output file location.
  1587. std::string output =
  1588. cmStrCat(macdir, '/', cmSystemTools::GetFilenameName(input));
  1589. output = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(output);
  1590. // Write a build statement to copy the content into the bundle.
  1591. this->Generator->GetGlobalGenerator()->WriteMacOSXContentBuild(
  1592. input, output, this->FileConfig);
  1593. // Add as a dependency to the target so that it gets called.
  1594. this->Generator->Configs[config].ExtraFiles.push_back(std::move(output));
  1595. }
  1596. void cmNinjaTargetGenerator::addPoolNinjaVariable(
  1597. const std::string& pool_property, cmGeneratorTarget* target,
  1598. cmNinjaVars& vars)
  1599. {
  1600. cmValue pool = target->GetProperty(pool_property);
  1601. if (pool) {
  1602. vars["pool"] = *pool;
  1603. }
  1604. }
  1605. bool cmNinjaTargetGenerator::ForceResponseFile()
  1606. {
  1607. static std::string const forceRspFile = "CMAKE_NINJA_FORCE_RESPONSE_FILE";
  1608. return (this->GetMakefile()->IsDefinitionSet(forceRspFile) ||
  1609. cmSystemTools::HasEnv(forceRspFile));
  1610. }