cmNinjaNormalTargetGenerator.cxx 55 KB

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