cmNinjaTargetGenerator.cxx 72 KB

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