cmNinjaTargetGenerator.cxx 81 KB

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