cmNinjaNormalTargetGenerator.cxx 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491
  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. if (targetType != cmStateEnums::EXECUTABLE) {
  966. linkBuild.Outputs.push_back(vars["SWIFT_MODULE"]);
  967. }
  968. } else {
  969. linkBuild.ExplicitDeps = this->GetObjects(config);
  970. }
  971. std::vector<std::string> extraISPCObjects =
  972. this->GetGeneratorTarget()->GetGeneratedISPCObjects(config);
  973. std::transform(extraISPCObjects.begin(), extraISPCObjects.end(),
  974. std::back_inserter(linkBuild.ExplicitDeps),
  975. this->MapToNinjaPath());
  976. linkBuild.ImplicitDeps =
  977. this->ComputeLinkDeps(this->TargetLinkLanguage(config), config);
  978. if (!this->DeviceLinkObject.empty()) {
  979. linkBuild.ExplicitDeps.push_back(this->DeviceLinkObject);
  980. }
  981. std::string frameworkPath;
  982. std::string linkPath;
  983. std::string createRule =
  984. gt->GetCreateRuleVariable(this->TargetLinkLanguage(config), config);
  985. bool useWatcomQuote = mf->IsOn(createRule + "_USE_WATCOM_QUOTE");
  986. cmLocalNinjaGenerator& localGen = *this->GetLocalGenerator();
  987. vars["TARGET_FILE"] =
  988. localGen.ConvertToOutputFormat(targetOutputReal, cmOutputConverter::SHELL);
  989. std::unique_ptr<cmLinkLineComputer> linkLineComputer =
  990. globalGen->CreateLinkLineComputer(
  991. this->GetLocalGenerator(),
  992. this->GetLocalGenerator()->GetStateSnapshot().GetDirectory());
  993. linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
  994. linkLineComputer->SetUseNinjaMulti(globalGen->IsMultiConfig());
  995. localGen.GetTargetFlags(linkLineComputer.get(), config,
  996. vars["LINK_LIBRARIES"], vars["FLAGS"],
  997. vars["LINK_FLAGS"], frameworkPath, linkPath, gt);
  998. // Add OS X version flags, if any.
  999. if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  1000. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  1001. this->AppendOSXVerFlag(vars["LINK_FLAGS"],
  1002. this->TargetLinkLanguage(config), "COMPATIBILITY",
  1003. true);
  1004. this->AppendOSXVerFlag(vars["LINK_FLAGS"],
  1005. this->TargetLinkLanguage(config), "CURRENT", false);
  1006. }
  1007. this->addPoolNinjaVariable("JOB_POOL_LINK", gt, vars);
  1008. this->UseLWYU = this->GetLocalGenerator()->AppendLWYUFlags(
  1009. vars["LINK_FLAGS"], this->GetGeneratorTarget(),
  1010. this->TargetLinkLanguage(config));
  1011. vars["LINK_FLAGS"] = globalGen->EncodeLiteral(vars["LINK_FLAGS"]);
  1012. vars["MANIFESTS"] = this->GetManifests(config);
  1013. vars["AIX_EXPORTS"] = this->GetAIXExports(config);
  1014. vars["LINK_PATH"] = frameworkPath + linkPath;
  1015. // Compute architecture specific link flags. Yes, these go into a different
  1016. // variable for executables, probably due to a mistake made when duplicating
  1017. // code between the Makefile executable and library generators.
  1018. if (targetType == cmStateEnums::EXECUTABLE) {
  1019. std::string t = vars["FLAGS"];
  1020. localGen.AddArchitectureFlags(t, gt, this->TargetLinkLanguage(config),
  1021. config);
  1022. vars["FLAGS"] = t;
  1023. } else {
  1024. std::string t = vars["ARCH_FLAGS"];
  1025. localGen.AddArchitectureFlags(t, gt, this->TargetLinkLanguage(config),
  1026. config);
  1027. vars["ARCH_FLAGS"] = t;
  1028. t.clear();
  1029. localGen.AddLanguageFlagsForLinking(
  1030. t, gt, this->TargetLinkLanguage(config), config);
  1031. vars["LANGUAGE_COMPILE_FLAGS"] = t;
  1032. }
  1033. if (gt->HasSOName(config)) {
  1034. vars["SONAME_FLAG"] = mf->GetSONameFlag(this->TargetLinkLanguage(config));
  1035. vars["SONAME"] = localGen.ConvertToOutputFormat(tgtNames.SharedObject,
  1036. cmOutputConverter::SHELL);
  1037. if (targetType == cmStateEnums::SHARED_LIBRARY) {
  1038. std::string install_dir = gt->GetInstallNameDirForBuildTree(config);
  1039. if (!install_dir.empty()) {
  1040. vars["INSTALLNAME_DIR"] = localGen.ConvertToOutputFormat(
  1041. install_dir, cmOutputConverter::SHELL);
  1042. }
  1043. }
  1044. }
  1045. cmGlobalNinjaGenerator::CCOutputs byproducts(this->GetGlobalGenerator());
  1046. if (!tgtNames.ImportLibrary.empty()) {
  1047. const std::string impLibPath = localGen.ConvertToOutputFormat(
  1048. targetOutputImplib, cmOutputConverter::SHELL);
  1049. vars["TARGET_IMPLIB"] = impLibPath;
  1050. this->EnsureParentDirectoryExists(targetOutputImplib);
  1051. if (gt->HasImportLibrary(config)) {
  1052. // Some linkers may update a binary without touching its import lib.
  1053. byproducts.ExplicitOuts.emplace_back(targetOutputImplib);
  1054. if (firstForConfig) {
  1055. globalGen->GetByproductsForCleanTarget(config).push_back(
  1056. targetOutputImplib);
  1057. }
  1058. }
  1059. }
  1060. if (!this->SetMsvcTargetPdbVariable(vars, config)) {
  1061. // It is common to place debug symbols at a specific place,
  1062. // so we need a plain target name in the rule available.
  1063. std::string prefix;
  1064. std::string base;
  1065. std::string suffix;
  1066. gt->GetFullNameComponents(prefix, base, suffix, config);
  1067. std::string dbg_suffix = ".dbg";
  1068. // TODO: Where to document?
  1069. if (cmValue d = mf->GetDefinition("CMAKE_DEBUG_SYMBOL_SUFFIX")) {
  1070. dbg_suffix = *d;
  1071. }
  1072. vars["TARGET_PDB"] = base + suffix + dbg_suffix;
  1073. }
  1074. const std::string objPath =
  1075. cmStrCat(gt->GetSupportDirectory(), globalGen->ConfigDirectory(config));
  1076. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1077. this->ConvertToNinjaPath(objPath), cmOutputConverter::SHELL);
  1078. this->EnsureDirectoryExists(objPath);
  1079. std::string& linkLibraries = vars["LINK_LIBRARIES"];
  1080. std::string& link_path = vars["LINK_PATH"];
  1081. if (globalGen->IsGCCOnWindows()) {
  1082. // ar.exe can't handle backslashes in rsp files (implicitly used by gcc)
  1083. std::replace(linkLibraries.begin(), linkLibraries.end(), '\\', '/');
  1084. std::replace(link_path.begin(), link_path.end(), '\\', '/');
  1085. }
  1086. const std::vector<cmCustomCommand>* cmdLists[3] = {
  1087. &gt->GetPreBuildCommands(), &gt->GetPreLinkCommands(),
  1088. &gt->GetPostBuildCommands()
  1089. };
  1090. std::vector<std::string> preLinkCmdLines;
  1091. std::vector<std::string> postBuildCmdLines;
  1092. std::vector<std::string>* cmdLineLists[3] = { &preLinkCmdLines,
  1093. &preLinkCmdLines,
  1094. &postBuildCmdLines };
  1095. for (unsigned i = 0; i != 3; ++i) {
  1096. for (cmCustomCommand const& cc : *cmdLists[i]) {
  1097. if (config == fileConfig ||
  1098. this->GetLocalGenerator()->HasUniqueByproducts(cc.GetByproducts(),
  1099. cc.GetBacktrace())) {
  1100. cmCustomCommandGenerator ccg(cc, fileConfig, this->GetLocalGenerator(),
  1101. true, config);
  1102. localGen.AppendCustomCommandLines(ccg, *cmdLineLists[i]);
  1103. std::vector<std::string> const& ccByproducts = ccg.GetByproducts();
  1104. byproducts.Add(ccByproducts);
  1105. std::transform(
  1106. ccByproducts.begin(), ccByproducts.end(),
  1107. std::back_inserter(globalGen->GetByproductsForCleanTarget()),
  1108. this->MapToNinjaPath());
  1109. }
  1110. }
  1111. }
  1112. // maybe create .def file from list of objects
  1113. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  1114. gt->GetModuleDefinitionInfo(config);
  1115. if (mdi && mdi->DefFileGenerated) {
  1116. std::string cmakeCommand =
  1117. this->GetLocalGenerator()->ConvertToOutputFormat(
  1118. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  1119. std::string cmd =
  1120. cmStrCat(cmakeCommand, " -E __create_def ",
  1121. this->GetLocalGenerator()->ConvertToOutputFormat(
  1122. mdi->DefFile, cmOutputConverter::SHELL),
  1123. ' ');
  1124. std::string obj_list_file = mdi->DefFile + ".objs";
  1125. cmd += this->GetLocalGenerator()->ConvertToOutputFormat(
  1126. obj_list_file, cmOutputConverter::SHELL);
  1127. cmValue nm_executable = this->GetMakefile()->GetDefinition("CMAKE_NM");
  1128. if (cmNonempty(nm_executable)) {
  1129. cmd += " --nm=";
  1130. cmd += this->LocalCommonGenerator->ConvertToOutputFormat(
  1131. *nm_executable, cmOutputConverter::SHELL);
  1132. }
  1133. preLinkCmdLines.push_back(std::move(cmd));
  1134. // create a list of obj files for the -E __create_def to read
  1135. cmGeneratedFileStream fout(obj_list_file);
  1136. if (mdi->WindowsExportAllSymbols) {
  1137. cmNinjaDeps objs = this->GetObjects(config);
  1138. for (std::string const& obj : objs) {
  1139. if (cmHasLiteralSuffix(obj, ".obj")) {
  1140. fout << obj << "\n";
  1141. }
  1142. }
  1143. }
  1144. for (cmSourceFile const* src : mdi->Sources) {
  1145. fout << src->GetFullPath() << "\n";
  1146. }
  1147. }
  1148. // If we have any PRE_LINK commands, we need to go back to CMAKE_BINARY_DIR
  1149. // for the link commands.
  1150. if (!preLinkCmdLines.empty()) {
  1151. const std::string homeOutDir = localGen.ConvertToOutputFormat(
  1152. localGen.GetBinaryDirectory(), cmOutputConverter::SHELL);
  1153. preLinkCmdLines.push_back("cd " + homeOutDir);
  1154. }
  1155. vars["PRE_LINK"] = localGen.BuildCommandLine(
  1156. preLinkCmdLines, config, fileConfig, "pre-link", this->GeneratorTarget);
  1157. std::string postBuildCmdLine =
  1158. localGen.BuildCommandLine(postBuildCmdLines, config, fileConfig,
  1159. "post-build", this->GeneratorTarget);
  1160. cmNinjaVars symlinkVars;
  1161. bool const symlinkNeeded =
  1162. (targetOutput != targetOutputReal && !gt->IsFrameworkOnApple());
  1163. if (!symlinkNeeded) {
  1164. vars["POST_BUILD"] = postBuildCmdLine;
  1165. } else {
  1166. vars["POST_BUILD"] = cmGlobalNinjaGenerator::SHELL_NOOP;
  1167. symlinkVars["POST_BUILD"] = postBuildCmdLine;
  1168. }
  1169. std::string cmakeVarLang =
  1170. cmStrCat("CMAKE_", this->TargetLinkLanguage(config));
  1171. // build response file name
  1172. std::string cmakeLinkVar = cmakeVarLang + "_RESPONSE_FILE_LINK_FLAG";
  1173. cmValue flag = this->GetMakefile()->GetDefinition(cmakeLinkVar);
  1174. bool const lang_supports_response =
  1175. !(this->TargetLinkLanguage(config) == "RC" ||
  1176. (this->TargetLinkLanguage(config) == "CUDA" && !flag));
  1177. int commandLineLengthLimit = -1;
  1178. if (!lang_supports_response || !this->ForceResponseFile()) {
  1179. commandLineLengthLimit =
  1180. static_cast<int>(cmSystemTools::CalculateCommandLineLengthLimit()) -
  1181. globalGen->GetRuleCmdLength(linkBuild.Rule);
  1182. }
  1183. linkBuild.RspFile = this->ConvertToNinjaPath(
  1184. cmStrCat("CMakeFiles/", gt->GetName(),
  1185. globalGen->IsMultiConfig() ? cmStrCat('.', config) : "", ".rsp"));
  1186. // Gather order-only dependencies.
  1187. this->GetLocalGenerator()->AppendTargetDepends(
  1188. gt, linkBuild.OrderOnlyDeps, config, fileConfig, DependOnTargetArtifact);
  1189. // Add order-only dependencies on versioning symlinks of shared libs we link.
  1190. if (!this->GeneratorTarget->IsDLLPlatform()) {
  1191. if (cmComputeLinkInformation* cli =
  1192. this->GeneratorTarget->GetLinkInformation(config)) {
  1193. for (auto const& item : cli->GetItems()) {
  1194. if (item.Target &&
  1195. item.Target->GetType() == cmStateEnums::SHARED_LIBRARY &&
  1196. !item.Target->IsFrameworkOnApple()) {
  1197. std::string const& lib =
  1198. this->ConvertToNinjaPath(item.Target->GetFullPath(config));
  1199. if (std::find(linkBuild.ImplicitDeps.begin(),
  1200. linkBuild.ImplicitDeps.end(),
  1201. lib) == linkBuild.ImplicitDeps.end()) {
  1202. linkBuild.OrderOnlyDeps.emplace_back(lib);
  1203. }
  1204. }
  1205. }
  1206. }
  1207. }
  1208. // Ninja should restat after linking if and only if there are byproducts.
  1209. vars["RESTAT"] = byproducts.ExplicitOuts.empty() ? "" : "1";
  1210. linkBuild.Outputs.reserve(linkBuild.Outputs.size() +
  1211. byproducts.ExplicitOuts.size());
  1212. std::move(byproducts.ExplicitOuts.begin(), byproducts.ExplicitOuts.end(),
  1213. std::back_inserter(linkBuild.Outputs));
  1214. linkBuild.WorkDirOuts = std::move(byproducts.WorkDirOuts);
  1215. // Write the build statement for this target.
  1216. bool usedResponseFile = false;
  1217. globalGen->WriteBuild(this->GetImplFileStream(fileConfig), linkBuild,
  1218. commandLineLengthLimit, &usedResponseFile);
  1219. this->WriteLinkRule(usedResponseFile, config);
  1220. if (symlinkNeeded) {
  1221. if (targetType == cmStateEnums::EXECUTABLE) {
  1222. cmNinjaBuild build("CMAKE_SYMLINK_EXECUTABLE");
  1223. build.Comment = "Create executable symlink " + targetOutput;
  1224. build.Outputs.push_back(targetOutput);
  1225. if (firstForConfig) {
  1226. globalGen->GetByproductsForCleanTarget(config).push_back(targetOutput);
  1227. }
  1228. build.ExplicitDeps.push_back(targetOutputReal);
  1229. build.Variables = std::move(symlinkVars);
  1230. globalGen->WriteBuild(this->GetImplFileStream(fileConfig), build);
  1231. } else {
  1232. cmNinjaBuild build("CMAKE_SYMLINK_LIBRARY");
  1233. build.Comment = "Create library symlink " + targetOutput;
  1234. std::string const soName = this->ConvertToNinjaPath(
  1235. this->GetTargetFilePath(tgtNames.SharedObject, config));
  1236. // If one link has to be created.
  1237. if (targetOutputReal == soName || targetOutput == soName) {
  1238. symlinkVars["SONAME"] =
  1239. this->GetLocalGenerator()->ConvertToOutputFormat(
  1240. soName, cmOutputConverter::SHELL);
  1241. } else {
  1242. symlinkVars["SONAME"].clear();
  1243. build.Outputs.push_back(soName);
  1244. if (firstForConfig) {
  1245. globalGen->GetByproductsForCleanTarget(config).push_back(soName);
  1246. }
  1247. }
  1248. build.Outputs.push_back(targetOutput);
  1249. if (firstForConfig) {
  1250. globalGen->GetByproductsForCleanTarget(config).push_back(targetOutput);
  1251. }
  1252. build.ExplicitDeps.push_back(targetOutputReal);
  1253. build.Variables = std::move(symlinkVars);
  1254. globalGen->WriteBuild(this->GetImplFileStream(fileConfig), build);
  1255. }
  1256. }
  1257. // Add aliases for the file name and the target name.
  1258. globalGen->AddTargetAlias(tgtNames.Output, gt, config);
  1259. globalGen->AddTargetAlias(this->GetTargetName(), gt, config);
  1260. }
  1261. void cmNinjaNormalTargetGenerator::WriteObjectLibStatement(
  1262. const std::string& config)
  1263. {
  1264. // Write a phony output that depends on all object files.
  1265. {
  1266. cmNinjaBuild build("phony");
  1267. build.Comment = "Object library " + this->GetTargetName();
  1268. this->GetLocalGenerator()->AppendTargetOutputs(this->GetGeneratorTarget(),
  1269. build.Outputs, config);
  1270. this->GetLocalGenerator()->AppendTargetOutputs(
  1271. this->GetGeneratorTarget(),
  1272. this->GetGlobalGenerator()->GetByproductsForCleanTarget(config), config);
  1273. build.ExplicitDeps = this->GetObjects(config);
  1274. this->GetGlobalGenerator()->WriteBuild(this->GetCommonFileStream(), build);
  1275. }
  1276. // Add aliases for the target name.
  1277. this->GetGlobalGenerator()->AddTargetAlias(
  1278. this->GetTargetName(), this->GetGeneratorTarget(), config);
  1279. }
  1280. cmGeneratorTarget::Names cmNinjaNormalTargetGenerator::TargetNames(
  1281. const std::string& config) const
  1282. {
  1283. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
  1284. return this->GeneratorTarget->GetExecutableNames(config);
  1285. }
  1286. return this->GeneratorTarget->GetLibraryNames(config);
  1287. }
  1288. std::string cmNinjaNormalTargetGenerator::TargetLinkLanguage(
  1289. const std::string& config) const
  1290. {
  1291. return this->GeneratorTarget->GetLinkerLanguage(config);
  1292. }