cmNinjaTargetGenerator.cxx 80 KB

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