cmNinjaNormalTargetGenerator.cxx 55 KB

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