cmNinjaTargetGenerator.cxx 63 KB

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