cmNinjaNormalTargetGenerator.cxx 64 KB

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