cmNinjaTargetGenerator.cxx 77 KB

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