cmNinjaTargetGenerator.cxx 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204
  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.emplace_back(
  1051. cmStrCat(this->Makefile->GetCurrentBinaryDirectory(), '/',
  1052. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  1053. this->GetGlobalGenerator()->ConfigDirectory(config), '/',
  1054. language, "Modules.json"));
  1055. build.ImplicitDeps.emplace_back(
  1056. this->GetTargetDependInfoPath(language, config));
  1057. for (auto const& scanFiles : scanningFiles) {
  1058. if (!scanFiles.ScanningOutput.empty()) {
  1059. build.ExplicitDeps.push_back(scanFiles.ScanningOutput);
  1060. }
  1061. if (!scanFiles.ModuleMapFile.empty()) {
  1062. build.ImplicitOuts.push_back(scanFiles.ModuleMapFile);
  1063. }
  1064. }
  1065. this->WriteTargetDependInfo(language, config);
  1066. auto const linked_directories =
  1067. this->GetLinkedTargetDirectories(language, config);
  1068. for (std::string const& l : linked_directories.Direct) {
  1069. build.ImplicitDeps.emplace_back(
  1070. cmStrCat(l, '/', language, "Modules.json"));
  1071. }
  1072. for (std::string const& l : linked_directories.Forward) {
  1073. build.ImplicitDeps.emplace_back(
  1074. cmStrCat(l, '/', language, "Modules.json"));
  1075. }
  1076. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1077. build);
  1078. }
  1079. this->GetImplFileStream(fileConfig) << "\n";
  1080. }
  1081. void cmNinjaTargetGenerator::GenerateSwiftOutputFileMap(
  1082. const std::string& config, std::string& flags)
  1083. {
  1084. if (this->Configs[config].SwiftOutputMap.empty()) {
  1085. return;
  1086. }
  1087. std::string const targetSwiftDepsPath = [this, config]() -> std::string {
  1088. cmGeneratorTarget const* target = this->GeneratorTarget;
  1089. if (cmValue name = target->GetProperty("Swift_DEPENDENCIES_FILE")) {
  1090. return *name;
  1091. }
  1092. return this->ConvertToNinjaPath(cmStrCat(target->GetSupportDirectory(),
  1093. '/', config, '/',
  1094. target->GetName(), ".swiftdeps"));
  1095. }();
  1096. std::string mapFilePath =
  1097. cmStrCat(this->GeneratorTarget->GetSupportDirectory(), '/', config, '/',
  1098. "output-file-map.json");
  1099. // build the global target dependencies
  1100. // https://github.com/apple/swift/blob/master/docs/Driver.md#output-file-maps
  1101. Json::Value deps(Json::objectValue);
  1102. deps["swift-dependencies"] = targetSwiftDepsPath;
  1103. this->Configs[config].SwiftOutputMap[""] = deps;
  1104. cmGeneratedFileStream output(mapFilePath);
  1105. output << this->Configs[config].SwiftOutputMap;
  1106. // Add flag
  1107. this->LocalGenerator->AppendFlags(flags, "-output-file-map");
  1108. this->LocalGenerator->AppendFlagEscape(flags,
  1109. ConvertToNinjaPath(mapFilePath));
  1110. }
  1111. namespace {
  1112. cmNinjaBuild GetScanBuildStatement(const std::string& ruleName,
  1113. const std::string& ppFileName,
  1114. bool compilePP, bool compilePPWithDefines,
  1115. bool compilationPreprocesses,
  1116. cmNinjaBuild& objBuild, cmNinjaVars& vars,
  1117. const std::string& objectFileName,
  1118. cmLocalGenerator* lg)
  1119. {
  1120. cmNinjaBuild scanBuild(ruleName);
  1121. if (compilePP) {
  1122. // Move compilation dependencies to the scan/preprocessing build statement.
  1123. std::swap(scanBuild.ExplicitDeps, objBuild.ExplicitDeps);
  1124. std::swap(scanBuild.ImplicitDeps, objBuild.ImplicitDeps);
  1125. std::swap(scanBuild.OrderOnlyDeps, objBuild.OrderOnlyDeps);
  1126. std::swap(scanBuild.Variables["IN_ABS"], vars["IN_ABS"]);
  1127. // The actual compilation will now use the preprocessed source.
  1128. objBuild.ExplicitDeps.push_back(ppFileName);
  1129. } else {
  1130. // Copy compilation dependencies to the scan/preprocessing build statement.
  1131. scanBuild.ExplicitDeps = objBuild.ExplicitDeps;
  1132. scanBuild.ImplicitDeps = objBuild.ImplicitDeps;
  1133. scanBuild.OrderOnlyDeps = objBuild.OrderOnlyDeps;
  1134. scanBuild.Variables["IN_ABS"] = vars["IN_ABS"];
  1135. }
  1136. // Scanning and compilation generally use the same flags.
  1137. scanBuild.Variables["FLAGS"] = vars["FLAGS"];
  1138. if (compilePP && !compilePPWithDefines) {
  1139. // Move preprocessor definitions to the scan/preprocessor build statement.
  1140. std::swap(scanBuild.Variables["DEFINES"], vars["DEFINES"]);
  1141. } else {
  1142. // Copy preprocessor definitions to the scan/preprocessor build statement.
  1143. scanBuild.Variables["DEFINES"] = vars["DEFINES"];
  1144. }
  1145. // Copy include directories to the preprocessor build statement. The
  1146. // Fortran compilation build statement still needs them for the INCLUDE
  1147. // directive.
  1148. scanBuild.Variables["INCLUDES"] = vars["INCLUDES"];
  1149. // Tell dependency scanner the object file that will result from
  1150. // compiling the source.
  1151. scanBuild.Variables["OBJ_FILE"] = objectFileName;
  1152. // Tell dependency scanner where to store dyndep intermediate results.
  1153. std::string ddiFileName = cmStrCat(objectFileName, ".ddi");
  1154. scanBuild.Variables["DYNDEP_INTERMEDIATE_FILE"] = ddiFileName;
  1155. scanBuild.RspFile = cmStrCat(ddiFileName, ".rsp");
  1156. // Outputs of the scan/preprocessor build statement.
  1157. if (compilePP) {
  1158. scanBuild.Outputs.push_back(ppFileName);
  1159. scanBuild.ImplicitOuts.push_back(ddiFileName);
  1160. } else {
  1161. scanBuild.Outputs.push_back(ddiFileName);
  1162. scanBuild.Variables["PREPROCESSED_OUTPUT_FILE"] = ppFileName;
  1163. if (!compilationPreprocesses) {
  1164. // Compilation does not preprocess and we are not compiling an
  1165. // already-preprocessed source. Make compilation depend on the scan
  1166. // results to honor implicit dependencies discovered during scanning
  1167. // (such as Fortran INCLUDE directives).
  1168. objBuild.ImplicitDeps.emplace_back(ddiFileName);
  1169. }
  1170. }
  1171. // Scanning always provides a depfile for preprocessor dependencies. This
  1172. // variable is unused in `msvc`-deptype scanners.
  1173. std::string const& depFileName = cmStrCat(scanBuild.Outputs.front(), ".d");
  1174. scanBuild.Variables["DEP_FILE"] =
  1175. lg->ConvertToOutputFormat(depFileName, cmOutputConverter::SHELL);
  1176. if (compilePP) {
  1177. // The actual compilation does not need a depfile because it
  1178. // depends on the already-preprocessed source.
  1179. vars.erase("DEP_FILE");
  1180. }
  1181. return scanBuild;
  1182. }
  1183. }
  1184. void cmNinjaTargetGenerator::WriteObjectBuildStatement(
  1185. cmSourceFile const* source, const std::string& config,
  1186. const std::string& fileConfig, bool firstForConfig)
  1187. {
  1188. std::string const language = source->GetLanguage();
  1189. std::string const sourceFilePath = this->GetCompiledSourceNinjaPath(source);
  1190. std::string const objectDir = this->ConvertToNinjaPath(
  1191. cmStrCat(this->GeneratorTarget->GetSupportDirectory(),
  1192. this->GetGlobalGenerator()->ConfigDirectory(config)));
  1193. std::string const objectFileName =
  1194. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1195. std::string const objectFileDir =
  1196. cmSystemTools::GetFilenamePath(objectFileName);
  1197. std::string cmakeVarLang = cmStrCat("CMAKE_", language);
  1198. // build response file name
  1199. std::string cmakeLinkVar = cmStrCat(cmakeVarLang, "_RESPONSE_FILE_FLAG");
  1200. cmValue flag = this->GetMakefile()->GetDefinition(cmakeLinkVar);
  1201. bool const lang_supports_response =
  1202. !(language == "RC" || (language == "CUDA" && !flag));
  1203. int const commandLineLengthLimit =
  1204. ((lang_supports_response && this->ForceResponseFile())) ? -1 : 0;
  1205. cmValue pchExtension =
  1206. this->GetMakefile()->GetDefinition("CMAKE_PCH_EXTENSION");
  1207. bool const isPch = cmHasSuffix(objectFileName, pchExtension);
  1208. bool const needDyndep = !isPch &&
  1209. this->GeneratorTarget->NeedDyndepForSource(language, config, source);
  1210. WithScanning withScanning =
  1211. needDyndep ? WithScanning::Yes : WithScanning::No;
  1212. cmNinjaBuild objBuild(
  1213. this->LanguageCompilerRule(language, config, withScanning));
  1214. cmNinjaVars& vars = objBuild.Variables;
  1215. vars["FLAGS"] =
  1216. this->ComputeFlagsForObject(source, language, config, objectFileName);
  1217. vars["DEFINES"] = this->ComputeDefines(source, language, config);
  1218. vars["INCLUDES"] = this->ComputeIncludes(source, language, config);
  1219. auto compilerLauncher = this->GetCompilerLauncher(language, config);
  1220. cmValue const skipCodeCheck = source->GetProperty("SKIP_LINTING");
  1221. if (!skipCodeCheck.IsOn()) {
  1222. auto const cmakeCmd = this->GetLocalGenerator()->ConvertToOutputFormat(
  1223. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  1224. vars["CODE_CHECK"] =
  1225. this->GenerateCodeCheckRules(*source, compilerLauncher, cmakeCmd, config,
  1226. [this](const std::string& path) {
  1227. return this->ConvertToNinjaPath(path);
  1228. });
  1229. }
  1230. // If compiler launcher was specified and not consumed above, it
  1231. // goes to the beginning of the command line.
  1232. if (!compilerLauncher.empty()) {
  1233. cmList args{ compilerLauncher, cmList::EmptyElements::Yes };
  1234. if (!args.empty()) {
  1235. args[0] = this->LocalGenerator->ConvertToOutputFormat(
  1236. args[0], cmOutputConverter::SHELL);
  1237. for (std::string& i : cmMakeRange(args.begin() + 1, args.end())) {
  1238. i = this->LocalGenerator->EscapeForShell(i);
  1239. }
  1240. vars["LAUNCHER"] = args.join(" ") + " ";
  1241. }
  1242. }
  1243. if (this->GetMakefile()->GetSafeDefinition(
  1244. cmStrCat("CMAKE_", language, "_DEPFILE_FORMAT")) != "msvc"_s) {
  1245. bool replaceExt(false);
  1246. if (!language.empty()) {
  1247. std::string repVar =
  1248. cmStrCat("CMAKE_", language, "_DEPFILE_EXTENSION_REPLACE");
  1249. replaceExt = this->Makefile->IsOn(repVar);
  1250. }
  1251. if (!replaceExt) {
  1252. // use original code
  1253. vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1254. cmStrCat(objectFileName, ".d"), cmOutputConverter::SHELL);
  1255. } else {
  1256. // Replace the original source file extension with the
  1257. // depend file extension.
  1258. std::string dependFileName = cmStrCat(
  1259. cmSystemTools::GetFilenameWithoutLastExtension(objectFileName), ".d");
  1260. vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1261. cmStrCat(objectFileDir, '/', dependFileName),
  1262. cmOutputConverter::SHELL);
  1263. }
  1264. }
  1265. if (firstForConfig) {
  1266. this->ExportObjectCompileCommand(
  1267. language, sourceFilePath, objectDir, objectFileName, objectFileDir,
  1268. vars["FLAGS"], vars["DEFINES"], vars["INCLUDES"], config, withScanning);
  1269. }
  1270. objBuild.Outputs.push_back(objectFileName);
  1271. if (firstForConfig && !isPch) {
  1272. // Add this object to the list of object files.
  1273. this->Configs[config].Objects.push_back(objectFileName);
  1274. }
  1275. objBuild.ExplicitDeps.push_back(sourceFilePath);
  1276. // Add precompile headers dependencies
  1277. std::vector<std::string> depList;
  1278. std::vector<std::string> architectures =
  1279. this->GeneratorTarget->GetAppleArchs(config, language);
  1280. if (architectures.empty()) {
  1281. architectures.emplace_back();
  1282. }
  1283. std::unordered_set<std::string> pchSources;
  1284. for (const std::string& arch : architectures) {
  1285. const std::string pchSource =
  1286. this->GeneratorTarget->GetPchSource(config, language, arch);
  1287. if (!pchSource.empty()) {
  1288. pchSources.insert(pchSource);
  1289. }
  1290. }
  1291. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  1292. for (const std::string& arch : architectures) {
  1293. depList.push_back(
  1294. this->GeneratorTarget->GetPchHeader(config, language, arch));
  1295. if (pchSources.find(source->GetFullPath()) == pchSources.end()) {
  1296. depList.push_back(
  1297. this->GeneratorTarget->GetPchFile(config, language, arch));
  1298. }
  1299. }
  1300. }
  1301. if (cmValue objectDeps = source->GetProperty("OBJECT_DEPENDS")) {
  1302. cmList objDepList{ *objectDeps };
  1303. std::copy(objDepList.begin(), objDepList.end(),
  1304. std::back_inserter(depList));
  1305. }
  1306. if (!depList.empty()) {
  1307. for (std::string& odi : depList) {
  1308. if (cmSystemTools::FileIsFullPath(odi)) {
  1309. odi = cmSystemTools::CollapseFullPath(odi);
  1310. }
  1311. }
  1312. std::transform(depList.begin(), depList.end(),
  1313. std::back_inserter(objBuild.ImplicitDeps),
  1314. this->MapToNinjaPath());
  1315. }
  1316. if (this->HasPrivateGeneratedSources) {
  1317. objBuild.OrderOnlyDeps.push_back(
  1318. this->OrderDependsTargetForTargetPrivate(config));
  1319. } else {
  1320. objBuild.OrderOnlyDeps.push_back(
  1321. this->OrderDependsTargetForTarget(config));
  1322. }
  1323. // If the source file is GENERATED and does not have a custom command
  1324. // (either attached to this source file or another one), assume that one of
  1325. // the target dependencies, OBJECT_DEPENDS or header file custom commands
  1326. // will rebuild the file.
  1327. if (source->GetIsGenerated() &&
  1328. !source->GetPropertyAsBool("__CMAKE_GENERATED_BY_CMAKE") &&
  1329. !source->GetCustomCommand() &&
  1330. !this->GetGlobalGenerator()->HasCustomCommandOutput(sourceFilePath)) {
  1331. this->GetGlobalGenerator()->AddAssumedSourceDependencies(
  1332. sourceFilePath, objBuild.OrderOnlyDeps);
  1333. }
  1334. // For some cases we scan to dynamically discover dependencies.
  1335. bool const compilationPreprocesses =
  1336. !this->NeedExplicitPreprocessing(language);
  1337. std::string modmapFormat;
  1338. if (needDyndep) {
  1339. std::string const modmapFormatVar =
  1340. cmStrCat("CMAKE_", language, "_MODULE_MAP_FORMAT");
  1341. modmapFormat = this->Makefile->GetSafeDefinition(modmapFormatVar);
  1342. }
  1343. if (needDyndep) {
  1344. // If source/target has preprocessing turned off, we still need to
  1345. // generate an explicit dependency step
  1346. const auto srcpp = source->GetSafeProperty("Fortran_PREPROCESS");
  1347. cmOutputConverter::FortranPreprocess preprocess =
  1348. cmOutputConverter::GetFortranPreprocess(srcpp);
  1349. if (preprocess == cmOutputConverter::FortranPreprocess::Unset) {
  1350. const auto& tgtpp =
  1351. this->GeneratorTarget->GetSafeProperty("Fortran_PREPROCESS");
  1352. preprocess = cmOutputConverter::GetFortranPreprocess(tgtpp);
  1353. }
  1354. bool const compilePP = !compilationPreprocesses &&
  1355. (preprocess != cmOutputConverter::FortranPreprocess::NotNeeded);
  1356. bool const compilePPWithDefines =
  1357. compilePP && this->CompileWithDefines(language);
  1358. std::string scanRuleName;
  1359. std::string ppFileName;
  1360. if (compilePP) {
  1361. scanRuleName = this->LanguagePreprocessAndScanRule(language, config);
  1362. ppFileName = this->ConvertToNinjaPath(
  1363. this->GetPreprocessedFilePath(source, config));
  1364. } else {
  1365. scanRuleName = this->LanguageScanRule(language, config);
  1366. ppFileName = cmStrCat(objectFileName, ".ddi.i");
  1367. }
  1368. cmNinjaBuild ppBuild = GetScanBuildStatement(
  1369. scanRuleName, ppFileName, compilePP, compilePPWithDefines,
  1370. compilationPreprocesses, objBuild, vars, objectFileName,
  1371. this->LocalGenerator);
  1372. if (compilePP) {
  1373. // In case compilation requires flags that are incompatible with
  1374. // preprocessing, include them here.
  1375. std::string const& postFlag = this->Makefile->GetSafeDefinition(
  1376. cmStrCat("CMAKE_", language, "_POSTPROCESS_FLAG"));
  1377. this->LocalGenerator->AppendFlags(vars["FLAGS"], postFlag);
  1378. // Prepend source file's original directory as an include directory
  1379. // so e.g. Fortran INCLUDE statements can look for files in it.
  1380. std::vector<std::string> sourceDirectory;
  1381. sourceDirectory.push_back(
  1382. cmSystemTools::GetParentDirectory(source->GetFullPath()));
  1383. std::string sourceDirectoryFlag = this->LocalGenerator->GetIncludeFlags(
  1384. sourceDirectory, this->GeneratorTarget, language, config, false);
  1385. vars["INCLUDES"] = cmStrCat(sourceDirectoryFlag, ' ', vars["INCLUDES"]);
  1386. }
  1387. ScanningFiles scanningFiles;
  1388. if (firstForConfig) {
  1389. scanningFiles.ScanningOutput = cmStrCat(objectFileName, ".ddi");
  1390. }
  1391. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1392. ppBuild.Variables);
  1393. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1394. ppBuild, commandLineLengthLimit);
  1395. std::string const dyndep = this->GetDyndepFilePath(language, config);
  1396. objBuild.OrderOnlyDeps.push_back(dyndep);
  1397. vars["dyndep"] = dyndep;
  1398. if (!modmapFormat.empty()) {
  1399. // XXX(modmap): If changing this path construction, change
  1400. // `cmGlobalNinjaGenerator::WriteDyndep` and
  1401. // `cmNinjaTargetGenerator::ExportObjectCompileCommand` to expect the
  1402. // corresponding file path.
  1403. std::string ddModmapFile = cmStrCat(objectFileName, ".modmap");
  1404. vars["DYNDEP_MODULE_MAP_FILE"] = ddModmapFile;
  1405. objBuild.ImplicitDeps.push_back(ddModmapFile);
  1406. scanningFiles.ModuleMapFile = std::move(ddModmapFile);
  1407. }
  1408. if (!scanningFiles.IsEmpty()) {
  1409. this->Configs[config].ScanningInfo[language].emplace_back(scanningFiles);
  1410. }
  1411. }
  1412. this->EnsureParentDirectoryExists(objectFileName);
  1413. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1414. objectDir, cmOutputConverter::SHELL);
  1415. vars["OBJECT_FILE_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1416. objectFileDir, cmOutputConverter::SHELL);
  1417. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1418. vars);
  1419. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  1420. auto pchIt = pchSources.find(source->GetFullPath());
  1421. if (pchIt != pchSources.end()) {
  1422. this->addPoolNinjaVariable("JOB_POOL_PRECOMPILE_HEADER",
  1423. this->GetGeneratorTarget(), vars);
  1424. }
  1425. }
  1426. this->SetMsvcTargetPdbVariable(vars, config);
  1427. objBuild.RspFile = cmStrCat(objectFileName, ".rsp");
  1428. if (language == "ISPC") {
  1429. std::string const& objectName =
  1430. this->GeneratorTarget->GetObjectName(source);
  1431. std::string ispcSource =
  1432. cmSystemTools::GetFilenameWithoutLastExtension(objectName);
  1433. ispcSource = cmSystemTools::GetFilenameWithoutLastExtension(ispcSource);
  1434. cmValue ispcSuffixProp =
  1435. this->GeneratorTarget->GetProperty("ISPC_HEADER_SUFFIX");
  1436. assert(ispcSuffixProp);
  1437. std::string ispcHeaderDirectory =
  1438. this->GeneratorTarget->GetObjectDirectory(config);
  1439. if (cmValue prop =
  1440. this->GeneratorTarget->GetProperty("ISPC_HEADER_DIRECTORY")) {
  1441. ispcHeaderDirectory =
  1442. cmStrCat(this->LocalGenerator->GetBinaryDirectory(), '/', *prop);
  1443. }
  1444. std::string ispcHeader =
  1445. cmStrCat(ispcHeaderDirectory, '/', ispcSource, *ispcSuffixProp);
  1446. ispcHeader = this->ConvertToNinjaPath(ispcHeader);
  1447. // Make sure ninja knows what command generates the header
  1448. objBuild.ImplicitOuts.push_back(ispcHeader);
  1449. // Make sure ninja knows how to clean the generated header
  1450. this->GetGlobalGenerator()->AddAdditionalCleanFile(ispcHeader, config);
  1451. auto ispcSuffixes =
  1452. detail::ComputeISPCObjectSuffixes(this->GeneratorTarget);
  1453. if (ispcSuffixes.size() > 1) {
  1454. std::string rootObjectDir =
  1455. this->GeneratorTarget->GetObjectDirectory(config);
  1456. auto ispcSideEfffectObjects = detail::ComputeISPCExtraObjects(
  1457. objectName, rootObjectDir, ispcSuffixes);
  1458. for (auto sideEffect : ispcSideEfffectObjects) {
  1459. sideEffect = this->ConvertToNinjaPath(sideEffect);
  1460. objBuild.ImplicitOuts.emplace_back(sideEffect);
  1461. this->GetGlobalGenerator()->AddAdditionalCleanFile(sideEffect, config);
  1462. }
  1463. }
  1464. vars["ISPC_HEADER_FILE"] =
  1465. this->GetLocalGenerator()->ConvertToOutputFormat(
  1466. ispcHeader, cmOutputConverter::SHELL);
  1467. } else {
  1468. auto headers = this->GeneratorTarget->GetGeneratedISPCHeaders(config);
  1469. if (!headers.empty()) {
  1470. std::transform(headers.begin(), headers.end(), headers.begin(),
  1471. this->MapToNinjaPath());
  1472. objBuild.OrderOnlyDeps.insert(objBuild.OrderOnlyDeps.end(),
  1473. headers.begin(), headers.end());
  1474. }
  1475. }
  1476. if (language == "Swift") {
  1477. this->EmitSwiftDependencyInfo(source, config);
  1478. } else {
  1479. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1480. objBuild, commandLineLengthLimit);
  1481. }
  1482. if (cmValue objectOutputs = source->GetProperty("OBJECT_OUTPUTS")) {
  1483. std::string evaluatedObjectOutputs = cmGeneratorExpression::Evaluate(
  1484. *objectOutputs, this->LocalGenerator, config);
  1485. if (!evaluatedObjectOutputs.empty()) {
  1486. cmNinjaBuild build("phony");
  1487. build.Comment = "Additional output files.";
  1488. build.Outputs = cmList{ evaluatedObjectOutputs }.data();
  1489. std::transform(build.Outputs.begin(), build.Outputs.end(),
  1490. build.Outputs.begin(), this->MapToNinjaPath());
  1491. build.ExplicitDeps = objBuild.Outputs;
  1492. this->GetGlobalGenerator()->WriteBuild(
  1493. this->GetImplFileStream(fileConfig), build);
  1494. }
  1495. }
  1496. }
  1497. void cmNinjaTargetGenerator::WriteCxxModuleBmiBuildStatement(
  1498. cmSourceFile const* source, const std::string& config,
  1499. const std::string& fileConfig, bool firstForConfig)
  1500. {
  1501. std::string const language = source->GetLanguage();
  1502. if (language != "CXX"_s) {
  1503. this->GetMakefile()->IssueMessage(
  1504. MessageType::FATAL_ERROR,
  1505. cmStrCat("Source file '", source->GetFullPath(), "' of target '",
  1506. this->GetTargetName(), "' is a '", language,
  1507. "' source but must be 'CXX' in order to have a BMI build "
  1508. "statement generated."));
  1509. return;
  1510. }
  1511. std::string const sourceFilePath = this->GetCompiledSourceNinjaPath(source);
  1512. std::string const bmiDir = this->ConvertToNinjaPath(
  1513. cmStrCat(this->GeneratorTarget->GetSupportDirectory(),
  1514. this->GetGlobalGenerator()->ConfigDirectory(config)));
  1515. std::string const bmiFileName =
  1516. this->ConvertToNinjaPath(this->GetBmiFilePath(source, config));
  1517. std::string const bmiFileDir = cmSystemTools::GetFilenamePath(bmiFileName);
  1518. int const commandLineLengthLimit = this->ForceResponseFile() ? -1 : 0;
  1519. cmNinjaBuild bmiBuild(
  1520. this->LanguageCompilerRule(language, config, WithScanning::Yes));
  1521. cmNinjaVars& vars = bmiBuild.Variables;
  1522. vars["FLAGS"] =
  1523. this->ComputeFlagsForObject(source, language, config, bmiFileName);
  1524. vars["DEFINES"] = this->ComputeDefines(source, language, config);
  1525. vars["INCLUDES"] = this->ComputeIncludes(source, language, config);
  1526. if (this->GetMakefile()->GetSafeDefinition(
  1527. cmStrCat("CMAKE_", language, "_DEPFILE_FORMAT")) != "msvc"_s) {
  1528. bool replaceExt(false);
  1529. if (!language.empty()) {
  1530. std::string repVar =
  1531. cmStrCat("CMAKE_", language, "_DEPFILE_EXTENSION_REPLACE");
  1532. replaceExt = this->Makefile->IsOn(repVar);
  1533. }
  1534. if (!replaceExt) {
  1535. // use original code
  1536. vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1537. cmStrCat(bmiFileName, ".d"), cmOutputConverter::SHELL);
  1538. } else {
  1539. // Replace the original source file extension with the
  1540. // depend file extension.
  1541. std::string dependFileName = cmStrCat(
  1542. cmSystemTools::GetFilenameWithoutLastExtension(bmiFileName), ".d");
  1543. vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1544. cmStrCat(bmiFileDir, '/', dependFileName), cmOutputConverter::SHELL);
  1545. }
  1546. }
  1547. std::string d =
  1548. this->GeneratorTarget->GetClangTidyExportFixesDirectory(language);
  1549. if (!d.empty()) {
  1550. this->GlobalCommonGenerator->AddClangTidyExportFixesDir(d);
  1551. std::string fixesFile =
  1552. this->GetClangTidyReplacementsFilePath(d, *source, config);
  1553. this->GlobalCommonGenerator->AddClangTidyExportFixesFile(fixesFile);
  1554. cmSystemTools::MakeDirectory(cmSystemTools::GetFilenamePath(fixesFile));
  1555. fixesFile = this->ConvertToNinjaPath(fixesFile);
  1556. vars["CLANG_TIDY_EXPORT_FIXES"] = fixesFile;
  1557. }
  1558. if (firstForConfig) {
  1559. this->ExportObjectCompileCommand(
  1560. language, sourceFilePath, bmiDir, bmiFileName, bmiFileDir, vars["FLAGS"],
  1561. vars["DEFINES"], vars["INCLUDES"], config, WithScanning::Yes);
  1562. }
  1563. bmiBuild.Outputs.push_back(bmiFileName);
  1564. bmiBuild.ExplicitDeps.push_back(sourceFilePath);
  1565. std::vector<std::string> depList;
  1566. std::vector<std::string> architectures =
  1567. this->GeneratorTarget->GetAppleArchs(config, language);
  1568. if (architectures.empty()) {
  1569. architectures.emplace_back();
  1570. }
  1571. bmiBuild.OrderOnlyDeps.push_back(this->OrderDependsTargetForTarget(config));
  1572. // For some cases we scan to dynamically discover dependencies.
  1573. std::string modmapFormat;
  1574. if (true) {
  1575. std::string const modmapFormatVar =
  1576. cmStrCat("CMAKE_", language, "_MODULE_MAP_FORMAT");
  1577. modmapFormat = this->Makefile->GetSafeDefinition(modmapFormatVar);
  1578. }
  1579. {
  1580. bool const compilePPWithDefines = this->CompileWithDefines(language);
  1581. std::string scanRuleName = this->LanguageScanRule(language, config);
  1582. std::string ppFileName = cmStrCat(bmiFileName, ".ddi.i");
  1583. cmNinjaBuild ppBuild = GetScanBuildStatement(
  1584. scanRuleName, ppFileName, false, compilePPWithDefines, true, bmiBuild,
  1585. vars, bmiFileName, this->LocalGenerator);
  1586. ScanningFiles scanningFiles;
  1587. if (firstForConfig) {
  1588. scanningFiles.ScanningOutput = cmStrCat(bmiFileName, ".ddi");
  1589. }
  1590. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1591. ppBuild.Variables);
  1592. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1593. ppBuild, commandLineLengthLimit);
  1594. std::string const dyndep = this->GetDyndepFilePath(language, config);
  1595. bmiBuild.OrderOnlyDeps.push_back(dyndep);
  1596. vars["dyndep"] = dyndep;
  1597. if (!modmapFormat.empty()) {
  1598. std::string ddModmapFile = cmStrCat(bmiFileName, ".modmap");
  1599. vars["DYNDEP_MODULE_MAP_FILE"] = ddModmapFile;
  1600. scanningFiles.ModuleMapFile = std::move(ddModmapFile);
  1601. }
  1602. if (!scanningFiles.IsEmpty()) {
  1603. this->Configs[config].ScanningInfo[language].emplace_back(scanningFiles);
  1604. }
  1605. }
  1606. this->EnsureParentDirectoryExists(bmiFileName);
  1607. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1608. bmiDir, cmOutputConverter::SHELL);
  1609. vars["OBJECT_FILE_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1610. bmiFileDir, cmOutputConverter::SHELL);
  1611. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1612. vars);
  1613. this->SetMsvcTargetPdbVariable(vars, config);
  1614. bmiBuild.RspFile = cmStrCat(bmiFileName, ".rsp");
  1615. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1616. bmiBuild, commandLineLengthLimit);
  1617. }
  1618. void cmNinjaTargetGenerator::WriteTargetDependInfo(std::string const& lang,
  1619. const std::string& config)
  1620. {
  1621. Json::Value tdi(Json::objectValue);
  1622. tdi["language"] = lang;
  1623. tdi["compiler-id"] = this->Makefile->GetSafeDefinition(
  1624. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  1625. tdi["compiler-simulate-id"] = this->Makefile->GetSafeDefinition(
  1626. cmStrCat("CMAKE_", lang, "_SIMULATE_ID"));
  1627. tdi["compiler-frontend-variant"] = this->Makefile->GetSafeDefinition(
  1628. cmStrCat("CMAKE_", lang, "_COMPILER_FRONTEND_VARIANT"));
  1629. std::string mod_dir;
  1630. if (lang == "Fortran") {
  1631. mod_dir = this->GeneratorTarget->GetFortranModuleDirectory(
  1632. this->Makefile->GetHomeOutputDirectory());
  1633. } else if (lang == "CXX") {
  1634. mod_dir = this->GetGlobalGenerator()->ExpandCFGIntDir(
  1635. cmSystemTools::CollapseFullPath(this->GeneratorTarget->ObjectDirectory),
  1636. config);
  1637. }
  1638. if (mod_dir.empty()) {
  1639. mod_dir = this->Makefile->GetCurrentBinaryDirectory();
  1640. }
  1641. tdi["module-dir"] = mod_dir;
  1642. if (lang == "Fortran") {
  1643. tdi["submodule-sep"] =
  1644. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
  1645. tdi["submodule-ext"] =
  1646. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
  1647. } else if (lang == "CXX") {
  1648. // No extra information necessary.
  1649. }
  1650. tdi["dir-cur-bld"] = this->Makefile->GetCurrentBinaryDirectory();
  1651. tdi["dir-cur-src"] = this->Makefile->GetCurrentSourceDirectory();
  1652. tdi["dir-top-bld"] = this->Makefile->GetHomeOutputDirectory();
  1653. tdi["dir-top-src"] = this->Makefile->GetHomeDirectory();
  1654. Json::Value& tdi_include_dirs = tdi["include-dirs"] = Json::arrayValue;
  1655. std::vector<std::string> includes;
  1656. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  1657. lang, config);
  1658. for (std::string const& i : includes) {
  1659. // Convert the include directories the same way we do for -I flags.
  1660. // See upstream ninja issue 1251.
  1661. tdi_include_dirs.append(this->ConvertToNinjaPath(i));
  1662. }
  1663. Json::Value& tdi_linked_target_dirs = tdi["linked-target-dirs"] =
  1664. Json::arrayValue;
  1665. auto const linked_directories =
  1666. this->GetLinkedTargetDirectories(lang, config);
  1667. for (std::string const& l : linked_directories.Direct) {
  1668. tdi_linked_target_dirs.append(l);
  1669. }
  1670. Json::Value& tdi_forward_modules_from_target_dirs =
  1671. tdi["forward-modules-from-target-dirs"] = Json::arrayValue;
  1672. for (std::string const& l : linked_directories.Forward) {
  1673. tdi_forward_modules_from_target_dirs.append(l);
  1674. }
  1675. cmDyndepGeneratorCallbacks cb;
  1676. cb.ObjectFilePath = [this](cmSourceFile const* sf, std::string const& cnf) {
  1677. return this->GetObjectFilePath(sf, cnf);
  1678. };
  1679. cb.BmiFilePath = [this](cmSourceFile const* sf, std::string const& cnf) {
  1680. return this->GetBmiFilePath(sf, cnf);
  1681. };
  1682. #if !defined(CMAKE_BOOTSTRAP)
  1683. cmDyndepCollation::AddCollationInformation(tdi, this->GeneratorTarget,
  1684. config, cb);
  1685. #endif
  1686. std::string const tdin = this->GetTargetDependInfoPath(lang, config);
  1687. cmGeneratedFileStream tdif(tdin);
  1688. tdif << tdi;
  1689. }
  1690. void cmNinjaTargetGenerator::EmitSwiftDependencyInfo(
  1691. cmSourceFile const* source, const std::string& config)
  1692. {
  1693. std::string const sourceFilePath = this->GetCompiledSourceNinjaPath(source);
  1694. std::string const objectFilePath =
  1695. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1696. std::string const swiftDepsPath = [source, objectFilePath]() -> std::string {
  1697. if (cmValue name = source->GetProperty("Swift_DEPENDENCIES_FILE")) {
  1698. return *name;
  1699. }
  1700. return cmStrCat(objectFilePath, ".swiftdeps");
  1701. }();
  1702. std::string const swiftDiaPath = [source, objectFilePath]() -> std::string {
  1703. if (cmValue name = source->GetProperty("Swift_DIAGNOSTICS_FILE")) {
  1704. return *name;
  1705. }
  1706. return cmStrCat(objectFilePath, ".dia");
  1707. }();
  1708. std::string const makeDepsPath = [this, source, config]() -> std::string {
  1709. cmLocalNinjaGenerator const* local = this->GetLocalGenerator();
  1710. std::string const objectFileName =
  1711. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1712. std::string const objectFileDir =
  1713. cmSystemTools::GetFilenamePath(objectFileName);
  1714. if (this->Makefile->IsOn("CMAKE_Swift_DEPFLE_EXTNSION_REPLACE")) {
  1715. std::string dependFileName = cmStrCat(
  1716. cmSystemTools::GetFilenameWithoutLastExtension(objectFileName), ".d");
  1717. return local->ConvertToOutputFormat(
  1718. cmStrCat(objectFileDir, '/', dependFileName),
  1719. cmOutputConverter::SHELL);
  1720. }
  1721. return local->ConvertToOutputFormat(cmStrCat(objectFileName, ".d"),
  1722. cmOutputConverter::SHELL);
  1723. }();
  1724. // build the source file mapping
  1725. // https://github.com/apple/swift/blob/master/docs/Driver.md#output-file-maps
  1726. Json::Value entry = Json::Value(Json::objectValue);
  1727. entry["object"] = objectFilePath;
  1728. entry["dependencies"] = makeDepsPath;
  1729. entry["swift-dependencies"] = swiftDepsPath;
  1730. entry["diagnostics"] = swiftDiaPath;
  1731. this->Configs[config].SwiftOutputMap[sourceFilePath] = entry;
  1732. }
  1733. void cmNinjaTargetGenerator::ExportObjectCompileCommand(
  1734. std::string const& language, std::string const& sourceFileName,
  1735. std::string const& objectDir, std::string const& objectFileName,
  1736. std::string const& objectFileDir, std::string const& flags,
  1737. std::string const& defines, std::string const& includes,
  1738. std::string const& outputConfig, WithScanning withScanning)
  1739. {
  1740. if (!this->GeneratorTarget->GetPropertyAsBool("EXPORT_COMPILE_COMMANDS")) {
  1741. return;
  1742. }
  1743. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  1744. compileObjectVars.Language = language.c_str();
  1745. std::string escapedSourceFileName = sourceFileName;
  1746. if (!cmSystemTools::FileIsFullPath(sourceFileName)) {
  1747. escapedSourceFileName =
  1748. cmSystemTools::CollapseFullPath(escapedSourceFileName,
  1749. this->GetGlobalGenerator()
  1750. ->GetCMakeInstance()
  1751. ->GetHomeOutputDirectory());
  1752. }
  1753. escapedSourceFileName = this->LocalGenerator->ConvertToOutputFormat(
  1754. escapedSourceFileName, cmOutputConverter::SHELL);
  1755. std::string fullFlags = flags;
  1756. if (withScanning == WithScanning::Yes) {
  1757. std::string const modmapFormatVar =
  1758. cmStrCat("CMAKE_", language, "_MODULE_MAP_FORMAT");
  1759. std::string const modmapFormat =
  1760. this->Makefile->GetSafeDefinition(modmapFormatVar);
  1761. if (!modmapFormat.empty()) {
  1762. std::string modmapFlags = this->GetMakefile()->GetRequiredDefinition(
  1763. cmStrCat("CMAKE_", language, "_MODULE_MAP_FLAG"));
  1764. // XXX(modmap): If changing this path construction, change
  1765. // `cmGlobalNinjaGenerator::WriteDyndep` and
  1766. // `cmNinjaTargetGenerator::WriteObjectBuildStatement` to expect the
  1767. // corresponding file path.
  1768. cmSystemTools::ReplaceString(modmapFlags, "<MODULE_MAP_FILE>",
  1769. cmStrCat(objectFileName, ".modmap"));
  1770. fullFlags += cmStrCat(' ', modmapFlags);
  1771. }
  1772. }
  1773. compileObjectVars.Source = escapedSourceFileName.c_str();
  1774. compileObjectVars.Object = objectFileName.c_str();
  1775. compileObjectVars.ObjectDir = objectDir.c_str();
  1776. compileObjectVars.ObjectFileDir = objectFileDir.c_str();
  1777. compileObjectVars.Flags = fullFlags.c_str();
  1778. compileObjectVars.Defines = defines.c_str();
  1779. compileObjectVars.Includes = includes.c_str();
  1780. // Rule for compiling object file.
  1781. std::string cudaCompileMode;
  1782. if (language == "CUDA") {
  1783. if (this->GeneratorTarget->GetPropertyAsBool(
  1784. "CUDA_SEPARABLE_COMPILATION")) {
  1785. const std::string& rdcFlag =
  1786. this->Makefile->GetRequiredDefinition("_CMAKE_CUDA_RDC_FLAG");
  1787. cudaCompileMode = cmStrCat(cudaCompileMode, rdcFlag, " ");
  1788. }
  1789. static std::array<cm::string_view, 4> const compileModes{
  1790. { "PTX"_s, "CUBIN"_s, "FATBIN"_s, "OPTIX"_s }
  1791. };
  1792. bool useNormalCompileMode = true;
  1793. for (cm::string_view mode : compileModes) {
  1794. auto propName = cmStrCat("CUDA_", mode, "_COMPILATION");
  1795. auto defName = cmStrCat("_CMAKE_CUDA_", mode, "_FLAG");
  1796. if (this->GeneratorTarget->GetPropertyAsBool(propName)) {
  1797. const std::string& flag =
  1798. this->Makefile->GetRequiredDefinition(defName);
  1799. cudaCompileMode = cmStrCat(cudaCompileMode, flag);
  1800. useNormalCompileMode = false;
  1801. break;
  1802. }
  1803. }
  1804. if (useNormalCompileMode) {
  1805. const std::string& wholeFlag =
  1806. this->Makefile->GetRequiredDefinition("_CMAKE_CUDA_WHOLE_FLAG");
  1807. cudaCompileMode = cmStrCat(cudaCompileMode, wholeFlag);
  1808. }
  1809. compileObjectVars.CudaCompileMode = cudaCompileMode.c_str();
  1810. }
  1811. const std::string cmdVar = cmStrCat("CMAKE_", language, "_COMPILE_OBJECT");
  1812. const std::string& compileCmd =
  1813. this->Makefile->GetRequiredDefinition(cmdVar);
  1814. cmList compileCmds(compileCmd);
  1815. auto rulePlaceholderExpander =
  1816. this->GetLocalGenerator()->CreateRulePlaceholderExpander();
  1817. for (auto& i : compileCmds) {
  1818. // no launcher for CMAKE_EXPORT_COMPILE_COMMANDS
  1819. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  1820. compileObjectVars);
  1821. }
  1822. std::string cmdLine = this->GetLocalGenerator()->BuildCommandLine(
  1823. compileCmds, outputConfig, outputConfig);
  1824. this->GetGlobalGenerator()->AddCXXCompileCommand(cmdLine, sourceFileName,
  1825. objectFileName);
  1826. }
  1827. void cmNinjaTargetGenerator::AdditionalCleanFiles(const std::string& config)
  1828. {
  1829. if (cmValue prop_value =
  1830. this->GeneratorTarget->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  1831. cmLocalNinjaGenerator* lg = this->LocalGenerator;
  1832. cmList cleanFiles(cmGeneratorExpression::Evaluate(*prop_value, lg, config,
  1833. this->GeneratorTarget));
  1834. std::string const& binaryDir = lg->GetCurrentBinaryDirectory();
  1835. cmGlobalNinjaGenerator* gg = lg->GetGlobalNinjaGenerator();
  1836. for (auto const& cleanFile : cleanFiles) {
  1837. // Support relative paths
  1838. gg->AddAdditionalCleanFile(
  1839. cmSystemTools::CollapseFullPath(cleanFile, binaryDir), config);
  1840. }
  1841. }
  1842. }
  1843. cmNinjaDeps cmNinjaTargetGenerator::GetObjects(const std::string& config) const
  1844. {
  1845. auto const it = this->Configs.find(config);
  1846. if (it != this->Configs.end()) {
  1847. return it->second.Objects;
  1848. }
  1849. return {};
  1850. }
  1851. void cmNinjaTargetGenerator::EnsureDirectoryExists(
  1852. const std::string& path) const
  1853. {
  1854. if (cmSystemTools::FileIsFullPath(path)) {
  1855. cmSystemTools::MakeDirectory(path);
  1856. } else {
  1857. cmGlobalNinjaGenerator* gg = this->GetGlobalGenerator();
  1858. std::string fullPath = gg->GetCMakeInstance()->GetHomeOutputDirectory();
  1859. // Also ensures there is a trailing slash.
  1860. gg->StripNinjaOutputPathPrefixAsSuffix(fullPath);
  1861. fullPath += path;
  1862. cmSystemTools::MakeDirectory(fullPath);
  1863. }
  1864. }
  1865. void cmNinjaTargetGenerator::EnsureParentDirectoryExists(
  1866. const std::string& path) const
  1867. {
  1868. this->EnsureDirectoryExists(cmSystemTools::GetParentDirectory(path));
  1869. }
  1870. void cmNinjaTargetGenerator::MacOSXContentGeneratorType::operator()(
  1871. cmSourceFile const& source, const char* pkgloc, const std::string& config)
  1872. {
  1873. // Skip OS X content when not building a Framework or Bundle.
  1874. if (!this->Generator->GetGeneratorTarget()->IsBundleOnApple()) {
  1875. return;
  1876. }
  1877. std::string macdir =
  1878. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(pkgloc,
  1879. config);
  1880. // Reject files that collide with files from the Ninja file's native config.
  1881. if (config != this->FileConfig) {
  1882. std::string nativeMacdir =
  1883. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(
  1884. pkgloc, this->FileConfig);
  1885. if (macdir == nativeMacdir) {
  1886. return;
  1887. }
  1888. }
  1889. // Get the input file location.
  1890. std::string input = source.GetFullPath();
  1891. input = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(input);
  1892. // Get the output file location.
  1893. std::string output =
  1894. cmStrCat(macdir, '/', cmSystemTools::GetFilenameName(input));
  1895. output = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(output);
  1896. // Write a build statement to copy the content into the bundle.
  1897. this->Generator->GetGlobalGenerator()->WriteMacOSXContentBuild(
  1898. input, output, this->FileConfig);
  1899. // Add as a dependency to the target so that it gets called.
  1900. this->Generator->Configs[config].ExtraFiles.push_back(std::move(output));
  1901. }
  1902. void cmNinjaTargetGenerator::addPoolNinjaVariable(
  1903. const std::string& pool_property, cmGeneratorTarget* target,
  1904. cmNinjaVars& vars)
  1905. {
  1906. cmValue pool = target->GetProperty(pool_property);
  1907. if (pool) {
  1908. vars["pool"] = *pool;
  1909. }
  1910. }
  1911. bool cmNinjaTargetGenerator::ForceResponseFile()
  1912. {
  1913. static std::string const forceRspFile = "CMAKE_NINJA_FORCE_RESPONSE_FILE";
  1914. return (this->GetMakefile()->IsDefinitionSet(forceRspFile) ||
  1915. cmSystemTools::HasEnv(forceRspFile));
  1916. }