Imported Upstream version 3.25.0
[platform/upstream/cmake.git] / Source / cmLocalGenerator.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 "cmLocalGenerator.h"
4
5 #include <algorithm>
6 #include <array>
7 #include <cassert>
8 #include <cstdio>
9 #include <cstdlib>
10 #include <initializer_list>
11 #include <iterator>
12 #include <sstream>
13 #include <unordered_set>
14 #include <utility>
15 #include <vector>
16
17 #include <cm/memory>
18 #include <cm/optional>
19 #include <cm/string_view>
20 #include <cmext/algorithm>
21 #include <cmext/string_view>
22
23 #include "cmsys/RegularExpression.hxx"
24
25 #include "cmAlgorithms.h"
26 #include "cmComputeLinkInformation.h"
27 #include "cmCustomCommand.h"
28 #include "cmCustomCommandGenerator.h"
29 #include "cmCustomCommandLines.h"
30 #include "cmCustomCommandTypes.h"
31 #include "cmGeneratedFileStream.h"
32 #include "cmGeneratorExpression.h"
33 #include "cmGeneratorExpressionEvaluationFile.h"
34 #include "cmGeneratorTarget.h"
35 #include "cmGlobalGenerator.h"
36 #include "cmInstallGenerator.h"
37 #include "cmInstallScriptGenerator.h"
38 #include "cmInstallTargetGenerator.h"
39 #include "cmLinkLineComputer.h"
40 #include "cmLinkLineDeviceComputer.h"
41 #include "cmMakefile.h"
42 #include "cmRange.h"
43 #include "cmRulePlaceholderExpander.h"
44 #include "cmSourceFile.h"
45 #include "cmSourceFileLocation.h"
46 #include "cmSourceFileLocationKind.h"
47 #include "cmStandardLevelResolver.h"
48 #include "cmState.h"
49 #include "cmStateDirectory.h"
50 #include "cmStateTypes.h"
51 #include "cmStringAlgorithms.h"
52 #include "cmSystemTools.h"
53 #include "cmTarget.h"
54 #include "cmTestGenerator.h"
55 #include "cmValue.h"
56 #include "cmVersion.h"
57 #include "cmake.h"
58
59 #if !defined(CMAKE_BOOTSTRAP)
60 #  define CM_LG_ENCODE_OBJECT_NAMES
61 #  include "cmCryptoHash.h"
62 #endif
63
64 #if defined(__HAIKU__)
65 #  include <FindDirectory.h>
66 #  include <StorageDefs.h>
67 #endif
68
69 // List of variables that are replaced when
70 // rules are expanced.  These variables are
71 // replaced in the form <var> with GetSafeDefinition(var).
72 // ${LANG} is replaced in the variable first with all enabled
73 // languages.
74 static auto ruleReplaceVars = { "CMAKE_${LANG}_COMPILER",
75                                 "CMAKE_SHARED_LIBRARY_CREATE_${LANG}_FLAGS",
76                                 "CMAKE_SHARED_MODULE_CREATE_${LANG}_FLAGS",
77                                 "CMAKE_SHARED_MODULE_${LANG}_FLAGS",
78                                 "CMAKE_SHARED_LIBRARY_${LANG}_FLAGS",
79                                 "CMAKE_${LANG}_LINK_FLAGS",
80                                 "CMAKE_SHARED_LIBRARY_SONAME_${LANG}_FLAG",
81                                 "CMAKE_${LANG}_ARCHIVE",
82                                 "CMAKE_AR",
83                                 "CMAKE_CURRENT_SOURCE_DIR",
84                                 "CMAKE_CURRENT_BINARY_DIR",
85                                 "CMAKE_RANLIB",
86                                 "CMAKE_LINKER",
87                                 "CMAKE_MT",
88                                 "CMAKE_CUDA_HOST_COMPILER",
89                                 "CMAKE_CUDA_HOST_LINK_LAUNCHER",
90                                 "CMAKE_CL_SHOWINCLUDES_PREFIX" };
91
92 cmLocalGenerator::cmLocalGenerator(cmGlobalGenerator* gg, cmMakefile* makefile)
93   : cmOutputConverter(makefile->GetStateSnapshot())
94   , DirectoryBacktrace(makefile->GetBacktrace())
95 {
96   this->GlobalGenerator = gg;
97
98   this->Makefile = makefile;
99
100   this->AliasTargets = makefile->GetAliasTargets();
101
102   this->EmitUniversalBinaryFlags = true;
103   this->BackwardsCompatibility = 0;
104   this->BackwardsCompatibilityFinal = false;
105
106   this->ComputeObjectMaxPath();
107
108   // Canonicalize entries of the CPATH environment variable the same
109   // way detection of CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES does.
110   {
111     std::vector<std::string> cpath;
112     cmSystemTools::GetPath(cpath, "CPATH");
113     for (std::string const& cp : cpath) {
114       if (cmSystemTools::FileIsFullPath(cp)) {
115         this->EnvCPATH.emplace_back(cmSystemTools::CollapseFullPath(cp));
116       }
117     }
118   }
119
120   std::vector<std::string> enabledLanguages =
121     this->GetState()->GetEnabledLanguages();
122
123   if (cmValue sysrootCompile =
124         this->Makefile->GetDefinition("CMAKE_SYSROOT_COMPILE")) {
125     this->CompilerSysroot = *sysrootCompile;
126   } else {
127     this->CompilerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
128   }
129
130   if (cmValue sysrootLink =
131         this->Makefile->GetDefinition("CMAKE_SYSROOT_LINK")) {
132     this->LinkerSysroot = *sysrootLink;
133   } else {
134     this->LinkerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
135   }
136
137   if (cmValue appleArchSysroots =
138         this->Makefile->GetDefinition("CMAKE_APPLE_ARCH_SYSROOTS")) {
139     std::string const& appleArchs =
140       this->Makefile->GetSafeDefinition("CMAKE_OSX_ARCHITECTURES");
141     std::vector<std::string> archs;
142     std::vector<std::string> sysroots;
143     cmExpandList(appleArchs, archs);
144     cmExpandList(*appleArchSysroots, sysroots, true);
145     if (archs.size() == sysroots.size()) {
146       for (size_t i = 0; i < archs.size(); ++i) {
147         this->AppleArchSysroots[archs[i]] = sysroots[i];
148       }
149     } else {
150       std::string const e =
151         cmStrCat("CMAKE_APPLE_ARCH_SYSROOTS:\n  ", *appleArchSysroots,
152                  "\n"
153                  "is not the same length as CMAKE_OSX_ARCHITECTURES:\n  ",
154                  appleArchs);
155       this->IssueMessage(MessageType::FATAL_ERROR, e);
156     }
157   }
158
159   for (std::string const& lang : enabledLanguages) {
160     if (lang == "NONE") {
161       continue;
162     }
163     this->Compilers["CMAKE_" + lang + "_COMPILER"] = lang;
164
165     this->VariableMappings["CMAKE_" + lang + "_COMPILER"] =
166       this->Makefile->GetSafeDefinition("CMAKE_" + lang + "_COMPILER");
167
168     std::string const& compilerArg1 = "CMAKE_" + lang + "_COMPILER_ARG1";
169     std::string const& compilerTarget = "CMAKE_" + lang + "_COMPILER_TARGET";
170     std::string const& compilerOptionTarget =
171       "CMAKE_" + lang + "_COMPILE_OPTIONS_TARGET";
172     std::string const& compilerExternalToolchain =
173       "CMAKE_" + lang + "_COMPILER_EXTERNAL_TOOLCHAIN";
174     std::string const& compilerOptionExternalToolchain =
175       "CMAKE_" + lang + "_COMPILE_OPTIONS_EXTERNAL_TOOLCHAIN";
176     std::string const& compilerOptionSysroot =
177       "CMAKE_" + lang + "_COMPILE_OPTIONS_SYSROOT";
178
179     this->VariableMappings[compilerArg1] =
180       this->Makefile->GetSafeDefinition(compilerArg1);
181     this->VariableMappings[compilerTarget] =
182       this->Makefile->GetSafeDefinition(compilerTarget);
183     this->VariableMappings[compilerOptionTarget] =
184       this->Makefile->GetSafeDefinition(compilerOptionTarget);
185     this->VariableMappings[compilerExternalToolchain] =
186       this->Makefile->GetSafeDefinition(compilerExternalToolchain);
187     this->VariableMappings[compilerOptionExternalToolchain] =
188       this->Makefile->GetSafeDefinition(compilerOptionExternalToolchain);
189     this->VariableMappings[compilerOptionSysroot] =
190       this->Makefile->GetSafeDefinition(compilerOptionSysroot);
191
192     for (std::string replaceVar : ruleReplaceVars) {
193       if (replaceVar.find("${LANG}") != std::string::npos) {
194         cmSystemTools::ReplaceString(replaceVar, "${LANG}", lang);
195       }
196
197       this->VariableMappings[replaceVar] =
198         this->Makefile->GetSafeDefinition(replaceVar);
199     }
200   }
201 }
202
203 cmRulePlaceholderExpander* cmLocalGenerator::CreateRulePlaceholderExpander()
204   const
205 {
206   return new cmRulePlaceholderExpander(this->Compilers, this->VariableMappings,
207                                        this->CompilerSysroot,
208                                        this->LinkerSysroot);
209 }
210
211 cmLocalGenerator::~cmLocalGenerator() = default;
212
213 void cmLocalGenerator::IssueMessage(MessageType t,
214                                     std::string const& text) const
215 {
216   this->GetCMakeInstance()->IssueMessage(t, text, this->DirectoryBacktrace);
217 }
218
219 void cmLocalGenerator::ComputeObjectMaxPath()
220 {
221 // Choose a maximum object file name length.
222 #if defined(_WIN32) || defined(__CYGWIN__)
223   this->ObjectPathMax = 250;
224 #else
225   this->ObjectPathMax = 1000;
226 #endif
227   cmValue plen = this->Makefile->GetDefinition("CMAKE_OBJECT_PATH_MAX");
228   if (cmNonempty(plen)) {
229     unsigned int pmax;
230     if (sscanf(plen->c_str(), "%u", &pmax) == 1) {
231       if (pmax >= 128) {
232         this->ObjectPathMax = pmax;
233       } else {
234         std::ostringstream w;
235         w << "CMAKE_OBJECT_PATH_MAX is set to " << pmax
236           << ", which is less than the minimum of 128.  "
237           << "The value will be ignored.";
238         this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
239       }
240     } else {
241       std::ostringstream w;
242       w << "CMAKE_OBJECT_PATH_MAX is set to \"" << *plen
243         << "\", which fails to parse as a positive integer.  "
244         << "The value will be ignored.";
245       this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
246     }
247   }
248   this->ObjectMaxPathViolations.clear();
249 }
250
251 static void MoveSystemIncludesToEnd(std::vector<std::string>& includeDirs,
252                                     const std::string& config,
253                                     const std::string& lang,
254                                     const cmGeneratorTarget* target)
255 {
256   if (!target) {
257     return;
258   }
259
260   std::stable_sort(
261     includeDirs.begin(), includeDirs.end(),
262     [&target, &config, &lang](std::string const& a, std::string const& b) {
263       return !target->IsSystemIncludeDirectory(a, config, lang) &&
264         target->IsSystemIncludeDirectory(b, config, lang);
265     });
266 }
267
268 static void MoveSystemIncludesToEnd(std::vector<BT<std::string>>& includeDirs,
269                                     const std::string& config,
270                                     const std::string& lang,
271                                     const cmGeneratorTarget* target)
272 {
273   if (!target) {
274     return;
275   }
276
277   std::stable_sort(includeDirs.begin(), includeDirs.end(),
278                    [target, &config, &lang](BT<std::string> const& a,
279                                             BT<std::string> const& b) {
280                      return !target->IsSystemIncludeDirectory(a.Value, config,
281                                                               lang) &&
282                        target->IsSystemIncludeDirectory(b.Value, config, lang);
283                    });
284 }
285
286 void cmLocalGenerator::TraceDependencies() const
287 {
288   // Generate the rule files for each target.
289   const auto& targets = this->GetGeneratorTargets();
290   for (const auto& target : targets) {
291     if (!target->IsInBuildSystem()) {
292       continue;
293     }
294     target->TraceDependencies();
295   }
296 }
297
298 void cmLocalGenerator::GenerateTestFiles()
299 {
300   if (!this->Makefile->IsOn("CMAKE_TESTING_ENABLED")) {
301     return;
302   }
303
304   // Compute the set of configurations.
305   std::vector<std::string> configurationTypes =
306     this->Makefile->GetGeneratorConfigs(cmMakefile::OnlyMultiConfig);
307   std::string config = this->Makefile->GetDefaultConfiguration();
308
309   std::string file =
310     cmStrCat(this->StateSnapshot.GetDirectory().GetCurrentBinary(),
311              "/CTestTestfile.cmake");
312
313   cmGeneratedFileStream fout(file);
314   fout.SetCopyIfDifferent(true);
315
316   fout << "# CMake generated Testfile for \n"
317           "# Source directory: "
318        << this->StateSnapshot.GetDirectory().GetCurrentSource()
319        << "\n"
320           "# Build directory: "
321        << this->StateSnapshot.GetDirectory().GetCurrentBinary()
322        << "\n"
323           "# \n"
324           "# This file includes the relevant testing commands "
325           "required for \n"
326           "# testing this directory and lists subdirectories to "
327           "be tested as well.\n";
328
329   std::string resourceSpecFile =
330     this->Makefile->GetSafeDefinition("CTEST_RESOURCE_SPEC_FILE");
331   if (!resourceSpecFile.empty()) {
332     fout << "set(CTEST_RESOURCE_SPEC_FILE \"" << resourceSpecFile << "\")\n";
333   }
334
335   cmValue testIncludeFile = this->Makefile->GetProperty("TEST_INCLUDE_FILE");
336   if (testIncludeFile) {
337     fout << "include(\"" << *testIncludeFile << "\")\n";
338   }
339
340   cmValue testIncludeFiles = this->Makefile->GetProperty("TEST_INCLUDE_FILES");
341   if (testIncludeFiles) {
342     std::vector<std::string> includesList = cmExpandedList(*testIncludeFiles);
343     for (std::string const& i : includesList) {
344       fout << "include(\"" << i << "\")\n";
345     }
346   }
347
348   // Ask each test generator to write its code.
349   for (const auto& tester : this->Makefile->GetTestGenerators()) {
350     tester->Compute(this);
351     tester->Generate(fout, config, configurationTypes);
352   }
353   using vec_t = std::vector<cmStateSnapshot>;
354   vec_t const& children = this->Makefile->GetStateSnapshot().GetChildren();
355   for (cmStateSnapshot const& i : children) {
356     // TODO: Use add_subdirectory instead?
357     std::string outP = i.GetDirectory().GetCurrentBinary();
358     outP = this->MaybeRelativeToCurBinDir(outP);
359     outP = cmOutputConverter::EscapeForCMake(outP);
360     fout << "subdirs(" << outP << ")\n";
361   }
362
363   // Add directory labels property
364   cmValue directoryLabels =
365     this->Makefile->GetDefinition("CMAKE_DIRECTORY_LABELS");
366   cmValue labels = this->Makefile->GetProperty("LABELS");
367
368   if (labels || directoryLabels) {
369     fout << "set_directory_properties(PROPERTIES LABELS ";
370     if (labels) {
371       fout << cmOutputConverter::EscapeForCMake(*labels);
372     }
373     if (labels && directoryLabels) {
374       fout << ";";
375     }
376     if (directoryLabels) {
377       fout << cmOutputConverter::EscapeForCMake(*directoryLabels);
378     }
379     fout << ")\n";
380   }
381 }
382
383 void cmLocalGenerator::CreateEvaluationFileOutputs()
384 {
385   std::vector<std::string> const& configs =
386     this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
387   for (std::string const& c : configs) {
388     this->CreateEvaluationFileOutputs(c);
389   }
390 }
391
392 void cmLocalGenerator::CreateEvaluationFileOutputs(std::string const& config)
393 {
394   for (const auto& geef : this->Makefile->GetEvaluationFiles()) {
395     geef->CreateOutputFile(this, config);
396   }
397 }
398
399 void cmLocalGenerator::ProcessEvaluationFiles(
400   std::vector<std::string>& generatedFiles)
401 {
402   for (const auto& geef : this->Makefile->GetEvaluationFiles()) {
403     geef->Generate(this);
404     if (cmSystemTools::GetFatalErrorOccurred()) {
405       return;
406     }
407     std::vector<std::string> files = geef->GetFiles();
408     std::sort(files.begin(), files.end());
409
410     std::vector<std::string> intersection;
411     std::set_intersection(files.begin(), files.end(), generatedFiles.begin(),
412                           generatedFiles.end(),
413                           std::back_inserter(intersection));
414     if (!intersection.empty()) {
415       cmSystemTools::Error("Files to be generated by multiple different "
416                            "commands: " +
417                            cmWrap('"', intersection, '"', " "));
418       return;
419     }
420
421     cm::append(generatedFiles, files);
422     std::inplace_merge(generatedFiles.begin(),
423                        generatedFiles.end() - files.size(),
424                        generatedFiles.end());
425   }
426 }
427
428 void cmLocalGenerator::GenerateInstallRules()
429 {
430   // Compute the install prefix.
431   cmValue installPrefix =
432     this->Makefile->GetDefinition("CMAKE_INSTALL_PREFIX");
433   std::string prefix = installPrefix;
434
435 #if defined(_WIN32) && !defined(__CYGWIN__)
436   if (!installPrefix) {
437     if (!cmSystemTools::GetEnv("SystemDrive", prefix)) {
438       prefix = "C:";
439     }
440     cmValue project_name = this->Makefile->GetDefinition("PROJECT_NAME");
441     if (cmNonempty(project_name)) {
442       prefix += "/Program Files/";
443       prefix += *project_name;
444     } else {
445       prefix += "/InstalledCMakeProject";
446     }
447   }
448 #elif defined(__HAIKU__)
449   char dir[B_PATH_NAME_LENGTH];
450   if (!installPrefix) {
451     if (find_directory(B_SYSTEM_DIRECTORY, -1, false, dir, sizeof(dir)) ==
452         B_OK) {
453       prefix = dir;
454     } else {
455       prefix = "/boot/system";
456     }
457   }
458 #else
459   if (!installPrefix) {
460     prefix = "/usr/local";
461   }
462 #endif
463   if (cmValue stagingPrefix =
464         this->Makefile->GetDefinition("CMAKE_STAGING_PREFIX")) {
465     prefix = *stagingPrefix;
466   }
467
468   // Compute the set of configurations.
469   std::vector<std::string> configurationTypes =
470     this->Makefile->GetGeneratorConfigs(cmMakefile::OnlyMultiConfig);
471   std::string config = this->Makefile->GetDefaultConfiguration();
472
473   // Choose a default install configuration.
474   std::string default_config = config;
475   const char* default_order[] = { "RELEASE", "MINSIZEREL", "RELWITHDEBINFO",
476                                   "DEBUG", nullptr };
477   for (const char** c = default_order; *c && default_config.empty(); ++c) {
478     for (std::string const& configurationType : configurationTypes) {
479       if (cmSystemTools::UpperCase(configurationType) == *c) {
480         default_config = configurationType;
481       }
482     }
483   }
484   if (default_config.empty() && !configurationTypes.empty()) {
485     default_config = configurationTypes[0];
486   }
487
488   // Create the install script file.
489   std::string file = this->StateSnapshot.GetDirectory().GetCurrentBinary();
490   std::string homedir = this->GetState()->GetBinaryDirectory();
491   int toplevel_install = 0;
492   if (file == homedir) {
493     toplevel_install = 1;
494   }
495   file += "/cmake_install.cmake";
496   cmGeneratedFileStream fout(file);
497   fout.SetCopyIfDifferent(true);
498
499   // Write the header.
500   /* clang-format off */
501   fout << "# Install script for directory: "
502        << this->StateSnapshot.GetDirectory().GetCurrentSource()
503        << "\n\n"
504           "# Set the install prefix\n"
505           "if(NOT DEFINED CMAKE_INSTALL_PREFIX)\n"
506           "  set(CMAKE_INSTALL_PREFIX \"" << prefix << "\")\n"
507           "endif()\n"
508        << R"(string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX )"
509        << "\"${CMAKE_INSTALL_PREFIX}\")\n\n";
510   /* clang-format on */
511
512   // Write support code for generating per-configuration install rules.
513   /* clang-format off */
514   fout <<
515     "# Set the install configuration name.\n"
516     "if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)\n"
517     "  if(BUILD_TYPE)\n"
518     "    string(REGEX REPLACE \"^[^A-Za-z0-9_]+\" \"\"\n"
519     "           CMAKE_INSTALL_CONFIG_NAME \"${BUILD_TYPE}\")\n"
520     "  else()\n"
521     "    set(CMAKE_INSTALL_CONFIG_NAME \"" << default_config << "\")\n"
522     "  endif()\n"
523     "  message(STATUS \"Install configuration: "
524     "\\\"${CMAKE_INSTALL_CONFIG_NAME}\\\"\")\n"
525     "endif()\n"
526     "\n";
527   /* clang-format on */
528
529   // Write support code for dealing with component-specific installs.
530   /* clang-format off */
531   fout <<
532     "# Set the component getting installed.\n"
533     "if(NOT CMAKE_INSTALL_COMPONENT)\n"
534     "  if(COMPONENT)\n"
535     "    message(STATUS \"Install component: \\\"${COMPONENT}\\\"\")\n"
536     "    set(CMAKE_INSTALL_COMPONENT \"${COMPONENT}\")\n"
537     "  else()\n"
538     "    set(CMAKE_INSTALL_COMPONENT)\n"
539     "  endif()\n"
540     "endif()\n"
541     "\n";
542   /* clang-format on */
543
544   // Copy user-specified install options to the install code.
545   if (cmValue so_no_exe =
546         this->Makefile->GetDefinition("CMAKE_INSTALL_SO_NO_EXE")) {
547     /* clang-format off */
548     fout <<
549       "# Install shared libraries without execute permission?\n"
550       "if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)\n"
551       "  set(CMAKE_INSTALL_SO_NO_EXE \"" << *so_no_exe << "\")\n"
552       "endif()\n"
553       "\n";
554     /* clang-format on */
555   }
556
557   // Copy cmake cross compile state to install code.
558   if (cmValue crosscompiling =
559         this->Makefile->GetDefinition("CMAKE_CROSSCOMPILING")) {
560     /* clang-format off */
561     fout <<
562       "# Is this installation the result of a crosscompile?\n"
563       "if(NOT DEFINED CMAKE_CROSSCOMPILING)\n"
564       "  set(CMAKE_CROSSCOMPILING \"" << *crosscompiling << "\")\n"
565       "endif()\n"
566       "\n";
567     /* clang-format on */
568   }
569
570   // Write default directory permissions.
571   if (cmValue defaultDirPermissions = this->Makefile->GetDefinition(
572         "CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS")) {
573     /* clang-format off */
574     fout <<
575       "# Set default install directory permissions.\n"
576       "if(NOT DEFINED CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS)\n"
577       "  set(CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS \""
578          << *defaultDirPermissions << "\")\n"
579       "endif()\n"
580       "\n";
581     /* clang-format on */
582   }
583
584   // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM so that
585   // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
586   // has same platform variable as when running cmake
587   if (cmValue platform = this->Makefile->GetDefinition(
588         "CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM")) {
589     /* clang-format off */
590     fout <<
591       "# Set default install directory permissions.\n"
592       "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM)\n"
593       "  set(CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM \""
594          << *platform << "\")\n"
595       "endif()\n"
596       "\n";
597     /* clang-format on */
598   }
599
600   // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL so that
601   // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
602   // has same tool selected as when running cmake
603   if (cmValue command =
604         this->Makefile->GetDefinition("CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL")) {
605     /* clang-format off */
606     fout <<
607       "# Set default install directory permissions.\n"
608       "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL)\n"
609       "  set(CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL \""
610          << *command << "\")\n"
611       "endif()\n"
612       "\n";
613     /* clang-format on */
614   }
615
616   // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND so that
617   // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
618   // has same path to the tool as when running cmake
619   if (cmValue command = this->Makefile->GetDefinition(
620         "CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND")) {
621     /* clang-format off */
622     fout <<
623       "# Set default install directory permissions.\n"
624       "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND)\n"
625       "  set(CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND \""
626          << *command << "\")\n"
627       "endif()\n"
628       "\n";
629     /* clang-format on */
630   }
631
632   // Write out CMAKE_OBJDUMP so that installed code that uses
633   // `file(GET_RUNTIME_DEPENDENCIES)` and hasn't specified
634   // CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND has consistent
635   // logic to fallback to CMAKE_OBJDUMP when `objdump` is
636   // not on the path
637   if (cmValue command = this->Makefile->GetDefinition("CMAKE_OBJDUMP")) {
638     /* clang-format off */
639     fout <<
640       "# Set default install directory permissions.\n"
641       "if(NOT DEFINED CMAKE_OBJDUMP)\n"
642       "  set(CMAKE_OBJDUMP \""
643          << *command << "\")\n"
644       "endif()\n"
645       "\n";
646     /* clang-format on */
647   }
648
649   this->AddGeneratorSpecificInstallSetup(fout);
650
651   // Ask each install generator to write its code.
652   cmPolicies::PolicyStatus status = this->GetPolicyStatus(cmPolicies::CMP0082);
653   auto const& installers = this->Makefile->GetInstallGenerators();
654   bool haveSubdirectoryInstall = false;
655   bool haveInstallAfterSubdirectory = false;
656   if (status == cmPolicies::WARN) {
657     for (const auto& installer : installers) {
658       installer->CheckCMP0082(haveSubdirectoryInstall,
659                               haveInstallAfterSubdirectory);
660       installer->Generate(fout, config, configurationTypes);
661     }
662   } else {
663     for (const auto& installer : installers) {
664       installer->Generate(fout, config, configurationTypes);
665     }
666   }
667
668   // Write rules from old-style specification stored in targets.
669   this->GenerateTargetInstallRules(fout, config, configurationTypes);
670
671   // Include install scripts from subdirectories.
672   switch (status) {
673     case cmPolicies::WARN:
674       if (haveInstallAfterSubdirectory &&
675           this->Makefile->PolicyOptionalWarningEnabled(
676             "CMAKE_POLICY_WARNING_CMP0082")) {
677         std::ostringstream e;
678         e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0082) << "\n";
679         this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
680       }
681       CM_FALLTHROUGH;
682     case cmPolicies::OLD: {
683       std::vector<cmStateSnapshot> children =
684         this->Makefile->GetStateSnapshot().GetChildren();
685       if (!children.empty()) {
686         fout << "if(NOT CMAKE_INSTALL_LOCAL_ONLY)\n";
687         fout << "  # Include the install script for each subdirectory.\n";
688         for (cmStateSnapshot const& c : children) {
689           if (!c.GetDirectory().GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
690             std::string odir = c.GetDirectory().GetCurrentBinary();
691             cmSystemTools::ConvertToUnixSlashes(odir);
692             fout << "  include(\"" << odir << "/cmake_install.cmake\")\n";
693           }
694         }
695         fout << "\n";
696         fout << "endif()\n\n";
697       }
698     } break;
699
700     case cmPolicies::REQUIRED_IF_USED:
701     case cmPolicies::REQUIRED_ALWAYS:
702     case cmPolicies::NEW:
703       // NEW behavior is handled in
704       // cmInstallSubdirectoryGenerator::GenerateScript()
705       break;
706   }
707
708   // Record the install manifest.
709   if (toplevel_install) {
710     /* clang-format off */
711     fout <<
712       "if(CMAKE_INSTALL_COMPONENT)\n"
713       "  set(CMAKE_INSTALL_MANIFEST \"install_manifest_"
714       "${CMAKE_INSTALL_COMPONENT}.txt\")\n"
715       "else()\n"
716       "  set(CMAKE_INSTALL_MANIFEST \"install_manifest.txt\")\n"
717       "endif()\n"
718       "\n"
719       "string(REPLACE \";\" \"\\n\" CMAKE_INSTALL_MANIFEST_CONTENT\n"
720       "       \"${CMAKE_INSTALL_MANIFEST_FILES}\")\n"
721       "file(WRITE \"" << homedir << "/${CMAKE_INSTALL_MANIFEST}\"\n"
722       "     \"${CMAKE_INSTALL_MANIFEST_CONTENT}\")\n";
723     /* clang-format on */
724   }
725 }
726
727 void cmLocalGenerator::AddGeneratorTarget(
728   std::unique_ptr<cmGeneratorTarget> gt)
729 {
730   cmGeneratorTarget* gt_ptr = gt.get();
731
732   this->GeneratorTargets.push_back(std::move(gt));
733   this->GeneratorTargetSearchIndex.emplace(gt_ptr->GetName(), gt_ptr);
734   this->GlobalGenerator->IndexGeneratorTarget(gt_ptr);
735 }
736
737 void cmLocalGenerator::AddImportedGeneratorTarget(cmGeneratorTarget* gt)
738 {
739   this->ImportedGeneratorTargets.emplace(gt->GetName(), gt);
740   this->GlobalGenerator->IndexGeneratorTarget(gt);
741 }
742
743 void cmLocalGenerator::AddOwnedImportedGeneratorTarget(
744   std::unique_ptr<cmGeneratorTarget> gt)
745 {
746   this->OwnedImportedGeneratorTargets.push_back(std::move(gt));
747 }
748
749 cmGeneratorTarget* cmLocalGenerator::FindLocalNonAliasGeneratorTarget(
750   const std::string& name) const
751 {
752   auto ti = this->GeneratorTargetSearchIndex.find(name);
753   if (ti != this->GeneratorTargetSearchIndex.end()) {
754     return ti->second;
755   }
756   return nullptr;
757 }
758
759 void cmLocalGenerator::ComputeTargetManifest()
760 {
761   // Collect the set of configuration types.
762   std::vector<std::string> configNames =
763     this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
764
765   // Add our targets to the manifest for each configuration.
766   const auto& targets = this->GetGeneratorTargets();
767   for (const auto& target : targets) {
768     if (!target->IsInBuildSystem()) {
769       continue;
770     }
771     for (std::string const& c : configNames) {
772       target->ComputeTargetManifest(c);
773     }
774   }
775 }
776
777 bool cmLocalGenerator::ComputeTargetCompileFeatures()
778 {
779   // Collect the set of configuration types.
780   std::vector<std::string> configNames =
781     this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
782
783   using LanguagePair = std::pair<std::string, std::string>;
784   std::vector<LanguagePair> pairedLanguages{
785     { "OBJC", "C" }, { "OBJCXX", "CXX" }, { "CUDA", "CXX" }, { "HIP", "CXX" }
786   };
787   std::set<LanguagePair> inferredEnabledLanguages;
788   for (auto const& lang : pairedLanguages) {
789     if (this->Makefile->GetState()->GetLanguageEnabled(lang.first)) {
790       inferredEnabledLanguages.insert(lang);
791     }
792   }
793
794   // Process compile features of all targets.
795   const auto& targets = this->GetGeneratorTargets();
796   for (const auto& target : targets) {
797     for (std::string const& c : configNames) {
798       if (!target->ComputeCompileFeatures(c)) {
799         return false;
800       }
801     }
802
803     // Now that C/C++ _STANDARD values have been computed
804     // set the values to ObjC/ObjCXX _STANDARD variables
805     if (target->CanCompileSources()) {
806       for (std::string const& c : configNames) {
807         target->ComputeCompileFeatures(c, inferredEnabledLanguages);
808       }
809     }
810   }
811
812   return true;
813 }
814
815 bool cmLocalGenerator::IsRootMakefile() const
816 {
817   return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
818 }
819
820 cmState* cmLocalGenerator::GetState() const
821 {
822   return this->GlobalGenerator->GetCMakeInstance()->GetState();
823 }
824
825 cmStateSnapshot cmLocalGenerator::GetStateSnapshot() const
826 {
827   return this->Makefile->GetStateSnapshot();
828 }
829
830 cmValue cmLocalGenerator::GetRuleLauncher(cmGeneratorTarget* target,
831                                           const std::string& prop)
832 {
833   if (target) {
834     return target->GetProperty(prop);
835   }
836   return this->Makefile->GetProperty(prop);
837 }
838
839 std::string cmLocalGenerator::ConvertToIncludeReference(
840   std::string const& path, OutputFormat format)
841 {
842   return this->ConvertToOutputForExisting(path, format);
843 }
844
845 std::string cmLocalGenerator::GetIncludeFlags(
846   std::vector<std::string> const& includeDirs, cmGeneratorTarget* target,
847   std::string const& lang, std::string const& config, bool forResponseFile)
848 {
849   if (lang.empty()) {
850     return "";
851   }
852
853   std::vector<std::string> includes = includeDirs;
854   MoveSystemIncludesToEnd(includes, config, lang, target);
855
856   OutputFormat shellFormat = forResponseFile ? RESPONSE : SHELL;
857   std::ostringstream includeFlags;
858
859   std::string const& includeFlag =
860     this->Makefile->GetSafeDefinition(cmStrCat("CMAKE_INCLUDE_FLAG_", lang));
861   bool quotePaths = false;
862   if (this->Makefile->GetDefinition("CMAKE_QUOTE_INCLUDE_PATHS")) {
863     quotePaths = true;
864   }
865   std::string sep = " ";
866   bool repeatFlag = true;
867   // should the include flag be repeated like ie. -IA -IB
868   if (cmValue incSep = this->Makefile->GetDefinition(
869         cmStrCat("CMAKE_INCLUDE_FLAG_SEP_", lang))) {
870     // if there is a separator then the flag is not repeated but is only
871     // given once i.e.  -classpath a:b:c
872     sep = incSep;
873     repeatFlag = false;
874   }
875
876   // Support special system include flag if it is available and the
877   // normal flag is repeated for each directory.
878   cmValue sysIncludeFlag = nullptr;
879   cmValue sysIncludeFlagWarning = nullptr;
880   if (repeatFlag) {
881     sysIncludeFlag = this->Makefile->GetDefinition(
882       cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", lang));
883     sysIncludeFlagWarning = this->Makefile->GetDefinition(
884       cmStrCat("_CMAKE_INCLUDE_SYSTEM_FLAG_", lang, "_WARNING"));
885   }
886
887   cmValue fwSearchFlag = this->Makefile->GetDefinition(
888     cmStrCat("CMAKE_", lang, "_FRAMEWORK_SEARCH_FLAG"));
889   cmValue sysFwSearchFlag = this->Makefile->GetDefinition(
890     cmStrCat("CMAKE_", lang, "_SYSTEM_FRAMEWORK_SEARCH_FLAG"));
891
892   bool flagUsed = false;
893   bool sysIncludeFlagUsed = false;
894   std::set<std::string> emitted;
895 #ifdef __APPLE__
896   emitted.insert("/System/Library/Frameworks");
897 #endif
898   for (std::string const& i : includes) {
899     if (cmNonempty(fwSearchFlag) && this->Makefile->IsOn("APPLE") &&
900         cmSystemTools::IsPathToFramework(i)) {
901       std::string const frameworkDir =
902         cmSystemTools::CollapseFullPath(cmStrCat(i, "/../"));
903       if (emitted.insert(frameworkDir).second) {
904         if (sysFwSearchFlag && target &&
905             target->IsSystemIncludeDirectory(i, config, lang)) {
906           includeFlags << *sysFwSearchFlag;
907         } else {
908           includeFlags << *fwSearchFlag;
909         }
910         includeFlags << this->ConvertToOutputFormat(frameworkDir, shellFormat)
911                      << " ";
912       }
913       continue;
914     }
915
916     if (!flagUsed || repeatFlag) {
917       if (sysIncludeFlag && target &&
918           target->IsSystemIncludeDirectory(i, config, lang)) {
919         includeFlags << *sysIncludeFlag;
920         sysIncludeFlagUsed = true;
921       } else {
922         includeFlags << includeFlag;
923       }
924       flagUsed = true;
925     }
926     std::string includePath = this->ConvertToIncludeReference(i, shellFormat);
927     if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
928       includeFlags << "\"";
929     }
930     includeFlags << includePath;
931     if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
932       includeFlags << "\"";
933     }
934     includeFlags << sep;
935   }
936   if (sysIncludeFlagUsed && sysIncludeFlagWarning) {
937     includeFlags << *sysIncludeFlagWarning;
938   }
939   std::string flags = includeFlags.str();
940   // remove trailing separators
941   if ((sep[0] != ' ') && !flags.empty() && flags.back() == sep[0]) {
942     flags.back() = ' ';
943   }
944   return cmTrimWhitespace(flags);
945 }
946
947 void cmLocalGenerator::AddCompileOptions(std::string& flags,
948                                          cmGeneratorTarget* target,
949                                          const std::string& lang,
950                                          const std::string& config)
951 {
952   std::vector<BT<std::string>> tmpFlags;
953   this->AddCompileOptions(tmpFlags, target, lang, config);
954   this->AppendFlags(flags, tmpFlags);
955 }
956
957 void cmLocalGenerator::AddCompileOptions(std::vector<BT<std::string>>& flags,
958                                          cmGeneratorTarget* target,
959                                          const std::string& lang,
960                                          const std::string& config)
961 {
962   std::string langFlagRegexVar = cmStrCat("CMAKE_", lang, "_FLAG_REGEX");
963
964   if (cmValue langFlagRegexStr =
965         this->Makefile->GetDefinition(langFlagRegexVar)) {
966     // Filter flags acceptable to this language.
967     if (cmValue targetFlags = target->GetProperty("COMPILE_FLAGS")) {
968       std::vector<std::string> opts;
969       cmSystemTools::ParseWindowsCommandLine(targetFlags->c_str(), opts);
970       // Re-escape these flags since COMPILE_FLAGS were already parsed
971       // as a command line above.
972       std::string compileOpts;
973       this->AppendCompileOptions(compileOpts, opts, langFlagRegexStr->c_str());
974       if (!compileOpts.empty()) {
975         flags.emplace_back(std::move(compileOpts));
976       }
977     }
978     std::vector<BT<std::string>> targetCompileOpts =
979       target->GetCompileOptions(config, lang);
980     // COMPILE_OPTIONS are escaped.
981     this->AppendCompileOptions(flags, targetCompileOpts,
982                                langFlagRegexStr->c_str());
983   } else {
984     // Use all flags.
985     if (cmValue targetFlags = target->GetProperty("COMPILE_FLAGS")) {
986       // COMPILE_FLAGS are not escaped for historical reasons.
987       std::string compileFlags;
988       this->AppendFlags(compileFlags, *targetFlags);
989       if (!compileFlags.empty()) {
990         flags.emplace_back(std::move(compileFlags));
991       }
992     }
993     std::vector<BT<std::string>> targetCompileOpts =
994       target->GetCompileOptions(config, lang);
995     // COMPILE_OPTIONS are escaped.
996     this->AppendCompileOptions(flags, targetCompileOpts);
997   }
998
999   cmStandardLevelResolver standardResolver(this->Makefile);
1000   for (auto const& it : target->GetMaxLanguageStandards()) {
1001     cmValue standard = target->GetLanguageStandard(it.first, config);
1002     if (!standard) {
1003       continue;
1004     }
1005     if (standardResolver.IsLaterStandard(it.first, *standard, it.second)) {
1006       std::ostringstream e;
1007       e << "The COMPILE_FEATURES property of target \"" << target->GetName()
1008         << "\" was evaluated when computing the link "
1009            "implementation, and the \""
1010         << it.first << "_STANDARD\" was \"" << it.second
1011         << "\" for that computation.  Computing the "
1012            "COMPILE_FEATURES based on the link implementation resulted in a "
1013            "higher \""
1014         << it.first << "_STANDARD\" \"" << *standard
1015         << "\".  "
1016            "This is not permitted. The COMPILE_FEATURES may not both depend "
1017            "on "
1018            "and be depended on by the link implementation.\n";
1019       this->IssueMessage(MessageType::FATAL_ERROR, e.str());
1020       return;
1021     }
1022   }
1023
1024   std::string compReqFlag;
1025   this->AddCompilerRequirementFlag(compReqFlag, target, lang, config);
1026   if (!compReqFlag.empty()) {
1027     flags.emplace_back(std::move(compReqFlag));
1028   }
1029
1030   // Add Warning as errors flags
1031   if (!this->GetCMakeInstance()->GetIgnoreWarningAsError()) {
1032     const cmValue wError = target->GetProperty("COMPILE_WARNING_AS_ERROR");
1033     const cmValue wErrorOpts = this->Makefile->GetDefinition(
1034       cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_WARNING_AS_ERROR"));
1035     if (wError.IsOn() && wErrorOpts.IsSet()) {
1036       std::string wErrorFlags;
1037       this->AppendCompileOptions(wErrorFlags, *wErrorOpts);
1038       if (!wErrorFlags.empty()) {
1039         flags.emplace_back(std::move(wErrorFlags));
1040       }
1041     }
1042   }
1043
1044   // Add compile flag for the MSVC compiler only.
1045   cmMakefile* mf = this->GetMakefile();
1046   if (cmValue jmc =
1047         mf->GetDefinition("CMAKE_" + lang + "_COMPILE_OPTIONS_JMC")) {
1048
1049     // Handle Just My Code debugging flags, /JMC.
1050     // If the target is a Managed C++ one, /JMC is not compatible.
1051     if (target->GetManagedType(config) !=
1052         cmGeneratorTarget::ManagedType::Managed) {
1053       // add /JMC flags if target property VS_JUST_MY_CODE_DEBUGGING is set
1054       // to ON
1055       if (cmValue jmcExprGen =
1056             target->GetProperty("VS_JUST_MY_CODE_DEBUGGING")) {
1057         std::string isJMCEnabled =
1058           cmGeneratorExpression::Evaluate(*jmcExprGen, this, config);
1059         if (cmIsOn(isJMCEnabled)) {
1060           std::vector<std::string> optVec = cmExpandedList(*jmc);
1061           std::string jmcFlags;
1062           this->AppendCompileOptions(jmcFlags, optVec);
1063           if (!jmcFlags.empty()) {
1064             flags.emplace_back(std::move(jmcFlags));
1065           }
1066         }
1067       }
1068     }
1069   }
1070 }
1071
1072 cmTarget* cmLocalGenerator::AddCustomCommandToTarget(
1073   const std::string& target, cmCustomCommandType type,
1074   std::unique_ptr<cmCustomCommand> cc, cmObjectLibraryCommands objLibCommands)
1075 {
1076   cmTarget* t = this->Makefile->GetCustomCommandTarget(
1077     target, objLibCommands, this->DirectoryBacktrace);
1078   if (!t) {
1079     return nullptr;
1080   }
1081
1082   cc->SetBacktrace(this->DirectoryBacktrace);
1083
1084   detail::AddCustomCommandToTarget(*this, cmCommandOrigin::Generator, t, type,
1085                                    std::move(cc));
1086
1087   return t;
1088 }
1089
1090 cmSourceFile* cmLocalGenerator::AddCustomCommandToOutput(
1091   std::unique_ptr<cmCustomCommand> cc, bool replace)
1092 {
1093   // Make sure there is at least one output.
1094   if (cc->GetOutputs().empty()) {
1095     cmSystemTools::Error("Attempt to add a custom rule with no output!");
1096     return nullptr;
1097   }
1098
1099   cc->SetBacktrace(this->DirectoryBacktrace);
1100   return detail::AddCustomCommandToOutput(*this, cmCommandOrigin::Generator,
1101                                           std::move(cc), replace);
1102 }
1103
1104 cmTarget* cmLocalGenerator::AddUtilityCommand(
1105   const std::string& utilityName, bool excludeFromAll,
1106   std::unique_ptr<cmCustomCommand> cc)
1107 {
1108   cmTarget* target =
1109     this->Makefile->AddNewUtilityTarget(utilityName, excludeFromAll);
1110   target->SetIsGeneratorProvided(true);
1111
1112   if (cc->GetCommandLines().empty() && cc->GetDepends().empty()) {
1113     return target;
1114   }
1115
1116   cc->SetBacktrace(this->DirectoryBacktrace);
1117   detail::AddUtilityCommand(*this, cmCommandOrigin::Generator, target,
1118                             std::move(cc));
1119
1120   return target;
1121 }
1122
1123 std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectoriesImplicit(
1124   cmGeneratorTarget const* target, std::string const& lang,
1125   std::string const& config, bool stripImplicitDirs,
1126   bool appendAllImplicitDirs) const
1127 {
1128   std::vector<BT<std::string>> result;
1129   // Do not repeat an include path.
1130   std::set<std::string> emitted;
1131
1132   auto emitDir = [&result, &emitted](std::string const& dir) {
1133     if (emitted.insert(dir).second) {
1134       result.emplace_back(dir);
1135     }
1136   };
1137
1138   auto emitBT = [&result, &emitted](BT<std::string> const& dir) {
1139     if (emitted.insert(dir.Value).second) {
1140       result.emplace_back(dir);
1141     }
1142   };
1143
1144   // When automatic include directories are requested for a build then
1145   // include the source and binary directories at the beginning of the
1146   // include path to approximate include file behavior for an
1147   // in-source build.  This does not account for the case of a source
1148   // file in a subdirectory of the current source directory but we
1149   // cannot fix this because not all native build tools support
1150   // per-source-file include paths.
1151   if (this->Makefile->IsOn("CMAKE_INCLUDE_CURRENT_DIR")) {
1152     // Current binary directory
1153     emitDir(this->StateSnapshot.GetDirectory().GetCurrentBinary());
1154     // Current source directory
1155     emitDir(this->StateSnapshot.GetDirectory().GetCurrentSource());
1156   }
1157
1158   if (!target) {
1159     return result;
1160   }
1161
1162   // Standard include directories to be added unconditionally at the end.
1163   // These are intended to simulate additional implicit include directories.
1164   std::vector<std::string> userStandardDirs;
1165   {
1166     std::string const value = this->Makefile->GetSafeDefinition(
1167       cmStrCat("CMAKE_", lang, "_STANDARD_INCLUDE_DIRECTORIES"));
1168     cmExpandList(value, userStandardDirs);
1169     for (std::string& usd : userStandardDirs) {
1170       cmSystemTools::ConvertToUnixSlashes(usd);
1171     }
1172   }
1173
1174   // Implicit include directories
1175   std::vector<std::string> implicitDirs;
1176   std::set<std::string> implicitSet;
1177   // Include directories to be excluded as if they were implicit.
1178   std::set<std::string> implicitExclude;
1179   {
1180     // Raw list of implicit include directories
1181     // Start with "standard" directories that we unconditionally add below.
1182     std::vector<std::string> impDirVec = userStandardDirs;
1183
1184     // Load implicit include directories for this language.
1185     // We ignore this for Fortran because:
1186     // * There are no standard library headers to avoid overriding.
1187     // * Compilers like gfortran do not search their own implicit include
1188     //   directories for modules ('.mod' files).
1189     if (lang != "Fortran") {
1190       size_t const impDirVecOldSize = impDirVec.size();
1191       if (this->Makefile->GetDefExpandList(
1192             cmStrCat("CMAKE_", lang, "_IMPLICIT_INCLUDE_DIRECTORIES"),
1193             impDirVec)) {
1194         // FIXME: Use cmRange with 'advance()' when it supports non-const.
1195         for (size_t i = impDirVecOldSize; i < impDirVec.size(); ++i) {
1196           cmSystemTools::ConvertToUnixSlashes(impDirVec[i]);
1197         }
1198       }
1199     }
1200
1201     // The Platform/UnixPaths module used to hard-code /usr/include for C, CXX,
1202     // and CUDA in CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES, but those
1203     // variables are now computed.  On macOS the /usr/include directory is
1204     // inside the platform SDK so the computed value does not contain it
1205     // directly.  In this case adding -I/usr/include can hide SDK headers so we
1206     // must still exclude it.
1207     if ((lang == "C" || lang == "CXX" || lang == "CUDA") &&
1208         !cm::contains(impDirVec, "/usr/include") &&
1209         std::find_if(impDirVec.begin(), impDirVec.end(),
1210                      [](std::string const& d) {
1211                        return cmHasLiteralSuffix(d, "/usr/include");
1212                      }) != impDirVec.end()) {
1213       // Only exclude this hard coded path for backwards compatibility.
1214       implicitExclude.emplace("/usr/include");
1215     }
1216
1217     for (std::string const& i : impDirVec) {
1218       if (implicitSet.insert(this->GlobalGenerator->GetRealPath(i)).second) {
1219         implicitDirs.emplace_back(i);
1220       }
1221     }
1222   }
1223
1224   bool const isCorCxx = (lang == "C" || lang == "CXX");
1225
1226   // Resolve symlinks in CPATH for comparison with resolved include paths.
1227   // We do this here instead of when EnvCPATH is populated in case symlinks
1228   // on disk have changed in the meantime.
1229   std::set<std::string> resolvedEnvCPATH;
1230   if (isCorCxx) {
1231     for (std::string const& i : this->EnvCPATH) {
1232       resolvedEnvCPATH.emplace(this->GlobalGenerator->GetRealPath(i));
1233     }
1234   }
1235
1236   // Checks if this is not an excluded (implicit) include directory.
1237   auto notExcluded = [this, &implicitSet, &implicitExclude, &resolvedEnvCPATH,
1238                       isCorCxx](std::string const& dir) -> bool {
1239     std::string const& real_dir = this->GlobalGenerator->GetRealPath(dir);
1240     return
1241       // Do not exclude directories that are not in any excluded set.
1242       !(cm::contains(implicitSet, real_dir) ||
1243         cm::contains(implicitExclude, dir))
1244       // Do not exclude entries of the CPATH environment variable even though
1245       // they are implicitly searched by the compiler.  They are meant to be
1246       // user-specified directories that can be re-ordered or converted to
1247       // -isystem without breaking real compiler builtin headers.
1248       || (isCorCxx && cm::contains(resolvedEnvCPATH, real_dir));
1249   };
1250
1251   // Get the target-specific include directories.
1252   std::vector<BT<std::string>> userDirs =
1253     target->GetIncludeDirectories(config, lang);
1254
1255   // Support putting all the in-project include directories first if
1256   // it is requested by the project.
1257   if (this->Makefile->IsOn("CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE")) {
1258     std::string const& topSourceDir = this->GetState()->GetSourceDirectory();
1259     std::string const& topBinaryDir = this->GetState()->GetBinaryDirectory();
1260     for (BT<std::string> const& udr : userDirs) {
1261       // Emit this directory only if it is a subdirectory of the
1262       // top-level source or binary tree.
1263       if (cmSystemTools::ComparePath(udr.Value, topSourceDir) ||
1264           cmSystemTools::ComparePath(udr.Value, topBinaryDir) ||
1265           cmSystemTools::IsSubDirectory(udr.Value, topSourceDir) ||
1266           cmSystemTools::IsSubDirectory(udr.Value, topBinaryDir)) {
1267         if (notExcluded(udr.Value)) {
1268           emitBT(udr);
1269         }
1270       }
1271     }
1272   }
1273
1274   // Emit remaining non implicit user directories.
1275   for (BT<std::string> const& udr : userDirs) {
1276     if (notExcluded(udr.Value)) {
1277       emitBT(udr);
1278     }
1279   }
1280
1281   // Sort result
1282   MoveSystemIncludesToEnd(result, config, lang, target);
1283
1284   // Append standard include directories for this language.
1285   userDirs.reserve(userDirs.size() + userStandardDirs.size());
1286   for (std::string& usd : userStandardDirs) {
1287     emitDir(usd);
1288     userDirs.emplace_back(std::move(usd));
1289   }
1290
1291   // Append compiler implicit include directories
1292   if (!stripImplicitDirs) {
1293     // Append implicit directories that were requested by the user only
1294     for (BT<std::string> const& udr : userDirs) {
1295       if (cm::contains(implicitSet, cmSystemTools::GetRealPath(udr.Value))) {
1296         emitBT(udr);
1297       }
1298     }
1299     // Append remaining implicit directories (on demand)
1300     if (appendAllImplicitDirs) {
1301       for (std::string& imd : implicitDirs) {
1302         emitDir(imd);
1303       }
1304     }
1305   }
1306
1307   return result;
1308 }
1309
1310 void cmLocalGenerator::GetIncludeDirectoriesImplicit(
1311   std::vector<std::string>& dirs, cmGeneratorTarget const* target,
1312   const std::string& lang, const std::string& config, bool stripImplicitDirs,
1313   bool appendAllImplicitDirs) const
1314 {
1315   std::vector<BT<std::string>> tmp = this->GetIncludeDirectoriesImplicit(
1316     target, lang, config, stripImplicitDirs, appendAllImplicitDirs);
1317   dirs.reserve(dirs.size() + tmp.size());
1318   for (BT<std::string>& v : tmp) {
1319     dirs.emplace_back(std::move(v.Value));
1320   }
1321 }
1322
1323 std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectories(
1324   cmGeneratorTarget const* target, std::string const& lang,
1325   std::string const& config) const
1326 {
1327   return this->GetIncludeDirectoriesImplicit(target, lang, config);
1328 }
1329
1330 void cmLocalGenerator::GetIncludeDirectories(std::vector<std::string>& dirs,
1331                                              cmGeneratorTarget const* target,
1332                                              const std::string& lang,
1333                                              const std::string& config) const
1334 {
1335   this->GetIncludeDirectoriesImplicit(dirs, target, lang, config);
1336 }
1337
1338 void cmLocalGenerator::GetStaticLibraryFlags(std::string& flags,
1339                                              std::string const& config,
1340                                              std::string const& linkLanguage,
1341                                              cmGeneratorTarget* target)
1342 {
1343   std::vector<BT<std::string>> tmpFlags =
1344     this->GetStaticLibraryFlags(config, linkLanguage, target);
1345   this->AppendFlags(flags, tmpFlags);
1346 }
1347
1348 std::vector<BT<std::string>> cmLocalGenerator::GetStaticLibraryFlags(
1349   std::string const& config, std::string const& linkLanguage,
1350   cmGeneratorTarget* target)
1351 {
1352   const std::string configUpper = cmSystemTools::UpperCase(config);
1353   std::vector<BT<std::string>> flags;
1354   if (linkLanguage != "Swift") {
1355     std::string staticLibFlags;
1356     this->AppendFlags(
1357       staticLibFlags,
1358       this->Makefile->GetSafeDefinition("CMAKE_STATIC_LINKER_FLAGS"));
1359     if (!configUpper.empty()) {
1360       std::string name = "CMAKE_STATIC_LINKER_FLAGS_" + configUpper;
1361       this->AppendFlags(staticLibFlags,
1362                         this->Makefile->GetSafeDefinition(name));
1363     }
1364     if (!staticLibFlags.empty()) {
1365       flags.emplace_back(std::move(staticLibFlags));
1366     }
1367   }
1368
1369   std::string staticLibFlags;
1370   this->AppendFlags(staticLibFlags,
1371                     target->GetSafeProperty("STATIC_LIBRARY_FLAGS"));
1372   if (!configUpper.empty()) {
1373     std::string name = "STATIC_LIBRARY_FLAGS_" + configUpper;
1374     this->AppendFlags(staticLibFlags, target->GetSafeProperty(name));
1375   }
1376
1377   if (!staticLibFlags.empty()) {
1378     flags.emplace_back(std::move(staticLibFlags));
1379   }
1380
1381   std::vector<BT<std::string>> staticLibOpts =
1382     target->GetStaticLibraryLinkOptions(config, linkLanguage);
1383   // STATIC_LIBRARY_OPTIONS are escaped.
1384   this->AppendCompileOptions(flags, staticLibOpts);
1385
1386   return flags;
1387 }
1388
1389 void cmLocalGenerator::GetDeviceLinkFlags(
1390   cmLinkLineDeviceComputer& linkLineComputer, const std::string& config,
1391   std::string& linkLibs, std::string& linkFlags, std::string& frameworkPath,
1392   std::string& linkPath, cmGeneratorTarget* target)
1393 {
1394   cmGeneratorTarget::DeviceLinkSetter setter(*target);
1395
1396   cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
1397
1398   auto linklang = linkLineComputer.GetLinkerLanguage(target, config);
1399   auto ipoEnabled = target->IsIPOEnabled(linklang, config);
1400   if (!ipoEnabled) {
1401     ipoEnabled = linkLineComputer.ComputeRequiresDeviceLinkingIPOFlag(*pcli);
1402   }
1403   if (ipoEnabled) {
1404     if (cmValue cudaIPOFlags = this->Makefile->GetDefinition(
1405           "CMAKE_CUDA_DEVICE_LINK_OPTIONS_IPO")) {
1406       linkFlags += cudaIPOFlags;
1407     }
1408   }
1409
1410   if (pcli) {
1411     // Compute the required device link libraries when
1412     // resolving gpu lang device symbols
1413     this->OutputLinkLibraries(pcli, &linkLineComputer, linkLibs, frameworkPath,
1414                               linkPath);
1415   }
1416
1417   // iterate link deps and see if any of them need IPO
1418
1419   std::vector<std::string> linkOpts;
1420   target->GetLinkOptions(linkOpts, config, "CUDA");
1421   // LINK_OPTIONS are escaped.
1422   this->AppendCompileOptions(linkFlags, linkOpts);
1423 }
1424
1425 void cmLocalGenerator::GetTargetFlags(
1426   cmLinkLineComputer* linkLineComputer, const std::string& config,
1427   std::string& linkLibs, std::string& flags, std::string& linkFlags,
1428   std::string& frameworkPath, std::string& linkPath, cmGeneratorTarget* target)
1429 {
1430   std::vector<BT<std::string>> linkFlagsList;
1431   std::vector<BT<std::string>> linkPathList;
1432   std::vector<BT<std::string>> linkLibsList;
1433   this->GetTargetFlags(linkLineComputer, config, linkLibsList, flags,
1434                        linkFlagsList, frameworkPath, linkPathList, target);
1435   this->AppendFlags(linkFlags, linkFlagsList);
1436   this->AppendFlags(linkPath, linkPathList);
1437   this->AppendFlags(linkLibs, linkLibsList);
1438 }
1439
1440 void cmLocalGenerator::GetTargetFlags(
1441   cmLinkLineComputer* linkLineComputer, const std::string& config,
1442   std::vector<BT<std::string>>& linkLibs, std::string& flags,
1443   std::vector<BT<std::string>>& linkFlags, std::string& frameworkPath,
1444   std::vector<BT<std::string>>& linkPath, cmGeneratorTarget* target)
1445 {
1446   const std::string configUpper = cmSystemTools::UpperCase(config);
1447   cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
1448   const char* libraryLinkVariable =
1449     "CMAKE_SHARED_LINKER_FLAGS"; // default to shared library
1450
1451   const std::string linkLanguage =
1452     linkLineComputer->GetLinkerLanguage(target, config);
1453
1454   switch (target->GetType()) {
1455     case cmStateEnums::STATIC_LIBRARY:
1456       linkFlags = this->GetStaticLibraryFlags(config, linkLanguage, target);
1457       break;
1458     case cmStateEnums::MODULE_LIBRARY:
1459       libraryLinkVariable = "CMAKE_MODULE_LINKER_FLAGS";
1460       CM_FALLTHROUGH;
1461     case cmStateEnums::SHARED_LIBRARY: {
1462       std::string sharedLibFlags;
1463       if (linkLanguage != "Swift") {
1464         sharedLibFlags = cmStrCat(
1465           this->Makefile->GetSafeDefinition(libraryLinkVariable), ' ');
1466         if (!configUpper.empty()) {
1467           std::string build = cmStrCat(libraryLinkVariable, '_', configUpper);
1468           sharedLibFlags += this->Makefile->GetSafeDefinition(build);
1469           sharedLibFlags += " ";
1470         }
1471       }
1472
1473       cmValue targetLinkFlags = target->GetProperty("LINK_FLAGS");
1474       if (targetLinkFlags) {
1475         sharedLibFlags += *targetLinkFlags;
1476         sharedLibFlags += " ";
1477       }
1478       if (!configUpper.empty()) {
1479         targetLinkFlags =
1480           target->GetProperty(cmStrCat("LINK_FLAGS_", configUpper));
1481         if (targetLinkFlags) {
1482           sharedLibFlags += *targetLinkFlags;
1483           sharedLibFlags += " ";
1484         }
1485       }
1486
1487       if (!sharedLibFlags.empty()) {
1488         linkFlags.emplace_back(std::move(sharedLibFlags));
1489       }
1490
1491       std::vector<BT<std::string>> linkOpts =
1492         target->GetLinkOptions(config, linkLanguage);
1493       // LINK_OPTIONS are escaped.
1494       this->AppendCompileOptions(linkFlags, linkOpts);
1495       if (pcli) {
1496         this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
1497                                   frameworkPath, linkPath);
1498       }
1499     } break;
1500     case cmStateEnums::EXECUTABLE: {
1501       std::string exeFlags;
1502       if (linkLanguage != "Swift") {
1503         exeFlags = this->Makefile->GetSafeDefinition("CMAKE_EXE_LINKER_FLAGS");
1504         exeFlags += " ";
1505         if (!configUpper.empty()) {
1506           exeFlags += this->Makefile->GetSafeDefinition(
1507             cmStrCat("CMAKE_EXE_LINKER_FLAGS_", configUpper));
1508           exeFlags += " ";
1509         }
1510         if (linkLanguage.empty()) {
1511           cmSystemTools::Error(
1512             "CMake can not determine linker language for target: " +
1513             target->GetName());
1514           return;
1515         }
1516
1517         if (target->IsWin32Executable(config)) {
1518           exeFlags += this->Makefile->GetSafeDefinition(
1519             cmStrCat("CMAKE_", linkLanguage, "_CREATE_WIN32_EXE"));
1520           exeFlags += " ";
1521         } else {
1522           exeFlags += this->Makefile->GetSafeDefinition(
1523             cmStrCat("CMAKE_", linkLanguage, "_CREATE_CONSOLE_EXE"));
1524           exeFlags += " ";
1525         }
1526
1527         if (target->IsExecutableWithExports()) {
1528           exeFlags += this->Makefile->GetSafeDefinition(
1529             cmStrCat("CMAKE_EXE_EXPORTS_", linkLanguage, "_FLAG"));
1530           exeFlags += " ";
1531         }
1532       }
1533
1534       this->AddLanguageFlagsForLinking(flags, target, linkLanguage, config);
1535       if (pcli) {
1536         this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
1537                                   frameworkPath, linkPath);
1538       }
1539
1540       if (this->Makefile->IsOn("BUILD_SHARED_LIBS")) {
1541         std::string sFlagVar = "CMAKE_SHARED_BUILD_" + linkLanguage + "_FLAGS";
1542         exeFlags += this->Makefile->GetSafeDefinition(sFlagVar);
1543         exeFlags += " ";
1544       }
1545
1546       std::string cmp0065Flags =
1547         this->GetLinkLibsCMP0065(linkLanguage, *target);
1548       if (!cmp0065Flags.empty()) {
1549         exeFlags += cmp0065Flags;
1550         exeFlags += " ";
1551       }
1552
1553       cmValue targetLinkFlags = target->GetProperty("LINK_FLAGS");
1554       if (targetLinkFlags) {
1555         exeFlags += *targetLinkFlags;
1556         exeFlags += " ";
1557       }
1558       if (!configUpper.empty()) {
1559         targetLinkFlags =
1560           target->GetProperty(cmStrCat("LINK_FLAGS_", configUpper));
1561         if (targetLinkFlags) {
1562           exeFlags += *targetLinkFlags;
1563           exeFlags += " ";
1564         }
1565       }
1566
1567       if (!exeFlags.empty()) {
1568         linkFlags.emplace_back(std::move(exeFlags));
1569       }
1570
1571       std::vector<BT<std::string>> linkOpts =
1572         target->GetLinkOptions(config, linkLanguage);
1573       // LINK_OPTIONS are escaped.
1574       this->AppendCompileOptions(linkFlags, linkOpts);
1575     } break;
1576     default:
1577       break;
1578   }
1579
1580   std::string extraLinkFlags;
1581   this->AppendPositionIndependentLinkerFlags(extraLinkFlags, target, config,
1582                                              linkLanguage);
1583   this->AppendIPOLinkerFlags(extraLinkFlags, target, config, linkLanguage);
1584   this->AppendModuleDefinitionFlag(extraLinkFlags, target, linkLineComputer,
1585                                    config);
1586
1587   if (!extraLinkFlags.empty()) {
1588     linkFlags.emplace_back(std::move(extraLinkFlags));
1589   }
1590 }
1591
1592 void cmLocalGenerator::GetTargetCompileFlags(cmGeneratorTarget* target,
1593                                              std::string const& config,
1594                                              std::string const& lang,
1595                                              std::string& flags,
1596                                              std::string const& arch)
1597 {
1598   std::vector<BT<std::string>> tmpFlags =
1599     this->GetTargetCompileFlags(target, config, lang, arch);
1600   this->AppendFlags(flags, tmpFlags);
1601 }
1602
1603 std::vector<BT<std::string>> cmLocalGenerator::GetTargetCompileFlags(
1604   cmGeneratorTarget* target, std::string const& config,
1605   std::string const& lang, std::string const& arch)
1606 {
1607   std::vector<BT<std::string>> flags;
1608   std::string compileFlags;
1609
1610   cmMakefile* mf = this->GetMakefile();
1611
1612   // Add language-specific flags.
1613   this->AddLanguageFlags(compileFlags, target, cmBuildStep::Compile, lang,
1614                          config);
1615
1616   if (target->IsIPOEnabled(lang, config)) {
1617     this->AppendFeatureOptions(compileFlags, lang, "IPO");
1618   }
1619
1620   this->AddArchitectureFlags(compileFlags, target, lang, config, arch);
1621
1622   if (lang == "Fortran") {
1623     this->AppendFlags(compileFlags,
1624                       this->GetTargetFortranFlags(target, config));
1625   }
1626
1627   this->AddCMP0018Flags(compileFlags, target, lang, config);
1628   this->AddVisibilityPresetFlags(compileFlags, target, lang);
1629   this->AddColorDiagnosticsFlags(compileFlags, lang);
1630   this->AppendFlags(compileFlags, mf->GetDefineFlags());
1631   this->AppendFlags(compileFlags,
1632                     this->GetFrameworkFlags(lang, config, target));
1633
1634   if (!compileFlags.empty()) {
1635     flags.emplace_back(std::move(compileFlags));
1636   }
1637   this->AddCompileOptions(flags, target, lang, config);
1638   return flags;
1639 }
1640
1641 static std::string GetFrameworkFlags(const std::string& lang,
1642                                      const std::string& config,
1643                                      cmGeneratorTarget* target)
1644 {
1645   cmLocalGenerator* lg = target->GetLocalGenerator();
1646   cmMakefile* mf = lg->GetMakefile();
1647
1648   if (!mf->IsOn("APPLE")) {
1649     return std::string();
1650   }
1651
1652   std::string fwSearchFlagVar = "CMAKE_" + lang + "_FRAMEWORK_SEARCH_FLAG";
1653   cmValue fwSearchFlag = mf->GetDefinition(fwSearchFlagVar);
1654   if (!cmNonempty(fwSearchFlag)) {
1655     return std::string();
1656   }
1657
1658   std::set<std::string> emitted;
1659 #ifdef __APPLE__ /* don't insert this when crosscompiling e.g. to iphone */
1660   emitted.insert("/System/Library/Frameworks");
1661 #endif
1662   std::vector<std::string> includes;
1663
1664   lg->GetIncludeDirectories(includes, target, "C", config);
1665   // check all include directories for frameworks as this
1666   // will already have added a -F for the framework
1667   for (std::string const& include : includes) {
1668     if (lg->GetGlobalGenerator()->NameResolvesToFramework(include)) {
1669       std::string frameworkDir = cmStrCat(include, "/../");
1670       frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
1671       emitted.insert(frameworkDir);
1672     }
1673   }
1674
1675   std::string flags;
1676   if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
1677     std::vector<std::string> const& frameworks = cli->GetFrameworkPaths();
1678     for (std::string const& framework : frameworks) {
1679       if (emitted.insert(framework).second) {
1680         flags += *fwSearchFlag;
1681         flags +=
1682           lg->ConvertToOutputFormat(framework, cmOutputConverter::SHELL);
1683         flags += " ";
1684       }
1685     }
1686   }
1687   return flags;
1688 }
1689
1690 std::string cmLocalGenerator::GetFrameworkFlags(std::string const& l,
1691                                                 std::string const& config,
1692                                                 cmGeneratorTarget* target)
1693 {
1694   return ::GetFrameworkFlags(l, config, target);
1695 }
1696
1697 void cmLocalGenerator::GetTargetDefines(cmGeneratorTarget const* target,
1698                                         std::string const& config,
1699                                         std::string const& lang,
1700                                         std::set<std::string>& defines) const
1701 {
1702   std::set<BT<std::string>> tmp = this->GetTargetDefines(target, config, lang);
1703   for (BT<std::string> const& v : tmp) {
1704     defines.emplace(v.Value);
1705   }
1706 }
1707
1708 std::set<BT<std::string>> cmLocalGenerator::GetTargetDefines(
1709   cmGeneratorTarget const* target, std::string const& config,
1710   std::string const& lang) const
1711 {
1712   std::set<BT<std::string>> defines;
1713
1714   // Add the export symbol definition for shared library objects.
1715   if (const std::string* exportMacro = target->GetExportMacro()) {
1716     this->AppendDefines(defines, *exportMacro);
1717   }
1718
1719   // Add preprocessor definitions for this target and configuration.
1720   std::vector<BT<std::string>> targetDefines =
1721     target->GetCompileDefinitions(config, lang);
1722   this->AppendDefines(defines, targetDefines);
1723
1724   return defines;
1725 }
1726
1727 std::string cmLocalGenerator::GetTargetFortranFlags(
1728   cmGeneratorTarget const* /*unused*/, std::string const& /*unused*/)
1729 {
1730   // Implemented by specific generators that override this.
1731   return std::string();
1732 }
1733
1734 /**
1735  * Output the linking rules on a command line.  For executables,
1736  * targetLibrary should be a NULL pointer.  For libraries, it should point
1737  * to the name of the library.  This will not link a library against itself.
1738  */
1739 void cmLocalGenerator::OutputLinkLibraries(
1740   cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
1741   std::string& linkLibraries, std::string& frameworkPath,
1742   std::string& linkPath)
1743 {
1744   std::vector<BT<std::string>> linkLibrariesList;
1745   std::vector<BT<std::string>> linkPathList;
1746   this->OutputLinkLibraries(pcli, linkLineComputer, linkLibrariesList,
1747                             frameworkPath, linkPathList);
1748   pcli->AppendValues(linkLibraries, linkLibrariesList);
1749   pcli->AppendValues(linkPath, linkPathList);
1750 }
1751
1752 void cmLocalGenerator::OutputLinkLibraries(
1753   cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
1754   std::vector<BT<std::string>>& linkLibraries, std::string& frameworkPath,
1755   std::vector<BT<std::string>>& linkPath)
1756 {
1757   cmComputeLinkInformation& cli = *pcli;
1758
1759   std::string linkLanguage = cli.GetLinkLanguage();
1760
1761   std::string libPathFlag;
1762   if (cmValue value = this->Makefile->GetDefinition(
1763         "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_FLAG")) {
1764     libPathFlag = *value;
1765   } else {
1766     libPathFlag =
1767       this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_FLAG");
1768   }
1769
1770   std::string libPathTerminator;
1771   if (cmValue value = this->Makefile->GetDefinition(
1772         "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_TERMINATOR")) {
1773     libPathTerminator = *value;
1774   } else {
1775     libPathTerminator =
1776       this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_TERMINATOR");
1777   }
1778
1779   // Add standard libraries for this language.
1780   std::string stdLibString = this->Makefile->GetSafeDefinition(
1781     cmStrCat("CMAKE_", cli.GetLinkLanguage(), "_STANDARD_LIBRARIES"));
1782
1783   // Append the framework search path flags.
1784   std::string fwSearchFlag = this->Makefile->GetSafeDefinition(
1785     cmStrCat("CMAKE_", linkLanguage, "_FRAMEWORK_SEARCH_FLAG"));
1786
1787   frameworkPath = linkLineComputer->ComputeFrameworkPath(cli, fwSearchFlag);
1788   linkLineComputer->ComputeLinkPath(cli, libPathFlag, libPathTerminator,
1789                                     linkPath);
1790   linkLineComputer->ComputeLinkLibraries(cli, stdLibString, linkLibraries);
1791 }
1792
1793 std::string cmLocalGenerator::GetLinkLibsCMP0065(
1794   std::string const& linkLanguage, cmGeneratorTarget& tgt) const
1795 {
1796   std::string linkFlags;
1797
1798   // Flags to link an executable to shared libraries.
1799   if (tgt.GetType() == cmStateEnums::EXECUTABLE &&
1800       this->StateSnapshot.GetState()->GetGlobalPropertyAsBool(
1801         "TARGET_SUPPORTS_SHARED_LIBS")) {
1802     bool add_shlib_flags = false;
1803     switch (tgt.GetPolicyStatusCMP0065()) {
1804       case cmPolicies::WARN:
1805         if (!tgt.GetPropertyAsBool("ENABLE_EXPORTS") &&
1806             this->Makefile->PolicyOptionalWarningEnabled(
1807               "CMAKE_POLICY_WARNING_CMP0065")) {
1808           std::ostringstream w;
1809           /* clang-format off */
1810             w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0065) << "\n"
1811               "For compatibility with older versions of CMake, "
1812               "additional flags may be added to export symbols on all "
1813               "executables regardless of their ENABLE_EXPORTS property.";
1814           /* clang-format on */
1815           this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
1816         }
1817         CM_FALLTHROUGH;
1818       case cmPolicies::OLD:
1819         // OLD behavior is to always add the flags, except on AIX where
1820         // we compute symbol exports if ENABLE_EXPORTS is on.
1821         add_shlib_flags =
1822           !(tgt.Target->IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS"));
1823         break;
1824       case cmPolicies::REQUIRED_IF_USED:
1825       case cmPolicies::REQUIRED_ALWAYS:
1826         this->IssueMessage(
1827           MessageType::FATAL_ERROR,
1828           cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0065));
1829         CM_FALLTHROUGH;
1830       case cmPolicies::NEW:
1831         // NEW behavior is to only add the flags if ENABLE_EXPORTS is on,
1832         // except on AIX where we compute symbol exports.
1833         add_shlib_flags =
1834           !tgt.Target->IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS");
1835         break;
1836     }
1837
1838     if (add_shlib_flags) {
1839       linkFlags = this->Makefile->GetSafeDefinition(
1840         cmStrCat("CMAKE_SHARED_LIBRARY_LINK_", linkLanguage, "_FLAGS"));
1841     }
1842   }
1843   return linkFlags;
1844 }
1845
1846 bool cmLocalGenerator::AllAppleArchSysrootsAreTheSame(
1847   const std::vector<std::string>& archs, cmValue sysroot)
1848 {
1849   if (!sysroot) {
1850     return false;
1851   }
1852
1853   return std::all_of(archs.begin(), archs.end(),
1854                      [this, sysroot](std::string const& arch) -> bool {
1855                        std::string const& archSysroot =
1856                          this->AppleArchSysroots[arch];
1857                        return cmIsOff(archSysroot) || sysroot == archSysroot;
1858                      });
1859 }
1860
1861 void cmLocalGenerator::AddArchitectureFlags(std::string& flags,
1862                                             cmGeneratorTarget const* target,
1863                                             const std::string& lang,
1864                                             const std::string& config,
1865                                             const std::string& filterArch)
1866 {
1867   // Only add Apple specific flags on Apple platforms
1868   if (this->Makefile->IsOn("APPLE") && this->EmitUniversalBinaryFlags) {
1869     std::vector<std::string> archs;
1870     target->GetAppleArchs(config, archs);
1871     if (!archs.empty() &&
1872         (lang == "C" || lang == "CXX" || lang == "OBJC" || lang == "OBJCXX" ||
1873          lang == "ASM")) {
1874       for (std::string const& arch : archs) {
1875         if (filterArch.empty() || filterArch == arch) {
1876           flags += " -arch ";
1877           flags += arch;
1878         }
1879       }
1880     }
1881
1882     cmValue sysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
1883     if (sysroot && *sysroot == "/") {
1884       sysroot = nullptr;
1885     }
1886     std::string sysrootFlagVar = "CMAKE_" + lang + "_SYSROOT_FLAG";
1887     cmValue sysrootFlag = this->Makefile->GetDefinition(sysrootFlagVar);
1888     if (cmNonempty(sysrootFlag)) {
1889       if (!this->AppleArchSysroots.empty() &&
1890           !this->AllAppleArchSysrootsAreTheSame(archs, sysroot)) {
1891         for (std::string const& arch : archs) {
1892           std::string const& archSysroot = this->AppleArchSysroots[arch];
1893           if (cmIsOff(archSysroot)) {
1894             continue;
1895           }
1896           if (filterArch.empty() || filterArch == arch) {
1897             flags += " -Xarch_" + arch + " ";
1898             // Combine sysroot flag and path to work with -Xarch
1899             std::string arch_sysroot = *sysrootFlag + archSysroot;
1900             flags += this->ConvertToOutputFormat(arch_sysroot, SHELL);
1901           }
1902         }
1903       } else if (cmNonempty(sysroot)) {
1904         flags += " ";
1905         flags += *sysrootFlag;
1906         flags += " ";
1907         flags += this->ConvertToOutputFormat(*sysroot, SHELL);
1908       }
1909     }
1910
1911     cmValue deploymentTarget =
1912       this->Makefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
1913     std::string deploymentTargetFlagVar =
1914       "CMAKE_" + lang + "_OSX_DEPLOYMENT_TARGET_FLAG";
1915     cmValue deploymentTargetFlag =
1916       this->Makefile->GetDefinition(deploymentTargetFlagVar);
1917     if (cmNonempty(deploymentTargetFlag) && cmNonempty(deploymentTarget)) {
1918       flags += " ";
1919       flags += *deploymentTargetFlag;
1920       flags += *deploymentTarget;
1921     }
1922   }
1923 }
1924
1925 void cmLocalGenerator::AddLanguageFlags(std::string& flags,
1926                                         cmGeneratorTarget const* target,
1927                                         cmBuildStep compileOrLink,
1928                                         const std::string& lang,
1929                                         const std::string& config)
1930 {
1931   // Add language-specific flags.
1932   this->AddConfigVariableFlags(flags, cmStrCat("CMAKE_", lang, "_FLAGS"),
1933                                config);
1934
1935   std::string compiler = this->Makefile->GetSafeDefinition(
1936     cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
1937
1938   std::string compilerSimulateId = this->Makefile->GetSafeDefinition(
1939     cmStrCat("CMAKE_", lang, "_SIMULATE_ID"));
1940
1941   if (lang == "Swift") {
1942     if (cmValue v = target->GetProperty("Swift_LANGUAGE_VERSION")) {
1943       if (cmSystemTools::VersionCompare(
1944             cmSystemTools::OP_GREATER_EQUAL,
1945             this->Makefile->GetDefinition("CMAKE_Swift_COMPILER_VERSION"),
1946             "4.2")) {
1947         this->AppendFlags(flags, "-swift-version " + *v);
1948       }
1949     }
1950   } else if (lang == "CUDA") {
1951     target->AddCUDAArchitectureFlags(compileOrLink, config, flags);
1952     target->AddCUDAToolkitFlags(flags);
1953   } else if (lang == "ISPC") {
1954     target->AddISPCTargetFlags(flags);
1955   } else if (lang == "RC" &&
1956              this->Makefile->GetSafeDefinition("CMAKE_RC_COMPILER")
1957                  .find("llvm-rc") != std::string::npos) {
1958     compiler = this->Makefile->GetSafeDefinition("CMAKE_C_COMPILER_ID");
1959     if (!compiler.empty()) {
1960       compilerSimulateId =
1961         this->Makefile->GetSafeDefinition("CMAKE_C_SIMULATE_ID");
1962     } else {
1963       compiler = this->Makefile->GetSafeDefinition("CMAKE_CXX_COMPILER_ID");
1964       compilerSimulateId =
1965         this->Makefile->GetSafeDefinition("CMAKE_CXX_SIMULATE_ID");
1966     }
1967   } else if (lang == "HIP") {
1968     target->AddHIPArchitectureFlags(flags);
1969   }
1970
1971   // Add VFS Overlay for Clang compilers
1972   if (compiler == "Clang") {
1973     if (cmValue vfsOverlay =
1974           this->Makefile->GetDefinition("CMAKE_CLANG_VFS_OVERLAY")) {
1975       if (compilerSimulateId == "MSVC") {
1976         this->AppendCompileOptions(
1977           flags,
1978           std::vector<std::string>{ "-Xclang", "-ivfsoverlay", "-Xclang",
1979                                     *vfsOverlay });
1980       } else {
1981         this->AppendCompileOptions(
1982           flags, std::vector<std::string>{ "-ivfsoverlay", *vfsOverlay });
1983       }
1984     }
1985   }
1986   // Add MSVC runtime library flags.  This is activated by the presence
1987   // of a default selection whether or not it is overridden by a property.
1988   cmValue msvcRuntimeLibraryDefault =
1989     this->Makefile->GetDefinition("CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT");
1990   if (cmNonempty(msvcRuntimeLibraryDefault)) {
1991     cmValue msvcRuntimeLibraryValue =
1992       target->GetProperty("MSVC_RUNTIME_LIBRARY");
1993     if (!msvcRuntimeLibraryValue) {
1994       msvcRuntimeLibraryValue = msvcRuntimeLibraryDefault;
1995     }
1996     std::string const msvcRuntimeLibrary = cmGeneratorExpression::Evaluate(
1997       *msvcRuntimeLibraryValue, this, config, target);
1998     if (!msvcRuntimeLibrary.empty()) {
1999       if (cmValue msvcRuntimeLibraryOptions = this->Makefile->GetDefinition(
2000             "CMAKE_" + lang + "_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_" +
2001             msvcRuntimeLibrary)) {
2002         this->AppendCompileOptions(flags, *msvcRuntimeLibraryOptions);
2003       } else if ((this->Makefile->GetSafeDefinition(
2004                     "CMAKE_" + lang + "_COMPILER_ID") == "MSVC" ||
2005                   this->Makefile->GetSafeDefinition(
2006                     "CMAKE_" + lang + "_SIMULATE_ID") == "MSVC") &&
2007                  !cmSystemTools::GetErrorOccurredFlag()) {
2008         // The compiler uses the MSVC ABI so it needs a known runtime library.
2009         this->IssueMessage(MessageType::FATAL_ERROR,
2010                            "MSVC_RUNTIME_LIBRARY value '" +
2011                              msvcRuntimeLibrary + "' not known for this " +
2012                              lang + " compiler.");
2013       }
2014     }
2015   }
2016
2017   // Add Watcom runtime library flags.  This is activated by the presence
2018   // of a default selection whether or not it is overridden by a property.
2019   cmValue watcomRuntimeLibraryDefault =
2020     this->Makefile->GetDefinition("CMAKE_WATCOM_RUNTIME_LIBRARY_DEFAULT");
2021   if (cmNonempty(watcomRuntimeLibraryDefault)) {
2022     cmValue watcomRuntimeLibraryValue =
2023       target->GetProperty("WATCOM_RUNTIME_LIBRARY");
2024     if (!watcomRuntimeLibraryValue) {
2025       watcomRuntimeLibraryValue = watcomRuntimeLibraryDefault;
2026     }
2027     std::string const watcomRuntimeLibrary = cmGeneratorExpression::Evaluate(
2028       *watcomRuntimeLibraryValue, this, config, target);
2029     if (!watcomRuntimeLibrary.empty()) {
2030       if (cmValue watcomRuntimeLibraryOptions = this->Makefile->GetDefinition(
2031             "CMAKE_" + lang + "_COMPILE_OPTIONS_WATCOM_RUNTIME_LIBRARY_" +
2032             watcomRuntimeLibrary)) {
2033         this->AppendCompileOptions(flags, *watcomRuntimeLibraryOptions);
2034       } else if ((this->Makefile->GetSafeDefinition(
2035                     "CMAKE_" + lang + "_COMPILER_ID") == "OpenWatcom" ||
2036                   this->Makefile->GetSafeDefinition(
2037                     "CMAKE_" + lang + "_SIMULATE_ID") == "OpenWatcom") &&
2038                  !cmSystemTools::GetErrorOccurredFlag()) {
2039         // The compiler uses the Watcom ABI so it needs a known runtime
2040         // library.
2041         this->IssueMessage(MessageType::FATAL_ERROR,
2042                            "WATCOM_RUNTIME_LIBRARY value '" +
2043                              watcomRuntimeLibrary + "' not known for this " +
2044                              lang + " compiler.");
2045       }
2046     }
2047   }
2048
2049   // Add MSVC debug information format flags if CMP0141 is NEW.
2050   if (cm::optional<std::string> msvcDebugInformationFormat =
2051         this->GetMSVCDebugFormatName(config, target)) {
2052     if (!msvcDebugInformationFormat->empty()) {
2053       if (cmValue msvcDebugInformationFormatOptions =
2054             this->Makefile->GetDefinition(
2055               cmStrCat("CMAKE_", lang,
2056                        "_COMPILE_OPTIONS_MSVC_DEBUG_INFORMATION_FORMAT_",
2057                        *msvcDebugInformationFormat))) {
2058         this->AppendCompileOptions(flags, *msvcDebugInformationFormatOptions);
2059       } else if ((this->Makefile->GetSafeDefinition(
2060                     cmStrCat("CMAKE_", lang, "_COMPILER_ID")) == "MSVC"_s ||
2061                   this->Makefile->GetSafeDefinition(
2062                     cmStrCat("CMAKE_", lang, "_SIMULATE_ID")) == "MSVC"_s) &&
2063                  !cmSystemTools::GetErrorOccurredFlag()) {
2064         // The compiler uses the MSVC ABI so it needs a known runtime library.
2065         this->IssueMessage(MessageType::FATAL_ERROR,
2066                            cmStrCat("MSVC_DEBUG_INFORMATION_FORMAT value '",
2067                                     *msvcDebugInformationFormat,
2068                                     "' not known for this ", lang,
2069                                     " compiler."));
2070       }
2071     }
2072   }
2073 }
2074
2075 void cmLocalGenerator::AddLanguageFlagsForLinking(
2076   std::string& flags, cmGeneratorTarget const* target, const std::string& lang,
2077   const std::string& config)
2078 {
2079   if (this->Makefile->IsOn("CMAKE_" + lang +
2080                            "_LINK_WITH_STANDARD_COMPILE_OPTION")) {
2081     // This toolchain requires use of the language standard flag
2082     // when linking in order to use the matching standard library.
2083     // FIXME: If CMake gains an abstraction for standard library
2084     // selection, this will have to be reconciled with it.
2085     this->AddCompilerRequirementFlag(flags, target, lang, config);
2086   }
2087
2088   this->AddLanguageFlags(flags, target, cmBuildStep::Link, lang, config);
2089
2090   if (target->IsIPOEnabled(lang, config)) {
2091     this->AppendFeatureOptions(flags, lang, "IPO");
2092   }
2093 }
2094
2095 cmGeneratorTarget* cmLocalGenerator::FindGeneratorTargetToUse(
2096   const std::string& name) const
2097 {
2098   auto imported = this->ImportedGeneratorTargets.find(name);
2099   if (imported != this->ImportedGeneratorTargets.end()) {
2100     return imported->second;
2101   }
2102
2103   // find local alias to imported target
2104   auto aliased = this->AliasTargets.find(name);
2105   if (aliased != this->AliasTargets.end()) {
2106     imported = this->ImportedGeneratorTargets.find(aliased->second);
2107     if (imported != this->ImportedGeneratorTargets.end()) {
2108       return imported->second;
2109     }
2110   }
2111
2112   if (cmGeneratorTarget* t = this->FindLocalNonAliasGeneratorTarget(name)) {
2113     return t;
2114   }
2115
2116   return this->GetGlobalGenerator()->FindGeneratorTarget(name);
2117 }
2118
2119 bool cmLocalGenerator::GetRealDependency(const std::string& inName,
2120                                          const std::string& config,
2121                                          std::string& dep)
2122 {
2123   // Older CMake code may specify the dependency using the target
2124   // output file rather than the target name.  Such code would have
2125   // been written before there was support for target properties that
2126   // modify the name so stripping down to just the file name should
2127   // produce the target name in this case.
2128   std::string name = cmSystemTools::GetFilenameName(inName);
2129
2130   // If the input name is the empty string, there is no real
2131   // dependency. Short-circuit the other checks:
2132   if (name.empty()) {
2133     return false;
2134   }
2135   if (cmSystemTools::GetFilenameLastExtension(name) == ".exe") {
2136     name = cmSystemTools::GetFilenameWithoutLastExtension(name);
2137   }
2138
2139   // Look for a CMake target with the given name.
2140   if (cmGeneratorTarget* target = this->FindGeneratorTargetToUse(name)) {
2141     // make sure it is not just a coincidence that the target name
2142     // found is part of the inName
2143     if (cmSystemTools::FileIsFullPath(inName)) {
2144       std::string tLocation;
2145       if (target->GetType() >= cmStateEnums::EXECUTABLE &&
2146           target->GetType() <= cmStateEnums::MODULE_LIBRARY) {
2147         tLocation = target->GetLocation(config);
2148         tLocation = cmSystemTools::GetFilenamePath(tLocation);
2149         tLocation = cmSystemTools::CollapseFullPath(tLocation);
2150       }
2151       std::string depLocation =
2152         cmSystemTools::GetFilenamePath(std::string(inName));
2153       depLocation = cmSystemTools::CollapseFullPath(depLocation);
2154       if (depLocation != tLocation) {
2155         // it is a full path to a depend that has the same name
2156         // as a target but is in a different location so do not use
2157         // the target as the depend
2158         dep = inName;
2159         return true;
2160       }
2161     }
2162     switch (target->GetType()) {
2163       case cmStateEnums::EXECUTABLE:
2164       case cmStateEnums::STATIC_LIBRARY:
2165       case cmStateEnums::SHARED_LIBRARY:
2166       case cmStateEnums::MODULE_LIBRARY:
2167       case cmStateEnums::UNKNOWN_LIBRARY:
2168         dep = target->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact,
2169                                   /*realname=*/true);
2170         return true;
2171       case cmStateEnums::OBJECT_LIBRARY:
2172         // An object library has no single file on which to depend.
2173         // This was listed to get the target-level dependency.
2174       case cmStateEnums::INTERFACE_LIBRARY:
2175         // An interface library has no file on which to depend.
2176         // This was listed to get the target-level dependency.
2177       case cmStateEnums::UTILITY:
2178       case cmStateEnums::GLOBAL_TARGET:
2179         // A utility target has no file on which to depend.  This was listed
2180         // only to get the target-level dependency.
2181         return false;
2182     }
2183   }
2184
2185   // The name was not that of a CMake target.  It must name a file.
2186   if (cmSystemTools::FileIsFullPath(inName)) {
2187     // This is a full path.  Return it as given.
2188     dep = inName;
2189     return true;
2190   }
2191
2192   // Check for a source file in this directory that matches the
2193   // dependency.
2194   if (cmSourceFile* sf = this->Makefile->GetSource(inName)) {
2195     dep = sf->ResolveFullPath();
2196     return true;
2197   }
2198
2199   // Treat the name as relative to the source directory in which it
2200   // was given.
2201   dep = cmStrCat(this->GetCurrentSourceDirectory(), '/', inName);
2202
2203   // If the in-source path does not exist, assume it instead lives in the
2204   // binary directory.
2205   if (!cmSystemTools::FileExists(dep)) {
2206     dep = cmStrCat(this->GetCurrentBinaryDirectory(), '/', inName);
2207   }
2208
2209   dep = cmSystemTools::CollapseFullPath(dep, this->GetBinaryDirectory());
2210
2211   return true;
2212 }
2213
2214 void cmLocalGenerator::AddSharedFlags(std::string& flags,
2215                                       const std::string& lang, bool shared)
2216 {
2217   std::string flagsVar;
2218
2219   // Add flags for dealing with shared libraries for this language.
2220   if (shared) {
2221     this->AppendFlags(flags,
2222                       this->Makefile->GetSafeDefinition(
2223                         cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS")));
2224   }
2225 }
2226
2227 void cmLocalGenerator::AddCompilerRequirementFlag(
2228   std::string& flags, cmGeneratorTarget const* target, const std::string& lang,
2229   const std::string& config)
2230 {
2231   cmStandardLevelResolver standardResolver(this->Makefile);
2232
2233   std::string const& optionFlagDef =
2234     standardResolver.GetCompileOptionDef(target, lang, config);
2235   if (!optionFlagDef.empty()) {
2236     cmValue opt = target->Target->GetMakefile()->GetDefinition(optionFlagDef);
2237     if (opt) {
2238       std::vector<std::string> optVec = cmExpandedList(*opt);
2239       for (std::string const& i : optVec) {
2240         this->AppendFlagEscape(flags, i);
2241       }
2242     }
2243   }
2244 }
2245
2246 static void AddVisibilityCompileOption(std::string& flags,
2247                                        cmGeneratorTarget const* target,
2248                                        cmLocalGenerator* lg,
2249                                        const std::string& lang,
2250                                        std::string* warnCMP0063)
2251 {
2252   std::string compileOption = "CMAKE_" + lang + "_COMPILE_OPTIONS_VISIBILITY";
2253   cmValue opt = lg->GetMakefile()->GetDefinition(compileOption);
2254   if (!opt) {
2255     return;
2256   }
2257   std::string flagDefine = lang + "_VISIBILITY_PRESET";
2258
2259   cmValue prop = target->GetProperty(flagDefine);
2260   if (!prop) {
2261     return;
2262   }
2263   if (warnCMP0063) {
2264     *warnCMP0063 += "  " + flagDefine + "\n";
2265     return;
2266   }
2267   if ((*prop != "hidden") && (*prop != "default") && (*prop != "protected") &&
2268       (*prop != "internal")) {
2269     std::ostringstream e;
2270     e << "Target " << target->GetName() << " uses unsupported value \""
2271       << *prop << "\" for " << flagDefine << "."
2272       << " The supported values are: default, hidden, protected, and "
2273          "internal.";
2274     cmSystemTools::Error(e.str());
2275     return;
2276   }
2277   std::string option = *opt + *prop;
2278   lg->AppendFlags(flags, option);
2279 }
2280
2281 static void AddInlineVisibilityCompileOption(std::string& flags,
2282                                              cmGeneratorTarget const* target,
2283                                              cmLocalGenerator* lg,
2284                                              std::string* warnCMP0063,
2285                                              const std::string& lang)
2286 {
2287   std::string compileOption =
2288     cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN");
2289   cmValue opt = lg->GetMakefile()->GetDefinition(compileOption);
2290   if (!opt) {
2291     return;
2292   }
2293
2294   bool prop = target->GetPropertyAsBool("VISIBILITY_INLINES_HIDDEN");
2295   if (!prop) {
2296     return;
2297   }
2298   if (warnCMP0063) {
2299     *warnCMP0063 += "  VISIBILITY_INLINES_HIDDEN\n";
2300     return;
2301   }
2302   lg->AppendFlags(flags, *opt);
2303 }
2304
2305 void cmLocalGenerator::AddVisibilityPresetFlags(
2306   std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
2307 {
2308   if (lang.empty()) {
2309     return;
2310   }
2311
2312   std::string warnCMP0063;
2313   std::string* pWarnCMP0063 = nullptr;
2314   if (target->GetType() != cmStateEnums::SHARED_LIBRARY &&
2315       target->GetType() != cmStateEnums::MODULE_LIBRARY &&
2316       !target->IsExecutableWithExports()) {
2317     switch (target->GetPolicyStatusCMP0063()) {
2318       case cmPolicies::OLD:
2319         return;
2320       case cmPolicies::WARN:
2321         pWarnCMP0063 = &warnCMP0063;
2322         break;
2323       default:
2324         break;
2325     }
2326   }
2327
2328   AddVisibilityCompileOption(flags, target, this, lang, pWarnCMP0063);
2329
2330   if (lang == "CXX" || lang == "OBJCXX") {
2331     AddInlineVisibilityCompileOption(flags, target, this, pWarnCMP0063, lang);
2332   }
2333
2334   if (!warnCMP0063.empty() && this->WarnCMP0063.insert(target).second) {
2335     std::ostringstream w;
2336     /* clang-format off */
2337     w <<
2338       cmPolicies::GetPolicyWarning(cmPolicies::CMP0063) << "\n"
2339       "Target \"" << target->GetName() << "\" of "
2340       "type \"" << cmState::GetTargetTypeName(target->GetType()) << "\" "
2341       "has the following visibility properties set for " << lang << ":\n" <<
2342       warnCMP0063 <<
2343       "For compatibility CMake is not honoring them for this target.";
2344     /* clang-format on */
2345     target->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
2346       MessageType::AUTHOR_WARNING, w.str(), target->GetBacktrace());
2347   }
2348 }
2349
2350 void cmLocalGenerator::AddCMP0018Flags(std::string& flags,
2351                                        cmGeneratorTarget const* target,
2352                                        std::string const& lang,
2353                                        const std::string& config)
2354 {
2355   int targetType = target->GetType();
2356
2357   bool shared = ((targetType == cmStateEnums::SHARED_LIBRARY) ||
2358                  (targetType == cmStateEnums::MODULE_LIBRARY));
2359
2360   if (this->GetShouldUseOldFlags(shared, lang)) {
2361     this->AddSharedFlags(flags, lang, shared);
2362   } else {
2363     if (target->GetLinkInterfaceDependentBoolProperty(
2364           "POSITION_INDEPENDENT_CODE", config)) {
2365       this->AddPositionIndependentFlags(flags, lang, targetType);
2366     }
2367     if (shared) {
2368       this->AppendFeatureOptions(flags, lang, "DLL");
2369     }
2370   }
2371 }
2372
2373 bool cmLocalGenerator::GetShouldUseOldFlags(bool shared,
2374                                             const std::string& lang) const
2375 {
2376   std::string originalFlags =
2377     this->GlobalGenerator->GetSharedLibFlagsForLanguage(lang);
2378   if (shared) {
2379     std::string flagsVar = cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS");
2380     std::string const& flags = this->Makefile->GetSafeDefinition(flagsVar);
2381
2382     if (flags != originalFlags) {
2383       switch (this->GetPolicyStatus(cmPolicies::CMP0018)) {
2384         case cmPolicies::WARN: {
2385           std::ostringstream e;
2386           e << "Variable " << flagsVar
2387             << " has been modified. CMake "
2388                "will ignore the POSITION_INDEPENDENT_CODE target property "
2389                "for "
2390                "shared libraries and will use the "
2391             << flagsVar
2392             << " variable "
2393                "instead.  This may cause errors if the original content of "
2394             << flagsVar << " was removed.\n"
2395             << cmPolicies::GetPolicyWarning(cmPolicies::CMP0018);
2396
2397           this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
2398           CM_FALLTHROUGH;
2399         }
2400         case cmPolicies::OLD:
2401           return true;
2402         case cmPolicies::REQUIRED_IF_USED:
2403         case cmPolicies::REQUIRED_ALWAYS:
2404         case cmPolicies::NEW:
2405           return false;
2406       }
2407     }
2408   }
2409   return false;
2410 }
2411
2412 void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
2413                                                    std::string const& lang,
2414                                                    int targetType)
2415 {
2416   std::string picFlags;
2417
2418   if (targetType == cmStateEnums::EXECUTABLE) {
2419     picFlags = this->Makefile->GetSafeDefinition(
2420       cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIE"));
2421   }
2422   if (picFlags.empty()) {
2423     picFlags = this->Makefile->GetSafeDefinition(
2424       cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIC"));
2425   }
2426   if (!picFlags.empty()) {
2427     std::vector<std::string> options = cmExpandedList(picFlags);
2428     for (std::string const& o : options) {
2429       this->AppendFlagEscape(flags, o);
2430     }
2431   }
2432 }
2433
2434 void cmLocalGenerator::AddColorDiagnosticsFlags(std::string& flags,
2435                                                 const std::string& lang)
2436 {
2437   cmValue diag = this->Makefile->GetDefinition("CMAKE_COLOR_DIAGNOSTICS");
2438   if (diag.IsSet()) {
2439     std::string colorFlagName;
2440     if (diag.IsOn()) {
2441       colorFlagName =
2442         cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_COLOR_DIAGNOSTICS");
2443     } else {
2444       colorFlagName =
2445         cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_COLOR_DIAGNOSTICS_OFF");
2446     }
2447
2448     std::vector<std::string> options;
2449     this->Makefile->GetDefExpandList(colorFlagName, options);
2450
2451     for (std::string const& option : options) {
2452       this->AppendFlagEscape(flags, option);
2453     }
2454   }
2455 }
2456
2457 void cmLocalGenerator::AddConfigVariableFlags(std::string& flags,
2458                                               const std::string& var,
2459                                               const std::string& config)
2460 {
2461   // Add the flags from the variable itself.
2462   this->AppendFlags(flags, this->Makefile->GetSafeDefinition(var));
2463   // Add the flags from the build-type specific variable.
2464   if (!config.empty()) {
2465     const std::string flagsVar =
2466       cmStrCat(var, '_', cmSystemTools::UpperCase(config));
2467     this->AppendFlags(flags, this->Makefile->GetSafeDefinition(flagsVar));
2468   }
2469 }
2470
2471 void cmLocalGenerator::AppendFlags(std::string& flags,
2472                                    const std::string& newFlags) const
2473 {
2474   bool allSpaces = std::all_of(newFlags.begin(), newFlags.end(), cmIsSpace);
2475
2476   if (!newFlags.empty() && !allSpaces) {
2477     if (!flags.empty()) {
2478       flags += " ";
2479     }
2480     flags += newFlags;
2481   }
2482 }
2483
2484 void cmLocalGenerator::AppendFlags(
2485   std::string& flags, const std::vector<BT<std::string>>& newFlags) const
2486 {
2487   for (BT<std::string> const& flag : newFlags) {
2488     this->AppendFlags(flags, flag.Value);
2489   }
2490 }
2491
2492 void cmLocalGenerator::AppendFlagEscape(std::string& flags,
2493                                         const std::string& rawFlag) const
2494 {
2495   this->AppendFlags(
2496     flags,
2497     this->EscapeForShell(rawFlag, false, false, false, this->IsNinjaMulti()));
2498 }
2499
2500 void cmLocalGenerator::AddISPCDependencies(cmGeneratorTarget* target)
2501 {
2502   std::vector<std::string> enabledLanguages =
2503     this->GetState()->GetEnabledLanguages();
2504   if (std::find(enabledLanguages.begin(), enabledLanguages.end(), "ISPC") ==
2505       enabledLanguages.end()) {
2506     return;
2507   }
2508
2509   cmValue ispcHeaderSuffixProp = target->GetProperty("ISPC_HEADER_SUFFIX");
2510   assert(ispcHeaderSuffixProp);
2511
2512   std::vector<std::string> ispcArchSuffixes =
2513     detail::ComputeISPCObjectSuffixes(target);
2514   const bool extra_objects = (ispcArchSuffixes.size() > 1);
2515
2516   std::vector<std::string> configsList =
2517     this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
2518   for (std::string const& config : configsList) {
2519
2520     std::string rootObjectDir = target->GetObjectDirectory(config);
2521     std::string headerDir = rootObjectDir;
2522     if (cmValue prop = target->GetProperty("ISPC_HEADER_DIRECTORY")) {
2523       headerDir = cmSystemTools::CollapseFullPath(
2524         cmStrCat(this->GetBinaryDirectory(), '/', *prop));
2525     }
2526
2527     std::vector<cmSourceFile*> sources;
2528     target->GetSourceFiles(sources, config);
2529
2530     // build up the list of ispc headers and extra objects that this target is
2531     // generating
2532     for (cmSourceFile const* sf : sources) {
2533       // Generate this object file's rule file.
2534       const std::string& lang = sf->GetLanguage();
2535       if (lang == "ISPC") {
2536         std::string const& objectName = target->GetObjectName(sf);
2537
2538         // Drop both ".obj" and the source file extension
2539         std::string ispcSource =
2540           cmSystemTools::GetFilenameWithoutLastExtension(objectName);
2541         ispcSource =
2542           cmSystemTools::GetFilenameWithoutLastExtension(ispcSource);
2543
2544         auto headerPath =
2545           cmStrCat(headerDir, '/', ispcSource, *ispcHeaderSuffixProp);
2546         target->AddISPCGeneratedHeader(headerPath, config);
2547         if (extra_objects) {
2548           std::vector<std::string> objs = detail::ComputeISPCExtraObjects(
2549             objectName, rootObjectDir, ispcArchSuffixes);
2550           target->AddISPCGeneratedObject(std::move(objs), config);
2551         }
2552       }
2553     }
2554   }
2555 }
2556
2557 void cmLocalGenerator::AddPchDependencies(cmGeneratorTarget* target)
2558 {
2559   std::vector<std::string> configsList =
2560     this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
2561
2562   for (std::string const& config : configsList) {
2563     // FIXME: Refactor collection of sources to not evaluate object
2564     // libraries.
2565     std::vector<cmSourceFile*> sources;
2566     target->GetSourceFiles(sources, config);
2567
2568     const std::string configUpper = cmSystemTools::UpperCase(config);
2569     static const std::array<std::string, 4> langs = { { "C", "CXX", "OBJC",
2570                                                         "OBJCXX" } };
2571
2572     std::set<std::string> pchLangSet;
2573     if (this->GetGlobalGenerator()->IsXcode()) {
2574       for (const std::string& lang : langs) {
2575         const std::string pchHeader = target->GetPchHeader(config, lang, "");
2576         if (!pchHeader.empty()) {
2577           pchLangSet.emplace(lang);
2578         }
2579       }
2580     }
2581
2582     for (const std::string& lang : langs) {
2583       auto langSources = std::count_if(
2584         sources.begin(), sources.end(), [lang](cmSourceFile* sf) {
2585           return lang == sf->GetLanguage() &&
2586             !sf->GetProperty("SKIP_PRECOMPILE_HEADERS");
2587         });
2588       if (langSources == 0) {
2589         continue;
2590       }
2591
2592       std::vector<std::string> architectures;
2593       if (!this->GetGlobalGenerator()->IsXcode()) {
2594         target->GetAppleArchs(config, architectures);
2595       }
2596       if (architectures.empty()) {
2597         architectures.emplace_back();
2598       } else {
2599         std::string useMultiArchPch;
2600         for (const std::string& arch : architectures) {
2601           const std::string pchHeader =
2602             target->GetPchHeader(config, lang, arch);
2603           if (!pchHeader.empty()) {
2604             useMultiArchPch = cmStrCat(useMultiArchPch, ";-Xarch_", arch,
2605                                        ";-include", pchHeader);
2606           }
2607         }
2608
2609         if (!useMultiArchPch.empty()) {
2610
2611           target->Target->AppendProperty(
2612             cmStrCat(lang, "_COMPILE_OPTIONS_USE_PCH"),
2613             cmStrCat("$<$<CONFIG:", config, ">:", useMultiArchPch, ">"));
2614         }
2615       }
2616
2617       for (const std::string& arch : architectures) {
2618         const std::string pchSource = target->GetPchSource(config, lang, arch);
2619         const std::string pchHeader = target->GetPchHeader(config, lang, arch);
2620
2621         if (pchSource.empty() || pchHeader.empty()) {
2622           if (this->GetGlobalGenerator()->IsXcode() && !pchLangSet.empty()) {
2623             for (auto* sf : sources) {
2624               const auto sourceLanguage = sf->GetLanguage();
2625               if (!sourceLanguage.empty() &&
2626                   pchLangSet.find(sourceLanguage) == pchLangSet.end()) {
2627                 sf->SetProperty("SKIP_PRECOMPILE_HEADERS", "ON");
2628               }
2629             }
2630           }
2631           continue;
2632         }
2633
2634         cmValue pchExtension =
2635           this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
2636
2637         if (pchExtension.IsEmpty()) {
2638           continue;
2639         }
2640
2641         cmValue ReuseFrom =
2642           target->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
2643
2644         auto* pch_sf = this->Makefile->GetOrCreateSource(
2645           pchSource, false, cmSourceFileLocationKind::Known);
2646
2647         if (!this->GetGlobalGenerator()->IsXcode()) {
2648           if (!ReuseFrom) {
2649             target->AddSource(pchSource, true);
2650           }
2651
2652           const std::string pchFile = target->GetPchFile(config, lang, arch);
2653
2654           // Exclude the pch files from linking
2655           if (this->Makefile->IsOn("CMAKE_LINK_PCH")) {
2656             if (!ReuseFrom) {
2657               pch_sf->AppendProperty(
2658                 "OBJECT_OUTPUTS",
2659                 cmStrCat("$<$<CONFIG:", config, ">:", pchFile, ">"));
2660             } else {
2661               auto* reuseTarget =
2662                 this->GlobalGenerator->FindGeneratorTarget(*ReuseFrom);
2663
2664               if (this->Makefile->IsOn("CMAKE_PCH_COPY_COMPILE_PDB")) {
2665
2666                 const std::string compilerId =
2667                   this->Makefile->GetSafeDefinition(
2668                     cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
2669
2670                 const std::string compilerVersion =
2671                   this->Makefile->GetSafeDefinition(
2672                     cmStrCat("CMAKE_", lang, "_COMPILER_VERSION"));
2673
2674                 const std::string langFlags =
2675                   this->Makefile->GetSafeDefinition(
2676                     cmStrCat("CMAKE_", lang, "_FLAGS_", configUpper));
2677
2678                 bool editAndContinueDebugInfo = false;
2679                 bool programDatabaseDebugInfo = false;
2680                 cm::optional<std::string> msvcDebugInformationFormat =
2681                   this->GetMSVCDebugFormatName(config, target);
2682                 if (msvcDebugInformationFormat &&
2683                     !msvcDebugInformationFormat->empty()) {
2684                   editAndContinueDebugInfo =
2685                     *msvcDebugInformationFormat == "EditAndContinue";
2686                   programDatabaseDebugInfo =
2687                     *msvcDebugInformationFormat == "ProgramDatabase";
2688                 } else {
2689                   editAndContinueDebugInfo =
2690                     langFlags.find("/ZI") != std::string::npos ||
2691                     langFlags.find("-ZI") != std::string::npos;
2692                   programDatabaseDebugInfo =
2693                     langFlags.find("/Zi") != std::string::npos ||
2694                     langFlags.find("-Zi") != std::string::npos;
2695                 }
2696
2697                 // MSVC 2008 is producing both .pdb and .idb files with /Zi.
2698                 bool msvc2008OrLess =
2699                   cmSystemTools::VersionCompare(cmSystemTools::OP_LESS,
2700                                                 compilerVersion, "16.0") &&
2701                   compilerId == "MSVC";
2702                 // but not when used via toolset -Tv90
2703                 if (this->Makefile->GetSafeDefinition(
2704                       "CMAKE_VS_PLATFORM_TOOLSET") == "v90") {
2705                   msvc2008OrLess = false;
2706                 }
2707
2708                 if (editAndContinueDebugInfo || msvc2008OrLess) {
2709                   this->CopyPchCompilePdb(config, target, *ReuseFrom,
2710                                           reuseTarget, { ".pdb", ".idb" });
2711                 } else if (programDatabaseDebugInfo) {
2712                   this->CopyPchCompilePdb(config, target, *ReuseFrom,
2713                                           reuseTarget, { ".pdb" });
2714                 }
2715               }
2716
2717               // Link to the pch object file
2718               std::string pchSourceObj =
2719                 reuseTarget->GetPchFileObject(config, lang, arch);
2720
2721               if (target->GetType() != cmStateEnums::OBJECT_LIBRARY) {
2722                 std::string linkerProperty = "LINK_FLAGS_";
2723                 if (target->GetType() == cmStateEnums::STATIC_LIBRARY) {
2724                   linkerProperty = "STATIC_LIBRARY_FLAGS_";
2725                 }
2726                 target->Target->AppendProperty(
2727                   cmStrCat(linkerProperty, configUpper),
2728                   cmStrCat(" ",
2729                            this->ConvertToOutputFormat(pchSourceObj, SHELL)),
2730                   cm::nullopt, true);
2731               } else if (reuseTarget->GetType() ==
2732                          cmStateEnums::OBJECT_LIBRARY) {
2733                 // FIXME: This can propagate more than one level, unlike
2734                 // the rest of the object files in an object library.
2735                 // Find another way to do this.
2736                 target->Target->AppendProperty(
2737                   "INTERFACE_LINK_LIBRARIES",
2738                   cmStrCat("$<$<CONFIG:", config,
2739                            ">:$<LINK_ONLY:", pchSourceObj, ">>"));
2740                 // We updated the link interface, so ensure it is recomputed.
2741                 target->ClearLinkInterfaceCache();
2742               }
2743             }
2744           } else {
2745             pch_sf->SetProperty("PCH_EXTENSION", pchExtension);
2746           }
2747
2748           // Add pchHeader to source files, which will
2749           // be grouped as "Precompile Header File"
2750           auto* pchHeader_sf = this->Makefile->GetOrCreateSource(
2751             pchHeader, false, cmSourceFileLocationKind::Known);
2752           std::string err;
2753           pchHeader_sf->ResolveFullPath(&err);
2754           if (!err.empty()) {
2755             std::ostringstream msg;
2756             msg << "Unable to resolve full path of PCH-header '" << pchHeader
2757                 << "' assigned to target " << target->GetName()
2758                 << ", although its path is supposed to be known!";
2759             this->IssueMessage(MessageType::FATAL_ERROR, msg.str());
2760           }
2761           target->AddSource(pchHeader);
2762         }
2763       }
2764     }
2765   }
2766 }
2767
2768 void cmLocalGenerator::CopyPchCompilePdb(
2769   const std::string& config, cmGeneratorTarget* target,
2770   const std::string& ReuseFrom, cmGeneratorTarget* reuseTarget,
2771   const std::vector<std::string>& extensions)
2772 {
2773   const std::string pdb_prefix =
2774     this->GetGlobalGenerator()->IsMultiConfig() ? cmStrCat(config, "/") : "";
2775
2776   const std::string target_compile_pdb_dir =
2777     cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/",
2778              target->GetName(), ".dir/");
2779
2780   const std::string copy_script = cmStrCat(
2781     target_compile_pdb_dir, "copy_idb_pdb_", config.c_str(), ".cmake");
2782   cmGeneratedFileStream file(copy_script);
2783
2784   file << "# CMake generated file\n";
2785
2786   file << "# The compiler generated pdb file needs to be written to disk\n"
2787        << "# by mspdbsrv. The foreach retry loop is needed to make sure\n"
2788        << "# the pdb file is ready to be copied.\n\n";
2789
2790   for (auto const& extension : extensions) {
2791     const std::string from_file =
2792       cmStrCat(reuseTarget->GetLocalGenerator()->GetCurrentBinaryDirectory(),
2793                "/", ReuseFrom, ".dir/${PDB_PREFIX}", ReuseFrom, extension);
2794
2795     const std::string to_dir =
2796       cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/",
2797                target->GetName(), ".dir/${PDB_PREFIX}");
2798
2799     const std::string to_file = cmStrCat(to_dir, ReuseFrom, extension);
2800
2801     std::string dest_file = to_file;
2802
2803     std::string const& prefix = target->GetSafeProperty("PREFIX");
2804     if (!prefix.empty()) {
2805       dest_file = cmStrCat(to_dir, prefix, ReuseFrom, extension);
2806     }
2807
2808     file << "foreach(retry RANGE 1 30)\n";
2809     file << "  if (EXISTS \"" << from_file << "\" AND (NOT EXISTS \""
2810          << dest_file << "\" OR NOT \"" << dest_file << "  \" IS_NEWER_THAN \""
2811          << from_file << "\"))\n";
2812     file << "    execute_process(COMMAND ${CMAKE_COMMAND} -E copy";
2813     file << " \"" << from_file << "\""
2814          << " \"" << to_dir << "\" RESULT_VARIABLE result "
2815          << " ERROR_QUIET)\n";
2816     file << "    if (NOT result EQUAL 0)\n"
2817          << "      execute_process(COMMAND ${CMAKE_COMMAND}"
2818          << " -E sleep 1)\n"
2819          << "    else()\n";
2820     if (!prefix.empty()) {
2821       file << "  file(REMOVE \"" << dest_file << "\")\n";
2822       file << "  file(RENAME \"" << to_file << "\" \"" << dest_file << "\")\n";
2823     }
2824     file << "      break()\n"
2825          << "    endif()\n";
2826     file << "  elseif(NOT EXISTS \"" << from_file << "\")\n"
2827          << "    execute_process(COMMAND ${CMAKE_COMMAND}"
2828          << " -E sleep 1)\n"
2829          << "  endif()\n";
2830     file << "endforeach()\n";
2831   }
2832
2833   auto configGenex = [&](cm::string_view expr) -> std::string {
2834     if (this->GetGlobalGenerator()->IsMultiConfig()) {
2835       return cmStrCat("$<$<CONFIG:", config, ">:", expr, ">");
2836     }
2837     return std::string(expr);
2838   };
2839
2840   cmCustomCommandLines commandLines = cmMakeSingleCommandLine(
2841     { configGenex(cmSystemTools::GetCMakeCommand()),
2842       configGenex(cmStrCat("-DPDB_PREFIX=", pdb_prefix)), configGenex("-P"),
2843       configGenex(copy_script) });
2844
2845   const char* no_message = "";
2846
2847   std::vector<std::string> outputs;
2848   outputs.push_back(configGenex(
2849     cmStrCat(target_compile_pdb_dir, pdb_prefix, ReuseFrom, ".pdb")));
2850
2851   auto cc = cm::make_unique<cmCustomCommand>();
2852   cc->SetCommandLines(commandLines);
2853   cc->SetComment(no_message);
2854   cc->SetCMP0116Status(cmPolicies::NEW);
2855   cc->SetStdPipesUTF8(true);
2856
2857   if (this->GetGlobalGenerator()->IsVisualStudio()) {
2858     cc->SetByproducts(outputs);
2859     this->AddCustomCommandToTarget(
2860       target->GetName(), cmCustomCommandType::PRE_BUILD, std::move(cc),
2861       cmObjectLibraryCommands::Accept);
2862   } else {
2863     cc->SetOutputs(outputs);
2864     cmSourceFile* copy_rule = this->AddCustomCommandToOutput(std::move(cc));
2865
2866     if (copy_rule) {
2867       target->AddSource(copy_rule->ResolveFullPath());
2868     }
2869   }
2870
2871   target->Target->SetProperty("COMPILE_PDB_OUTPUT_DIRECTORY",
2872                               target_compile_pdb_dir);
2873 }
2874
2875 cm::optional<std::string> cmLocalGenerator::GetMSVCDebugFormatName(
2876   std::string const& config, cmGeneratorTarget const* target)
2877 {
2878   // MSVC debug information format selection is activated by the presence
2879   // of a default whether or not it is overridden by a property.
2880   cm::optional<std::string> msvcDebugInformationFormat;
2881   cmValue msvcDebugInformationFormatDefault = this->Makefile->GetDefinition(
2882     "CMAKE_MSVC_DEBUG_INFORMATION_FORMAT_DEFAULT");
2883   if (cmNonempty(msvcDebugInformationFormatDefault)) {
2884     cmValue msvcDebugInformationFormatValue =
2885       target->GetProperty("MSVC_DEBUG_INFORMATION_FORMAT");
2886     if (!msvcDebugInformationFormatValue) {
2887       msvcDebugInformationFormatValue = msvcDebugInformationFormatDefault;
2888     }
2889     msvcDebugInformationFormat = cmGeneratorExpression::Evaluate(
2890       *msvcDebugInformationFormatValue, this, config, target);
2891   }
2892   return msvcDebugInformationFormat;
2893 }
2894
2895 namespace {
2896
2897 inline void RegisterUnitySources(cmGeneratorTarget* target, cmSourceFile* sf,
2898                                  std::string const& filename)
2899 {
2900   target->AddSourceFileToUnityBatch(sf->ResolveFullPath());
2901   sf->SetProperty("UNITY_SOURCE_FILE", filename);
2902 }
2903 }
2904
2905 cmLocalGenerator::UnitySource cmLocalGenerator::WriteUnitySource(
2906   cmGeneratorTarget* target, std::vector<std::string> const& configs,
2907   cmRange<std::vector<UnityBatchedSource>::const_iterator> sources,
2908   cmValue beforeInclude, cmValue afterInclude, std::string filename) const
2909 {
2910   cmValue uniqueIdName = target->GetProperty("UNITY_BUILD_UNIQUE_ID");
2911   cmGeneratedFileStream file(
2912     filename, false, target->GetGlobalGenerator()->GetMakefileEncoding());
2913   file.SetCopyIfDifferent(true);
2914   file << "/* generated by CMake */\n\n";
2915
2916   bool perConfig = false;
2917   for (UnityBatchedSource const& ubs : sources) {
2918     cm::optional<std::string> cond;
2919     if (ubs.Configs.size() != configs.size()) {
2920       perConfig = true;
2921       cond = std::string();
2922       cm::string_view sep;
2923       for (size_t ci : ubs.Configs) {
2924         cond = cmStrCat(*cond, sep, "defined(CMAKE_UNITY_CONFIG_",
2925                         cmSystemTools::UpperCase(configs[ci]), ")");
2926         sep = " || "_s;
2927       }
2928     }
2929     RegisterUnitySources(target, ubs.Source, filename);
2930     WriteUnitySourceInclude(file, cond, ubs.Source->ResolveFullPath(),
2931                             beforeInclude, afterInclude, uniqueIdName);
2932   }
2933
2934   return UnitySource(std::move(filename), perConfig);
2935 }
2936
2937 void cmLocalGenerator::WriteUnitySourceInclude(
2938   std::ostream& unity_file, cm::optional<std::string> const& cond,
2939   std::string const& sf_full_path, cmValue beforeInclude, cmValue afterInclude,
2940   cmValue uniqueIdName) const
2941 {
2942   if (cond) {
2943     unity_file << "#if " << *cond << "\n";
2944   }
2945
2946   if (cmNonempty(uniqueIdName)) {
2947     std::string pathToHash;
2948     auto PathEqOrSubDir = [](std::string const& a, std::string const& b) {
2949       return (cmSystemTools::ComparePath(a, b) ||
2950               cmSystemTools::IsSubDirectory(a, b));
2951     };
2952     const auto path = cmSystemTools::GetFilenamePath(sf_full_path);
2953     if (PathEqOrSubDir(path, this->GetBinaryDirectory())) {
2954       pathToHash = "BLD_" +
2955         cmSystemTools::RelativePath(this->GetBinaryDirectory(), sf_full_path);
2956     } else if (PathEqOrSubDir(path, this->GetSourceDirectory())) {
2957       pathToHash = "SRC_" +
2958         cmSystemTools::RelativePath(this->GetSourceDirectory(), sf_full_path);
2959     } else {
2960       pathToHash = "ABS_" + sf_full_path;
2961     }
2962     unity_file << "/* " << pathToHash << " */\n"
2963                << "#undef " << *uniqueIdName << "\n"
2964                << "#define " << *uniqueIdName << " unity_"
2965 #ifndef CMAKE_BOOTSTRAP
2966                << cmSystemTools::ComputeStringMD5(pathToHash) << "\n"
2967 #endif
2968       ;
2969   }
2970
2971   if (beforeInclude) {
2972     unity_file << *beforeInclude << "\n";
2973   }
2974
2975   unity_file << "#include \"" << sf_full_path << "\"\n";
2976
2977   if (afterInclude) {
2978     unity_file << *afterInclude << "\n";
2979   }
2980   if (cond) {
2981     unity_file << "#endif\n";
2982   }
2983   unity_file << "\n";
2984 }
2985
2986 std::vector<cmLocalGenerator::UnitySource>
2987 cmLocalGenerator::AddUnityFilesModeAuto(
2988   cmGeneratorTarget* target, std::string const& lang,
2989   std::vector<std::string> const& configs,
2990   std::vector<UnityBatchedSource> const& filtered_sources,
2991   cmValue beforeInclude, cmValue afterInclude,
2992   std::string const& filename_base, size_t batchSize)
2993 {
2994   if (batchSize == 0) {
2995     batchSize = filtered_sources.size();
2996   }
2997
2998   std::vector<UnitySource> unity_files;
2999   for (size_t itemsLeft = filtered_sources.size(), chunk, batch = 0;
3000        itemsLeft > 0; itemsLeft -= chunk, ++batch) {
3001
3002     chunk = std::min(itemsLeft, batchSize);
3003
3004     std::string filename = cmStrCat(filename_base, "unity_", batch,
3005                                     (lang == "C") ? "_c.c" : "_cxx.cxx");
3006     auto const begin = filtered_sources.begin() + batch * batchSize;
3007     auto const end = begin + chunk;
3008     unity_files.emplace_back(this->WriteUnitySource(
3009       target, configs, cmMakeRange(begin, end), beforeInclude, afterInclude,
3010       std::move(filename)));
3011   }
3012   return unity_files;
3013 }
3014
3015 std::vector<cmLocalGenerator::UnitySource>
3016 cmLocalGenerator::AddUnityFilesModeGroup(
3017   cmGeneratorTarget* target, std::string const& lang,
3018   std::vector<std::string> const& configs,
3019   std::vector<UnityBatchedSource> const& filtered_sources,
3020   cmValue beforeInclude, cmValue afterInclude,
3021   std::string const& filename_base)
3022 {
3023   std::vector<UnitySource> unity_files;
3024
3025   // sources organized by group name. Drop any source
3026   // without a group
3027   std::unordered_map<std::string, std::vector<UnityBatchedSource>>
3028     explicit_mapping;
3029   for (UnityBatchedSource const& ubs : filtered_sources) {
3030     if (cmValue value = ubs.Source->GetProperty("UNITY_GROUP")) {
3031       auto i = explicit_mapping.find(*value);
3032       if (i == explicit_mapping.end()) {
3033         std::vector<UnityBatchedSource> sources{ ubs };
3034         explicit_mapping.emplace(*value, std::move(sources));
3035       } else {
3036         i->second.emplace_back(ubs);
3037       }
3038     }
3039   }
3040
3041   for (auto const& item : explicit_mapping) {
3042     auto const& name = item.first;
3043     std::string filename = cmStrCat(filename_base, "unity_", name,
3044                                     (lang == "C") ? "_c.c" : "_cxx.cxx");
3045     unity_files.emplace_back(this->WriteUnitySource(
3046       target, configs, cmMakeRange(item.second), beforeInclude, afterInclude,
3047       std::move(filename)));
3048   }
3049
3050   return unity_files;
3051 }
3052
3053 void cmLocalGenerator::AddUnityBuild(cmGeneratorTarget* target)
3054 {
3055   if (!target->GetPropertyAsBool("UNITY_BUILD")) {
3056     return;
3057   }
3058
3059   std::vector<UnityBatchedSource> unitySources;
3060
3061   std::vector<std::string> configs =
3062     this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
3063
3064   std::map<cmSourceFile const*, size_t> index;
3065
3066   for (size_t ci = 0; ci < configs.size(); ++ci) {
3067     // FIXME: Refactor collection of sources to not evaluate object libraries.
3068     std::vector<cmSourceFile*> sources;
3069     target->GetSourceFiles(sources, configs[ci]);
3070     for (cmSourceFile* sf : sources) {
3071       auto mi = index.find(sf);
3072       if (mi == index.end()) {
3073         unitySources.emplace_back(sf);
3074         std::map<cmSourceFile const*, size_t>::value_type entry(
3075           sf, unitySources.size() - 1);
3076         mi = index.insert(entry).first;
3077       }
3078       unitySources[mi->second].Configs.emplace_back(ci);
3079     }
3080   }
3081
3082   std::string filename_base =
3083     cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/",
3084              target->GetName(), ".dir/Unity/");
3085
3086   cmValue batchSizeString = target->GetProperty("UNITY_BUILD_BATCH_SIZE");
3087   const size_t unityBatchSize = batchSizeString
3088     ? static_cast<size_t>(std::atoi(batchSizeString->c_str()))
3089     : 0;
3090
3091   cmValue beforeInclude =
3092     target->GetProperty("UNITY_BUILD_CODE_BEFORE_INCLUDE");
3093   cmValue afterInclude = target->GetProperty("UNITY_BUILD_CODE_AFTER_INCLUDE");
3094   cmValue unityMode = target->GetProperty("UNITY_BUILD_MODE");
3095
3096   for (std::string lang : { "C", "CXX" }) {
3097     std::vector<UnityBatchedSource> filtered_sources;
3098     std::copy_if(unitySources.begin(), unitySources.end(),
3099                  std::back_inserter(filtered_sources),
3100                  [&](UnityBatchedSource const& ubs) -> bool {
3101                    cmSourceFile* sf = ubs.Source;
3102                    return sf->GetLanguage() == lang &&
3103                      !sf->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION") &&
3104                      !sf->GetPropertyAsBool("HEADER_FILE_ONLY") &&
3105                      !sf->GetProperty("COMPILE_OPTIONS") &&
3106                      !sf->GetProperty("COMPILE_DEFINITIONS") &&
3107                      !sf->GetProperty("COMPILE_FLAGS") &&
3108                      !sf->GetProperty("INCLUDE_DIRECTORIES");
3109                  });
3110
3111     std::vector<UnitySource> unity_files;
3112     if (!unityMode || *unityMode == "BATCH") {
3113       unity_files = AddUnityFilesModeAuto(
3114         target, lang, configs, filtered_sources, beforeInclude, afterInclude,
3115         filename_base, unityBatchSize);
3116     } else if (unityMode && *unityMode == "GROUP") {
3117       unity_files =
3118         AddUnityFilesModeGroup(target, lang, configs, filtered_sources,
3119                                beforeInclude, afterInclude, filename_base);
3120     } else {
3121       // unity mode is set to an unsupported value
3122       std::string e("Invalid UNITY_BUILD_MODE value of " + *unityMode +
3123                     " assigned to target " + target->GetName() +
3124                     ". Acceptable values are BATCH and GROUP.");
3125       this->IssueMessage(MessageType::FATAL_ERROR, e);
3126     }
3127
3128     for (UnitySource const& file : unity_files) {
3129       auto* unity = this->GetMakefile()->GetOrCreateSource(file.Path);
3130       target->AddSource(file.Path, true);
3131       unity->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "ON");
3132       unity->SetProperty("UNITY_SOURCE_FILE", file.Path);
3133       if (file.PerConfig) {
3134         unity->SetProperty("COMPILE_DEFINITIONS",
3135                            "CMAKE_UNITY_CONFIG_$<UPPER_CASE:$<CONFIG>>");
3136       }
3137     }
3138   }
3139 }
3140
3141 void cmLocalGenerator::AppendIPOLinkerFlags(std::string& flags,
3142                                             cmGeneratorTarget* target,
3143                                             const std::string& config,
3144                                             const std::string& lang)
3145 {
3146   if (!target->IsIPOEnabled(lang, config)) {
3147     return;
3148   }
3149
3150   switch (target->GetType()) {
3151     case cmStateEnums::EXECUTABLE:
3152     case cmStateEnums::SHARED_LIBRARY:
3153     case cmStateEnums::MODULE_LIBRARY:
3154       break;
3155     default:
3156       return;
3157   }
3158
3159   const std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_IPO";
3160   cmValue rawFlagsList = this->Makefile->GetDefinition(name);
3161   if (!rawFlagsList) {
3162     return;
3163   }
3164
3165   std::vector<std::string> flagsList = cmExpandedList(*rawFlagsList);
3166   for (std::string const& o : flagsList) {
3167     this->AppendFlagEscape(flags, o);
3168   }
3169 }
3170
3171 void cmLocalGenerator::AppendPositionIndependentLinkerFlags(
3172   std::string& flags, cmGeneratorTarget* target, const std::string& config,
3173   const std::string& lang)
3174 {
3175   // For now, only EXECUTABLE is concerned
3176   if (target->GetType() != cmStateEnums::EXECUTABLE) {
3177     return;
3178   }
3179
3180   const char* PICValue = target->GetLinkPIEProperty(config);
3181   if (PICValue == nullptr) {
3182     // POSITION_INDEPENDENT_CODE is not set
3183     return;
3184   }
3185
3186   const std::string mode = cmIsOn(PICValue) ? "PIE" : "NO_PIE";
3187
3188   std::string supported = "CMAKE_" + lang + "_LINK_" + mode + "_SUPPORTED";
3189   if (cmIsOff(this->Makefile->GetDefinition(supported))) {
3190     return;
3191   }
3192
3193   std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_" + mode;
3194
3195   auto pieFlags = this->Makefile->GetSafeDefinition(name);
3196   if (pieFlags.empty()) {
3197     return;
3198   }
3199
3200   std::vector<std::string> flagsList = cmExpandedList(pieFlags);
3201   for (const auto& flag : flagsList) {
3202     this->AppendFlagEscape(flags, flag);
3203   }
3204 }
3205
3206 void cmLocalGenerator::AppendModuleDefinitionFlag(
3207   std::string& flags, cmGeneratorTarget const* target,
3208   cmLinkLineComputer* linkLineComputer, std::string const& config)
3209 {
3210   cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
3211     target->GetModuleDefinitionInfo(config);
3212   if (!mdi || mdi->DefFile.empty()) {
3213     return;
3214   }
3215
3216   cmValue defFileFlag =
3217     this->Makefile->GetDefinition("CMAKE_LINK_DEF_FILE_FLAG");
3218   if (!defFileFlag) {
3219     return;
3220   }
3221
3222   // Append the flag and value.  Use ConvertToLinkReference to help
3223   // vs6's "cl -link" pass it to the linker.
3224   std::string flag =
3225     cmStrCat(*defFileFlag,
3226              this->ConvertToOutputFormat(
3227                linkLineComputer->ConvertToLinkReference(mdi->DefFile),
3228                cmOutputConverter::SHELL));
3229   this->AppendFlags(flags, flag);
3230 }
3231
3232 bool cmLocalGenerator::AppendLWYUFlags(std::string& flags,
3233                                        const cmGeneratorTarget* target,
3234                                        const std::string& lang)
3235 {
3236   auto useLWYU = target->GetPropertyAsBool("LINK_WHAT_YOU_USE") &&
3237     (target->GetType() == cmStateEnums::TargetType::EXECUTABLE ||
3238      target->GetType() == cmStateEnums::TargetType::SHARED_LIBRARY ||
3239      target->GetType() == cmStateEnums::TargetType::MODULE_LIBRARY);
3240
3241   if (useLWYU) {
3242     const auto& lwyuFlag = this->GetMakefile()->GetSafeDefinition(
3243       cmStrCat("CMAKE_", lang, "_LINK_WHAT_YOU_USE_FLAG"));
3244     useLWYU = !lwyuFlag.empty();
3245
3246     if (useLWYU) {
3247       std::vector<BT<std::string>> lwyuOpts;
3248       lwyuOpts.emplace_back(lwyuFlag);
3249       this->AppendFlags(flags, target->ResolveLinkerWrapper(lwyuOpts, lang));
3250     }
3251   }
3252
3253   return useLWYU;
3254 }
3255
3256 void cmLocalGenerator::AppendCompileOptions(std::string& options,
3257                                             std::string const& options_list,
3258                                             const char* regex) const
3259 {
3260   // Short-circuit if there are no options.
3261   if (options_list.empty()) {
3262     return;
3263   }
3264
3265   // Expand the list of options.
3266   std::vector<std::string> options_vec = cmExpandedList(options_list);
3267   this->AppendCompileOptions(options, options_vec, regex);
3268 }
3269
3270 void cmLocalGenerator::AppendCompileOptions(
3271   std::string& options, const std::vector<std::string>& options_vec,
3272   const char* regex) const
3273 {
3274   if (regex != nullptr) {
3275     // Filter flags upon specified reges.
3276     cmsys::RegularExpression r(regex);
3277
3278     for (std::string const& opt : options_vec) {
3279       if (r.find(opt)) {
3280         this->AppendFlagEscape(options, opt);
3281       }
3282     }
3283   } else {
3284     for (std::string const& opt : options_vec) {
3285       this->AppendFlagEscape(options, opt);
3286     }
3287   }
3288 }
3289
3290 void cmLocalGenerator::AppendCompileOptions(
3291   std::vector<BT<std::string>>& options,
3292   const std::vector<BT<std::string>>& options_vec, const char* regex) const
3293 {
3294   if (regex != nullptr) {
3295     // Filter flags upon specified regular expressions.
3296     cmsys::RegularExpression r(regex);
3297
3298     for (BT<std::string> const& opt : options_vec) {
3299       if (r.find(opt.Value)) {
3300         std::string flag;
3301         this->AppendFlagEscape(flag, opt.Value);
3302         options.emplace_back(std::move(flag), opt.Backtrace);
3303       }
3304     }
3305   } else {
3306     for (BT<std::string> const& opt : options_vec) {
3307       std::string flag;
3308       this->AppendFlagEscape(flag, opt.Value);
3309       options.emplace_back(std::move(flag), opt.Backtrace);
3310     }
3311   }
3312 }
3313
3314 void cmLocalGenerator::AppendIncludeDirectories(
3315   std::vector<std::string>& includes, const std::string& includes_list,
3316   const cmSourceFile& sourceFile) const
3317 {
3318   // Short-circuit if there are no includes.
3319   if (includes_list.empty()) {
3320     return;
3321   }
3322
3323   // Expand the list of includes.
3324   std::vector<std::string> includes_vec = cmExpandedList(includes_list);
3325   this->AppendIncludeDirectories(includes, includes_vec, sourceFile);
3326 }
3327
3328 void cmLocalGenerator::AppendIncludeDirectories(
3329   std::vector<std::string>& includes,
3330   const std::vector<std::string>& includes_vec,
3331   const cmSourceFile& sourceFile) const
3332 {
3333   std::unordered_set<std::string> uniqueIncludes;
3334
3335   for (const std::string& include : includes_vec) {
3336     if (!cmSystemTools::FileIsFullPath(include)) {
3337       std::ostringstream e;
3338       e << "Found relative path while evaluating include directories of "
3339            "\""
3340         << sourceFile.GetLocation().GetName() << "\":\n  \"" << include
3341         << "\"\n";
3342
3343       this->IssueMessage(MessageType::FATAL_ERROR, e.str());
3344       return;
3345     }
3346
3347     std::string inc = include;
3348
3349     if (!cmIsOff(inc)) {
3350       cmSystemTools::ConvertToUnixSlashes(inc);
3351     }
3352
3353     if (uniqueIncludes.insert(inc).second) {
3354       includes.push_back(std::move(inc));
3355     }
3356   }
3357 }
3358
3359 void cmLocalGenerator::AppendDefines(std::set<std::string>& defines,
3360                                      std::string const& defines_list) const
3361 {
3362   std::set<BT<std::string>> tmp;
3363   this->AppendDefines(tmp, cmExpandListWithBacktrace(defines_list));
3364   for (BT<std::string> const& i : tmp) {
3365     defines.emplace(i.Value);
3366   }
3367 }
3368
3369 void cmLocalGenerator::AppendDefines(std::set<BT<std::string>>& defines,
3370                                      std::string const& defines_list) const
3371 {
3372   // Short-circuit if there are no definitions.
3373   if (defines_list.empty()) {
3374     return;
3375   }
3376
3377   // Expand the list of definitions.
3378   this->AppendDefines(defines, cmExpandListWithBacktrace(defines_list));
3379 }
3380
3381 void cmLocalGenerator::AppendDefines(
3382   std::set<BT<std::string>>& defines,
3383   const std::vector<BT<std::string>>& defines_vec) const
3384 {
3385   for (BT<std::string> const& d : defines_vec) {
3386     // Skip unsupported definitions.
3387     if (!this->CheckDefinition(d.Value)) {
3388       continue;
3389     }
3390     defines.insert(d);
3391   }
3392 }
3393
3394 void cmLocalGenerator::JoinDefines(const std::set<std::string>& defines,
3395                                    std::string& definesString,
3396                                    const std::string& lang)
3397 {
3398   // Lookup the define flag for the current language.
3399   std::string dflag = "-D";
3400   if (!lang.empty()) {
3401     cmValue df =
3402       this->Makefile->GetDefinition(cmStrCat("CMAKE_", lang, "_DEFINE_FLAG"));
3403     if (cmNonempty(df)) {
3404       dflag = *df;
3405     }
3406   }
3407   const char* itemSeparator = definesString.empty() ? "" : " ";
3408   for (std::string const& define : defines) {
3409     // Append the definition with proper escaping.
3410     std::string def = dflag;
3411     if (this->GetState()->UseWatcomWMake()) {
3412       // The Watcom compiler does its own command line parsing instead
3413       // of using the windows shell rules.  Definitions are one of
3414       //   -DNAME
3415       //   -DNAME=<cpp-token>
3416       //   -DNAME="c-string with spaces and other characters(?@#$)"
3417       //
3418       // Watcom will properly parse each of these cases from the
3419       // command line without any escapes.  However we still have to
3420       // get the '$' and '#' characters through WMake as '$$' and
3421       // '$#'.
3422       for (char c : define) {
3423         if (c == '$' || c == '#') {
3424           def += '$';
3425         }
3426         def += c;
3427       }
3428     } else {
3429       // Make the definition appear properly on the command line.  Use
3430       // -DNAME="value" instead of -D"NAME=value" for historical reasons.
3431       std::string::size_type eq = define.find('=');
3432       def += define.substr(0, eq);
3433       if (eq != std::string::npos) {
3434         def += "=";
3435         def += this->EscapeForShell(define.substr(eq + 1), true);
3436       }
3437     }
3438     definesString += itemSeparator;
3439     itemSeparator = " ";
3440     definesString += def;
3441   }
3442 }
3443
3444 void cmLocalGenerator::AppendFeatureOptions(std::string& flags,
3445                                             const std::string& lang,
3446                                             const char* feature)
3447 {
3448   cmValue optionList = this->Makefile->GetDefinition(
3449     cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_", feature));
3450   if (optionList) {
3451     std::vector<std::string> options = cmExpandedList(*optionList);
3452     for (std::string const& o : options) {
3453       this->AppendFlagEscape(flags, o);
3454     }
3455   }
3456 }
3457
3458 cmValue cmLocalGenerator::GetFeature(const std::string& feature,
3459                                      const std::string& config)
3460 {
3461   std::string featureName = feature;
3462   // TODO: Define accumulation policy for features (prepend, append,
3463   // replace). Currently we always replace.
3464   if (!config.empty()) {
3465     featureName += "_";
3466     featureName += cmSystemTools::UpperCase(config);
3467   }
3468   cmStateSnapshot snp = this->StateSnapshot;
3469   while (snp.IsValid()) {
3470     if (cmValue value = snp.GetDirectory().GetProperty(featureName)) {
3471       return value;
3472     }
3473     snp = snp.GetBuildsystemDirectoryParent();
3474   }
3475   return nullptr;
3476 }
3477
3478 std::string cmLocalGenerator::GetProjectName() const
3479 {
3480   return this->StateSnapshot.GetProjectName();
3481 }
3482
3483 std::string cmLocalGenerator::ConstructComment(
3484   cmCustomCommandGenerator const& ccg, const char* default_comment) const
3485 {
3486   // Check for a comment provided with the command.
3487   if (ccg.GetComment()) {
3488     return ccg.GetComment();
3489   }
3490
3491   // Construct a reasonable default comment if possible.
3492   if (!ccg.GetOutputs().empty()) {
3493     std::string comment;
3494     comment = "Generating ";
3495     const char* sep = "";
3496     for (std::string const& o : ccg.GetOutputs()) {
3497       comment += sep;
3498       comment += this->MaybeRelativeToCurBinDir(o);
3499       sep = ", ";
3500     }
3501     return comment;
3502   }
3503
3504   // Otherwise use the provided default.
3505   return default_comment;
3506 }
3507
3508 class cmInstallTargetGeneratorLocal : public cmInstallTargetGenerator
3509 {
3510 public:
3511   cmInstallTargetGeneratorLocal(cmLocalGenerator* lg, std::string const& t,
3512                                 std::string const& dest, bool implib)
3513     : cmInstallTargetGenerator(
3514         t, dest, implib, "", std::vector<std::string>(), "Unspecified",
3515         cmInstallGenerator::SelectMessageLevel(lg->GetMakefile()), false,
3516         false)
3517   {
3518     this->Compute(lg);
3519   }
3520 };
3521
3522 void cmLocalGenerator::GenerateTargetInstallRules(
3523   std::ostream& os, const std::string& config,
3524   std::vector<std::string> const& configurationTypes)
3525 {
3526   // Convert the old-style install specification from each target to
3527   // an install generator and run it.
3528   const auto& tgts = this->GetGeneratorTargets();
3529   for (const auto& l : tgts) {
3530     if (l->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
3531       continue;
3532     }
3533
3534     // Include the user-specified pre-install script for this target.
3535     if (cmValue preinstall = l->GetProperty("PRE_INSTALL_SCRIPT")) {
3536       cmInstallScriptGenerator g(*preinstall, false, "", false, false);
3537       g.Generate(os, config, configurationTypes);
3538     }
3539
3540     // Install this target if a destination is given.
3541     if (!l->Target->GetInstallPath().empty()) {
3542       // Compute the full install destination.  Note that converting
3543       // to unix slashes also removes any trailing slash.
3544       // We also skip over the leading slash given by the user.
3545       std::string destination = l->Target->GetInstallPath().substr(1);
3546       cmSystemTools::ConvertToUnixSlashes(destination);
3547       if (destination.empty()) {
3548         destination = ".";
3549       }
3550
3551       // Generate the proper install generator for this target type.
3552       switch (l->GetType()) {
3553         case cmStateEnums::EXECUTABLE:
3554         case cmStateEnums::STATIC_LIBRARY:
3555         case cmStateEnums::MODULE_LIBRARY: {
3556           // Use a target install generator.
3557           cmInstallTargetGeneratorLocal g(this, l->GetName(), destination,
3558                                           false);
3559           g.Generate(os, config, configurationTypes);
3560         } break;
3561         case cmStateEnums::SHARED_LIBRARY: {
3562 #if defined(_WIN32) || defined(__CYGWIN__)
3563           // Special code to handle DLL.  Install the import library
3564           // to the normal destination and the DLL to the runtime
3565           // destination.
3566           cmInstallTargetGeneratorLocal g1(this, l->GetName(), destination,
3567                                            true);
3568           g1.Generate(os, config, configurationTypes);
3569           // We also skip over the leading slash given by the user.
3570           destination = l->Target->GetRuntimeInstallPath().substr(1);
3571           cmSystemTools::ConvertToUnixSlashes(destination);
3572           cmInstallTargetGeneratorLocal g2(this, l->GetName(), destination,
3573                                            false);
3574           g2.Generate(os, config, configurationTypes);
3575 #else
3576           // Use a target install generator.
3577           cmInstallTargetGeneratorLocal g(this, l->GetName(), destination,
3578                                           false);
3579           g.Generate(os, config, configurationTypes);
3580 #endif
3581         } break;
3582         default:
3583           break;
3584       }
3585     }
3586
3587     // Include the user-specified post-install script for this target.
3588     if (cmValue postinstall = l->GetProperty("POST_INSTALL_SCRIPT")) {
3589       cmInstallScriptGenerator g(*postinstall, false, "", false, false);
3590       g.Generate(os, config, configurationTypes);
3591     }
3592   }
3593 }
3594
3595 #if defined(CM_LG_ENCODE_OBJECT_NAMES)
3596 static bool cmLocalGeneratorShortenObjectName(std::string& objName,
3597                                               std::string::size_type max_len)
3598 {
3599   // Check if the path can be shortened using an md5 sum replacement for
3600   // a portion of the path.
3601   std::string::size_type md5Len = 32;
3602   std::string::size_type numExtraChars = objName.size() - max_len + md5Len;
3603   std::string::size_type pos = objName.find('/', numExtraChars);
3604   if (pos == std::string::npos) {
3605     pos = objName.rfind('/', numExtraChars);
3606     if (pos == std::string::npos || pos <= md5Len) {
3607       return false;
3608     }
3609   }
3610
3611   // Replace the beginning of the path portion of the object name with
3612   // its own md5 sum.
3613   cmCryptoHash md5(cmCryptoHash::AlgoMD5);
3614   std::string md5name = cmStrCat(md5.HashString(objName.substr(0, pos)),
3615                                  cm::string_view(objName).substr(pos));
3616   objName = md5name;
3617
3618   // The object name is now shorter, check if it is short enough.
3619   return pos >= numExtraChars;
3620 }
3621
3622 bool cmLocalGeneratorCheckObjectName(std::string& objName,
3623                                      std::string::size_type dir_len,
3624                                      std::string::size_type max_total_len)
3625 {
3626   // Enforce the maximum file name length if possible.
3627   std::string::size_type max_obj_len = max_total_len;
3628   if (dir_len < max_total_len) {
3629     max_obj_len = max_total_len - dir_len;
3630     if (objName.size() > max_obj_len) {
3631       // The current object file name is too long.  Try to shorten it.
3632       return cmLocalGeneratorShortenObjectName(objName, max_obj_len);
3633     }
3634     // The object file name is short enough.
3635     return true;
3636   }
3637   // The build directory in which the object will be stored is
3638   // already too deep.
3639   return false;
3640 }
3641 #endif
3642
3643 std::string& cmLocalGenerator::CreateSafeUniqueObjectFileName(
3644   const std::string& sin, std::string const& dir_max)
3645 {
3646   // Look for an existing mapped name for this object file.
3647   auto it = this->UniqueObjectNamesMap.find(sin);
3648
3649   // If no entry exists create one.
3650   if (it == this->UniqueObjectNamesMap.end()) {
3651     // Start with the original name.
3652     std::string ssin = sin;
3653
3654     // Avoid full paths by removing leading slashes.
3655     ssin.erase(0, ssin.find_first_not_of('/'));
3656
3657     // Avoid full paths by removing colons.
3658     std::replace(ssin.begin(), ssin.end(), ':', '_');
3659
3660     // Avoid relative paths that go up the tree.
3661     cmSystemTools::ReplaceString(ssin, "../", "__/");
3662
3663     // Avoid spaces.
3664     std::replace(ssin.begin(), ssin.end(), ' ', '_');
3665
3666     // Mangle the name if necessary.
3667     if (this->Makefile->IsOn("CMAKE_MANGLE_OBJECT_FILE_NAMES")) {
3668       bool done;
3669       int cc = 0;
3670       char rpstr[100];
3671       snprintf(rpstr, sizeof(rpstr), "_p_");
3672       cmSystemTools::ReplaceString(ssin, "+", rpstr);
3673       std::string sssin = sin;
3674       do {
3675         done = true;
3676         for (it = this->UniqueObjectNamesMap.begin();
3677              it != this->UniqueObjectNamesMap.end(); ++it) {
3678           if (it->second == ssin) {
3679             done = false;
3680           }
3681         }
3682         if (done) {
3683           break;
3684         }
3685         sssin = ssin;
3686         cmSystemTools::ReplaceString(ssin, "_p_", rpstr);
3687         snprintf(rpstr, sizeof(rpstr), "_p%d_", cc++);
3688       } while (!done);
3689     }
3690
3691 #if defined(CM_LG_ENCODE_OBJECT_NAMES)
3692     if (!cmLocalGeneratorCheckObjectName(ssin, dir_max.size(),
3693                                          this->ObjectPathMax)) {
3694       // Warn if this is the first time the path has been seen.
3695       if (this->ObjectMaxPathViolations.insert(dir_max).second) {
3696         std::ostringstream m;
3697         /* clang-format off */
3698         m << "The object file directory\n"
3699           << "  " << dir_max << "\n"
3700           << "has " << dir_max.size() << " characters.  "
3701           << "The maximum full path to an object file is "
3702           << this->ObjectPathMax << " characters "
3703           << "(see CMAKE_OBJECT_PATH_MAX).  "
3704           << "Object file\n"
3705           << "  " << ssin << "\n"
3706           << "cannot be safely placed under this directory.  "
3707           << "The build may not work correctly.";
3708         /* clang-format on */
3709         this->IssueMessage(MessageType::WARNING, m.str());
3710       }
3711     }
3712 #else
3713     (void)dir_max;
3714 #endif
3715
3716     // Insert the newly mapped object file name.
3717     std::map<std::string, std::string>::value_type e(sin, ssin);
3718     it = this->UniqueObjectNamesMap.insert(e).first;
3719   }
3720
3721   // Return the map entry.
3722   return it->second;
3723 }
3724
3725 void cmLocalGenerator::ComputeObjectFilenames(
3726   std::map<cmSourceFile const*, std::string>& /*unused*/,
3727   cmGeneratorTarget const* /*unused*/)
3728 {
3729 }
3730
3731 bool cmLocalGenerator::IsWindowsShell() const
3732 {
3733   return this->GetState()->UseWindowsShell();
3734 }
3735
3736 bool cmLocalGenerator::IsWatcomWMake() const
3737 {
3738   return this->GetState()->UseWatcomWMake();
3739 }
3740
3741 bool cmLocalGenerator::IsMinGWMake() const
3742 {
3743   return this->GetState()->UseMinGWMake();
3744 }
3745
3746 bool cmLocalGenerator::IsNMake() const
3747 {
3748   return this->GetState()->UseNMake();
3749 }
3750
3751 bool cmLocalGenerator::IsNinjaMulti() const
3752 {
3753   return this->GetState()->UseNinjaMulti();
3754 }
3755
3756 namespace {
3757 std::string relativeIfUnder(std::string const& top, std::string const& cur,
3758                             std::string const& path)
3759 {
3760   // Use a path relative to 'cur' if it can be expressed without
3761   // a `../` sequence that leaves 'top'.
3762   if (cmSystemTools::IsSubDirectory(path, cur) ||
3763       (cmSystemTools::IsSubDirectory(cur, top) &&
3764        cmSystemTools::IsSubDirectory(path, top))) {
3765     return cmSystemTools::ForceToRelativePath(cur, path);
3766   }
3767   return path;
3768 }
3769 }
3770
3771 std::string cmLocalGenerator::GetObjectFileNameWithoutTarget(
3772   const cmSourceFile& source, std::string const& dir_max,
3773   bool* hasSourceExtension, char const* customOutputExtension)
3774 {
3775   // Construct the object file name using the full path to the source
3776   // file which is its only unique identification.
3777   std::string const& fullPath = source.GetFullPath();
3778
3779   // Try referencing the source relative to the source tree.
3780   std::string relFromSource = relativeIfUnder(
3781     this->GetSourceDirectory(), this->GetCurrentSourceDirectory(), fullPath);
3782   assert(!relFromSource.empty());
3783   bool relSource = !cmSystemTools::FileIsFullPath(relFromSource);
3784   bool subSource = relSource && relFromSource[0] != '.';
3785
3786   // Try referencing the source relative to the binary tree.
3787   std::string relFromBinary = relativeIfUnder(
3788     this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory(), fullPath);
3789   assert(!relFromBinary.empty());
3790   bool relBinary = !cmSystemTools::FileIsFullPath(relFromBinary);
3791   bool subBinary = relBinary && relFromBinary[0] != '.';
3792
3793   // Select a nice-looking reference to the source file to construct
3794   // the object file name.
3795   std::string objectName;
3796   // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
3797   // NOLINTNEXTLINE(bugprone-branch-clone)
3798   if ((relSource && !relBinary) || (subSource && !subBinary)) {
3799     objectName = relFromSource;
3800   } else if ((relBinary && !relSource) || (subBinary && !subSource) ||
3801              relFromBinary.length() < relFromSource.length()) {
3802     objectName = relFromBinary;
3803   } else {
3804     objectName = relFromSource;
3805   }
3806
3807   // if it is still a full path check for the try compile case
3808   // try compile never have in source sources, and should not
3809   // have conflicting source file names in the same target
3810   if (cmSystemTools::FileIsFullPath(objectName)) {
3811     if (this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
3812       objectName = cmSystemTools::GetFilenameName(source.GetFullPath());
3813     }
3814   }
3815
3816   // Ensure that for the CMakeFiles/<target>.dir/generated_source_file
3817   // we don't end up having:
3818   // CMakeFiles/<target>.dir/CMakeFiles/<target>.dir/generated_source_file.obj
3819   cmValue unitySourceFile = source.GetProperty("UNITY_SOURCE_FILE");
3820   cmValue pchExtension = source.GetProperty("PCH_EXTENSION");
3821   const bool isPchObject = objectName.find("cmake_pch") != std::string::npos;
3822   if (unitySourceFile || pchExtension || isPchObject) {
3823     if (pchExtension) {
3824       customOutputExtension = pchExtension->c_str();
3825     }
3826
3827     cmsys::RegularExpression var("(CMakeFiles/[^/]+.dir/)");
3828     if (var.find(objectName)) {
3829       objectName.erase(var.start(), var.end() - var.start());
3830     }
3831   }
3832
3833   // Replace the original source file extension with the object file
3834   // extension.
3835   bool keptSourceExtension = true;
3836   if (!source.GetPropertyAsBool("KEEP_EXTENSION")) {
3837     // Decide whether this language wants to replace the source
3838     // extension with the object extension.  For CMake 2.4
3839     // compatibility do this by default.
3840     bool replaceExt = this->NeedBackwardsCompatibility_2_4();
3841     if (!replaceExt) {
3842       std::string lang = source.GetLanguage();
3843       if (!lang.empty()) {
3844         replaceExt = this->Makefile->IsOn(
3845           cmStrCat("CMAKE_", lang, "_OUTPUT_EXTENSION_REPLACE"));
3846       }
3847     }
3848
3849     // Remove the source extension if it is to be replaced.
3850     if (replaceExt || customOutputExtension) {
3851       keptSourceExtension = false;
3852       std::string::size_type dot_pos = objectName.rfind('.');
3853       if (dot_pos != std::string::npos) {
3854         objectName = objectName.substr(0, dot_pos);
3855       }
3856     }
3857
3858     // Store the new extension.
3859     if (customOutputExtension) {
3860       objectName += customOutputExtension;
3861     } else {
3862       objectName += this->GlobalGenerator->GetLanguageOutputExtension(source);
3863     }
3864   }
3865   if (hasSourceExtension) {
3866     *hasSourceExtension = keptSourceExtension;
3867   }
3868
3869   // Convert to a safe name.
3870   return this->CreateSafeUniqueObjectFileName(objectName, dir_max);
3871 }
3872
3873 std::string cmLocalGenerator::GetSourceFileLanguage(const cmSourceFile& source)
3874 {
3875   return source.GetLanguage();
3876 }
3877
3878 cmake* cmLocalGenerator::GetCMakeInstance() const
3879 {
3880   return this->GlobalGenerator->GetCMakeInstance();
3881 }
3882
3883 std::string const& cmLocalGenerator::GetSourceDirectory() const
3884 {
3885   return this->GetCMakeInstance()->GetHomeDirectory();
3886 }
3887
3888 std::string const& cmLocalGenerator::GetBinaryDirectory() const
3889 {
3890   return this->GetCMakeInstance()->GetHomeOutputDirectory();
3891 }
3892
3893 std::string const& cmLocalGenerator::GetCurrentBinaryDirectory() const
3894 {
3895   return this->StateSnapshot.GetDirectory().GetCurrentBinary();
3896 }
3897
3898 std::string const& cmLocalGenerator::GetCurrentSourceDirectory() const
3899 {
3900   return this->StateSnapshot.GetDirectory().GetCurrentSource();
3901 }
3902
3903 std::string cmLocalGenerator::GetTargetDirectory(
3904   const cmGeneratorTarget* /*unused*/) const
3905 {
3906   cmSystemTools::Error("GetTargetDirectory"
3907                        " called on cmLocalGenerator");
3908   return "";
3909 }
3910
3911 KWIML_INT_uint64_t cmLocalGenerator::GetBackwardsCompatibility()
3912 {
3913   // The computed version may change until the project is fully
3914   // configured.
3915   if (!this->BackwardsCompatibilityFinal) {
3916     unsigned int major = 0;
3917     unsigned int minor = 0;
3918     unsigned int patch = 0;
3919     if (cmValue value =
3920           this->Makefile->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY")) {
3921       switch (sscanf(value->c_str(), "%u.%u.%u", &major, &minor, &patch)) {
3922         case 2:
3923           patch = 0;
3924           break;
3925         case 1:
3926           minor = 0;
3927           patch = 0;
3928           break;
3929         default:
3930           break;
3931       }
3932     }
3933     this->BackwardsCompatibility = CMake_VERSION_ENCODE(major, minor, patch);
3934     this->BackwardsCompatibilityFinal = true;
3935   }
3936
3937   return this->BackwardsCompatibility;
3938 }
3939
3940 bool cmLocalGenerator::NeedBackwardsCompatibility_2_4()
3941 {
3942   // Check the policy to decide whether to pay attention to this
3943   // variable.
3944   switch (this->GetPolicyStatus(cmPolicies::CMP0001)) {
3945     case cmPolicies::WARN:
3946       // WARN is just OLD without warning because user code does not
3947       // always affect whether this check is done.
3948       CM_FALLTHROUGH;
3949     case cmPolicies::OLD:
3950       // Old behavior is to check the variable.
3951       break;
3952     case cmPolicies::NEW:
3953       // New behavior is to ignore the variable.
3954     case cmPolicies::REQUIRED_IF_USED:
3955     case cmPolicies::REQUIRED_ALWAYS:
3956       // This will never be the case because the only way to require
3957       // the setting is to require the user to specify version policy
3958       // 2.6 or higher.  Once we add that requirement then this whole
3959       // method can be removed anyway.
3960       return false;
3961   }
3962
3963   // Compatibility is needed if CMAKE_BACKWARDS_COMPATIBILITY is set
3964   // equal to or lower than the given version.
3965   KWIML_INT_uint64_t actual_compat = this->GetBackwardsCompatibility();
3966   return (actual_compat && actual_compat <= CMake_VERSION_ENCODE(2, 4, 255));
3967 }
3968
3969 cmPolicies::PolicyStatus cmLocalGenerator::GetPolicyStatus(
3970   cmPolicies::PolicyID id) const
3971 {
3972   return this->Makefile->GetPolicyStatus(id);
3973 }
3974
3975 bool cmLocalGenerator::CheckDefinition(std::string const& define) const
3976 {
3977   // Many compilers do not support -DNAME(arg)=sdf so we disable it.
3978   std::string::size_type pos = define.find_first_of("(=");
3979   if (pos != std::string::npos) {
3980     if (define[pos] == '(') {
3981       std::ostringstream e;
3982       /* clang-format off */
3983       e << "WARNING: Function-style preprocessor definitions may not be "
3984         << "passed on the compiler command line because many compilers "
3985         << "do not support it.\n"
3986         << "CMake is dropping a preprocessor definition: " << define << "\n"
3987         << "Consider defining the macro in a (configured) header file.\n";
3988       /* clang-format on */
3989       cmSystemTools::Message(e.str());
3990       return false;
3991     }
3992   }
3993
3994   // Many compilers do not support # in the value so we disable it.
3995   if (define.find_first_of('#') != std::string::npos) {
3996     std::ostringstream e;
3997     /* clang-format off */
3998     e << "WARNING: Preprocessor definitions containing '#' may not be "
3999       << "passed on the compiler command line because many compilers "
4000       << "do not support it.\n"
4001       << "CMake is dropping a preprocessor definition: " << define << "\n"
4002       << "Consider defining the macro in a (configured) header file.\n";
4003     /* clang-format on */
4004     cmSystemTools::Message(e.str());
4005     return false;
4006   }
4007
4008   // Assume it is supported.
4009   return true;
4010 }
4011
4012 static void cmLGInfoProp(cmMakefile* mf, cmGeneratorTarget* target,
4013                          const std::string& prop)
4014 {
4015   if (cmValue val = target->GetProperty(prop)) {
4016     mf->AddDefinition(prop, *val);
4017   }
4018 }
4019
4020 void cmLocalGenerator::GenerateAppleInfoPList(cmGeneratorTarget* target,
4021                                               const std::string& targetName,
4022                                               const std::string& fname)
4023 {
4024   // Find the Info.plist template.
4025   cmValue in = target->GetProperty("MACOSX_BUNDLE_INFO_PLIST");
4026   std::string inFile = cmNonempty(in) ? *in : "MacOSXBundleInfo.plist.in";
4027   if (!cmSystemTools::FileIsFullPath(inFile)) {
4028     std::string inMod = this->Makefile->GetModulesFile(inFile);
4029     if (!inMod.empty()) {
4030       inFile = inMod;
4031     }
4032   }
4033   if (!cmSystemTools::FileExists(inFile, true)) {
4034     std::ostringstream e;
4035     e << "Target " << target->GetName() << " Info.plist template \"" << inFile
4036       << "\" could not be found.";
4037     cmSystemTools::Error(e.str());
4038     return;
4039   }
4040
4041   // Convert target properties to variables in an isolated makefile
4042   // scope to configure the file.  If properties are set they will
4043   // override user make variables.  If not the configuration will fall
4044   // back to the directory-level values set by the user.
4045   cmMakefile* mf = this->Makefile;
4046   cmMakefile::ScopePushPop varScope(mf);
4047   mf->AddDefinition("MACOSX_BUNDLE_EXECUTABLE_NAME", targetName);
4048   cmLGInfoProp(mf, target, "MACOSX_BUNDLE_INFO_STRING");
4049   cmLGInfoProp(mf, target, "MACOSX_BUNDLE_ICON_FILE");
4050   cmLGInfoProp(mf, target, "MACOSX_BUNDLE_GUI_IDENTIFIER");
4051   cmLGInfoProp(mf, target, "MACOSX_BUNDLE_LONG_VERSION_STRING");
4052   cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_NAME");
4053   cmLGInfoProp(mf, target, "MACOSX_BUNDLE_SHORT_VERSION_STRING");
4054   cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_VERSION");
4055   cmLGInfoProp(mf, target, "MACOSX_BUNDLE_COPYRIGHT");
4056   mf->ConfigureFile(inFile, fname, false, false, false);
4057 }
4058
4059 void cmLocalGenerator::GenerateFrameworkInfoPList(
4060   cmGeneratorTarget* target, const std::string& targetName,
4061   const std::string& fname)
4062 {
4063   // Find the Info.plist template.
4064   cmValue in = target->GetProperty("MACOSX_FRAMEWORK_INFO_PLIST");
4065   std::string inFile = cmNonempty(in) ? *in : "MacOSXFrameworkInfo.plist.in";
4066   if (!cmSystemTools::FileIsFullPath(inFile)) {
4067     std::string inMod = this->Makefile->GetModulesFile(inFile);
4068     if (!inMod.empty()) {
4069       inFile = inMod;
4070     }
4071   }
4072   if (!cmSystemTools::FileExists(inFile, true)) {
4073     std::ostringstream e;
4074     e << "Target " << target->GetName() << " Info.plist template \"" << inFile
4075       << "\" could not be found.";
4076     cmSystemTools::Error(e.str());
4077     return;
4078   }
4079
4080   // Convert target properties to variables in an isolated makefile
4081   // scope to configure the file.  If properties are set they will
4082   // override user make variables.  If not the configuration will fall
4083   // back to the directory-level values set by the user.
4084   cmMakefile* mf = this->Makefile;
4085   cmMakefile::ScopePushPop varScope(mf);
4086   mf->AddDefinition("MACOSX_FRAMEWORK_NAME", targetName);
4087   cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_ICON_FILE");
4088   cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_IDENTIFIER");
4089   cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_SHORT_VERSION_STRING");
4090   cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_BUNDLE_VERSION");
4091   mf->ConfigureFile(inFile, fname, false, false, false);
4092 }
4093
4094 namespace {
4095 cm::string_view CustomOutputRoleKeyword(cmLocalGenerator::OutputRole role)
4096 {
4097   return (role == cmLocalGenerator::OutputRole::Primary ? "OUTPUT"_s
4098                                                         : "BYPRODUCTS"_s);
4099 }
4100
4101 void CreateGeneratedSource(cmLocalGenerator& lg, const std::string& output,
4102                            cmLocalGenerator::OutputRole role,
4103                            cmCommandOrigin origin,
4104                            const cmListFileBacktrace& lfbt)
4105 {
4106   if (cmGeneratorExpression::Find(output) != std::string::npos) {
4107     lg.GetCMakeInstance()->IssueMessage(
4108       MessageType::FATAL_ERROR,
4109       "Generator expressions in custom command outputs are not implemented!",
4110       lfbt);
4111     return;
4112   }
4113
4114   // Make sure the file will not be generated into the source
4115   // directory during an out of source build.
4116   if (!lg.GetMakefile()->CanIWriteThisFile(output)) {
4117     lg.GetCMakeInstance()->IssueMessage(
4118       MessageType::FATAL_ERROR,
4119       cmStrCat(CustomOutputRoleKeyword(role), " path\n  ", output,
4120                "\nin a source directory as an output of custom command."),
4121       lfbt);
4122     return;
4123   }
4124
4125   // Make sure the output file name has no invalid characters.
4126   std::string::size_type pos = output.find_first_of("#<>");
4127   if (pos != std::string::npos) {
4128     lg.GetCMakeInstance()->IssueMessage(
4129       MessageType::FATAL_ERROR,
4130       cmStrCat(CustomOutputRoleKeyword(role), " containing a \"", output[pos],
4131                "\" is not allowed."),
4132       lfbt);
4133     return;
4134   }
4135
4136   // Outputs without generator expressions from the project are already
4137   // created and marked as generated.  Do not mark them again, because
4138   // other commands might have overwritten the property.
4139   if (origin == cmCommandOrigin::Generator) {
4140     lg.GetMakefile()->GetOrCreateGeneratedSource(output);
4141   }
4142 }
4143
4144 std::string ComputeCustomCommandRuleFileName(cmLocalGenerator& lg,
4145                                              cmListFileBacktrace const& bt,
4146                                              std::string const& output)
4147 {
4148   // If the output path has no generator expressions, use it directly.
4149   if (cmGeneratorExpression::Find(output) == std::string::npos) {
4150     return output;
4151   }
4152
4153   // The output path contains a generator expression, but we must choose
4154   // a single source file path to which to attach the custom command.
4155   // Use some heuristics to provide a nice-looking name when possible.
4156
4157   // If the only genex is $<CONFIG>, replace that gracefully.
4158   {
4159     std::string simple = output;
4160     cmSystemTools::ReplaceString(simple, "$<CONFIG>", "(CONFIG)");
4161     if (cmGeneratorExpression::Find(simple) == std::string::npos) {
4162       return simple;
4163     }
4164   }
4165
4166   // If the genex evaluates to the same value in all configurations, use that.
4167   {
4168     std::vector<std::string> allConfigOutputs =
4169       lg.ExpandCustomCommandOutputGenex(output, bt);
4170     if (allConfigOutputs.size() == 1) {
4171       return allConfigOutputs.front();
4172     }
4173   }
4174
4175   // Fall back to a deterministic unique name.
4176   cmCryptoHash h(cmCryptoHash::AlgoSHA256);
4177   return cmStrCat(lg.GetCurrentBinaryDirectory(), "/CMakeFiles/",
4178                   h.HashString(output).substr(0, 16));
4179 }
4180
4181 cmSourceFile* AddCustomCommand(cmLocalGenerator& lg, cmCommandOrigin origin,
4182                                std::unique_ptr<cmCustomCommand> cc,
4183                                bool replace)
4184 {
4185   cmMakefile* mf = lg.GetMakefile();
4186   const auto& lfbt = cc->GetBacktrace();
4187   const auto& outputs = cc->GetOutputs();
4188   const auto& byproducts = cc->GetByproducts();
4189   const auto& commandLines = cc->GetCommandLines();
4190
4191   // Choose a source file on which to store the custom command.
4192   cmSourceFile* file = nullptr;
4193   if (!commandLines.empty() && cc->HasMainDependency()) {
4194     const auto& main_dependency = cc->GetMainDependency();
4195     // The main dependency was specified.  Use it unless a different
4196     // custom command already used it.
4197     file = mf->GetSource(main_dependency);
4198     if (file && file->GetCustomCommand() && !replace) {
4199       // The main dependency already has a custom command.
4200       if (commandLines == file->GetCustomCommand()->GetCommandLines()) {
4201         // The existing custom command is identical.  Silently ignore
4202         // the duplicate.
4203         return file;
4204       }
4205       // The existing custom command is different.  We need to
4206       // generate a rule file for this new command.
4207       file = nullptr;
4208     } else if (!file) {
4209       file = mf->CreateSource(main_dependency);
4210     }
4211   }
4212
4213   // Generate a rule file if the main dependency is not available.
4214   if (!file) {
4215     cmGlobalGenerator* gg = lg.GetGlobalGenerator();
4216
4217     // Construct a rule file associated with the first output produced.
4218     std::string outName = gg->GenerateRuleFile(
4219       ComputeCustomCommandRuleFileName(lg, lfbt, outputs[0]));
4220
4221     // Check if the rule file already exists.
4222     file = mf->GetSource(outName, cmSourceFileLocationKind::Known);
4223     if (file && file->GetCustomCommand() && !replace) {
4224       // The rule file already exists.
4225       if (commandLines != file->GetCustomCommand()->GetCommandLines()) {
4226         lg.GetCMakeInstance()->IssueMessage(
4227           MessageType::FATAL_ERROR,
4228           cmStrCat("Attempt to add a custom rule to output\n  ", outName,
4229                    "\nwhich already has a custom rule."),
4230           lfbt);
4231       }
4232       return file;
4233     }
4234
4235     // Create a cmSourceFile for the rule file.
4236     if (!file) {
4237       file = mf->CreateSource(outName, true, cmSourceFileLocationKind::Known);
4238     }
4239     file->SetProperty("__CMAKE_RULE", "1");
4240   }
4241
4242   // Attach the custom command to the file.
4243   if (file) {
4244     cc->SetEscapeAllowMakeVars(true);
4245
4246     lg.AddSourceOutputs(file, outputs, cmLocalGenerator::OutputRole::Primary,
4247                         lfbt, origin);
4248     lg.AddSourceOutputs(file, byproducts,
4249                         cmLocalGenerator::OutputRole::Byproduct, lfbt, origin);
4250
4251     file->SetCustomCommand(std::move(cc));
4252   }
4253   return file;
4254 }
4255
4256 bool AnyOutputMatches(const std::string& name,
4257                       const std::vector<std::string>& outputs)
4258 {
4259   return std::any_of(outputs.begin(), outputs.end(),
4260                      [&name](std::string const& output) -> bool {
4261                        std::string::size_type pos = output.rfind(name);
4262                        // If the output matches exactly
4263                        return (pos != std::string::npos &&
4264                                pos == output.size() - name.size() &&
4265                                (pos == 0 || output[pos - 1] == '/'));
4266                      });
4267 }
4268
4269 bool AnyTargetCommandOutputMatches(
4270   const std::string& name, const std::vector<cmCustomCommand>& commands)
4271 {
4272   return std::any_of(commands.begin(), commands.end(),
4273                      [&name](cmCustomCommand const& command) -> bool {
4274                        return AnyOutputMatches(name, command.GetByproducts());
4275                      });
4276 }
4277 }
4278
4279 namespace detail {
4280 void AddCustomCommandToTarget(cmLocalGenerator& lg, cmCommandOrigin origin,
4281                               cmTarget* target, cmCustomCommandType type,
4282                               std::unique_ptr<cmCustomCommand> cc)
4283 {
4284   // Add the command to the appropriate build step for the target.
4285   cc->SetEscapeAllowMakeVars(true);
4286   cc->SetTarget(target->GetName());
4287
4288   lg.AddTargetByproducts(target, cc->GetByproducts(), cc->GetBacktrace(),
4289                          origin);
4290
4291   switch (type) {
4292     case cmCustomCommandType::PRE_BUILD:
4293       target->AddPreBuildCommand(std::move(*cc));
4294       break;
4295     case cmCustomCommandType::PRE_LINK:
4296       target->AddPreLinkCommand(std::move(*cc));
4297       break;
4298     case cmCustomCommandType::POST_BUILD:
4299       target->AddPostBuildCommand(std::move(*cc));
4300       break;
4301   }
4302
4303   cc.reset();
4304 }
4305
4306 cmSourceFile* AddCustomCommandToOutput(cmLocalGenerator& lg,
4307                                        cmCommandOrigin origin,
4308                                        std::unique_ptr<cmCustomCommand> cc,
4309                                        bool replace)
4310 {
4311   return AddCustomCommand(lg, origin, std::move(cc), replace);
4312 }
4313
4314 void AppendCustomCommandToOutput(cmLocalGenerator& lg,
4315                                  const cmListFileBacktrace& lfbt,
4316                                  const std::string& output,
4317                                  const std::vector<std::string>& depends,
4318                                  const cmImplicitDependsList& implicit_depends,
4319                                  const cmCustomCommandLines& commandLines)
4320 {
4321   // Lookup an existing command.
4322   cmSourceFile* sf = nullptr;
4323   if (cmGeneratorExpression::Find(output) == std::string::npos) {
4324     sf = lg.GetSourceFileWithOutput(output);
4325   } else {
4326     // This output path has a generator expression.  Evaluate it to
4327     // find the output for any configurations.
4328     for (std::string const& out :
4329          lg.ExpandCustomCommandOutputGenex(output, lfbt)) {
4330       sf = lg.GetSourceFileWithOutput(out);
4331       if (sf) {
4332         break;
4333       }
4334     }
4335   }
4336
4337   if (sf) {
4338     if (cmCustomCommand* cc = sf->GetCustomCommand()) {
4339       cc->AppendCommands(commandLines);
4340       cc->AppendDepends(depends);
4341       cc->AppendImplicitDepends(implicit_depends);
4342       return;
4343     }
4344   }
4345
4346   // No existing command found.
4347   lg.GetCMakeInstance()->IssueMessage(
4348     MessageType::FATAL_ERROR,
4349     cmStrCat("Attempt to APPEND to custom command with output\n  ", output,
4350              "\nwhich is not already a custom command output."),
4351     lfbt);
4352 }
4353
4354 void AddUtilityCommand(cmLocalGenerator& lg, cmCommandOrigin origin,
4355                        cmTarget* target, std::unique_ptr<cmCustomCommand> cc)
4356 {
4357   // They might be moved away
4358   auto byproducts = cc->GetByproducts();
4359   auto lfbt = cc->GetBacktrace();
4360
4361   // Use an empty comment to avoid generation of default comment.
4362   if (!cc->GetComment()) {
4363     cc->SetComment("");
4364   }
4365
4366   // Create the generated symbolic output name of the utility target.
4367   std::string output =
4368     lg.CreateUtilityOutput(target->GetName(), byproducts, lfbt);
4369   cc->SetOutputs(output);
4370
4371   cmSourceFile* rule = AddCustomCommand(lg, origin, std::move(cc),
4372                                         /*replace=*/false);
4373   if (rule) {
4374     lg.AddTargetByproducts(target, byproducts, lfbt, origin);
4375   }
4376
4377   target->AddSource(output);
4378 }
4379
4380 std::vector<std::string> ComputeISPCObjectSuffixes(cmGeneratorTarget* target)
4381 {
4382   const std::string& targetProperty =
4383     target->GetSafeProperty("ISPC_INSTRUCTION_SETS");
4384   std::vector<std::string> ispcTargets;
4385
4386   if (!cmIsOff(targetProperty)) {
4387     cmExpandList(targetProperty, ispcTargets);
4388     for (auto& ispcTarget : ispcTargets) {
4389       // transform targets into the suffixes
4390       auto pos = ispcTarget.find('-');
4391       auto target_suffix = ispcTarget.substr(0, pos);
4392       if (target_suffix ==
4393           "avx1") { // when targeting avx1 ISPC uses the 'avx' output string
4394         target_suffix = "avx";
4395       }
4396       ispcTarget = target_suffix;
4397     }
4398   }
4399   return ispcTargets;
4400 }
4401
4402 std::vector<std::string> ComputeISPCExtraObjects(
4403   std::string const& objectName, std::string const& buildDirectory,
4404   std::vector<std::string> const& ispcSuffixes)
4405 {
4406   auto normalizedDir = cmSystemTools::CollapseFullPath(buildDirectory);
4407   std::vector<std::string> computedObjects;
4408   computedObjects.reserve(ispcSuffixes.size());
4409
4410   auto extension = cmSystemTools::GetFilenameLastExtension(objectName);
4411
4412   // We can't use cmSystemTools::GetFilenameWithoutLastExtension as it
4413   // drops any directories in objectName
4414   auto objNameNoExt = objectName;
4415   std::string::size_type dot_pos = objectName.rfind('.');
4416   if (dot_pos != std::string::npos) {
4417     objNameNoExt.resize(dot_pos);
4418   }
4419
4420   for (const auto& ispcTarget : ispcSuffixes) {
4421     computedObjects.emplace_back(
4422       cmStrCat(normalizedDir, "/", objNameNoExt, "_", ispcTarget, extension));
4423   }
4424
4425   return computedObjects;
4426 }
4427 }
4428
4429 cmSourcesWithOutput cmLocalGenerator::GetSourcesWithOutput(
4430   const std::string& name) const
4431 {
4432   // Linear search?  Also see GetSourceFileWithOutput for detail.
4433   if (!cmSystemTools::FileIsFullPath(name)) {
4434     cmSourcesWithOutput sources;
4435     sources.Target = this->LinearGetTargetWithOutput(name);
4436     sources.Source = this->LinearGetSourceFileWithOutput(
4437       name, cmSourceOutputKind::OutputOrByproduct, sources.SourceIsByproduct);
4438     return sources;
4439   }
4440   // Otherwise we use an efficient lookup map.
4441   auto o = this->OutputToSource.find(name);
4442   if (o != this->OutputToSource.end()) {
4443     return o->second.Sources;
4444   }
4445   return {};
4446 }
4447
4448 cmSourceFile* cmLocalGenerator::GetSourceFileWithOutput(
4449   const std::string& name, cmSourceOutputKind kind) const
4450 {
4451   // If the queried path is not absolute we use the backward compatible
4452   // linear-time search for an output with a matching suffix.
4453   if (!cmSystemTools::FileIsFullPath(name)) {
4454     bool byproduct = false;
4455     return this->LinearGetSourceFileWithOutput(name, kind, byproduct);
4456   }
4457   // Otherwise we use an efficient lookup map.
4458   auto o = this->OutputToSource.find(name);
4459   if (o != this->OutputToSource.end() &&
4460       (!o->second.Sources.SourceIsByproduct ||
4461        kind == cmSourceOutputKind::OutputOrByproduct)) {
4462     // Source file could also be null pointer for example if we found the
4463     // byproduct of a utility target, a PRE_BUILD, PRE_LINK, or POST_BUILD
4464     // command of a target, or a not yet created custom command.
4465     return o->second.Sources.Source;
4466   }
4467   return nullptr;
4468 }
4469
4470 std::string cmLocalGenerator::CreateUtilityOutput(
4471   std::string const& targetName, std::vector<std::string> const&,
4472   cmListFileBacktrace const&)
4473 {
4474   std::string force =
4475     cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/", targetName);
4476   // The output is not actually created so mark it symbolic.
4477   if (cmSourceFile* sf = this->Makefile->GetOrCreateGeneratedSource(force)) {
4478     sf->SetProperty("SYMBOLIC", "1");
4479   } else {
4480     cmSystemTools::Error("Could not get source file entry for " + force);
4481   }
4482   return force;
4483 }
4484
4485 std::vector<cmCustomCommandGenerator>
4486 cmLocalGenerator::MakeCustomCommandGenerators(cmCustomCommand const& cc,
4487                                               std::string const& config)
4488 {
4489   std::vector<cmCustomCommandGenerator> ccgs;
4490   ccgs.emplace_back(cc, config, this);
4491   return ccgs;
4492 }
4493
4494 std::vector<std::string> cmLocalGenerator::ExpandCustomCommandOutputPaths(
4495   cmCompiledGeneratorExpression const& cge, std::string const& config)
4496 {
4497   std::vector<std::string> paths = cmExpandedList(cge.Evaluate(this, config));
4498   for (std::string& p : paths) {
4499     p = cmSystemTools::CollapseFullPath(p, this->GetCurrentBinaryDirectory());
4500   }
4501   return paths;
4502 }
4503
4504 std::vector<std::string> cmLocalGenerator::ExpandCustomCommandOutputGenex(
4505   std::string const& o, cmListFileBacktrace const& bt)
4506 {
4507   std::vector<std::string> allConfigOutputs;
4508   cmGeneratorExpression ge(bt);
4509   std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(o);
4510   std::vector<std::string> configs =
4511     this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
4512   for (std::string const& config : configs) {
4513     std::vector<std::string> configOutputs =
4514       this->ExpandCustomCommandOutputPaths(*cge, config);
4515     allConfigOutputs.reserve(allConfigOutputs.size() + configOutputs.size());
4516     std::move(configOutputs.begin(), configOutputs.end(),
4517               std::back_inserter(allConfigOutputs));
4518   }
4519   auto endUnique =
4520     cmRemoveDuplicates(allConfigOutputs.begin(), allConfigOutputs.end());
4521   allConfigOutputs.erase(endUnique, allConfigOutputs.end());
4522   return allConfigOutputs;
4523 }
4524
4525 void cmLocalGenerator::AddTargetByproducts(
4526   cmTarget* target, const std::vector<std::string>& byproducts,
4527   cmListFileBacktrace const& bt, cmCommandOrigin origin)
4528 {
4529   for (std::string const& o : byproducts) {
4530     if (cmGeneratorExpression::Find(o) == std::string::npos) {
4531       this->UpdateOutputToSourceMap(o, target, bt, origin);
4532       continue;
4533     }
4534
4535     // This byproduct path has a generator expression.  Evaluate it to
4536     // register the byproducts for all configurations.
4537     for (std::string const& b : this->ExpandCustomCommandOutputGenex(o, bt)) {
4538       this->UpdateOutputToSourceMap(b, target, bt, cmCommandOrigin::Generator);
4539     }
4540   }
4541 }
4542
4543 void cmLocalGenerator::AddSourceOutputs(
4544   cmSourceFile* source, const std::vector<std::string>& outputs,
4545   OutputRole role, cmListFileBacktrace const& bt, cmCommandOrigin origin)
4546 {
4547   for (std::string const& o : outputs) {
4548     if (cmGeneratorExpression::Find(o) == std::string::npos) {
4549       this->UpdateOutputToSourceMap(o, source, role, bt, origin);
4550       continue;
4551     }
4552
4553     // This output path has a generator expression.  Evaluate it to
4554     // register the outputs for all configurations.
4555     for (std::string const& out :
4556          this->ExpandCustomCommandOutputGenex(o, bt)) {
4557       this->UpdateOutputToSourceMap(out, source, role, bt,
4558                                     cmCommandOrigin::Generator);
4559     }
4560   }
4561 }
4562
4563 void cmLocalGenerator::UpdateOutputToSourceMap(std::string const& byproduct,
4564                                                cmTarget* target,
4565                                                cmListFileBacktrace const& bt,
4566                                                cmCommandOrigin origin)
4567 {
4568   SourceEntry entry;
4569   entry.Sources.Target = target;
4570
4571   auto pr = this->OutputToSource.emplace(byproduct, entry);
4572   if (pr.second) {
4573     CreateGeneratedSource(*this, byproduct, OutputRole::Byproduct, origin, bt);
4574   } else {
4575     SourceEntry& current = pr.first->second;
4576     // Has the target already been set?
4577     if (!current.Sources.Target) {
4578       current.Sources.Target = target;
4579     } else {
4580       // Multiple custom commands/targets produce the same output (source file
4581       // or target).  See also comment in other UpdateOutputToSourceMap
4582       // overload.
4583       //
4584       // TODO: Warn the user about this case.
4585     }
4586   }
4587 }
4588
4589 void cmLocalGenerator::UpdateOutputToSourceMap(std::string const& output,
4590                                                cmSourceFile* source,
4591                                                OutputRole role,
4592                                                cmListFileBacktrace const& bt,
4593                                                cmCommandOrigin origin)
4594 {
4595   SourceEntry entry;
4596   entry.Sources.Source = source;
4597   entry.Sources.SourceIsByproduct = role == OutputRole::Byproduct;
4598
4599   auto pr = this->OutputToSource.emplace(output, entry);
4600   if (pr.second) {
4601     CreateGeneratedSource(*this, output, role, origin, bt);
4602   } else {
4603     SourceEntry& current = pr.first->second;
4604     // Outputs take precedence over byproducts
4605     if (!current.Sources.Source ||
4606         (current.Sources.SourceIsByproduct && role == OutputRole::Primary)) {
4607       current.Sources.Source = source;
4608       current.Sources.SourceIsByproduct = false;
4609     } else {
4610       // Multiple custom commands produce the same output but may
4611       // be attached to a different source file (MAIN_DEPENDENCY).
4612       // LinearGetSourceFileWithOutput would return the first one,
4613       // so keep the mapping for the first one.
4614       //
4615       // TODO: Warn the user about this case.  However, the VS 8 generator
4616       // triggers it for separate generate.stamp rules in ZERO_CHECK and
4617       // individual targets.
4618     }
4619   }
4620 }
4621
4622 cmTarget* cmLocalGenerator::LinearGetTargetWithOutput(
4623   const std::string& name) const
4624 {
4625   // We go through the ordered vector of targets to get reproducible results
4626   // should multiple names match.
4627   for (cmTarget* t : this->Makefile->GetOrderedTargets()) {
4628     // Does the output of any command match the source file name?
4629     if (AnyTargetCommandOutputMatches(name, t->GetPreBuildCommands())) {
4630       return t;
4631     }
4632     if (AnyTargetCommandOutputMatches(name, t->GetPreLinkCommands())) {
4633       return t;
4634     }
4635     if (AnyTargetCommandOutputMatches(name, t->GetPostBuildCommands())) {
4636       return t;
4637     }
4638   }
4639   return nullptr;
4640 }
4641
4642 cmSourceFile* cmLocalGenerator::LinearGetSourceFileWithOutput(
4643   const std::string& name, cmSourceOutputKind kind, bool& byproduct) const
4644 {
4645   // Outputs take precedence over byproducts.
4646   byproduct = false;
4647   cmSourceFile* fallback = nullptr;
4648
4649   // Look through all the source files that have custom commands and see if the
4650   // custom command has the passed source file as an output.
4651   for (const auto& src : this->Makefile->GetSourceFiles()) {
4652     // Does this source file have a custom command?
4653     if (src->GetCustomCommand()) {
4654       // Does the output of the custom command match the source file name?
4655       if (AnyOutputMatches(name, src->GetCustomCommand()->GetOutputs())) {
4656         // Return the first matching output.
4657         return src.get();
4658       }
4659       if (kind == cmSourceOutputKind::OutputOrByproduct) {
4660         if (AnyOutputMatches(name, src->GetCustomCommand()->GetByproducts())) {
4661           // Do not return the source yet as there might be a matching output.
4662           fallback = src.get();
4663         }
4664       }
4665     }
4666   }
4667
4668   // Did we find a byproduct?
4669   byproduct = fallback != nullptr;
4670   return fallback;
4671 }