cmNinjaTargetGenerator.cxx 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535
  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/optional>
  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 "cmBuildDatabase.h"
  22. #include "cmComputeLinkInformation.h"
  23. #include "cmCustomCommandGenerator.h"
  24. #include "cmDyndepCollation.h"
  25. #include "cmFileSet.h"
  26. #include "cmGeneratedFileStream.h"
  27. #include "cmGeneratorExpression.h"
  28. #include "cmGeneratorTarget.h"
  29. #include "cmGlobalCommonGenerator.h"
  30. #include "cmGlobalNinjaGenerator.h"
  31. #include "cmList.h"
  32. #include "cmListFileCache.h"
  33. #include "cmLocalGenerator.h"
  34. #include "cmLocalNinjaGenerator.h"
  35. #include "cmMakefile.h"
  36. #include "cmMessageType.h"
  37. #include "cmNinjaNormalTargetGenerator.h"
  38. #include "cmNinjaUtilityTargetGenerator.h"
  39. #include "cmOutputConverter.h"
  40. #include "cmPolicies.h"
  41. #include "cmRange.h"
  42. #include "cmRulePlaceholderExpander.h"
  43. #include "cmSourceFile.h"
  44. #include "cmState.h"
  45. #include "cmStateTypes.h"
  46. #include "cmStringAlgorithms.h"
  47. #include "cmSystemTools.h"
  48. #include "cmTarget.h"
  49. #include "cmTargetDepend.h"
  50. #include "cmValue.h"
  51. #include "cmake.h"
  52. class cmCustomCommand;
  53. std::unique_ptr<cmNinjaTargetGenerator> cmNinjaTargetGenerator::New(
  54. cmGeneratorTarget* target)
  55. {
  56. switch (target->GetType()) {
  57. case cmStateEnums::EXECUTABLE:
  58. case cmStateEnums::SHARED_LIBRARY:
  59. case cmStateEnums::STATIC_LIBRARY:
  60. case cmStateEnums::MODULE_LIBRARY:
  61. case cmStateEnums::OBJECT_LIBRARY:
  62. return cm::make_unique<cmNinjaNormalTargetGenerator>(target);
  63. case cmStateEnums::INTERFACE_LIBRARY:
  64. if (target->HaveCxx20ModuleSources()) {
  65. return cm::make_unique<cmNinjaNormalTargetGenerator>(target);
  66. }
  67. CM_FALLTHROUGH;
  68. case cmStateEnums::UTILITY:
  69. case cmStateEnums::GLOBAL_TARGET:
  70. return cm::make_unique<cmNinjaUtilityTargetGenerator>(target);
  71. default:
  72. return std::unique_ptr<cmNinjaTargetGenerator>();
  73. }
  74. }
  75. cmNinjaTargetGenerator::cmNinjaTargetGenerator(cmGeneratorTarget* target)
  76. : cmCommonTargetGenerator(target)
  77. , OSXBundleGenerator(nullptr)
  78. , LocalGenerator(
  79. static_cast<cmLocalNinjaGenerator*>(target->GetLocalGenerator()))
  80. {
  81. for (auto const& fileConfig : this->LocalGenerator->GetConfigNames()) {
  82. this->Configs[fileConfig].MacOSXContentGenerator =
  83. cm::make_unique<MacOSXContentGeneratorType>(this, fileConfig);
  84. }
  85. }
  86. cmNinjaTargetGenerator::~cmNinjaTargetGenerator() = default;
  87. cmGeneratedFileStream& cmNinjaTargetGenerator::GetImplFileStream(
  88. const std::string& config) const
  89. {
  90. return *this->GetGlobalGenerator()->GetImplFileStream(config);
  91. }
  92. cmGeneratedFileStream& cmNinjaTargetGenerator::GetCommonFileStream() const
  93. {
  94. return *this->GetGlobalGenerator()->GetCommonFileStream();
  95. }
  96. cmGeneratedFileStream& cmNinjaTargetGenerator::GetRulesFileStream() const
  97. {
  98. return *this->GetGlobalGenerator()->GetRulesFileStream();
  99. }
  100. cmGlobalNinjaGenerator* cmNinjaTargetGenerator::GetGlobalGenerator() const
  101. {
  102. return this->LocalGenerator->GetGlobalNinjaGenerator();
  103. }
  104. std::string cmNinjaTargetGenerator::LanguageCompilerRule(
  105. const std::string& lang, const std::string& config,
  106. WithScanning withScanning) const
  107. {
  108. return cmStrCat(
  109. lang, "_COMPILER__",
  110. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  111. withScanning == WithScanning::Yes ? "_scanned_" : "_unscanned_", config);
  112. }
  113. std::string cmNinjaTargetGenerator::LanguagePreprocessAndScanRule(
  114. std::string const& lang, const std::string& config) const
  115. {
  116. return cmStrCat(
  117. lang, "_PREPROCESS_SCAN__",
  118. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  119. '_', config);
  120. }
  121. std::string cmNinjaTargetGenerator::LanguageScanRule(
  122. std::string const& lang, const std::string& config) const
  123. {
  124. return cmStrCat(
  125. lang, "_SCAN__",
  126. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  127. '_', config);
  128. }
  129. bool cmNinjaTargetGenerator::NeedExplicitPreprocessing(
  130. std::string const& lang) const
  131. {
  132. return lang == "Fortran" || lang == "Swift";
  133. }
  134. bool cmNinjaTargetGenerator::CompileWithDefines(std::string const& lang) const
  135. {
  136. return this->Makefile->IsOn(
  137. cmStrCat("CMAKE_", lang, "_COMPILE_WITH_DEFINES"));
  138. }
  139. std::string cmNinjaTargetGenerator::LanguageDyndepRule(
  140. const std::string& lang, const std::string& config) const
  141. {
  142. return cmStrCat(
  143. lang, "_DYNDEP__",
  144. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  145. '_', config);
  146. }
  147. std::string cmNinjaTargetGenerator::OrderDependsTargetForTarget(
  148. const std::string& config)
  149. {
  150. return this->GetGlobalGenerator()->OrderDependsTargetForTarget(
  151. this->GeneratorTarget, config);
  152. }
  153. std::string cmNinjaTargetGenerator::OrderDependsTargetForTargetPrivate(
  154. const std::string& config)
  155. {
  156. return this->GetGlobalGenerator()->OrderDependsTargetForTargetPrivate(
  157. this->GeneratorTarget, config);
  158. }
  159. // TODO: Most of the code is picked up from
  160. // void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink),
  161. // void cmMakefileTargetGenerator::WriteTargetLanguageFlags()
  162. // Refactor it.
  163. std::string cmNinjaTargetGenerator::ComputeFlagsForObject(
  164. cmSourceFile const* source, const std::string& language,
  165. const std::string& config, const std::string& objectFileName)
  166. {
  167. std::unordered_map<std::string, std::string> pchSources;
  168. std::vector<std::string> pchArchs =
  169. this->GeneratorTarget->GetPchArchs(config, language);
  170. std::string filterArch;
  171. for (const std::string& arch : pchArchs) {
  172. const std::string pchSource =
  173. this->GeneratorTarget->GetPchSource(config, language, arch);
  174. if (pchSource == source->GetFullPath()) {
  175. filterArch = arch;
  176. }
  177. if (!pchSource.empty()) {
  178. pchSources.insert(std::make_pair(pchSource, arch));
  179. }
  180. }
  181. std::string flags;
  182. // Explicitly add the explicit language flag before any other flag
  183. // so user flags can override it.
  184. this->GeneratorTarget->AddExplicitLanguageFlags(flags, *source);
  185. if (!flags.empty()) {
  186. flags += " ";
  187. }
  188. flags += this->GetFlags(language, config, filterArch);
  189. // Add Fortran format flags.
  190. if (language == "Fortran") {
  191. this->AppendFortranFormatFlags(flags, *source);
  192. this->AppendFortranPreprocessFlags(flags, *source,
  193. PreprocessFlagsRequired::NO);
  194. }
  195. // Add source file specific flags.
  196. cmGeneratorExpressionInterpreter genexInterpreter(
  197. this->LocalGenerator, config, this->GeneratorTarget, language);
  198. const std::string COMPILE_FLAGS("COMPILE_FLAGS");
  199. if (cmValue cflags = source->GetProperty(COMPILE_FLAGS)) {
  200. this->LocalGenerator->AppendFlags(
  201. flags, genexInterpreter.Evaluate(*cflags, COMPILE_FLAGS));
  202. }
  203. const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
  204. if (cmValue coptions = source->GetProperty(COMPILE_OPTIONS)) {
  205. this->LocalGenerator->AppendCompileOptions(
  206. flags, genexInterpreter.Evaluate(*coptions, COMPILE_OPTIONS));
  207. }
  208. // Add precompile headers compile options.
  209. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  210. std::string pchOptions;
  211. auto pchIt = pchSources.find(source->GetFullPath());
  212. if (pchIt != pchSources.end()) {
  213. pchOptions = this->GeneratorTarget->GetPchCreateCompileOptions(
  214. config, language, pchIt->second);
  215. } else {
  216. pchOptions =
  217. this->GeneratorTarget->GetPchUseCompileOptions(config, language);
  218. }
  219. this->LocalGenerator->AppendCompileOptions(
  220. flags, genexInterpreter.Evaluate(pchOptions, COMPILE_OPTIONS));
  221. }
  222. auto const* fs = this->GeneratorTarget->GetFileSetForSource(config, source);
  223. if (fs && fs->GetType() == "CXX_MODULES"_s) {
  224. if (source->GetLanguage() != "CXX"_s) {
  225. this->GetMakefile()->IssueMessage(
  226. MessageType::FATAL_ERROR,
  227. cmStrCat("Target \"", this->GeneratorTarget->Target->GetName(),
  228. "\" contains the source\n ", source->GetFullPath(),
  229. "\nin a file set of type \"", fs->GetType(),
  230. R"(" but the source is not classified as a "CXX" source.)"));
  231. }
  232. if (!this->GeneratorTarget->Target->IsNormal()) {
  233. auto flag = this->GetMakefile()->GetSafeDefinition(
  234. "CMAKE_CXX_MODULE_BMI_ONLY_FLAG");
  235. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  236. compileObjectVars.Object = objectFileName.c_str();
  237. auto rulePlaceholderExpander =
  238. this->GetLocalGenerator()->CreateRulePlaceholderExpander();
  239. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  240. flag, compileObjectVars);
  241. this->LocalGenerator->AppendCompileOptions(flags, flag);
  242. }
  243. }
  244. return flags;
  245. }
  246. void cmNinjaTargetGenerator::AddIncludeFlags(std::string& languageFlags,
  247. std::string const& language,
  248. const std::string& config)
  249. {
  250. std::vector<std::string> includes;
  251. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  252. language, config);
  253. // Add include directory flags.
  254. std::string includeFlags = this->LocalGenerator->GetIncludeFlags(
  255. includes, this->GeneratorTarget, language, config, false);
  256. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  257. std::replace(includeFlags.begin(), includeFlags.end(), '\\', '/');
  258. }
  259. this->LocalGenerator->AppendFlags(languageFlags, includeFlags);
  260. }
  261. // TODO: Refactor with
  262. // void cmMakefileTargetGenerator::WriteTargetLanguageFlags().
  263. std::string cmNinjaTargetGenerator::ComputeDefines(cmSourceFile const* source,
  264. const std::string& language,
  265. const std::string& config)
  266. {
  267. std::set<std::string> defines;
  268. cmGeneratorExpressionInterpreter genexInterpreter(
  269. this->LocalGenerator, config, this->GeneratorTarget, language);
  270. // Seriously??
  271. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  272. defines.insert(cmStrCat("CMAKE_INTDIR=\"", config, '"'));
  273. }
  274. const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
  275. if (cmValue compile_defs = source->GetProperty(COMPILE_DEFINITIONS)) {
  276. this->LocalGenerator->AppendDefines(
  277. defines, genexInterpreter.Evaluate(*compile_defs, COMPILE_DEFINITIONS));
  278. }
  279. std::string defPropName =
  280. cmStrCat("COMPILE_DEFINITIONS_", cmSystemTools::UpperCase(config));
  281. if (cmValue config_compile_defs = source->GetProperty(defPropName)) {
  282. this->LocalGenerator->AppendDefines(
  283. defines,
  284. genexInterpreter.Evaluate(*config_compile_defs, COMPILE_DEFINITIONS));
  285. }
  286. std::string definesString = this->GetDefines(language, config);
  287. this->LocalGenerator->JoinDefines(defines, definesString, language);
  288. return definesString;
  289. }
  290. std::string cmNinjaTargetGenerator::ComputeIncludes(
  291. cmSourceFile const* source, const std::string& language,
  292. const std::string& config)
  293. {
  294. std::vector<std::string> includes;
  295. cmGeneratorExpressionInterpreter genexInterpreter(
  296. this->LocalGenerator, config, this->GeneratorTarget, language);
  297. const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
  298. if (cmValue cincludes = source->GetProperty(INCLUDE_DIRECTORIES)) {
  299. this->LocalGenerator->AppendIncludeDirectories(
  300. includes, genexInterpreter.Evaluate(*cincludes, INCLUDE_DIRECTORIES),
  301. *source);
  302. }
  303. std::string includesString = this->LocalGenerator->GetIncludeFlags(
  304. includes, this->GeneratorTarget, language, config, false);
  305. this->LocalGenerator->AppendFlags(includesString,
  306. this->GetIncludes(language, config));
  307. return includesString;
  308. }
  309. cmNinjaDeps cmNinjaTargetGenerator::ComputeLinkDeps(
  310. const std::string& linkLanguage, const std::string& config,
  311. bool ignoreType) const
  312. {
  313. // Static libraries never depend on other targets for linking.
  314. if (!ignoreType &&
  315. (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  316. this->GeneratorTarget->GetType() == cmStateEnums::OBJECT_LIBRARY)) {
  317. return cmNinjaDeps();
  318. }
  319. cmComputeLinkInformation* cli =
  320. this->GeneratorTarget->GetLinkInformation(config);
  321. if (!cli) {
  322. return cmNinjaDeps();
  323. }
  324. const std::vector<std::string>& deps = cli->GetDepends();
  325. cmNinjaDeps result(deps.size());
  326. std::transform(deps.begin(), deps.end(), result.begin(),
  327. this->MapToNinjaPath());
  328. // Add a dependency on the link definitions file, if any.
  329. if (cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  330. this->GeneratorTarget->GetModuleDefinitionInfo(config)) {
  331. for (cmSourceFile const* src : mdi->Sources) {
  332. result.push_back(this->ConvertToNinjaPath(src->GetFullPath()));
  333. }
  334. }
  335. // Add a dependency on user-specified manifest files, if any.
  336. std::vector<cmSourceFile const*> manifest_srcs;
  337. this->GeneratorTarget->GetManifests(manifest_srcs, config);
  338. for (cmSourceFile const* manifest_src : manifest_srcs) {
  339. result.push_back(this->ConvertToNinjaPath(manifest_src->GetFullPath()));
  340. }
  341. // Add user-specified dependencies.
  342. std::vector<std::string> linkDeps;
  343. this->GeneratorTarget->GetLinkDepends(linkDeps, config, linkLanguage);
  344. std::transform(linkDeps.begin(), linkDeps.end(), std::back_inserter(result),
  345. this->MapToNinjaPath());
  346. return result;
  347. }
  348. std::string cmNinjaTargetGenerator::GetCompiledSourceNinjaPath(
  349. cmSourceFile const* source) const
  350. {
  351. // Pass source files to the compiler by absolute path.
  352. return this->ConvertToNinjaAbsPath(source->GetFullPath());
  353. }
  354. std::string cmNinjaTargetGenerator::GetObjectFileDir(
  355. const std::string& config) const
  356. {
  357. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  358. if (!path.empty()) {
  359. path += '/';
  360. }
  361. path +=
  362. cmStrCat(this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  363. this->GetGlobalGenerator()->ConfigDirectory(config));
  364. return path;
  365. }
  366. std::string cmNinjaTargetGenerator::GetObjectFilePath(
  367. cmSourceFile const* source, const std::string& config) const
  368. {
  369. std::string const& objectName = this->GeneratorTarget->GetObjectName(source);
  370. return cmStrCat(this->GetObjectFileDir(config), '/', objectName);
  371. }
  372. std::string cmNinjaTargetGenerator::GetBmiFilePath(
  373. cmSourceFile const* source, const std::string& config) const
  374. {
  375. auto& importedConfigInfo = this->Configs.at(config).ImportedCxxModules;
  376. if (!importedConfigInfo.Initialized()) {
  377. std::string configUpper = cmSystemTools::UpperCase(config);
  378. std::string propName = cmStrCat("IMPORTED_CXX_MODULES_", configUpper);
  379. auto value = this->GeneratorTarget->GetSafeProperty(propName);
  380. importedConfigInfo.Initialize(value);
  381. }
  382. std::string bmiName =
  383. importedConfigInfo.BmiNameForSource(source->GetFullPath());
  384. return cmStrCat(this->GetObjectFileDir(config), '/', bmiName);
  385. }
  386. std::string cmNinjaTargetGenerator::GetClangTidyReplacementsFilePath(
  387. std::string const& directory, cmSourceFile const& source,
  388. std::string const& config) const
  389. {
  390. auto path = this->LocalGenerator->GetHomeRelativeOutputPath();
  391. if (!path.empty()) {
  392. path += '/';
  393. }
  394. path = cmStrCat(directory, '/', path);
  395. auto const& objectName = this->GeneratorTarget->GetObjectName(&source);
  396. path =
  397. cmStrCat(std::move(path),
  398. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  399. this->GetGlobalGenerator()->ConfigDirectory(config), '/',
  400. objectName, ".yaml");
  401. return path;
  402. }
  403. std::string cmNinjaTargetGenerator::GetPreprocessedFilePath(
  404. cmSourceFile const* source, const std::string& config) const
  405. {
  406. // Choose an extension to compile already-preprocessed source.
  407. std::string ppExt = source->GetExtension();
  408. if (cmHasLiteralPrefix(ppExt, "F")) {
  409. // Some Fortran compilers automatically enable preprocessing for
  410. // upper-case extensions. Since the source is already preprocessed,
  411. // use a lower-case extension.
  412. ppExt = cmSystemTools::LowerCase(ppExt);
  413. }
  414. if (ppExt == "fpp") {
  415. // Some Fortran compilers automatically enable preprocessing for
  416. // the ".fpp" extension. Since the source is already preprocessed,
  417. // use the ".f" extension.
  418. ppExt = "f";
  419. }
  420. // Take the object file name and replace the extension.
  421. std::string const& objName = this->GeneratorTarget->GetObjectName(source);
  422. std::string const& objExt =
  423. this->GetGlobalGenerator()->GetLanguageOutputExtension(*source);
  424. assert(objName.size() >= objExt.size());
  425. std::string const ppName =
  426. cmStrCat(objName.substr(0, objName.size() - objExt.size()), "-pp.", ppExt);
  427. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  428. if (!path.empty()) {
  429. path += '/';
  430. }
  431. path +=
  432. cmStrCat(this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  433. this->GetGlobalGenerator()->ConfigDirectory(config), '/', ppName);
  434. return path;
  435. }
  436. std::string cmNinjaTargetGenerator::GetDyndepFilePath(
  437. std::string const& lang, const std::string& config) const
  438. {
  439. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  440. if (!path.empty()) {
  441. path += '/';
  442. }
  443. path += cmStrCat(
  444. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  445. this->GetGlobalGenerator()->ConfigDirectory(config), '/', lang, ".dd");
  446. return path;
  447. }
  448. std::string cmNinjaTargetGenerator::GetTargetDependInfoPath(
  449. std::string const& lang, const std::string& config) const
  450. {
  451. std::string path =
  452. cmStrCat(this->Makefile->GetCurrentBinaryDirectory(), '/',
  453. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  454. this->GetGlobalGenerator()->ConfigDirectory(config), '/', lang,
  455. "DependInfo.json");
  456. return path;
  457. }
  458. std::string cmNinjaTargetGenerator::GetTargetOutputDir(
  459. const std::string& config) const
  460. {
  461. std::string dir = this->GeneratorTarget->GetDirectory(config);
  462. return this->ConvertToNinjaPath(dir);
  463. }
  464. std::string cmNinjaTargetGenerator::GetTargetFilePath(
  465. const std::string& name, const std::string& config) const
  466. {
  467. std::string path = this->GetTargetOutputDir(config);
  468. if (path.empty() || path == ".") {
  469. return name;
  470. }
  471. path += cmStrCat('/', name);
  472. return path;
  473. }
  474. std::string cmNinjaTargetGenerator::GetTargetName() const
  475. {
  476. return this->GeneratorTarget->GetName();
  477. }
  478. bool cmNinjaTargetGenerator::SetMsvcTargetPdbVariable(
  479. cmNinjaVars& vars, const std::string& config) const
  480. {
  481. cmMakefile* mf = this->GetMakefile();
  482. if (mf->GetDefinition("MSVC_C_ARCHITECTURE_ID") ||
  483. mf->GetDefinition("MSVC_CXX_ARCHITECTURE_ID") ||
  484. mf->GetDefinition("MSVC_CUDA_ARCHITECTURE_ID")) {
  485. std::string pdbPath;
  486. std::string compilePdbPath = this->ComputeTargetCompilePDB(config);
  487. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
  488. this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  489. this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  490. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  491. pdbPath = cmStrCat(this->GeneratorTarget->GetPDBDirectory(config), '/',
  492. this->GeneratorTarget->GetPDBName(config));
  493. }
  494. vars["TARGET_PDB"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  495. this->ConvertToNinjaPath(pdbPath), cmOutputConverter::SHELL);
  496. vars["TARGET_COMPILE_PDB"] =
  497. this->GetLocalGenerator()->ConvertToOutputFormat(
  498. this->ConvertToNinjaPath(compilePdbPath), cmOutputConverter::SHELL);
  499. this->EnsureParentDirectoryExists(pdbPath);
  500. this->EnsureParentDirectoryExists(compilePdbPath);
  501. return true;
  502. }
  503. return false;
  504. }
  505. void cmNinjaTargetGenerator::WriteLanguageRules(const std::string& language,
  506. const std::string& config)
  507. {
  508. #ifdef NINJA_GEN_VERBOSE_FILES
  509. this->GetRulesFileStream() << "# Rules for language " << language << "\n\n";
  510. #endif
  511. this->WriteCompileRule(language, config);
  512. }
  513. namespace {
  514. // Create the command to run the dependency scanner
  515. std::string GetScanCommand(
  516. cm::string_view cmakeCmd, cm::string_view tdi, cm::string_view lang,
  517. cm::string_view srcFile, cm::string_view ddiFile,
  518. cm::optional<cm::string_view> srcOrigFile = cm::nullopt)
  519. {
  520. return cmStrCat(cmakeCmd, " -E cmake_ninja_depends --tdi=", tdi,
  521. " --lang=", lang, " --src=", srcFile, " --out=$out",
  522. " --dep=$DEP_FILE --obj=$OBJ_FILE --ddi=", ddiFile,
  523. srcOrigFile ? cmStrCat(" --src-orig=", *srcOrigFile) : "");
  524. }
  525. // Helper function to create dependency scanning rule that may or may
  526. // not perform explicit preprocessing too.
  527. cmNinjaRule GetScanRule(
  528. std::string const& ruleName, std::string const& ppFileName,
  529. std::string const& deptype,
  530. cmRulePlaceholderExpander::RuleVariables const& vars,
  531. const std::string& responseFlag, const std::string& flags,
  532. cmRulePlaceholderExpander* const rulePlaceholderExpander,
  533. cmLocalNinjaGenerator* generator, std::vector<std::string> scanCmds,
  534. const std::string& outputConfig)
  535. {
  536. cmNinjaRule rule(ruleName);
  537. // Scanning always uses a depfile for preprocessor dependencies.
  538. if (deptype == "msvc"_s) {
  539. rule.DepType = deptype;
  540. rule.DepFile.clear();
  541. } else {
  542. rule.DepType.clear(); // no deps= for multiple outputs
  543. rule.DepFile = "$DEP_FILE";
  544. }
  545. cmRulePlaceholderExpander::RuleVariables scanVars;
  546. scanVars.CMTargetName = vars.CMTargetName;
  547. scanVars.CMTargetType = vars.CMTargetType;
  548. scanVars.Language = vars.Language;
  549. scanVars.Object = "$OBJ_FILE";
  550. scanVars.PreprocessedSource = ppFileName.c_str();
  551. scanVars.DynDepFile = "$DYNDEP_INTERMEDIATE_FILE";
  552. scanVars.DependencyFile = rule.DepFile.c_str();
  553. scanVars.DependencyTarget = "$out";
  554. // Scanning needs the same preprocessor settings as direct compilation would.
  555. scanVars.Source = vars.Source;
  556. scanVars.Defines = vars.Defines;
  557. scanVars.Includes = vars.Includes;
  558. // Scanning needs the compilation flags too.
  559. std::string scanFlags = flags;
  560. // If using a response file, move defines, includes, and flags into it.
  561. if (!responseFlag.empty()) {
  562. rule.RspFile = "$RSP_FILE";
  563. rule.RspContent =
  564. cmStrCat(' ', scanVars.Defines, ' ', scanVars.Includes, ' ', scanFlags);
  565. scanFlags = cmStrCat(responseFlag, rule.RspFile);
  566. scanVars.Defines = "";
  567. scanVars.Includes = "";
  568. }
  569. scanVars.Flags = scanFlags.c_str();
  570. // Rule for scanning a source file.
  571. for (std::string& scanCmd : scanCmds) {
  572. rulePlaceholderExpander->ExpandRuleVariables(generator, scanCmd, scanVars);
  573. }
  574. rule.Command =
  575. generator->BuildCommandLine(scanCmds, outputConfig, outputConfig);
  576. return rule;
  577. }
  578. }
  579. void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang,
  580. const std::string& config)
  581. {
  582. // For some cases we scan to dynamically discover dependencies.
  583. bool const needDyndep = this->GetGeneratorTarget()->NeedDyndep(lang, config);
  584. if (needDyndep) {
  585. this->WriteCompileRule(lang, config, WithScanning::Yes);
  586. }
  587. this->WriteCompileRule(lang, config, WithScanning::No);
  588. }
  589. void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang,
  590. const std::string& config,
  591. WithScanning withScanning)
  592. {
  593. cmRulePlaceholderExpander::RuleVariables vars;
  594. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  595. vars.CMTargetType =
  596. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()).c_str();
  597. vars.Language = lang.c_str();
  598. vars.Source = "$in";
  599. vars.Object = "$out";
  600. vars.Defines = "$DEFINES";
  601. vars.Includes = "$INCLUDES";
  602. vars.TargetPDB = "$TARGET_PDB";
  603. vars.TargetCompilePDB = "$TARGET_COMPILE_PDB";
  604. vars.ObjectDir = "$OBJECT_DIR";
  605. vars.ObjectFileDir = "$OBJECT_FILE_DIR";
  606. vars.CudaCompileMode = "$CUDA_COMPILE_MODE";
  607. vars.ISPCHeader = "$ISPC_HEADER_FILE";
  608. cmMakefile* mf = this->GetMakefile();
  609. // For some cases we scan to dynamically discover dependencies.
  610. bool const compilationPreprocesses = !this->NeedExplicitPreprocessing(lang);
  611. std::string flags = "$FLAGS";
  612. std::string responseFlag;
  613. bool const lang_supports_response = lang != "RC";
  614. if (lang_supports_response && this->ForceResponseFile()) {
  615. std::string const responseFlagVar =
  616. cmStrCat("CMAKE_", lang, "_RESPONSE_FILE_FLAG");
  617. responseFlag = this->Makefile->GetSafeDefinition(responseFlagVar);
  618. if (responseFlag.empty() && lang != "CUDA") {
  619. responseFlag = "@";
  620. }
  621. }
  622. std::string const modmapFormatVar =
  623. cmStrCat("CMAKE_", lang, "_MODULE_MAP_FORMAT");
  624. std::string const modmapFormat =
  625. this->Makefile->GetSafeDefinition(modmapFormatVar);
  626. auto rulePlaceholderExpander =
  627. this->GetLocalGenerator()->CreateRulePlaceholderExpander();
  628. std::string const tdi = this->GetLocalGenerator()->ConvertToOutputFormat(
  629. this->ConvertToNinjaPath(this->GetTargetDependInfoPath(lang, config)),
  630. cmLocalGenerator::SHELL);
  631. std::string launcher;
  632. std::string val = this->GetLocalGenerator()->GetRuleLauncher(
  633. this->GetGeneratorTarget(), "RULE_LAUNCH_COMPILE", config);
  634. if (cmNonempty(val)) {
  635. launcher = cmStrCat(val, ' ');
  636. }
  637. std::string const cmakeCmd =
  638. this->GetLocalGenerator()->ConvertToOutputFormat(
  639. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  640. if (withScanning == WithScanning::Yes) {
  641. const auto& scanDepType = this->GetMakefile()->GetSafeDefinition(
  642. cmStrCat("CMAKE_", lang, "_SCANDEP_DEPFILE_FORMAT"));
  643. // Rule to scan dependencies of sources that need preprocessing.
  644. {
  645. cmList scanCommands;
  646. std::string scanRuleName;
  647. std::string ppFileName;
  648. if (compilationPreprocesses) {
  649. scanRuleName = this->LanguageScanRule(lang, config);
  650. ppFileName = "$PREPROCESSED_OUTPUT_FILE";
  651. std::string const& scanCommand = mf->GetRequiredDefinition(
  652. cmStrCat("CMAKE_", lang, "_SCANDEP_SOURCE"));
  653. scanCommands.assign(scanCommand);
  654. for (auto& i : scanCommands) {
  655. i = cmStrCat(launcher, i);
  656. }
  657. } else {
  658. scanRuleName = this->LanguagePreprocessAndScanRule(lang, config);
  659. ppFileName = "$out";
  660. std::string const& ppCommmand = mf->GetRequiredDefinition(
  661. cmStrCat("CMAKE_", lang, "_PREPROCESS_SOURCE"));
  662. scanCommands.assign(ppCommmand);
  663. for (auto& i : scanCommands) {
  664. i = cmStrCat(launcher, i);
  665. }
  666. scanCommands.emplace_back(GetScanCommand(
  667. cmakeCmd, tdi, lang, "$out", "$DYNDEP_INTERMEDIATE_FILE", "$in"));
  668. }
  669. auto scanRule = GetScanRule(
  670. scanRuleName, ppFileName, scanDepType, vars, responseFlag, flags,
  671. rulePlaceholderExpander.get(), this->GetLocalGenerator(),
  672. std::move(scanCommands), config);
  673. scanRule.Comment =
  674. cmStrCat("Rule for generating ", lang, " dependencies.");
  675. if (compilationPreprocesses) {
  676. scanRule.Description =
  677. cmStrCat("Scanning $in for ", lang, " dependencies");
  678. } else {
  679. scanRule.Description =
  680. cmStrCat("Building ", lang, " preprocessed $out");
  681. }
  682. this->GetGlobalGenerator()->AddRule(scanRule);
  683. }
  684. if (!compilationPreprocesses) {
  685. // Compilation will not preprocess, so it does not need the defines
  686. // unless the compiler wants them for some other purpose.
  687. if (!this->CompileWithDefines(lang)) {
  688. vars.Defines = "";
  689. }
  690. // Rule to scan dependencies of sources that do not need preprocessing.
  691. std::string const& scanRuleName = this->LanguageScanRule(lang, config);
  692. std::vector<std::string> scanCommands;
  693. scanCommands.emplace_back(
  694. GetScanCommand(cmakeCmd, tdi, lang, "$in", "$out"));
  695. auto scanRule =
  696. GetScanRule(scanRuleName, "", scanDepType, vars, "", flags,
  697. rulePlaceholderExpander.get(), this->GetLocalGenerator(),
  698. std::move(scanCommands), config);
  699. // Write the rule for generating dependencies for the given language.
  700. scanRule.Comment = cmStrCat("Rule for generating ", lang,
  701. " dependencies on non-preprocessed files.");
  702. scanRule.Description =
  703. cmStrCat("Generating ", lang, " dependencies for $in");
  704. this->GetGlobalGenerator()->AddRule(scanRule);
  705. }
  706. // Write the rule for ninja dyndep file generation.
  707. cmNinjaRule rule(this->LanguageDyndepRule(lang, config));
  708. // Command line length is almost always limited -> use response file for
  709. // dyndep rules
  710. rule.RspFile = "$out.rsp";
  711. rule.RspContent = "$in";
  712. // Ninja's collator writes all outputs using `cmGeneratedFileStream`, so
  713. // they are only updated if contents actually change. Avoid running
  714. // dependent jobs if the contents don't change by telling `ninja` to check
  715. // the timestamp again.
  716. rule.Restat = "1";
  717. // Run CMake dependency scanner on the source file (using the preprocessed
  718. // source if that was performed).
  719. std::string ddModmapArg;
  720. if (!modmapFormat.empty()) {
  721. ddModmapArg += cmStrCat(" --modmapfmt=", modmapFormat);
  722. }
  723. {
  724. std::vector<std::string> ddCmds;
  725. {
  726. std::string ccmd = cmStrCat(
  727. cmakeCmd, " -E cmake_ninja_dyndep --tdi=", tdi, " --lang=", lang,
  728. ddModmapArg, " --dd=$out @", rule.RspFile);
  729. ddCmds.emplace_back(std::move(ccmd));
  730. }
  731. rule.Command =
  732. this->GetLocalGenerator()->BuildCommandLine(ddCmds, config, config);
  733. }
  734. rule.Comment =
  735. cmStrCat("Rule to generate ninja dyndep files for ", lang, '.');
  736. rule.Description = cmStrCat("Generating ", lang, " dyndep file $out");
  737. this->GetGlobalGenerator()->AddRule(rule);
  738. }
  739. cmNinjaRule rule(this->LanguageCompilerRule(lang, config, withScanning));
  740. // If using a response file, move defines, includes, and flags into it.
  741. if (!responseFlag.empty()) {
  742. rule.RspFile = "$RSP_FILE";
  743. rule.RspContent =
  744. cmStrCat(' ', vars.Defines, ' ', vars.Includes, ' ', flags);
  745. flags = cmStrCat(responseFlag, rule.RspFile);
  746. vars.Defines = "";
  747. vars.Includes = "";
  748. // Swift consumes all source files in a module at once, which reaches
  749. // command line length limits pretty quickly. Inject source files into the
  750. // response file in this case as well.
  751. if (lang == "Swift") {
  752. rule.RspContent = cmStrCat(rule.RspContent, ' ', vars.Source);
  753. vars.Source = "";
  754. }
  755. }
  756. // Tell ninja dependency format so all deps can be loaded into a database
  757. std::string cldeps;
  758. if (!compilationPreprocesses) {
  759. // The compiler will not do preprocessing, so it has no such dependencies.
  760. } else if (mf->IsOn(cmStrCat("CMAKE_NINJA_CMCLDEPS_", lang))) {
  761. // For the MS resource compiler we need cmcldeps, but skip dependencies
  762. // for source-file try_compile cases because they are always fresh.
  763. if (!mf->GetIsSourceFileTryCompile()) {
  764. rule.DepType = "gcc";
  765. rule.DepFile = "$DEP_FILE";
  766. cmValue d = mf->GetDefinition("CMAKE_C_COMPILER");
  767. const std::string cl =
  768. d ? *d : mf->GetSafeDefinition("CMAKE_CXX_COMPILER");
  769. std::string cmcldepsPath;
  770. cmSystemTools::GetShortPath(cmSystemTools::GetCMClDepsCommand(),
  771. cmcldepsPath);
  772. cldeps = cmStrCat(cmcldepsPath, ' ', lang, ' ', vars.Source,
  773. " $DEP_FILE $out \"",
  774. mf->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX"),
  775. "\" \"", cl, "\" ");
  776. }
  777. } else {
  778. const auto& depType = this->GetMakefile()->GetSafeDefinition(
  779. cmStrCat("CMAKE_", lang, "_DEPFILE_FORMAT"));
  780. if (depType == "msvc"_s) {
  781. rule.DepType = "msvc";
  782. rule.DepFile.clear();
  783. } else {
  784. rule.DepType = "gcc";
  785. rule.DepFile = "$DEP_FILE";
  786. }
  787. vars.DependencyFile = rule.DepFile.c_str();
  788. vars.DependencyTarget = "$out";
  789. const std::string flagsName = cmStrCat("CMAKE_DEPFILE_FLAGS_", lang);
  790. std::string depfileFlags = mf->GetSafeDefinition(flagsName);
  791. if (!depfileFlags.empty()) {
  792. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  793. depfileFlags, vars);
  794. flags += cmStrCat(' ', depfileFlags);
  795. }
  796. }
  797. if (withScanning == WithScanning::Yes && !modmapFormat.empty()) {
  798. std::string modmapFlags =
  799. mf->GetRequiredDefinition(cmStrCat("CMAKE_", lang, "_MODULE_MAP_FLAG"));
  800. cmSystemTools::ReplaceString(modmapFlags, "<MODULE_MAP_FILE>",
  801. "$DYNDEP_MODULE_MAP_FILE");
  802. flags += cmStrCat(' ', modmapFlags);
  803. }
  804. vars.Flags = flags.c_str();
  805. vars.DependencyFile = rule.DepFile.c_str();
  806. std::string cudaCompileMode;
  807. if (lang == "CUDA") {
  808. if (this->GeneratorTarget->GetPropertyAsBool(
  809. "CUDA_SEPARABLE_COMPILATION")) {
  810. const std::string& rdcFlag =
  811. this->Makefile->GetRequiredDefinition("_CMAKE_CUDA_RDC_FLAG");
  812. cudaCompileMode = cmStrCat(cudaCompileMode, rdcFlag, " ");
  813. }
  814. static std::array<cm::string_view, 4> const compileModes{
  815. { "PTX"_s, "CUBIN"_s, "FATBIN"_s, "OPTIX"_s }
  816. };
  817. bool useNormalCompileMode = true;
  818. for (cm::string_view mode : compileModes) {
  819. auto propName = cmStrCat("CUDA_", mode, "_COMPILATION");
  820. auto defName = cmStrCat("_CMAKE_CUDA_", mode, "_FLAG");
  821. if (this->GeneratorTarget->GetPropertyAsBool(propName)) {
  822. const std::string& flag =
  823. this->Makefile->GetRequiredDefinition(defName);
  824. cudaCompileMode = cmStrCat(cudaCompileMode, flag);
  825. useNormalCompileMode = false;
  826. break;
  827. }
  828. }
  829. if (useNormalCompileMode) {
  830. const std::string& wholeFlag =
  831. this->Makefile->GetRequiredDefinition("_CMAKE_CUDA_WHOLE_FLAG");
  832. cudaCompileMode = cmStrCat(cudaCompileMode, wholeFlag);
  833. }
  834. vars.CudaCompileMode = cudaCompileMode.c_str();
  835. }
  836. // Rule for compiling object file.
  837. const std::string cmdVar = cmStrCat("CMAKE_", lang, "_COMPILE_OBJECT");
  838. const std::string& compileCmd = mf->GetRequiredDefinition(cmdVar);
  839. cmList compileCmds(compileCmd);
  840. if (!compileCmds.empty()) {
  841. compileCmds.front().insert(0, "${CODE_CHECK}");
  842. compileCmds.front().insert(0, "${LAUNCHER}");
  843. }
  844. if (!compileCmds.empty()) {
  845. compileCmds.front().insert(0, cldeps);
  846. }
  847. const auto& extraCommands = this->GetMakefile()->GetSafeDefinition(
  848. cmStrCat("CMAKE_", lang, "_DEPENDS_EXTRA_COMMANDS"));
  849. if (!extraCommands.empty()) {
  850. compileCmds.append(extraCommands);
  851. }
  852. for (auto& i : compileCmds) {
  853. i = cmStrCat(launcher, i);
  854. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  855. vars);
  856. }
  857. rule.Command =
  858. this->GetLocalGenerator()->BuildCommandLine(compileCmds, config, config);
  859. // Write the rule for compiling file of the given language.
  860. rule.Comment = cmStrCat("Rule for compiling ", lang, " files.");
  861. rule.Description = cmStrCat("Building ", lang, " object $out");
  862. this->GetGlobalGenerator()->AddRule(rule);
  863. }
  864. void cmNinjaTargetGenerator::WriteObjectBuildStatements(
  865. const std::string& config, const std::string& fileConfig,
  866. bool firstForConfig)
  867. {
  868. this->GeneratorTarget->CheckCxxModuleStatus(config);
  869. // Write comments.
  870. cmGlobalNinjaGenerator::WriteDivider(this->GetImplFileStream(fileConfig));
  871. this->GetImplFileStream(fileConfig)
  872. << "# Object build statements for "
  873. << cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType())
  874. << " target " << this->GetTargetName() << "\n\n";
  875. std::vector<cmCustomCommand const*> customCommands;
  876. {
  877. std::vector<cmSourceFile const*> customCommandSources;
  878. this->GeneratorTarget->GetCustomCommands(customCommandSources, config);
  879. for (cmSourceFile const* sf : customCommandSources) {
  880. cmCustomCommand const* cc = sf->GetCustomCommand();
  881. this->GetLocalGenerator()->AddCustomCommandTarget(
  882. cc, this->GetGeneratorTarget());
  883. customCommands.push_back(cc);
  884. }
  885. }
  886. {
  887. std::vector<cmSourceFile const*> headerSources;
  888. this->GeneratorTarget->GetHeaderSources(headerSources, config);
  889. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  890. headerSources, this->Configs[fileConfig].MacOSXContentGenerator.get(),
  891. config);
  892. }
  893. {
  894. std::vector<cmSourceFile const*> extraSources;
  895. this->GeneratorTarget->GetExtraSources(extraSources, config);
  896. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  897. extraSources, this->Configs[fileConfig].MacOSXContentGenerator.get(),
  898. config);
  899. }
  900. if (firstForConfig) {
  901. cmValue pchExtension =
  902. this->GetMakefile()->GetDefinition("CMAKE_PCH_EXTENSION");
  903. std::vector<cmSourceFile const*> externalObjects;
  904. this->GeneratorTarget->GetExternalObjects(externalObjects, config);
  905. for (cmSourceFile const* sf : externalObjects) {
  906. auto objectFileName = this->GetGlobalGenerator()->ExpandCFGIntDir(
  907. this->ConvertToNinjaPath(sf->GetFullPath()), config);
  908. if (!cmHasSuffix(objectFileName, pchExtension)) {
  909. this->Configs[config].Objects.push_back(objectFileName);
  910. }
  911. }
  912. }
  913. if (!this->GetGlobalGenerator()->SupportsCWDDepend()) {
  914. // Ensure that the object directory exists. If there are no objects in the
  915. // target (e.g., an empty `OBJECT` library), the directory is still listed
  916. // as an order-only depends in the build files. Alternate `ninja`
  917. // implementations may not allow this (such as `samu`). See #25526.
  918. auto const objectDir = this->GetObjectFileDir(config);
  919. this->EnsureDirectoryExists(objectDir);
  920. }
  921. {
  922. cmNinjaBuild build("phony");
  923. build.Comment =
  924. cmStrCat("Order-only phony target for ", this->GetTargetName());
  925. build.Outputs.push_back(this->OrderDependsTargetForTarget(config));
  926. // Gather order-only dependencies on custom command outputs.
  927. std::vector<std::string> ccouts;
  928. std::vector<std::string> ccouts_private;
  929. bool usePrivateGeneratedSources = false;
  930. if (this->GeneratorTarget->Target->HasFileSets()) {
  931. switch (this->GetGeneratorTarget()->GetPolicyStatusCMP0154()) {
  932. case cmPolicies::WARN:
  933. case cmPolicies::OLD:
  934. break;
  935. case cmPolicies::REQUIRED_ALWAYS:
  936. case cmPolicies::REQUIRED_IF_USED:
  937. case cmPolicies::NEW:
  938. usePrivateGeneratedSources = true;
  939. break;
  940. }
  941. }
  942. for (cmCustomCommand const* cc : customCommands) {
  943. cmCustomCommandGenerator ccg(*cc, config, this->GetLocalGenerator());
  944. const std::vector<std::string>& ccoutputs = ccg.GetOutputs();
  945. const std::vector<std::string>& ccbyproducts = ccg.GetByproducts();
  946. auto const nPreviousOutputs = ccouts.size();
  947. ccouts.insert(ccouts.end(), ccoutputs.begin(), ccoutputs.end());
  948. ccouts.insert(ccouts.end(), ccbyproducts.begin(), ccbyproducts.end());
  949. if (usePrivateGeneratedSources) {
  950. auto it = ccouts.begin();
  951. // Skip over outputs that were already detected.
  952. std::advance(it, nPreviousOutputs);
  953. while (it != ccouts.end()) {
  954. cmFileSet const* fileset =
  955. this->GeneratorTarget->GetFileSetForSource(
  956. config, this->Makefile->GetOrCreateGeneratedSource(*it));
  957. bool isVisible = fileset &&
  958. cmFileSetVisibilityIsForInterface(fileset->GetVisibility());
  959. bool isIncludeable =
  960. !fileset || cmFileSetTypeCanBeIncluded(fileset->GetType());
  961. if (fileset && isVisible && isIncludeable) {
  962. ++it;
  963. continue;
  964. }
  965. if (!fileset || isIncludeable) {
  966. ccouts_private.push_back(*it);
  967. }
  968. it = ccouts.erase(it);
  969. }
  970. }
  971. }
  972. cmNinjaDeps& orderOnlyDeps = build.OrderOnlyDeps;
  973. this->GetLocalGenerator()->AppendTargetDepends(
  974. this->GeneratorTarget, orderOnlyDeps, config, fileConfig,
  975. DependOnTargetOrdering);
  976. // Add order-only dependencies on other files associated with the target.
  977. cm::append(orderOnlyDeps, this->Configs[config].ExtraFiles);
  978. // Add order-only dependencies on custom command outputs.
  979. std::transform(ccouts.begin(), ccouts.end(),
  980. std::back_inserter(orderOnlyDeps), this->MapToNinjaPath());
  981. std::sort(orderOnlyDeps.begin(), orderOnlyDeps.end());
  982. orderOnlyDeps.erase(
  983. std::unique(orderOnlyDeps.begin(), orderOnlyDeps.end()),
  984. orderOnlyDeps.end());
  985. // The phony target must depend on at least one input or ninja will explain
  986. // that "output ... of phony edge with no inputs doesn't exist" and
  987. // consider the phony output "dirty".
  988. if (orderOnlyDeps.empty()) {
  989. std::string tgtDir;
  990. if (this->GetGlobalGenerator()->SupportsCWDDepend()) {
  991. tgtDir = ".";
  992. } else {
  993. // Any path that always exists will work here.
  994. tgtDir = cmStrCat(
  995. this->LocalGenerator->GetCurrentBinaryDirectory(), '/',
  996. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget));
  997. }
  998. orderOnlyDeps.push_back(this->ConvertToNinjaPath(tgtDir));
  999. }
  1000. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1001. build);
  1002. // Add order-only dependencies on custom command outputs that are
  1003. // private to this target.
  1004. this->HasPrivateGeneratedSources = !ccouts_private.empty();
  1005. if (this->HasPrivateGeneratedSources) {
  1006. cmNinjaBuild buildPrivate("phony");
  1007. cmNinjaDeps& orderOnlyDepsPrivate = buildPrivate.OrderOnlyDeps;
  1008. orderOnlyDepsPrivate.push_back(
  1009. this->OrderDependsTargetForTarget(config));
  1010. buildPrivate.Outputs.push_back(
  1011. this->OrderDependsTargetForTargetPrivate(config));
  1012. std::transform(ccouts_private.begin(), ccouts_private.end(),
  1013. std::back_inserter(orderOnlyDepsPrivate),
  1014. this->MapToNinjaPath());
  1015. std::sort(orderOnlyDepsPrivate.begin(), orderOnlyDepsPrivate.end());
  1016. orderOnlyDepsPrivate.erase(
  1017. std::unique(orderOnlyDepsPrivate.begin(), orderOnlyDepsPrivate.end()),
  1018. orderOnlyDepsPrivate.end());
  1019. this->GetGlobalGenerator()->WriteBuild(
  1020. this->GetImplFileStream(fileConfig), buildPrivate);
  1021. }
  1022. }
  1023. {
  1024. std::vector<cmSourceFile const*> objectSources;
  1025. this->GeneratorTarget->GetObjectSources(objectSources, config);
  1026. std::vector<cmSourceFile const*> swiftSources;
  1027. for (cmSourceFile const* sf : objectSources) {
  1028. if (this->GetLocalGenerator()->IsSplitSwiftBuild() &&
  1029. sf->GetLanguage() == "Swift") {
  1030. swiftSources.push_back(sf);
  1031. } else {
  1032. this->WriteObjectBuildStatement(sf, config, fileConfig,
  1033. firstForConfig);
  1034. }
  1035. }
  1036. WriteSwiftObjectBuildStatement(swiftSources, config, fileConfig,
  1037. firstForConfig);
  1038. }
  1039. {
  1040. std::vector<cmSourceFile const*> bmiOnlySources;
  1041. this->GeneratorTarget->GetCxxModuleSources(bmiOnlySources, config);
  1042. for (cmSourceFile const* sf : bmiOnlySources) {
  1043. this->WriteCxxModuleBmiBuildStatement(sf, config, fileConfig,
  1044. firstForConfig);
  1045. }
  1046. }
  1047. // Detect sources in `CXX_MODULES` which are not compiled.
  1048. {
  1049. std::vector<cmSourceFile*> sources;
  1050. this->GeneratorTarget->GetSourceFiles(sources, config);
  1051. for (cmSourceFile const* sf : sources) {
  1052. cmFileSet const* fs =
  1053. this->GeneratorTarget->GetFileSetForSource(config, sf);
  1054. if (!fs) {
  1055. continue;
  1056. }
  1057. if (fs->GetType() != "CXX_MODULES"_s) {
  1058. continue;
  1059. }
  1060. if (sf->GetLanguage().empty()) {
  1061. this->GeneratorTarget->Makefile->IssueMessage(
  1062. MessageType::FATAL_ERROR,
  1063. cmStrCat("Target \"", this->GeneratorTarget->GetName(),
  1064. "\" has source file\n ", sf->GetFullPath(),
  1065. "\nin a \"FILE_SET TYPE CXX_MODULES\" but it is not "
  1066. "scheduled for compilation."));
  1067. }
  1068. }
  1069. }
  1070. // Check if there are Fortran objects which need to participate in forwarding
  1071. // module requirements.
  1072. if (this->GeneratorTarget->HaveFortranSources(config) &&
  1073. !this->Configs[config].ScanningInfo.count("Fortran")) {
  1074. ScanningFiles files;
  1075. this->Configs[config].ScanningInfo["Fortran"].emplace_back(files);
  1076. this->WriteCompileRule("Fortran", config, WithScanning::Yes);
  1077. }
  1078. for (auto const& langScanningFiles : this->Configs[config].ScanningInfo) {
  1079. std::string const& language = langScanningFiles.first;
  1080. std::vector<ScanningFiles> const& scanningFiles = langScanningFiles.second;
  1081. cmNinjaBuild build(this->LanguageDyndepRule(language, config));
  1082. build.Outputs.push_back(this->GetDyndepFilePath(language, config));
  1083. build.ImplicitOuts.emplace_back(
  1084. cmStrCat(this->Makefile->GetCurrentBinaryDirectory(), '/',
  1085. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  1086. this->GetGlobalGenerator()->ConfigDirectory(config), '/',
  1087. language, "Modules.json"));
  1088. build.ImplicitDeps.emplace_back(
  1089. this->GetTargetDependInfoPath(language, config));
  1090. {
  1091. auto bdb_path =
  1092. this->GeneratorTarget->BuildDatabasePath(language, config);
  1093. if (!bdb_path.empty()) {
  1094. build.ImplicitOuts.emplace_back(this->ConvertToNinjaPath(bdb_path));
  1095. }
  1096. }
  1097. auto bdb_path = this->GeneratorTarget->BuildDatabasePath(language, config);
  1098. if (!bdb_path.empty()) {
  1099. auto db = cmBuildDatabase::ForTarget(this->GeneratorTarget, config);
  1100. auto mcdb_template_path = cmStrCat(bdb_path, ".in");
  1101. db.Write(mcdb_template_path);
  1102. build.ImplicitDeps.emplace_back(std::move(mcdb_template_path));
  1103. build.ImplicitOuts.emplace_back(std::move(bdb_path));
  1104. }
  1105. for (auto const& scanFiles : scanningFiles) {
  1106. if (!scanFiles.ScanningOutput.empty()) {
  1107. build.ExplicitDeps.push_back(scanFiles.ScanningOutput);
  1108. }
  1109. if (!scanFiles.ModuleMapFile.empty()) {
  1110. build.ImplicitOuts.push_back(scanFiles.ModuleMapFile);
  1111. }
  1112. }
  1113. this->WriteTargetDependInfo(language, config);
  1114. auto const linked_directories =
  1115. this->GetLinkedTargetDirectories(language, config);
  1116. for (std::string const& l : linked_directories.Direct) {
  1117. build.ImplicitDeps.emplace_back(
  1118. cmStrCat(l, '/', language, "Modules.json"));
  1119. }
  1120. for (std::string const& l : linked_directories.Forward) {
  1121. build.ImplicitDeps.emplace_back(
  1122. cmStrCat(l, '/', language, "Modules.json"));
  1123. }
  1124. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1125. build);
  1126. }
  1127. this->GetImplFileStream(fileConfig) << "\n";
  1128. }
  1129. void cmNinjaTargetGenerator::GenerateSwiftOutputFileMap(
  1130. const std::string& config, std::string& flags)
  1131. {
  1132. if (this->Configs[config].SwiftOutputMap.empty()) {
  1133. return;
  1134. }
  1135. std::string const targetSwiftDepsPath = [this, config]() -> std::string {
  1136. cmGeneratorTarget const* target = this->GeneratorTarget;
  1137. if (cmValue name = target->GetProperty("Swift_DEPENDENCIES_FILE")) {
  1138. return *name;
  1139. }
  1140. return this->ConvertToNinjaPath(cmStrCat(target->GetSupportDirectory(),
  1141. '/', config, '/',
  1142. target->GetName(), ".swiftdeps"));
  1143. }();
  1144. std::string mapFilePath =
  1145. cmStrCat(this->GeneratorTarget->GetSupportDirectory(), '/', config, '/',
  1146. "output-file-map.json");
  1147. // build the global target dependencies
  1148. // https://github.com/apple/swift/blob/master/docs/Driver.md#output-file-maps
  1149. Json::Value deps(Json::objectValue);
  1150. deps["swift-dependencies"] = targetSwiftDepsPath;
  1151. this->Configs[config].SwiftOutputMap[""] = deps;
  1152. cmGeneratedFileStream output(mapFilePath);
  1153. output << this->Configs[config].SwiftOutputMap;
  1154. // Add flag
  1155. this->LocalGenerator->AppendFlags(flags, "-output-file-map");
  1156. this->LocalGenerator->AppendFlags(
  1157. flags,
  1158. this->GetLocalGenerator()->ConvertToOutputFormat(
  1159. ConvertToNinjaPath(mapFilePath), cmOutputConverter::SHELL));
  1160. }
  1161. namespace {
  1162. cmNinjaBuild GetScanBuildStatement(const std::string& ruleName,
  1163. const std::string& ppFileName,
  1164. bool compilePP, bool compilePPWithDefines,
  1165. bool compilationPreprocesses,
  1166. cmNinjaBuild& objBuild, cmNinjaVars& vars,
  1167. const std::string& objectFileName,
  1168. cmNinjaTargetGenerator* tg)
  1169. {
  1170. cmNinjaBuild scanBuild(ruleName);
  1171. if (compilePP) {
  1172. // Move compilation dependencies to the scan/preprocessing build statement.
  1173. std::swap(scanBuild.ExplicitDeps, objBuild.ExplicitDeps);
  1174. std::swap(scanBuild.ImplicitDeps, objBuild.ImplicitDeps);
  1175. std::swap(scanBuild.OrderOnlyDeps, objBuild.OrderOnlyDeps);
  1176. std::swap(scanBuild.Variables["IN_ABS"], vars["IN_ABS"]);
  1177. // The actual compilation will now use the preprocessed source.
  1178. objBuild.ExplicitDeps.push_back(ppFileName);
  1179. } else {
  1180. // Copy compilation dependencies to the scan/preprocessing build statement.
  1181. scanBuild.ExplicitDeps = objBuild.ExplicitDeps;
  1182. scanBuild.ImplicitDeps = objBuild.ImplicitDeps;
  1183. scanBuild.OrderOnlyDeps = objBuild.OrderOnlyDeps;
  1184. scanBuild.Variables["IN_ABS"] = vars["IN_ABS"];
  1185. }
  1186. // Scanning and compilation generally use the same flags.
  1187. scanBuild.Variables["FLAGS"] = vars["FLAGS"];
  1188. if (compilePP && !compilePPWithDefines) {
  1189. // Move preprocessor definitions to the scan/preprocessor build statement.
  1190. std::swap(scanBuild.Variables["DEFINES"], vars["DEFINES"]);
  1191. } else {
  1192. // Copy preprocessor definitions to the scan/preprocessor build statement.
  1193. scanBuild.Variables["DEFINES"] = vars["DEFINES"];
  1194. }
  1195. // Copy include directories to the preprocessor build statement. The
  1196. // Fortran compilation build statement still needs them for the INCLUDE
  1197. // directive.
  1198. scanBuild.Variables["INCLUDES"] = vars["INCLUDES"];
  1199. // Tell dependency scanner the object file that will result from
  1200. // compiling the source.
  1201. scanBuild.Variables["OBJ_FILE"] = objectFileName;
  1202. // Tell dependency scanner where to store dyndep intermediate results.
  1203. std::string ddiFileName = cmStrCat(objectFileName, ".ddi");
  1204. scanBuild.Variables["DYNDEP_INTERMEDIATE_FILE"] = ddiFileName;
  1205. scanBuild.RspFile = cmStrCat(ddiFileName, ".rsp");
  1206. // Outputs of the scan/preprocessor build statement.
  1207. if (compilePP) {
  1208. scanBuild.Outputs.push_back(ppFileName);
  1209. scanBuild.ImplicitOuts.push_back(ddiFileName);
  1210. } else {
  1211. scanBuild.Outputs.push_back(ddiFileName);
  1212. scanBuild.Variables["PREPROCESSED_OUTPUT_FILE"] = ppFileName;
  1213. if (!compilationPreprocesses) {
  1214. // Compilation does not preprocess and we are not compiling an
  1215. // already-preprocessed source. Make compilation depend on the scan
  1216. // results to honor implicit dependencies discovered during scanning
  1217. // (such as Fortran INCLUDE directives).
  1218. objBuild.ImplicitDeps.emplace_back(ddiFileName);
  1219. }
  1220. }
  1221. // Scanning always provides a depfile for preprocessor dependencies. This
  1222. // variable is unused in `msvc`-deptype scanners.
  1223. tg->AddDepfileBinding(scanBuild.Variables,
  1224. cmStrCat(scanBuild.Outputs.front(), ".d"));
  1225. if (compilePP) {
  1226. // The actual compilation does not need a depfile because it
  1227. // depends on the already-preprocessed source.
  1228. tg->RemoveDepfileBinding(vars);
  1229. }
  1230. return scanBuild;
  1231. }
  1232. }
  1233. void cmNinjaTargetGenerator::WriteObjectBuildStatement(
  1234. cmSourceFile const* source, const std::string& config,
  1235. const std::string& fileConfig, bool firstForConfig)
  1236. {
  1237. std::string const language = source->GetLanguage();
  1238. std::string const sourceFilePath = this->GetCompiledSourceNinjaPath(source);
  1239. std::string const objectDir = this->ConvertToNinjaPath(
  1240. cmStrCat(this->GeneratorTarget->GetSupportDirectory(),
  1241. this->GetGlobalGenerator()->ConfigDirectory(config)));
  1242. std::string const objectFileName =
  1243. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1244. std::string const objectFileDir =
  1245. cmSystemTools::GetFilenamePath(objectFileName);
  1246. std::string cmakeVarLang = cmStrCat("CMAKE_", language);
  1247. // build response file name
  1248. std::string cmakeLinkVar = cmStrCat(cmakeVarLang, "_RESPONSE_FILE_FLAG");
  1249. cmValue flag = this->GetMakefile()->GetDefinition(cmakeLinkVar);
  1250. bool const lang_supports_response =
  1251. !(language == "RC" || (language == "CUDA" && !flag));
  1252. int const commandLineLengthLimit =
  1253. ((lang_supports_response && this->ForceResponseFile())) ? -1 : 0;
  1254. cmValue pchExtension =
  1255. this->GetMakefile()->GetDefinition("CMAKE_PCH_EXTENSION");
  1256. bool const isPch = cmHasSuffix(objectFileName, pchExtension);
  1257. bool const needDyndep = !isPch &&
  1258. this->GeneratorTarget->NeedDyndepForSource(language, config, source);
  1259. WithScanning withScanning =
  1260. needDyndep ? WithScanning::Yes : WithScanning::No;
  1261. cmNinjaBuild objBuild(
  1262. this->LanguageCompilerRule(language, config, withScanning));
  1263. cmNinjaVars& vars = objBuild.Variables;
  1264. vars["FLAGS"] =
  1265. this->ComputeFlagsForObject(source, language, config, objectFileName);
  1266. vars["DEFINES"] = this->ComputeDefines(source, language, config);
  1267. vars["INCLUDES"] = this->ComputeIncludes(source, language, config);
  1268. auto compilerLauncher = this->GetCompilerLauncher(language, config);
  1269. cmValue const skipCodeCheck = source->GetProperty("SKIP_LINTING");
  1270. if (!skipCodeCheck.IsOn()) {
  1271. auto const cmakeCmd = this->GetLocalGenerator()->ConvertToOutputFormat(
  1272. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  1273. vars["CODE_CHECK"] =
  1274. this->GenerateCodeCheckRules(*source, compilerLauncher, cmakeCmd, config,
  1275. [this](const std::string& path) {
  1276. return this->ConvertToNinjaPath(path);
  1277. });
  1278. }
  1279. // If compiler launcher was specified and not consumed above, it
  1280. // goes to the beginning of the command line.
  1281. if (!compilerLauncher.empty()) {
  1282. cmList args{ compilerLauncher, cmList::EmptyElements::Yes };
  1283. if (!args.empty()) {
  1284. args[0] = this->LocalGenerator->ConvertToOutputFormat(
  1285. args[0], cmOutputConverter::SHELL);
  1286. for (std::string& i : cmMakeRange(args.begin() + 1, args.end())) {
  1287. i = this->LocalGenerator->EscapeForShell(i);
  1288. }
  1289. vars["LAUNCHER"] = args.join(" ") + " ";
  1290. }
  1291. }
  1292. if (this->GetMakefile()->GetSafeDefinition(
  1293. cmStrCat("CMAKE_", language, "_DEPFILE_FORMAT")) != "msvc"_s) {
  1294. bool replaceExt = false;
  1295. if (!language.empty()) {
  1296. std::string repVar =
  1297. cmStrCat("CMAKE_", language, "_DEPFILE_EXTENSION_REPLACE");
  1298. replaceExt = this->Makefile->IsOn(repVar);
  1299. }
  1300. this->AddDepfileBinding(
  1301. vars,
  1302. replaceExt ? cmStrCat(objectFileDir, '/',
  1303. cmSystemTools::GetFilenameWithoutLastExtension(
  1304. objectFileName),
  1305. ".d")
  1306. : cmStrCat(objectFileName, ".d"));
  1307. }
  1308. this->SetMsvcTargetPdbVariable(vars, config);
  1309. if (firstForConfig) {
  1310. this->ExportObjectCompileCommand(
  1311. language, sourceFilePath, objectDir, objectFileName, objectFileDir,
  1312. vars["FLAGS"], vars["DEFINES"], vars["INCLUDES"],
  1313. vars["TARGET_COMPILE_PDB"], vars["TARGET_PDB"], config, withScanning);
  1314. }
  1315. objBuild.Outputs.push_back(objectFileName);
  1316. if (firstForConfig && !isPch) {
  1317. // Add this object to the list of object files.
  1318. this->Configs[config].Objects.push_back(objectFileName);
  1319. }
  1320. objBuild.ExplicitDeps.push_back(sourceFilePath);
  1321. // Add precompile headers dependencies
  1322. std::vector<std::string> depList;
  1323. std::vector<std::string> pchArchs =
  1324. this->GeneratorTarget->GetPchArchs(config, language);
  1325. std::unordered_set<std::string> pchSources;
  1326. for (const std::string& arch : pchArchs) {
  1327. const std::string pchSource =
  1328. this->GeneratorTarget->GetPchSource(config, language, arch);
  1329. if (!pchSource.empty()) {
  1330. pchSources.insert(pchSource);
  1331. }
  1332. }
  1333. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  1334. for (const std::string& arch : pchArchs) {
  1335. depList.push_back(
  1336. this->GeneratorTarget->GetPchHeader(config, language, arch));
  1337. if (pchSources.find(source->GetFullPath()) == pchSources.end()) {
  1338. depList.push_back(
  1339. this->GeneratorTarget->GetPchFile(config, language, arch));
  1340. }
  1341. }
  1342. }
  1343. if (cmValue objectDeps = source->GetProperty("OBJECT_DEPENDS")) {
  1344. cmList objDepList{ *objectDeps };
  1345. std::copy(objDepList.begin(), objDepList.end(),
  1346. std::back_inserter(depList));
  1347. }
  1348. if (!depList.empty()) {
  1349. for (std::string& odi : depList) {
  1350. if (cmSystemTools::FileIsFullPath(odi)) {
  1351. odi = cmSystemTools::CollapseFullPath(odi);
  1352. }
  1353. }
  1354. std::transform(depList.begin(), depList.end(),
  1355. std::back_inserter(objBuild.ImplicitDeps),
  1356. this->MapToNinjaPath());
  1357. }
  1358. if (this->HasPrivateGeneratedSources) {
  1359. objBuild.OrderOnlyDeps.push_back(
  1360. this->OrderDependsTargetForTargetPrivate(config));
  1361. } else {
  1362. objBuild.OrderOnlyDeps.push_back(
  1363. this->OrderDependsTargetForTarget(config));
  1364. }
  1365. // If the source file is GENERATED and does not have a custom command
  1366. // (either attached to this source file or another one), assume that one of
  1367. // the target dependencies, OBJECT_DEPENDS or header file custom commands
  1368. // will rebuild the file.
  1369. if (source->GetIsGenerated() &&
  1370. !source->GetPropertyAsBool("__CMAKE_GENERATED_BY_CMAKE") &&
  1371. !source->GetCustomCommand() &&
  1372. !this->GetGlobalGenerator()->HasCustomCommandOutput(sourceFilePath)) {
  1373. this->GetGlobalGenerator()->AddAssumedSourceDependencies(
  1374. sourceFilePath, objBuild.OrderOnlyDeps);
  1375. }
  1376. // For some cases we scan to dynamically discover dependencies.
  1377. bool const compilationPreprocesses =
  1378. !this->NeedExplicitPreprocessing(language);
  1379. std::string modmapFormat;
  1380. if (needDyndep) {
  1381. std::string const modmapFormatVar =
  1382. cmStrCat("CMAKE_", language, "_MODULE_MAP_FORMAT");
  1383. modmapFormat = this->Makefile->GetSafeDefinition(modmapFormatVar);
  1384. }
  1385. if (needDyndep) {
  1386. // If source/target has preprocessing turned off, we still need to
  1387. // generate an explicit dependency step
  1388. const auto srcpp = source->GetSafeProperty("Fortran_PREPROCESS");
  1389. cmOutputConverter::FortranPreprocess preprocess =
  1390. cmOutputConverter::GetFortranPreprocess(srcpp);
  1391. if (preprocess == cmOutputConverter::FortranPreprocess::Unset) {
  1392. const auto& tgtpp =
  1393. this->GeneratorTarget->GetSafeProperty("Fortran_PREPROCESS");
  1394. preprocess = cmOutputConverter::GetFortranPreprocess(tgtpp);
  1395. }
  1396. bool const compilePP = !compilationPreprocesses &&
  1397. (preprocess != cmOutputConverter::FortranPreprocess::NotNeeded);
  1398. bool const compilePPWithDefines =
  1399. compilePP && this->CompileWithDefines(language);
  1400. std::string scanRuleName;
  1401. std::string ppFileName;
  1402. if (compilePP) {
  1403. scanRuleName = this->LanguagePreprocessAndScanRule(language, config);
  1404. ppFileName = this->ConvertToNinjaPath(
  1405. this->GetPreprocessedFilePath(source, config));
  1406. } else {
  1407. scanRuleName = this->LanguageScanRule(language, config);
  1408. ppFileName = cmStrCat(objectFileName, ".ddi.i");
  1409. }
  1410. cmNinjaBuild ppBuild = GetScanBuildStatement(
  1411. scanRuleName, ppFileName, compilePP, compilePPWithDefines,
  1412. compilationPreprocesses, objBuild, vars, objectFileName, this);
  1413. if (compilePP) {
  1414. // In case compilation requires flags that are incompatible with
  1415. // preprocessing, include them here.
  1416. std::string const& postFlag = this->Makefile->GetSafeDefinition(
  1417. cmStrCat("CMAKE_", language, "_POSTPROCESS_FLAG"));
  1418. this->LocalGenerator->AppendFlags(vars["FLAGS"], postFlag);
  1419. // Prepend source file's original directory as an include directory
  1420. // so e.g. Fortran INCLUDE statements can look for files in it.
  1421. std::vector<std::string> sourceDirectory;
  1422. sourceDirectory.push_back(
  1423. cmSystemTools::GetParentDirectory(source->GetFullPath()));
  1424. std::string sourceDirectoryFlag = this->LocalGenerator->GetIncludeFlags(
  1425. sourceDirectory, this->GeneratorTarget, language, config, false);
  1426. vars["INCLUDES"] = cmStrCat(sourceDirectoryFlag, ' ', vars["INCLUDES"]);
  1427. }
  1428. ScanningFiles scanningFiles;
  1429. if (firstForConfig) {
  1430. scanningFiles.ScanningOutput = cmStrCat(objectFileName, ".ddi");
  1431. }
  1432. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1433. ppBuild.Variables);
  1434. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1435. ppBuild, commandLineLengthLimit);
  1436. std::string const dyndep = this->GetDyndepFilePath(language, config);
  1437. objBuild.OrderOnlyDeps.push_back(dyndep);
  1438. vars["dyndep"] = dyndep;
  1439. if (!modmapFormat.empty()) {
  1440. // XXX(modmap): If changing this path construction, change
  1441. // `cmGlobalNinjaGenerator::WriteDyndep` and
  1442. // `cmNinjaTargetGenerator::ExportObjectCompileCommand` to expect the
  1443. // corresponding file path.
  1444. std::string ddModmapFile = cmStrCat(objectFileName, ".modmap");
  1445. vars["DYNDEP_MODULE_MAP_FILE"] = ddModmapFile;
  1446. objBuild.ImplicitDeps.push_back(ddModmapFile);
  1447. scanningFiles.ModuleMapFile = std::move(ddModmapFile);
  1448. }
  1449. if (!scanningFiles.IsEmpty()) {
  1450. this->Configs[config].ScanningInfo[language].emplace_back(scanningFiles);
  1451. }
  1452. }
  1453. this->EnsureParentDirectoryExists(objectFileName);
  1454. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1455. objectDir, cmOutputConverter::SHELL);
  1456. vars["OBJECT_FILE_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1457. objectFileDir, cmOutputConverter::SHELL);
  1458. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1459. vars);
  1460. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  1461. auto pchIt = pchSources.find(source->GetFullPath());
  1462. if (pchIt != pchSources.end()) {
  1463. this->addPoolNinjaVariable("JOB_POOL_PRECOMPILE_HEADER",
  1464. this->GetGeneratorTarget(), vars);
  1465. }
  1466. }
  1467. objBuild.RspFile = cmStrCat(objectFileName, ".rsp");
  1468. if (language == "ISPC") {
  1469. std::string const& objectName =
  1470. this->GeneratorTarget->GetObjectName(source);
  1471. std::string ispcSource =
  1472. cmSystemTools::GetFilenameWithoutLastExtension(objectName);
  1473. ispcSource = cmSystemTools::GetFilenameWithoutLastExtension(ispcSource);
  1474. cmValue ispcSuffixProp =
  1475. this->GeneratorTarget->GetProperty("ISPC_HEADER_SUFFIX");
  1476. assert(ispcSuffixProp);
  1477. std::string ispcHeaderDirectory =
  1478. this->GeneratorTarget->GetObjectDirectory(config);
  1479. if (cmValue prop =
  1480. this->GeneratorTarget->GetProperty("ISPC_HEADER_DIRECTORY")) {
  1481. ispcHeaderDirectory =
  1482. cmStrCat(this->LocalGenerator->GetBinaryDirectory(), '/', *prop);
  1483. }
  1484. std::string ispcHeader =
  1485. cmStrCat(ispcHeaderDirectory, '/', ispcSource, *ispcSuffixProp);
  1486. ispcHeader = this->ConvertToNinjaPath(ispcHeader);
  1487. // Make sure ninja knows what command generates the header
  1488. objBuild.ImplicitOuts.push_back(ispcHeader);
  1489. // Make sure ninja knows how to clean the generated header
  1490. this->GetGlobalGenerator()->AddAdditionalCleanFile(ispcHeader, config);
  1491. auto ispcSuffixes =
  1492. detail::ComputeISPCObjectSuffixes(this->GeneratorTarget);
  1493. if (ispcSuffixes.size() > 1) {
  1494. std::string rootObjectDir =
  1495. this->GeneratorTarget->GetObjectDirectory(config);
  1496. auto ispcSideEfffectObjects = detail::ComputeISPCExtraObjects(
  1497. objectName, rootObjectDir, ispcSuffixes);
  1498. for (auto sideEffect : ispcSideEfffectObjects) {
  1499. sideEffect = this->ConvertToNinjaPath(sideEffect);
  1500. objBuild.ImplicitOuts.emplace_back(sideEffect);
  1501. this->GetGlobalGenerator()->AddAdditionalCleanFile(sideEffect, config);
  1502. }
  1503. }
  1504. vars["ISPC_HEADER_FILE"] =
  1505. this->GetLocalGenerator()->ConvertToOutputFormat(
  1506. ispcHeader, cmOutputConverter::SHELL);
  1507. } else {
  1508. auto headers = this->GeneratorTarget->GetGeneratedISPCHeaders(config);
  1509. if (!headers.empty()) {
  1510. std::transform(headers.begin(), headers.end(), headers.begin(),
  1511. this->MapToNinjaPath());
  1512. objBuild.OrderOnlyDeps.insert(objBuild.OrderOnlyDeps.end(),
  1513. headers.begin(), headers.end());
  1514. }
  1515. }
  1516. if (language == "Swift") {
  1517. this->EmitSwiftDependencyInfo(source, config);
  1518. } else {
  1519. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1520. objBuild, commandLineLengthLimit);
  1521. }
  1522. if (cmValue objectOutputs = source->GetProperty("OBJECT_OUTPUTS")) {
  1523. std::string evaluatedObjectOutputs = cmGeneratorExpression::Evaluate(
  1524. *objectOutputs, this->LocalGenerator, config);
  1525. if (!evaluatedObjectOutputs.empty()) {
  1526. cmNinjaBuild build("phony");
  1527. build.Comment = "Additional output files.";
  1528. build.Outputs = cmList{ evaluatedObjectOutputs }.data();
  1529. std::transform(build.Outputs.begin(), build.Outputs.end(),
  1530. build.Outputs.begin(), this->MapToNinjaPath());
  1531. build.ExplicitDeps = objBuild.Outputs;
  1532. this->GetGlobalGenerator()->WriteBuild(
  1533. this->GetImplFileStream(fileConfig), build);
  1534. }
  1535. }
  1536. }
  1537. void cmNinjaTargetGenerator::WriteCxxModuleBmiBuildStatement(
  1538. cmSourceFile const* source, const std::string& config,
  1539. const std::string& fileConfig, bool firstForConfig)
  1540. {
  1541. std::string const language = source->GetLanguage();
  1542. if (language != "CXX"_s) {
  1543. this->GetMakefile()->IssueMessage(
  1544. MessageType::FATAL_ERROR,
  1545. cmStrCat("Source file '", source->GetFullPath(), "' of target '",
  1546. this->GetTargetName(), "' is a '", language,
  1547. "' source but must be 'CXX' in order to have a BMI build "
  1548. "statement generated."));
  1549. return;
  1550. }
  1551. std::string const sourceFilePath = this->GetCompiledSourceNinjaPath(source);
  1552. std::string const bmiDir = this->ConvertToNinjaPath(
  1553. cmStrCat(this->GeneratorTarget->GetSupportDirectory(),
  1554. this->GetGlobalGenerator()->ConfigDirectory(config)));
  1555. std::string const bmiFileName =
  1556. this->ConvertToNinjaPath(this->GetBmiFilePath(source, config));
  1557. std::string const bmiFileDir = cmSystemTools::GetFilenamePath(bmiFileName);
  1558. int const commandLineLengthLimit = this->ForceResponseFile() ? -1 : 0;
  1559. cmNinjaBuild bmiBuild(
  1560. this->LanguageCompilerRule(language, config, WithScanning::Yes));
  1561. cmNinjaVars& vars = bmiBuild.Variables;
  1562. vars["FLAGS"] =
  1563. this->ComputeFlagsForObject(source, language, config, bmiFileName);
  1564. vars["DEFINES"] = this->ComputeDefines(source, language, config);
  1565. vars["INCLUDES"] = this->ComputeIncludes(source, language, config);
  1566. if (this->GetMakefile()->GetSafeDefinition(
  1567. cmStrCat("CMAKE_", language, "_DEPFILE_FORMAT")) != "msvc"_s) {
  1568. bool replaceExt = false;
  1569. if (!language.empty()) {
  1570. std::string repVar =
  1571. cmStrCat("CMAKE_", language, "_DEPFILE_EXTENSION_REPLACE");
  1572. replaceExt = this->Makefile->IsOn(repVar);
  1573. }
  1574. this->AddDepfileBinding(
  1575. vars,
  1576. replaceExt
  1577. ? cmStrCat(bmiFileDir, '/',
  1578. cmSystemTools::GetFilenameWithoutLastExtension(bmiFileName),
  1579. ".d")
  1580. : cmStrCat(bmiFileName, ".d"));
  1581. }
  1582. std::string d =
  1583. this->GeneratorTarget->GetClangTidyExportFixesDirectory(language);
  1584. if (!d.empty()) {
  1585. this->GlobalCommonGenerator->AddClangTidyExportFixesDir(d);
  1586. std::string fixesFile =
  1587. this->GetClangTidyReplacementsFilePath(d, *source, config);
  1588. this->GlobalCommonGenerator->AddClangTidyExportFixesFile(fixesFile);
  1589. cmSystemTools::MakeDirectory(cmSystemTools::GetFilenamePath(fixesFile));
  1590. fixesFile = this->ConvertToNinjaPath(fixesFile);
  1591. vars["CLANG_TIDY_EXPORT_FIXES"] = fixesFile;
  1592. }
  1593. this->SetMsvcTargetPdbVariable(vars, config);
  1594. if (firstForConfig) {
  1595. this->ExportObjectCompileCommand(
  1596. language, sourceFilePath, bmiDir, bmiFileName, bmiFileDir, vars["FLAGS"],
  1597. vars["DEFINES"], vars["INCLUDES"], vars["TARGET_COMPILE_PDB"],
  1598. vars["TARGET_PDB"], config, WithScanning::Yes);
  1599. }
  1600. bmiBuild.Outputs.push_back(bmiFileName);
  1601. bmiBuild.ExplicitDeps.push_back(sourceFilePath);
  1602. std::vector<std::string> depList;
  1603. bmiBuild.OrderOnlyDeps.push_back(this->OrderDependsTargetForTarget(config));
  1604. // For some cases we scan to dynamically discover dependencies.
  1605. std::string modmapFormat;
  1606. if (true) {
  1607. std::string const modmapFormatVar =
  1608. cmStrCat("CMAKE_", language, "_MODULE_MAP_FORMAT");
  1609. modmapFormat = this->Makefile->GetSafeDefinition(modmapFormatVar);
  1610. }
  1611. {
  1612. bool const compilePPWithDefines = this->CompileWithDefines(language);
  1613. std::string scanRuleName = this->LanguageScanRule(language, config);
  1614. std::string ppFileName = cmStrCat(bmiFileName, ".ddi.i");
  1615. cmNinjaBuild ppBuild = GetScanBuildStatement(
  1616. scanRuleName, ppFileName, false, compilePPWithDefines, true, bmiBuild,
  1617. vars, bmiFileName, this);
  1618. ScanningFiles scanningFiles;
  1619. if (firstForConfig) {
  1620. scanningFiles.ScanningOutput = cmStrCat(bmiFileName, ".ddi");
  1621. }
  1622. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1623. ppBuild.Variables);
  1624. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1625. ppBuild, commandLineLengthLimit);
  1626. std::string const dyndep = this->GetDyndepFilePath(language, config);
  1627. bmiBuild.OrderOnlyDeps.push_back(dyndep);
  1628. vars["dyndep"] = dyndep;
  1629. if (!modmapFormat.empty()) {
  1630. std::string ddModmapFile = cmStrCat(bmiFileName, ".modmap");
  1631. vars["DYNDEP_MODULE_MAP_FILE"] = ddModmapFile;
  1632. scanningFiles.ModuleMapFile = std::move(ddModmapFile);
  1633. }
  1634. if (!scanningFiles.IsEmpty()) {
  1635. this->Configs[config].ScanningInfo[language].emplace_back(scanningFiles);
  1636. }
  1637. }
  1638. this->EnsureParentDirectoryExists(bmiFileName);
  1639. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1640. bmiDir, cmOutputConverter::SHELL);
  1641. vars["OBJECT_FILE_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1642. bmiFileDir, cmOutputConverter::SHELL);
  1643. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1644. vars);
  1645. bmiBuild.RspFile = cmStrCat(bmiFileName, ".rsp");
  1646. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1647. bmiBuild, commandLineLengthLimit);
  1648. }
  1649. void cmNinjaTargetGenerator::WriteSwiftObjectBuildStatement(
  1650. std::vector<cmSourceFile const*> const& sources, std::string const& config,
  1651. std::string const& fileConfig, bool firstForConfig)
  1652. {
  1653. // Swift sources are compiled as a module, not individually like with C/C++.
  1654. // Flags, header search paths, and definitions are passed to the entire
  1655. // module build, but we still need to emit compile-commands for each source
  1656. // file in order to support CMAKE_EXPORT_COMPILE_COMMANDS.
  1657. // In whole-module mode, with a single thread, the Swift compiler will
  1658. // only emit a single object file, but if more than one thread is specified,
  1659. // or building in other modes, the compiler will emit multiple object files.
  1660. // When building a single-output, we do not provide an output-file-map (OFM),
  1661. // and instead pass `-o` to tell the compiler where to write the object.
  1662. // When building multiple outputs, we provide an OFM to tell the compiler
  1663. // where to put each object.
  1664. //
  1665. //
  1666. // Per-Target (module):
  1667. // - Flags
  1668. // - Definitions
  1669. // - Include paths
  1670. // - (single-output) output object filename
  1671. // - Swiftmodule
  1672. //
  1673. // Per-File:
  1674. // - compile-command
  1675. // - (multi-output) OFM data
  1676. // - (multi-output) output object filename
  1677. //
  1678. // Note: Due to the differences in the build models, we are only able to
  1679. // build the object build-graph if we know what mode the target is built in.
  1680. // For that, we need the "NEW" behavior for CMP0157. Otherwise, we have to
  1681. // fall back on the old "linker" build. Otherwise, this should be
  1682. // indistinguishable from the old behavior.
  1683. if (sources.empty()) {
  1684. return;
  1685. }
  1686. cmSwiftCompileMode compileMode;
  1687. if (cm::optional<cmSwiftCompileMode> optionalCompileMode =
  1688. this->LocalGenerator->GetSwiftCompileMode(this->GeneratorTarget,
  1689. config)) {
  1690. compileMode = *optionalCompileMode;
  1691. } else {
  1692. // CMP0157 is not NEW, bailing early!
  1693. return;
  1694. }
  1695. std::string const language = "Swift";
  1696. std::string const objectDir = this->ConvertToNinjaPath(
  1697. cmStrCat(this->GeneratorTarget->GetSupportDirectory(),
  1698. this->GetGlobalGenerator()->ConfigDirectory(config)));
  1699. cmGeneratorTarget const& target = *this->GeneratorTarget;
  1700. cmNinjaBuild objBuild(
  1701. this->LanguageCompilerRule(language, config, WithScanning::No));
  1702. cmNinjaVars& vars = objBuild.Variables;
  1703. // The swift toolchain leaves outputs untouched if there are no meaningful
  1704. // changes to input files (e.g. addition of a comment).
  1705. vars.emplace("restat", "1");
  1706. std::string const moduleName = target.GetSwiftModuleName();
  1707. std::string const moduleFilepath =
  1708. this->ConvertToNinjaPath(target.GetSwiftModulePath(config));
  1709. vars.emplace("description",
  1710. cmStrCat("Building Swift Module '", moduleName, "' with ",
  1711. sources.size(),
  1712. sources.size() == 1 ? " source" : " sources"));
  1713. bool const isSingleOutput = [this, compileMode]() -> bool {
  1714. bool isMultiThread = false;
  1715. if (cmValue numThreadStr =
  1716. this->GetMakefile()->GetDefinition("CMAKE_Swift_NUM_THREADS")) {
  1717. unsigned long numThreads;
  1718. cmStrToULong(*numThreadStr, &numThreads);
  1719. // numThreads == 1 is multi-threaded according to swiftc
  1720. isMultiThread = numThreads > 0;
  1721. }
  1722. return !isMultiThread && compileMode == cmSwiftCompileMode::Wholemodule;
  1723. }();
  1724. // Without `-emit-library` or `-emit-executable`, targets with a single
  1725. // source file parse as a Swift script instead of like normal source. For
  1726. // non-executable targets, append this to ensure that they are parsed like a
  1727. // normal source.
  1728. if (target.GetType() != cmStateEnums::EXECUTABLE) {
  1729. this->LocalGenerator->AppendFlags(vars["FLAGS"], "-parse-as-library");
  1730. }
  1731. if (target.GetType() == cmStateEnums::STATIC_LIBRARY) {
  1732. this->LocalGenerator->AppendFlags(vars["FLAGS"], "-static");
  1733. }
  1734. // Does this swift target emit a module file for importing into other
  1735. // targets?
  1736. auto isImportableTarget = [](cmGeneratorTarget const& tgt) -> bool {
  1737. // Everything except for executables that don't export anything should emit
  1738. // some way to import them.
  1739. if (tgt.GetType() == cmStateEnums::EXECUTABLE) {
  1740. return tgt.IsExecutableWithExports();
  1741. }
  1742. return true;
  1743. };
  1744. // Swift modules only make sense to emit from things that can be imported.
  1745. // Executables that don't export symbols can't be imported, so don't try to
  1746. // emit a swiftmodule for them. It will break.
  1747. if (isImportableTarget(target)) {
  1748. std::string const emitModuleFlag = "-emit-module";
  1749. std::string const modulePathFlag = "-emit-module-path";
  1750. this->LocalGenerator->AppendFlags(
  1751. vars["FLAGS"],
  1752. { emitModuleFlag, modulePathFlag,
  1753. this->LocalGenerator->ConvertToOutputFormat(
  1754. moduleFilepath, cmOutputConverter::SHELL) });
  1755. objBuild.Outputs.push_back(moduleFilepath);
  1756. }
  1757. this->LocalGenerator->AppendFlags(vars["FLAGS"],
  1758. cmStrCat("-module-name ", moduleName));
  1759. if (target.GetType() != cmStateEnums::EXECUTABLE) {
  1760. std::string const libraryLinkNameFlag = "-module-link-name";
  1761. std::string const libraryLinkName =
  1762. this->GetGeneratorTarget()->GetLibraryNames(config).Base;
  1763. this->LocalGenerator->AppendFlags(
  1764. vars["FLAGS"], cmStrCat(libraryLinkNameFlag, ' ', libraryLinkName));
  1765. }
  1766. this->LocalGenerator->AppendFlags(vars["FLAGS"],
  1767. this->GetFlags(language, config));
  1768. vars["DEFINES"] = this->GetDefines(language, config);
  1769. vars["INCLUDES"] = this->GetIncludes(language, config);
  1770. // target-level object filename
  1771. std::string const targetObjectFilename = this->ConvertToNinjaPath(cmStrCat(
  1772. objectDir, '/', moduleName,
  1773. this->GetGlobalGenerator()->GetLanguageOutputExtension(language)));
  1774. objBuild.RspFile = cmStrCat(targetObjectFilename, ".swift.rsp");
  1775. if (isSingleOutput) {
  1776. this->LocalGenerator->AppendFlags(vars["FLAGS"],
  1777. cmStrCat("-o ", targetObjectFilename));
  1778. objBuild.Outputs.push_back(targetObjectFilename);
  1779. this->Configs[config].Objects.push_back(targetObjectFilename);
  1780. }
  1781. for (cmSourceFile const* sf : sources) {
  1782. // Add dependency to object build on each source file
  1783. std::string const sourceFilePath = this->GetCompiledSourceNinjaPath(sf);
  1784. objBuild.ExplicitDeps.push_back(sourceFilePath);
  1785. if (!isSingleOutput) {
  1786. // Object outputs
  1787. std::string const objectFilepath =
  1788. this->ConvertToNinjaPath(this->GetObjectFilePath(sf, config));
  1789. this->EnsureParentDirectoryExists(objectFilepath);
  1790. objBuild.Outputs.push_back(objectFilepath);
  1791. this->Configs[config].Objects.push_back(objectFilepath);
  1792. // Add OFM data
  1793. this->EmitSwiftDependencyInfo(sf, config);
  1794. }
  1795. }
  1796. if (!isSingleOutput) {
  1797. this->GenerateSwiftOutputFileMap(config, vars["FLAGS"]);
  1798. }
  1799. if (firstForConfig) {
  1800. this->ExportSwiftObjectCompileCommand(
  1801. sources, targetObjectFilename, vars["FLAGS"], vars["DEFINES"],
  1802. vars["INCLUDES"], config, isSingleOutput);
  1803. }
  1804. for (cmTargetDepend const& dep :
  1805. this->GetGlobalGenerator()->GetTargetDirectDepends(&target)) {
  1806. if (!dep->IsLanguageUsed("Swift", config)) {
  1807. continue;
  1808. }
  1809. // If the dependency emits a swiftmodule, add a dependency edge on that
  1810. // swiftmodule to the ninja build graph.
  1811. if (isImportableTarget(*dep)) {
  1812. std::string const depModuleFilepath =
  1813. this->ConvertToNinjaPath(dep->GetSwiftModulePath(config));
  1814. objBuild.ImplicitDeps.push_back(depModuleFilepath);
  1815. }
  1816. }
  1817. objBuild.OrderOnlyDeps.push_back(this->OrderDependsTargetForTarget(config));
  1818. // Write object build
  1819. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1820. objBuild,
  1821. this->ForceResponseFile() ? -1 : 0);
  1822. }
  1823. void cmNinjaTargetGenerator::WriteTargetDependInfo(std::string const& lang,
  1824. const std::string& config)
  1825. {
  1826. Json::Value tdi(Json::objectValue);
  1827. tdi["language"] = lang;
  1828. tdi["compiler-id"] = this->Makefile->GetSafeDefinition(
  1829. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  1830. tdi["compiler-simulate-id"] = this->Makefile->GetSafeDefinition(
  1831. cmStrCat("CMAKE_", lang, "_SIMULATE_ID"));
  1832. tdi["compiler-frontend-variant"] = this->Makefile->GetSafeDefinition(
  1833. cmStrCat("CMAKE_", lang, "_COMPILER_FRONTEND_VARIANT"));
  1834. std::string mod_dir;
  1835. if (lang == "Fortran") {
  1836. mod_dir = this->GeneratorTarget->GetFortranModuleDirectory(
  1837. this->Makefile->GetHomeOutputDirectory());
  1838. } else if (lang == "CXX") {
  1839. mod_dir = this->GetGlobalGenerator()->ExpandCFGIntDir(
  1840. cmSystemTools::CollapseFullPath(this->GeneratorTarget->ObjectDirectory),
  1841. config);
  1842. }
  1843. if (mod_dir.empty()) {
  1844. mod_dir = this->Makefile->GetCurrentBinaryDirectory();
  1845. }
  1846. tdi["module-dir"] = mod_dir;
  1847. if (lang == "Fortran") {
  1848. tdi["submodule-sep"] =
  1849. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
  1850. tdi["submodule-ext"] =
  1851. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
  1852. } else if (lang == "CXX") {
  1853. // No extra information necessary.
  1854. }
  1855. tdi["dir-cur-bld"] = this->Makefile->GetCurrentBinaryDirectory();
  1856. tdi["dir-cur-src"] = this->Makefile->GetCurrentSourceDirectory();
  1857. tdi["dir-top-bld"] = this->Makefile->GetHomeOutputDirectory();
  1858. tdi["dir-top-src"] = this->Makefile->GetHomeDirectory();
  1859. Json::Value& tdi_include_dirs = tdi["include-dirs"] = Json::arrayValue;
  1860. std::vector<std::string> includes;
  1861. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  1862. lang, config);
  1863. for (std::string const& i : includes) {
  1864. // Convert the include directories the same way we do for -I flags.
  1865. // See upstream ninja issue 1251.
  1866. tdi_include_dirs.append(this->ConvertToNinjaPath(i));
  1867. }
  1868. Json::Value& tdi_linked_target_dirs = tdi["linked-target-dirs"] =
  1869. Json::arrayValue;
  1870. auto const linked_directories =
  1871. this->GetLinkedTargetDirectories(lang, config);
  1872. for (std::string const& l : linked_directories.Direct) {
  1873. tdi_linked_target_dirs.append(l);
  1874. }
  1875. Json::Value& tdi_forward_modules_from_target_dirs =
  1876. tdi["forward-modules-from-target-dirs"] = Json::arrayValue;
  1877. for (std::string const& l : linked_directories.Forward) {
  1878. tdi_forward_modules_from_target_dirs.append(l);
  1879. }
  1880. cmDyndepGeneratorCallbacks cb;
  1881. cb.ObjectFilePath = [this](cmSourceFile const* sf, std::string const& cnf) {
  1882. return this->GetObjectFilePath(sf, cnf);
  1883. };
  1884. cb.BmiFilePath = [this](cmSourceFile const* sf, std::string const& cnf) {
  1885. return this->GetBmiFilePath(sf, cnf);
  1886. };
  1887. #if !defined(CMAKE_BOOTSTRAP)
  1888. cmDyndepCollation::AddCollationInformation(tdi, this->GeneratorTarget,
  1889. config, cb);
  1890. #endif
  1891. std::string const tdin = this->GetTargetDependInfoPath(lang, config);
  1892. cmGeneratedFileStream tdif(tdin);
  1893. tdif << tdi;
  1894. }
  1895. void cmNinjaTargetGenerator::EmitSwiftDependencyInfo(
  1896. cmSourceFile const* source, const std::string& config)
  1897. {
  1898. std::string const sourceFilePath = this->GetCompiledSourceNinjaPath(source);
  1899. std::string const objectFilePath =
  1900. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1901. std::string const swiftDepsPath = [source, objectFilePath]() -> std::string {
  1902. if (cmValue name = source->GetProperty("Swift_DEPENDENCIES_FILE")) {
  1903. return *name;
  1904. }
  1905. return cmStrCat(objectFilePath, ".swiftdeps");
  1906. }();
  1907. std::string const swiftDiaPath = [source, objectFilePath]() -> std::string {
  1908. if (cmValue name = source->GetProperty("Swift_DIAGNOSTICS_FILE")) {
  1909. return *name;
  1910. }
  1911. return cmStrCat(objectFilePath, ".dia");
  1912. }();
  1913. std::string const makeDepsPath = [this, source, config]() -> std::string {
  1914. cmLocalNinjaGenerator const* local = this->GetLocalGenerator();
  1915. std::string const objectFileName =
  1916. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1917. std::string const objectFileDir =
  1918. cmSystemTools::GetFilenamePath(objectFileName);
  1919. if (this->Makefile->IsOn("CMAKE_Swift_DEPFLE_EXTNSION_REPLACE")) {
  1920. std::string dependFileName = cmStrCat(
  1921. cmSystemTools::GetFilenameWithoutLastExtension(objectFileName), ".d");
  1922. return local->ConvertToOutputFormat(
  1923. cmStrCat(objectFileDir, '/', dependFileName),
  1924. cmOutputConverter::SHELL);
  1925. }
  1926. return local->ConvertToOutputFormat(cmStrCat(objectFileName, ".d"),
  1927. cmOutputConverter::SHELL);
  1928. }();
  1929. // build the source file mapping
  1930. // https://github.com/apple/swift/blob/master/docs/Driver.md#output-file-maps
  1931. Json::Value entry = Json::Value(Json::objectValue);
  1932. entry["object"] = objectFilePath;
  1933. entry["dependencies"] = makeDepsPath;
  1934. entry["swift-dependencies"] = swiftDepsPath;
  1935. entry["diagnostics"] = swiftDiaPath;
  1936. this->Configs[config].SwiftOutputMap[sourceFilePath] = entry;
  1937. }
  1938. void cmNinjaTargetGenerator::ExportObjectCompileCommand(
  1939. std::string const& language, std::string const& sourceFileName,
  1940. std::string const& objectDir, std::string const& objectFileName,
  1941. std::string const& objectFileDir, std::string const& flags,
  1942. std::string const& defines, std::string const& includes,
  1943. std::string const& targetCompilePdb, std::string const& targetPdb,
  1944. std::string const& outputConfig, WithScanning withScanning)
  1945. {
  1946. if (!this->GeneratorTarget->GetPropertyAsBool("EXPORT_COMPILE_COMMANDS")) {
  1947. return;
  1948. }
  1949. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  1950. compileObjectVars.Language = language.c_str();
  1951. std::string escapedSourceFileName = sourceFileName;
  1952. if (!cmSystemTools::FileIsFullPath(sourceFileName)) {
  1953. escapedSourceFileName =
  1954. cmSystemTools::CollapseFullPath(escapedSourceFileName,
  1955. this->GetGlobalGenerator()
  1956. ->GetCMakeInstance()
  1957. ->GetHomeOutputDirectory());
  1958. }
  1959. escapedSourceFileName = this->LocalGenerator->ConvertToOutputFormat(
  1960. escapedSourceFileName, cmOutputConverter::SHELL);
  1961. std::string fullFlags = flags;
  1962. if (withScanning == WithScanning::Yes) {
  1963. std::string const modmapFormatVar =
  1964. cmStrCat("CMAKE_", language, "_MODULE_MAP_FORMAT");
  1965. std::string const modmapFormat =
  1966. this->Makefile->GetSafeDefinition(modmapFormatVar);
  1967. if (!modmapFormat.empty()) {
  1968. std::string modmapFlags = this->GetMakefile()->GetRequiredDefinition(
  1969. cmStrCat("CMAKE_", language, "_MODULE_MAP_FLAG"));
  1970. // XXX(modmap): If changing this path construction, change
  1971. // `cmGlobalNinjaGenerator::WriteDyndep` and
  1972. // `cmNinjaTargetGenerator::WriteObjectBuildStatement` to expect the
  1973. // corresponding file path.
  1974. cmSystemTools::ReplaceString(modmapFlags, "<MODULE_MAP_FILE>",
  1975. cmStrCat(objectFileName, ".modmap"));
  1976. fullFlags += cmStrCat(' ', modmapFlags);
  1977. }
  1978. }
  1979. compileObjectVars.Source = escapedSourceFileName.c_str();
  1980. std::string escapedObjectFileName =
  1981. this->LocalGenerator->ConvertToOutputFormat(objectFileName,
  1982. cmOutputConverter::SHELL);
  1983. compileObjectVars.Object = escapedObjectFileName.c_str();
  1984. compileObjectVars.ObjectDir = objectDir.c_str();
  1985. compileObjectVars.ObjectFileDir = objectFileDir.c_str();
  1986. compileObjectVars.Flags = fullFlags.c_str();
  1987. compileObjectVars.Defines = defines.c_str();
  1988. compileObjectVars.Includes = includes.c_str();
  1989. compileObjectVars.TargetCompilePDB = targetCompilePdb.c_str();
  1990. compileObjectVars.TargetPDB = targetPdb.c_str();
  1991. // Rule for compiling object file.
  1992. std::string cudaCompileMode;
  1993. if (language == "CUDA") {
  1994. if (this->GeneratorTarget->GetPropertyAsBool(
  1995. "CUDA_SEPARABLE_COMPILATION")) {
  1996. const std::string& rdcFlag =
  1997. this->Makefile->GetRequiredDefinition("_CMAKE_CUDA_RDC_FLAG");
  1998. cudaCompileMode = cmStrCat(cudaCompileMode, rdcFlag, " ");
  1999. }
  2000. static std::array<cm::string_view, 4> const compileModes{
  2001. { "PTX"_s, "CUBIN"_s, "FATBIN"_s, "OPTIX"_s }
  2002. };
  2003. bool useNormalCompileMode = true;
  2004. for (cm::string_view mode : compileModes) {
  2005. auto propName = cmStrCat("CUDA_", mode, "_COMPILATION");
  2006. auto defName = cmStrCat("_CMAKE_CUDA_", mode, "_FLAG");
  2007. if (this->GeneratorTarget->GetPropertyAsBool(propName)) {
  2008. const std::string& flag =
  2009. this->Makefile->GetRequiredDefinition(defName);
  2010. cudaCompileMode = cmStrCat(cudaCompileMode, flag);
  2011. useNormalCompileMode = false;
  2012. break;
  2013. }
  2014. }
  2015. if (useNormalCompileMode) {
  2016. const std::string& wholeFlag =
  2017. this->Makefile->GetRequiredDefinition("_CMAKE_CUDA_WHOLE_FLAG");
  2018. cudaCompileMode = cmStrCat(cudaCompileMode, wholeFlag);
  2019. }
  2020. compileObjectVars.CudaCompileMode = cudaCompileMode.c_str();
  2021. }
  2022. const std::string cmdVar = cmStrCat("CMAKE_", language, "_COMPILE_OBJECT");
  2023. const std::string& compileCmd =
  2024. this->Makefile->GetRequiredDefinition(cmdVar);
  2025. cmList compileCmds(compileCmd);
  2026. auto rulePlaceholderExpander =
  2027. this->GetLocalGenerator()->CreateRulePlaceholderExpander();
  2028. for (auto& i : compileCmds) {
  2029. // no launcher for CMAKE_EXPORT_COMPILE_COMMANDS
  2030. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  2031. compileObjectVars);
  2032. }
  2033. std::string cmdLine = this->GetLocalGenerator()->BuildCommandLine(
  2034. compileCmds, outputConfig, outputConfig);
  2035. this->GetGlobalGenerator()->AddCXXCompileCommand(cmdLine, sourceFileName,
  2036. objectFileName);
  2037. }
  2038. void cmNinjaTargetGenerator::ExportSwiftObjectCompileCommand(
  2039. std::vector<cmSourceFile const*> const& moduleSourceFiles,
  2040. std::string const& moduleObjectFilename, std::string const& flags,
  2041. std::string const& defines, std::string const& includes,
  2042. std::string const& outputConfig, bool singleOutput)
  2043. {
  2044. if (!this->GeneratorTarget->GetPropertyAsBool("EXPORT_COMPILE_COMMANDS")) {
  2045. return;
  2046. }
  2047. auto escapeSourceFileName = [this](std::string srcFilename) -> std::string {
  2048. if (!cmSystemTools::FileIsFullPath(srcFilename)) {
  2049. srcFilename =
  2050. cmSystemTools::CollapseFullPath(srcFilename,
  2051. this->GetGlobalGenerator()
  2052. ->GetCMakeInstance()
  2053. ->GetHomeOutputDirectory());
  2054. }
  2055. return this->LocalGenerator->ConvertToOutputFormat(
  2056. srcFilename, cmOutputConverter::SHELL);
  2057. };
  2058. auto escapedModuleObjectFilename =
  2059. this->ConvertToNinjaPath(moduleObjectFilename);
  2060. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  2061. compileObjectVars.Language = "Swift";
  2062. compileObjectVars.Flags = flags.c_str();
  2063. compileObjectVars.Defines = defines.c_str();
  2064. compileObjectVars.Includes = includes.c_str();
  2065. // Build up the list of source files in the module
  2066. std::vector<std::string> filenames;
  2067. filenames.reserve(moduleSourceFiles.size());
  2068. for (cmSourceFile const* sf : moduleSourceFiles) {
  2069. filenames.emplace_back(
  2070. escapeSourceFileName(this->GetCompiledSourceNinjaPath(sf)));
  2071. }
  2072. // Note that `escapedSourceFilenames` must remain alive until the
  2073. // compileObjectVars is consumed or Source will be a dangling pointer.
  2074. std::string const escapedSourceFilenames = cmJoin(filenames, " ");
  2075. compileObjectVars.Source = escapedSourceFilenames.c_str();
  2076. std::string const& compileCommand =
  2077. this->Makefile->GetRequiredDefinition("CMAKE_Swift_COMPILE_OBJECT");
  2078. cmList compileCmds(compileCommand);
  2079. auto rulePlaceholderExpander =
  2080. this->GetLocalGenerator()->CreateRulePlaceholderExpander();
  2081. for (cmSourceFile const* sf : moduleSourceFiles) {
  2082. std::string const sourceFilename = this->GetCompiledSourceNinjaPath(sf);
  2083. std::string objectFilename = escapedModuleObjectFilename;
  2084. if (!singleOutput) {
  2085. // If it's not single-output, each source file gets a separate object
  2086. objectFilename =
  2087. this->ConvertToNinjaPath(this->GetObjectFilePath(sf, outputConfig));
  2088. }
  2089. compileObjectVars.Objects = objectFilename.c_str();
  2090. for (std::string& cmd : compileCmds) {
  2091. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  2092. cmd, compileObjectVars);
  2093. }
  2094. std::string commandLine = this->GetLocalGenerator()->BuildCommandLine(
  2095. compileCmds, outputConfig, outputConfig);
  2096. this->GetGlobalGenerator()->AddCXXCompileCommand(
  2097. commandLine, sourceFilename, objectFilename);
  2098. }
  2099. }
  2100. void cmNinjaTargetGenerator::AdditionalCleanFiles(const std::string& config)
  2101. {
  2102. if (cmValue prop_value =
  2103. this->GeneratorTarget->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  2104. cmLocalNinjaGenerator* lg = this->LocalGenerator;
  2105. cmList cleanFiles(cmGeneratorExpression::Evaluate(*prop_value, lg, config,
  2106. this->GeneratorTarget));
  2107. std::string const& binaryDir = lg->GetCurrentBinaryDirectory();
  2108. cmGlobalNinjaGenerator* gg = lg->GetGlobalNinjaGenerator();
  2109. for (auto const& cleanFile : cleanFiles) {
  2110. // Support relative paths
  2111. gg->AddAdditionalCleanFile(
  2112. cmSystemTools::CollapseFullPath(cleanFile, binaryDir), config);
  2113. }
  2114. }
  2115. }
  2116. cmNinjaDeps cmNinjaTargetGenerator::GetObjects(const std::string& config) const
  2117. {
  2118. auto const it = this->Configs.find(config);
  2119. if (it != this->Configs.end()) {
  2120. return it->second.Objects;
  2121. }
  2122. return {};
  2123. }
  2124. void cmNinjaTargetGenerator::EnsureDirectoryExists(
  2125. const std::string& path) const
  2126. {
  2127. if (cmSystemTools::FileIsFullPath(path)) {
  2128. cmSystemTools::MakeDirectory(path);
  2129. } else {
  2130. cmGlobalNinjaGenerator* gg = this->GetGlobalGenerator();
  2131. std::string fullPath = gg->GetCMakeInstance()->GetHomeOutputDirectory();
  2132. // Also ensures there is a trailing slash.
  2133. gg->StripNinjaOutputPathPrefixAsSuffix(fullPath);
  2134. fullPath += path;
  2135. cmSystemTools::MakeDirectory(fullPath);
  2136. }
  2137. }
  2138. void cmNinjaTargetGenerator::EnsureParentDirectoryExists(
  2139. const std::string& path) const
  2140. {
  2141. this->EnsureDirectoryExists(cmSystemTools::GetParentDirectory(path));
  2142. }
  2143. void cmNinjaTargetGenerator::MacOSXContentGeneratorType::operator()(
  2144. cmSourceFile const& source, const char* pkgloc, const std::string& config)
  2145. {
  2146. // Skip OS X content when not building a Framework or Bundle.
  2147. if (!this->Generator->GetGeneratorTarget()->IsBundleOnApple()) {
  2148. return;
  2149. }
  2150. std::string macdir =
  2151. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(pkgloc,
  2152. config);
  2153. // Reject files that collide with files from the Ninja file's native config.
  2154. if (config != this->FileConfig) {
  2155. std::string nativeMacdir =
  2156. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(
  2157. pkgloc, this->FileConfig);
  2158. if (macdir == nativeMacdir) {
  2159. return;
  2160. }
  2161. }
  2162. // Get the input file location.
  2163. std::string input = source.GetFullPath();
  2164. input = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(input);
  2165. // Get the output file location.
  2166. std::string output =
  2167. cmStrCat(macdir, '/', cmSystemTools::GetFilenameName(input));
  2168. output = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(output);
  2169. // Write a build statement to copy the content into the bundle.
  2170. this->Generator->GetGlobalGenerator()->WriteMacOSXContentBuild(
  2171. input, output, this->FileConfig);
  2172. // Add as a dependency to the target so that it gets called.
  2173. this->Generator->Configs[config].ExtraFiles.push_back(std::move(output));
  2174. }
  2175. void cmNinjaTargetGenerator::AddDepfileBinding(cmNinjaVars& vars,
  2176. std::string depfile) const
  2177. {
  2178. std::string depfileForShell =
  2179. this->GetLocalGenerator()->ConvertToOutputFormat(depfile,
  2180. cmOutputConverter::SHELL);
  2181. if (depfile != depfileForShell) {
  2182. vars["depfile"] = std::move(depfile);
  2183. }
  2184. vars["DEP_FILE"] = std::move(depfileForShell);
  2185. }
  2186. void cmNinjaTargetGenerator::RemoveDepfileBinding(cmNinjaVars& vars) const
  2187. {
  2188. vars.erase("DEP_FILE");
  2189. vars.erase("depfile");
  2190. }
  2191. void cmNinjaTargetGenerator::addPoolNinjaVariable(
  2192. const std::string& pool_property, cmGeneratorTarget* target,
  2193. cmNinjaVars& vars)
  2194. {
  2195. cmValue pool = target->GetProperty(pool_property);
  2196. if (pool) {
  2197. vars["pool"] = *pool;
  2198. }
  2199. }
  2200. bool cmNinjaTargetGenerator::ForceResponseFile()
  2201. {
  2202. static std::string const forceRspFile = "CMAKE_NINJA_FORCE_RESPONSE_FILE";
  2203. return (this->GetMakefile()->IsDefinitionSet(forceRspFile) ||
  2204. cmSystemTools::HasEnv(forceRspFile));
  2205. }