cmNinjaNormalTargetGenerator.cxx 63 KB

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