cmNinjaNormalTargetGenerator.cxx 65 KB

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