f30ec27463cd5b440d6bd71880b124d5d6931505
[platform/upstream/cmake.git] / Source / cmMakefileLibraryTargetGenerator.cxx
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 "cmMakefileLibraryTargetGenerator.h"
4
5 #include <cstddef>
6 #include <set>
7 #include <sstream>
8 #include <utility>
9 #include <vector>
10
11 #include <cm/memory>
12 #include <cmext/algorithm>
13
14 #include "cmGeneratedFileStream.h"
15 #include "cmGeneratorTarget.h"
16 #include "cmGlobalUnixMakefileGenerator3.h"
17 #include "cmLinkLineComputer.h"
18 #include "cmLinkLineDeviceComputer.h"
19 #include "cmLocalGenerator.h"
20 #include "cmLocalUnixMakefileGenerator3.h"
21 #include "cmMakefile.h"
22 #include "cmOSXBundleGenerator.h"
23 #include "cmOutputConverter.h"
24 #include "cmRulePlaceholderExpander.h"
25 #include "cmState.h"
26 #include "cmStateDirectory.h"
27 #include "cmStateSnapshot.h"
28 #include "cmStateTypes.h"
29 #include "cmStringAlgorithms.h"
30 #include "cmSystemTools.h"
31 #include "cmValue.h"
32
33 cmMakefileLibraryTargetGenerator::cmMakefileLibraryTargetGenerator(
34   cmGeneratorTarget* target)
35   : cmMakefileTargetGenerator(target)
36 {
37   this->CustomCommandDriver = OnDepends;
38   if (this->GeneratorTarget->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
39     this->TargetNames =
40       this->GeneratorTarget->GetLibraryNames(this->GetConfigName());
41   }
42
43   this->OSXBundleGenerator = cm::make_unique<cmOSXBundleGenerator>(target);
44   this->OSXBundleGenerator->SetMacContentFolders(&this->MacContentFolders);
45 }
46
47 cmMakefileLibraryTargetGenerator::~cmMakefileLibraryTargetGenerator() =
48   default;
49
50 void cmMakefileLibraryTargetGenerator::WriteRuleFiles()
51 {
52   // create the build.make file and directory, put in the common blocks
53   this->CreateRuleFile();
54
55   // write rules used to help build object files
56   this->WriteCommonCodeRules();
57
58   // write the per-target per-language flags
59   this->WriteTargetLanguageFlags();
60
61   // write in rules for object files and custom commands
62   this->WriteTargetBuildRules();
63
64   // write the link rules
65   // Write the rule for this target type.
66   switch (this->GeneratorTarget->GetType()) {
67     case cmStateEnums::STATIC_LIBRARY:
68       this->WriteStaticLibraryRules();
69       break;
70     case cmStateEnums::SHARED_LIBRARY:
71       this->WriteSharedLibraryRules(false);
72       if (this->GeneratorTarget->NeedRelinkBeforeInstall(
73             this->GetConfigName())) {
74         // Write rules to link an installable version of the target.
75         this->WriteSharedLibraryRules(true);
76       }
77       break;
78     case cmStateEnums::MODULE_LIBRARY:
79       this->WriteModuleLibraryRules(false);
80       if (this->GeneratorTarget->NeedRelinkBeforeInstall(
81             this->GetConfigName())) {
82         // Write rules to link an installable version of the target.
83         this->WriteModuleLibraryRules(true);
84       }
85       break;
86     case cmStateEnums::OBJECT_LIBRARY:
87       this->WriteObjectLibraryRules();
88       break;
89     default:
90       // If language is not known, this is an error.
91       cmSystemTools::Error("Unknown Library Type");
92       break;
93   }
94
95   // Write clean target
96   this->WriteTargetCleanRules();
97
98   // Write the dependency generation rule.  This must be done last so
99   // that multiple output pair information is available.
100   this->WriteTargetDependRules();
101
102   // close the streams
103   this->CloseFileStreams();
104 }
105
106 void cmMakefileLibraryTargetGenerator::WriteObjectLibraryRules()
107 {
108   std::vector<std::string> commands;
109   std::vector<std::string> depends;
110
111   // Add post-build rules.
112   this->LocalGenerator->AppendCustomCommands(
113     commands, this->GeneratorTarget->GetPostBuildCommands(),
114     this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
115
116   // Depend on the object files.
117   this->AppendObjectDepends(depends);
118
119   // Write the rule.
120   this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
121                                       this->GeneratorTarget->GetName(),
122                                       depends, commands, true);
123
124   // Write the main driver rule to build everything in this target.
125   this->WriteTargetDriverRule(this->GeneratorTarget->GetName(), false);
126 }
127
128 void cmMakefileLibraryTargetGenerator::WriteStaticLibraryRules()
129 {
130   const bool requiresDeviceLinking = requireDeviceLinking(
131     *this->GeneratorTarget, *this->LocalGenerator, this->GetConfigName());
132   if (requiresDeviceLinking) {
133     this->WriteDeviceLibraryRules("CMAKE_CUDA_DEVICE_LINK_LIBRARY", false);
134   }
135
136   std::string linkLanguage =
137     this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName());
138
139   std::string linkRuleVar = this->GeneratorTarget->GetCreateRuleVariable(
140     linkLanguage, this->GetConfigName());
141
142   std::string extraFlags;
143   this->LocalGenerator->GetStaticLibraryFlags(
144     extraFlags, this->GetConfigName(), linkLanguage, this->GeneratorTarget);
145   this->WriteLibraryRules(linkRuleVar, extraFlags, false);
146 }
147
148 void cmMakefileLibraryTargetGenerator::WriteSharedLibraryRules(bool relink)
149 {
150   if (this->GeneratorTarget->IsFrameworkOnApple()) {
151     this->WriteFrameworkRules(relink);
152     return;
153   }
154
155   if (!relink) {
156     const bool requiresDeviceLinking = requireDeviceLinking(
157       *this->GeneratorTarget, *this->LocalGenerator, this->GetConfigName());
158     if (requiresDeviceLinking) {
159       this->WriteDeviceLibraryRules("CMAKE_CUDA_DEVICE_LINK_LIBRARY", relink);
160     }
161   }
162
163   std::string linkLanguage =
164     this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName());
165   std::string linkRuleVar =
166     cmStrCat("CMAKE_", linkLanguage, "_CREATE_SHARED_LIBRARY");
167
168   std::string extraFlags;
169   this->GetTargetLinkFlags(extraFlags, linkLanguage);
170   this->LocalGenerator->AddConfigVariableFlags(
171     extraFlags, "CMAKE_SHARED_LINKER_FLAGS", this->GetConfigName());
172
173   std::unique_ptr<cmLinkLineComputer> linkLineComputer =
174     this->CreateLinkLineComputer(
175       this->LocalGenerator,
176       this->LocalGenerator->GetStateSnapshot().GetDirectory());
177
178   this->LocalGenerator->AppendModuleDefinitionFlag(
179     extraFlags, this->GeneratorTarget, linkLineComputer.get(),
180     this->GetConfigName());
181
182   this->UseLWYU = this->LocalGenerator->AppendLWYUFlags(
183     extraFlags, this->GeneratorTarget, linkLanguage);
184
185   this->WriteLibraryRules(linkRuleVar, extraFlags, relink);
186 }
187
188 void cmMakefileLibraryTargetGenerator::WriteModuleLibraryRules(bool relink)
189 {
190   if (!relink) {
191     const bool requiresDeviceLinking = requireDeviceLinking(
192       *this->GeneratorTarget, *this->LocalGenerator, this->GetConfigName());
193     if (requiresDeviceLinking) {
194       this->WriteDeviceLibraryRules("CMAKE_CUDA_DEVICE_LINK_LIBRARY", relink);
195     }
196   }
197
198   std::string linkLanguage =
199     this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName());
200   std::string linkRuleVar =
201     cmStrCat("CMAKE_", linkLanguage, "_CREATE_SHARED_MODULE");
202
203   std::string extraFlags;
204   this->GetTargetLinkFlags(extraFlags, linkLanguage);
205   this->LocalGenerator->AddConfigVariableFlags(
206     extraFlags, "CMAKE_MODULE_LINKER_FLAGS", this->GetConfigName());
207
208   std::unique_ptr<cmLinkLineComputer> linkLineComputer =
209     this->CreateLinkLineComputer(
210       this->LocalGenerator,
211       this->LocalGenerator->GetStateSnapshot().GetDirectory());
212
213   this->LocalGenerator->AppendModuleDefinitionFlag(
214     extraFlags, this->GeneratorTarget, linkLineComputer.get(),
215     this->GetConfigName());
216
217   this->WriteLibraryRules(linkRuleVar, extraFlags, relink);
218 }
219
220 void cmMakefileLibraryTargetGenerator::WriteFrameworkRules(bool relink)
221 {
222   std::string linkLanguage =
223     this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName());
224   std::string linkRuleVar =
225     cmStrCat("CMAKE_", linkLanguage, "_CREATE_MACOSX_FRAMEWORK");
226
227   std::string extraFlags;
228   this->GetTargetLinkFlags(extraFlags, linkLanguage);
229   this->LocalGenerator->AddConfigVariableFlags(
230     extraFlags, "CMAKE_MACOSX_FRAMEWORK_LINKER_FLAGS", this->GetConfigName());
231
232   this->WriteLibraryRules(linkRuleVar, extraFlags, relink);
233 }
234
235 void cmMakefileLibraryTargetGenerator::WriteDeviceLibraryRules(
236   const std::string& linkRuleVar, bool relink)
237 {
238 #ifndef CMAKE_BOOTSTRAP
239   // TODO: Merge the methods that call this method to avoid
240   // code duplication.
241   std::vector<std::string> commands;
242   std::string const objExt =
243     this->Makefile->GetSafeDefinition("CMAKE_CUDA_OUTPUT_EXTENSION");
244
245   // Get the name of the device object to generate.
246   std::string const targetOutput =
247     this->GeneratorTarget->ObjectDirectory + "cmake_device_link" + objExt;
248   this->DeviceLinkObject = targetOutput;
249
250   this->NumberOfProgressActions++;
251   if (!this->NoRuleMessages) {
252     cmLocalUnixMakefileGenerator3::EchoProgress progress;
253     this->MakeEchoProgress(progress);
254     // Add the link message.
255     std::string buildEcho = cmStrCat(
256       "Linking CUDA device code ",
257       this->LocalGenerator->ConvertToOutputFormat(
258         this->LocalGenerator->MaybeRelativeToCurBinDir(this->DeviceLinkObject),
259         cmOutputConverter::SHELL));
260     this->LocalGenerator->AppendEcho(
261       commands, buildEcho, cmLocalUnixMakefileGenerator3::EchoLink, &progress);
262   }
263
264   if (this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_ID") == "Clang") {
265     this->WriteDeviceLinkRule(commands, targetOutput);
266   } else {
267     this->WriteNvidiaDeviceLibraryRules(linkRuleVar, relink, commands,
268                                         targetOutput);
269   }
270
271   // Write the main driver rule to build everything in this target.
272   this->WriteTargetDriverRule(targetOutput, relink);
273 }
274
275 void cmMakefileLibraryTargetGenerator::WriteNvidiaDeviceLibraryRules(
276   const std::string& linkRuleVar, bool relink,
277   std::vector<std::string>& commands, const std::string& targetOutput)
278 {
279   std::string linkLanguage = "CUDA";
280
281   // Build list of dependencies.
282   std::vector<std::string> depends;
283   this->AppendLinkDepends(depends, linkLanguage);
284
285   // Add language-specific flags.
286   std::string langFlags;
287   this->LocalGenerator->AddLanguageFlagsForLinking(
288     langFlags, this->GeneratorTarget, linkLanguage, this->GetConfigName());
289
290   // Create set of linking flags.
291   std::string linkFlags;
292   this->GetDeviceLinkFlags(linkFlags, linkLanguage);
293
294   // Clean files associated with this library.
295   std::set<std::string> libCleanFiles;
296   libCleanFiles.insert(
297     this->LocalGenerator->MaybeRelativeToCurBinDir(targetOutput));
298
299   // Determine whether a link script will be used.
300   bool useLinkScript = this->GlobalGenerator->GetUseLinkScript();
301
302   bool useResponseFileForObjects =
303     this->CheckUseResponseFileForObjects(linkLanguage);
304   bool const useResponseFileForLibs =
305     this->CheckUseResponseFileForLibraries(linkLanguage);
306
307   cmRulePlaceholderExpander::RuleVariables vars;
308   vars.Language = linkLanguage.c_str();
309
310   // Expand the rule variables.
311   std::vector<std::string> real_link_commands;
312   {
313     // Set path conversion for link script shells.
314     this->LocalGenerator->SetLinkScriptShell(useLinkScript);
315
316     // Collect up flags to link in needed libraries.
317     std::string linkLibs;
318     std::unique_ptr<cmLinkLineComputer> linkLineComputer(
319       new cmLinkLineDeviceComputer(
320         this->LocalGenerator,
321         this->LocalGenerator->GetStateSnapshot().GetDirectory()));
322     linkLineComputer->SetForResponse(useResponseFileForLibs);
323     linkLineComputer->SetRelink(relink);
324
325     this->CreateLinkLibs(linkLineComputer.get(), linkLibs,
326                          useResponseFileForLibs, depends);
327
328     // Construct object file lists that may be needed to expand the
329     // rule.
330     std::string buildObjs;
331     this->CreateObjectLists(useLinkScript, false, // useArchiveRules
332                             useResponseFileForObjects, buildObjs, depends,
333                             false);
334
335     std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
336     objectDir = this->LocalGenerator->ConvertToOutputFormat(
337       this->LocalGenerator->MaybeRelativeToCurBinDir(objectDir),
338       cmOutputConverter::SHELL);
339
340     std::string target = this->LocalGenerator->ConvertToOutputFormat(
341       this->LocalGenerator->MaybeRelativeToCurBinDir(targetOutput),
342       cmOutputConverter::SHELL);
343
344     std::string targetFullPathCompilePDB =
345       this->ComputeTargetCompilePDB(this->GetConfigName());
346     std::string targetOutPathCompilePDB =
347       this->LocalGenerator->ConvertToOutputFormat(targetFullPathCompilePDB,
348                                                   cmOutputConverter::SHELL);
349
350     vars.Objects = buildObjs.c_str();
351     vars.ObjectDir = objectDir.c_str();
352     vars.Target = target.c_str();
353     vars.LinkLibraries = linkLibs.c_str();
354     vars.ObjectsQuoted = buildObjs.c_str();
355     vars.LanguageCompileFlags = langFlags.c_str();
356     vars.LinkFlags = linkFlags.c_str();
357     vars.TargetCompilePDB = targetOutPathCompilePDB.c_str();
358
359     std::string launcher;
360     cmValue val = this->LocalGenerator->GetRuleLauncher(this->GeneratorTarget,
361                                                         "RULE_LAUNCH_LINK");
362     if (cmNonempty(val)) {
363       launcher = cmStrCat(*val, ' ');
364     }
365
366     std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
367       this->LocalGenerator->CreateRulePlaceholderExpander());
368
369     // Construct the main link rule and expand placeholders.
370     rulePlaceholderExpander->SetTargetImpLib(targetOutput);
371     std::string linkRule = this->GetLinkRule(linkRuleVar);
372     cmExpandList(linkRule, real_link_commands);
373
374     // Expand placeholders.
375     for (std::string& real_link_command : real_link_commands) {
376       real_link_command = cmStrCat(launcher, real_link_command);
377       rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
378                                                    real_link_command, vars);
379     }
380     // Restore path conversion to normal shells.
381     this->LocalGenerator->SetLinkScriptShell(false);
382
383     // Clean all the possible library names and symlinks.
384     this->CleanFiles.insert(libCleanFiles.begin(), libCleanFiles.end());
385   }
386
387   std::vector<std::string> commands1;
388   // Optionally convert the build rule to use a script to avoid long
389   // command lines in the make shell.
390   if (useLinkScript) {
391     // Use a link script.
392     const char* name = (relink ? "drelink.txt" : "dlink.txt");
393     this->CreateLinkScript(name, real_link_commands, commands1, depends);
394   } else {
395     // No link script.  Just use the link rule directly.
396     commands1 = real_link_commands;
397   }
398   this->LocalGenerator->CreateCDCommand(
399     commands1, this->Makefile->GetCurrentBinaryDirectory(),
400     this->LocalGenerator->GetBinaryDirectory());
401   cm::append(commands, commands1);
402   commands1.clear();
403
404   // Compute the list of outputs.
405   std::vector<std::string> outputs(1, targetOutput);
406
407   // Write the build rule.
408   this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs, depends,
409                       commands, false);
410 #else
411   static_cast<void>(linkRuleVar);
412   static_cast<void>(relink);
413 #endif
414 }
415
416 void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
417   const std::string& linkRuleVar, const std::string& extraFlags, bool relink)
418 {
419   // TODO: Merge the methods that call this method to avoid
420   // code duplication.
421   std::vector<std::string> commands;
422
423   // Get the language to use for linking this library.
424   std::string linkLanguage =
425     this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName());
426
427   // Make sure we have a link language.
428   if (linkLanguage.empty()) {
429     cmSystemTools::Error("Cannot determine link language for target \"" +
430                          this->GeneratorTarget->GetName() + "\".");
431     return;
432   }
433
434   // Build list of dependencies.
435   std::vector<std::string> depends;
436   this->AppendLinkDepends(depends, linkLanguage);
437   if (!this->DeviceLinkObject.empty()) {
438     depends.push_back(this->DeviceLinkObject);
439   }
440
441   // Create set of linking flags.
442   std::string linkFlags;
443   this->LocalGenerator->AppendFlags(linkFlags, extraFlags);
444   this->LocalGenerator->AppendIPOLinkerFlags(
445     linkFlags, this->GeneratorTarget, this->GetConfigName(), linkLanguage);
446
447   // Add OSX version flags, if any.
448   if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
449       this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
450     this->AppendOSXVerFlag(linkFlags, linkLanguage, "COMPATIBILITY", true);
451     this->AppendOSXVerFlag(linkFlags, linkLanguage, "CURRENT", false);
452   }
453
454   // Construct the name of the library.
455   this->GeneratorTarget->GetLibraryNames(this->GetConfigName());
456
457   // Construct the full path version of the names.
458   std::string outpath;
459   std::string outpathImp;
460   if (this->GeneratorTarget->IsFrameworkOnApple()) {
461     outpath = this->GeneratorTarget->GetDirectory(this->GetConfigName());
462     this->OSXBundleGenerator->CreateFramework(this->TargetNames.Output,
463                                               outpath, this->GetConfigName());
464     outpath += '/';
465   } else if (this->GeneratorTarget->IsCFBundleOnApple()) {
466     outpath = this->GeneratorTarget->GetDirectory(this->GetConfigName());
467     this->OSXBundleGenerator->CreateCFBundle(this->TargetNames.Output, outpath,
468                                              this->GetConfigName());
469     outpath += '/';
470   } else if (relink) {
471     outpath = cmStrCat(this->Makefile->GetCurrentBinaryDirectory(),
472                        "/CMakeFiles/CMakeRelink.dir");
473     cmSystemTools::MakeDirectory(outpath);
474     outpath += '/';
475     if (!this->TargetNames.ImportLibrary.empty()) {
476       outpathImp = outpath;
477     }
478   } else {
479     outpath = this->GeneratorTarget->GetDirectory(this->GetConfigName());
480     cmSystemTools::MakeDirectory(outpath);
481     outpath += '/';
482     if (!this->TargetNames.ImportLibrary.empty()) {
483       outpathImp = this->GeneratorTarget->GetDirectory(
484         this->GetConfigName(), cmStateEnums::ImportLibraryArtifact);
485       cmSystemTools::MakeDirectory(outpathImp);
486       outpathImp += '/';
487     }
488   }
489
490   std::string compilePdbOutputPath =
491     this->GeneratorTarget->GetCompilePDBDirectory(this->GetConfigName());
492   cmSystemTools::MakeDirectory(compilePdbOutputPath);
493
494   std::string pdbOutputPath =
495     this->GeneratorTarget->GetPDBDirectory(this->GetConfigName());
496   cmSystemTools::MakeDirectory(pdbOutputPath);
497   pdbOutputPath += "/";
498
499   std::string targetFullPath = outpath + this->TargetNames.Output;
500   std::string targetFullPathPDB = pdbOutputPath + this->TargetNames.PDB;
501   std::string targetFullPathSO = outpath + this->TargetNames.SharedObject;
502   std::string targetFullPathReal = outpath + this->TargetNames.Real;
503   std::string targetFullPathImport =
504     outpathImp + this->TargetNames.ImportLibrary;
505
506   // Construct the output path version of the names for use in command
507   // arguments.
508   std::string targetOutPathPDB = this->LocalGenerator->ConvertToOutputFormat(
509     targetFullPathPDB, cmOutputConverter::SHELL);
510
511   std::string targetOutPath = this->LocalGenerator->ConvertToOutputFormat(
512     this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPath),
513     cmOutputConverter::SHELL);
514   std::string targetOutPathSO = this->LocalGenerator->ConvertToOutputFormat(
515     this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathSO),
516     cmOutputConverter::SHELL);
517   std::string targetOutPathReal = this->LocalGenerator->ConvertToOutputFormat(
518     this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathReal),
519     cmOutputConverter::SHELL);
520   std::string targetOutPathImport =
521     this->LocalGenerator->ConvertToOutputFormat(
522       this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathImport),
523       cmOutputConverter::SHELL);
524
525   this->NumberOfProgressActions++;
526   if (!this->NoRuleMessages) {
527     cmLocalUnixMakefileGenerator3::EchoProgress progress;
528     this->MakeEchoProgress(progress);
529     // Add the link message.
530     std::string buildEcho = cmStrCat("Linking ", linkLanguage);
531     switch (this->GeneratorTarget->GetType()) {
532       case cmStateEnums::STATIC_LIBRARY:
533         buildEcho += " static library ";
534         break;
535       case cmStateEnums::SHARED_LIBRARY:
536         buildEcho += " shared library ";
537         break;
538       case cmStateEnums::MODULE_LIBRARY:
539         if (this->GeneratorTarget->IsCFBundleOnApple()) {
540           buildEcho += " CFBundle";
541         }
542         buildEcho += " shared module ";
543         break;
544       default:
545         buildEcho += " library ";
546         break;
547     }
548     buildEcho += targetOutPath;
549     this->LocalGenerator->AppendEcho(
550       commands, buildEcho, cmLocalUnixMakefileGenerator3::EchoLink, &progress);
551   }
552
553   // Clean files associated with this library.
554   std::set<std::string> libCleanFiles;
555   libCleanFiles.insert(
556     this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathReal));
557
558   std::vector<std::string> commands1;
559   // Add a command to remove any existing files for this library.
560   // for static libs only
561   if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
562     this->LocalGenerator->AppendCleanCommand(commands1, libCleanFiles,
563                                              this->GeneratorTarget, "target");
564     this->LocalGenerator->CreateCDCommand(
565       commands1, this->Makefile->GetCurrentBinaryDirectory(),
566       this->LocalGenerator->GetBinaryDirectory());
567     cm::append(commands, commands1);
568     commands1.clear();
569   }
570
571   if (this->TargetNames.Output != this->TargetNames.Real) {
572     libCleanFiles.insert(
573       this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPath));
574   }
575   if (this->TargetNames.SharedObject != this->TargetNames.Real &&
576       this->TargetNames.SharedObject != this->TargetNames.Output) {
577     libCleanFiles.insert(
578       this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathSO));
579   }
580   if (!this->TargetNames.ImportLibrary.empty()) {
581     libCleanFiles.insert(
582       this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathImport));
583     std::string implib;
584     if (this->GeneratorTarget->GetImplibGNUtoMS(
585           this->GetConfigName(), targetFullPathImport, implib)) {
586       libCleanFiles.insert(
587         this->LocalGenerator->MaybeRelativeToCurBinDir(implib));
588     }
589   }
590
591   // List the PDB for cleaning only when the whole target is
592   // cleaned.  We do not want to delete the .pdb file just before
593   // linking the target.
594   this->CleanFiles.insert(
595     this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathPDB));
596
597 #ifdef _WIN32
598   // There may be a manifest file for this target.  Add it to the
599   // clean set just in case.
600   if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY) {
601     libCleanFiles.insert(this->LocalGenerator->MaybeRelativeToCurBinDir(
602       targetFullPath + ".manifest"));
603   }
604 #endif
605
606   // Add the pre-build and pre-link rules building but not when relinking.
607   if (!relink) {
608     this->LocalGenerator->AppendCustomCommands(
609       commands, this->GeneratorTarget->GetPreBuildCommands(),
610       this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
611     this->LocalGenerator->AppendCustomCommands(
612       commands, this->GeneratorTarget->GetPreLinkCommands(),
613       this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
614   }
615
616   // Determine whether a link script will be used.
617   bool useLinkScript = this->GlobalGenerator->GetUseLinkScript();
618
619   bool useResponseFileForObjects =
620     this->CheckUseResponseFileForObjects(linkLanguage);
621   bool const useResponseFileForLibs =
622     this->CheckUseResponseFileForLibraries(linkLanguage);
623
624   // For static libraries there might be archiving rules.
625   bool haveStaticLibraryRule = false;
626   std::vector<std::string> archiveCreateCommands;
627   std::vector<std::string> archiveAppendCommands;
628   std::vector<std::string> archiveFinishCommands;
629   std::string::size_type archiveCommandLimit = std::string::npos;
630   if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
631     haveStaticLibraryRule = this->Makefile->IsDefinitionSet(linkRuleVar);
632     std::string arCreateVar =
633       cmStrCat("CMAKE_", linkLanguage, "_ARCHIVE_CREATE");
634
635     arCreateVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
636       arCreateVar, linkLanguage, this->GetConfigName());
637
638     this->Makefile->GetDefExpandList(arCreateVar, archiveCreateCommands);
639     std::string arAppendVar =
640       cmStrCat("CMAKE_", linkLanguage, "_ARCHIVE_APPEND");
641
642     arAppendVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
643       arAppendVar, linkLanguage, this->GetConfigName());
644
645     this->Makefile->GetDefExpandList(arAppendVar, archiveAppendCommands);
646     std::string arFinishVar =
647       cmStrCat("CMAKE_", linkLanguage, "_ARCHIVE_FINISH");
648
649     arFinishVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
650       arFinishVar, linkLanguage, this->GetConfigName());
651
652     this->Makefile->GetDefExpandList(arFinishVar, archiveFinishCommands);
653   }
654
655   // Decide whether to use archiving rules.
656   bool useArchiveRules = !haveStaticLibraryRule &&
657     !archiveCreateCommands.empty() && !archiveAppendCommands.empty();
658   if (useArchiveRules) {
659     // Archiving rules are always run with a link script.
660     useLinkScript = true;
661
662     // Archiving rules never use a response file.
663     useResponseFileForObjects = false;
664
665     // Limit the length of individual object lists to less than half of
666     // the command line length limit (leaving half for other flags).
667     // This may result in several calls to the archiver.
668     if (size_t limit = cmSystemTools::CalculateCommandLineLengthLimit()) {
669       archiveCommandLimit = limit / 2;
670     } else {
671       archiveCommandLimit = 8000;
672     }
673   }
674
675   // Expand the rule variables.
676   std::vector<std::string> real_link_commands;
677   {
678     bool useWatcomQuote =
679       this->Makefile->IsOn(linkRuleVar + "_USE_WATCOM_QUOTE");
680
681     // Set path conversion for link script shells.
682     this->LocalGenerator->SetLinkScriptShell(useLinkScript);
683
684     // Collect up flags to link in needed libraries.
685     std::string linkLibs;
686     if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY) {
687
688       std::unique_ptr<cmLinkLineComputer> linkLineComputer =
689         this->CreateLinkLineComputer(
690           this->LocalGenerator,
691           this->LocalGenerator->GetStateSnapshot().GetDirectory());
692       linkLineComputer->SetForResponse(useResponseFileForLibs);
693       linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
694       linkLineComputer->SetRelink(relink);
695
696       this->CreateLinkLibs(linkLineComputer.get(), linkLibs,
697                            useResponseFileForLibs, depends);
698     }
699
700     // Construct object file lists that may be needed to expand the
701     // rule.
702     std::string buildObjs;
703     this->CreateObjectLists(useLinkScript, useArchiveRules,
704                             useResponseFileForObjects, buildObjs, depends,
705                             useWatcomQuote);
706     if (!this->DeviceLinkObject.empty()) {
707       buildObjs += " " +
708         this->LocalGenerator->ConvertToOutputFormat(
709           this->LocalGenerator->MaybeRelativeToCurBinDir(
710             this->DeviceLinkObject),
711           cmOutputConverter::SHELL);
712     }
713
714     std::string const& aixExports = this->GetAIXExports(this->GetConfigName());
715
716     // maybe create .def file from list of objects
717     this->GenDefFile(real_link_commands);
718
719     std::string manifests = this->GetManifests(this->GetConfigName());
720
721     cmRulePlaceholderExpander::RuleVariables vars;
722     vars.TargetPDB = targetOutPathPDB.c_str();
723
724     // Setup the target version.
725     std::string targetVersionMajor;
726     std::string targetVersionMinor;
727     {
728       std::ostringstream majorStream;
729       std::ostringstream minorStream;
730       int major;
731       int minor;
732       this->GeneratorTarget->GetTargetVersion(major, minor);
733       majorStream << major;
734       minorStream << minor;
735       targetVersionMajor = majorStream.str();
736       targetVersionMinor = minorStream.str();
737     }
738     vars.TargetVersionMajor = targetVersionMajor.c_str();
739     vars.TargetVersionMinor = targetVersionMinor.c_str();
740
741     vars.CMTargetName = this->GeneratorTarget->GetName().c_str();
742     vars.CMTargetType =
743       cmState::GetTargetTypeName(this->GeneratorTarget->GetType()).c_str();
744     vars.Language = linkLanguage.c_str();
745     vars.AIXExports = aixExports.c_str();
746     vars.Objects = buildObjs.c_str();
747     std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
748
749     objectDir = this->LocalGenerator->ConvertToOutputFormat(
750       this->LocalGenerator->MaybeRelativeToCurBinDir(objectDir),
751       cmOutputConverter::SHELL);
752
753     vars.ObjectDir = objectDir.c_str();
754     cmOutputConverter::OutputFormat output = (useWatcomQuote)
755       ? cmOutputConverter::WATCOMQUOTE
756       : cmOutputConverter::SHELL;
757     std::string target = this->LocalGenerator->ConvertToOutputFormat(
758       this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathReal),
759       output);
760     vars.Target = target.c_str();
761     vars.LinkLibraries = linkLibs.c_str();
762     vars.ObjectsQuoted = buildObjs.c_str();
763     std::string targetOutSOName;
764     if (this->GeneratorTarget->HasSOName(this->GetConfigName())) {
765       vars.SONameFlag = this->Makefile->GetSONameFlag(linkLanguage);
766       targetOutSOName = this->LocalGenerator->ConvertToOutputFormat(
767         this->TargetNames.SharedObject.c_str(), cmOutputConverter::SHELL);
768       vars.TargetSOName = targetOutSOName.c_str();
769     }
770     vars.LinkFlags = linkFlags.c_str();
771
772     vars.Manifests = manifests.c_str();
773
774     // Compute the directory portion of the install_name setting.
775     std::string install_name_dir;
776     if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY) {
777       // Get the install_name directory for the build tree.
778       install_name_dir = this->GeneratorTarget->GetInstallNameDirForBuildTree(
779         this->GetConfigName());
780
781       // Set the rule variable replacement value.
782       if (install_name_dir.empty()) {
783         vars.TargetInstallNameDir = "";
784       } else {
785         // Convert to a path for the native build tool.
786         install_name_dir = this->LocalGenerator->ConvertToOutputFormat(
787           install_name_dir, cmOutputConverter::SHELL);
788         vars.TargetInstallNameDir = install_name_dir.c_str();
789       }
790     }
791
792     // Add language-specific flags.
793     std::string langFlags;
794     this->LocalGenerator->AddLanguageFlagsForLinking(
795       langFlags, this->GeneratorTarget, linkLanguage, this->GetConfigName());
796
797     this->LocalGenerator->AddArchitectureFlags(
798       langFlags, this->GeneratorTarget, linkLanguage, this->GetConfigName());
799
800     vars.LanguageCompileFlags = langFlags.c_str();
801
802     std::string linkerLauncher =
803       this->GetLinkerLauncher(this->GetConfigName());
804     if (cmNonempty(linkerLauncher)) {
805       vars.Launcher = linkerLauncher.c_str();
806     }
807
808     std::string launcher;
809     cmValue val = this->LocalGenerator->GetRuleLauncher(this->GeneratorTarget,
810                                                         "RULE_LAUNCH_LINK");
811     if (cmNonempty(val)) {
812       launcher = cmStrCat(*val, ' ');
813     }
814
815     std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
816       this->LocalGenerator->CreateRulePlaceholderExpander());
817     // Construct the main link rule and expand placeholders.
818     rulePlaceholderExpander->SetTargetImpLib(targetOutPathImport);
819     if (useArchiveRules) {
820       // Construct the individual object list strings.
821       std::vector<std::string> object_strings;
822       this->WriteObjectsStrings(object_strings, archiveCommandLimit);
823
824       // Add the cuda device object to the list of archive files. This will
825       // only occur on archives which have CUDA_RESOLVE_DEVICE_SYMBOLS enabled
826       if (!this->DeviceLinkObject.empty()) {
827         object_strings.push_back(this->LocalGenerator->ConvertToOutputFormat(
828           this->LocalGenerator->MaybeRelativeToCurBinDir(
829             this->DeviceLinkObject),
830           cmOutputConverter::SHELL));
831       }
832
833       // Create the archive with the first set of objects.
834       auto osi = object_strings.begin();
835       {
836         vars.Objects = osi->c_str();
837         for (std::string const& acc : archiveCreateCommands) {
838           std::string cmd = launcher + acc;
839           rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
840                                                        cmd, vars);
841           real_link_commands.push_back(std::move(cmd));
842         }
843       }
844       // Append to the archive with the other object sets.
845       for (++osi; osi != object_strings.end(); ++osi) {
846         vars.Objects = osi->c_str();
847         for (std::string const& aac : archiveAppendCommands) {
848           std::string cmd = launcher + aac;
849           rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
850                                                        cmd, vars);
851           real_link_commands.push_back(std::move(cmd));
852         }
853       }
854       // Finish the archive.
855       vars.Objects = "";
856       for (std::string const& afc : archiveFinishCommands) {
857         std::string cmd = launcher + afc;
858         rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, cmd,
859                                                      vars);
860         // If there is no ranlib the command will be ":".  Skip it.
861         if (!cmd.empty() && cmd[0] != ':') {
862           real_link_commands.push_back(std::move(cmd));
863         }
864       }
865     } else {
866       // Get the set of commands.
867       std::string linkRule = this->GetLinkRule(linkRuleVar);
868       cmExpandList(linkRule, real_link_commands);
869       if (this->UseLWYU) {
870         cmValue lwyuCheck =
871           this->Makefile->GetDefinition("CMAKE_LINK_WHAT_YOU_USE_CHECK");
872         if (lwyuCheck) {
873           std::string cmakeCommand = cmStrCat(
874             this->LocalGenerator->ConvertToOutputFormat(
875               cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL),
876             " -E __run_co_compile --lwyu=");
877           cmakeCommand += this->LocalGenerator->EscapeForShell(*lwyuCheck);
878           cmakeCommand += cmStrCat(" --source=", targetOutPathReal);
879           real_link_commands.push_back(std::move(cmakeCommand));
880         }
881       }
882
883       // Expand placeholders.
884       for (std::string& real_link_command : real_link_commands) {
885         real_link_command = cmStrCat(launcher, real_link_command);
886         rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
887                                                      real_link_command, vars);
888       }
889     }
890
891     // Restore path conversion to normal shells.
892     this->LocalGenerator->SetLinkScriptShell(false);
893   }
894
895   // Optionally convert the build rule to use a script to avoid long
896   // command lines in the make shell.
897   if (useLinkScript) {
898     // Use a link script.
899     const char* name = (relink ? "relink.txt" : "link.txt");
900     this->CreateLinkScript(name, real_link_commands, commands1, depends);
901   } else {
902     // No link script.  Just use the link rule directly.
903     commands1 = real_link_commands;
904   }
905   this->LocalGenerator->CreateCDCommand(
906     commands1, this->Makefile->GetCurrentBinaryDirectory(),
907     this->LocalGenerator->GetBinaryDirectory());
908   cm::append(commands, commands1);
909   commands1.clear();
910
911   // Add a rule to create necessary symlinks for the library.
912   // Frameworks are handled by cmOSXBundleGenerator.
913   if (targetOutPath != targetOutPathReal &&
914       !this->GeneratorTarget->IsFrameworkOnApple()) {
915     std::string symlink =
916       cmStrCat("$(CMAKE_COMMAND) -E cmake_symlink_library ", targetOutPathReal,
917                ' ', targetOutPathSO, ' ', targetOutPath);
918     commands1.push_back(std::move(symlink));
919     this->LocalGenerator->CreateCDCommand(
920       commands1, this->Makefile->GetCurrentBinaryDirectory(),
921       this->LocalGenerator->GetBinaryDirectory());
922     cm::append(commands, commands1);
923     commands1.clear();
924   }
925
926   // Add the post-build rules when building but not when relinking.
927   if (!relink) {
928     this->LocalGenerator->AppendCustomCommands(
929       commands, this->GeneratorTarget->GetPostBuildCommands(),
930       this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
931   }
932
933   // Compute the list of outputs.
934   std::vector<std::string> outputs;
935   outputs.reserve(3);
936   outputs.push_back(targetFullPathReal);
937   if (this->TargetNames.SharedObject != this->TargetNames.Real) {
938     outputs.push_back(targetFullPathSO);
939   }
940   if (this->TargetNames.Output != this->TargetNames.SharedObject &&
941       this->TargetNames.Output != this->TargetNames.Real) {
942     outputs.push_back(targetFullPath);
943   }
944
945   // Write the build rule.
946   this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs, depends,
947                       commands, false);
948
949   // Write the main driver rule to build everything in this target.
950   this->WriteTargetDriverRule(targetFullPath, relink);
951
952   // Clean all the possible library names and symlinks.
953   this->CleanFiles.insert(libCleanFiles.begin(), libCleanFiles.end());
954 }