0f01f85c7030979b75f267d6da04c3d26842fac4
[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   std::string path = localGen.GetHomeRelativeOutputPath();
737   if (!path.empty()) {
738     path += '/';
739   }
740   build.RspFile = this->ConvertToNinjaPath(
741     cmStrCat(path, "CMakeFiles/", genTarget->GetName(),
742              globalGen->IsMultiConfig() ? cmStrCat('.', config) : "", ".rsp"));
743
744   // Gather order-only dependencies.
745   this->GetLocalGenerator()->AppendTargetDepends(
746     this->GetGeneratorTarget(), build.OrderOnlyDeps, config, config);
747
748   // Write the build statement for this target.
749   bool usedResponseFile = false;
750   globalGen->WriteBuild(this->GetCommonFileStream(), build,
751                         commandLineLengthLimit, &usedResponseFile);
752   this->WriteDeviceLinkRule(usedResponseFile, config);
753 }
754
755 void cmNinjaNormalTargetGenerator::WriteLinkStatement(
756   const std::string& config, const std::string& fileConfig,
757   bool firstForConfig)
758 {
759   cmMakefile* mf = this->GetMakefile();
760   cmGlobalNinjaGenerator* globalGen = this->GetGlobalGenerator();
761   cmGeneratorTarget* gt = this->GetGeneratorTarget();
762
763   std::string targetOutput = ConvertToNinjaPath(gt->GetFullPath(config));
764   std::string targetOutputReal = ConvertToNinjaPath(
765     gt->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact,
766                     /*realname=*/true));
767   std::string targetOutputImplib = ConvertToNinjaPath(
768     gt->GetFullPath(config, cmStateEnums::ImportLibraryArtifact));
769
770   if (config != fileConfig) {
771     if (targetOutput == ConvertToNinjaPath(gt->GetFullPath(fileConfig))) {
772       return;
773     }
774     if (targetOutputReal ==
775         ConvertToNinjaPath(gt->GetFullPath(fileConfig,
776                                            cmStateEnums::RuntimeBinaryArtifact,
777                                            /*realname=*/true))) {
778       return;
779     }
780     if (!gt->GetFullName(config, cmStateEnums::ImportLibraryArtifact)
781            .empty() &&
782         !gt->GetFullName(fileConfig, cmStateEnums::ImportLibraryArtifact)
783            .empty() &&
784         targetOutputImplib ==
785           ConvertToNinjaPath(gt->GetFullPath(
786             fileConfig, cmStateEnums::ImportLibraryArtifact))) {
787       return;
788     }
789   }
790
791   auto const tgtNames = this->TargetNames(config);
792   if (gt->IsAppBundleOnApple()) {
793     // Create the app bundle
794     std::string outpath = gt->GetDirectory(config);
795     this->OSXBundleGenerator->CreateAppBundle(tgtNames.Output, outpath,
796                                               config);
797
798     // Calculate the output path
799     targetOutput = cmStrCat(outpath, '/', tgtNames.Output);
800     targetOutput = this->ConvertToNinjaPath(targetOutput);
801     targetOutputReal = cmStrCat(outpath, '/', tgtNames.Real);
802     targetOutputReal = this->ConvertToNinjaPath(targetOutputReal);
803   } else if (gt->IsFrameworkOnApple()) {
804     // Create the library framework.
805
806     cmOSXBundleGenerator::SkipParts bundleSkipParts;
807     if (globalGen->GetName() == "Ninja Multi-Config") {
808       const auto postFix = this->GeneratorTarget->GetFilePostfix(config);
809       // Skip creating Info.plist when there are multiple configurations, and
810       // the current configuration has a postfix. The non-postfix configuration
811       // Info.plist can be used by all the other configurations.
812       if (!postFix.empty()) {
813         bundleSkipParts.infoPlist = true;
814       }
815     }
816
817     this->OSXBundleGenerator->CreateFramework(
818       tgtNames.Output, gt->GetDirectory(config), config, bundleSkipParts);
819   } else if (gt->IsCFBundleOnApple()) {
820     // Create the core foundation bundle.
821     this->OSXBundleGenerator->CreateCFBundle(tgtNames.Output,
822                                              gt->GetDirectory(config), config);
823   }
824
825   // Write comments.
826   cmGlobalNinjaGenerator::WriteDivider(this->GetImplFileStream(fileConfig));
827   const cmStateEnums::TargetType targetType = gt->GetType();
828   this->GetImplFileStream(fileConfig)
829     << "# Link build statements for " << cmState::GetTargetTypeName(targetType)
830     << " target " << this->GetTargetName() << "\n\n";
831
832   cmNinjaBuild linkBuild(this->LanguageLinkerRule(config));
833   cmNinjaVars& vars = linkBuild.Variables;
834
835   // Compute the comment.
836   linkBuild.Comment =
837     cmStrCat("Link the ", this->GetVisibleTypeName(), ' ', targetOutputReal);
838
839   // Compute outputs.
840   linkBuild.Outputs.push_back(targetOutputReal);
841   if (firstForConfig) {
842     globalGen->GetByproductsForCleanTarget(config).push_back(targetOutputReal);
843   }
844
845   if (this->TargetLinkLanguage(config) == "Swift") {
846     vars["SWIFT_LIBRARY_NAME"] = [this, config]() -> std::string {
847       cmGeneratorTarget::Names targetNames =
848         this->GetGeneratorTarget()->GetLibraryNames(config);
849       return targetNames.Base;
850     }();
851
852     vars["SWIFT_MODULE_NAME"] = [gt]() -> std::string {
853       if (cmProp name = gt->GetProperty("Swift_MODULE_NAME")) {
854         return *name;
855       }
856       return gt->GetName();
857     }();
858
859     vars["SWIFT_MODULE"] = [this](const std::string& module) -> std::string {
860       std::string directory =
861         this->GetLocalGenerator()->GetCurrentBinaryDirectory();
862       if (cmProp prop = this->GetGeneratorTarget()->GetProperty(
863             "Swift_MODULE_DIRECTORY")) {
864         directory = *prop;
865       }
866
867       std::string name = module + ".swiftmodule";
868       if (cmProp prop =
869             this->GetGeneratorTarget()->GetProperty("Swift_MODULE")) {
870         name = *prop;
871       }
872
873       return this->GetLocalGenerator()->ConvertToOutputFormat(
874         this->ConvertToNinjaPath(directory + "/" + name),
875         cmOutputConverter::SHELL);
876     }(vars["SWIFT_MODULE_NAME"]);
877
878     const std::string map = cmStrCat(gt->GetSupportDirectory(), '/', config,
879                                      '/', "output-file-map.json");
880     vars["SWIFT_OUTPUT_FILE_MAP"] =
881       this->GetLocalGenerator()->ConvertToOutputFormat(
882         this->ConvertToNinjaPath(map), cmOutputConverter::SHELL);
883
884     vars["SWIFT_SOURCES"] = [this, config]() -> std::string {
885       std::vector<cmSourceFile const*> sources;
886       std::stringstream oss;
887
888       this->GetGeneratorTarget()->GetObjectSources(sources, config);
889       cmLocalGenerator const* LocalGen = this->GetLocalGenerator();
890       for (const auto& source : sources) {
891         oss << " "
892             << LocalGen->ConvertToOutputFormat(
893                  this->ConvertToNinjaPath(this->GetSourceFilePath(source)),
894                  cmOutputConverter::SHELL);
895       }
896       return oss.str();
897     }();
898
899     // Since we do not perform object builds, compute the
900     // defines/flags/includes here so that they can be passed along
901     // appropriately.
902     vars["DEFINES"] = this->GetDefines("Swift", config);
903     vars["FLAGS"] = this->GetFlags("Swift", config);
904     vars["INCLUDES"] = this->GetIncludes("Swift", config);
905   }
906
907   // Compute specific libraries to link with.
908   if (this->TargetLinkLanguage(config) == "Swift") {
909     std::vector<cmSourceFile const*> sources;
910     gt->GetObjectSources(sources, config);
911     for (const auto& source : sources) {
912       linkBuild.Outputs.push_back(
913         this->ConvertToNinjaPath(this->GetObjectFilePath(source, config)));
914       linkBuild.ExplicitDeps.push_back(
915         this->ConvertToNinjaPath(this->GetSourceFilePath(source)));
916     }
917
918     linkBuild.Outputs.push_back(vars["SWIFT_MODULE"]);
919   } else {
920     linkBuild.ExplicitDeps = this->GetObjects(config);
921   }
922   linkBuild.ImplicitDeps =
923     this->ComputeLinkDeps(this->TargetLinkLanguage(config), config);
924
925   if (!this->DeviceLinkObject.empty()) {
926     linkBuild.ExplicitDeps.push_back(this->DeviceLinkObject);
927   }
928
929   std::string frameworkPath;
930   std::string linkPath;
931
932   std::string createRule =
933     gt->GetCreateRuleVariable(this->TargetLinkLanguage(config), config);
934   bool useWatcomQuote = mf->IsOn(createRule + "_USE_WATCOM_QUOTE");
935   cmLocalNinjaGenerator& localGen = *this->GetLocalGenerator();
936
937   vars["TARGET_FILE"] =
938     localGen.ConvertToOutputFormat(targetOutputReal, cmOutputConverter::SHELL);
939
940   std::unique_ptr<cmLinkLineComputer> linkLineComputer =
941     globalGen->CreateLinkLineComputer(
942       this->GetLocalGenerator(),
943       this->GetLocalGenerator()->GetStateSnapshot().GetDirectory());
944   linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
945   linkLineComputer->SetUseNinjaMulti(globalGen->IsMultiConfig());
946
947   localGen.GetTargetFlags(linkLineComputer.get(), config,
948                           vars["LINK_LIBRARIES"], vars["FLAGS"],
949                           vars["LINK_FLAGS"], frameworkPath, linkPath, gt);
950
951   // Add OS X version flags, if any.
952   if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
953       this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
954     this->AppendOSXVerFlag(vars["LINK_FLAGS"],
955                            this->TargetLinkLanguage(config), "COMPATIBILITY",
956                            true);
957     this->AppendOSXVerFlag(vars["LINK_FLAGS"],
958                            this->TargetLinkLanguage(config), "CURRENT", false);
959   }
960
961   this->addPoolNinjaVariable("JOB_POOL_LINK", gt, vars);
962
963   this->AddModuleDefinitionFlag(linkLineComputer.get(), vars["LINK_FLAGS"],
964                                 config);
965   vars["LINK_FLAGS"] = globalGen->EncodeLiteral(vars["LINK_FLAGS"]);
966
967   vars["MANIFESTS"] = this->GetManifests(config);
968   vars["AIX_EXPORTS"] = this->GetAIXExports(config);
969
970   vars["LINK_PATH"] = frameworkPath + linkPath;
971   std::string lwyuFlags;
972   if (gt->GetPropertyAsBool("LINK_WHAT_YOU_USE")) {
973     lwyuFlags = " -Wl,--no-as-needed";
974   }
975
976   // Compute architecture specific link flags.  Yes, these go into a different
977   // variable for executables, probably due to a mistake made when duplicating
978   // code between the Makefile executable and library generators.
979   if (targetType == cmStateEnums::EXECUTABLE) {
980     std::string t = vars["FLAGS"];
981     localGen.AddArchitectureFlags(t, gt, this->TargetLinkLanguage(config),
982                                   config);
983     t += lwyuFlags;
984     vars["FLAGS"] = t;
985   } else {
986     std::string t = vars["ARCH_FLAGS"];
987     localGen.AddArchitectureFlags(t, gt, this->TargetLinkLanguage(config),
988                                   config);
989     vars["ARCH_FLAGS"] = t;
990     t.clear();
991     t += lwyuFlags;
992     localGen.AddLanguageFlagsForLinking(
993       t, gt, this->TargetLinkLanguage(config), config);
994     vars["LANGUAGE_COMPILE_FLAGS"] = t;
995   }
996   if (gt->HasSOName(config)) {
997     vars["SONAME_FLAG"] = mf->GetSONameFlag(this->TargetLinkLanguage(config));
998     vars["SONAME"] = tgtNames.SharedObject;
999     if (targetType == cmStateEnums::SHARED_LIBRARY) {
1000       std::string install_dir = gt->GetInstallNameDirForBuildTree(config);
1001       if (!install_dir.empty()) {
1002         vars["INSTALLNAME_DIR"] = localGen.ConvertToOutputFormat(
1003           install_dir, cmOutputConverter::SHELL);
1004       }
1005     }
1006   }
1007
1008   cmNinjaDeps byproducts;
1009
1010   if (!tgtNames.ImportLibrary.empty()) {
1011     const std::string impLibPath = localGen.ConvertToOutputFormat(
1012       targetOutputImplib, cmOutputConverter::SHELL);
1013     vars["TARGET_IMPLIB"] = impLibPath;
1014     EnsureParentDirectoryExists(impLibPath);
1015     if (gt->HasImportLibrary(config)) {
1016       byproducts.push_back(targetOutputImplib);
1017       if (firstForConfig) {
1018         globalGen->GetByproductsForCleanTarget(config).push_back(
1019           targetOutputImplib);
1020       }
1021     }
1022   }
1023
1024   if (!this->SetMsvcTargetPdbVariable(vars, config)) {
1025     // It is common to place debug symbols at a specific place,
1026     // so we need a plain target name in the rule available.
1027     std::string prefix;
1028     std::string base;
1029     std::string suffix;
1030     gt->GetFullNameComponents(prefix, base, suffix, config);
1031     std::string dbg_suffix = ".dbg";
1032     // TODO: Where to document?
1033     if (auto d = mf->GetDefinition("CMAKE_DEBUG_SYMBOL_SUFFIX")) {
1034       dbg_suffix = d;
1035     }
1036     vars["TARGET_PDB"] = base + suffix + dbg_suffix;
1037   }
1038
1039   const std::string objPath =
1040     cmStrCat(gt->GetSupportDirectory(), globalGen->ConfigDirectory(config));
1041   vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
1042     this->ConvertToNinjaPath(objPath), cmOutputConverter::SHELL);
1043   EnsureDirectoryExists(objPath);
1044
1045   std::string& linkLibraries = vars["LINK_LIBRARIES"];
1046   std::string& link_path = vars["LINK_PATH"];
1047   if (globalGen->IsGCCOnWindows()) {
1048     // ar.exe can't handle backslashes in rsp files (implicitly used by gcc)
1049     std::replace(linkLibraries.begin(), linkLibraries.end(), '\\', '/');
1050     std::replace(link_path.begin(), link_path.end(), '\\', '/');
1051   }
1052
1053   const std::vector<cmCustomCommand>* cmdLists[3] = {
1054     &gt->GetPreBuildCommands(), &gt->GetPreLinkCommands(),
1055     &gt->GetPostBuildCommands()
1056   };
1057
1058   std::vector<std::string> preLinkCmdLines;
1059   std::vector<std::string> postBuildCmdLines;
1060
1061   if (config == fileConfig) {
1062     std::vector<std::string>* cmdLineLists[3] = { &preLinkCmdLines,
1063                                                   &preLinkCmdLines,
1064                                                   &postBuildCmdLines };
1065
1066     for (unsigned i = 0; i != 3; ++i) {
1067       for (cmCustomCommand const& cc : *cmdLists[i]) {
1068         cmCustomCommandGenerator ccg(cc, config, this->GetLocalGenerator());
1069         localGen.AppendCustomCommandLines(ccg, *cmdLineLists[i]);
1070         std::vector<std::string> const& ccByproducts = ccg.GetByproducts();
1071         std::transform(ccByproducts.begin(), ccByproducts.end(),
1072                        std::back_inserter(byproducts), MapToNinjaPath());
1073         std::transform(
1074           ccByproducts.begin(), ccByproducts.end(),
1075           std::back_inserter(globalGen->GetByproductsForCleanTarget()),
1076           MapToNinjaPath());
1077       }
1078     }
1079   }
1080
1081   // maybe create .def file from list of objects
1082   cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
1083     gt->GetModuleDefinitionInfo(config);
1084   if (mdi && mdi->DefFileGenerated) {
1085     std::string cmakeCommand =
1086       this->GetLocalGenerator()->ConvertToOutputFormat(
1087         cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
1088     std::string cmd =
1089       cmStrCat(cmakeCommand, " -E __create_def ",
1090                this->GetLocalGenerator()->ConvertToOutputFormat(
1091                  mdi->DefFile, cmOutputConverter::SHELL),
1092                ' ');
1093     std::string obj_list_file = mdi->DefFile + ".objs";
1094     cmd += this->GetLocalGenerator()->ConvertToOutputFormat(
1095       obj_list_file, cmOutputConverter::SHELL);
1096
1097     const char* nm_executable = GetMakefile()->GetDefinition("CMAKE_NM");
1098     if (nm_executable && *nm_executable) {
1099       cmd += " --nm=";
1100       cmd += this->LocalCommonGenerator->ConvertToOutputFormat(
1101         nm_executable, cmOutputConverter::SHELL);
1102     }
1103     preLinkCmdLines.push_back(std::move(cmd));
1104
1105     // create a list of obj files for the -E __create_def to read
1106     cmGeneratedFileStream fout(obj_list_file);
1107
1108     if (mdi->WindowsExportAllSymbols) {
1109       cmNinjaDeps objs = this->GetObjects(config);
1110       for (std::string const& obj : objs) {
1111         if (cmHasLiteralSuffix(obj, ".obj")) {
1112           fout << obj << "\n";
1113         }
1114       }
1115     }
1116
1117     for (cmSourceFile const* src : mdi->Sources) {
1118       fout << src->GetFullPath() << "\n";
1119     }
1120   }
1121   // If we have any PRE_LINK commands, we need to go back to CMAKE_BINARY_DIR
1122   // for the link commands.
1123   if (!preLinkCmdLines.empty()) {
1124     const std::string homeOutDir = localGen.ConvertToOutputFormat(
1125       localGen.GetBinaryDirectory(), cmOutputConverter::SHELL);
1126     preLinkCmdLines.push_back("cd " + homeOutDir);
1127   }
1128
1129   vars["PRE_LINK"] = localGen.BuildCommandLine(preLinkCmdLines, "pre-link",
1130                                                this->GeneratorTarget);
1131   std::string postBuildCmdLine = localGen.BuildCommandLine(
1132     postBuildCmdLines, "post-build", this->GeneratorTarget);
1133
1134   cmNinjaVars symlinkVars;
1135   bool const symlinkNeeded =
1136     (targetOutput != targetOutputReal && !gt->IsFrameworkOnApple());
1137   if (!symlinkNeeded) {
1138     vars["POST_BUILD"] = postBuildCmdLine;
1139   } else {
1140     vars["POST_BUILD"] = cmGlobalNinjaGenerator::SHELL_NOOP;
1141     symlinkVars["POST_BUILD"] = postBuildCmdLine;
1142   }
1143
1144   std::string cmakeVarLang =
1145     cmStrCat("CMAKE_", this->TargetLinkLanguage(config));
1146
1147   // build response file name
1148   std::string cmakeLinkVar = cmakeVarLang + "_RESPONSE_FILE_LINK_FLAG";
1149
1150   const char* flag = GetMakefile()->GetDefinition(cmakeLinkVar);
1151
1152   bool const lang_supports_response =
1153     !(this->TargetLinkLanguage(config) == "RC" ||
1154       (this->TargetLinkLanguage(config) == "CUDA" && !flag));
1155   int commandLineLengthLimit = -1;
1156   if (!lang_supports_response || !this->ForceResponseFile()) {
1157     commandLineLengthLimit =
1158       static_cast<int>(cmSystemTools::CalculateCommandLineLengthLimit()) -
1159       globalGen->GetRuleCmdLength(linkBuild.Rule);
1160   }
1161
1162   std::string path = localGen.GetHomeRelativeOutputPath();
1163   if (!path.empty()) {
1164     path += '/';
1165   }
1166   linkBuild.RspFile = this->ConvertToNinjaPath(
1167     cmStrCat(path, "CMakeFiles/", gt->GetName(),
1168              globalGen->IsMultiConfig() ? cmStrCat('.', config) : "", ".rsp"));
1169
1170   // Gather order-only dependencies.
1171   this->GetLocalGenerator()->AppendTargetDepends(gt, linkBuild.OrderOnlyDeps,
1172                                                  config, fileConfig);
1173
1174   // Add order-only dependencies on versioning symlinks of shared libs we link.
1175   if (!this->GeneratorTarget->IsDLLPlatform()) {
1176     if (cmComputeLinkInformation* cli =
1177           this->GeneratorTarget->GetLinkInformation(config)) {
1178       for (auto const& item : cli->GetItems()) {
1179         if (item.Target &&
1180             item.Target->GetType() == cmStateEnums::SHARED_LIBRARY &&
1181             !item.Target->IsFrameworkOnApple()) {
1182           std::string const& lib =
1183             this->ConvertToNinjaPath(item.Target->GetFullPath(config));
1184           if (std::find(linkBuild.ImplicitDeps.begin(),
1185                         linkBuild.ImplicitDeps.end(),
1186                         lib) == linkBuild.ImplicitDeps.end()) {
1187             linkBuild.OrderOnlyDeps.emplace_back(lib);
1188           }
1189         }
1190       }
1191     }
1192   }
1193
1194   // Ninja should restat after linking if and only if there are byproducts.
1195   vars["RESTAT"] = byproducts.empty() ? "" : "1";
1196
1197   for (std::string const& o : byproducts) {
1198     globalGen->SeenCustomCommandOutput(o);
1199     linkBuild.Outputs.push_back(o);
1200   }
1201
1202   // Write the build statement for this target.
1203   bool usedResponseFile = false;
1204   globalGen->WriteBuild(this->GetImplFileStream(fileConfig), linkBuild,
1205                         commandLineLengthLimit, &usedResponseFile);
1206   this->WriteLinkRule(usedResponseFile, config);
1207
1208   if (symlinkNeeded) {
1209     if (targetType == cmStateEnums::EXECUTABLE) {
1210       cmNinjaBuild build("CMAKE_SYMLINK_EXECUTABLE");
1211       build.Comment = "Create executable symlink " + targetOutput;
1212       build.Outputs.push_back(targetOutput);
1213       if (firstForConfig) {
1214         globalGen->GetByproductsForCleanTarget(config).push_back(targetOutput);
1215       }
1216       build.ExplicitDeps.push_back(targetOutputReal);
1217       build.Variables = std::move(symlinkVars);
1218       globalGen->WriteBuild(this->GetImplFileStream(fileConfig), build);
1219     } else {
1220       cmNinjaBuild build("CMAKE_SYMLINK_LIBRARY");
1221       build.Comment = "Create library symlink " + targetOutput;
1222
1223       std::string const soName = this->ConvertToNinjaPath(
1224         this->GetTargetFilePath(tgtNames.SharedObject, config));
1225       // If one link has to be created.
1226       if (targetOutputReal == soName || targetOutput == soName) {
1227         symlinkVars["SONAME"] =
1228           this->GetLocalGenerator()->ConvertToOutputFormat(
1229             soName, cmOutputConverter::SHELL);
1230       } else {
1231         symlinkVars["SONAME"].clear();
1232         build.Outputs.push_back(soName);
1233         if (firstForConfig) {
1234           globalGen->GetByproductsForCleanTarget(config).push_back(soName);
1235         }
1236       }
1237       build.Outputs.push_back(targetOutput);
1238       if (firstForConfig) {
1239         globalGen->GetByproductsForCleanTarget(config).push_back(targetOutput);
1240       }
1241       build.ExplicitDeps.push_back(targetOutputReal);
1242       build.Variables = std::move(symlinkVars);
1243
1244       globalGen->WriteBuild(this->GetImplFileStream(fileConfig), build);
1245     }
1246   }
1247
1248   // Add aliases for the file name and the target name.
1249   globalGen->AddTargetAlias(tgtNames.Output, gt, config);
1250   globalGen->AddTargetAlias(this->GetTargetName(), gt, config);
1251 }
1252
1253 void cmNinjaNormalTargetGenerator::WriteObjectLibStatement(
1254   const std::string& config)
1255 {
1256   // Write a phony output that depends on all object files.
1257   {
1258     cmNinjaBuild build("phony");
1259     build.Comment = "Object library " + this->GetTargetName();
1260     this->GetLocalGenerator()->AppendTargetOutputs(this->GetGeneratorTarget(),
1261                                                    build.Outputs, config);
1262     this->GetLocalGenerator()->AppendTargetOutputs(
1263       this->GetGeneratorTarget(),
1264       this->GetGlobalGenerator()->GetByproductsForCleanTarget(config), config);
1265     build.ExplicitDeps = this->GetObjects(config);
1266     this->GetGlobalGenerator()->WriteBuild(this->GetCommonFileStream(), build);
1267   }
1268
1269   // Add aliases for the target name.
1270   this->GetGlobalGenerator()->AddTargetAlias(
1271     this->GetTargetName(), this->GetGeneratorTarget(), config);
1272 }
1273
1274 cmGeneratorTarget::Names cmNinjaNormalTargetGenerator::TargetNames(
1275   const std::string& config) const
1276 {
1277   if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
1278     return this->GeneratorTarget->GetExecutableNames(config);
1279   }
1280   return this->GeneratorTarget->GetLibraryNames(config);
1281 }
1282
1283 std::string cmNinjaNormalTargetGenerator::TargetLinkLanguage(
1284   const std::string& config) const
1285 {
1286   return this->GeneratorTarget->GetLinkerLanguage(config);
1287 }