cmNinjaNormalTargetGenerator.cxx 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst or https://cmake.org/licensing for details. */
  3. #include "cmNinjaNormalTargetGenerator.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <iterator>
  7. #include <set>
  8. #include <sstream>
  9. #include <unordered_set>
  10. #include <utility>
  11. #include <cm/memory>
  12. #include <cm/optional>
  13. #include <cm/vector>
  14. #include "cmComputeLinkInformation.h"
  15. #include "cmCustomCommand.h" // IWYU pragma: keep
  16. #include "cmCustomCommandGenerator.h"
  17. #include "cmGeneratedFileStream.h"
  18. #include "cmGeneratorExpression.h"
  19. #include "cmGeneratorOptions.h"
  20. #include "cmGeneratorTarget.h"
  21. #include "cmGlobalNinjaGenerator.h"
  22. #include "cmLinkLineComputer.h"
  23. #include "cmLinkLineDeviceComputer.h"
  24. #include "cmList.h"
  25. #include "cmLocalCommonGenerator.h"
  26. #include "cmLocalGenerator.h"
  27. #include "cmLocalNinjaGenerator.h"
  28. #include "cmMakefile.h"
  29. #include "cmMessageType.h"
  30. #include "cmNinjaLinkLineDeviceComputer.h"
  31. #include "cmNinjaTypes.h"
  32. #include "cmOSXBundleGenerator.h"
  33. #include "cmOutputConverter.h"
  34. #include "cmRulePlaceholderExpander.h"
  35. #include "cmSourceFile.h"
  36. #include "cmState.h"
  37. #include "cmStateDirectory.h"
  38. #include "cmStateSnapshot.h"
  39. #include "cmStateTypes.h"
  40. #include "cmStringAlgorithms.h"
  41. #include "cmSystemTools.h"
  42. #include "cmValue.h"
  43. cmNinjaNormalTargetGenerator::cmNinjaNormalTargetGenerator(
  44. cmGeneratorTarget* target)
  45. : cmNinjaTargetGenerator(target)
  46. {
  47. if (target->GetType() != cmStateEnums::OBJECT_LIBRARY) {
  48. // on Windows the output dir is already needed at compile time
  49. // ensure the directory exists (OutDir test)
  50. for (auto const& config : this->GetConfigNames()) {
  51. this->EnsureDirectoryExists(target->GetDirectory(config));
  52. }
  53. }
  54. this->OSXBundleGenerator = cm::make_unique<cmOSXBundleGenerator>(target);
  55. this->OSXBundleGenerator->SetMacContentFolders(&this->MacContentFolders);
  56. }
  57. cmNinjaNormalTargetGenerator::~cmNinjaNormalTargetGenerator() = default;
  58. void cmNinjaNormalTargetGenerator::Generate(std::string const& config)
  59. {
  60. if (this->GetGeneratorTarget()->GetType() !=
  61. cmStateEnums::INTERFACE_LIBRARY) {
  62. std::string lang = this->GeneratorTarget->GetLinkerLanguage(config);
  63. if (this->TargetLinkLanguage(config).empty()) {
  64. cmSystemTools::Error(
  65. cmStrCat("CMake can not determine linker language for target: ",
  66. this->GetGeneratorTarget()->GetName()));
  67. return;
  68. }
  69. }
  70. // Write the rules for each language.
  71. this->WriteLanguagesRules(config);
  72. // Write the build statements
  73. bool firstForConfig = true;
  74. for (auto const& fileConfig : this->GetConfigNames()) {
  75. if (!this->GetGlobalGenerator()
  76. ->GetCrossConfigs(fileConfig)
  77. .count(config)) {
  78. continue;
  79. }
  80. this->WriteObjectBuildStatements(config, fileConfig, firstForConfig);
  81. firstForConfig = false;
  82. }
  83. if (this->GetGeneratorTarget()->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  84. this->WriteObjectLibStatement(config);
  85. } else if (this->GetGeneratorTarget()->GetType() ==
  86. cmStateEnums::INTERFACE_LIBRARY) {
  87. bool haveCxxModuleSources = false;
  88. if (this->GetGeneratorTarget()->HaveCxx20ModuleSources()) {
  89. haveCxxModuleSources = true;
  90. }
  91. if (!haveCxxModuleSources) {
  92. cmSystemTools::Error(cmStrCat(
  93. "Ninja does not support INTERFACE libraries without C++ module "
  94. "sources as a normal target: ",
  95. this->GetGeneratorTarget()->GetName()));
  96. return;
  97. }
  98. firstForConfig = true;
  99. for (auto const& fileConfig : this->GetConfigNames()) {
  100. if (!this->GetGlobalGenerator()
  101. ->GetCrossConfigs(fileConfig)
  102. .count(config)) {
  103. continue;
  104. }
  105. if (haveCxxModuleSources) {
  106. this->WriteCxxModuleLibraryStatement(config, fileConfig,
  107. firstForConfig);
  108. }
  109. firstForConfig = false;
  110. }
  111. } else {
  112. firstForConfig = true;
  113. for (auto const& fileConfig : this->GetConfigNames()) {
  114. if (!this->GetGlobalGenerator()
  115. ->GetCrossConfigs(fileConfig)
  116. .count(config)) {
  117. continue;
  118. }
  119. // If this target has cuda language link inputs, and we need to do
  120. // device linking
  121. this->WriteDeviceLinkStatement(config, fileConfig, firstForConfig);
  122. this->WriteLinkStatement(config, fileConfig, firstForConfig);
  123. firstForConfig = false;
  124. }
  125. }
  126. if (this->GetGlobalGenerator()->EnableCrossConfigBuild()) {
  127. this->GetGlobalGenerator()->AddTargetAlias(
  128. this->GetTargetName(), this->GetGeneratorTarget(), "all");
  129. }
  130. // Find ADDITIONAL_CLEAN_FILES
  131. this->AdditionalCleanFiles(config);
  132. }
  133. void cmNinjaNormalTargetGenerator::WriteLanguagesRules(
  134. std::string const& config)
  135. {
  136. #ifdef NINJA_GEN_VERBOSE_FILES
  137. cmGlobalNinjaGenerator::WriteDivider(this->GetRulesFileStream());
  138. this->GetRulesFileStream()
  139. << "# Rules for each language for "
  140. << cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType())
  141. << " target " << this->GetTargetName() << "\n\n";
  142. #endif
  143. // Write rules for languages compiled in this target.
  144. {
  145. std::set<std::string> languages;
  146. std::vector<cmSourceFile const*> sourceFiles;
  147. this->GetGeneratorTarget()->GetObjectSources(sourceFiles, config);
  148. if (this->HaveRequiredLanguages(sourceFiles, languages)) {
  149. for (std::string const& language : languages) {
  150. this->WriteLanguageRules(language, config);
  151. }
  152. }
  153. }
  154. // Write rules for languages in BMI-only rules.
  155. {
  156. std::set<std::string> languages;
  157. std::vector<cmSourceFile const*> sourceFiles;
  158. this->GetGeneratorTarget()->GetCxxModuleSources(sourceFiles, config);
  159. if (this->HaveRequiredLanguages(sourceFiles, languages)) {
  160. for (std::string const& language : languages) {
  161. this->WriteLanguageRules(language, config);
  162. }
  163. }
  164. }
  165. }
  166. char const* cmNinjaNormalTargetGenerator::GetVisibleTypeName() const
  167. {
  168. switch (this->GetGeneratorTarget()->GetType()) {
  169. case cmStateEnums::STATIC_LIBRARY:
  170. return "static library";
  171. case cmStateEnums::SHARED_LIBRARY:
  172. return "shared library";
  173. case cmStateEnums::MODULE_LIBRARY:
  174. if (this->GetGeneratorTarget()->IsCFBundleOnApple()) {
  175. return "CFBundle shared module";
  176. } else {
  177. return "shared module";
  178. }
  179. case cmStateEnums::EXECUTABLE:
  180. return "executable";
  181. default:
  182. return nullptr;
  183. }
  184. }
  185. std::string cmNinjaNormalTargetGenerator::LanguageLinkerRule(
  186. std::string const& config) const
  187. {
  188. return cmStrCat(
  189. this->TargetLinkLanguage(config), "_",
  190. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()),
  191. "_LINKER__",
  192. cmGlobalNinjaGenerator::EncodeRuleName(
  193. this->GetGeneratorTarget()->GetName()),
  194. "_", config);
  195. }
  196. std::string cmNinjaNormalTargetGenerator::LanguageLinkerDeviceRule(
  197. std::string const& config) const
  198. {
  199. return cmStrCat(
  200. this->TargetLinkLanguage(config), "_",
  201. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()),
  202. "_DEVICE_LINKER__",
  203. cmGlobalNinjaGenerator::EncodeRuleName(
  204. this->GetGeneratorTarget()->GetName()),
  205. "_", config);
  206. }
  207. std::string cmNinjaNormalTargetGenerator::LanguageLinkerCudaDeviceRule(
  208. std::string const& config) const
  209. {
  210. return cmStrCat(
  211. this->TargetLinkLanguage(config), "_DEVICE_LINK__",
  212. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  213. '_', config);
  214. }
  215. std::string cmNinjaNormalTargetGenerator::LanguageLinkerCudaDeviceCompileRule(
  216. std::string const& config) const
  217. {
  218. return cmStrCat(
  219. this->TargetLinkLanguage(config), "_DEVICE_LINK_COMPILE__",
  220. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  221. '_', config);
  222. }
  223. std::string cmNinjaNormalTargetGenerator::LanguageLinkerCudaFatbinaryRule(
  224. std::string const& config) const
  225. {
  226. return cmStrCat(
  227. this->TargetLinkLanguage(config), "_FATBINARY__",
  228. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  229. '_', config);
  230. }
  231. std::string cmNinjaNormalTargetGenerator::TextStubsGeneratorRule(
  232. std::string const& config) const
  233. {
  234. return cmStrCat(
  235. "TEXT_STUBS_GENERATOR__",
  236. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  237. '_', config);
  238. }
  239. bool cmNinjaNormalTargetGenerator::CheckUseResponseFileForLibraries(
  240. std::string const& l) const
  241. {
  242. // Check for an explicit setting one way or the other.
  243. std::string const responseVar =
  244. "CMAKE_" + l + "_USE_RESPONSE_FILE_FOR_LIBRARIES";
  245. // If the option is defined, read it's value
  246. if (cmValue val = this->Makefile->GetDefinition(responseVar)) {
  247. return val.IsOn();
  248. }
  249. // Default to true
  250. return true;
  251. }
  252. struct cmNinjaRemoveNoOpCommands
  253. {
  254. bool operator()(std::string const& cmd)
  255. {
  256. return cmd.empty() || cmd[0] == ':';
  257. }
  258. };
  259. void cmNinjaNormalTargetGenerator::WriteNvidiaDeviceLinkRule(
  260. bool useResponseFile, std::string const& config)
  261. {
  262. cmNinjaRule rule(this->LanguageLinkerDeviceRule(config));
  263. if (!this->GetGlobalGenerator()->HasRule(rule.Name)) {
  264. cmRulePlaceholderExpander::RuleVariables vars;
  265. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  266. vars.CMTargetType =
  267. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType())
  268. .c_str();
  269. vars.CMTargetLabels =
  270. this->GetGeneratorTarget()->GetTargetLabelsString().c_str();
  271. vars.Language = "CUDA";
  272. std::string linker =
  273. this->GetGeneratorTarget()->GetLinkerTool("CUDA", config);
  274. vars.Linker = linker.c_str();
  275. // build response file name
  276. std::string responseFlag = this->GetMakefile()->GetSafeDefinition(
  277. "CMAKE_CUDA_RESPONSE_FILE_DEVICE_LINK_FLAG");
  278. if (!useResponseFile || responseFlag.empty()) {
  279. vars.Objects = "$in";
  280. vars.LinkLibraries = "$LINK_PATH $LINK_LIBRARIES";
  281. } else {
  282. rule.RspFile = "$RSP_FILE";
  283. responseFlag += rule.RspFile;
  284. // build response file content
  285. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  286. rule.RspContent = "$in";
  287. } else {
  288. rule.RspContent = "$in_newline";
  289. }
  290. // add the link command in the file if necessary
  291. if (this->CheckUseResponseFileForLibraries("CUDA")) {
  292. rule.RspContent += " $LINK_LIBRARIES";
  293. vars.LinkLibraries = "";
  294. } else {
  295. vars.LinkLibraries = "$LINK_PATH $LINK_LIBRARIES";
  296. }
  297. vars.Objects = responseFlag.c_str();
  298. }
  299. vars.ObjectDir = "$OBJECT_DIR";
  300. vars.Target = "$TARGET_FILE";
  301. vars.SONameFlag = "$SONAME_FLAG";
  302. vars.TargetSOName = "$SONAME";
  303. vars.TargetPDB = "$TARGET_PDB";
  304. vars.TargetCompilePDB = "$TARGET_COMPILE_PDB";
  305. vars.Flags = "$FLAGS";
  306. vars.LinkFlags = "$LINK_FLAGS";
  307. vars.Manifests = "$MANIFESTS";
  308. vars.Config = "$CONFIG";
  309. vars.LanguageCompileFlags = "$LANGUAGE_COMPILE_FLAGS";
  310. std::string launcher;
  311. std::string val = this->GetLocalGenerator()->GetRuleLauncher(
  312. this->GetGeneratorTarget(), "RULE_LAUNCH_LINK", config);
  313. if (cmNonempty(val)) {
  314. launcher = cmStrCat(val, ' ');
  315. }
  316. auto rulePlaceholderExpander =
  317. this->GetLocalGenerator()->CreateRulePlaceholderExpander(
  318. cmBuildStep::Link, this->GetGeneratorTarget(),
  319. this->TargetLinkLanguage(config));
  320. // Rule for linking library/executable.
  321. std::vector<std::string> linkCmds = this->ComputeDeviceLinkCmd();
  322. for (std::string& linkCmd : linkCmds) {
  323. linkCmd = cmStrCat(launcher, linkCmd);
  324. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  325. linkCmd, vars);
  326. }
  327. // If there is no ranlib the command will be ":". Skip it.
  328. cm::erase_if(linkCmds, cmNinjaRemoveNoOpCommands());
  329. rule.Command =
  330. this->GetLocalGenerator()->BuildCommandLine(linkCmds, config, config);
  331. // Write the linker rule with response file if needed.
  332. rule.Comment =
  333. cmStrCat("Rule for linking ", this->TargetLinkLanguage(config), ' ',
  334. this->GetVisibleTypeName(), '.');
  335. rule.Description =
  336. cmStrCat("Linking ", this->TargetLinkLanguage(config), ' ',
  337. this->GetVisibleTypeName(), " $TARGET_FILE");
  338. rule.Restat = "$RESTAT";
  339. this->GetGlobalGenerator()->AddRule(rule);
  340. }
  341. }
  342. void cmNinjaNormalTargetGenerator::WriteDeviceLinkRules(
  343. std::string const& config)
  344. {
  345. cmMakefile const* mf = this->GetMakefile();
  346. cmNinjaRule rule(this->LanguageLinkerCudaDeviceRule(config));
  347. rule.Command = this->GetLocalGenerator()->BuildCommandLine(
  348. { cmStrCat(mf->GetRequiredDefinition("CMAKE_CUDA_DEVICE_LINKER"),
  349. " -arch=$ARCH $REGISTER -o=$out $in") },
  350. config, config);
  351. rule.Comment = "Rule for CUDA device linking.";
  352. rule.Description = "Linking CUDA $out";
  353. this->GetGlobalGenerator()->AddRule(rule);
  354. cmRulePlaceholderExpander::RuleVariables vars;
  355. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  356. vars.CMTargetType =
  357. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()).c_str();
  358. vars.CMTargetLabels =
  359. this->GetGeneratorTarget()->GetTargetLabelsString().c_str();
  360. vars.Language = "CUDA";
  361. vars.Object = "$out";
  362. vars.Fatbinary = "$FATBIN";
  363. vars.RegisterFile = "$REGISTER";
  364. vars.LinkFlags = "$LINK_FLAGS";
  365. std::string linker =
  366. this->GetGeneratorTarget()->GetLinkerTool("CUDA", config);
  367. vars.Linker = linker.c_str();
  368. std::string flags = this->GetFlags("CUDA", config);
  369. vars.Flags = flags.c_str();
  370. vars.Config = "$CONFIG";
  371. std::string compileCmd = this->GetMakefile()->GetRequiredDefinition(
  372. "CMAKE_CUDA_DEVICE_LINK_COMPILE");
  373. auto rulePlaceholderExpander =
  374. this->GetLocalGenerator()->CreateRulePlaceholderExpander(
  375. cmBuildStep::Link, this->GetGeneratorTarget(),
  376. this->TargetLinkLanguage(config));
  377. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  378. compileCmd, vars);
  379. rule.Name = this->LanguageLinkerCudaDeviceCompileRule(config);
  380. rule.Command = this->GetLocalGenerator()->BuildCommandLine({ compileCmd },
  381. config, config);
  382. rule.Comment = "Rule for compiling CUDA device stubs.";
  383. rule.Description = "Compiling CUDA device stub $out";
  384. this->GetGlobalGenerator()->AddRule(rule);
  385. rule.Name = this->LanguageLinkerCudaFatbinaryRule(config);
  386. rule.Command = this->GetLocalGenerator()->BuildCommandLine(
  387. { cmStrCat(mf->GetRequiredDefinition("CMAKE_CUDA_FATBINARY"),
  388. " -64 -cmdline=--compile-only -compress-all -link "
  389. "--embedded-fatbin=$out $PROFILES") },
  390. config, config);
  391. rule.Comment = "Rule for CUDA fatbinaries.";
  392. rule.Description = "Creating fatbinary $out";
  393. this->GetGlobalGenerator()->AddRule(rule);
  394. }
  395. void cmNinjaNormalTargetGenerator::WriteLinkRule(
  396. bool useResponseFile, std::string const& config,
  397. std::vector<std::string> const& preLinkComments,
  398. std::vector<std::string> const& postBuildComments)
  399. {
  400. cmStateEnums::TargetType targetType = this->GetGeneratorTarget()->GetType();
  401. std::string linkRuleName = this->LanguageLinkerRule(config);
  402. if (!this->GetGlobalGenerator()->HasRule(linkRuleName)) {
  403. cmNinjaRule rule(std::move(linkRuleName));
  404. cmRulePlaceholderExpander::RuleVariables vars;
  405. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  406. vars.CMTargetType = cmState::GetTargetTypeName(targetType).c_str();
  407. vars.CMTargetLabels =
  408. this->GetGeneratorTarget()->GetTargetLabelsString().c_str();
  409. std::string linker = this->GetGeneratorTarget()->GetLinkerTool(config);
  410. vars.Linker = linker.c_str();
  411. std::string lang = this->TargetLinkLanguage(config);
  412. vars.Language = lang.c_str();
  413. vars.AIXExports = "$AIX_EXPORTS";
  414. if (!this->GetLocalGenerator()->IsSplitSwiftBuild() &&
  415. this->TargetLinkLanguage(config) == "Swift") {
  416. vars.SwiftLibraryName = "$SWIFT_LIBRARY_NAME";
  417. vars.SwiftModule = "$SWIFT_MODULE";
  418. vars.SwiftModuleName = "$SWIFT_MODULE_NAME";
  419. vars.SwiftSources = "$SWIFT_SOURCES";
  420. vars.Defines = "$DEFINES";
  421. vars.Flags = "$FLAGS";
  422. vars.Includes = "$INCLUDES";
  423. }
  424. std::string responseFlag;
  425. std::string cmakeVarLang =
  426. cmStrCat("CMAKE_", this->TargetLinkLanguage(config));
  427. if (this->GeneratorTarget->HasLinkDependencyFile(config)) {
  428. auto DepFileFormat = this->GetMakefile()->GetDefinition(
  429. cmStrCat(cmakeVarLang, "_LINKER_DEPFILE_FORMAT"));
  430. rule.DepType = DepFileFormat;
  431. rule.DepFile = "$DEP_FILE";
  432. }
  433. // build response file name
  434. std::string cmakeLinkVar = cmakeVarLang + "_RESPONSE_FILE_LINK_FLAG";
  435. cmValue flag = this->GetMakefile()->GetDefinition(cmakeLinkVar);
  436. if (flag) {
  437. responseFlag = *flag;
  438. } else {
  439. responseFlag = "@";
  440. }
  441. if (!useResponseFile || responseFlag.empty()) {
  442. vars.Objects = "$in";
  443. vars.LinkLibraries = "$LINK_PATH $LINK_LIBRARIES";
  444. } else {
  445. rule.RspFile = "$RSP_FILE";
  446. responseFlag += rule.RspFile;
  447. // build response file content
  448. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  449. rule.RspContent = "$in";
  450. } else {
  451. rule.RspContent = "$in_newline";
  452. }
  453. // If libraries in rsp is enable
  454. if (this->CheckUseResponseFileForLibraries(lang)) {
  455. rule.RspContent += " $LINK_PATH $LINK_LIBRARIES";
  456. vars.LinkLibraries = "";
  457. } else {
  458. vars.LinkLibraries = "$LINK_PATH $LINK_LIBRARIES";
  459. }
  460. if (!this->GetLocalGenerator()->IsSplitSwiftBuild() &&
  461. this->TargetLinkLanguage(config) == "Swift") {
  462. vars.SwiftSources = responseFlag.c_str();
  463. } else {
  464. vars.Objects = responseFlag.c_str();
  465. }
  466. }
  467. vars.ObjectDir = "$OBJECT_DIR";
  468. vars.Target = "$TARGET_FILE";
  469. vars.SONameFlag = "$SONAME_FLAG";
  470. vars.TargetSOName = "$SONAME";
  471. vars.TargetInstallNameDir = "$INSTALLNAME_DIR";
  472. vars.TargetPDB = "$TARGET_PDB";
  473. // Setup the target version.
  474. std::string targetVersionMajor;
  475. std::string targetVersionMinor;
  476. {
  477. std::ostringstream majorStream;
  478. std::ostringstream minorStream;
  479. int major;
  480. int minor;
  481. this->GetGeneratorTarget()->GetTargetVersion(major, minor);
  482. majorStream << major;
  483. minorStream << minor;
  484. targetVersionMajor = majorStream.str();
  485. targetVersionMinor = minorStream.str();
  486. }
  487. vars.TargetVersionMajor = targetVersionMajor.c_str();
  488. vars.TargetVersionMinor = targetVersionMinor.c_str();
  489. vars.Flags = "$FLAGS";
  490. vars.LinkFlags = "$LINK_FLAGS";
  491. vars.Manifests = "$MANIFESTS";
  492. vars.Config = "$CONFIG";
  493. std::string langFlags;
  494. if (targetType != cmStateEnums::EXECUTABLE) {
  495. langFlags += "$LANGUAGE_COMPILE_FLAGS $ARCH_FLAGS";
  496. vars.LanguageCompileFlags = langFlags.c_str();
  497. }
  498. std::string linkerLauncher = this->GetLinkerLauncher(config);
  499. if (cmNonempty(linkerLauncher)) {
  500. vars.Launcher = linkerLauncher.c_str();
  501. }
  502. std::string launcher;
  503. std::string val = this->GetLocalGenerator()->GetRuleLauncher(
  504. this->GetGeneratorTarget(), "RULE_LAUNCH_LINK", config);
  505. if (cmNonempty(val)) {
  506. launcher = cmStrCat(val, ' ');
  507. }
  508. auto rulePlaceholderExpander =
  509. this->GetLocalGenerator()->CreateRulePlaceholderExpander(
  510. cmBuildStep::Link, this->GetGeneratorTarget(),
  511. this->TargetLinkLanguage(config));
  512. // Rule for linking library/executable.
  513. std::vector<std::string> linkCmds = this->ComputeLinkCmd(config);
  514. for (std::string& linkCmd : linkCmds) {
  515. linkCmd = cmStrCat(launcher, linkCmd);
  516. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  517. linkCmd, vars);
  518. }
  519. // If there is no ranlib the command will be ":". Skip it.
  520. cm::erase_if(linkCmds, cmNinjaRemoveNoOpCommands());
  521. linkCmds.insert(linkCmds.begin(), "$PRE_LINK");
  522. linkCmds.emplace_back("$POST_BUILD");
  523. rule.Command =
  524. this->GetLocalGenerator()->BuildCommandLine(linkCmds, config, config);
  525. // Write the linker rule with response file if needed.
  526. rule.Comment =
  527. cmStrCat("Rule for linking ", this->TargetLinkLanguage(config), ' ',
  528. this->GetVisibleTypeName(), '.');
  529. char const* presep = "";
  530. char const* postsep = "";
  531. auto prelink = cmJoin(preLinkComments, "; ");
  532. if (!prelink.empty()) {
  533. presep = "; ";
  534. }
  535. auto postbuild = cmJoin(postBuildComments, "; ");
  536. if (!postbuild.empty()) {
  537. postsep = "; ";
  538. }
  539. rule.Description = cmStrCat(
  540. prelink, presep, "Linking ", this->TargetLinkLanguage(config), ' ',
  541. this->GetVisibleTypeName(), " $TARGET_FILE", postsep, postbuild);
  542. rule.Restat = "$RESTAT";
  543. this->GetGlobalGenerator()->AddRule(rule);
  544. }
  545. auto const tgtNames = this->TargetNames(config);
  546. if (tgtNames.Output != tgtNames.Real &&
  547. !this->GetGeneratorTarget()->IsFrameworkOnApple()) {
  548. std::string cmakeCommand =
  549. this->GetLocalGenerator()->ConvertToOutputFormat(
  550. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  551. if (targetType == cmStateEnums::EXECUTABLE) {
  552. cmNinjaRule rule("CMAKE_SYMLINK_EXECUTABLE");
  553. {
  554. std::vector<std::string> cmd;
  555. cmd.push_back(cmakeCommand + " -E cmake_symlink_executable $in $out");
  556. cmd.emplace_back("$POST_BUILD");
  557. rule.Command =
  558. this->GetLocalGenerator()->BuildCommandLine(cmd, config, config);
  559. }
  560. rule.Description = "Creating executable symlink $out";
  561. rule.Comment = "Rule for creating executable symlink.";
  562. this->GetGlobalGenerator()->AddRule(rule);
  563. } else {
  564. cmNinjaRule rule("CMAKE_SYMLINK_LIBRARY");
  565. {
  566. std::vector<std::string> cmd;
  567. cmd.push_back(cmakeCommand +
  568. " -E cmake_symlink_library $in $SONAME $out");
  569. cmd.emplace_back("$POST_BUILD");
  570. rule.Command =
  571. this->GetLocalGenerator()->BuildCommandLine(cmd, config, config);
  572. }
  573. rule.Description = "Creating library symlink $out";
  574. rule.Comment = "Rule for creating library symlink.";
  575. this->GetGlobalGenerator()->AddRule(rule);
  576. }
  577. }
  578. if (this->GetGeneratorTarget()->IsApple() &&
  579. this->GetGeneratorTarget()->HasImportLibrary(config)) {
  580. cmNinjaRule rule(this->TextStubsGeneratorRule(config));
  581. rule.Comment = cmStrCat("Rule for generating text-based stubs for ",
  582. this->GetVisibleTypeName(), '.');
  583. rule.Description = "Creating text-based stubs $out";
  584. std::string cmd =
  585. this->GetMakefile()->GetDefinition("CMAKE_CREATE_TEXT_STUBS");
  586. auto rulePlaceholderExpander =
  587. this->GetLocalGenerator()->CreateRulePlaceholderExpander();
  588. cmRulePlaceholderExpander::RuleVariables vars;
  589. vars.Target = "$in";
  590. rulePlaceholderExpander->SetTargetImpLib("$out");
  591. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  592. cmd, vars);
  593. rule.Command =
  594. this->GetLocalGenerator()->BuildCommandLine({ cmd }, config, config);
  595. this->GetGlobalGenerator()->AddRule(rule);
  596. if (tgtNames.ImportOutput != tgtNames.ImportReal &&
  597. !this->GetGeneratorTarget()->IsFrameworkOnApple()) {
  598. cmNinjaRule slRule("CMAKE_SYMLINK_IMPORT_LIBRARY");
  599. {
  600. std::string cmakeCommand =
  601. this->GetLocalGenerator()->ConvertToOutputFormat(
  602. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  603. std::string slCmd =
  604. cmStrCat(cmakeCommand, " -E cmake_symlink_library $in $SONAME $out");
  605. slRule.Command = this->GetLocalGenerator()->BuildCommandLine(
  606. { slCmd }, config, config);
  607. }
  608. slRule.Description = "Creating import library symlink $out";
  609. slRule.Comment = "Rule for creating import library symlink.";
  610. this->GetGlobalGenerator()->AddRule(slRule);
  611. }
  612. }
  613. }
  614. std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeDeviceLinkCmd()
  615. {
  616. cmList linkCmds;
  617. // this target requires separable cuda compilation
  618. // now build the correct command depending on if the target is
  619. // an executable or a dynamic library.
  620. switch (this->GetGeneratorTarget()->GetType()) {
  621. case cmStateEnums::STATIC_LIBRARY:
  622. case cmStateEnums::SHARED_LIBRARY:
  623. case cmStateEnums::MODULE_LIBRARY: {
  624. linkCmds.assign(
  625. this->GetMakefile()->GetDefinition("CMAKE_CUDA_DEVICE_LINK_LIBRARY"));
  626. } break;
  627. case cmStateEnums::EXECUTABLE: {
  628. linkCmds.assign(this->GetMakefile()->GetDefinition(
  629. "CMAKE_CUDA_DEVICE_LINK_EXECUTABLE"));
  630. } break;
  631. default:
  632. break;
  633. }
  634. return std::move(linkCmds.data());
  635. }
  636. std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeLinkCmd(
  637. std::string const& config)
  638. {
  639. cmList linkCmds;
  640. cmMakefile* mf = this->GetMakefile();
  641. {
  642. // If we have a rule variable prefer it. In the case of static libraries
  643. // this occurs when things like IPO is enabled, and we need to use the
  644. // CMAKE_<lang>_CREATE_STATIC_LIBRARY_IPO define instead.
  645. std::string linkCmdVar = this->GetGeneratorTarget()->GetCreateRuleVariable(
  646. this->TargetLinkLanguage(config), config);
  647. cmValue linkCmd = mf->GetDefinition(linkCmdVar);
  648. if (linkCmd) {
  649. std::string linkCmdStr = *linkCmd;
  650. if (this->GetGeneratorTarget()->HasImplibGNUtoMS(config)) {
  651. std::string ruleVar =
  652. cmStrCat("CMAKE_", this->GeneratorTarget->GetLinkerLanguage(config),
  653. "_GNUtoMS_RULE");
  654. if (cmValue rule = this->Makefile->GetDefinition(ruleVar)) {
  655. linkCmdStr += *rule;
  656. }
  657. }
  658. linkCmds.assign(linkCmdStr);
  659. if (this->UseLWYU) {
  660. cmValue lwyuCheck = mf->GetDefinition("CMAKE_LINK_WHAT_YOU_USE_CHECK");
  661. if (lwyuCheck) {
  662. std::string cmakeCommand = cmStrCat(
  663. this->GetLocalGenerator()->ConvertToOutputFormat(
  664. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL),
  665. " -E __run_co_compile --lwyu=");
  666. cmakeCommand +=
  667. this->GetLocalGenerator()->EscapeForShell(*lwyuCheck);
  668. std::string targetOutputReal =
  669. this->ConvertToNinjaPath(this->GetGeneratorTarget()->GetFullPath(
  670. config, cmStateEnums::RuntimeBinaryArtifact,
  671. /*realname=*/true));
  672. cmakeCommand += cmStrCat(" --source=", targetOutputReal);
  673. linkCmds.push_back(std::move(cmakeCommand));
  674. }
  675. }
  676. return std::move(linkCmds.data());
  677. }
  678. }
  679. switch (this->GetGeneratorTarget()->GetType()) {
  680. case cmStateEnums::STATIC_LIBRARY: {
  681. // We have archive link commands set. First, delete the existing archive.
  682. {
  683. std::string cmakeCommand =
  684. this->GetLocalGenerator()->ConvertToOutputFormat(
  685. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  686. linkCmds.push_back(cmakeCommand + " -E rm -f $TARGET_FILE");
  687. }
  688. // TODO: Use ARCHIVE_APPEND for archives over a certain size.
  689. {
  690. std::string linkCmdVar = cmStrCat(
  691. "CMAKE_", this->TargetLinkLanguage(config), "_ARCHIVE_CREATE");
  692. linkCmdVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
  693. linkCmdVar, this->TargetLinkLanguage(config), config);
  694. std::string const& linkCmd = mf->GetRequiredDefinition(linkCmdVar);
  695. linkCmds.append(linkCmd);
  696. }
  697. {
  698. std::string linkCmdVar = cmStrCat(
  699. "CMAKE_", this->TargetLinkLanguage(config), "_ARCHIVE_FINISH");
  700. linkCmdVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
  701. linkCmdVar, this->TargetLinkLanguage(config), config);
  702. std::string const& linkCmd = mf->GetRequiredDefinition(linkCmdVar);
  703. linkCmds.append(linkCmd);
  704. }
  705. #ifdef __APPLE__
  706. // On macOS ranlib truncates the fractional part of the static archive
  707. // file modification time. If the archive and at least one contained
  708. // object file were created within the same second this will make look
  709. // the archive older than the object file. On subsequent ninja runs this
  710. // leads to re-archiving and updating dependent targets.
  711. // As a work-around we touch the archive after ranlib (see #19222).
  712. {
  713. std::string cmakeCommand =
  714. this->GetLocalGenerator()->ConvertToOutputFormat(
  715. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  716. linkCmds.push_back(cmakeCommand + " -E touch $TARGET_FILE");
  717. }
  718. #endif
  719. } break;
  720. case cmStateEnums::SHARED_LIBRARY:
  721. case cmStateEnums::MODULE_LIBRARY:
  722. case cmStateEnums::EXECUTABLE:
  723. break;
  724. default:
  725. assert(false && "Unexpected target type");
  726. }
  727. return std::move(linkCmds.data());
  728. }
  729. void cmNinjaNormalTargetGenerator::WriteDeviceLinkStatement(
  730. std::string const& config, std::string const& fileConfig,
  731. bool firstForConfig)
  732. {
  733. cmGlobalNinjaGenerator* globalGen = this->GetGlobalGenerator();
  734. if (!globalGen->GetLanguageEnabled("CUDA")) {
  735. return;
  736. }
  737. cmGeneratorTarget* genTarget = this->GetGeneratorTarget();
  738. bool requiresDeviceLinking = requireDeviceLinking(
  739. *this->GeneratorTarget, *this->GetLocalGenerator(), config);
  740. if (!requiresDeviceLinking) {
  741. return;
  742. }
  743. // First and very important step is to make sure while inside this
  744. // step our link language is set to CUDA
  745. std::string const& objExt =
  746. this->Makefile->GetSafeDefinition("CMAKE_CUDA_OUTPUT_EXTENSION");
  747. std::string targetOutputDir =
  748. cmStrCat(this->GetLocalGenerator()->GetTargetDirectory(genTarget),
  749. globalGen->ConfigDirectory(config), "/");
  750. targetOutputDir = globalGen->ExpandCFGIntDir(targetOutputDir, config);
  751. std::string targetOutputReal =
  752. this->ConvertToNinjaPath(targetOutputDir + "cmake_device_link" + objExt);
  753. if (firstForConfig) {
  754. globalGen->GetByproductsForCleanTarget(config).push_back(targetOutputReal);
  755. }
  756. this->DeviceLinkObject = targetOutputReal;
  757. // Write comments.
  758. cmGlobalNinjaGenerator::WriteDivider(this->GetCommonFileStream());
  759. this->GetCommonFileStream()
  760. << "# Device Link build statements for "
  761. << cmState::GetTargetTypeName(genTarget->GetType()) << " target "
  762. << this->GetTargetName() << "\n\n";
  763. if (this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_ID") == "Clang") {
  764. std::string architecturesStr =
  765. this->GeneratorTarget->GetSafeProperty("CUDA_ARCHITECTURES");
  766. if (cmIsOff(architecturesStr)) {
  767. this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
  768. "CUDA_SEPARABLE_COMPILATION on Clang "
  769. "requires CUDA_ARCHITECTURES to be set.");
  770. return;
  771. }
  772. this->WriteDeviceLinkRules(config);
  773. this->WriteDeviceLinkStatements(config, cmList{ architecturesStr },
  774. targetOutputReal);
  775. } else {
  776. this->WriteNvidiaDeviceLinkStatement(config, fileConfig, targetOutputDir,
  777. targetOutputReal);
  778. }
  779. }
  780. void cmNinjaNormalTargetGenerator::WriteDeviceLinkStatements(
  781. std::string const& config, std::vector<std::string> const& architectures,
  782. std::string const& output)
  783. {
  784. // Ensure there are no duplicates.
  785. cmNinjaDeps const explicitDeps = [&]() -> std::vector<std::string> {
  786. std::unordered_set<std::string> depsSet;
  787. cmNinjaDeps const linkDeps =
  788. this->ComputeLinkDeps(this->TargetLinkLanguage(config), config, true);
  789. cmNinjaDeps const objects = this->GetObjects(config);
  790. depsSet.insert(linkDeps.begin(), linkDeps.end());
  791. depsSet.insert(objects.begin(), objects.end());
  792. std::vector<std::string> deps;
  793. std::copy(depsSet.begin(), depsSet.end(), std::back_inserter(deps));
  794. return deps;
  795. }();
  796. cmGlobalNinjaGenerator* globalGen{ this->GetGlobalGenerator() };
  797. std::string const objectDir =
  798. cmStrCat(this->GeneratorTarget->GetSupportDirectory(),
  799. globalGen->ConfigDirectory(config));
  800. std::string const ninjaOutputDir = this->ConvertToNinjaPath(objectDir);
  801. cmNinjaBuild fatbinary(this->LanguageLinkerCudaFatbinaryRule(config));
  802. // Link device code for each architecture.
  803. for (std::string const& architectureKind : architectures) {
  804. // Clang always generates real code, so strip the specifier.
  805. std::string const architecture =
  806. architectureKind.substr(0, architectureKind.find('-'));
  807. std::string const cubin =
  808. cmStrCat(ninjaOutputDir, "/sm_", architecture, ".cubin");
  809. cmNinjaBuild dlink(this->LanguageLinkerCudaDeviceRule(config));
  810. dlink.ExplicitDeps = explicitDeps;
  811. dlink.Outputs = { cubin };
  812. dlink.Variables["ARCH"] = cmStrCat("sm_", architecture);
  813. // The generated register file contains macros that when expanded register
  814. // the device routines. Because the routines are the same for all
  815. // architectures the register file will be the same too. Thus generate it
  816. // only on the first invocation to reduce overhead.
  817. if (fatbinary.ExplicitDeps.empty()) {
  818. dlink.Variables["REGISTER"] = cmStrCat(
  819. "--register-link-binaries=", ninjaOutputDir, "/cmake_cuda_register.h");
  820. }
  821. fatbinary.Variables["PROFILES"] +=
  822. cmStrCat(" -im=profile=sm_", architecture, ",file=", cubin);
  823. fatbinary.ExplicitDeps.emplace_back(cubin);
  824. globalGen->WriteBuild(this->GetCommonFileStream(), dlink);
  825. }
  826. // Combine all architectures into a single fatbinary.
  827. fatbinary.Outputs = { cmStrCat(ninjaOutputDir, "/cmake_cuda_fatbin.h") };
  828. globalGen->WriteBuild(this->GetCommonFileStream(), fatbinary);
  829. // Compile the stub that registers the kernels and contains the fatbinaries.
  830. cmLocalNinjaGenerator* localGen{ this->GetLocalGenerator() };
  831. cmNinjaBuild dcompile(this->LanguageLinkerCudaDeviceCompileRule(config));
  832. dcompile.Outputs = { output };
  833. dcompile.ExplicitDeps = { cmStrCat(ninjaOutputDir, "/cmake_cuda_fatbin.h") };
  834. dcompile.Variables["FATBIN"] = localGen->ConvertToOutputFormat(
  835. cmStrCat(objectDir, "/cmake_cuda_fatbin.h"), cmOutputConverter::SHELL);
  836. dcompile.Variables["REGISTER"] = localGen->ConvertToOutputFormat(
  837. cmStrCat(objectDir, "/cmake_cuda_register.h"), cmOutputConverter::SHELL);
  838. cmNinjaLinkLineDeviceComputer linkLineComputer(
  839. localGen, localGen->GetStateSnapshot().GetDirectory(), globalGen);
  840. linkLineComputer.SetUseNinjaMulti(globalGen->IsMultiConfig());
  841. // Link libraries and paths are only used during the final executable/library
  842. // link.
  843. std::string frameworkPath;
  844. std::string linkPath;
  845. std::string linkLibs;
  846. localGen->GetDeviceLinkFlags(linkLineComputer, config, linkLibs,
  847. dcompile.Variables["LINK_FLAGS"], frameworkPath,
  848. linkPath, this->GetGeneratorTarget());
  849. globalGen->WriteBuild(this->GetCommonFileStream(), dcompile);
  850. }
  851. void cmNinjaNormalTargetGenerator::WriteNvidiaDeviceLinkStatement(
  852. std::string const& config, std::string const& fileConfig,
  853. std::string const& outputDir, std::string const& output)
  854. {
  855. cmGeneratorTarget* genTarget = this->GetGeneratorTarget();
  856. cmGlobalNinjaGenerator* globalGen = this->GetGlobalGenerator();
  857. std::string targetOutputImplib = this->ConvertToNinjaPath(
  858. genTarget->GetFullPath(config, cmStateEnums::ImportLibraryArtifact));
  859. if (config != fileConfig) {
  860. std::string targetOutputFileConfigDir =
  861. cmStrCat(this->GetLocalGenerator()->GetTargetDirectory(genTarget),
  862. globalGen->ConfigDirectory(fileConfig), "/");
  863. targetOutputFileConfigDir =
  864. globalGen->ExpandCFGIntDir(outputDir, fileConfig);
  865. if (outputDir == targetOutputFileConfigDir) {
  866. return;
  867. }
  868. if (!genTarget->GetFullName(config, cmStateEnums::ImportLibraryArtifact)
  869. .empty() &&
  870. !genTarget
  871. ->GetFullName(fileConfig, cmStateEnums::ImportLibraryArtifact)
  872. .empty() &&
  873. targetOutputImplib ==
  874. this->ConvertToNinjaPath(genTarget->GetFullPath(
  875. fileConfig, cmStateEnums::ImportLibraryArtifact))) {
  876. return;
  877. }
  878. }
  879. // Compute the comment.
  880. cmNinjaBuild build(this->LanguageLinkerDeviceRule(config));
  881. build.Comment =
  882. cmStrCat("Link the ", this->GetVisibleTypeName(), ' ', output);
  883. cmNinjaVars& vars = build.Variables;
  884. // Compute outputs.
  885. build.Outputs.push_back(output);
  886. // Compute specific libraries to link with.
  887. build.ExplicitDeps = this->GetObjects(config);
  888. build.ImplicitDeps =
  889. this->ComputeLinkDeps(this->TargetLinkLanguage(config), config);
  890. std::string frameworkPath;
  891. std::string linkPath;
  892. std::string createRule =
  893. genTarget->GetCreateRuleVariable(this->TargetLinkLanguage(config), config);
  894. cmLocalNinjaGenerator& localGen = *this->GetLocalGenerator();
  895. vars["TARGET_FILE"] =
  896. localGen.ConvertToOutputFormat(output, cmOutputConverter::SHELL);
  897. cmNinjaLinkLineDeviceComputer linkLineComputer(
  898. this->GetLocalGenerator(),
  899. this->GetLocalGenerator()->GetStateSnapshot().GetDirectory(), globalGen);
  900. linkLineComputer.SetUseNinjaMulti(globalGen->IsMultiConfig());
  901. localGen.GetDeviceLinkFlags(linkLineComputer, config, vars["LINK_LIBRARIES"],
  902. vars["LINK_FLAGS"], frameworkPath, linkPath,
  903. genTarget);
  904. this->addPoolNinjaVariable("JOB_POOL_LINK", genTarget, vars);
  905. vars["MANIFESTS"] = this->GetManifests(config);
  906. vars["LINK_PATH"] = frameworkPath + linkPath;
  907. // Compute language specific link flags.
  908. std::string langFlags;
  909. localGen.AddLanguageFlagsForLinking(langFlags, genTarget, "CUDA", config);
  910. vars["LANGUAGE_COMPILE_FLAGS"] = langFlags;
  911. auto const tgtNames = this->TargetNames(config);
  912. if (genTarget->HasSOName(config) ||
  913. genTarget->IsArchivedAIXSharedLibrary()) {
  914. vars["SONAME_FLAG"] =
  915. this->GetMakefile()->GetSONameFlag(this->TargetLinkLanguage(config));
  916. vars["SONAME"] = localGen.ConvertToOutputFormat(tgtNames.SharedObject,
  917. cmOutputConverter::SHELL);
  918. if (genTarget->GetType() == cmStateEnums::SHARED_LIBRARY) {
  919. std::string install_dir =
  920. this->GetGeneratorTarget()->GetInstallNameDirForBuildTree(config);
  921. if (!install_dir.empty()) {
  922. vars["INSTALLNAME_DIR"] = localGen.ConvertToOutputFormat(
  923. install_dir, cmOutputConverter::SHELL);
  924. }
  925. }
  926. }
  927. if (!tgtNames.ImportLibrary.empty()) {
  928. std::string const impLibPath = localGen.ConvertToOutputFormat(
  929. targetOutputImplib, cmOutputConverter::SHELL);
  930. vars["TARGET_IMPLIB"] = impLibPath;
  931. this->EnsureParentDirectoryExists(targetOutputImplib);
  932. }
  933. std::string const objPath =
  934. cmStrCat(this->GetGeneratorTarget()->GetSupportDirectory(),
  935. globalGen->ConfigDirectory(config));
  936. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  937. this->ConvertToNinjaPath(objPath), cmOutputConverter::SHELL);
  938. this->EnsureDirectoryExists(objPath);
  939. this->SetMsvcTargetPdbVariable(vars, config);
  940. std::string& linkLibraries = vars["LINK_LIBRARIES"];
  941. std::string& link_path = vars["LINK_PATH"];
  942. if (globalGen->IsGCCOnWindows()) {
  943. // ar.exe can't handle backslashes in rsp files (implicitly used by gcc)
  944. std::replace(linkLibraries.begin(), linkLibraries.end(), '\\', '/');
  945. std::replace(link_path.begin(), link_path.end(), '\\', '/');
  946. }
  947. // Device linking currently doesn't support response files so
  948. // do not check if the user has explicitly forced a response file.
  949. int const commandLineLengthLimit =
  950. static_cast<int>(cmSystemTools::CalculateCommandLineLengthLimit()) -
  951. globalGen->GetRuleCmdLength(build.Rule);
  952. build.RspFile = this->ConvertToNinjaPath(
  953. cmStrCat("CMakeFiles/", genTarget->GetName(),
  954. globalGen->IsMultiConfig() ? cmStrCat('.', config) : "", ".rsp"));
  955. // Gather order-only dependencies.
  956. this->GetLocalGenerator()->AppendTargetDepends(
  957. this->GetGeneratorTarget(), build.OrderOnlyDeps, config, config,
  958. DependOnTargetArtifact);
  959. // Write the build statement for this target.
  960. bool usedResponseFile = false;
  961. globalGen->WriteBuild(this->GetCommonFileStream(), build,
  962. commandLineLengthLimit, &usedResponseFile);
  963. this->WriteNvidiaDeviceLinkRule(usedResponseFile, config);
  964. }
  965. void cmNinjaNormalTargetGenerator::WriteLinkStatement(
  966. std::string const& config, std::string const& fileConfig,
  967. bool firstForConfig)
  968. {
  969. cmMakefile* mf = this->GetMakefile();
  970. cmGlobalNinjaGenerator* globalGen = this->GetGlobalGenerator();
  971. cmGeneratorTarget* gt = this->GetGeneratorTarget();
  972. std::string targetOutput = this->ConvertToNinjaPath(gt->GetFullPath(config));
  973. std::string targetOutputReal = this->ConvertToNinjaPath(
  974. gt->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact,
  975. /*realname=*/true));
  976. std::string targetOutputImplib = this->ConvertToNinjaPath(
  977. gt->GetFullPath(config, cmStateEnums::ImportLibraryArtifact));
  978. if (config != fileConfig) {
  979. if (targetOutput ==
  980. this->ConvertToNinjaPath(gt->GetFullPath(fileConfig))) {
  981. return;
  982. }
  983. if (targetOutputReal ==
  984. this->ConvertToNinjaPath(
  985. gt->GetFullPath(fileConfig, cmStateEnums::RuntimeBinaryArtifact,
  986. /*realname=*/true))) {
  987. return;
  988. }
  989. if (!gt->GetFullName(config, cmStateEnums::ImportLibraryArtifact)
  990. .empty() &&
  991. !gt->GetFullName(fileConfig, cmStateEnums::ImportLibraryArtifact)
  992. .empty() &&
  993. targetOutputImplib ==
  994. this->ConvertToNinjaPath(gt->GetFullPath(
  995. fileConfig, cmStateEnums::ImportLibraryArtifact))) {
  996. return;
  997. }
  998. }
  999. auto const tgtNames = this->TargetNames(config);
  1000. if (gt->IsAppBundleOnApple()) {
  1001. // Create the app bundle
  1002. std::string outpath = gt->GetDirectory(config);
  1003. this->OSXBundleGenerator->CreateAppBundle(tgtNames.Output, outpath,
  1004. config);
  1005. // Calculate the output path
  1006. targetOutput = cmStrCat(outpath, '/', tgtNames.Output);
  1007. targetOutput = this->ConvertToNinjaPath(targetOutput);
  1008. targetOutputReal = cmStrCat(outpath, '/', tgtNames.Real);
  1009. targetOutputReal = this->ConvertToNinjaPath(targetOutputReal);
  1010. } else if (gt->IsFrameworkOnApple()) {
  1011. // Create the library framework.
  1012. cmOSXBundleGenerator::SkipParts bundleSkipParts;
  1013. if (globalGen->GetName() == "Ninja Multi-Config") {
  1014. auto const postFix = this->GeneratorTarget->GetFilePostfix(config);
  1015. // Skip creating Info.plist when there are multiple configurations, and
  1016. // the current configuration has a postfix. The non-postfix configuration
  1017. // Info.plist can be used by all the other configurations.
  1018. if (!postFix.empty()) {
  1019. bundleSkipParts.InfoPlist = true;
  1020. }
  1021. }
  1022. if (gt->HasImportLibrary(config)) {
  1023. bundleSkipParts.TextStubs = false;
  1024. }
  1025. this->OSXBundleGenerator->CreateFramework(
  1026. tgtNames.Output, gt->GetDirectory(config), config, bundleSkipParts);
  1027. } else if (gt->IsCFBundleOnApple()) {
  1028. // Create the core foundation bundle.
  1029. this->OSXBundleGenerator->CreateCFBundle(tgtNames.Output,
  1030. gt->GetDirectory(config), config);
  1031. }
  1032. // Write comments.
  1033. cmGlobalNinjaGenerator::WriteDivider(this->GetImplFileStream(fileConfig));
  1034. cmStateEnums::TargetType const targetType = gt->GetType();
  1035. this->GetImplFileStream(fileConfig)
  1036. << "# Link build statements for " << cmState::GetTargetTypeName(targetType)
  1037. << " target " << this->GetTargetName() << "\n\n";
  1038. cmNinjaBuild linkBuild(this->LanguageLinkerRule(config));
  1039. cmNinjaVars& vars = linkBuild.Variables;
  1040. if (this->GeneratorTarget->HasLinkDependencyFile(config)) {
  1041. this->AddDepfileBinding(vars,
  1042. this->ConvertToNinjaPath(
  1043. this->GetLocalGenerator()->GetLinkDependencyFile(
  1044. this->GeneratorTarget, config)));
  1045. }
  1046. // Compute the comment.
  1047. linkBuild.Comment =
  1048. cmStrCat("Link the ", this->GetVisibleTypeName(), ' ', targetOutputReal);
  1049. // Compute outputs.
  1050. linkBuild.Outputs.push_back(targetOutputReal);
  1051. if (firstForConfig) {
  1052. globalGen->GetByproductsForCleanTarget(config).push_back(targetOutputReal);
  1053. }
  1054. // If we can't split the Swift build model (CMP0157 is OLD or unset), fall
  1055. // back on the old one-step "build/link" logic.
  1056. if (!this->GetLocalGenerator()->IsSplitSwiftBuild() &&
  1057. this->TargetLinkLanguage(config) == "Swift") {
  1058. vars["SWIFT_LIBRARY_NAME"] = [this, config]() -> std::string {
  1059. cmGeneratorTarget::Names targetNames =
  1060. this->GetGeneratorTarget()->GetLibraryNames(config);
  1061. return targetNames.Base;
  1062. }();
  1063. vars["SWIFT_MODULE_NAME"] = gt->GetSwiftModuleName();
  1064. vars["SWIFT_MODULE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1065. this->ConvertToNinjaPath(gt->GetSwiftModulePath(config)),
  1066. cmOutputConverter::SHELL);
  1067. vars["SWIFT_SOURCES"] = [this, config]() -> std::string {
  1068. std::vector<cmSourceFile const*> sourceFiles;
  1069. std::stringstream oss;
  1070. this->GetGeneratorTarget()->GetObjectSources(sourceFiles, config);
  1071. cmLocalGenerator const* LocalGen = this->GetLocalGenerator();
  1072. for (auto const& source : sourceFiles) {
  1073. std::string const sourcePath = source->GetLanguage() == "Swift"
  1074. ? this->GetCompiledSourceNinjaPath(source)
  1075. : this->GetObjectFilePath(source, config);
  1076. oss << " "
  1077. << LocalGen->ConvertToOutputFormat(sourcePath,
  1078. cmOutputConverter::SHELL);
  1079. }
  1080. return oss.str();
  1081. }();
  1082. // Since we do not perform object builds, compute the
  1083. // defines/flags/includes here so that they can be passed along
  1084. // appropriately.
  1085. vars["DEFINES"] = this->GetDefines("Swift", config);
  1086. vars["FLAGS"] = this->GetFlags("Swift", config);
  1087. vars["INCLUDES"] = this->GetIncludes("Swift", config);
  1088. this->GenerateSwiftOutputFileMap(config, vars["FLAGS"]);
  1089. // Compute specific libraries to link with.
  1090. std::vector<cmSourceFile const*> sources;
  1091. gt->GetObjectSources(sources, config);
  1092. for (auto const& source : sources) {
  1093. if (source->GetLanguage() == "Swift") {
  1094. linkBuild.Outputs.push_back(
  1095. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config)));
  1096. linkBuild.ExplicitDeps.emplace_back(
  1097. this->GetCompiledSourceNinjaPath(source));
  1098. } else {
  1099. linkBuild.ExplicitDeps.emplace_back(
  1100. this->GetObjectFilePath(source, config));
  1101. }
  1102. }
  1103. if (targetType != cmStateEnums::EXECUTABLE ||
  1104. gt->IsExecutableWithExports()) {
  1105. linkBuild.Outputs.push_back(vars["SWIFT_MODULE"]);
  1106. }
  1107. } else {
  1108. linkBuild.ExplicitDeps = this->GetObjects(config);
  1109. }
  1110. std::vector<std::string> extraISPCObjects =
  1111. this->GetGeneratorTarget()->GetGeneratedISPCObjects(config);
  1112. std::transform(extraISPCObjects.begin(), extraISPCObjects.end(),
  1113. std::back_inserter(linkBuild.ExplicitDeps),
  1114. this->MapToNinjaPath());
  1115. linkBuild.ImplicitDeps =
  1116. this->ComputeLinkDeps(this->TargetLinkLanguage(config), config);
  1117. if (!this->DeviceLinkObject.empty()) {
  1118. linkBuild.ExplicitDeps.push_back(this->DeviceLinkObject);
  1119. }
  1120. std::string frameworkPath;
  1121. std::string linkPath;
  1122. std::string createRule =
  1123. gt->GetCreateRuleVariable(this->TargetLinkLanguage(config), config);
  1124. bool useWatcomQuote = mf->IsOn(createRule + "_USE_WATCOM_QUOTE");
  1125. cmLocalNinjaGenerator& localGen = *this->GetLocalGenerator();
  1126. vars["TARGET_FILE"] =
  1127. localGen.ConvertToOutputFormat(targetOutputReal, cmOutputConverter::SHELL);
  1128. std::unique_ptr<cmLinkLineComputer> linkLineComputer =
  1129. globalGen->CreateLinkLineComputer(
  1130. this->GetLocalGenerator(),
  1131. this->GetLocalGenerator()->GetStateSnapshot().GetDirectory());
  1132. linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
  1133. linkLineComputer->SetUseNinjaMulti(globalGen->IsMultiConfig());
  1134. localGen.GetTargetFlags(linkLineComputer.get(), config,
  1135. vars["LINK_LIBRARIES"], vars["FLAGS"],
  1136. vars["LINK_FLAGS"], frameworkPath, linkPath, gt);
  1137. localGen.AppendDependencyInfoLinkerFlags(vars["LINK_FLAGS"], gt, config,
  1138. this->TargetLinkLanguage(config));
  1139. // Add OS X version flags, if any.
  1140. if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  1141. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  1142. this->AppendOSXVerFlag(vars["LINK_FLAGS"],
  1143. this->TargetLinkLanguage(config), "COMPATIBILITY",
  1144. true);
  1145. this->AppendOSXVerFlag(vars["LINK_FLAGS"],
  1146. this->TargetLinkLanguage(config), "CURRENT", false);
  1147. }
  1148. this->addPoolNinjaVariable("JOB_POOL_LINK", gt, vars);
  1149. this->UseLWYU = this->GetLocalGenerator()->AppendLWYUFlags(
  1150. vars["LINK_FLAGS"], this->GetGeneratorTarget(),
  1151. this->TargetLinkLanguage(config));
  1152. vars["MANIFESTS"] = this->GetManifests(config);
  1153. vars["AIX_EXPORTS"] = this->GetAIXExports(config);
  1154. vars["LINK_PATH"] = frameworkPath + linkPath;
  1155. vars["CONFIG"] = config;
  1156. // Compute architecture specific link flags. Yes, these go into a different
  1157. // variable for executables, probably due to a mistake made when duplicating
  1158. // code between the Makefile executable and library generators.
  1159. if (targetType == cmStateEnums::EXECUTABLE) {
  1160. std::string t = vars["FLAGS"];
  1161. localGen.AddArchitectureFlags(t, gt, this->TargetLinkLanguage(config),
  1162. config);
  1163. vars["FLAGS"] = t;
  1164. } else {
  1165. std::string t = vars["ARCH_FLAGS"];
  1166. localGen.AddArchitectureFlags(t, gt, this->TargetLinkLanguage(config),
  1167. config);
  1168. vars["ARCH_FLAGS"] = t;
  1169. t.clear();
  1170. localGen.AddLanguageFlagsForLinking(
  1171. t, gt, this->TargetLinkLanguage(config), config);
  1172. vars["LANGUAGE_COMPILE_FLAGS"] = t;
  1173. }
  1174. if (gt->HasSOName(config) || gt->IsArchivedAIXSharedLibrary()) {
  1175. vars["SONAME_FLAG"] = mf->GetSONameFlag(this->TargetLinkLanguage(config));
  1176. vars["SONAME"] = localGen.ConvertToOutputFormat(tgtNames.SharedObject,
  1177. cmOutputConverter::SHELL);
  1178. if (targetType == cmStateEnums::SHARED_LIBRARY) {
  1179. std::string install_dir = gt->GetInstallNameDirForBuildTree(config);
  1180. if (!install_dir.empty()) {
  1181. vars["INSTALLNAME_DIR"] = localGen.ConvertToOutputFormat(
  1182. install_dir, cmOutputConverter::SHELL);
  1183. }
  1184. }
  1185. }
  1186. cmGlobalNinjaGenerator::CCOutputs byproducts(this->GetGlobalGenerator());
  1187. if (!gt->IsApple() && !tgtNames.ImportLibrary.empty()) {
  1188. std::string const impLibPath = localGen.ConvertToOutputFormat(
  1189. targetOutputImplib, cmOutputConverter::SHELL);
  1190. vars["TARGET_IMPLIB"] = impLibPath;
  1191. this->EnsureParentDirectoryExists(targetOutputImplib);
  1192. if (gt->HasImportLibrary(config)) {
  1193. // Some linkers may update a binary without touching its import lib.
  1194. byproducts.ExplicitOuts.emplace_back(targetOutputImplib);
  1195. if (firstForConfig) {
  1196. globalGen->GetByproductsForCleanTarget(config).push_back(
  1197. targetOutputImplib);
  1198. }
  1199. }
  1200. }
  1201. if (!this->SetMsvcTargetPdbVariable(vars, config)) {
  1202. // It is common to place debug symbols at a specific place,
  1203. // so we need a plain target name in the rule available.
  1204. cmGeneratorTarget::NameComponents const& components =
  1205. gt->GetFullNameComponents(config);
  1206. std::string dbg_suffix = ".dbg";
  1207. // TODO: Where to document?
  1208. if (cmValue d = mf->GetDefinition("CMAKE_DEBUG_SYMBOL_SUFFIX")) {
  1209. dbg_suffix = *d;
  1210. }
  1211. vars["TARGET_PDB"] = components.base + components.suffix + dbg_suffix;
  1212. }
  1213. std::string const objPath =
  1214. cmStrCat(gt->GetSupportDirectory(), globalGen->ConfigDirectory(config));
  1215. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1216. this->ConvertToNinjaPath(objPath), cmOutputConverter::SHELL);
  1217. this->EnsureDirectoryExists(objPath);
  1218. std::string& linkLibraries = vars["LINK_LIBRARIES"];
  1219. std::string& link_path = vars["LINK_PATH"];
  1220. if (globalGen->IsGCCOnWindows()) {
  1221. // ar.exe can't handle backslashes in rsp files (implicitly used by gcc)
  1222. std::replace(linkLibraries.begin(), linkLibraries.end(), '\\', '/');
  1223. std::replace(link_path.begin(), link_path.end(), '\\', '/');
  1224. }
  1225. std::vector<cmCustomCommand> const* cmdLists[3] = {
  1226. &gt->GetPreBuildCommands(), &gt->GetPreLinkCommands(),
  1227. &gt->GetPostBuildCommands()
  1228. };
  1229. std::vector<std::string> preLinkComments;
  1230. std::vector<std::string> postBuildComments;
  1231. std::vector<std::string> preLinkCmdLines;
  1232. std::vector<std::string> postBuildCmdLines;
  1233. std::vector<std::string>* cmdComments[3] = { &preLinkComments,
  1234. &preLinkComments,
  1235. &postBuildComments };
  1236. std::vector<std::string>* cmdLineLists[3] = { &preLinkCmdLines,
  1237. &preLinkCmdLines,
  1238. &postBuildCmdLines };
  1239. cmGeneratorExpression ge(*this->GetLocalGenerator()->GetCMakeInstance());
  1240. for (unsigned i = 0; i != 3; ++i) {
  1241. for (cmCustomCommand const& cc : *cmdLists[i]) {
  1242. if (config == fileConfig ||
  1243. this->GetLocalGenerator()->HasUniqueByproducts(cc.GetByproducts(),
  1244. cc.GetBacktrace())) {
  1245. cmCustomCommandGenerator ccg(cc, fileConfig, this->GetLocalGenerator(),
  1246. true, config);
  1247. localGen.AppendCustomCommandLines(ccg, *cmdLineLists[i]);
  1248. if (cc.GetComment()) {
  1249. auto cge = ge.Parse(cc.GetComment());
  1250. cmdComments[i]->emplace_back(
  1251. cge->Evaluate(this->GetLocalGenerator(), config));
  1252. }
  1253. std::vector<std::string> const& ccByproducts = ccg.GetByproducts();
  1254. byproducts.Add(ccByproducts);
  1255. std::transform(
  1256. ccByproducts.begin(), ccByproducts.end(),
  1257. std::back_inserter(globalGen->GetByproductsForCleanTarget()),
  1258. this->MapToNinjaPath());
  1259. }
  1260. }
  1261. }
  1262. // maybe create .def file from list of objects
  1263. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  1264. gt->GetModuleDefinitionInfo(config);
  1265. if (mdi && mdi->DefFileGenerated) {
  1266. std::string cmakeCommand =
  1267. this->GetLocalGenerator()->ConvertToOutputFormat(
  1268. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  1269. std::string cmd =
  1270. cmStrCat(cmakeCommand, " -E __create_def ",
  1271. this->GetLocalGenerator()->ConvertToOutputFormat(
  1272. mdi->DefFile, cmOutputConverter::SHELL),
  1273. ' ');
  1274. std::string obj_list_file = mdi->DefFile + ".objs";
  1275. cmd += this->GetLocalGenerator()->ConvertToOutputFormat(
  1276. obj_list_file, cmOutputConverter::SHELL);
  1277. cmValue nm_executable = this->GetMakefile()->GetDefinition("CMAKE_NM");
  1278. if (cmNonempty(nm_executable)) {
  1279. cmd += " --nm=";
  1280. cmd += this->LocalCommonGenerator->ConvertToOutputFormat(
  1281. *nm_executable, cmOutputConverter::SHELL);
  1282. }
  1283. preLinkCmdLines.push_back(std::move(cmd));
  1284. // create a list of obj files for the -E __create_def to read
  1285. cmGeneratedFileStream fout(obj_list_file);
  1286. if (mdi->WindowsExportAllSymbols) {
  1287. cmNinjaDeps objs = this->GetObjects(config);
  1288. for (std::string const& obj : objs) {
  1289. if (cmHasLiteralSuffix(obj, ".obj")) {
  1290. fout << obj << "\n";
  1291. }
  1292. }
  1293. }
  1294. for (cmSourceFile const* src : mdi->Sources) {
  1295. fout << src->GetFullPath() << "\n";
  1296. }
  1297. }
  1298. // If we have any PRE_LINK commands, we need to go back to CMAKE_BINARY_DIR
  1299. // for the link commands.
  1300. if (!preLinkCmdLines.empty()) {
  1301. std::string const homeOutDir = localGen.ConvertToOutputFormat(
  1302. localGen.GetBinaryDirectory(), cmOutputConverter::SHELL);
  1303. preLinkCmdLines.push_back("cd " + homeOutDir);
  1304. }
  1305. vars["PRE_LINK"] = localGen.BuildCommandLine(
  1306. preLinkCmdLines, config, fileConfig, "pre-link", this->GeneratorTarget);
  1307. std::string postBuildCmdLine =
  1308. localGen.BuildCommandLine(postBuildCmdLines, config, fileConfig,
  1309. "post-build", this->GeneratorTarget);
  1310. cmNinjaVars symlinkVars;
  1311. bool const symlinkNeeded =
  1312. (targetOutput != targetOutputReal && !gt->IsFrameworkOnApple() &&
  1313. !gt->IsArchivedAIXSharedLibrary());
  1314. if (!symlinkNeeded) {
  1315. vars["POST_BUILD"] = postBuildCmdLine;
  1316. } else {
  1317. vars["POST_BUILD"] = cmGlobalNinjaGenerator::SHELL_NOOP;
  1318. symlinkVars["POST_BUILD"] = postBuildCmdLine;
  1319. }
  1320. std::string cmakeVarLang =
  1321. cmStrCat("CMAKE_", this->TargetLinkLanguage(config));
  1322. // build response file name
  1323. std::string cmakeLinkVar = cmakeVarLang + "_RESPONSE_FILE_LINK_FLAG";
  1324. cmValue flag = this->GetMakefile()->GetDefinition(cmakeLinkVar);
  1325. bool const lang_supports_response =
  1326. !(this->TargetLinkLanguage(config) == "RC" ||
  1327. (this->TargetLinkLanguage(config) == "CUDA" && !flag));
  1328. int commandLineLengthLimit = -1;
  1329. if (!lang_supports_response || !this->ForceResponseFile()) {
  1330. commandLineLengthLimit =
  1331. static_cast<int>(cmSystemTools::CalculateCommandLineLengthLimit()) -
  1332. globalGen->GetRuleCmdLength(linkBuild.Rule);
  1333. }
  1334. linkBuild.RspFile = this->ConvertToNinjaPath(
  1335. cmStrCat("CMakeFiles/", gt->GetName(),
  1336. globalGen->IsMultiConfig() ? cmStrCat('.', config) : "", ".rsp"));
  1337. // Gather order-only dependencies.
  1338. this->GetLocalGenerator()->AppendTargetDepends(
  1339. gt, linkBuild.OrderOnlyDeps, config, fileConfig, DependOnTargetArtifact);
  1340. // Add order-only dependencies on versioning symlinks of shared libs we link.
  1341. // If our target is not producing a runtime binary, it doesn't need the
  1342. // symlinks (anything that links to the target might, but that consumer will
  1343. // get its own order-only dependency).
  1344. if (!gt->IsDLLPlatform() && gt->IsRuntimeBinary()) {
  1345. if (cmComputeLinkInformation* cli = gt->GetLinkInformation(config)) {
  1346. for (auto const& item : cli->GetItems()) {
  1347. if (item.Target &&
  1348. item.Target->GetType() == cmStateEnums::SHARED_LIBRARY &&
  1349. !item.Target->IsFrameworkOnApple()) {
  1350. std::string const& lib =
  1351. this->ConvertToNinjaPath(item.Target->GetFullPath(config));
  1352. if (std::find(linkBuild.ImplicitDeps.begin(),
  1353. linkBuild.ImplicitDeps.end(),
  1354. lib) == linkBuild.ImplicitDeps.end()) {
  1355. linkBuild.OrderOnlyDeps.emplace_back(lib);
  1356. }
  1357. }
  1358. }
  1359. }
  1360. }
  1361. // Add dependencies on swiftmodule files when using the swift linker
  1362. if (this->TargetLinkLanguage(config) == "Swift") {
  1363. if (cmComputeLinkInformation* cli =
  1364. this->GeneratorTarget->GetLinkInformation(config)) {
  1365. for (auto const& dependency : cli->GetItems()) {
  1366. // Both the current target and the linked target must be swift targets
  1367. // in order for there to be a swiftmodule to depend on
  1368. if (dependency.Target &&
  1369. dependency.Target->GetLinkerLanguage(config) == "Swift") {
  1370. std::string swiftmodule = this->ConvertToNinjaPath(
  1371. dependency.Target->GetSwiftModulePath(config));
  1372. linkBuild.ImplicitDeps.emplace_back(swiftmodule);
  1373. }
  1374. }
  1375. }
  1376. }
  1377. // Ninja should restat after linking if and only if there are byproducts.
  1378. vars["RESTAT"] = byproducts.ExplicitOuts.empty() ? "" : "1";
  1379. linkBuild.Outputs.reserve(linkBuild.Outputs.size() +
  1380. byproducts.ExplicitOuts.size());
  1381. std::move(byproducts.ExplicitOuts.begin(), byproducts.ExplicitOuts.end(),
  1382. std::back_inserter(linkBuild.Outputs));
  1383. linkBuild.WorkDirOuts = std::move(byproducts.WorkDirOuts);
  1384. // Write the build statement for this target.
  1385. bool usedResponseFile = false;
  1386. globalGen->WriteBuild(this->GetImplFileStream(fileConfig), linkBuild,
  1387. commandLineLengthLimit, &usedResponseFile);
  1388. this->WriteLinkRule(usedResponseFile, config, preLinkComments,
  1389. postBuildComments);
  1390. if (symlinkNeeded) {
  1391. if (targetType == cmStateEnums::EXECUTABLE) {
  1392. cmNinjaBuild build("CMAKE_SYMLINK_EXECUTABLE");
  1393. build.Comment = "Create executable symlink " + targetOutput;
  1394. build.Outputs.push_back(targetOutput);
  1395. if (firstForConfig) {
  1396. globalGen->GetByproductsForCleanTarget(config).push_back(targetOutput);
  1397. }
  1398. build.ExplicitDeps.push_back(targetOutputReal);
  1399. build.Variables = std::move(symlinkVars);
  1400. globalGen->WriteBuild(this->GetImplFileStream(fileConfig), build);
  1401. } else {
  1402. cmNinjaBuild build("CMAKE_SYMLINK_LIBRARY");
  1403. build.Comment = "Create library symlink " + targetOutput;
  1404. std::string const soName = this->ConvertToNinjaPath(
  1405. this->GetTargetFilePath(tgtNames.SharedObject, config));
  1406. // If one link has to be created.
  1407. if (targetOutputReal == soName || targetOutput == soName) {
  1408. symlinkVars["SONAME"] =
  1409. this->GetLocalGenerator()->ConvertToOutputFormat(
  1410. soName, cmOutputConverter::SHELL);
  1411. } else {
  1412. symlinkVars["SONAME"].clear();
  1413. build.Outputs.push_back(soName);
  1414. if (firstForConfig) {
  1415. globalGen->GetByproductsForCleanTarget(config).push_back(soName);
  1416. }
  1417. }
  1418. build.Outputs.push_back(targetOutput);
  1419. if (firstForConfig) {
  1420. globalGen->GetByproductsForCleanTarget(config).push_back(targetOutput);
  1421. }
  1422. build.ExplicitDeps.push_back(targetOutputReal);
  1423. build.Variables = std::move(symlinkVars);
  1424. globalGen->WriteBuild(this->GetImplFileStream(fileConfig), build);
  1425. }
  1426. }
  1427. // Add aliases for the file name and the target name.
  1428. globalGen->AddTargetAlias(tgtNames.Output, gt, config);
  1429. globalGen->AddTargetAlias(this->GetTargetName(), gt, config);
  1430. if (this->GetGeneratorTarget()->IsApple() &&
  1431. this->GetGeneratorTarget()->HasImportLibrary(config)) {
  1432. auto dirTBD =
  1433. gt->GetDirectory(config, cmStateEnums::ImportLibraryArtifact);
  1434. auto targetTBD =
  1435. this->ConvertToNinjaPath(cmStrCat(dirTBD, '/', tgtNames.ImportReal));
  1436. this->EnsureParentDirectoryExists(targetTBD);
  1437. cmNinjaBuild build(this->TextStubsGeneratorRule(config));
  1438. build.Comment = cmStrCat("Generate the text-based stubs file ", targetTBD);
  1439. build.Outputs.push_back(targetTBD);
  1440. build.ExplicitDeps.push_back(targetOutputReal);
  1441. globalGen->WriteBuild(this->GetImplFileStream(fileConfig), build);
  1442. if (tgtNames.ImportOutput != tgtNames.ImportReal &&
  1443. !this->GetGeneratorTarget()->IsFrameworkOnApple()) {
  1444. auto outputTBD =
  1445. this->ConvertToNinjaPath(cmStrCat(dirTBD, '/', tgtNames.ImportOutput));
  1446. std::string const soNameTBD = this->ConvertToNinjaPath(
  1447. cmStrCat(dirTBD, '/', tgtNames.ImportLibrary));
  1448. cmNinjaBuild slBuild("CMAKE_SYMLINK_IMPORT_LIBRARY");
  1449. slBuild.Comment = cmStrCat("Create import library symlink ", outputTBD);
  1450. cmNinjaVars slVars;
  1451. // If one link has to be created.
  1452. if (targetTBD == soNameTBD || outputTBD == soNameTBD) {
  1453. slVars["SONAME"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1454. soNameTBD, cmOutputConverter::SHELL);
  1455. } else {
  1456. slVars["SONAME"].clear();
  1457. slBuild.Outputs.push_back(soNameTBD);
  1458. if (firstForConfig) {
  1459. globalGen->GetByproductsForCleanTarget(config).push_back(soNameTBD);
  1460. }
  1461. }
  1462. slBuild.Outputs.push_back(outputTBD);
  1463. if (firstForConfig) {
  1464. globalGen->GetByproductsForCleanTarget(config).push_back(outputTBD);
  1465. }
  1466. slBuild.ExplicitDeps.push_back(targetTBD);
  1467. slBuild.Variables = std::move(slVars);
  1468. globalGen->WriteBuild(this->GetImplFileStream(fileConfig), slBuild);
  1469. }
  1470. // Add alias for the import file name
  1471. globalGen->AddTargetAlias(tgtNames.ImportOutput, gt, config);
  1472. }
  1473. }
  1474. void cmNinjaNormalTargetGenerator::WriteObjectLibStatement(
  1475. std::string const& config)
  1476. {
  1477. // Write a phony output that depends on all object files.
  1478. {
  1479. cmNinjaBuild build("phony");
  1480. build.Comment = "Object library " + this->GetTargetName();
  1481. this->GetLocalGenerator()->AppendTargetOutputs(this->GetGeneratorTarget(),
  1482. build.Outputs, config);
  1483. this->GetLocalGenerator()->AppendTargetOutputs(
  1484. this->GetGeneratorTarget(),
  1485. this->GetGlobalGenerator()->GetByproductsForCleanTarget(config), config);
  1486. build.ExplicitDeps = this->GetObjects(config);
  1487. this->GetGlobalGenerator()->WriteBuild(this->GetCommonFileStream(), build);
  1488. }
  1489. // Add aliases for the target name.
  1490. this->GetGlobalGenerator()->AddTargetAlias(
  1491. this->GetTargetName(), this->GetGeneratorTarget(), config);
  1492. }
  1493. void cmNinjaNormalTargetGenerator::WriteCxxModuleLibraryStatement(
  1494. std::string const& config, std::string const& /*fileConfig*/,
  1495. bool firstForConfig)
  1496. {
  1497. // TODO: How to use `fileConfig` properly?
  1498. // Write a phony output that depends on the scanning output.
  1499. {
  1500. cmNinjaBuild build("phony");
  1501. build.Comment =
  1502. cmStrCat("Imported C++ module library ", this->GetTargetName());
  1503. this->GetLocalGenerator()->AppendTargetOutputs(this->GetGeneratorTarget(),
  1504. build.Outputs, config);
  1505. if (firstForConfig) {
  1506. this->GetLocalGenerator()->AppendTargetOutputs(
  1507. this->GetGeneratorTarget(),
  1508. this->GetGlobalGenerator()->GetByproductsForCleanTarget(config),
  1509. config);
  1510. }
  1511. build.ExplicitDeps.emplace_back(this->GetDyndepFilePath("CXX", config));
  1512. this->GetGlobalGenerator()->WriteBuild(this->GetCommonFileStream(), build);
  1513. }
  1514. // Add aliases for the target name.
  1515. this->GetGlobalGenerator()->AddTargetAlias(
  1516. this->GetTargetName(), this->GetGeneratorTarget(), config);
  1517. }
  1518. cmGeneratorTarget::Names cmNinjaNormalTargetGenerator::TargetNames(
  1519. std::string const& config) const
  1520. {
  1521. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
  1522. return this->GeneratorTarget->GetExecutableNames(config);
  1523. }
  1524. return this->GeneratorTarget->GetLibraryNames(config);
  1525. }
  1526. std::string cmNinjaNormalTargetGenerator::TargetLinkLanguage(
  1527. std::string const& config) const
  1528. {
  1529. return this->GeneratorTarget->GetLinkerLanguage(config);
  1530. }