cmNinjaTargetGenerator.cxx 66 KB

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