cmNinjaNormalTargetGenerator.cxx 64 KB

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