cmNinjaTargetGenerator.cxx 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696
  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. std::string ispcDirectory = objectFileDir;
  1181. if (cmProp prop =
  1182. this->GeneratorTarget->GetProperty("ISPC_HEADER_DIRECTORY")) {
  1183. ispcDirectory = *prop;
  1184. }
  1185. ispcDirectory =
  1186. cmStrCat(this->LocalGenerator->GetBinaryDirectory(), '/', ispcDirectory);
  1187. std::string ispcHeader = cmStrCat(ispcDirectory, '/', ispcSource, ".h");
  1188. ispcHeader = this->ConvertToNinjaPath(ispcHeader);
  1189. // Make sure ninja knows what command generates the header
  1190. objBuild.ImplicitOuts.push_back(ispcHeader);
  1191. // Make sure ninja knows how to clean the generated header
  1192. this->GetGlobalGenerator()->AddAdditionalCleanFile(ispcHeader, config);
  1193. auto ispcSuffixes =
  1194. detail::ComputeISPCObjectSuffixes(this->GeneratorTarget);
  1195. if (ispcSuffixes.size() > 1) {
  1196. auto ispcSideEfffectObjects = detail::ComputeISPCExtraObjects(
  1197. objectName, ispcDirectory, ispcSuffixes);
  1198. for (auto sideEffect : ispcSideEfffectObjects) {
  1199. sideEffect = this->ConvertToNinjaPath(sideEffect);
  1200. objBuild.ImplicitOuts.emplace_back(sideEffect);
  1201. this->GetGlobalGenerator()->AddAdditionalCleanFile(sideEffect, config);
  1202. }
  1203. }
  1204. vars["ISPC_HEADER_FILE"] =
  1205. this->GetLocalGenerator()->ConvertToOutputFormat(
  1206. ispcHeader, cmOutputConverter::SHELL);
  1207. } else {
  1208. auto headers = this->GeneratorTarget->GetGeneratedISPCHeaders(config);
  1209. if (!headers.empty()) {
  1210. std::transform(headers.begin(), headers.end(), headers.begin(),
  1211. MapToNinjaPath());
  1212. objBuild.OrderOnlyDeps.insert(objBuild.OrderOnlyDeps.end(),
  1213. headers.begin(), headers.end());
  1214. }
  1215. }
  1216. if (language == "Swift") {
  1217. this->EmitSwiftDependencyInfo(source, config);
  1218. } else {
  1219. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1220. objBuild, commandLineLengthLimit);
  1221. }
  1222. if (cmProp objectOutputs = source->GetProperty("OBJECT_OUTPUTS")) {
  1223. std::string evaluatedObjectOutputs = cmGeneratorExpression::Evaluate(
  1224. *objectOutputs, this->LocalGenerator, config);
  1225. if (!evaluatedObjectOutputs.empty()) {
  1226. cmNinjaBuild build("phony");
  1227. build.Comment = "Additional output files.";
  1228. build.Outputs = cmExpandedList(evaluatedObjectOutputs);
  1229. std::transform(build.Outputs.begin(), build.Outputs.end(),
  1230. build.Outputs.begin(), MapToNinjaPath());
  1231. build.ExplicitDeps = objBuild.Outputs;
  1232. this->GetGlobalGenerator()->WriteBuild(
  1233. this->GetImplFileStream(fileConfig), build);
  1234. }
  1235. }
  1236. }
  1237. void cmNinjaTargetGenerator::WriteTargetDependInfo(std::string const& lang,
  1238. const std::string& config)
  1239. {
  1240. Json::Value tdi(Json::objectValue);
  1241. tdi["language"] = lang;
  1242. tdi["compiler-id"] = this->Makefile->GetSafeDefinition(
  1243. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  1244. if (lang == "Fortran") {
  1245. std::string mod_dir = this->GeneratorTarget->GetFortranModuleDirectory(
  1246. this->Makefile->GetHomeOutputDirectory());
  1247. if (mod_dir.empty()) {
  1248. mod_dir = this->Makefile->GetCurrentBinaryDirectory();
  1249. }
  1250. tdi["module-dir"] = mod_dir;
  1251. tdi["submodule-sep"] =
  1252. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
  1253. tdi["submodule-ext"] =
  1254. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
  1255. }
  1256. tdi["dir-cur-bld"] = this->Makefile->GetCurrentBinaryDirectory();
  1257. tdi["dir-cur-src"] = this->Makefile->GetCurrentSourceDirectory();
  1258. tdi["dir-top-bld"] = this->Makefile->GetHomeOutputDirectory();
  1259. tdi["dir-top-src"] = this->Makefile->GetHomeDirectory();
  1260. Json::Value& tdi_include_dirs = tdi["include-dirs"] = Json::arrayValue;
  1261. std::vector<std::string> includes;
  1262. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  1263. lang, config);
  1264. for (std::string const& i : includes) {
  1265. // Convert the include directories the same way we do for -I flags.
  1266. // See upstream ninja issue 1251.
  1267. tdi_include_dirs.append(this->ConvertToNinjaPath(i));
  1268. }
  1269. Json::Value& tdi_linked_target_dirs = tdi["linked-target-dirs"] =
  1270. Json::arrayValue;
  1271. for (std::string const& l : this->GetLinkedTargetDirectories(config)) {
  1272. tdi_linked_target_dirs.append(l);
  1273. }
  1274. std::string const tdin = this->GetTargetDependInfoPath(lang, config);
  1275. cmGeneratedFileStream tdif(tdin);
  1276. tdif << tdi;
  1277. }
  1278. void cmNinjaTargetGenerator::EmitSwiftDependencyInfo(
  1279. cmSourceFile const* source, const std::string& config)
  1280. {
  1281. std::string const sourceFilePath =
  1282. this->ConvertToNinjaPath(this->GetSourceFilePath(source));
  1283. std::string const objectFilePath =
  1284. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1285. std::string const swiftDepsPath = [source, objectFilePath]() -> std::string {
  1286. if (cmProp name = source->GetProperty("Swift_DEPENDENCIES_FILE")) {
  1287. return *name;
  1288. }
  1289. return cmStrCat(objectFilePath, ".swiftdeps");
  1290. }();
  1291. std::string const swiftDiaPath = [source, objectFilePath]() -> std::string {
  1292. if (cmProp name = source->GetProperty("Swift_DIAGNOSTICS_FILE")) {
  1293. return *name;
  1294. }
  1295. return cmStrCat(objectFilePath, ".dia");
  1296. }();
  1297. std::string const makeDepsPath = [this, source, config]() -> std::string {
  1298. cmLocalNinjaGenerator const* local = this->GetLocalGenerator();
  1299. std::string const objectFileName =
  1300. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1301. std::string const objectFileDir =
  1302. cmSystemTools::GetFilenamePath(objectFileName);
  1303. if (this->Makefile->IsOn("CMAKE_Swift_DEPFLE_EXTNSION_REPLACE")) {
  1304. std::string dependFileName = cmStrCat(
  1305. cmSystemTools::GetFilenameWithoutLastExtension(objectFileName), ".d");
  1306. return local->ConvertToOutputFormat(
  1307. cmStrCat(objectFileDir, '/', dependFileName),
  1308. cmOutputConverter::SHELL);
  1309. }
  1310. return local->ConvertToOutputFormat(cmStrCat(objectFileName, ".d"),
  1311. cmOutputConverter::SHELL);
  1312. }();
  1313. // build the source file mapping
  1314. // https://github.com/apple/swift/blob/master/docs/Driver.md#output-file-maps
  1315. Json::Value entry = Json::Value(Json::objectValue);
  1316. entry["object"] = objectFilePath;
  1317. entry["dependencies"] = makeDepsPath;
  1318. entry["swift-dependencies"] = swiftDepsPath;
  1319. entry["diagnostics"] = swiftDiaPath;
  1320. this->Configs[config].SwiftOutputMap[sourceFilePath] = entry;
  1321. }
  1322. void cmNinjaTargetGenerator::ExportObjectCompileCommand(
  1323. std::string const& language, std::string const& sourceFileName,
  1324. std::string const& objectDir, std::string const& objectFileName,
  1325. std::string const& objectFileDir, std::string const& flags,
  1326. std::string const& defines, std::string const& includes)
  1327. {
  1328. if (!this->Makefile->IsOn("CMAKE_EXPORT_COMPILE_COMMANDS")) {
  1329. return;
  1330. }
  1331. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  1332. compileObjectVars.Language = language.c_str();
  1333. std::string escapedSourceFileName = sourceFileName;
  1334. if (!cmSystemTools::FileIsFullPath(sourceFileName)) {
  1335. escapedSourceFileName =
  1336. cmSystemTools::CollapseFullPath(escapedSourceFileName,
  1337. this->GetGlobalGenerator()
  1338. ->GetCMakeInstance()
  1339. ->GetHomeOutputDirectory());
  1340. }
  1341. escapedSourceFileName = this->LocalGenerator->ConvertToOutputFormat(
  1342. escapedSourceFileName, cmOutputConverter::SHELL);
  1343. compileObjectVars.Source = escapedSourceFileName.c_str();
  1344. compileObjectVars.Object = objectFileName.c_str();
  1345. compileObjectVars.ObjectDir = objectDir.c_str();
  1346. compileObjectVars.ObjectFileDir = objectFileDir.c_str();
  1347. compileObjectVars.Flags = flags.c_str();
  1348. compileObjectVars.Defines = defines.c_str();
  1349. compileObjectVars.Includes = includes.c_str();
  1350. // Rule for compiling object file.
  1351. std::vector<std::string> compileCmds;
  1352. if (language == "CUDA") {
  1353. std::string cmdVar;
  1354. if (this->GeneratorTarget->GetPropertyAsBool(
  1355. "CUDA_SEPARABLE_COMPILATION")) {
  1356. cmdVar = "CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION";
  1357. } else if (this->GeneratorTarget->GetPropertyAsBool(
  1358. "CUDA_PTX_COMPILATION")) {
  1359. cmdVar = "CMAKE_CUDA_COMPILE_PTX_COMPILATION";
  1360. } else {
  1361. cmdVar = "CMAKE_CUDA_COMPILE_WHOLE_COMPILATION";
  1362. }
  1363. const std::string& compileCmd =
  1364. this->GetMakefile()->GetRequiredDefinition(cmdVar);
  1365. cmExpandList(compileCmd, compileCmds);
  1366. } else {
  1367. const std::string cmdVar = cmStrCat("CMAKE_", language, "_COMPILE_OBJECT");
  1368. const std::string& compileCmd =
  1369. this->GetMakefile()->GetRequiredDefinition(cmdVar);
  1370. cmExpandList(compileCmd, compileCmds);
  1371. }
  1372. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  1373. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  1374. for (std::string& i : compileCmds) {
  1375. // no launcher for CMAKE_EXPORT_COMPILE_COMMANDS
  1376. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  1377. compileObjectVars);
  1378. }
  1379. std::string cmdLine =
  1380. this->GetLocalGenerator()->BuildCommandLine(compileCmds);
  1381. this->GetGlobalGenerator()->AddCXXCompileCommand(cmdLine, sourceFileName);
  1382. }
  1383. void cmNinjaTargetGenerator::AdditionalCleanFiles(const std::string& config)
  1384. {
  1385. if (cmProp prop_value =
  1386. this->GeneratorTarget->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  1387. cmLocalNinjaGenerator* lg = this->LocalGenerator;
  1388. std::vector<std::string> cleanFiles;
  1389. cmExpandList(cmGeneratorExpression::Evaluate(*prop_value, lg, config,
  1390. this->GeneratorTarget),
  1391. cleanFiles);
  1392. std::string const& binaryDir = lg->GetCurrentBinaryDirectory();
  1393. cmGlobalNinjaGenerator* gg = lg->GetGlobalNinjaGenerator();
  1394. for (std::string const& cleanFile : cleanFiles) {
  1395. // Support relative paths
  1396. gg->AddAdditionalCleanFile(
  1397. cmSystemTools::CollapseFullPath(cleanFile, binaryDir), config);
  1398. }
  1399. }
  1400. }
  1401. cmNinjaDeps cmNinjaTargetGenerator::GetObjects(const std::string& config) const
  1402. {
  1403. auto const it = this->Configs.find(config);
  1404. if (it != this->Configs.end()) {
  1405. return it->second.Objects;
  1406. }
  1407. return {};
  1408. }
  1409. void cmNinjaTargetGenerator::EnsureDirectoryExists(
  1410. const std::string& path) const
  1411. {
  1412. if (cmSystemTools::FileIsFullPath(path)) {
  1413. cmSystemTools::MakeDirectory(path);
  1414. } else {
  1415. cmGlobalNinjaGenerator* gg = this->GetGlobalGenerator();
  1416. std::string fullPath = gg->GetCMakeInstance()->GetHomeOutputDirectory();
  1417. // Also ensures their is a trailing slash.
  1418. gg->StripNinjaOutputPathPrefixAsSuffix(fullPath);
  1419. fullPath += path;
  1420. cmSystemTools::MakeDirectory(fullPath);
  1421. }
  1422. }
  1423. void cmNinjaTargetGenerator::EnsureParentDirectoryExists(
  1424. const std::string& path) const
  1425. {
  1426. EnsureDirectoryExists(cmSystemTools::GetParentDirectory(path));
  1427. }
  1428. void cmNinjaTargetGenerator::MacOSXContentGeneratorType::operator()(
  1429. cmSourceFile const& source, const char* pkgloc, const std::string& config)
  1430. {
  1431. // Skip OS X content when not building a Framework or Bundle.
  1432. if (!this->Generator->GetGeneratorTarget()->IsBundleOnApple()) {
  1433. return;
  1434. }
  1435. std::string macdir =
  1436. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(pkgloc,
  1437. config);
  1438. // Reject files that collide with files from the Ninja file's native config.
  1439. if (config != this->FileConfig) {
  1440. std::string nativeMacdir =
  1441. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(
  1442. pkgloc, this->FileConfig);
  1443. if (macdir == nativeMacdir) {
  1444. return;
  1445. }
  1446. }
  1447. // Get the input file location.
  1448. std::string input = source.GetFullPath();
  1449. input = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(input);
  1450. // Get the output file location.
  1451. std::string output =
  1452. cmStrCat(macdir, '/', cmSystemTools::GetFilenameName(input));
  1453. output = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(output);
  1454. // Write a build statement to copy the content into the bundle.
  1455. this->Generator->GetGlobalGenerator()->WriteMacOSXContentBuild(
  1456. input, output, this->FileConfig);
  1457. // Add as a dependency to the target so that it gets called.
  1458. this->Generator->Configs[config].ExtraFiles.push_back(std::move(output));
  1459. }
  1460. void cmNinjaTargetGenerator::addPoolNinjaVariable(
  1461. const std::string& pool_property, cmGeneratorTarget* target,
  1462. cmNinjaVars& vars)
  1463. {
  1464. cmProp pool = target->GetProperty(pool_property);
  1465. if (pool) {
  1466. vars["pool"] = *pool;
  1467. }
  1468. }
  1469. bool cmNinjaTargetGenerator::ForceResponseFile()
  1470. {
  1471. static std::string const forceRspFile = "CMAKE_NINJA_FORCE_RESPONSE_FILE";
  1472. return (this->GetMakefile()->IsDefinitionSet(forceRspFile) ||
  1473. cmSystemTools::HasEnv(forceRspFile));
  1474. }