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