cmNinjaNormalTargetGenerator.cxx 64 KB

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