cmNinjaTargetGenerator.cxx 77 KB

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