Coverage Report

Created: 2026-09-14 06:43

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/CMake/Source/cmGeneratorTarget.cxx
Line
Count
Source
1
/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
2
   file LICENSE.rst or https://cmake.org/licensing for details.  */
3
#include "cmGeneratorTarget.h"
4
5
#include <algorithm>
6
#include <array>
7
#include <cassert>
8
#include <cstddef>
9
#include <cstdio>
10
#include <cstring>
11
#include <sstream>
12
#include <string>
13
#include <unordered_set>
14
#include <utility>
15
16
#include <cm/memory>
17
#include <cm/optional>
18
#include <cm/string_view>
19
#include <cmext/algorithm>
20
#include <cmext/string_view>
21
22
#include "cmsys/String.h"
23
24
#include "cmAlgorithms.h"
25
#include "cmComputeLinkInformation.h" // IWYU pragma: keep
26
#include "cmCryptoHash.h"
27
#include "cmCxxModuleMetadata.h"
28
#include "cmCxxModuleUsageEffects.h"
29
#include "cmExperimental.h"
30
#include "cmFileSet.h"
31
#include "cmFileSetMetadata.h"
32
#include "cmFileTimes.h"
33
#include "cmGenExContext.h"
34
#include "cmGeneratedFileStream.h"
35
#include "cmGeneratorExpression.h"
36
#include "cmGeneratorExpressionDAGChecker.h"
37
#include "cmGeneratorFileSet.h"
38
#include "cmGeneratorFileSets.h"
39
#include "cmGeneratorOptions.h"
40
#include "cmGlobalGenerator.h"
41
#include "cmList.h"
42
#include "cmLocalGenerator.h"
43
#include "cmMakefile.h"
44
#include "cmMessageType.h"
45
#include "cmOutputConverter.h"
46
#include "cmPropertyMap.h"
47
#include "cmRulePlaceholderExpander.h"
48
#include "cmSourceFile.h"
49
#include "cmSourceFileLocationKind.h"
50
#include "cmStandardLevel.h"
51
#include "cmStandardLevelResolver.h"
52
#include "cmState.h"
53
#include "cmStateTypes.h"
54
#include "cmStringAlgorithms.h"
55
#include "cmSystemTools.h"
56
#include "cmTarget.h"
57
#include "cmTargetLinkLibraryType.h"
58
#include "cmTargetPropertyComputer.h"
59
#include "cmTargetTraceDependencies.h"
60
#include "cmake.h"
61
62
namespace {
63
using UseTo = cmGeneratorTarget::UseTo;
64
}
65
66
template <>
67
cmValue cmTargetPropertyComputer::GetSources<cmGeneratorTarget>(
68
  cmGeneratorTarget const* tgt)
69
0
{
70
0
  return tgt->GetSourcesProperty();
71
0
}
72
73
template <>
74
std::string const&
75
cmTargetPropertyComputer::ImportedLocation<cmGeneratorTarget>(
76
  cmGeneratorTarget const* tgt, std::string const& config)
77
0
{
78
0
  return tgt->GetLocation(config);
79
0
}
80
81
static void CreatePropertyGeneratorExpressions(
82
  cmake& cmakeInstance, cmBTStringRange entries,
83
  std::vector<std::unique_ptr<cm::TargetPropertyEntry>>& items,
84
  bool evaluateForBuildsystem = false)
85
0
{
86
0
  for (auto const& entry : entries) {
87
0
    items.emplace_back(cm::TargetPropertyEntry::Create(
88
0
      cmakeInstance, entry, evaluateForBuildsystem));
89
0
  }
90
0
}
91
92
cmGeneratorTarget::cmGeneratorTarget(cmTarget* t, cmLocalGenerator* lg)
93
0
  : Target(t)
94
0
  , Makefile(t->GetMakefile())
95
0
  , LocalGenerator(lg)
96
0
  , GlobalGenerator(lg->GetGlobalGenerator())
97
0
  , FileSets(cm::make_unique<cmGeneratorFileSets>(this, lg))
98
0
{
99
0
  this->GlobalGenerator->ComputeTargetObjectDirectory(this);
100
101
0
  CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
102
0
                                     t->GetIncludeDirectoriesEntries(),
103
0
                                     this->IncludeDirectoriesEntries);
104
105
0
  CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
106
0
                                     t->GetCompileOptionsEntries(),
107
0
                                     this->CompileOptionsEntries);
108
109
0
  CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
110
0
                                     t->GetCompileFeaturesEntries(),
111
0
                                     this->CompileFeaturesEntries);
112
113
0
  CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
114
0
                                     t->GetCompileDefinitionsEntries(),
115
0
                                     this->CompileDefinitionsEntries);
116
117
0
  CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
118
0
                                     t->GetLinkOptionsEntries(),
119
0
                                     this->LinkOptionsEntries);
120
121
0
  CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
122
0
                                     t->GetLinkDirectoriesEntries(),
123
0
                                     this->LinkDirectoriesEntries);
124
125
0
  CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
126
0
                                     t->GetPrecompileHeadersEntries(),
127
0
                                     this->PrecompileHeadersEntries);
128
129
0
  CreatePropertyGeneratorExpressions(
130
0
    *lg->GetCMakeInstance(), t->GetSourceEntries(), this->SourceEntries, true);
131
132
0
  this->PolicyMap = t->GetPolicyMap();
133
134
  // Get hard-coded linker language
135
0
  if (this->Target->GetProperty("HAS_CXX")) {
136
0
    this->LinkerLanguage = "CXX";
137
0
  } else {
138
0
    this->LinkerLanguage = this->Target->GetSafeProperty("LINKER_LANGUAGE");
139
0
  }
140
141
0
  auto configs =
142
0
    this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
143
0
  std::string build_db_languages[] = { "CXX" };
144
0
  for (auto const& language : build_db_languages) {
145
0
    for (auto const& config : configs) {
146
0
      auto bdb_path = this->BuildDatabasePath(language, config);
147
0
      if (!bdb_path.empty()) {
148
0
        this->Makefile->GetOrCreateGeneratedSource(bdb_path);
149
0
        this->GetGlobalGenerator()->AddBuildDatabaseFile(language, config,
150
0
                                                         bdb_path);
151
0
      }
152
0
    }
153
0
  }
154
0
}
155
156
0
cmGeneratorTarget::~cmGeneratorTarget() = default;
157
158
cmValue cmGeneratorTarget::GetSourcesProperty() const
159
0
{
160
0
  std::vector<std::string> values;
161
0
  for (auto const& se : this->SourceEntries) {
162
0
    values.push_back(se->GetInput());
163
0
  }
164
0
  static std::string value;
165
0
  value = cmList::to_string(values);
166
0
  return cmValue(value);
167
0
}
168
169
cmGlobalGenerator* cmGeneratorTarget::GetGlobalGenerator() const
170
0
{
171
0
  return this->GetLocalGenerator()->GetGlobalGenerator();
172
0
}
173
174
cmLocalGenerator* cmGeneratorTarget::GetLocalGenerator() const
175
0
{
176
0
  return this->LocalGenerator;
177
0
}
178
179
cm::TargetType cmGeneratorTarget::GetType() const
180
0
{
181
0
  return this->Target->GetType();
182
0
}
183
184
std::string const& cmGeneratorTarget::GetName() const
185
0
{
186
0
  return this->Target->GetName();
187
0
}
188
189
std::string cmGeneratorTarget::GetFamilyName() const
190
0
{
191
0
  if (!this->IsImported() && !this->IsSynthetic()) {
192
0
    return this->Target->GetTemplateName();
193
0
  }
194
0
  cmCryptoHash hasher(cmCryptoHash::AlgoSHA3_512);
195
0
  constexpr size_t HASH_TRUNCATION = 12;
196
0
  auto dirhash =
197
0
    hasher.HashString(this->GetLocalGenerator()->GetCurrentBinaryDirectory());
198
0
  auto targetIdent = hasher.HashString(cmStrCat("@d_", dirhash));
199
0
  return cmStrCat(this->Target->GetTemplateName(), '@',
200
0
                  targetIdent.substr(0, HASH_TRUNCATION));
201
0
}
202
203
std::string cmGeneratorTarget::GetExportName() const
204
0
{
205
0
  cmValue exportName = this->GetProperty("EXPORT_NAME");
206
207
0
  if (cmNonempty(exportName)) {
208
0
    if (!cmGeneratorExpression::IsValidTargetName(*exportName)) {
209
0
      std::ostringstream e;
210
0
      e << "EXPORT_NAME property \"" << *exportName << "\" for \""
211
0
        << this->GetName() << "\": is not valid.";
212
0
      cmSystemTools::Error(e.str());
213
0
      return "";
214
0
    }
215
0
    return *exportName;
216
0
  }
217
0
  return this->GetName();
218
0
}
219
220
std::string cmGeneratorTarget::GetFilesystemExportName() const
221
0
{
222
0
  auto fs_safe = this->GetExportName();
223
  // First escape any `_` characters to avoid collisions.
224
0
  cmSystemTools::ReplaceString(fs_safe, "_", "__");
225
  // Escape other characters that are not generally filesystem-safe.
226
0
  cmSystemTools::ReplaceString(fs_safe, ":", "_c");
227
0
  return fs_safe;
228
0
}
229
230
cmValue cmGeneratorTarget::GetProperty(std::string const& prop) const
231
0
{
232
0
  if (cmValue result =
233
0
        cmTargetPropertyComputer::GetProperty(this, prop, *this->Makefile)) {
234
0
    return result;
235
0
  }
236
0
  if (cmSystemTools::GetFatalErrorOccurred()) {
237
0
    return nullptr;
238
0
  }
239
0
  return this->Target->GetProperty(prop);
240
0
}
241
242
std::string const& cmGeneratorTarget::GetSafeProperty(
243
  std::string const& prop) const
244
0
{
245
0
  return this->GetProperty(prop);
246
0
}
247
248
char const* cmGeneratorTarget::GetOutputTargetType(
249
  cmStateEnums::ArtifactType artifact) const
250
0
{
251
0
  if (this->IsFrameworkOnApple() || this->GetGlobalGenerator()->IsXcode()) {
252
    // import file (i.e. .tbd file) is always in same location as library
253
0
    artifact = cmStateEnums::RuntimeBinaryArtifact;
254
0
  }
255
256
0
  switch (this->GetType()) {
257
0
    case cm::TargetType::SHARED_LIBRARY:
258
0
      if (this->IsDLLPlatform()) {
259
0
        switch (artifact) {
260
0
          case cmStateEnums::RuntimeBinaryArtifact:
261
            // A DLL shared library is treated as a runtime target.
262
0
            return "RUNTIME";
263
0
          case cmStateEnums::ImportLibraryArtifact:
264
            // A DLL import library is treated as an archive target.
265
0
            return "ARCHIVE";
266
0
        }
267
0
      } else {
268
0
        switch (artifact) {
269
0
          case cmStateEnums::RuntimeBinaryArtifact:
270
            // For non-DLL platforms shared libraries are treated as
271
            // library targets.
272
0
            return "LIBRARY";
273
0
          case cmStateEnums::ImportLibraryArtifact:
274
            // Library import libraries are treated as archive targets.
275
0
            return "ARCHIVE";
276
0
        }
277
0
      }
278
0
      break;
279
0
    case cm::TargetType::STATIC_LIBRARY:
280
      // Static libraries are always treated as archive targets.
281
0
      return "ARCHIVE";
282
0
    case cm::TargetType::MODULE_LIBRARY:
283
0
      switch (artifact) {
284
0
        case cmStateEnums::RuntimeBinaryArtifact:
285
          // Module libraries are always treated as library targets.
286
0
          return "LIBRARY";
287
0
        case cmStateEnums::ImportLibraryArtifact:
288
          // Module import libraries are treated as archive targets.
289
0
          return "ARCHIVE";
290
0
      }
291
0
      break;
292
0
    case cm::TargetType::OBJECT_LIBRARY:
293
      // Object libraries are always treated as object targets.
294
0
      return "OBJECT";
295
0
    case cm::TargetType::EXECUTABLE:
296
0
      switch (artifact) {
297
0
        case cmStateEnums::RuntimeBinaryArtifact:
298
          // Executables are always treated as runtime targets.
299
0
          return "RUNTIME";
300
0
        case cmStateEnums::ImportLibraryArtifact:
301
          // Executable import libraries are treated as archive targets.
302
0
          return "ARCHIVE";
303
0
      }
304
0
      break;
305
0
    default:
306
0
      break;
307
0
  }
308
0
  return "";
309
0
}
310
311
std::string cmGeneratorTarget::GetOutputName(
312
  std::string const& config, cmStateEnums::ArtifactType artifact) const
313
0
{
314
  // Lookup/compute/cache the output name for this configuration.
315
0
  OutputNameKey key(config, artifact);
316
0
  auto i = this->OutputNameMap.find(key);
317
0
  if (i == this->OutputNameMap.end()) {
318
    // Add empty name in map to detect potential recursion.
319
0
    OutputNameMapType::value_type entry(key, "");
320
0
    i = this->OutputNameMap.insert(entry).first;
321
322
    // Compute output name.
323
0
    std::vector<std::string> props;
324
0
    std::string type = this->GetOutputTargetType(artifact);
325
0
    std::string configUpper = cmSystemTools::UpperCase(config);
326
0
    if (!type.empty() && !configUpper.empty()) {
327
      // <ARCHIVE|LIBRARY|RUNTIME>_OUTPUT_NAME_<CONFIG>
328
0
      props.push_back(cmStrCat(type, "_OUTPUT_NAME_", configUpper));
329
0
    }
330
0
    if (!type.empty()) {
331
      // <ARCHIVE|LIBRARY|RUNTIME>_OUTPUT_NAME
332
0
      props.push_back(type + "_OUTPUT_NAME");
333
0
    }
334
0
    if (!configUpper.empty()) {
335
      // OUTPUT_NAME_<CONFIG>
336
0
      props.push_back("OUTPUT_NAME_" + configUpper);
337
      // <CONFIG>_OUTPUT_NAME
338
0
      props.push_back(configUpper + "_OUTPUT_NAME");
339
0
    }
340
    // OUTPUT_NAME
341
0
    props.emplace_back("OUTPUT_NAME");
342
343
0
    std::string outName;
344
0
    for (std::string const& p : props) {
345
0
      if (cmValue outNameProp = this->GetProperty(p)) {
346
0
        outName = *outNameProp;
347
0
        break;
348
0
      }
349
0
    }
350
351
0
    if (outName.empty()) {
352
0
      outName = this->GetName();
353
0
    }
354
355
    // Now evaluate genex and update the previously-prepared map entry.
356
0
    i->second =
357
0
      cmGeneratorExpression::Evaluate(outName, this->LocalGenerator, config);
358
0
  } else if (i->second.empty()) {
359
    // An empty map entry indicates we have been called recursively
360
    // from the above block.
361
0
    this->LocalGenerator->GetCMakeInstance()->IssueMessage(
362
0
      MessageType::FATAL_ERROR,
363
0
      cmStrCat("Target '", this->GetName(),
364
0
               "' OUTPUT_NAME depends on itself."),
365
0
      this->GetBacktrace());
366
0
  }
367
0
  return i->second;
368
0
}
369
370
std::string cmGeneratorTarget::GetFilePrefix(
371
  std::string const& config, cmStateEnums::ArtifactType artifact) const
372
0
{
373
0
  if (this->IsImported()) {
374
0
    cmValue prefix = this->GetFilePrefixInternal(config, artifact);
375
0
    return prefix ? *prefix : std::string();
376
0
  }
377
0
  return this->GetFullNameInternalComponents(config, artifact).prefix;
378
0
}
379
std::string cmGeneratorTarget::GetFileSuffix(
380
  std::string const& config, cmStateEnums::ArtifactType artifact) const
381
0
{
382
0
  if (this->IsImported()) {
383
0
    cmValue suffix = this->GetFileSuffixInternal(config, artifact);
384
0
    return suffix ? *suffix : std::string();
385
0
  }
386
0
  return this->GetFullNameInternalComponents(config, artifact).suffix;
387
0
}
388
389
std::string cmGeneratorTarget::GetFilePostfix(std::string const& config) const
390
0
{
391
0
  cmValue postfix = nullptr;
392
0
  std::string frameworkPostfix;
393
0
  if (!config.empty()) {
394
0
    std::string configProp =
395
0
      cmStrCat(cmSystemTools::UpperCase(config), "_POSTFIX");
396
0
    postfix = this->GetProperty(configProp);
397
398
    // Mac application bundles and frameworks have no regular postfix like
399
    // libraries do.
400
0
    if (!this->IsImported() && postfix &&
401
0
        (this->IsAppBundleOnApple() || this->IsFrameworkOnApple())) {
402
0
      postfix = nullptr;
403
0
    }
404
405
    // Frameworks created by multi config generators can have a special
406
    // framework postfix.
407
0
    frameworkPostfix = this->GetFrameworkMultiConfigPostfix(config);
408
0
    if (!frameworkPostfix.empty()) {
409
0
      postfix = cmValue(frameworkPostfix);
410
0
    }
411
0
  }
412
0
  return postfix ? *postfix : std::string();
413
0
}
414
415
std::string cmGeneratorTarget::GetFrameworkMultiConfigPostfix(
416
  std::string const& config) const
417
0
{
418
0
  cmValue postfix = nullptr;
419
0
  if (!config.empty()) {
420
0
    std::string configProp = cmStrCat("FRAMEWORK_MULTI_CONFIG_POSTFIX_",
421
0
                                      cmSystemTools::UpperCase(config));
422
0
    postfix = this->GetProperty(configProp);
423
424
0
    if (!this->IsImported() && postfix &&
425
0
        (this->IsFrameworkOnApple() &&
426
0
         !this->GetGlobalGenerator()->IsMultiConfig())) {
427
0
      postfix = nullptr;
428
0
    }
429
0
  }
430
0
  return postfix ? *postfix : std::string();
431
0
}
432
433
cmValue cmGeneratorTarget::GetFilePrefixInternal(
434
  std::string const& config, cmStateEnums::ArtifactType artifact,
435
  std::string const& language) const
436
0
{
437
  // no prefix for non-main target types.
438
0
  if (this->GetType() != cm::TargetType::STATIC_LIBRARY &&
439
0
      this->GetType() != cm::TargetType::SHARED_LIBRARY &&
440
0
      this->GetType() != cm::TargetType::MODULE_LIBRARY &&
441
0
      this->GetType() != cm::TargetType::EXECUTABLE) {
442
0
    return nullptr;
443
0
  }
444
445
0
  bool const isImportedLibraryArtifact =
446
0
    (artifact == cmStateEnums::ImportLibraryArtifact);
447
448
  // Return an empty prefix for the import library if this platform
449
  // does not support import libraries.
450
0
  if (isImportedLibraryArtifact && !this->NeedImportLibraryName(config)) {
451
0
    return nullptr;
452
0
  }
453
454
  // The implib option is only allowed for shared libraries, module
455
  // libraries, and executables.
456
0
  if (this->GetType() != cm::TargetType::SHARED_LIBRARY &&
457
0
      this->GetType() != cm::TargetType::MODULE_LIBRARY &&
458
0
      this->GetType() != cm::TargetType::EXECUTABLE) {
459
0
    artifact = cmStateEnums::RuntimeBinaryArtifact;
460
0
  }
461
462
  // Compute prefix value.
463
0
  cmValue targetPrefix =
464
0
    (isImportedLibraryArtifact ? this->GetProperty("IMPORT_PREFIX")
465
0
                               : this->GetProperty("PREFIX"));
466
467
0
  if (!targetPrefix) {
468
0
    char const* prefixVar = this->Target->GetPrefixVariableInternal(artifact);
469
0
    if (!language.empty() && cmNonempty(prefixVar)) {
470
0
      std::string langPrefix = cmStrCat(prefixVar, '_', language);
471
0
      targetPrefix = this->Makefile->GetDefinition(langPrefix);
472
0
    }
473
474
    // if there is no prefix on the target nor specific language
475
    // use the cmake definition.
476
0
    if (!targetPrefix && prefixVar) {
477
0
      targetPrefix = this->Makefile->GetDefinition(prefixVar);
478
0
    }
479
0
  }
480
481
0
  return targetPrefix;
482
0
}
483
484
cmValue cmGeneratorTarget::GetFileSuffixInternal(
485
  std::string const& config, cmStateEnums::ArtifactType artifact,
486
  std::string const& language) const
487
0
{
488
  // no suffix for non-main target types.
489
0
  if (this->GetType() != cm::TargetType::STATIC_LIBRARY &&
490
0
      this->GetType() != cm::TargetType::SHARED_LIBRARY &&
491
0
      this->GetType() != cm::TargetType::MODULE_LIBRARY &&
492
0
      this->GetType() != cm::TargetType::EXECUTABLE) {
493
0
    return nullptr;
494
0
  }
495
496
0
  bool const isImportedLibraryArtifact =
497
0
    (artifact == cmStateEnums::ImportLibraryArtifact);
498
499
  // Return an empty suffix for the import library if this platform
500
  // does not support import libraries.
501
0
  if (isImportedLibraryArtifact && !this->NeedImportLibraryName(config)) {
502
0
    return nullptr;
503
0
  }
504
505
  // The implib option is only allowed for shared libraries, module
506
  // libraries, and executables.
507
0
  if (this->GetType() != cm::TargetType::SHARED_LIBRARY &&
508
0
      this->GetType() != cm::TargetType::MODULE_LIBRARY &&
509
0
      this->GetType() != cm::TargetType::EXECUTABLE) {
510
0
    artifact = cmStateEnums::RuntimeBinaryArtifact;
511
0
  }
512
513
  // Compute suffix value.
514
0
  cmValue targetSuffix =
515
0
    (isImportedLibraryArtifact ? this->GetProperty("IMPORT_SUFFIX")
516
0
                               : this->GetProperty("SUFFIX"));
517
518
0
  if (!targetSuffix) {
519
0
    char const* suffixVar = this->Target->GetSuffixVariableInternal(artifact);
520
0
    if (!language.empty() && cmNonempty(suffixVar)) {
521
0
      std::string langSuffix = cmStrCat(suffixVar, '_', language);
522
0
      targetSuffix = this->Makefile->GetDefinition(langSuffix);
523
0
    }
524
525
    // if there is no suffix on the target nor specific language
526
    // use the cmake definition.
527
0
    if (!targetSuffix && suffixVar) {
528
0
      targetSuffix = this->Makefile->GetDefinition(suffixVar);
529
0
    }
530
0
  }
531
532
0
  return targetSuffix;
533
0
}
534
535
void cmGeneratorTarget::ClearSourcesCache()
536
0
{
537
0
  this->AllConfigSources.clear();
538
0
  this->AllConfigCompileLanguages.clear();
539
0
  this->KindedSourcesMap.clear();
540
0
  this->SourcesAreContextDependent = Tribool::Indeterminate;
541
0
  this->Objects.clear();
542
0
  this->VisitedConfigsForObjects.clear();
543
0
  this->LinkImplClosureForLinkMap.clear();
544
0
  this->LinkImplClosureForUsageMap.clear();
545
0
  this->LinkImplMap.clear();
546
0
  this->LinkImplUsageRequirementsOnlyMap.clear();
547
0
  this->IncludeDirectoriesCache.clear();
548
0
  this->CompileOptionsCache.clear();
549
0
  this->CompileDefinitionsCache.clear();
550
0
  this->CustomTransitiveBuildPropertiesMap.clear();
551
0
  this->CustomTransitiveInterfacePropertiesMap.clear();
552
0
  this->PrecompileHeadersCache.clear();
553
0
  this->LinkOptionsCache.clear();
554
0
  this->LinkDirectoriesCache.clear();
555
0
  this->RuntimeBinaryFullNameCache.clear();
556
0
  this->ImportLibraryFullNameCache.clear();
557
0
}
558
559
void cmGeneratorTarget::ClearLinkInterfaceCache()
560
0
{
561
0
  this->LinkInterfaceMap.clear();
562
0
  this->LinkInterfaceUsageRequirementsOnlyMap.clear();
563
0
}
564
565
void cmGeneratorTarget::AddSourceCommon(std::string const& src, bool before)
566
0
{
567
0
  this->SourceEntries.insert(
568
0
    before ? this->SourceEntries.begin() : this->SourceEntries.end(),
569
0
    TargetPropertyEntry::Create(
570
0
      *this->LocalGenerator->GetCMakeInstance(),
571
0
      BT<std::string>(src, this->Makefile->GetBacktrace()), true));
572
0
  this->ClearSourcesCache();
573
0
}
574
575
cmSourceFile* cmGeneratorTarget::AddSource(std::string const& src, bool before)
576
0
{
577
0
  auto* sf = this->Target->AddSource(src, before);
578
0
  this->AddSourceCommon(src, before);
579
0
  return sf;
580
0
}
581
582
void cmGeneratorTarget::AddTracedSources(std::vector<std::string> const& srcs)
583
0
{
584
0
  this->Target->AddTracedSources(srcs);
585
0
  if (!srcs.empty()) {
586
0
    this->AddSourceCommon(cmJoin(srcs, ";"));
587
0
  }
588
0
}
589
590
void cmGeneratorTarget::AddIncludeDirectory(std::string const& src,
591
                                            bool before)
592
0
{
593
0
  this->Target->InsertInclude(
594
0
    BT<std::string>(src, this->Makefile->GetBacktrace()), before);
595
0
  this->IncludeDirectoriesEntries.insert(
596
0
    before ? this->IncludeDirectoriesEntries.begin()
597
0
           : this->IncludeDirectoriesEntries.end(),
598
0
    TargetPropertyEntry::Create(
599
0
      *this->Makefile->GetCMakeInstance(),
600
0
      BT<std::string>(src, this->Makefile->GetBacktrace()), true));
601
0
}
602
603
void cmGeneratorTarget::AddSystemIncludeDirectory(std::string const& inc,
604
                                                  std::string const& lang)
605
0
{
606
0
  std::string config_upper;
607
0
  auto const& configs =
608
0
    this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
609
610
0
  for (auto const& config : configs) {
611
0
    std::string inc_with_config = inc;
612
0
    if (!config.empty()) {
613
0
      cmSystemTools::ReplaceString(inc_with_config, "$<CONFIG>", config);
614
0
      config_upper = cmSystemTools::UpperCase(config);
615
0
    }
616
0
    auto const& key = cmStrCat(config_upper, '/', lang);
617
0
    this->Target->AddSystemIncludeDirectories({ inc_with_config });
618
0
    if (this->SystemIncludesCache.find(key) ==
619
0
        this->SystemIncludesCache.end()) {
620
0
      this->AddSystemIncludeCacheKey(key, config, lang);
621
0
    }
622
0
    this->SystemIncludesCache[key].emplace_back(inc_with_config);
623
624
    // SystemIncludesCache should be sorted so that binary search can be used
625
0
    std::sort(this->SystemIncludesCache[key].begin(),
626
0
              this->SystemIncludesCache[key].end());
627
0
  }
628
0
}
629
630
std::vector<cmSourceFile*> const* cmGeneratorTarget::GetSourceDepends(
631
  cmSourceFile const* sf) const
632
0
{
633
0
  auto i = this->SourceDepends.find(sf);
634
0
  if (i != this->SourceDepends.end()) {
635
0
    return &i->second.Depends;
636
0
  }
637
0
  return nullptr;
638
0
}
639
640
namespace {
641
void handleSystemIncludesDep(cmLocalGenerator const* lg,
642
                             cmGeneratorTarget const* depTgt,
643
                             std::string const& config,
644
                             cmGeneratorTarget const* headTarget,
645
                             cmGeneratorExpressionDAGChecker* dagChecker,
646
                             cmList& result, bool excludeImported,
647
                             std::string const& language)
648
0
{
649
0
  if (cmValue dirs =
650
0
        depTgt->GetProperty("INTERFACE_SYSTEM_INCLUDE_DIRECTORIES")) {
651
0
    result.append(cmGeneratorExpression::Evaluate(
652
0
      *dirs, lg, config, headTarget, dagChecker, depTgt, language));
653
0
  }
654
0
  if (!depTgt->GetPropertyAsBool("SYSTEM")) {
655
0
    return;
656
0
  }
657
0
  if (depTgt->IsImported()) {
658
0
    if (excludeImported) {
659
0
      return;
660
0
    }
661
0
    if (depTgt->GetPropertyAsBool("IMPORTED_NO_SYSTEM")) {
662
0
      return;
663
0
    }
664
0
  }
665
666
0
  if (cmValue dirs = depTgt->GetProperty("INTERFACE_INCLUDE_DIRECTORIES")) {
667
0
    result.append(cmGeneratorExpression::Evaluate(
668
0
      *dirs, lg, config, headTarget, dagChecker, depTgt, language));
669
0
  }
670
671
0
  if (depTgt->Target->IsFrameworkOnApple() ||
672
0
      depTgt->IsImportedFrameworkFolderOnApple(config)) {
673
0
    if (auto fwDescriptor = depTgt->GetGlobalGenerator()->SplitFrameworkPath(
674
0
          depTgt->GetLocation(config))) {
675
0
      result.push_back(fwDescriptor->Directory);
676
0
      result.push_back(fwDescriptor->GetFrameworkPath());
677
0
    }
678
0
  }
679
0
}
680
}
681
682
/* clang-format off */
683
#define IMPLEMENT_VISIT(KIND)                                                 \
684
0
  do {                                                                        \
685
0
    KindedSources const& kinded = this->GetKindedSources(config);             \
686
0
    for (SourceAndKind const& s : kinded.Sources) {                           \
687
0
      if (s.Kind == KIND) {                                                   \
688
0
        data.push_back(s.Source.Value);                                       \
689
0
      }                                                                       \
690
0
    }                                                                         \
691
0
  } while (false)
692
/* clang-format on */
693
694
void cmGeneratorTarget::GetObjectSources(
695
  std::vector<cmSourceFile const*>& data, std::string const& config) const
696
0
{
697
0
  IMPLEMENT_VISIT(SourceKindObjectSource);
698
699
0
  if (this->VisitedConfigsForObjects.count(config)) {
700
0
    return;
701
0
  }
702
703
0
  for (cmSourceFile const* it : data) {
704
0
    this->Objects[it];
705
0
  }
706
707
0
  this->LocalGenerator->ComputeObjectFilenames(this->Objects, config, this);
708
0
  this->VisitedConfigsForObjects.insert(config);
709
0
}
710
711
void cmGeneratorTarget::ComputeObjectMapping() const
712
0
{
713
0
  auto const& configs =
714
0
    this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
715
0
  std::set<std::string> configSet(configs.begin(), configs.end());
716
0
  if (configSet == this->VisitedConfigsForObjects) {
717
0
    return;
718
0
  }
719
720
0
  for (std::string const& c : configs) {
721
0
    std::vector<cmSourceFile const*> sourceFiles;
722
0
    this->GetObjectSources(sourceFiles, c);
723
0
  }
724
0
}
725
726
cmValue cmGeneratorTarget::GetFeature(std::string const& feature,
727
                                      std::string const& config) const
728
0
{
729
0
  if (!config.empty()) {
730
0
    std::string featureConfig =
731
0
      cmStrCat(feature, '_', cmSystemTools::UpperCase(config));
732
0
    if (cmValue value = this->GetProperty(featureConfig)) {
733
0
      return value;
734
0
    }
735
0
  }
736
0
  if (cmValue value = this->GetProperty(feature)) {
737
0
    return value;
738
0
  }
739
0
  return this->LocalGenerator->GetFeature(feature, config);
740
0
}
741
742
std::string cmGeneratorTarget::GetLinkerTypeProperty(
743
  std::string const& lang, std::string const& config) const
744
0
{
745
0
  std::string propName{ "LINKER_TYPE" };
746
0
  auto linkerType = this->GetProperty(propName);
747
0
  if (!linkerType.IsEmpty()) {
748
0
    cm::GenEx::Context context(this->LocalGenerator, config, lang);
749
0
    cmGeneratorExpressionDAGChecker dagChecker{
750
0
      this, propName, nullptr, nullptr, context,
751
0
    };
752
0
    auto ltype = cmGeneratorExpression::Evaluate(
753
0
      *linkerType, context.LG, context.Config, this, &dagChecker, this,
754
0
      context.Language);
755
0
    if (this->IsDeviceLink()) {
756
0
      cmList list{ ltype };
757
0
      auto const DL_BEGIN = "<DEVICE_LINK>"_s;
758
0
      auto const DL_END = "</DEVICE_LINK>"_s;
759
0
      cm::erase_if(list, [&](std::string const& item) {
760
0
        return item == DL_BEGIN || item == DL_END;
761
0
      });
762
0
      return list.to_string();
763
0
    }
764
0
    return ltype;
765
0
  }
766
0
  return std::string{};
767
0
}
768
769
char const* cmGeneratorTarget::GetLinkPIEProperty(
770
  std::string const& config) const
771
0
{
772
0
  static std::string PICValue;
773
774
0
  PICValue = this->GetLinkInterfaceDependentStringAsBoolProperty(
775
0
    "POSITION_INDEPENDENT_CODE", config);
776
777
0
  if (PICValue == "(unset)") {
778
    // POSITION_INDEPENDENT_CODE is not set
779
0
    return nullptr;
780
0
  }
781
782
0
  auto status = this->GetPolicyStatusCMP0083();
783
0
  return (status != cmPolicies::WARN && status != cmPolicies::OLD)
784
0
    ? PICValue.c_str()
785
0
    : nullptr;
786
0
}
787
788
bool cmGeneratorTarget::IsIPOEnabled(std::string const& lang,
789
                                     std::string const& config) const
790
0
{
791
0
  cmValue feature = this->GetFeature("INTERPROCEDURAL_OPTIMIZATION", config);
792
793
0
  if (!feature.IsOn()) {
794
    // 'INTERPROCEDURAL_OPTIMIZATION' is off, no need to check policies
795
0
    return false;
796
0
  }
797
798
0
  if (lang != "C" && lang != "CXX" && lang != "CUDA" && lang != "Fortran") {
799
    // We do not define IPO behavior for other languages.
800
0
    return false;
801
0
  }
802
803
0
  if (lang == "CUDA") {
804
    // CUDA IPO requires both CUDA_ARCHITECTURES and CUDA_SEPARABLE_COMPILATION
805
0
    if (cmIsOff(this->GetSafeProperty("CUDA_ARCHITECTURES")) ||
806
0
        cmIsOff(this->GetSafeProperty("CUDA_SEPARABLE_COMPILATION"))) {
807
0
      return false;
808
0
    }
809
0
  }
810
811
0
  cmPolicies::PolicyStatus cmp0069 = this->GetPolicyStatusCMP0069();
812
813
0
  if (cmp0069 == cmPolicies::OLD || cmp0069 == cmPolicies::WARN) {
814
0
    if (this->Makefile->IsOn(
815
0
          cmStrCat("_CMAKE_", lang, "_IPO_LEGACY_BEHAVIOR"))) {
816
0
      return true;
817
0
    }
818
0
    if (this->PolicyReportedCMP0069) {
819
      // problem is already reported, no need to issue a message
820
0
      return false;
821
0
    }
822
0
    bool const in_try_compile =
823
0
      this->LocalGenerator->GetCMakeInstance()->GetIsInTryCompile();
824
0
    if (cmp0069 == cmPolicies::WARN && !in_try_compile) {
825
0
      this->Makefile->IssuePolicyWarning(
826
0
        cmPolicies::CMP0069, {},
827
0
        cmStrCat("INTERPROCEDURAL_OPTIMIZATION property "
828
0
                 "will be ignored for target '"_s,
829
0
                 this->GetName(), "'."_s),
830
0
        this->GetBacktrace());
831
832
0
      this->PolicyReportedCMP0069 = true;
833
0
    }
834
0
    return false;
835
0
  }
836
837
  // Note: check consistency with messages from CheckIPOSupported
838
0
  char const* message = nullptr;
839
0
  if (!this->Makefile->IsOn(
840
0
        cmStrCat("_CMAKE_", lang, "_IPO_SUPPORTED_BY_CMAKE"))) {
841
0
    message = "CMake doesn't support IPO for current compiler";
842
0
  } else if (!this->Makefile->IsOn(cmStrCat(
843
0
               "_CMAKE_", lang, "_IPO_MAY_BE_SUPPORTED_BY_COMPILER"))) {
844
0
    message = "Compiler doesn't support IPO";
845
0
  } else if (!this->GlobalGenerator->IsIPOSupported()) {
846
0
    message = "CMake doesn't support IPO for current generator";
847
0
  }
848
849
0
  if (!message) {
850
    // No error/warning messages
851
0
    return true;
852
0
  }
853
854
0
  if (this->PolicyReportedCMP0069) {
855
    // problem is already reported, no need to issue a message
856
0
    return false;
857
0
  }
858
859
0
  this->PolicyReportedCMP0069 = true;
860
861
0
  this->LocalGenerator->GetCMakeInstance()->IssueMessage(
862
0
    MessageType::FATAL_ERROR, message, this->GetBacktrace());
863
0
  return false;
864
0
}
865
866
std::string const& cmGeneratorTarget::GetObjectName(
867
  cmSourceFile const* file) const
868
0
{
869
0
  this->ComputeObjectMapping();
870
0
  auto const useShortPaths = this->GetUseShortObjectNames()
871
0
    ? cmObjectLocations::UseShortPath::Yes
872
0
    : cmObjectLocations::UseShortPath::No;
873
0
  return this->Objects[file].GetPath(useShortPaths);
874
0
}
875
876
char const* cmGeneratorTarget::GetCustomObjectExtension() const
877
0
{
878
0
  struct compiler_mode
879
0
  {
880
0
    std::string variable;
881
0
    std::string extension;
882
0
  };
883
0
  static std::array<compiler_mode, 4> const modes{
884
0
    { { "CUDA_PTX_COMPILATION", ".ptx" },
885
0
      { "CUDA_CUBIN_COMPILATION", ".cubin" },
886
0
      { "CUDA_FATBIN_COMPILATION", ".fatbin" },
887
0
      { "CUDA_OPTIX_COMPILATION", ".optixir" } }
888
0
  };
889
890
0
  std::string const& compiler =
891
0
    this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_ID");
892
0
  if (!compiler.empty()) {
893
0
    for (auto const& m : modes) {
894
0
      bool const has_extension = this->GetPropertyAsBool(m.variable);
895
0
      if (has_extension) {
896
0
        return m.extension.c_str();
897
0
      }
898
0
    }
899
0
  }
900
0
  return nullptr;
901
0
}
902
903
void cmGeneratorTarget::AddExplicitObjectName(cmSourceFile const* sf)
904
0
{
905
0
  this->ExplicitObjectName.insert(sf);
906
0
}
907
908
bool cmGeneratorTarget::HasExplicitObjectName(cmSourceFile const* file) const
909
0
{
910
0
  this->ComputeObjectMapping();
911
0
  auto it = this->ExplicitObjectName.find(file);
912
0
  return it != this->ExplicitObjectName.end();
913
0
}
914
915
BTs<std::string> const* cmGeneratorTarget::GetLanguageStandardProperty(
916
  std::string const& lang, std::string const& config) const
917
0
{
918
0
  std::string key = cmStrCat(cmSystemTools::UpperCase(config), '-', lang);
919
0
  auto langStandardIter = this->LanguageStandardMap.find(key);
920
0
  if (langStandardIter != this->LanguageStandardMap.end()) {
921
0
    return &langStandardIter->second;
922
0
  }
923
924
0
  return this->Target->GetLanguageStandardProperty(
925
0
    cmStrCat(lang, "_STANDARD"));
926
0
}
927
928
cmValue cmGeneratorTarget::GetLanguageStandard(std::string const& lang,
929
                                               std::string const& config) const
930
0
{
931
0
  BTs<std::string> const* languageStandard =
932
0
    this->GetLanguageStandardProperty(lang, config);
933
934
0
  if (languageStandard) {
935
0
    return cmValue(languageStandard->Value);
936
0
  }
937
938
0
  return nullptr;
939
0
}
940
941
cmValue cmGeneratorTarget::GetPropertyWithPairedLanguageSupport(
942
  std::string const& lang, char const* suffix) const
943
0
{
944
0
  cmValue propertyValue = this->Target->GetProperty(cmStrCat(lang, suffix));
945
0
  if (!propertyValue) {
946
    // Check if we should use the value set by another language.
947
0
    if (lang == "OBJC") {
948
0
      propertyValue = this->GetPropertyWithPairedLanguageSupport("C", suffix);
949
0
    } else if (lang == "OBJCXX" || lang == "CUDA" || lang == "HIP") {
950
0
      propertyValue =
951
0
        this->GetPropertyWithPairedLanguageSupport("CXX", suffix);
952
0
    }
953
0
  }
954
0
  return propertyValue;
955
0
}
956
957
cmValue cmGeneratorTarget::GetLanguageExtensions(std::string const& lang) const
958
0
{
959
0
  return this->GetPropertyWithPairedLanguageSupport(lang, "_EXTENSIONS");
960
0
}
961
962
bool cmGeneratorTarget::GetLanguageStandardRequired(
963
  std::string const& lang) const
964
0
{
965
0
  return this->GetPropertyWithPairedLanguageSupport(lang, "_STANDARD_REQUIRED")
966
0
    .IsOn();
967
0
}
968
969
void cmGeneratorTarget::GetModuleDefinitionSources(
970
  std::vector<cmSourceFile const*>& data, std::string const& config) const
971
0
{
972
0
  IMPLEMENT_VISIT(SourceKindModuleDefinition);
973
0
}
974
975
void cmGeneratorTarget::GetHeaderSources(
976
  std::vector<cmSourceFile const*>& data, std::string const& config) const
977
0
{
978
0
  IMPLEMENT_VISIT(SourceKindHeader);
979
0
}
980
981
void cmGeneratorTarget::GetCxxModuleSources(
982
  std::vector<cmSourceFile const*>& data, std::string const& config) const
983
0
{
984
0
  IMPLEMENT_VISIT(SourceKindCxxModuleSource);
985
0
}
986
987
void cmGeneratorTarget::GetExtraSources(std::vector<cmSourceFile const*>& data,
988
                                        std::string const& config) const
989
0
{
990
0
  IMPLEMENT_VISIT(SourceKindExtra);
991
0
}
992
993
void cmGeneratorTarget::GetCustomCommands(
994
  std::vector<cmSourceFile const*>& data, std::string const& config) const
995
0
{
996
0
  IMPLEMENT_VISIT(SourceKindCustomCommand);
997
0
}
998
999
void cmGeneratorTarget::GetExternalObjects(
1000
  std::vector<cmSourceFile const*>& data, std::string const& config) const
1001
0
{
1002
0
  IMPLEMENT_VISIT(SourceKindExternalObject);
1003
0
}
1004
1005
void cmGeneratorTarget::GetManifests(std::vector<cmSourceFile const*>& data,
1006
                                     std::string const& config) const
1007
0
{
1008
0
  IMPLEMENT_VISIT(SourceKindManifest);
1009
0
}
1010
1011
void cmGeneratorTarget::GetRustMainCrateRoot(
1012
  std::vector<cmSourceFile const*>& data, std::string const& config) const
1013
0
{
1014
0
  IMPLEMENT_VISIT(SourceKindRustMainCrateRoot);
1015
0
}
1016
1017
cmSourceFile const* cmGeneratorTarget::GetRustMainCrateRoot(
1018
  std::string const& config) const
1019
0
{
1020
0
  std::vector<cmSourceFile const*> files;
1021
0
  GetRustMainCrateRoot(files, config);
1022
0
  if (files.empty()) {
1023
0
    return nullptr;
1024
0
  }
1025
0
  assert(files.size() == 1);
1026
0
  return files[0];
1027
0
}
1028
1029
std::set<cmLinkItem> const& cmGeneratorTarget::GetUtilityItems() const
1030
0
{
1031
0
  if (!this->UtilityItemsDone) {
1032
0
    this->UtilityItemsDone = true;
1033
0
    std::set<BT<std::pair<std::string, bool>>> const& utilities =
1034
0
      this->GetUtilities();
1035
0
    for (BT<std::pair<std::string, bool>> const& i : utilities) {
1036
0
      if (cmGeneratorTarget* gt =
1037
0
            this->LocalGenerator->FindGeneratorTargetToUse(i.Value.first)) {
1038
0
        this->UtilityItems.insert(cmLinkItem(gt, i.Value.second, i.Backtrace));
1039
0
      } else {
1040
0
        this->UtilityItems.insert(
1041
0
          cmLinkItem(i.Value.first, i.Value.second, i.Backtrace));
1042
0
      }
1043
0
    }
1044
0
    if (cmGeneratorTarget const* reuseTarget = this->GetPchReuseTarget()) {
1045
0
      this->UtilityItems.insert(
1046
0
        cmLinkItem(reuseTarget, false, cmListFileBacktrace()));
1047
0
    }
1048
0
  }
1049
0
  return this->UtilityItems;
1050
0
}
1051
1052
std::string const& cmGeneratorTarget::GetLocation(
1053
  std::string const& config) const
1054
0
{
1055
0
  static std::string location;
1056
0
  if (this->IsImported()) {
1057
0
    location = this->Target->ImportedGetFullPath(
1058
0
      config, cmStateEnums::RuntimeBinaryArtifact);
1059
0
  } else {
1060
0
    location = this->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact);
1061
0
  }
1062
0
  return location;
1063
0
}
1064
1065
cm::optional<std::string> cmGeneratorTarget::MaybeGetLocation(
1066
  std::string const& config) const
1067
0
{
1068
0
  cm::optional<std::string> location;
1069
0
  if (cmGeneratorTarget::ImportInfo const* imp = this->GetImportInfo(config)) {
1070
0
    if (!imp->Location.empty()) {
1071
0
      location = imp->Location;
1072
0
    }
1073
0
  } else {
1074
0
    location = this->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact);
1075
0
  }
1076
0
  return location;
1077
0
}
1078
1079
std::vector<cmCustomCommand> const& cmGeneratorTarget::GetPreBuildCommands()
1080
  const
1081
0
{
1082
0
  return this->Target->GetPreBuildCommands();
1083
0
}
1084
1085
std::vector<cmCustomCommand> const& cmGeneratorTarget::GetPreLinkCommands()
1086
  const
1087
0
{
1088
0
  return this->Target->GetPreLinkCommands();
1089
0
}
1090
1091
std::vector<cmCustomCommand> const& cmGeneratorTarget::GetPostBuildCommands()
1092
  const
1093
0
{
1094
0
  return this->Target->GetPostBuildCommands();
1095
0
}
1096
1097
void cmGeneratorTarget::AppendCustomCommandSideEffects(
1098
  std::set<cmGeneratorTarget const*>& sideEffects) const
1099
0
{
1100
0
  if (!this->GetPreBuildCommands().empty() ||
1101
0
      !this->GetPreLinkCommands().empty() ||
1102
0
      !this->GetPostBuildCommands().empty()) {
1103
0
    sideEffects.insert(this);
1104
0
  } else {
1105
0
    for (auto const& source : this->GetAllConfigSources()) {
1106
0
      if (source.Source->GetCustomCommand()) {
1107
0
        sideEffects.insert(this);
1108
0
        break;
1109
0
      }
1110
0
    }
1111
0
  }
1112
0
}
1113
1114
void cmGeneratorTarget::AppendLanguageSideEffects(
1115
  std::map<std::string, std::set<cmGeneratorTarget const*>>& sideEffects) const
1116
0
{
1117
0
  static std::set<cm::string_view> const LANGS_WITH_NO_SIDE_EFFECTS = {
1118
0
    "C"_s, "CXX"_s, "OBJC"_s, "OBJCXX"_s, "ASM"_s, "CUDA"_s, "HIP"_s
1119
0
  };
1120
1121
0
  for (auto const& lang : this->GetAllConfigCompileLanguages()) {
1122
0
    if (!LANGS_WITH_NO_SIDE_EFFECTS.count(lang)) {
1123
0
      sideEffects[lang].insert(this);
1124
0
    }
1125
0
  }
1126
0
}
1127
1128
bool cmGeneratorTarget::IsInBuildSystem() const
1129
0
{
1130
0
  if (this->IsImported()) {
1131
0
    return false;
1132
0
  }
1133
0
  switch (this->Target->GetType()) {
1134
0
    case cm::TargetType::EXECUTABLE:
1135
0
    case cm::TargetType::STATIC_LIBRARY:
1136
0
    case cm::TargetType::SHARED_LIBRARY:
1137
0
    case cm::TargetType::MODULE_LIBRARY:
1138
0
    case cm::TargetType::OBJECT_LIBRARY:
1139
0
    case cm::TargetType::UTILITY:
1140
0
    case cm::TargetType::GLOBAL_TARGET:
1141
0
      return true;
1142
0
    case cm::TargetType::INTERFACE_LIBRARY:
1143
      // An INTERFACE library is in the build system if it has SOURCES
1144
      // or C++ module filesets.
1145
0
      if (!this->SourceEntries.empty() ||
1146
0
          !this->GetFileSets(cm::FileSetMetadata::HEADERS).empty() ||
1147
0
          !this->GetFileSets(cm::FileSetMetadata::CXX_MODULES).empty()) {
1148
0
        return true;
1149
0
      }
1150
0
      break;
1151
0
    case cm::TargetType::UNKNOWN_LIBRARY:
1152
0
      break;
1153
0
  }
1154
0
  return false;
1155
0
}
1156
1157
bool cmGeneratorTarget::IsNormal() const
1158
0
{
1159
0
  return this->Target->IsNormal();
1160
0
}
1161
1162
bool cmGeneratorTarget::IsRuntimeBinary() const
1163
0
{
1164
0
  return this->Target->IsRuntimeBinary();
1165
0
}
1166
1167
bool cmGeneratorTarget::IsSynthetic() const
1168
0
{
1169
0
  return this->Target->IsSynthetic();
1170
0
}
1171
1172
bool cmGeneratorTarget::IsImported() const
1173
0
{
1174
0
  return this->Target->IsImported();
1175
0
}
1176
1177
bool cmGeneratorTarget::IsImportedGloballyVisible() const
1178
0
{
1179
0
  return this->Target->IsImportedGloballyVisible();
1180
0
}
1181
1182
bool cmGeneratorTarget::IsSymbolic() const
1183
0
{
1184
0
  return this->Target->IsSymbolic();
1185
0
}
1186
1187
bool cmGeneratorTarget::IsForeign() const
1188
0
{
1189
0
  return this->Target->IsForeign();
1190
0
}
1191
1192
bool cmGeneratorTarget::CanCompileSources() const
1193
0
{
1194
0
  return this->Target->CanCompileSources();
1195
0
}
1196
1197
bool cmGeneratorTarget::HasKnownRuntimeArtifactLocation(
1198
  std::string const& config) const
1199
0
{
1200
0
  if (!this->IsRuntimeBinary()) {
1201
0
    return false;
1202
0
  }
1203
0
  if (!this->IsImported()) {
1204
0
    return true;
1205
0
  }
1206
0
  ImportInfo const* info = this->GetImportInfo(config);
1207
0
  return info && !info->Location.empty();
1208
0
}
1209
1210
std::string const& cmGeneratorTarget::GetLocationForBuild() const
1211
0
{
1212
0
  static std::string location;
1213
0
  if (this->IsImported()) {
1214
0
    location = this->Target->ImportedGetFullPath(
1215
0
      "", cmStateEnums::RuntimeBinaryArtifact);
1216
0
    return location;
1217
0
  }
1218
1219
  // Now handle the deprecated build-time configuration location.
1220
0
  std::string const noConfig;
1221
0
  location = this->GetDirectory(noConfig);
1222
0
  cmValue cfgid = this->Makefile->GetDefinition("CMAKE_CFG_INTDIR");
1223
0
  if (cfgid && (*cfgid != ".")) {
1224
0
    location = cmStrCat(std::move(location), '/', *cfgid);
1225
0
  }
1226
1227
0
  if (this->IsAppBundleOnApple()) {
1228
0
    std::string macdir = this->BuildBundleDirectory("", "", FullLevel);
1229
0
    if (!macdir.empty()) {
1230
0
      location = cmStrCat(std::move(location), '/', macdir);
1231
0
    }
1232
0
  }
1233
0
  location =
1234
0
    cmStrCat(std::move(location), '/',
1235
0
             this->GetFullName("", cmStateEnums::RuntimeBinaryArtifact));
1236
0
  return location;
1237
0
}
1238
1239
void cmGeneratorTarget::AddSystemIncludeCacheKey(
1240
  std::string const& key, std::string const& config,
1241
  std::string const& language) const
1242
0
{
1243
0
  cm::GenEx::Context context(this->LocalGenerator, config, language);
1244
0
  cmGeneratorExpressionDAGChecker dagChecker{
1245
0
    this, "SYSTEM_INCLUDE_DIRECTORIES", nullptr, nullptr, context,
1246
0
  };
1247
1248
0
  bool excludeImported = this->GetPropertyAsBool("NO_SYSTEM_FROM_IMPORTED");
1249
1250
0
  cmList result;
1251
0
  for (std::string const& it : this->Target->GetSystemIncludeDirectories()) {
1252
0
    result.append(
1253
0
      cmGeneratorExpression::Evaluate(it, context.LG, context.Config, this,
1254
0
                                      &dagChecker, nullptr, context.Language));
1255
0
  }
1256
1257
0
  std::vector<cmGeneratorTarget const*> const& deps =
1258
0
    this->GetLinkImplementationClosure(config, UseTo::Compile);
1259
0
  for (cmGeneratorTarget const* dep : deps) {
1260
0
    handleSystemIncludesDep(context.LG, dep, context.Config, this, &dagChecker,
1261
0
                            result, excludeImported, context.Language);
1262
0
  }
1263
1264
0
  cmLinkImplementation const* impl =
1265
0
    this->GetLinkImplementation(config, UseTo::Compile);
1266
0
  if (impl) {
1267
0
    auto runtimeEntries = impl->LanguageRuntimeLibraries.find(language);
1268
0
    if (runtimeEntries != impl->LanguageRuntimeLibraries.end()) {
1269
0
      for (auto const& lib : runtimeEntries->second) {
1270
0
        if (lib.Target) {
1271
0
          handleSystemIncludesDep(context.LG, lib.Target, context.Config, this,
1272
0
                                  &dagChecker, result, excludeImported,
1273
0
                                  context.Language);
1274
0
        }
1275
0
      }
1276
0
    }
1277
0
  }
1278
1279
0
  std::for_each(result.begin(), result.end(),
1280
0
                cmSystemTools::ConvertToUnixSlashes);
1281
0
  std::sort(result.begin(), result.end());
1282
0
  result.erase(std::unique(result.begin(), result.end()), result.end());
1283
0
  SystemIncludesCache.emplace(key, result);
1284
0
}
1285
1286
bool cmGeneratorTarget::IsSystemIncludeDirectory(
1287
  std::string const& dir, std::string const& config,
1288
  std::string const& language) const
1289
0
{
1290
0
  std::string config_upper;
1291
0
  if (!config.empty()) {
1292
0
    config_upper = cmSystemTools::UpperCase(config);
1293
0
  }
1294
1295
0
  std::string key = cmStrCat(config_upper, '/', language);
1296
0
  auto iter = this->SystemIncludesCache.find(key);
1297
1298
0
  if (iter == this->SystemIncludesCache.end()) {
1299
0
    this->AddSystemIncludeCacheKey(key, config, language);
1300
0
    iter = this->SystemIncludesCache.find(key);
1301
0
  }
1302
1303
0
  return std::binary_search(iter->second.begin(), iter->second.end(), dir);
1304
0
}
1305
1306
bool cmGeneratorTarget::GetPropertyAsBool(std::string const& prop) const
1307
0
{
1308
0
  return this->Target->GetPropertyAsBool(prop);
1309
0
}
1310
1311
std::string cmGeneratorTarget::GetCompilePDBName(
1312
  std::string const& config) const
1313
0
{
1314
0
  if (cmGeneratorTarget const* reuseTarget = this->GetPchReuseTarget()) {
1315
0
    if (reuseTarget != this) {
1316
0
      return reuseTarget->GetCompilePDBName(config);
1317
0
    }
1318
0
  }
1319
1320
  // Check for a per-configuration output directory target property.
1321
0
  std::string configUpper = cmSystemTools::UpperCase(config);
1322
0
  std::string configProp = cmStrCat("COMPILE_PDB_NAME_", configUpper);
1323
0
  cmValue config_name = this->GetProperty(configProp);
1324
0
  if (cmNonempty(config_name)) {
1325
0
    std::string pdbName = cmGeneratorExpression::Evaluate(
1326
0
      *config_name, this->LocalGenerator, config, this);
1327
0
    NameComponents const& components = GetFullNameInternalComponents(
1328
0
      config, cmStateEnums::RuntimeBinaryArtifact);
1329
0
    return components.prefix + pdbName + ".pdb";
1330
0
  }
1331
1332
0
  cmValue name = this->GetProperty("COMPILE_PDB_NAME");
1333
0
  if (cmNonempty(name)) {
1334
0
    std::string pdbName = cmGeneratorExpression::Evaluate(
1335
0
      *name, this->LocalGenerator, config, this);
1336
0
    NameComponents const& components = GetFullNameInternalComponents(
1337
0
      config, cmStateEnums::RuntimeBinaryArtifact);
1338
0
    return components.prefix + pdbName + ".pdb";
1339
0
  }
1340
1341
  // If the target is PCH-reused or PCH-reuses, we need a stable name for the
1342
  // PDB file so that reusing targets can construct a stable name for it.
1343
0
  cmGeneratorTarget const* reuseTarget = this->GetPchReuseTarget();
1344
0
  bool const hasReuse = reuseTarget && reuseTarget != this;
1345
0
  if (this->PchReused || hasReuse) {
1346
0
    NameComponents const& components = GetFullNameInternalComponents(
1347
0
      config, cmStateEnums::RuntimeBinaryArtifact);
1348
0
    return cmStrCat(components.prefix, this->GetName(), ".pdb");
1349
0
  }
1350
1351
0
  return std::string{};
1352
0
}
1353
1354
std::string cmGeneratorTarget::GetCompilePDBPath(
1355
  std::string const& config) const
1356
0
{
1357
0
  std::string dir = this->GetCompilePDBDirectory(config);
1358
0
  std::string name = this->GetCompilePDBName(config);
1359
0
  if (dir.empty() && !name.empty() && this->HaveWellDefinedOutputFiles()) {
1360
0
    dir = this->GetPDBDirectory(config);
1361
0
  }
1362
0
  if (!dir.empty()) {
1363
0
    dir += '/';
1364
0
  }
1365
0
  return dir + name;
1366
0
}
1367
1368
bool cmGeneratorTarget::HasSOName(std::string const& config) const
1369
0
{
1370
  // soname is supported only for shared libraries and modules,
1371
  // and then only when the platform supports an soname flag.
1372
0
  return ((this->GetType() == cm::TargetType::SHARED_LIBRARY) &&
1373
0
          !this->GetPropertyAsBool("NO_SONAME") &&
1374
0
          (this->Makefile->GetSONameFlag(this->GetLinkerLanguage(config)) ||
1375
0
           this->IsArchivedAIXSharedLibrary()));
1376
0
}
1377
1378
bool cmGeneratorTarget::NeedRelinkBeforeInstall(
1379
  std::string const& config) const
1380
0
{
1381
  // Only executables and shared libraries can have an rpath and may
1382
  // need relinking.
1383
0
  if (this->GetType() != cm::TargetType::EXECUTABLE &&
1384
0
      this->GetType() != cm::TargetType::SHARED_LIBRARY &&
1385
0
      this->GetType() != cm::TargetType::MODULE_LIBRARY) {
1386
0
    return false;
1387
0
  }
1388
1389
  // If there is no install location this target will not be installed
1390
  // and therefore does not need relinking.
1391
0
  if (!this->Target->GetHaveInstallRule()) {
1392
0
    return false;
1393
0
  }
1394
1395
  // If skipping all rpaths completely then no relinking is needed.
1396
0
  if (this->Makefile->IsOn("CMAKE_SKIP_RPATH")) {
1397
0
    return false;
1398
0
  }
1399
1400
  // If building with the install-tree rpath no relinking is needed.
1401
0
  if (this->GetPropertyAsBool("BUILD_WITH_INSTALL_RPATH")) {
1402
0
    return false;
1403
0
  }
1404
1405
  // If chrpath is going to be used no relinking is needed.
1406
0
  if (this->IsChrpathUsed(config)) {
1407
0
    return false;
1408
0
  }
1409
1410
  // Check for rpath support on this platform.
1411
0
  std::string ll = this->GetLinkerLanguage(config);
1412
0
  if (!ll.empty()) {
1413
0
    std::string flagVar =
1414
0
      cmStrCat("CMAKE_SHARED_LIBRARY_RUNTIME_", ll, "_FLAG");
1415
0
    if (!this->Makefile->IsSet(flagVar)) {
1416
      // There is no rpath support on this platform so nothing needs
1417
      // relinking.
1418
0
      return false;
1419
0
    }
1420
0
  } else {
1421
    // No linker language is known.  This error will be reported by
1422
    // other code.
1423
0
    return false;
1424
0
  }
1425
1426
  // If either a build or install tree rpath is set then the rpath
1427
  // will likely change between the build tree and install tree and
1428
  // this target must be relinked.
1429
0
  bool have_rpath =
1430
0
    this->HaveBuildTreeRPATH(config) || this->HaveInstallTreeRPATH(config);
1431
0
  bool is_ninja = this->LocalGenerator->GetGlobalGenerator()->IsNinja();
1432
1433
0
  if (have_rpath && is_ninja) {
1434
0
    std::ostringstream w;
1435
    /* clang-format off */
1436
0
    w <<
1437
0
      "The install of the " << this->GetName() << " target requires changing "
1438
0
      "an RPATH from the build tree, but this is not supported with the Ninja "
1439
0
      "generator unless on an ELF-based or XCOFF-based platform.  "
1440
0
      "The CMAKE_BUILD_WITH_INSTALL_RPATH variable may be set to avoid this "
1441
0
      "relinking step."
1442
0
      ;
1443
    /* clang-format on */
1444
1445
0
    cmake* cm = this->LocalGenerator->GetCMakeInstance();
1446
0
    cm->IssueMessage(MessageType::FATAL_ERROR, w.str(), this->GetBacktrace());
1447
0
  }
1448
1449
0
  return have_rpath;
1450
0
}
1451
1452
bool cmGeneratorTarget::IsChrpathUsed(std::string const& config) const
1453
0
{
1454
  // Only certain target types have an rpath.
1455
0
  if (!(this->GetType() == cm::TargetType::SHARED_LIBRARY ||
1456
0
        this->GetType() == cm::TargetType::MODULE_LIBRARY ||
1457
0
        this->GetType() == cm::TargetType::EXECUTABLE)) {
1458
0
    return false;
1459
0
  }
1460
1461
  // If the target will not be installed we do not need to change its
1462
  // rpath.
1463
0
  if (!this->Target->GetHaveInstallRule()) {
1464
0
    return false;
1465
0
  }
1466
1467
  // Skip chrpath if skipping rpath altogether.
1468
0
  if (this->Makefile->IsOn("CMAKE_SKIP_RPATH")) {
1469
0
    return false;
1470
0
  }
1471
1472
  // Skip chrpath if it does not need to be changed at install time.
1473
0
  if (this->GetPropertyAsBool("BUILD_WITH_INSTALL_RPATH")) {
1474
0
    return false;
1475
0
  }
1476
1477
  // Allow the user to disable builtin chrpath explicitly.
1478
0
  if (this->Makefile->IsOn("CMAKE_NO_BUILTIN_CHRPATH")) {
1479
0
    return false;
1480
0
  }
1481
1482
0
  if (this->Makefile->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
1483
0
    return true;
1484
0
  }
1485
1486
  // Enable if the rpath flag uses a separator and the target uses
1487
  // binaries we know how to edit.
1488
0
  std::string ll = this->GetLinkerLanguage(config);
1489
0
  if (!ll.empty()) {
1490
0
    std::string sepVar =
1491
0
      cmStrCat("CMAKE_SHARED_LIBRARY_RUNTIME_", ll, "_FLAG_SEP");
1492
0
    cmValue sep = this->Makefile->GetDefinition(sepVar);
1493
0
    if (cmNonempty(sep)) {
1494
      // TODO: Add binary format check to ABI detection and get rid of
1495
      // CMAKE_EXECUTABLE_FORMAT.
1496
0
      if (cmValue fmt =
1497
0
            this->Makefile->GetDefinition("CMAKE_EXECUTABLE_FORMAT")) {
1498
0
        if (*fmt == "ELF") {
1499
0
          return true;
1500
0
        }
1501
#if defined(CMake_USE_XCOFF_PARSER)
1502
        if (*fmt == "XCOFF") {
1503
          return true;
1504
        }
1505
#endif
1506
0
      }
1507
0
    }
1508
0
  }
1509
0
  return false;
1510
0
}
1511
1512
bool cmGeneratorTarget::IsImportedSharedLibWithoutSOName(
1513
  std::string const& config) const
1514
0
{
1515
0
  if (this->IsImported() &&
1516
0
      this->GetType() == cm::TargetType::SHARED_LIBRARY) {
1517
0
    if (cmGeneratorTarget::ImportInfo const* info =
1518
0
          this->GetImportInfo(config)) {
1519
0
      return info->NoSOName;
1520
0
    }
1521
0
  }
1522
0
  return false;
1523
0
}
1524
1525
bool cmGeneratorTarget::HasMacOSXRpathInstallNameDir(
1526
  std::string const& config) const
1527
0
{
1528
0
  TargetPtrToBoolMap& cache = this->MacOSXRpathInstallNameDirCache[config];
1529
0
  auto const lookup = cache.find(this->Target);
1530
1531
0
  if (lookup != cache.cend()) {
1532
0
    return lookup->second;
1533
0
  }
1534
1535
0
  bool const result = this->DetermineHasMacOSXRpathInstallNameDir(config);
1536
0
  cache[this->Target] = result;
1537
0
  return result;
1538
0
}
1539
1540
bool cmGeneratorTarget::DetermineHasMacOSXRpathInstallNameDir(
1541
  std::string const& config) const
1542
0
{
1543
0
  bool install_name_is_rpath = false;
1544
0
  bool macosx_rpath = false;
1545
1546
0
  if (!this->IsImported()) {
1547
0
    if (this->GetType() != cm::TargetType::SHARED_LIBRARY) {
1548
0
      return false;
1549
0
    }
1550
0
    cmValue install_name = this->GetProperty("INSTALL_NAME_DIR");
1551
0
    bool use_install_name = this->MacOSXUseInstallNameDir();
1552
0
    if (install_name && use_install_name && *install_name == "@rpath") {
1553
0
      install_name_is_rpath = true;
1554
0
    } else if (install_name && use_install_name) {
1555
0
      return false;
1556
0
    }
1557
0
    if (!install_name_is_rpath) {
1558
0
      macosx_rpath = this->MacOSXRpathInstallNameDirDefault();
1559
0
    }
1560
0
  } else {
1561
    // Lookup the imported soname.
1562
0
    if (cmGeneratorTarget::ImportInfo const* info =
1563
0
          this->GetImportInfo(config)) {
1564
0
      if (!info->NoSOName && !info->SOName.empty()) {
1565
0
        if (cmHasLiteralPrefix(info->SOName, "@rpath/")) {
1566
0
          install_name_is_rpath = true;
1567
0
        }
1568
0
      } else {
1569
0
        std::string install_name;
1570
0
        cmSystemTools::GuessLibraryInstallName(info->Location, install_name);
1571
0
        if (install_name.find("@rpath") != std::string::npos) {
1572
0
          install_name_is_rpath = true;
1573
0
        }
1574
0
      }
1575
0
    }
1576
0
  }
1577
1578
0
  if (!install_name_is_rpath && !macosx_rpath) {
1579
0
    return false;
1580
0
  }
1581
1582
0
  if (!this->Makefile->IsSet("CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG")) {
1583
0
    std::ostringstream w;
1584
0
    w << "Attempting to use ";
1585
0
    if (macosx_rpath) {
1586
0
      w << "MACOSX_RPATH";
1587
0
    } else {
1588
0
      w << "@rpath";
1589
0
    }
1590
0
    w << " without CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG being set.";
1591
0
    w << "  This could be because you are using a Mac OS X version";
1592
0
    w << " less than 10.5 or because CMake's platform configuration is";
1593
0
    w << " corrupt.";
1594
0
    cmake* cm = this->LocalGenerator->GetCMakeInstance();
1595
0
    cm->IssueMessage(MessageType::FATAL_ERROR, w.str(), this->GetBacktrace());
1596
0
  }
1597
1598
0
  return true;
1599
0
}
1600
1601
bool cmGeneratorTarget::MacOSXRpathInstallNameDirDefault() const
1602
0
{
1603
  // we can't do rpaths when unsupported
1604
0
  if (!this->Makefile->IsSet("CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG")) {
1605
0
    return false;
1606
0
  }
1607
1608
0
  cmValue macosx_rpath_str = this->GetProperty("MACOSX_RPATH");
1609
0
  if (macosx_rpath_str) {
1610
0
    return this->GetPropertyAsBool("MACOSX_RPATH");
1611
0
  }
1612
1613
0
  return true;
1614
0
}
1615
1616
bool cmGeneratorTarget::MacOSXUseInstallNameDir() const
1617
0
{
1618
0
  cmValue build_with_install_name =
1619
0
    this->GetProperty("BUILD_WITH_INSTALL_NAME_DIR");
1620
0
  if (build_with_install_name) {
1621
0
    return build_with_install_name.IsOn();
1622
0
  }
1623
1624
0
  cmPolicies::PolicyStatus cmp0068 = this->GetPolicyStatusCMP0068();
1625
0
  if (cmp0068 == cmPolicies::NEW) {
1626
0
    return false;
1627
0
  }
1628
1629
0
  bool use_install_name = this->GetPropertyAsBool("BUILD_WITH_INSTALL_RPATH");
1630
1631
0
  if (use_install_name && cmp0068 == cmPolicies::WARN) {
1632
0
    this->LocalGenerator->GetGlobalGenerator()->AddCMP0068WarnTarget(
1633
0
      this->GetName());
1634
0
  }
1635
1636
0
  return use_install_name;
1637
0
}
1638
1639
bool cmGeneratorTarget::CanGenerateInstallNameDir(
1640
  InstallNameType name_type) const
1641
0
{
1642
0
  cmPolicies::PolicyStatus cmp0068 = this->GetPolicyStatusCMP0068();
1643
1644
0
  if (cmp0068 == cmPolicies::NEW) {
1645
0
    return true;
1646
0
  }
1647
1648
0
  bool skip = this->Makefile->IsOn("CMAKE_SKIP_RPATH");
1649
0
  if (name_type == INSTALL_NAME_FOR_INSTALL) {
1650
0
    skip |= this->Makefile->IsOn("CMAKE_SKIP_INSTALL_RPATH");
1651
0
  } else {
1652
0
    skip |= this->GetPropertyAsBool("SKIP_BUILD_RPATH");
1653
0
  }
1654
1655
0
  if (skip && cmp0068 == cmPolicies::WARN) {
1656
0
    this->LocalGenerator->GetGlobalGenerator()->AddCMP0068WarnTarget(
1657
0
      this->GetName());
1658
0
  }
1659
1660
0
  return !skip;
1661
0
}
1662
1663
std::string cmGeneratorTarget::GetSOName(
1664
  std::string const& config, cmStateEnums::ArtifactType artifact) const
1665
0
{
1666
0
  if (this->IsImported()) {
1667
    // Lookup the imported soname.
1668
0
    if (cmGeneratorTarget::ImportInfo const* info =
1669
0
          this->GetImportInfo(config)) {
1670
0
      if (info->NoSOName) {
1671
        // The imported library has no builtin soname so the name
1672
        // searched at runtime will be just the filename.
1673
0
        return cmSystemTools::GetFilenameName(info->Location);
1674
0
      }
1675
      // Use the soname given if any.
1676
0
      if (this->IsFrameworkOnApple()) {
1677
0
        auto fwDescriptor = this->GetGlobalGenerator()->SplitFrameworkPath(
1678
0
          info->SOName, cmGlobalGenerator::FrameworkFormat::Strict);
1679
0
        if (fwDescriptor) {
1680
0
          return fwDescriptor->GetVersionedName();
1681
0
        }
1682
0
      }
1683
0
      if (cmHasLiteralPrefix(info->SOName, "@rpath/")) {
1684
0
        return info->SOName.substr(cmStrLen("@rpath/"));
1685
0
      }
1686
0
      return info->SOName;
1687
0
    }
1688
0
    return "";
1689
0
  }
1690
  // Compute the soname that will be built.
1691
0
  return artifact == cmStateEnums::RuntimeBinaryArtifact
1692
0
    ? this->GetLibraryNames(config).SharedObject
1693
0
    : this->GetLibraryNames(config).ImportLibrary;
1694
0
}
1695
1696
namespace {
1697
bool shouldAddFullLevel(cmGeneratorTarget::BundleDirectoryLevel level)
1698
0
{
1699
0
  return level == cmGeneratorTarget::FullLevel;
1700
0
}
1701
1702
bool shouldAddContentLevel(cmGeneratorTarget::BundleDirectoryLevel level)
1703
0
{
1704
0
  return level == cmGeneratorTarget::ContentLevel || shouldAddFullLevel(level);
1705
0
}
1706
}
1707
1708
std::string cmGeneratorTarget::GetAppBundleDirectory(
1709
  std::string const& config, BundleDirectoryLevel level) const
1710
0
{
1711
0
  std::string fpath = cmStrCat(
1712
0
    this->GetFullName(config, cmStateEnums::RuntimeBinaryArtifact), '.');
1713
0
  cmValue ext = this->GetProperty("BUNDLE_EXTENSION");
1714
0
  fpath += (ext ? *ext : "app");
1715
0
  if (shouldAddContentLevel(level) &&
1716
0
      !this->Makefile->PlatformIsAppleEmbedded()) {
1717
0
    fpath += "/Contents";
1718
0
    if (shouldAddFullLevel(level)) {
1719
0
      fpath += "/MacOS";
1720
0
    }
1721
0
  }
1722
0
  return fpath;
1723
0
}
1724
1725
bool cmGeneratorTarget::IsBundleOnApple() const
1726
0
{
1727
0
  return this->IsFrameworkOnApple() || this->IsAppBundleOnApple() ||
1728
0
    this->IsCFBundleOnApple();
1729
0
}
1730
1731
bool cmGeneratorTarget::IsWin32Executable(std::string const& config) const
1732
0
{
1733
0
  return cmIsOn(cmGeneratorExpression::Evaluate(
1734
0
    this->GetSafeProperty("WIN32_EXECUTABLE"), this->LocalGenerator, config));
1735
0
}
1736
1737
std::string cmGeneratorTarget::GetCFBundleDirectory(
1738
  std::string const& config, BundleDirectoryLevel level) const
1739
0
{
1740
0
  std::string fpath = cmStrCat(
1741
0
    this->GetOutputName(config, cmStateEnums::RuntimeBinaryArtifact), '.');
1742
0
  std::string ext;
1743
0
  if (cmValue p = this->GetProperty("BUNDLE_EXTENSION")) {
1744
0
    ext = *p;
1745
0
  } else {
1746
0
    if (this->IsXCTestOnApple()) {
1747
0
      ext = "xctest";
1748
0
    } else {
1749
0
      ext = "bundle";
1750
0
    }
1751
0
  }
1752
0
  fpath += ext;
1753
0
  if (shouldAddContentLevel(level) &&
1754
0
      !this->Makefile->PlatformIsAppleEmbedded()) {
1755
0
    fpath += "/Contents";
1756
0
    if (shouldAddFullLevel(level)) {
1757
0
      fpath += "/MacOS";
1758
0
    }
1759
0
  }
1760
0
  return fpath;
1761
0
}
1762
1763
std::string cmGeneratorTarget::GetFrameworkDirectory(
1764
  std::string const& config, BundleDirectoryLevel level) const
1765
0
{
1766
0
  std::string fpath = cmStrCat(
1767
0
    this->GetOutputName(config, cmStateEnums::RuntimeBinaryArtifact), '.');
1768
0
  cmValue ext = this->GetProperty("BUNDLE_EXTENSION");
1769
0
  fpath += (ext ? *ext : "framework");
1770
0
  if (shouldAddFullLevel(level) &&
1771
0
      !this->Makefile->PlatformIsAppleEmbedded()) {
1772
0
    fpath =
1773
0
      cmStrCat(std::move(fpath), "/Versions/", this->GetFrameworkVersion());
1774
0
  }
1775
0
  return fpath;
1776
0
}
1777
1778
std::string cmGeneratorTarget::GetFullName(
1779
  std::string const& config, cmStateEnums::ArtifactType artifact) const
1780
0
{
1781
0
  if (this->IsImported()) {
1782
0
    return this->GetFullNameImported(config, artifact);
1783
0
  }
1784
0
  return this->GetFullNameInternal(config, artifact);
1785
0
}
1786
1787
std::string cmGeneratorTarget::GetInstallNameDirForBuildTree(
1788
  std::string const& config) const
1789
0
{
1790
0
  if (this->Makefile->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
1791
1792
    // If building directly for installation then the build tree install_name
1793
    // is the same as the install tree.
1794
0
    if (this->MacOSXUseInstallNameDir()) {
1795
0
      std::string installPrefix =
1796
0
        this->Makefile->GetSafeDefinition("CMAKE_INSTALL_PREFIX");
1797
0
      return this->GetInstallNameDirForInstallTree(config, installPrefix);
1798
0
    }
1799
1800
    // Use the build tree directory for the target.
1801
0
    if (this->CanGenerateInstallNameDir(INSTALL_NAME_FOR_BUILD)) {
1802
0
      std::string dir;
1803
0
      if (this->MacOSXRpathInstallNameDirDefault()) {
1804
0
        dir = "@rpath";
1805
0
      } else {
1806
0
        dir = this->GetDirectory(config);
1807
0
      }
1808
0
      dir += '/';
1809
0
      return dir;
1810
0
    }
1811
0
  }
1812
0
  return "";
1813
0
}
1814
1815
std::string cmGeneratorTarget::GetInstallNameDirForInstallTree(
1816
  std::string const& config, std::string const& installPrefix) const
1817
0
{
1818
0
  if (this->Makefile->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
1819
0
    std::string dir;
1820
0
    cmValue install_name_dir = this->GetProperty("INSTALL_NAME_DIR");
1821
1822
0
    if (this->CanGenerateInstallNameDir(INSTALL_NAME_FOR_INSTALL)) {
1823
0
      if (cmNonempty(install_name_dir)) {
1824
0
        dir = *install_name_dir;
1825
0
        cmGeneratorExpression::ReplaceInstallPrefix(dir, installPrefix);
1826
0
        dir =
1827
0
          cmGeneratorExpression::Evaluate(dir, this->LocalGenerator, config);
1828
0
        if (!dir.empty()) {
1829
0
          dir = cmStrCat(dir, '/');
1830
0
        }
1831
0
      }
1832
0
    }
1833
0
    if (!install_name_dir) {
1834
0
      if (this->MacOSXRpathInstallNameDirDefault()) {
1835
0
        dir = "@rpath/";
1836
0
      }
1837
0
    }
1838
0
    return dir;
1839
0
  }
1840
0
  return "";
1841
0
}
1842
1843
cmListFileBacktrace cmGeneratorTarget::GetBacktrace() const
1844
0
{
1845
0
  return this->Target->GetBacktrace();
1846
0
}
1847
1848
std::set<BT<std::pair<std::string, bool>>> const&
1849
cmGeneratorTarget::GetUtilities() const
1850
0
{
1851
0
  return this->Target->GetUtilities();
1852
0
}
1853
1854
bool cmGeneratorTarget::HaveWellDefinedOutputFiles() const
1855
0
{
1856
0
  return this->GetType() == cm::TargetType::STATIC_LIBRARY ||
1857
0
    this->GetType() == cm::TargetType::SHARED_LIBRARY ||
1858
0
    this->GetType() == cm::TargetType::MODULE_LIBRARY ||
1859
0
    this->GetType() == cm::TargetType::OBJECT_LIBRARY ||
1860
0
    this->GetType() == cm::TargetType::EXECUTABLE;
1861
0
}
1862
1863
std::string const* cmGeneratorTarget::GetExportMacro() const
1864
0
{
1865
  // Define the symbol for targets that export symbols.
1866
0
  if (this->GetType() == cm::TargetType::SHARED_LIBRARY ||
1867
0
      this->GetType() == cm::TargetType::MODULE_LIBRARY ||
1868
0
      this->IsExecutableWithExports()) {
1869
0
    if (cmValue custom_export_name = this->GetProperty("DEFINE_SYMBOL")) {
1870
0
      this->ExportMacro = *custom_export_name;
1871
0
    } else {
1872
0
      std::string in = cmStrCat(this->GetName(), "_EXPORTS");
1873
0
      this->ExportMacro = cmSystemTools::MakeCidentifier(in);
1874
0
    }
1875
0
    return &this->ExportMacro;
1876
0
  }
1877
0
  return nullptr;
1878
0
}
1879
1880
cmList const& cmGeneratorTarget::GetSharedLibraryCompileDefs(
1881
  std::string const& config) const
1882
0
{
1883
0
  {
1884
0
    auto it = this->SharedLibraryCompileDefs.find(config);
1885
0
    if (it != this->SharedLibraryCompileDefs.end()) {
1886
0
      return it->second;
1887
0
    }
1888
0
  }
1889
1890
0
  auto emplaceResult =
1891
0
    this->SharedLibraryCompileDefs.emplace(config, cmList{});
1892
0
  auto& defs = emplaceResult.first->second;
1893
0
  if (this->GetType() != cm::TargetType::SHARED_LIBRARY &&
1894
0
      this->GetType() != cm::TargetType::MODULE_LIBRARY) {
1895
0
    return defs;
1896
0
  }
1897
1898
0
  if (this->GetPolicyStatusCMP0203() != cmPolicies::NEW) {
1899
0
    return defs;
1900
0
  }
1901
1902
0
  auto linkerLang = this->GetLinkerLanguage(config);
1903
0
  auto definitionVar =
1904
0
    cmStrCat("CMAKE_", linkerLang, "_SHARED_LIBRARY_COMPILE_DEFINITIONS");
1905
0
  defs = this->Makefile->GetSafeDefinition(definitionVar);
1906
1907
0
  return defs;
1908
0
}
1909
1910
cmGeneratorTarget::NameComponents const&
1911
cmGeneratorTarget::GetFullNameComponents(
1912
  std::string const& config, cmStateEnums::ArtifactType artifact) const
1913
0
{
1914
0
  return this->GetFullNameInternalComponents(config, artifact);
1915
0
}
1916
1917
std::string cmGeneratorTarget::BuildBundleDirectory(
1918
  std::string const& base, std::string const& config,
1919
  BundleDirectoryLevel level) const
1920
0
{
1921
0
  std::string fpath = base;
1922
0
  if (this->IsAppBundleOnApple()) {
1923
0
    fpath += this->GetAppBundleDirectory(config, level);
1924
0
  }
1925
0
  if (this->IsFrameworkOnApple()) {
1926
0
    fpath += this->GetFrameworkDirectory(config, level);
1927
0
  }
1928
0
  if (this->IsCFBundleOnApple()) {
1929
0
    fpath += this->GetCFBundleDirectory(config, level);
1930
0
  }
1931
0
  return fpath;
1932
0
}
1933
1934
std::string cmGeneratorTarget::GetMacContentDirectory(
1935
  std::string const& config, cmStateEnums::ArtifactType artifact) const
1936
0
{
1937
  // Start with the output directory for the target.
1938
0
  std::string fpath = cmStrCat(this->GetDirectory(config, artifact), '/');
1939
0
  BundleDirectoryLevel level = ContentLevel;
1940
0
  if (this->IsFrameworkOnApple()) {
1941
    // additional files with a framework go into the version specific
1942
    // directory
1943
0
    level = FullLevel;
1944
0
  }
1945
0
  fpath = this->BuildBundleDirectory(fpath, config, level);
1946
0
  return fpath;
1947
0
}
1948
1949
std::string cmGeneratorTarget::GetEffectiveFolderName() const
1950
0
{
1951
0
  std::string effectiveFolder;
1952
1953
0
  if (!this->GlobalGenerator->UseFolderProperty()) {
1954
0
    return effectiveFolder;
1955
0
  }
1956
1957
0
  cmValue targetFolder = this->GetProperty("FOLDER");
1958
0
  if (targetFolder) {
1959
0
    effectiveFolder += *targetFolder;
1960
0
  }
1961
1962
0
  return effectiveFolder;
1963
0
}
1964
1965
cmGeneratorTarget::CompileInfo const* cmGeneratorTarget::GetCompileInfo(
1966
  std::string const& config) const
1967
0
{
1968
  // There is no compile information for imported targets.
1969
0
  if (this->IsImported()) {
1970
0
    return nullptr;
1971
0
  }
1972
1973
0
  if (this->GetType() > cm::TargetType::OBJECT_LIBRARY) {
1974
0
    std::string msg = cmStrCat("cmTarget::GetCompileInfo called for ",
1975
0
                               this->GetName(), " which has type ",
1976
0
                               cmState::GetTargetTypeName(this->GetType()));
1977
0
    this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
1978
0
    return nullptr;
1979
0
  }
1980
1981
  // Lookup/compute/cache the compile information for this configuration.
1982
0
  std::string config_upper;
1983
0
  if (!config.empty()) {
1984
0
    config_upper = cmSystemTools::UpperCase(config);
1985
0
  }
1986
0
  auto i = this->CompileInfoMap.find(config_upper);
1987
0
  if (i == this->CompileInfoMap.end()) {
1988
0
    CompileInfo info;
1989
0
    this->ComputePDBOutputDir("COMPILE_PDB", config, info.CompilePdbDir);
1990
0
    CompileInfoMapType::value_type entry(config_upper, info);
1991
0
    i = this->CompileInfoMap.insert(entry).first;
1992
0
  }
1993
0
  return &i->second;
1994
0
}
1995
1996
cmGeneratorTarget::ModuleDefinitionInfo const*
1997
cmGeneratorTarget::GetModuleDefinitionInfo(std::string const& config) const
1998
0
{
1999
  // A module definition file only makes sense on certain target types.
2000
0
  if (this->GetType() != cm::TargetType::SHARED_LIBRARY &&
2001
0
      this->GetType() != cm::TargetType::MODULE_LIBRARY &&
2002
0
      !this->IsExecutableWithExports()) {
2003
0
    return nullptr;
2004
0
  }
2005
2006
  // Lookup/compute/cache the compile information for this configuration.
2007
0
  std::string config_upper;
2008
0
  if (!config.empty()) {
2009
0
    config_upper = cmSystemTools::UpperCase(config);
2010
0
  }
2011
0
  auto i = this->ModuleDefinitionInfoMap.find(config_upper);
2012
0
  if (i == this->ModuleDefinitionInfoMap.end()) {
2013
0
    ModuleDefinitionInfo info;
2014
0
    this->ComputeModuleDefinitionInfo(config, info);
2015
0
    ModuleDefinitionInfoMapType::value_type entry(config_upper, info);
2016
0
    i = this->ModuleDefinitionInfoMap.insert(entry).first;
2017
0
  }
2018
0
  return &i->second;
2019
0
}
2020
2021
void cmGeneratorTarget::ComputeModuleDefinitionInfo(
2022
  std::string const& config, ModuleDefinitionInfo& info) const
2023
0
{
2024
0
  this->GetModuleDefinitionSources(info.Sources, config);
2025
0
  info.WindowsExportAllSymbols =
2026
0
    this->Makefile->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS") &&
2027
0
    this->GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS");
2028
0
#if !defined(CMAKE_BOOTSTRAP)
2029
0
  info.DefFileGenerated =
2030
0
    info.WindowsExportAllSymbols || info.Sources.size() > 1;
2031
#else
2032
  // Our __create_def helper is not available during CMake bootstrap.
2033
  info.DefFileGenerated = false;
2034
#endif
2035
0
  if (info.DefFileGenerated) {
2036
0
    info.DefFile =
2037
0
      this->GetObjectDirectory(config) /* has slash */ + "exports.def";
2038
0
  } else if (!info.Sources.empty()) {
2039
0
    info.DefFile = info.Sources.front()->GetFullPath();
2040
0
  }
2041
0
}
2042
2043
bool cmGeneratorTarget::IsAIX() const
2044
0
{
2045
0
  return this->Target->IsAIX();
2046
0
}
2047
2048
bool cmGeneratorTarget::IsApple() const
2049
0
{
2050
0
  return this->Target->IsApple();
2051
0
}
2052
2053
bool cmGeneratorTarget::IsDLLPlatform() const
2054
0
{
2055
0
  return this->Target->IsDLLPlatform();
2056
0
}
2057
2058
void cmGeneratorTarget::GetAutoUicOptions(std::vector<std::string>& result,
2059
                                          std::string const& config) const
2060
0
{
2061
0
  char const* prop =
2062
0
    this->GetLinkInterfaceDependentStringProperty("AUTOUIC_OPTIONS", config);
2063
0
  if (!prop) {
2064
0
    return;
2065
0
  }
2066
2067
0
  cm::GenEx::Context context(this->LocalGenerator, config);
2068
0
  cmGeneratorExpressionDAGChecker dagChecker{
2069
0
    this, "AUTOUIC_OPTIONS", nullptr, nullptr, context,
2070
0
  };
2071
0
  cmExpandList(cmGeneratorExpression::Evaluate(
2072
0
                 prop, context.LG, context.Config, this, &dagChecker),
2073
0
               result);
2074
0
}
2075
2076
void cmGeneratorTarget::TraceDependencies()
2077
0
{
2078
  // CMake-generated targets have no dependencies to trace.  Normally tracing
2079
  // would find nothing anyway, but when building CMake itself the "install"
2080
  // target command ends up referencing the "cmake" target but we do not
2081
  // really want the dependency because "install" depend on "all" anyway.
2082
0
  if (this->GetType() == cm::TargetType::GLOBAL_TARGET) {
2083
0
    return;
2084
0
  }
2085
2086
  // Use a helper object to trace the dependencies.
2087
0
  cmTargetTraceDependencies tracer(this);
2088
0
  tracer.Trace();
2089
0
}
2090
2091
std::string cmGeneratorTarget::GetCompilePDBDirectory(
2092
  std::string const& config) const
2093
0
{
2094
0
  if (CompileInfo const* info = this->GetCompileInfo(config)) {
2095
0
    return info->CompilePdbDir;
2096
0
  }
2097
0
  return "";
2098
0
}
2099
2100
std::vector<std::string> cmGeneratorTarget::GetAppleArchs(
2101
  std::string const& config, cm::optional<std::string> lang) const
2102
0
{
2103
0
  cmList archList;
2104
0
  if (!this->IsApple()) {
2105
0
    return std::move(archList.data());
2106
0
  }
2107
0
  cmValue archs = nullptr;
2108
0
  if (!config.empty()) {
2109
0
    std::string defVarName =
2110
0
      cmStrCat("OSX_ARCHITECTURES_", cmSystemTools::UpperCase(config));
2111
0
    archs = this->GetProperty(defVarName);
2112
0
  }
2113
0
  if (!archs) {
2114
0
    archs = this->GetProperty("OSX_ARCHITECTURES");
2115
0
  }
2116
0
  if (archs) {
2117
0
    archList.assign(*archs);
2118
0
  }
2119
0
  if (archList.empty() &&
2120
      // Fall back to a default architecture if no compiler target is set.
2121
0
      (!lang ||
2122
0
       this->Makefile
2123
0
         ->GetDefinition(cmStrCat("CMAKE_", *lang, "_COMPILER_TARGET"))
2124
0
         .IsEmpty())) {
2125
0
    archList.assign(
2126
0
      this->Makefile->GetDefinition("_CMAKE_APPLE_ARCHS_DEFAULT"));
2127
0
  }
2128
0
  return std::move(archList.data());
2129
0
}
2130
2131
namespace {
2132
2133
bool IsSupportedClassifiedFlagsLanguage(std::string const& lang)
2134
0
{
2135
0
  return lang == "CXX"_s;
2136
0
}
2137
2138
bool CanUseCompilerLauncher(std::string const& lang)
2139
0
{
2140
  // Also found in `cmCommonTargetGenerator::GetCompilerLauncher`.
2141
0
  return lang == "C"_s || lang == "CXX"_s || lang == "Fortran"_s ||
2142
0
    lang == "CUDA"_s || lang == "HIP"_s || lang == "ISPC"_s ||
2143
0
    lang == "OBJC"_s || lang == "OBJCXX"_s;
2144
0
}
2145
2146
// FIXME: return a vector of `cm::string_view` instead to avoid lots of tiny
2147
// allocations.
2148
std::vector<std::string> SplitFlags(std::string const& flags)
2149
0
{
2150
0
  std::vector<std::string> options;
2151
2152
#ifdef _WIN32
2153
  cmSystemTools::ParseWindowsCommandLine(flags.c_str(), options);
2154
#else
2155
0
  cmSystemTools::ParseUnixCommandLine(flags.c_str(), options);
2156
0
#endif
2157
2158
0
  return options;
2159
0
}
2160
2161
}
2162
2163
cmGeneratorTarget::ClassifiedFlags
2164
cmGeneratorTarget::GetClassifiedFlagsForSource(cmSourceFile const* sf,
2165
                                               std::string const& config)
2166
0
{
2167
0
  auto& sourceFlagsCache = this->Configs[config].SourceFlags;
2168
0
  auto cacheEntry = sourceFlagsCache.lower_bound(sf);
2169
0
  if (cacheEntry != sourceFlagsCache.end() && cacheEntry->first == sf) {
2170
0
    return cacheEntry->second;
2171
0
  }
2172
2173
0
  ClassifiedFlags flags;
2174
0
  std::string const& lang = sf->GetLanguage();
2175
2176
0
  if (!IsSupportedClassifiedFlagsLanguage(lang)) {
2177
0
    return flags;
2178
0
  }
2179
2180
0
  auto* const lg = this->GetLocalGenerator();
2181
0
  auto const* const mf = this->Makefile;
2182
0
  cmGeneratorFileSet const* const fileSet =
2183
0
    this->GetFileSetForSource(config, sf);
2184
2185
  // Compute the compiler launcher flags.
2186
0
  if (CanUseCompilerLauncher(lang)) {
2187
    // Compiler launchers are all execution flags and should not be relevant to
2188
    // the actual compilation.
2189
0
    FlagClassification cls = FlagClassification::ExecutionFlag;
2190
0
    FlagKind kind = FlagKind::NotAFlag;
2191
2192
0
    std::string const clauncher_prop = cmStrCat(lang, "_COMPILER_LAUNCHER");
2193
0
    cmValue clauncher = this->GetProperty(clauncher_prop);
2194
0
    std::string const evaluatedClauncher = cmGeneratorExpression::Evaluate(
2195
0
      *clauncher, lg, config, this, nullptr, this, lang);
2196
2197
0
    for (auto const& flag : SplitFlags(evaluatedClauncher)) {
2198
0
      flags.emplace_back(cls, kind, flag);
2199
0
    }
2200
0
  }
2201
2202
0
  ClassifiedFlags define_flags;
2203
0
  ClassifiedFlags include_flags;
2204
0
  ClassifiedFlags compile_flags;
2205
2206
0
  SourceVariables sfVars = this->GetSourceVariables(sf, config);
2207
2208
  // Compute language flags.
2209
0
  {
2210
0
    FlagClassification cls = FlagClassification::BaselineFlag;
2211
0
    FlagKind kind = FlagKind::Compile;
2212
2213
0
    std::string mfFlags;
2214
    // Explicitly add the explicit language flag before any other flag
2215
    // so user flags can override it.
2216
0
    this->AddExplicitLanguageFlags(mfFlags, *sf);
2217
2218
0
    for (auto const& flag : SplitFlags(mfFlags)) {
2219
0
      flags.emplace_back(cls, kind, flag);
2220
0
    }
2221
0
  }
2222
2223
0
  std::unordered_map<std::string, std::string> pchSources;
2224
0
  std::string filterArch;
2225
2226
0
  {
2227
0
    std::vector<std::string> pchArchs = this->GetPchArchs(config, lang);
2228
2229
0
    for (std::string const& arch : pchArchs) {
2230
0
      std::string const pchSource = this->GetPchSource(config, lang, arch);
2231
0
      if (pchSource == sf->GetFullPath()) {
2232
0
        filterArch = arch;
2233
0
      }
2234
0
      if (!pchSource.empty()) {
2235
0
        pchSources.insert(std::make_pair(pchSource, arch));
2236
0
      }
2237
0
    }
2238
0
  }
2239
2240
  // File set specific flags
2241
0
  if (fileSet) {
2242
    // include flags
2243
0
    {
2244
0
      auto fsIncludes = fileSet->BelongsTo(this)
2245
0
        ? fileSet->GetIncludeDirectories(config, lang)
2246
0
        : fileSet->GetInterfaceIncludeDirectories(config, lang);
2247
0
      if (!fsIncludes.empty()) {
2248
0
        std::vector<std::string> includes;
2249
0
        lg->AppendIncludeDirectories(includes, cm::remove_BT(fsIncludes), *sf);
2250
2251
0
        auto includeFlags =
2252
0
          lg->GetIncludeFlags(includes, this, lang, config, false);
2253
2254
0
        for (auto&& flag : SplitFlags(includeFlags)) {
2255
0
          include_flags.emplace_back(FlagClassification::PrivateFlag,
2256
0
                                     FlagKind::Include, std::move(flag));
2257
0
        }
2258
0
      }
2259
0
    }
2260
0
  }
2261
2262
  // source specific flags
2263
0
  {
2264
    // include flags
2265
0
    if (cmValue srcIncludes = sf->GetProperty("INCLUDE_DIRECTORIES")) {
2266
0
      std::vector<std::string> includes;
2267
0
      lg->AppendIncludeDirectories(includes, srcIncludes, *sf);
2268
2269
0
      auto includeFlags =
2270
0
        lg->GetIncludeFlags(includes, this, lang, config, false);
2271
2272
0
      for (auto&& flag : SplitFlags(includeFlags)) {
2273
0
        include_flags.emplace_back(FlagClassification::PrivateFlag,
2274
0
                                   FlagKind::Include, std::move(flag));
2275
0
      }
2276
0
    }
2277
0
  }
2278
2279
  // Compute target-wide flags.
2280
0
  {
2281
0
    FlagClassification cls = FlagClassification::BaselineFlag;
2282
2283
    // Compile flags
2284
0
    {
2285
0
      FlagKind kind = FlagKind::Compile;
2286
0
      std::string targetFlags;
2287
2288
0
      lg->GetTargetCompileFlags(this, config, lang, targetFlags, filterArch);
2289
2290
0
      for (auto&& flag : SplitFlags(targetFlags)) {
2291
0
        compile_flags.emplace_back(cls, kind, std::move(flag));
2292
0
      }
2293
0
    }
2294
2295
    // Define flags
2296
0
    {
2297
0
      FlagKind kind = FlagKind::Definition;
2298
0
      std::set<std::string> defines;
2299
2300
0
      lg->GetTargetDefines(this, config, lang, defines);
2301
2302
0
      std::string defineFlags;
2303
0
      lg->JoinDefines(defines, defineFlags, lang);
2304
2305
0
      for (auto&& flag : SplitFlags(defineFlags)) {
2306
0
        define_flags.emplace_back(cls, kind, std::move(flag));
2307
0
      }
2308
0
    }
2309
2310
    // Include flags
2311
0
    {
2312
0
      FlagKind kind = FlagKind::Include;
2313
0
      std::vector<std::string> includes;
2314
2315
0
      lg->GetIncludeDirectories(includes, this, lang, config);
2316
0
      auto includeFlags =
2317
0
        lg->GetIncludeFlags(includes, this, lang, config, false);
2318
2319
0
      for (auto&& flag : SplitFlags(includeFlags)) {
2320
0
        include_flags.emplace_back(cls, kind, std::move(flag));
2321
0
      }
2322
0
    }
2323
0
  }
2324
2325
0
  std::string const COMPILE_OPTIONS("COMPILE_OPTIONS");
2326
0
  cmGeneratorExpressionInterpreter genexInterpreter(lg, config, this, lang);
2327
2328
  // Source-specific flags.
2329
0
  {
2330
    // Define flags
2331
0
    {
2332
0
      if (cmValue srcDefines = sf->GetProperty("COMPILE_DEFINITIONS")) {
2333
0
        std::set<std::string> defines;
2334
0
        lg->AppendDefines(defines, srcDefines);
2335
2336
0
        std::string defineFlags;
2337
0
        lg->JoinDefines(defines, defineFlags, lang);
2338
2339
0
        for (auto&& flag : SplitFlags(defineFlags)) {
2340
0
          define_flags.emplace_back(FlagClassification::PrivateFlag,
2341
0
                                    FlagKind::Definition, std::move(flag));
2342
0
        }
2343
0
      }
2344
0
    }
2345
2346
    // Compile flags.
2347
0
    {
2348
0
      std::string const COMPILE_FLAGS("COMPILE_FLAGS");
2349
2350
0
      FlagClassification cls = FlagClassification::PrivateFlag;
2351
0
      FlagKind kind = FlagKind::Compile;
2352
2353
0
      std::string sourceFlags;
2354
2355
0
      if (cmValue cflags = sf->GetProperty(COMPILE_FLAGS)) {
2356
0
        lg->AppendFlags(sourceFlags,
2357
0
                        genexInterpreter.Evaluate(*cflags, COMPILE_FLAGS));
2358
0
      }
2359
2360
0
      if (cmValue coptions = sf->GetProperty(COMPILE_OPTIONS)) {
2361
0
        lg->AppendCompileOptions(
2362
0
          sourceFlags, genexInterpreter.Evaluate(*coptions, COMPILE_OPTIONS));
2363
0
      }
2364
2365
0
      for (auto&& flag : SplitFlags(sourceFlags)) {
2366
0
        compile_flags.emplace_back(cls, kind, std::move(flag));
2367
0
      }
2368
0
    }
2369
0
  }
2370
2371
  // File set specific flags
2372
0
  if (fileSet) {
2373
    // Define flags
2374
0
    {
2375
0
      auto fsDefines = fileSet->BelongsTo(this)
2376
0
        ? fileSet->GetCompileDefinitions(config, lang)
2377
0
        : fileSet->GetInterfaceCompileDefinitions(config, lang);
2378
0
      if (!fsDefines.empty()) {
2379
0
        std::set<std::string> defines;
2380
0
        lg->AppendDefines(defines, fsDefines);
2381
2382
0
        std::string defineFlags;
2383
0
        lg->JoinDefines(defines, defineFlags, lang);
2384
2385
0
        for (auto&& flag : SplitFlags(defineFlags)) {
2386
0
          define_flags.emplace_back(FlagClassification::PrivateFlag,
2387
0
                                    FlagKind::Definition, std::move(flag));
2388
0
        }
2389
0
      }
2390
0
    }
2391
2392
    // Compile flags.
2393
0
    {
2394
0
      auto options = fileSet->BelongsTo(this)
2395
0
        ? fileSet->GetCompileOptions(config, lang)
2396
0
        : fileSet->GetInterfaceCompileOptions(config, lang);
2397
0
      if (!options.empty()) {
2398
0
        std::string compileFlags;
2399
0
        lg->AppendCompileOptions(compileFlags, cm::remove_BT(options));
2400
2401
0
        for (auto&& flag : SplitFlags(compileFlags)) {
2402
0
          compile_flags.emplace_back(FlagClassification::PrivateFlag,
2403
0
                                     FlagKind::Compile, std::move(flag));
2404
0
        }
2405
0
      }
2406
0
    }
2407
0
  }
2408
2409
  // Dependency tracking flags.
2410
0
  {
2411
0
    if (!sfVars.DependencyFlags.empty()) {
2412
0
      cmRulePlaceholderExpander::RuleVariables vars;
2413
0
      auto rulePlaceholderExpander = lg->CreateRulePlaceholderExpander();
2414
2415
0
      vars.DependencyFile = sfVars.DependencyFile.c_str();
2416
0
      vars.DependencyTarget = sfVars.DependencyTarget.c_str();
2417
2418
0
      std::string depfileFlags = sfVars.DependencyFlags;
2419
0
      rulePlaceholderExpander->ExpandRuleVariables(lg, depfileFlags, vars);
2420
0
      for (auto&& flag : SplitFlags(depfileFlags)) {
2421
0
        compile_flags.emplace_back(FlagClassification::LocationFlag,
2422
0
                                   FlagKind::BuildSystem, std::move(flag));
2423
0
      }
2424
0
    }
2425
0
  }
2426
2427
  // Precompiled headers.
2428
0
  {
2429
0
    FlagClassification cls = FlagClassification::PrivateFlag;
2430
0
    FlagKind kind = FlagKind::Compile;
2431
2432
0
    std::string pchFlags;
2433
2434
    // Add precompile headers compile options.
2435
0
    if (!((fileSet && sf->GetProperty("SKIP_PRECOMPILE_HEADERS")) ||
2436
0
          sf->GetProperty("SKIP_PRECOMPILE_HEADERS"))) {
2437
0
      if (!pchSources.empty()) {
2438
0
        std::string pchOptions;
2439
0
        auto pchIt = pchSources.find(sf->GetFullPath());
2440
0
        if (pchIt != pchSources.end()) {
2441
0
          pchOptions =
2442
0
            this->GetPchCreateCompileOptions(config, lang, pchIt->second);
2443
0
        } else {
2444
0
          pchOptions = this->GetPchUseCompileOptions(config, lang);
2445
0
        }
2446
2447
0
        this->LocalGenerator->AppendCompileOptions(
2448
0
          pchFlags, genexInterpreter.Evaluate(pchOptions, COMPILE_OPTIONS));
2449
0
      }
2450
0
    }
2451
2452
0
    for (auto&& flag : SplitFlags(pchFlags)) {
2453
0
      compile_flags.emplace_back(cls, kind, std::move(flag));
2454
0
    }
2455
0
  }
2456
2457
  // C++ module flags.
2458
0
  bool useBmiTemplate = false;
2459
0
  if (lang == "CXX"_s) {
2460
0
    FlagClassification cls = FlagClassification::LocationFlag;
2461
0
    FlagKind kind = FlagKind::BuildSystem;
2462
2463
0
    std::string bmiFlags;
2464
2465
0
    auto const* fs = this->GetFileSetForSource(config, sf);
2466
0
    if (fs && fs->GetType() == cm::FileSetMetadata::CXX_MODULES) {
2467
0
      if (lang != "CXX"_s) {
2468
0
        mf->IssueMessage(
2469
0
          MessageType::FATAL_ERROR,
2470
0
          cmStrCat(
2471
0
            "Target \"", this->Target->GetName(), "\" contains the source\n  ",
2472
0
            sf->GetFullPath(), "\nin a file set of type \"", fs->GetType(),
2473
0
            R"(" but the source is not classified as a "CXX" source.)"));
2474
0
      }
2475
2476
0
      if (!this->Target->IsNormal()) {
2477
0
        if (!mf->GetDefinition("CMAKE_CXX_COMPILE_BMI").IsEmpty()) {
2478
0
          useBmiTemplate = true;
2479
0
        } else {
2480
0
          std::string flag =
2481
0
            mf->GetSafeDefinition("CMAKE_CXX_MODULE_BMI_ONLY_FLAG");
2482
0
          cmRulePlaceholderExpander::RuleVariables compileObjectVars;
2483
0
          compileObjectVars.Object = sfVars.ObjectFileDir.c_str();
2484
0
          auto rulePlaceholderExpander = lg->CreateRulePlaceholderExpander();
2485
0
          rulePlaceholderExpander->ExpandRuleVariables(lg, flag,
2486
0
                                                       compileObjectVars);
2487
0
          lg->AppendCompileOptions(bmiFlags, flag);
2488
0
        }
2489
0
      }
2490
0
    }
2491
2492
0
    for (auto&& flag : SplitFlags(bmiFlags)) {
2493
0
      compile_flags.emplace_back(cls, kind, std::move(flag));
2494
0
    }
2495
0
  }
2496
2497
0
  cmRulePlaceholderExpander::RuleVariables vars;
2498
0
  vars.CMTargetName = this->GetName().c_str();
2499
0
  vars.CMTargetType = cmState::GetTargetTypeName(this->GetType()).c_str();
2500
0
  vars.Language = lang.c_str();
2501
2502
0
  auto const sfPath = this->LocalGenerator->ConvertToOutputFormat(
2503
0
    sf->GetFullPath(), cmOutputConverter::SHELL);
2504
2505
  // Compute the base compiler command line. We'll find placeholders and
2506
  // replace them with arguments later in this function.
2507
0
  {
2508
0
    FlagClassification cls = FlagClassification::ExecutionFlag;
2509
0
    FlagKind kind = FlagKind::NotAFlag;
2510
2511
0
    std::string const cmdVar =
2512
0
      cmStrCat("CMAKE_", lang, "_COMPILE_", useBmiTemplate ? "BMI" : "OBJECT");
2513
0
    std::string const& compileCmd = mf->GetRequiredDefinition(cmdVar);
2514
0
    cmList compileCmds(compileCmd); // FIXME: which command to use?
2515
0
    std::string& cmd = compileCmds[0];
2516
0
    auto rulePlaceholderExpander = lg->CreateRulePlaceholderExpander();
2517
2518
0
    static std::string const PlaceholderDefines = "__CMAKE_DEFINES";
2519
0
    static std::string const PlaceholderIncludes = "__CMAKE_INCLUDES";
2520
0
    static std::string const PlaceholderFlags = "__CMAKE_FLAGS";
2521
0
    static std::string const PlaceholderSource = "__CMAKE_SOURCE";
2522
2523
0
    vars.Defines = PlaceholderDefines.c_str();
2524
0
    vars.Includes = PlaceholderIncludes.c_str();
2525
0
    vars.TargetPDB = sfVars.TargetPDB.c_str();
2526
0
    vars.TargetCompilePDB = sfVars.TargetCompilePDB.c_str();
2527
0
    vars.Object = sfVars.ObjectFileDir.c_str();
2528
0
    vars.ObjectDir = sfVars.ObjectDir.c_str();
2529
0
    vars.ObjectFileDir = sfVars.ObjectFileDir.c_str();
2530
0
    vars.TargetSupportDir = sfVars.TargetSupportDir.c_str();
2531
0
    vars.Flags = PlaceholderFlags.c_str();
2532
0
    vars.DependencyFile = sfVars.DependencyFile.c_str();
2533
0
    vars.DependencyTarget = sfVars.DependencyTarget.c_str();
2534
0
    vars.Source = PlaceholderSource.c_str();
2535
2536
0
    rulePlaceholderExpander->ExpandRuleVariables(lg, cmd, vars);
2537
0
    for (auto&& flag : SplitFlags(cmd)) {
2538
0
      if (flag == PlaceholderDefines) {
2539
0
        flags.insert(flags.end(), define_flags.begin(), define_flags.end());
2540
0
      } else if (flag == PlaceholderIncludes) {
2541
0
        flags.insert(flags.end(), include_flags.begin(), include_flags.end());
2542
0
      } else if (flag == PlaceholderFlags) {
2543
0
        flags.insert(flags.end(), compile_flags.begin(), compile_flags.end());
2544
0
      } else if (flag == PlaceholderSource) {
2545
0
        flags.emplace_back(FlagClassification::LocationFlag,
2546
0
                           FlagKind::BuildSystem, sfPath);
2547
0
      } else {
2548
0
        flags.emplace_back(cls, kind, std::move(flag));
2549
        // All remaining flags here are build system flags.
2550
0
        kind = FlagKind::BuildSystem;
2551
0
      }
2552
0
    }
2553
0
  }
2554
2555
0
  cacheEntry = sourceFlagsCache.emplace_hint(cacheEntry, sf, std::move(flags));
2556
0
  return cacheEntry->second;
2557
0
}
2558
2559
cmGeneratorTarget::SourceVariables cmGeneratorTarget::GetSourceVariables(
2560
  cmSourceFile const* sf, std::string const& config)
2561
0
{
2562
0
  SourceVariables vars;
2563
0
  auto const language = sf->GetLanguage();
2564
0
  auto const targetType = this->GetType();
2565
0
  auto const* const lg = this->GetLocalGenerator();
2566
0
  auto const* const gg = this->GetGlobalGenerator();
2567
0
  auto const* const mf = this->Makefile;
2568
2569
  // PDB settings.
2570
0
  {
2571
0
    if (mf->GetDefinition("MSVC_C_ARCHITECTURE_ID") ||
2572
0
        mf->GetDefinition("MSVC_CXX_ARCHITECTURE_ID") ||
2573
0
        mf->GetDefinition("MSVC_CUDA_ARCHITECTURE_ID")) {
2574
0
      std::string pdbPath;
2575
0
      std::string compilePdbPath;
2576
0
      if (targetType <= cm::TargetType::OBJECT_LIBRARY) {
2577
0
        compilePdbPath = this->GetCompilePDBPath(config);
2578
0
        if (compilePdbPath.empty()) {
2579
          // Match VS default: `$(IntDir)vc$(PlatformToolsetVersion).pdb`.
2580
          // A trailing slash tells the toolchain to add its default file name.
2581
0
          compilePdbPath = this->GetSupportDirectory();
2582
0
          if (gg->IsMultiConfig()) {
2583
0
            compilePdbPath = cmStrCat(compilePdbPath, '/', config);
2584
0
          }
2585
0
          compilePdbPath += '/';
2586
0
          if (targetType == cm::TargetType::STATIC_LIBRARY) {
2587
            // Match VS default for static libs: `$(IntDir)$(ProjectName).pdb`.
2588
0
            compilePdbPath = cmStrCat(compilePdbPath, this->GetName(), ".pdb");
2589
0
          }
2590
0
        }
2591
0
      }
2592
2593
0
      if (targetType == cm::TargetType::EXECUTABLE ||
2594
0
          targetType == cm::TargetType::STATIC_LIBRARY ||
2595
0
          targetType == cm::TargetType::SHARED_LIBRARY ||
2596
0
          targetType == cm::TargetType::MODULE_LIBRARY) {
2597
0
        pdbPath = cmStrCat(this->GetPDBDirectory(config), '/',
2598
0
                           this->GetPDBName(config));
2599
0
      }
2600
2601
0
      vars.TargetPDB = lg->ConvertToOutputFormat(
2602
0
        gg->ConvertToOutputPath(std::move(pdbPath)), cmOutputConverter::SHELL);
2603
0
      vars.TargetCompilePDB = lg->ConvertToOutputFormat(
2604
0
        gg->ConvertToOutputPath(std::move(compilePdbPath)),
2605
0
        cmOutputConverter::SHELL);
2606
0
    }
2607
0
  }
2608
2609
  // Object settings.
2610
0
  {
2611
0
    std::string const targetSupportDir = lg->MaybeRelativeToTopBinDir(
2612
0
      gg->ConvertToOutputPath(this->GetCMFSupportDirectory()));
2613
0
    std::string const objectDir = gg->ConvertToOutputPath(
2614
0
      cmStrCat(this->GetSupportDirectory(), gg->GetConfigDirectory(config)));
2615
0
    std::string const objectFileName = this->GetObjectName(sf);
2616
0
    std::string const objectFilePath =
2617
0
      cmStrCat(objectDir, '/', objectFileName);
2618
2619
0
    vars.TargetSupportDir =
2620
0
      lg->ConvertToOutputFormat(targetSupportDir, cmOutputConverter::SHELL);
2621
0
    vars.ObjectDir =
2622
0
      lg->ConvertToOutputFormat(objectDir, cmOutputConverter::SHELL);
2623
0
    vars.ObjectFileDir =
2624
0
      lg->ConvertToOutputFormat(objectFilePath, cmOutputConverter::SHELL);
2625
2626
    // Dependency settings.
2627
0
    {
2628
0
      std::string const depfileFormatName =
2629
0
        cmStrCat("CMAKE_", language, "_DEPFILE_FORMAT");
2630
0
      std::string const depfileFormat =
2631
0
        mf->GetSafeDefinition(depfileFormatName);
2632
0
      if (depfileFormat != "msvc"_s) {
2633
0
        std::string const flagsName =
2634
0
          cmStrCat("CMAKE_DEPFILE_FLAGS_", language);
2635
0
        std::string const depfileFlags = mf->GetSafeDefinition(flagsName);
2636
0
        if (!depfileFlags.empty()) {
2637
0
          bool replaceExt = false;
2638
0
          if (!language.empty()) {
2639
0
            std::string const repVar =
2640
0
              cmStrCat("CMAKE_", language, "_DEPFILE_EXTENSION_REPLACE");
2641
0
            replaceExt = mf->IsOn(repVar);
2642
0
          }
2643
0
          std::string const depfilePath = cmStrCat(
2644
0
            objectDir, '/',
2645
0
            replaceExt
2646
0
              ? cmSystemTools::GetFilenameWithoutLastExtension(objectFileName)
2647
0
              : objectFileName,
2648
0
            ".d");
2649
2650
0
          vars.DependencyFlags = depfileFlags;
2651
0
          vars.DependencyTarget = vars.ObjectFileDir;
2652
0
          vars.DependencyFile =
2653
0
            lg->ConvertToOutputFormat(depfilePath, cmOutputConverter::SHELL);
2654
0
        }
2655
0
      }
2656
0
    }
2657
0
  }
2658
2659
0
  return vars;
2660
0
}
2661
2662
void cmGeneratorTarget::AddExplicitLanguageFlags(std::string& flags,
2663
                                                 cmSourceFile const& sf) const
2664
0
{
2665
0
  cmValue lang = sf.GetProperty("LANGUAGE");
2666
0
  if (!lang) {
2667
0
    return;
2668
0
  }
2669
2670
0
  switch (this->GetPolicyStatusCMP0119()) {
2671
0
    case cmPolicies::WARN:
2672
0
      CM_FALLTHROUGH;
2673
0
    case cmPolicies::OLD:
2674
      // The OLD behavior is to not add explicit language flags.
2675
0
      return;
2676
0
    case cmPolicies::NEW:
2677
      // The NEW behavior is to add explicit language flags.
2678
0
      break;
2679
0
  }
2680
2681
0
  this->LocalGenerator->AppendFeatureOptions(flags, *lang,
2682
0
                                             "EXPLICIT_LANGUAGE");
2683
0
}
2684
2685
void cmGeneratorTarget::AddCUDAArchitectureFlags(cmBuildStep compileOrLink,
2686
                                                 std::string const& config,
2687
                                                 std::string& flags) const
2688
0
{
2689
0
  std::string arch = this->GetSafeProperty("CUDA_ARCHITECTURES");
2690
2691
0
  if (arch.empty()) {
2692
0
    switch (this->GetPolicyStatusCMP0104()) {
2693
0
      case cmPolicies::WARN:
2694
0
        if (!this->LocalGenerator->GetCMakeInstance()->GetIsInTryCompile()) {
2695
0
          this->Makefile->IssuePolicyWarning(
2696
0
            cmPolicies::CMP0104, {},
2697
0
            cmStrCat("CUDA_ARCHITECTURES is empty for target \""_s,
2698
0
                     this->GetName(), "\"."_s));
2699
0
        }
2700
0
        CM_FALLTHROUGH;
2701
0
      case cmPolicies::OLD:
2702
0
        break;
2703
0
      default:
2704
0
        this->Makefile->IssueMessage(
2705
0
          MessageType::FATAL_ERROR,
2706
0
          cmStrCat("CUDA_ARCHITECTURES is empty for target \"",
2707
0
                   this->GetName(), "\"."));
2708
0
    }
2709
0
  }
2710
2711
  // If CUDA_ARCHITECTURES is false we don't add any architectures.
2712
0
  if (cmIsOff(arch)) {
2713
0
    return;
2714
0
  }
2715
2716
0
  this->AddCUDAArchitectureFlagsImpl(compileOrLink, config, "CUDA",
2717
0
                                     std::move(arch), flags);
2718
0
}
2719
2720
void cmGeneratorTarget::AddCUDAArchitectureFlagsImpl(cmBuildStep compileOrLink,
2721
                                                     std::string const& config,
2722
                                                     std::string const& lang,
2723
                                                     std::string arch,
2724
                                                     std::string& flags) const
2725
0
{
2726
0
  std::string const& compiler = this->Makefile->GetSafeDefinition(
2727
0
    cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
2728
0
  bool const ipoEnabled = this->IsIPOEnabled(lang, config);
2729
2730
  // Check for special modes: `all`, `all-major`.
2731
0
  if (arch == "all" || arch == "all-major") {
2732
0
    if (compiler == "NVIDIA" &&
2733
0
        cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
2734
0
                                      this->Makefile->GetDefinition(cmStrCat(
2735
0
                                        "CMAKE_", lang, "_COMPILER_VERSION")),
2736
0
                                      "11.5")) {
2737
0
      flags = cmStrCat(flags, " -arch=", arch);
2738
0
      return;
2739
0
    }
2740
0
    if (arch == "all") {
2741
0
      arch = *this->Makefile->GetDefinition(
2742
0
        cmStrCat("CMAKE_", lang, "_ARCHITECTURES_ALL"));
2743
0
    } else if (arch == "all-major") {
2744
0
      arch = *this->Makefile->GetDefinition(
2745
0
        cmStrCat("CMAKE_", lang, "_ARCHITECTURES_ALL_MAJOR"));
2746
0
    }
2747
0
  } else if (arch == "native") {
2748
0
    cmValue native = this->Makefile->GetDefinition(
2749
0
      cmStrCat("CMAKE_", lang, "_ARCHITECTURES_NATIVE"));
2750
0
    if (native.IsEmpty()) {
2751
0
      this->Makefile->IssueMessage(
2752
0
        MessageType::FATAL_ERROR,
2753
0
        cmStrCat(lang,
2754
0
                 "_ARCHITECTURES is set to \"native\", but no NVIDIA GPU was "
2755
0
                 "detected."));
2756
0
    }
2757
0
    if (compiler == "NVIDIA" &&
2758
0
        cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
2759
0
                                      this->Makefile->GetDefinition(cmStrCat(
2760
0
                                        "CMAKE_", lang, "_COMPILER_VERSION")),
2761
0
                                      "11.6")) {
2762
0
      flags = cmStrCat(flags, " -arch=", arch);
2763
0
      return;
2764
0
    }
2765
0
    arch = *native;
2766
0
  }
2767
2768
0
  struct CudaArchitecture
2769
0
  {
2770
0
    std::string name;
2771
0
    bool real{ true };
2772
0
    bool virtual_{ true };
2773
0
  };
2774
0
  std::vector<CudaArchitecture> architectures;
2775
2776
0
  {
2777
0
    cmList options(arch);
2778
2779
0
    for (auto& option : options) {
2780
0
      CudaArchitecture architecture;
2781
2782
      // Architecture name is up to the first specifier.
2783
0
      std::size_t pos = option.find_first_of('-');
2784
0
      architecture.name = option.substr(0, pos);
2785
2786
0
      if (pos != std::string::npos) {
2787
0
        cm::string_view specifier{ option.c_str() + pos + 1,
2788
0
                                   option.length() - pos - 1 };
2789
2790
0
        if (specifier == "real") {
2791
0
          architecture.real = true;
2792
0
          architecture.virtual_ = false;
2793
0
        } else if (specifier == "virtual") {
2794
0
          architecture.real = false;
2795
0
          architecture.virtual_ = true;
2796
0
        } else {
2797
0
          this->Makefile->IssueMessage(
2798
0
            MessageType::FATAL_ERROR,
2799
0
            cmStrCat("Unknown CUDA architecture specifier \"", specifier,
2800
0
                     "\"."));
2801
0
        }
2802
0
      }
2803
2804
0
      architectures.emplace_back(architecture);
2805
0
    }
2806
0
  }
2807
2808
0
  if (compiler == "NVIDIA") {
2809
0
    if (ipoEnabled && compileOrLink == cmBuildStep::Link) {
2810
0
      if (cmValue cudaIPOFlags = this->Makefile->GetDefinition(
2811
0
            cmStrCat("CMAKE_", lang, "_LINK_OPTIONS_IPO"))) {
2812
0
        flags += *cudaIPOFlags;
2813
0
      }
2814
0
    }
2815
2816
0
    for (CudaArchitecture& architecture : architectures) {
2817
0
      flags = cmStrCat(std::move(flags), " \"--generate-code=arch=compute_",
2818
0
                       architecture.name, ",code=[");
2819
2820
0
      if (architecture.virtual_) {
2821
0
        flags = cmStrCat(std::move(flags), "compute_", architecture.name);
2822
2823
0
        if (ipoEnabled || architecture.real) {
2824
0
          flags += ',';
2825
0
        }
2826
0
      }
2827
2828
0
      if (ipoEnabled) {
2829
0
        if (compileOrLink == cmBuildStep::Compile) {
2830
0
          flags = cmStrCat(std::move(flags), "lto_", architecture.name);
2831
0
        } else if (compileOrLink == cmBuildStep::Link) {
2832
0
          flags = cmStrCat(std::move(flags), "sm_", architecture.name);
2833
0
        }
2834
0
      } else if (architecture.real) {
2835
0
        flags = cmStrCat(std::move(flags), "sm_", architecture.name);
2836
0
      }
2837
2838
0
      flags += "]\"";
2839
0
    }
2840
0
  } else if (compiler == "Clang" && compileOrLink == cmBuildStep::Compile) {
2841
0
    if (cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
2842
0
                                      this->Makefile->GetDefinition(cmStrCat(
2843
0
                                        "CMAKE_", lang, "_COMPILER_VERSION")),
2844
0
                                      "20.0")) {
2845
0
      for (CudaArchitecture& architecture : architectures) {
2846
0
        flags =
2847
0
          cmStrCat(std::move(flags), " --offload-arch=sm_", architecture.name);
2848
2849
0
        if (!architecture.real) {
2850
0
          this->Makefile->IssueMessage(
2851
0
            MessageType::WARNING,
2852
0
            "Clang doesn't support disabling CUDA real code generation.");
2853
0
        }
2854
2855
0
        if (architecture.virtual_) {
2856
0
          flags = cmStrCat(std::move(flags), " --cuda-include-ptx=sm_",
2857
0
                           architecture.name);
2858
0
        }
2859
0
      }
2860
0
    } else {
2861
0
      for (CudaArchitecture& architecture : architectures) {
2862
0
        flags = cmStrCat(std::move(flags), " --cuda-gpu-arch=sm_",
2863
0
                         architecture.name);
2864
2865
0
        if (!architecture.real) {
2866
0
          this->Makefile->IssueMessage(
2867
0
            MessageType::WARNING,
2868
0
            "Clang doesn't support disabling CUDA real code generation.");
2869
0
        }
2870
2871
0
        if (!architecture.virtual_) {
2872
0
          flags = cmStrCat(std::move(flags), " --no-cuda-include-ptx=sm_",
2873
0
                           architecture.name);
2874
0
        }
2875
0
      }
2876
0
    }
2877
0
  }
2878
0
}
2879
2880
void cmGeneratorTarget::AddISPCTargetFlags(std::string& flags) const
2881
0
{
2882
0
  std::string const& arch = this->GetSafeProperty("ISPC_INSTRUCTION_SETS");
2883
2884
  // If ISPC_TARGET is false we don't add any architectures.
2885
0
  if (cmIsOff(arch)) {
2886
0
    return;
2887
0
  }
2888
2889
0
  std::string const& compiler =
2890
0
    this->Makefile->GetSafeDefinition("CMAKE_ISPC_COMPILER_ID");
2891
2892
0
  if (compiler == "Intel") {
2893
0
    cmList targets(arch);
2894
0
    if (!targets.empty()) {
2895
0
      flags += cmStrCat(" --target=", cmWrap("", targets, "", ","));
2896
0
    }
2897
0
  }
2898
0
}
2899
2900
void cmGeneratorTarget::AddHIPArchitectureFlags(cmBuildStep compileOrLink,
2901
                                                std::string const& config,
2902
                                                std::string& flags) const
2903
0
{
2904
0
  std::string arch = this->GetSafeProperty("HIP_ARCHITECTURES");
2905
2906
0
  if (arch.empty()) {
2907
0
    this->Makefile->IssueMessage(
2908
0
      MessageType::FATAL_ERROR,
2909
0
      cmStrCat("HIP_ARCHITECTURES is empty for target \"", this->GetName(),
2910
0
               "\"."));
2911
0
  }
2912
2913
  // If HIP_ARCHITECTURES is false we don't add any architectures.
2914
0
  if (cmIsOff(arch)) {
2915
0
    return;
2916
0
  }
2917
2918
0
  if (this->Makefile->GetSafeDefinition("CMAKE_HIP_PLATFORM") == "nvidia") {
2919
0
    this->AddCUDAArchitectureFlagsImpl(compileOrLink, config, "HIP",
2920
0
                                       std::move(arch), flags);
2921
0
    return;
2922
0
  }
2923
2924
  // For spirv platform, chipStar handles targeting via the hip package
2925
0
  if (this->Makefile->GetSafeDefinition("CMAKE_HIP_PLATFORM") == "spirv") {
2926
0
    return;
2927
0
  }
2928
2929
0
  cmList options(arch);
2930
2931
0
  for (std::string& option : options) {
2932
0
    flags = cmStrCat(std::move(flags), " --offload-arch=", option);
2933
0
  }
2934
0
}
2935
2936
void cmGeneratorTarget::AddRustTargetFlags(std::string& flags) const
2937
0
{
2938
0
  cmValue const edition = this->GetProperty("Rust_EDITION");
2939
0
  if (edition && !edition->empty()) {
2940
0
    flags = cmStrCat(std::move(flags), " --edition=", *edition);
2941
0
  }
2942
0
}
2943
2944
void cmGeneratorTarget::AddSwiftTargetFlags(std::string& flags) const
2945
0
{
2946
0
  if (cmValue version = GetProperty("Swift_LANGUAGE_VERSION")) {
2947
0
    if (cmSystemTools::VersionCompare(
2948
0
          cmSystemTools::OP_GREATER_EQUAL,
2949
0
          this->Makefile->GetDefinition("CMAKE_Swift_COMPILER_VERSION"),
2950
0
          "4.2")) {
2951
0
      flags = cmStrCat(std::move(flags), " -swift-version ", *version);
2952
0
    }
2953
0
  }
2954
2955
0
  if (!this->GetGlobalGenerator()->IsXcode() &&
2956
0
      cmSystemTools::VersionCompare(
2957
0
        cmSystemTools::OP_GREATER_EQUAL,
2958
0
        this->Makefile->GetDefinition("CMAKE_Swift_COMPILER_VERSION"),
2959
0
        "5.8")) {
2960
    // Note: The Xcode generator sets the `SWIFT_PACKAGE_NAME` BuildSettings
2961
    //       attribute
2962
0
    std::string const packageName = this->GetSwiftPackageName();
2963
0
    if (!packageName.empty()) {
2964
0
      std::string const packageFlag =
2965
0
        this->Makefile->GetSafeDefinition("CMAKE_Swift_PACKAGE_NAME_FLAG");
2966
      // Add the package name to the flags
2967
0
      flags = cmStrCat(std::move(flags), ' ', packageFlag, ' ', packageName);
2968
0
    }
2969
0
  }
2970
0
}
2971
2972
void cmGeneratorTarget::AddCUDAToolkitFlags(std::string& flags) const
2973
0
{
2974
0
  std::string const& compiler =
2975
0
    this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_ID");
2976
2977
0
  if (compiler == "Clang") {
2978
    // Pass CUDA toolkit explicitly to Clang.
2979
    // Clang's searching for the system CUDA toolkit isn't very good and it's
2980
    // expected the user will explicitly pass the toolkit path.
2981
    // This also avoids Clang having to search for the toolkit on every
2982
    // invocation.
2983
0
    std::string toolkitRoot =
2984
0
      this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_LIBRARY_ROOT");
2985
2986
0
    if (!toolkitRoot.empty()) {
2987
0
      flags = cmStrCat(std::move(flags), " --cuda-path=",
2988
0
                       this->LocalGenerator->ConvertToOutputFormat(
2989
0
                         toolkitRoot, cmOutputConverter::SHELL));
2990
0
    }
2991
0
  }
2992
0
}
2993
2994
//----------------------------------------------------------------------------
2995
std::string cmGeneratorTarget::GetFeatureSpecificLinkRuleVariable(
2996
  std::string const& var, std::string const& lang,
2997
  std::string const& config) const
2998
0
{
2999
0
  if (this->IsIPOEnabled(lang, config)) {
3000
0
    std::string varIPO = var + "_IPO";
3001
0
    if (this->Makefile->IsDefinitionSet(varIPO)) {
3002
0
      return varIPO;
3003
0
    }
3004
0
  }
3005
3006
0
  return var;
3007
0
}
3008
3009
//----------------------------------------------------------------------------
3010
std::string cmGeneratorTarget::GetCreateRuleVariable(
3011
  std::string const& lang, std::string const& config) const
3012
0
{
3013
0
  switch (this->GetType()) {
3014
0
    case cm::TargetType::STATIC_LIBRARY: {
3015
0
      std::string var = cmStrCat("CMAKE_", lang, "_CREATE_STATIC_LIBRARY");
3016
0
      return this->GetFeatureSpecificLinkRuleVariable(var, lang, config);
3017
0
    }
3018
0
    case cm::TargetType::SHARED_LIBRARY:
3019
0
      if (this->IsArchivedAIXSharedLibrary()) {
3020
0
        return cmStrCat("CMAKE_", lang, "_CREATE_SHARED_LIBRARY_ARCHIVE");
3021
0
      }
3022
0
      return cmStrCat("CMAKE_", lang, "_CREATE_SHARED_LIBRARY");
3023
0
    case cm::TargetType::MODULE_LIBRARY:
3024
0
      return cmStrCat("CMAKE_", lang, "_CREATE_SHARED_MODULE");
3025
0
    case cm::TargetType::EXECUTABLE:
3026
0
      if (this->IsExecutableWithExports()) {
3027
0
        std::string linkExeWithExports =
3028
0
          cmStrCat("CMAKE_", lang, "_LINK_EXECUTABLE_WITH_EXPORTS");
3029
0
        if (this->Makefile->IsDefinitionSet(linkExeWithExports)) {
3030
0
          return linkExeWithExports;
3031
0
        }
3032
0
      }
3033
0
      return cmStrCat("CMAKE_", lang, "_LINK_EXECUTABLE");
3034
0
    default:
3035
0
      break;
3036
0
  }
3037
0
  return {};
3038
0
}
3039
3040
//----------------------------------------------------------------------------
3041
std::string cmGeneratorTarget::GetClangTidyExportFixesDirectory(
3042
  std::string const& lang) const
3043
0
{
3044
0
  cmValue val =
3045
0
    this->GetProperty(cmStrCat(lang, "_CLANG_TIDY_EXPORT_FIXES_DIR"));
3046
0
  if (!cmNonempty(val)) {
3047
0
    return {};
3048
0
  }
3049
3050
0
  std::string path = *val;
3051
0
  if (!cmSystemTools::FileIsFullPath(path)) {
3052
0
    path =
3053
0
      cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), '/', path);
3054
0
  }
3055
0
  return cmSystemTools::CollapseFullPath(path);
3056
0
}
3057
3058
struct CycleWatcher
3059
{
3060
  CycleWatcher(bool& flag)
3061
0
    : Flag(flag)
3062
0
  {
3063
0
    this->Flag = true;
3064
0
  }
3065
0
  ~CycleWatcher() { this->Flag = false; }
3066
  bool& Flag;
3067
};
3068
3069
cmGeneratorTarget const* cmGeneratorTarget::GetPchReuseTarget() const
3070
0
{
3071
0
  if (this->ComputingPchReuse) {
3072
    // TODO: Get the full cycle.
3073
0
    if (!this->PchReuseCycleDetected) {
3074
0
      this->Makefile->IssueMessage(
3075
0
        MessageType::FATAL_ERROR,
3076
0
        cmStrCat("Circular PCH reuse target involving '", this->GetName(),
3077
0
                 '\''));
3078
0
    }
3079
0
    this->PchReuseCycleDetected = true;
3080
0
    return nullptr;
3081
0
  }
3082
0
  CycleWatcher watch(this->ComputingPchReuse);
3083
0
  (void)watch;
3084
0
  cmValue pchReuseFrom = this->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
3085
0
  if (!pchReuseFrom) {
3086
0
    return nullptr;
3087
0
  }
3088
0
  cmGeneratorTarget const* generatorTarget =
3089
0
    this->GetGlobalGenerator()->FindGeneratorTarget(*pchReuseFrom);
3090
0
  if (!generatorTarget) {
3091
0
    this->Makefile->IssueMessage(
3092
0
      MessageType::FATAL_ERROR,
3093
0
      cmStrCat(
3094
0
        "Target \"", *pchReuseFrom, "\" for the \"", this->GetName(),
3095
0
        R"(" target's "PRECOMPILE_HEADERS_REUSE_FROM" property does not exist.)"));
3096
0
  }
3097
0
  if (this->GetProperty("PRECOMPILE_HEADERS").IsOn()) {
3098
0
    this->Makefile->IssueMessage(
3099
0
      MessageType::FATAL_ERROR,
3100
0
      cmStrCat("PRECOMPILE_HEADERS property is already set on target (\"",
3101
0
               this->GetName(), "\")\n"));
3102
0
  }
3103
3104
0
  if (generatorTarget) {
3105
0
    if (generatorTarget->GetPropertyAsBool("DISABLE_PRECOMPILE_HEADERS")) {
3106
0
      this->Makefile->IssueMessage(
3107
0
        MessageType::WARNING,
3108
0
        cmStrCat(
3109
0
          "Target \"", *pchReuseFrom, "\" for the \"", this->GetName(),
3110
0
          R"(" target's "PRECOMPILE_HEADERS_REUSE_FROM" property has set "DISABLE_PRECOMPILE_HEADERS"; ignoring.)"));
3111
0
      return nullptr;
3112
0
    }
3113
3114
0
    if (auto const* recurseReuseTarget =
3115
0
          generatorTarget->GetPchReuseTarget()) {
3116
0
      return recurseReuseTarget;
3117
0
    }
3118
0
  }
3119
0
  return generatorTarget;
3120
0
}
3121
3122
cmGeneratorTarget* cmGeneratorTarget::GetPchReuseTarget()
3123
0
{
3124
0
  if (this->ComputingPchReuse) {
3125
    // TODO: Get the full cycle.
3126
0
    if (!this->PchReuseCycleDetected) {
3127
0
      this->Makefile->IssueMessage(
3128
0
        MessageType::FATAL_ERROR,
3129
0
        cmStrCat("Circular PCH reuse target involving '", this->GetName(),
3130
0
                 '\''));
3131
0
    }
3132
0
    this->PchReuseCycleDetected = true;
3133
0
    return nullptr;
3134
0
  }
3135
0
  CycleWatcher watch(this->ComputingPchReuse);
3136
0
  (void)watch;
3137
0
  cmValue pchReuseFrom = this->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
3138
0
  if (!pchReuseFrom) {
3139
0
    return nullptr;
3140
0
  }
3141
0
  cmGeneratorTarget* generatorTarget =
3142
0
    this->GetGlobalGenerator()->FindGeneratorTarget(*pchReuseFrom);
3143
0
  if (!generatorTarget) {
3144
0
    this->Makefile->IssueMessage(
3145
0
      MessageType::FATAL_ERROR,
3146
0
      cmStrCat(
3147
0
        "Target \"", *pchReuseFrom, "\" for the \"", this->GetName(),
3148
0
        R"(" target's "PRECOMPILE_HEADERS_REUSE_FROM" property does not exist.)"));
3149
0
  }
3150
0
  if (this->GetProperty("PRECOMPILE_HEADERS").IsOn()) {
3151
0
    this->Makefile->IssueMessage(
3152
0
      MessageType::FATAL_ERROR,
3153
0
      cmStrCat("PRECOMPILE_HEADERS property is already set on target (\"",
3154
0
               this->GetName(), "\")\n"));
3155
0
  }
3156
3157
0
  if (generatorTarget) {
3158
0
    if (generatorTarget->GetPropertyAsBool("DISABLE_PRECOMPILE_HEADERS")) {
3159
0
      this->Makefile->IssueMessage(
3160
0
        MessageType::WARNING,
3161
0
        cmStrCat(
3162
0
          "Target \"", *pchReuseFrom, "\" for the \"", this->GetName(),
3163
0
          R"(" target's "PRECOMPILE_HEADERS_REUSE_FROM" property has set "DISABLE_PRECOMPILE_HEADERS"; ignoring.)"));
3164
0
      return nullptr;
3165
0
    }
3166
3167
0
    if (auto* recurseReuseTarget = generatorTarget->GetPchReuseTarget()) {
3168
0
      return recurseReuseTarget;
3169
0
    }
3170
0
  }
3171
0
  return generatorTarget;
3172
0
}
3173
3174
std::vector<std::string> cmGeneratorTarget::GetPchArchs(
3175
  std::string const& config, std::string const& lang) const
3176
0
{
3177
0
  std::vector<std::string> pchArchs;
3178
0
  if (!this->GetGlobalGenerator()->IsXcode()) {
3179
0
    pchArchs = this->GetAppleArchs(config, lang);
3180
0
  }
3181
0
  if (pchArchs.size() < 2) {
3182
    // We do not need per-arch PCH files when building for one architecture.
3183
0
    pchArchs = { {} };
3184
0
  }
3185
0
  return pchArchs;
3186
0
}
3187
3188
std::string cmGeneratorTarget::GetPchHeader(std::string const& config,
3189
                                            std::string const& language,
3190
                                            std::string const& arch) const
3191
0
{
3192
0
  if (language != "C" && language != "CXX" && language != "OBJC" &&
3193
0
      language != "OBJCXX") {
3194
0
    return std::string();
3195
0
  }
3196
3197
0
  if (this->GetPropertyAsBool("DISABLE_PRECOMPILE_HEADERS")) {
3198
0
    return std::string();
3199
0
  }
3200
0
  cmGeneratorTarget const* generatorTarget = this;
3201
0
  cmGeneratorTarget const* reuseTarget = this->GetPchReuseTarget();
3202
0
  bool const haveReuseTarget = reuseTarget && reuseTarget != this;
3203
0
  if (reuseTarget) {
3204
0
    generatorTarget = reuseTarget;
3205
0
  }
3206
3207
0
  auto const inserted =
3208
0
    this->PchHeaders.insert(std::make_pair(language + config + arch, ""));
3209
0
  if (inserted.second) {
3210
0
    std::vector<BT<std::string>> const headers =
3211
0
      this->GetPrecompileHeaders(config, language);
3212
0
    if (headers.empty() && !haveReuseTarget) {
3213
0
      return std::string();
3214
0
    }
3215
0
    std::string& filename = inserted.first->second;
3216
3217
0
    std::map<std::string, std::string> const languageToExtension = {
3218
0
      { "C", ".h" },
3219
0
      { "CXX", ".hxx" },
3220
0
      { "OBJC", ".objc.h" },
3221
0
      { "OBJCXX", ".objcxx.hxx" }
3222
0
    };
3223
3224
0
    filename = generatorTarget->GetCMFSupportDirectory();
3225
3226
0
    if (this->GetGlobalGenerator()->IsMultiConfig()) {
3227
0
      filename = cmStrCat(filename, '/', config);
3228
0
    }
3229
3230
    // This is acceptable as its the source file, won't have a rename/hash
3231
0
    filename =
3232
0
      cmStrCat(filename, "/cmake_pch", arch.empty() ? "" : cmStrCat('_', arch),
3233
0
               languageToExtension.at(language));
3234
3235
0
    std::string const filename_tmp = cmStrCat(filename, ".tmp");
3236
0
    if (!haveReuseTarget) {
3237
0
      cmValue pchPrologue =
3238
0
        this->Makefile->GetDefinition("CMAKE_PCH_PROLOGUE");
3239
0
      cmValue pchEpilogue =
3240
0
        this->Makefile->GetDefinition("CMAKE_PCH_EPILOGUE");
3241
3242
0
      std::string firstHeaderOnDisk;
3243
0
      {
3244
0
        cmGeneratedFileStream file(
3245
0
          filename_tmp, false,
3246
0
          this->GetGlobalGenerator()->GetMakefileEncoding());
3247
0
        file << "/* generated by CMake */\n\n";
3248
0
        if (pchPrologue) {
3249
0
          file << *pchPrologue << "\n";
3250
0
        }
3251
0
        if (this->GetGlobalGenerator()->IsXcode()) {
3252
0
          file << "#ifndef CMAKE_SKIP_PRECOMPILE_HEADERS\n";
3253
0
        }
3254
0
        if (language == "CXX" && !this->GetGlobalGenerator()->IsXcode()) {
3255
0
          file << "#ifdef __cplusplus\n";
3256
0
        }
3257
0
        for (auto const& header_bt : headers) {
3258
0
          if (header_bt.Value.empty()) {
3259
0
            continue;
3260
0
          }
3261
0
          if (header_bt.Value[0] == '<' || header_bt.Value[0] == '\"') {
3262
0
            file << "#include " << header_bt.Value << "\n";
3263
0
          } else {
3264
0
            file << "#include \"" << header_bt.Value << "\"\n";
3265
0
          }
3266
3267
0
          if (cmSystemTools::FileExists(header_bt.Value) &&
3268
0
              firstHeaderOnDisk.empty()) {
3269
0
            firstHeaderOnDisk = header_bt.Value;
3270
0
          }
3271
0
        }
3272
0
        if (language == "CXX" && !this->GetGlobalGenerator()->IsXcode()) {
3273
0
          file << "#endif // __cplusplus\n";
3274
0
        }
3275
0
        if (this->GetGlobalGenerator()->IsXcode()) {
3276
0
          file << "#endif // CMAKE_SKIP_PRECOMPILE_HEADERS\n";
3277
0
        }
3278
0
        if (pchEpilogue) {
3279
0
          file << *pchEpilogue << "\n";
3280
0
        }
3281
0
      }
3282
3283
0
      if (!firstHeaderOnDisk.empty()) {
3284
0
        cmFileTimes::Copy(firstHeaderOnDisk, filename_tmp);
3285
0
      }
3286
3287
0
      cmSystemTools::MoveFileIfDifferent(filename_tmp, filename);
3288
0
    }
3289
0
  }
3290
0
  return inserted.first->second;
3291
0
}
3292
3293
std::string cmGeneratorTarget::GetPchSource(std::string const& config,
3294
                                            std::string const& language,
3295
                                            std::string const& arch) const
3296
0
{
3297
0
  if (language != "C" && language != "CXX" && language != "OBJC" &&
3298
0
      language != "OBJCXX") {
3299
0
    return std::string();
3300
0
  }
3301
0
  auto const inserted =
3302
0
    this->PchSources.insert(std::make_pair(language + config + arch, ""));
3303
0
  if (inserted.second) {
3304
0
    std::string const pchHeader = this->GetPchHeader(config, language, arch);
3305
0
    if (pchHeader.empty()) {
3306
0
      return std::string();
3307
0
    }
3308
0
    std::string& filename = inserted.first->second;
3309
3310
0
    cmGeneratorTarget const* generatorTarget = this;
3311
0
    cmGeneratorTarget const* reuseTarget = this->GetPchReuseTarget();
3312
0
    bool const haveReuseTarget = reuseTarget && reuseTarget != this;
3313
0
    if (reuseTarget) {
3314
0
      generatorTarget = reuseTarget;
3315
0
    }
3316
3317
0
    filename =
3318
0
      cmStrCat(generatorTarget->GetCMFSupportDirectory(), "/cmake_pch");
3319
3320
    // For GCC the source extension will be transformed into .h[xx].gch
3321
0
    if (!this->Makefile->IsOn("CMAKE_LINK_PCH")) {
3322
0
      std::map<std::string, std::string> const languageToExtension = {
3323
0
        { "C", ".h.c" },
3324
0
        { "CXX", ".hxx.cxx" },
3325
0
        { "OBJC", ".objc.h.m" },
3326
0
        { "OBJCXX", ".objcxx.hxx.mm" }
3327
0
      };
3328
3329
0
      filename = cmStrCat(filename, arch.empty() ? "" : cmStrCat('_', arch),
3330
0
                          languageToExtension.at(language));
3331
0
    } else {
3332
0
      std::map<std::string, std::string> const languageToExtension = {
3333
0
        { "C", ".c" }, { "CXX", ".cxx" }, { "OBJC", ".m" }, { "OBJCXX", ".mm" }
3334
0
      };
3335
3336
0
      filename = cmStrCat(filename, arch.empty() ? "" : cmStrCat('_', arch),
3337
0
                          languageToExtension.at(language));
3338
0
    }
3339
3340
0
    std::string const filename_tmp = cmStrCat(filename, ".tmp");
3341
0
    if (!haveReuseTarget) {
3342
0
      {
3343
0
        cmGeneratedFileStream file(filename_tmp);
3344
0
        file << "/* generated by CMake */\n";
3345
0
      }
3346
0
      cmFileTimes::Copy(pchHeader, filename_tmp);
3347
0
      cmSystemTools::MoveFileIfDifferent(filename_tmp, filename);
3348
0
    }
3349
0
  }
3350
0
  return inserted.first->second;
3351
0
}
3352
3353
std::string cmGeneratorTarget::GetPchFileObject(std::string const& config,
3354
                                                std::string const& language,
3355
                                                std::string const& arch)
3356
0
{
3357
0
  if (language != "C" && language != "CXX" && language != "OBJC" &&
3358
0
      language != "OBJCXX") {
3359
0
    return std::string();
3360
0
  }
3361
0
  auto const inserted =
3362
0
    this->PchObjectFiles.insert(std::make_pair(language + config + arch, ""));
3363
0
  if (inserted.second) {
3364
0
    std::string const pchSource = this->GetPchSource(config, language, arch);
3365
0
    if (pchSource.empty()) {
3366
0
      return std::string();
3367
0
    }
3368
0
    std::string& filename = inserted.first->second;
3369
3370
0
    auto* pchSf = this->Makefile->GetOrCreateSource(
3371
0
      pchSource, false, cmSourceFileLocationKind::Known);
3372
0
    pchSf->SetSpecialSourceType(cmSourceFile::SpecialSourceType::PchSource);
3373
0
    pchSf->ResolveFullPath();
3374
0
    filename = cmStrCat(this->GetObjectDirectory(config), '/',
3375
0
                        this->GetObjectName(pchSf));
3376
0
  }
3377
0
  return inserted.first->second;
3378
0
}
3379
3380
std::string cmGeneratorTarget::GetPchFile(std::string const& config,
3381
                                          std::string const& language,
3382
                                          std::string const& arch)
3383
0
{
3384
0
  auto const inserted =
3385
0
    this->PchFiles.insert(std::make_pair(language + config + arch, ""));
3386
0
  if (inserted.second) {
3387
0
    std::string& pchFile = inserted.first->second;
3388
3389
0
    std::string const pchExtension =
3390
0
      this->Makefile->GetSafeDefinition("CMAKE_PCH_EXTENSION");
3391
3392
0
    if (this->Makefile->IsOn("CMAKE_LINK_PCH")) {
3393
0
      auto replaceExtension = [](std::string const& str,
3394
0
                                 std::string const& ext) -> std::string {
3395
0
        auto dot_pos = str.rfind('.');
3396
0
        std::string result;
3397
0
        if (dot_pos != std::string::npos) {
3398
0
          result = str.substr(0, dot_pos);
3399
0
        }
3400
0
        result += ext;
3401
0
        return result;
3402
0
      };
3403
3404
0
      cmGeneratorTarget* generatorTarget = this;
3405
0
      cmGeneratorTarget* reuseTarget = this->GetPchReuseTarget();
3406
0
      if (reuseTarget) {
3407
0
        generatorTarget = reuseTarget;
3408
0
      }
3409
3410
0
      std::string const pchFileObject =
3411
0
        generatorTarget->GetPchFileObject(config, language, arch);
3412
0
      if (!pchExtension.empty()) {
3413
0
        pchFile = replaceExtension(pchFileObject, pchExtension);
3414
0
      }
3415
0
    } else {
3416
0
      if (this->GetUseShortObjectNames() && !pchExtension.empty()) {
3417
0
        auto pchSource = this->GetPchSource(config, language, arch);
3418
0
        auto* pchSf = this->Makefile->GetOrCreateSource(
3419
0
          pchSource, false, cmSourceFileLocationKind::Known);
3420
0
        pchSf->SetSpecialSourceType(
3421
0
          cmSourceFile::SpecialSourceType::PchSource);
3422
0
        pchSf->ResolveFullPath();
3423
0
        std::string cfgSubdir;
3424
0
        if (this->GetGlobalGenerator()->IsMultiConfig()) {
3425
0
          cfgSubdir = cmStrCat(config, '/');
3426
0
        }
3427
0
        pchFile = cmStrCat(
3428
0
          this->GetSupportDirectory(), '/', cfgSubdir,
3429
0
          this->LocalGenerator->GetShortObjectFileName(*pchSf), pchExtension);
3430
0
      } else {
3431
0
        pchFile =
3432
0
          cmStrCat(this->GetPchHeader(config, language, arch), pchExtension);
3433
0
      }
3434
0
    }
3435
0
  }
3436
0
  return inserted.first->second;
3437
0
}
3438
3439
std::string cmGeneratorTarget::GetPchCreateCompileOptions(
3440
  std::string const& config, std::string const& language,
3441
  std::string const& arch)
3442
0
{
3443
0
  auto const inserted = this->PchCreateCompileOptions.insert(
3444
0
    std::make_pair(language + config + arch, ""));
3445
0
  if (inserted.second) {
3446
0
    std::string& createOptionList = inserted.first->second;
3447
3448
0
    if (this->GetPropertyAsBool("PCH_WARN_INVALID")) {
3449
0
      createOptionList = this->Makefile->GetSafeDefinition(
3450
0
        cmStrCat("CMAKE_", language, "_COMPILE_OPTIONS_INVALID_PCH"));
3451
0
    }
3452
3453
0
    if (this->GetPropertyAsBool("PCH_INSTANTIATE_TEMPLATES")) {
3454
0
      std::string varName = cmStrCat(
3455
0
        "CMAKE_", language, "_COMPILE_OPTIONS_INSTANTIATE_TEMPLATES_PCH");
3456
0
      std::string instantiateOption =
3457
0
        this->Makefile->GetSafeDefinition(varName);
3458
0
      if (!instantiateOption.empty()) {
3459
0
        createOptionList = cmStrCat(createOptionList, ';', instantiateOption);
3460
0
      }
3461
0
    }
3462
3463
0
    std::string const createOptVar =
3464
0
      cmStrCat("CMAKE_", language, "_COMPILE_OPTIONS_CREATE_PCH");
3465
3466
0
    createOptionList = cmStrCat(
3467
0
      createOptionList, ';', this->Makefile->GetSafeDefinition(createOptVar));
3468
3469
0
    std::string const pchHeader = this->GetPchHeader(config, language, arch);
3470
0
    std::string const pchFile = this->GetPchFile(config, language, arch);
3471
3472
0
    if (GlobalGenerator->IsFastbuild()) {
3473
      // Account for potential spaces in a shell-friendly way.
3474
0
      cmSystemTools::ReplaceString(createOptionList, "<PCH_HEADER>",
3475
0
                                   cmStrCat('"', pchHeader, '"'));
3476
0
      cmSystemTools::ReplaceString(createOptionList, "<PCH_FILE>",
3477
0
                                   cmStrCat('"', pchFile, '"'));
3478
0
    } else {
3479
0
      cmSystemTools::ReplaceString(createOptionList, "<PCH_HEADER>",
3480
0
                                   pchHeader);
3481
0
      cmSystemTools::ReplaceString(createOptionList, "<PCH_FILE>", pchFile);
3482
0
    }
3483
0
  }
3484
0
  return inserted.first->second;
3485
0
}
3486
3487
std::string cmGeneratorTarget::GetPchUseCompileOptions(
3488
  std::string const& config, std::string const& language,
3489
  std::string const& arch)
3490
0
{
3491
0
  auto const inserted = this->PchUseCompileOptions.insert(
3492
0
    std::make_pair(language + config + arch, ""));
3493
0
  if (inserted.second) {
3494
0
    std::string& useOptionList = inserted.first->second;
3495
3496
0
    if (this->GetPropertyAsBool("PCH_WARN_INVALID")) {
3497
0
      useOptionList = this->Makefile->GetSafeDefinition(
3498
0
        cmStrCat("CMAKE_", language, "_COMPILE_OPTIONS_INVALID_PCH"));
3499
0
    }
3500
3501
0
    std::string const useOptVar =
3502
0
      cmStrCat(language, "_COMPILE_OPTIONS_USE_PCH");
3503
3504
0
    std::string const& useOptionListProperty =
3505
0
      this->GetSafeProperty(useOptVar);
3506
3507
0
    useOptionList = cmStrCat(
3508
0
      useOptionList, ';',
3509
0
      useOptionListProperty.empty()
3510
0
        ? this->Makefile->GetSafeDefinition(cmStrCat("CMAKE_", useOptVar))
3511
0
        : useOptionListProperty);
3512
3513
0
    std::string const pchHeader = this->GetPchHeader(config, language, arch);
3514
0
    std::string const pchFile = this->GetPchFile(config, language, arch);
3515
3516
0
    if (GlobalGenerator->IsFastbuild()) {
3517
      // Account for potential spaces in a shell-friendly way.
3518
0
      cmSystemTools::ReplaceString(useOptionList, "<PCH_HEADER>",
3519
0
                                   cmStrCat('"', pchHeader, '"'));
3520
0
      cmSystemTools::ReplaceString(useOptionList, "<PCH_FILE>",
3521
0
                                   cmStrCat('"', pchFile, '"'));
3522
0
    } else {
3523
0
      cmSystemTools::ReplaceString(useOptionList, "<PCH_HEADER>", pchHeader);
3524
0
      cmSystemTools::ReplaceString(useOptionList, "<PCH_FILE>", pchFile);
3525
0
    }
3526
0
  }
3527
0
  return inserted.first->second;
3528
0
}
3529
3530
void cmGeneratorTarget::AddSourceFileToUnityBatch(
3531
  std::string const& sourceFilename)
3532
0
{
3533
0
  this->UnityBatchedSourceFiles.insert(sourceFilename);
3534
0
}
3535
3536
bool cmGeneratorTarget::IsSourceFilePartOfUnityBatch(
3537
  std::string const& sourceFilename) const
3538
0
{
3539
0
  if (!this->GetPropertyAsBool("UNITY_BUILD")) {
3540
0
    return false;
3541
0
  }
3542
3543
0
  return this->UnityBatchedSourceFiles.find(sourceFilename) !=
3544
0
    this->UnityBatchedSourceFiles.end();
3545
0
}
3546
3547
void cmGeneratorTarget::ComputeTargetManifest(std::string const& config) const
3548
0
{
3549
0
  if (this->IsImported()) {
3550
0
    return;
3551
0
  }
3552
0
  cmGlobalGenerator* gg = this->LocalGenerator->GetGlobalGenerator();
3553
3554
  // Get the names.
3555
0
  cmGeneratorTarget::Names targetNames;
3556
0
  if (this->GetType() == cm::TargetType::EXECUTABLE) {
3557
0
    targetNames = this->GetExecutableNames(config);
3558
0
  } else if (this->GetType() == cm::TargetType::STATIC_LIBRARY ||
3559
0
             this->GetType() == cm::TargetType::SHARED_LIBRARY ||
3560
0
             this->GetType() == cm::TargetType::MODULE_LIBRARY) {
3561
0
    targetNames = this->GetLibraryNames(config);
3562
0
  } else {
3563
0
    return;
3564
0
  }
3565
3566
  // Get the directory.
3567
0
  std::string dir =
3568
0
    this->GetDirectory(config, cmStateEnums::RuntimeBinaryArtifact);
3569
3570
  // Add each name.
3571
0
  std::string f;
3572
0
  if (!targetNames.Output.empty()) {
3573
0
    f = cmStrCat(dir, '/', targetNames.Output);
3574
0
    gg->AddToManifest(f);
3575
0
  }
3576
0
  if (!targetNames.SharedObject.empty()) {
3577
0
    f = cmStrCat(dir, '/', targetNames.SharedObject);
3578
0
    gg->AddToManifest(f);
3579
0
  }
3580
0
  if (!targetNames.Real.empty()) {
3581
0
    f = cmStrCat(dir, '/', targetNames.Real);
3582
0
    gg->AddToManifest(f);
3583
0
  }
3584
0
  if (!targetNames.PDB.empty()) {
3585
0
    f = cmStrCat(dir, '/', targetNames.PDB);
3586
0
    gg->AddToManifest(f);
3587
0
  }
3588
3589
0
  dir = this->GetDirectory(config, cmStateEnums::ImportLibraryArtifact);
3590
0
  if (!targetNames.ImportOutput.empty()) {
3591
0
    f = cmStrCat(dir, '/', targetNames.ImportOutput);
3592
0
    gg->AddToManifest(f);
3593
0
  }
3594
0
  if (!targetNames.ImportLibrary.empty()) {
3595
0
    f = cmStrCat(dir, '/', targetNames.ImportLibrary);
3596
0
    gg->AddToManifest(f);
3597
0
  }
3598
0
  if (!targetNames.ImportReal.empty()) {
3599
0
    f = cmStrCat(dir, '/', targetNames.ImportReal);
3600
0
    gg->AddToManifest(f);
3601
0
  }
3602
0
}
3603
3604
cm::optional<cmStandardLevel> cmGeneratorTarget::GetExplicitStandardLevel(
3605
  std::string const& lang, std::string const& config) const
3606
0
{
3607
0
  cm::optional<cmStandardLevel> level;
3608
0
  std::string key = cmStrCat(cmSystemTools::UpperCase(config), '-', lang);
3609
0
  auto i = this->ExplicitStandardLevel.find(key);
3610
0
  if (i != this->ExplicitStandardLevel.end()) {
3611
0
    level = i->second;
3612
0
  }
3613
0
  return level;
3614
0
}
3615
3616
void cmGeneratorTarget::UpdateExplicitStandardLevel(std::string const& lang,
3617
                                                    std::string const& config,
3618
                                                    cmStandardLevel level)
3619
0
{
3620
0
  auto e = this->ExplicitStandardLevel.emplace(
3621
0
    cmStrCat(cmSystemTools::UpperCase(config), '-', lang), level);
3622
0
  if (!e.second && e.first->second < level) {
3623
0
    e.first->second = level;
3624
0
  }
3625
0
}
3626
3627
bool cmGeneratorTarget::ComputeCompileFeatures(std::string const& config)
3628
0
{
3629
0
  cmStandardLevelResolver standardResolver(this->Makefile);
3630
3631
0
  for (std::string const& lang :
3632
0
       this->Makefile->GetState()->GetEnabledLanguages()) {
3633
0
    if (cmValue languageStd = this->GetLanguageStandard(lang, config)) {
3634
0
      if (cm::optional<cmStandardLevel> langLevel =
3635
0
            standardResolver.LanguageStandardLevel(lang, *languageStd)) {
3636
0
        this->UpdateExplicitStandardLevel(lang, config, *langLevel);
3637
0
      }
3638
0
    }
3639
0
  }
3640
3641
  // Compute the language standard based on the compile features.
3642
0
  std::vector<BT<std::string>> features = this->GetCompileFeatures(config);
3643
0
  for (BT<std::string> const& f : features) {
3644
0
    std::string lang;
3645
0
    if (!standardResolver.CompileFeatureKnown(this->Target->GetName(), f.Value,
3646
0
                                              lang, nullptr)) {
3647
0
      return false;
3648
0
    }
3649
3650
0
    std::string key = cmStrCat(cmSystemTools::UpperCase(config), '-', lang);
3651
0
    cmValue currentLanguageStandard = this->GetLanguageStandard(lang, config);
3652
3653
0
    cm::optional<cmStandardLevel> featureLevel;
3654
0
    std::string newRequiredStandard;
3655
0
    if (!standardResolver.GetNewRequiredStandard(
3656
0
          this->Target->GetName(), f.Value, currentLanguageStandard,
3657
0
          featureLevel, newRequiredStandard)) {
3658
0
      return false;
3659
0
    }
3660
3661
0
    if (featureLevel) {
3662
0
      this->UpdateExplicitStandardLevel(lang, config, *featureLevel);
3663
0
    }
3664
3665
0
    if (!newRequiredStandard.empty()) {
3666
0
      BTs<std::string>& languageStandardProperty =
3667
0
        this->LanguageStandardMap[key];
3668
0
      if (languageStandardProperty.Value != newRequiredStandard) {
3669
0
        languageStandardProperty.Value = newRequiredStandard;
3670
0
        languageStandardProperty.Backtraces.clear();
3671
0
      }
3672
0
      languageStandardProperty.Backtraces.emplace_back(f.Backtrace);
3673
0
    }
3674
0
  }
3675
3676
0
  return true;
3677
0
}
3678
3679
bool cmGeneratorTarget::ComputeCompileFeatures(
3680
  std::string const& config, std::set<LanguagePair> const& languagePairs)
3681
0
{
3682
0
  for (auto const& language : languagePairs) {
3683
0
    BTs<std::string> const* generatorTargetLanguageStandard =
3684
0
      this->GetLanguageStandardProperty(language.first, config);
3685
0
    if (!generatorTargetLanguageStandard) {
3686
      // If the standard isn't explicitly set we copy it over from the
3687
      // specified paired language.
3688
0
      std::string key =
3689
0
        cmStrCat(cmSystemTools::UpperCase(config), '-', language.first);
3690
0
      BTs<std::string> const* standardToCopy =
3691
0
        this->GetLanguageStandardProperty(language.second, config);
3692
0
      if (standardToCopy) {
3693
0
        this->LanguageStandardMap[key] = *standardToCopy;
3694
0
        generatorTargetLanguageStandard = &this->LanguageStandardMap[key];
3695
0
      } else {
3696
0
        cmValue defaultStandard = this->Makefile->GetDefinition(
3697
0
          cmStrCat("CMAKE_", language.second, "_STANDARD_DEFAULT"));
3698
0
        if (defaultStandard) {
3699
0
          this->LanguageStandardMap[key] = BTs<std::string>(*defaultStandard);
3700
0
          generatorTargetLanguageStandard = &this->LanguageStandardMap[key];
3701
0
        }
3702
0
      }
3703
3704
      // Custom updates for the CUDA standard.
3705
0
      if (generatorTargetLanguageStandard && (language.first == "CUDA")) {
3706
0
        if (generatorTargetLanguageStandard->Value == "98") {
3707
0
          this->LanguageStandardMap[key].Value = "03";
3708
0
        }
3709
0
      }
3710
0
    }
3711
0
  }
3712
3713
0
  return true;
3714
0
}
3715
3716
std::string cmGeneratorTarget::GetImportedLibName(
3717
  std::string const& config) const
3718
0
{
3719
0
  if (cmGeneratorTarget::ImportInfo const* info =
3720
0
        this->GetImportInfo(config)) {
3721
0
    return info->LibName;
3722
0
  }
3723
0
  return std::string();
3724
0
}
3725
3726
std::string cmGeneratorTarget::GetFullPath(std::string const& config,
3727
                                           cmStateEnums::ArtifactType artifact,
3728
                                           bool realname) const
3729
0
{
3730
0
  if (this->IsImported()) {
3731
0
    return this->Target->ImportedGetFullPath(config, artifact);
3732
0
  }
3733
0
  return this->NormalGetFullPath(config, artifact, realname);
3734
0
}
3735
3736
std::string cmGeneratorTarget::NormalGetFullPath(
3737
  std::string const& config, cmStateEnums::ArtifactType artifact,
3738
  bool realname) const
3739
0
{
3740
0
  std::string fpath = cmStrCat(this->GetDirectory(config, artifact), '/');
3741
0
  if (this->IsAppBundleOnApple()) {
3742
0
    fpath =
3743
0
      cmStrCat(this->BuildBundleDirectory(fpath, config, FullLevel), '/');
3744
0
  }
3745
3746
  // Add the full name of the target.
3747
0
  switch (artifact) {
3748
0
    case cmStateEnums::RuntimeBinaryArtifact:
3749
0
      if (realname) {
3750
0
        fpath += this->NormalGetRealName(config);
3751
0
      } else {
3752
0
        fpath +=
3753
0
          this->GetFullName(config, cmStateEnums::RuntimeBinaryArtifact);
3754
0
      }
3755
0
      break;
3756
0
    case cmStateEnums::ImportLibraryArtifact:
3757
0
      if (realname) {
3758
0
        fpath +=
3759
0
          this->NormalGetRealName(config, cmStateEnums::ImportLibraryArtifact);
3760
0
      } else {
3761
0
        fpath +=
3762
0
          this->GetFullName(config, cmStateEnums::ImportLibraryArtifact);
3763
0
      }
3764
0
      break;
3765
0
  }
3766
0
  return fpath;
3767
0
}
3768
3769
std::string cmGeneratorTarget::NormalGetRealName(
3770
  std::string const& config, cmStateEnums::ArtifactType artifact) const
3771
0
{
3772
  // This should not be called for imported targets.
3773
  // TODO: Split cmTarget into a class hierarchy to get compile-time
3774
  // enforcement of the limited imported target API.
3775
0
  if (this->IsImported()) {
3776
0
    std::string msg = cmStrCat("NormalGetRealName called on imported target: ",
3777
0
                               this->GetName());
3778
0
    this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
3779
0
  }
3780
3781
0
  Names names = this->GetType() == cm::TargetType::EXECUTABLE
3782
0
    ? this->GetExecutableNames(config)
3783
0
    : this->GetLibraryNames(config);
3784
3785
  // Compute the real name that will be built.
3786
0
  return artifact == cmStateEnums::RuntimeBinaryArtifact ? names.Real
3787
0
                                                         : names.ImportReal;
3788
0
}
3789
3790
cmGeneratorTarget::Names cmGeneratorTarget::GetLibraryNames(
3791
  std::string const& config) const
3792
0
{
3793
0
  cmGeneratorTarget::Names targetNames;
3794
3795
  // This should not be called for imported targets.
3796
  // TODO: Split cmTarget into a class hierarchy to get compile-time
3797
  // enforcement of the limited imported target API.
3798
0
  if (this->IsImported()) {
3799
0
    std::string msg =
3800
0
      cmStrCat("GetLibraryNames called on imported target: ", this->GetName());
3801
0
    this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
3802
0
  }
3803
3804
  // Check for library version properties.
3805
0
  cmValue version = this->GetProperty("VERSION");
3806
0
  cmValue soversion = this->GetProperty("SOVERSION");
3807
0
  if (!this->HasSOName(config) ||
3808
0
      this->Makefile->IsOn("CMAKE_PLATFORM_NO_VERSIONED_SONAME") ||
3809
0
      this->IsFrameworkOnApple()) {
3810
    // Versioning is supported only for shared libraries and modules,
3811
    // and then only when the platform supports an soname flag.
3812
0
    version = nullptr;
3813
0
    soversion = nullptr;
3814
0
  }
3815
0
  if (version && !soversion) {
3816
    // The soversion must be set if the library version is set.  Use
3817
    // the library version as the soversion.
3818
0
    soversion = version;
3819
0
  }
3820
0
  if (!version && soversion) {
3821
    // Use the soversion as the library version.
3822
0
    version = soversion;
3823
0
  }
3824
3825
  // Get the components of the library name.
3826
0
  NameComponents const& components = this->GetFullNameInternalComponents(
3827
0
    config, cmStateEnums::RuntimeBinaryArtifact);
3828
3829
  // The library name.
3830
0
  targetNames.Base = components.base;
3831
0
  targetNames.Output =
3832
0
    cmStrCat(components.prefix, targetNames.Base, components.suffix);
3833
3834
0
  if (this->IsFrameworkOnApple()) {
3835
0
    targetNames.Real = components.prefix;
3836
0
    if (!this->Makefile->PlatformIsAppleEmbedded()) {
3837
0
      targetNames.Real = cmStrCat(std::move(targetNames.Real), "Versions/",
3838
0
                                  this->GetFrameworkVersion(), '/');
3839
0
    }
3840
0
    targetNames.Real = cmStrCat(std::move(targetNames.Real), targetNames.Base,
3841
0
                                components.suffix);
3842
0
    targetNames.SharedObject = targetNames.Real;
3843
0
  } else if (this->IsArchivedAIXSharedLibrary()) {
3844
0
    targetNames.SharedObject =
3845
0
      cmStrCat(components.prefix, targetNames.Base, ".so");
3846
0
    if (soversion) {
3847
0
      targetNames.SharedObject =
3848
0
        cmStrCat(std::move(targetNames.SharedObject), '.', *soversion);
3849
0
    }
3850
0
    targetNames.Real = targetNames.Output;
3851
0
  } else {
3852
    // The library's soname.
3853
0
    targetNames.SharedObject = this->ComputeVersionedName(
3854
0
      components.prefix, targetNames.Base, components.suffix,
3855
0
      targetNames.Output, soversion);
3856
3857
    // The library's real name on disk.
3858
0
    targetNames.Real = this->ComputeVersionedName(
3859
0
      components.prefix, targetNames.Base, components.suffix,
3860
0
      targetNames.Output, version);
3861
0
  }
3862
3863
  // The import library names.
3864
0
  if (this->GetType() == cm::TargetType::SHARED_LIBRARY ||
3865
0
      this->GetType() == cm::TargetType::MODULE_LIBRARY) {
3866
0
    NameComponents const& importComponents =
3867
0
      this->GetFullNameInternalComponents(config,
3868
0
                                          cmStateEnums::ImportLibraryArtifact);
3869
0
    targetNames.ImportOutput = cmStrCat(
3870
0
      importComponents.prefix, importComponents.base, importComponents.suffix);
3871
3872
0
    if (this->IsFrameworkOnApple() && this->IsSharedLibraryWithExports()) {
3873
0
      targetNames.ImportReal = components.prefix;
3874
0
      if (!this->Makefile->PlatformIsAppleEmbedded()) {
3875
0
        targetNames.ImportReal =
3876
0
          cmStrCat(std::move(targetNames.ImportReal), "Versions/",
3877
0
                   this->GetFrameworkVersion(), '/');
3878
0
      }
3879
0
      targetNames.ImportReal =
3880
0
        cmStrCat(std::move(targetNames.ImportReal), importComponents.base,
3881
0
                 importComponents.suffix);
3882
0
      targetNames.ImportLibrary = targetNames.ImportOutput;
3883
0
    } else {
3884
      // The import library's soname.
3885
0
      targetNames.ImportLibrary = this->ComputeVersionedName(
3886
0
        importComponents.prefix, importComponents.base,
3887
0
        importComponents.suffix, targetNames.ImportOutput, soversion);
3888
3889
      // The import library's real name on disk.
3890
0
      targetNames.ImportReal = this->ComputeVersionedName(
3891
0
        importComponents.prefix, importComponents.base,
3892
0
        importComponents.suffix, targetNames.ImportOutput, version);
3893
0
    }
3894
0
  }
3895
3896
  // The program database file name.
3897
0
  targetNames.PDB = this->GetPDBName(config);
3898
3899
0
  return targetNames;
3900
0
}
3901
3902
cmGeneratorTarget::Names cmGeneratorTarget::GetExecutableNames(
3903
  std::string const& config) const
3904
0
{
3905
0
  cmGeneratorTarget::Names targetNames;
3906
3907
  // This should not be called for imported targets.
3908
  // TODO: Split cmTarget into a class hierarchy to get compile-time
3909
  // enforcement of the limited imported target API.
3910
0
  if (this->IsImported()) {
3911
0
    std::string msg = cmStrCat(
3912
0
      "GetExecutableNames called on imported target: ", this->GetName());
3913
0
    this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
3914
0
  }
3915
3916
// This versioning is supported only for executables and then only
3917
// when the platform supports symbolic links.
3918
#if defined(_WIN32) && !defined(__CYGWIN__)
3919
  cmValue version;
3920
#else
3921
  // Check for executable version properties.
3922
0
  cmValue version = this->GetProperty("VERSION");
3923
0
  if (this->GetType() != cm::TargetType::EXECUTABLE ||
3924
0
      this->Makefile->IsOn("XCODE")) {
3925
0
    version = nullptr;
3926
0
  }
3927
0
#endif
3928
3929
  // Get the components of the executable name.
3930
0
  NameComponents const& components = this->GetFullNameInternalComponents(
3931
0
    config, cmStateEnums::RuntimeBinaryArtifact);
3932
3933
  // The executable name.
3934
0
  targetNames.Base = components.base;
3935
3936
0
  if (this->IsArchivedAIXSharedLibrary()) {
3937
0
    targetNames.Output = components.prefix + targetNames.Base;
3938
0
  } else {
3939
0
    targetNames.Output =
3940
0
      components.prefix + targetNames.Base + components.suffix;
3941
0
  }
3942
3943
// The executable's real name on disk.
3944
#if defined(__CYGWIN__)
3945
  targetNames.Real = components.prefix + targetNames.Base;
3946
#else
3947
0
  targetNames.Real = targetNames.Output;
3948
0
#endif
3949
0
  if (version) {
3950
0
    targetNames.Real = cmStrCat(std::move(targetNames.Real), '-', *version);
3951
0
  }
3952
#if defined(__CYGWIN__)
3953
  targetNames.Real += components.suffix;
3954
#endif
3955
3956
  // The import library name.
3957
0
  targetNames.ImportLibrary =
3958
0
    this->GetFullNameInternal(config, cmStateEnums::ImportLibraryArtifact);
3959
0
  targetNames.ImportReal = targetNames.ImportLibrary;
3960
0
  targetNames.ImportOutput = targetNames.ImportLibrary;
3961
3962
  // The program database file name.
3963
0
  targetNames.PDB = this->GetPDBName(config);
3964
3965
0
  return targetNames;
3966
0
}
3967
3968
std::string cmGeneratorTarget::GetFullNameInternal(
3969
  std::string const& config, cmStateEnums::ArtifactType artifact) const
3970
0
{
3971
0
  NameComponents const& components =
3972
0
    this->GetFullNameInternalComponents(config, artifact);
3973
0
  return components.prefix + components.base + components.suffix;
3974
0
}
3975
3976
std::string cmGeneratorTarget::ImportedGetLocation(
3977
  std::string const& config) const
3978
0
{
3979
0
  assert(this->IsImported());
3980
0
  return this->Target->ImportedGetFullPath(
3981
0
    config, cmStateEnums::RuntimeBinaryArtifact);
3982
0
}
3983
3984
std::string cmGeneratorTarget::GetFullNameImported(
3985
  std::string const& config, cmStateEnums::ArtifactType artifact) const
3986
0
{
3987
0
  return cmSystemTools::GetFilenameName(
3988
0
    this->Target->ImportedGetFullPath(config, artifact));
3989
0
}
3990
3991
cmGeneratorTarget::NameComponents const&
3992
cmGeneratorTarget::GetFullNameInternalComponents(
3993
  std::string const& config, cmStateEnums::ArtifactType artifact) const
3994
0
{
3995
0
  assert(artifact == cmStateEnums::RuntimeBinaryArtifact ||
3996
0
         artifact == cmStateEnums::ImportLibraryArtifact);
3997
0
  FullNameCache& cache = artifact == cmStateEnums::RuntimeBinaryArtifact
3998
0
    ? RuntimeBinaryFullNameCache
3999
0
    : ImportLibraryFullNameCache;
4000
0
  auto search = cache.find(config);
4001
0
  if (search != cache.end()) {
4002
0
    return search->second;
4003
0
  }
4004
  // Use just the target name for non-main target types.
4005
0
  if (this->GetType() != cm::TargetType::STATIC_LIBRARY &&
4006
0
      this->GetType() != cm::TargetType::SHARED_LIBRARY &&
4007
0
      this->GetType() != cm::TargetType::MODULE_LIBRARY &&
4008
0
      this->GetType() != cm::TargetType::EXECUTABLE) {
4009
0
    NameComponents components;
4010
0
    components.base = this->GetName();
4011
0
    return cache.emplace(config, std::move(components)).first->second;
4012
0
  }
4013
4014
0
  bool const isImportedLibraryArtifact =
4015
0
    (artifact == cmStateEnums::ImportLibraryArtifact);
4016
4017
  // Return an empty name for the import library if this platform
4018
  // does not support import libraries.
4019
0
  if (isImportedLibraryArtifact && !this->NeedImportLibraryName(config)) {
4020
0
    return cache.emplace(config, NameComponents()).first->second;
4021
0
  }
4022
4023
0
  NameComponents parts;
4024
0
  std::string& outPrefix = parts.prefix;
4025
0
  std::string& outBase = parts.base;
4026
0
  std::string& outSuffix = parts.suffix;
4027
4028
  // retrieve prefix and suffix
4029
0
  std::string ll = this->GetLinkerLanguage(config);
4030
0
  cmValue targetPrefix = this->GetFilePrefixInternal(config, artifact, ll);
4031
0
  cmValue targetSuffix = this->GetFileSuffixInternal(config, artifact, ll);
4032
4033
  // The implib option is only allowed for shared libraries, module
4034
  // libraries, and executables.
4035
0
  if (this->GetType() != cm::TargetType::SHARED_LIBRARY &&
4036
0
      this->GetType() != cm::TargetType::MODULE_LIBRARY &&
4037
0
      this->GetType() != cm::TargetType::EXECUTABLE) {
4038
0
    artifact = cmStateEnums::RuntimeBinaryArtifact;
4039
0
  }
4040
4041
  // Compute the full name for main target types.
4042
0
  std::string configPostfix = this->GetFilePostfix(config);
4043
4044
  // frameworks have directory prefix
4045
0
  std::string fw_prefix;
4046
0
  if (this->IsFrameworkOnApple()) {
4047
0
    fw_prefix =
4048
0
      cmStrCat(this->GetFrameworkDirectory(config, ContentLevel), '/');
4049
0
    targetPrefix = cmValue(fw_prefix);
4050
0
    if (!isImportedLibraryArtifact) {
4051
      // no suffix
4052
0
      targetSuffix = nullptr;
4053
0
    }
4054
0
  }
4055
4056
0
  if (this->IsCFBundleOnApple()) {
4057
0
    fw_prefix = cmStrCat(this->GetCFBundleDirectory(config, FullLevel), '/');
4058
0
    targetPrefix = cmValue(fw_prefix);
4059
0
    targetSuffix = nullptr;
4060
0
  }
4061
4062
  // Begin the final name with the prefix.
4063
0
  outPrefix = targetPrefix ? *targetPrefix : "";
4064
4065
  // Append the target name or property-specified name.
4066
0
  outBase += this->GetOutputName(config, artifact);
4067
4068
  // Append the per-configuration postfix.
4069
  // When using Xcode, the postfix should be part of the suffix rather than
4070
  // the base, because the suffix ends up being used in Xcode's
4071
  // EXECUTABLE_SUFFIX attribute.
4072
0
  if (this->IsFrameworkOnApple() && this->GetGlobalGenerator()->IsXcode()) {
4073
0
    configPostfix += *targetSuffix;
4074
0
    targetSuffix = cmValue(configPostfix);
4075
0
  } else {
4076
0
    outBase += configPostfix;
4077
0
  }
4078
4079
  // Name shared libraries with their version number on some platforms.
4080
0
  if (cmValue soversion = this->GetProperty("SOVERSION")) {
4081
0
    cmValue dllProp;
4082
0
    if (this->IsDLLPlatform()) {
4083
0
      dllProp = this->GetProperty("DLL_NAME_WITH_SOVERSION");
4084
0
    }
4085
0
    if (this->GetType() == cm::TargetType::SHARED_LIBRARY &&
4086
0
        !isImportedLibraryArtifact &&
4087
0
        (dllProp.IsOn() ||
4088
0
         (!dllProp.IsSet() &&
4089
0
          this->Makefile->IsOn("CMAKE_SHARED_LIBRARY_NAME_WITH_VERSION")))) {
4090
0
      outBase = cmStrCat(std::move(outBase), '-', *soversion);
4091
0
    }
4092
0
  }
4093
4094
  // Append the suffix.
4095
0
  outSuffix = targetSuffix ? *targetSuffix : "";
4096
4097
0
  return cache.emplace(config, std::move(parts)).first->second;
4098
0
}
4099
4100
std::string cmGeneratorTarget::GetLinkerLanguage(
4101
  std::string const& config) const
4102
0
{
4103
0
  return this->GetLinkClosure(config)->LinkerLanguage;
4104
0
}
4105
4106
std::string cmGeneratorTarget::GetLinkerTool(std::string const& config) const
4107
0
{
4108
0
  return this->GetLinkerTool(this->GetLinkerLanguage(config), config);
4109
0
}
4110
4111
std::string cmGeneratorTarget::GetLinkerTool(std::string const& lang,
4112
                                             std::string const& config) const
4113
0
{
4114
0
  auto linkMode = cmStrCat(
4115
0
    "CMAKE_", lang, this->IsDeviceLink() ? "_DEVICE_" : "_", "LINK_MODE");
4116
0
  auto mode = this->Makefile->GetDefinition(linkMode);
4117
0
  if (!mode || mode != "LINKER"_s) {
4118
    // On the Visual Studio generators the project links via the platform
4119
    // toolset, so languages without a LINKER-mode toolchain (e.g. ASM_NASM)
4120
    // must not force a linker; defer to the toolset's default.
4121
0
    if (this->GetGlobalGenerator()->IsVisualStudio()) {
4122
0
      return std::string{};
4123
0
    }
4124
0
    return this->Makefile->GetDefinition("CMAKE_LINKER");
4125
0
  }
4126
4127
0
  auto linkerType = this->GetLinkerTypeProperty(lang, config);
4128
0
  if (linkerType.empty()) {
4129
0
    linkerType = "DEFAULT";
4130
0
  }
4131
0
  auto usingLinker =
4132
0
    cmStrCat("CMAKE_", lang, "_USING_", this->IsDeviceLink() ? "DEVICE_" : "",
4133
0
             "LINKER_", linkerType);
4134
0
  auto linkerTool = this->Makefile->GetDefinition(usingLinker);
4135
4136
0
  if (!linkerTool) {
4137
0
    if (this->GetGlobalGenerator()->IsVisualStudio() &&
4138
0
        linkerType == "DEFAULT"_s) {
4139
0
      return std::string{};
4140
0
    }
4141
4142
    // fall-back to generic definition
4143
0
    linkerTool = this->Makefile->GetDefinition("CMAKE_LINKER");
4144
4145
0
    if (linkerType != "DEFAULT"_s) {
4146
0
      auto isCMakeLinkerType = [](std::string const& type) -> bool {
4147
0
        return std::all_of(type.cbegin(), type.cend(), cmsysString_isupper);
4148
0
      };
4149
0
      if (isCMakeLinkerType(linkerType)) {
4150
0
        this->LocalGenerator->IssueMessage(
4151
0
          MessageType::FATAL_ERROR,
4152
0
          cmStrCat("LINKER_TYPE '", linkerType,
4153
0
                   "' is unknown or not supported by this toolchain."));
4154
0
      } else {
4155
0
        this->LocalGenerator->IssueMessage(
4156
0
          MessageType::FATAL_ERROR,
4157
0
          cmStrCat("LINKER_TYPE '", linkerType,
4158
0
                   "' is unknown. Did you forget to define the '", usingLinker,
4159
0
                   "' variable?"));
4160
0
      }
4161
0
    }
4162
0
  }
4163
4164
0
  return linkerTool;
4165
0
}
4166
4167
bool cmGeneratorTarget::LinkerEnforcesNoAllowShLibUndefined(
4168
  std::string const& config) const
4169
0
{
4170
  // FIXME(#25486): Account for the LINKER_TYPE target property.
4171
  // Also factor out the hard-coded list below into a platform
4172
  // information table based on the linker id.
4173
0
  std::string ll = this->GetLinkerLanguage(config);
4174
0
  std::string linkerIdVar = cmStrCat("CMAKE_", ll, "_COMPILER_LINKER_ID");
4175
0
  cmValue linkerId = this->Makefile->GetDefinition(linkerIdVar);
4176
  // The GNU bfd-based linker may enforce '--no-allow-shlib-undefined'
4177
  // recursively by default.  The Solaris linker has similar behavior.
4178
0
  return linkerId && (*linkerId == "GNU" || *linkerId == "Solaris");
4179
0
}
4180
4181
std::string cmGeneratorTarget::GetPDBOutputName(
4182
  std::string const& config) const
4183
0
{
4184
  // Lookup/compute/cache the pdb output name for this configuration.
4185
0
  auto i = this->PdbOutputNameMap.find(config);
4186
0
  if (i == this->PdbOutputNameMap.end()) {
4187
    // Add empty name in map to detect potential recursion.
4188
0
    PdbOutputNameMapType::value_type entry(config, "");
4189
0
    i = this->PdbOutputNameMap.insert(entry).first;
4190
4191
    // Compute output name.
4192
0
    std::vector<std::string> props;
4193
0
    std::string configUpper = cmSystemTools::UpperCase(config);
4194
0
    if (!configUpper.empty()) {
4195
      // PDB_NAME_<CONFIG>
4196
0
      props.push_back("PDB_NAME_" + configUpper);
4197
0
    }
4198
4199
    // PDB_NAME
4200
0
    props.emplace_back("PDB_NAME");
4201
4202
0
    std::string outName;
4203
0
    for (std::string const& p : props) {
4204
0
      if (cmValue outNameProp = this->GetProperty(p)) {
4205
0
        outName = *outNameProp;
4206
0
        break;
4207
0
      }
4208
0
    }
4209
4210
    // Now evaluate genex and update the previously-prepared map entry.
4211
0
    if (outName.empty()) {
4212
0
      i->second = cmStrCat(
4213
0
        this->GetOutputName(config, cmStateEnums::RuntimeBinaryArtifact),
4214
0
        this->GetPolicyStatusCMP0202() != cmPolicies::NEW
4215
0
          ? this->GetFilePostfix(config)
4216
0
          : "");
4217
0
    } else {
4218
0
      i->second =
4219
0
        cmGeneratorExpression::Evaluate(outName, this->LocalGenerator, config);
4220
0
    }
4221
0
  } else if (i->second.empty()) {
4222
    // An empty map entry indicates we have been called recursively
4223
    // from the above block.
4224
0
    this->LocalGenerator->GetCMakeInstance()->IssueMessage(
4225
0
      MessageType::FATAL_ERROR,
4226
0
      cmStrCat("Target '", this->GetName(), "' PDB_NAME depends on itself."),
4227
0
      this->GetBacktrace());
4228
0
  }
4229
0
  return i->second;
4230
0
}
4231
4232
std::string cmGeneratorTarget::GetPDBName(std::string const& config) const
4233
0
{
4234
0
  NameComponents const& parts = this->GetFullNameInternalComponents(
4235
0
    config, cmStateEnums::RuntimeBinaryArtifact);
4236
4237
0
  std::string base = this->GetPDBOutputName(config);
4238
4239
0
  return cmStrCat(parts.prefix, base,
4240
0
                  this->GetPolicyStatusCMP0202() == cmPolicies::NEW
4241
0
                    ? this->GetFilePostfix(config)
4242
0
                    : "",
4243
0
                  ".pdb");
4244
0
}
4245
4246
std::string cmGeneratorTarget::GetObjectDirectory(
4247
  std::string const& config) const
4248
0
{
4249
0
  std::string obj_dir =
4250
0
    this->GlobalGenerator->ExpandCFGIntDir(this->ObjectDirectory, config);
4251
#if defined(__APPLE__)
4252
  // Replace Xcode's placeholder for the object file directory since
4253
  // installation and export scripts need to know the real directory.
4254
  // Xcode has build-time settings (e.g. for sanitizers) that affect this,
4255
  // but we use the default here.  Users that want to enable sanitizers
4256
  // will do so at the cost of object library installation and export.
4257
  cmSystemTools::ReplaceString(obj_dir, "$(OBJECT_FILE_DIR_normal:base)",
4258
                               "Objects-normal");
4259
#endif
4260
0
  return obj_dir;
4261
0
}
4262
4263
void cmGeneratorTarget::GetTargetObjectNames(
4264
  std::string const& config, std::vector<std::string>& objects) const
4265
0
{
4266
0
  this->GetTargetObjectNames(
4267
0
    config, [](cmSourceFile const&) -> bool { return true; }, objects);
4268
0
}
4269
4270
void cmGeneratorTarget::GetTargetObjectNames(
4271
  std::string const& config, std::function<bool(cmSourceFile const&)> filter,
4272
  std::vector<std::string>& objects) const
4273
0
{
4274
0
  this->GetTargetObjectLocations(
4275
0
    config, filter,
4276
0
    [&objects](cmObjectLocation const& buildLoc, cmObjectLocation const&) {
4277
0
      objects.push_back(buildLoc.GetPath());
4278
0
    });
4279
0
}
4280
4281
void cmGeneratorTarget::GetTargetObjectLocations(
4282
  std::string const& config,
4283
  std::function<void(cmObjectLocation const&, cmObjectLocation const&)> cb)
4284
  const
4285
0
{
4286
0
  this->GetTargetObjectLocations(
4287
0
    config, [](cmSourceFile const&) -> bool { return true; }, cb);
4288
0
}
4289
4290
void cmGeneratorTarget::GetTargetObjectLocations(
4291
  std::string const& config, std::function<bool(cmSourceFile const&)> filter,
4292
  std::function<void(cmObjectLocation const&, cmObjectLocation const&)> cb)
4293
  const
4294
0
{
4295
0
  std::vector<cmSourceFile const*> objectSources;
4296
0
  this->GetObjectSources(objectSources, config);
4297
0
  std::map<cmSourceFile const*, cmObjectLocations> mapping;
4298
4299
0
  for (cmSourceFile const* sf : objectSources) {
4300
0
    mapping[sf];
4301
0
  }
4302
4303
0
  this->LocalGenerator->ComputeObjectFilenames(mapping, config, this);
4304
4305
0
  auto const buildUseShortPaths = this->GetUseShortObjectNames()
4306
0
    ? cmObjectLocations::UseShortPath::Yes
4307
0
    : cmObjectLocations::UseShortPath::No;
4308
0
  auto const installUseShortPaths = this->GetUseShortObjectNamesForInstall();
4309
4310
0
  for (cmSourceFile const* src : objectSources) {
4311
0
    if (filter(*src)) {
4312
      // Find the object file name corresponding to this source file.
4313
0
      auto map_it = mapping.find(src);
4314
0
      auto const& buildLoc = map_it->second.GetLocation(buildUseShortPaths);
4315
0
      auto const& installLoc =
4316
0
        map_it->second.GetInstallLocation(installUseShortPaths, config);
4317
      // It must exist because we populated the mapping just above.
4318
0
      assert(!buildLoc.GetPath().empty());
4319
0
      assert(!installLoc.GetPath().empty());
4320
0
      cb(buildLoc, installLoc);
4321
0
    }
4322
0
  }
4323
4324
  // We need to compute the relative path from the root of
4325
  // of the object directory to handle subdirectory paths
4326
0
  std::string rootObjectDir = this->GetObjectDirectory(config);
4327
0
  rootObjectDir = cmSystemTools::CollapseFullPath(rootObjectDir);
4328
0
  auto ispcObjects = this->GetGeneratedISPCObjects(config);
4329
0
  for (auto const& output : ispcObjects) {
4330
0
    if (filter(*output.first)) {
4331
0
      auto relativePathFromObjectDir =
4332
0
        output.second.substr(rootObjectDir.size());
4333
0
      cmObjectLocation ispcLoc(relativePathFromObjectDir);
4334
      // FIXME: apply short path to this object if needed.
4335
0
      cb(ispcLoc, ispcLoc);
4336
0
    }
4337
0
  }
4338
0
}
4339
4340
bool cmGeneratorTarget::StrictTargetComparison::operator()(
4341
  cmGeneratorTarget const* t1, cmGeneratorTarget const* t2) const
4342
0
{
4343
0
  int nameResult = strcmp(t1->GetName().c_str(), t2->GetName().c_str());
4344
0
  if (nameResult == 0) {
4345
0
    return strcmp(
4346
0
             t1->GetLocalGenerator()->GetCurrentBinaryDirectory().c_str(),
4347
0
             t2->GetLocalGenerator()->GetCurrentBinaryDirectory().c_str()) < 0;
4348
0
  }
4349
0
  return nameResult < 0;
4350
0
}
4351
4352
struct cmGeneratorTarget::SourceFileFlags
4353
cmGeneratorTarget::GetTargetSourceFileFlags(cmSourceFile const* sf) const
4354
0
{
4355
0
  struct SourceFileFlags flags;
4356
0
  this->ConstructSourceFileFlags();
4357
0
  auto si = this->SourceFlagsMap.find(sf);
4358
0
  if (si != this->SourceFlagsMap.end()) {
4359
0
    flags = si->second;
4360
0
  } else {
4361
    // Handle the MACOSX_PACKAGE_LOCATION property on source files that
4362
    // were not listed in one of the other lists.
4363
0
    if (cmValue location = sf->GetProperty("MACOSX_PACKAGE_LOCATION")) {
4364
0
      flags.MacFolder = location->c_str();
4365
0
      bool const stripResources =
4366
0
        this->GlobalGenerator->ShouldStripResourcePath(this->Makefile);
4367
0
      if (*location == "Resources") {
4368
0
        flags.Type = cmGeneratorTarget::SourceFileTypeResource;
4369
0
        if (stripResources) {
4370
0
          flags.MacFolder = "";
4371
0
        }
4372
0
      } else if (cmHasLiteralPrefix(*location, "Resources/")) {
4373
0
        flags.Type = cmGeneratorTarget::SourceFileTypeDeepResource;
4374
0
        if (stripResources) {
4375
0
          flags.MacFolder += cmStrLen("Resources/");
4376
0
        }
4377
0
      } else {
4378
0
        flags.Type = cmGeneratorTarget::SourceFileTypeMacContent;
4379
0
      }
4380
0
    }
4381
0
  }
4382
0
  return flags;
4383
0
}
4384
4385
void cmGeneratorTarget::ConstructSourceFileFlags() const
4386
0
{
4387
0
  if (this->SourceFileFlagsConstructed) {
4388
0
    return;
4389
0
  }
4390
0
  this->SourceFileFlagsConstructed = true;
4391
4392
  // Process public headers to mark the source files.
4393
0
  if (cmValue files = this->GetProperty("PUBLIC_HEADER")) {
4394
0
    cmList relFiles{ *files };
4395
0
    for (auto const& relFile : relFiles) {
4396
0
      if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
4397
0
        SourceFileFlags& flags = this->SourceFlagsMap[sf];
4398
0
        flags.MacFolder = "Headers";
4399
0
        flags.Type = cmGeneratorTarget::SourceFileTypePublicHeader;
4400
0
      }
4401
0
    }
4402
0
  }
4403
4404
  // Process private headers after public headers so that they take
4405
  // precedence if a file is listed in both.
4406
0
  if (cmValue files = this->GetProperty("PRIVATE_HEADER")) {
4407
0
    cmList relFiles{ *files };
4408
0
    for (auto const& relFile : relFiles) {
4409
0
      if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
4410
0
        SourceFileFlags& flags = this->SourceFlagsMap[sf];
4411
0
        flags.MacFolder = "PrivateHeaders";
4412
0
        flags.Type = cmGeneratorTarget::SourceFileTypePrivateHeader;
4413
0
      }
4414
0
    }
4415
0
  }
4416
4417
  // Mark sources listed as resources.
4418
0
  if (cmValue files = this->GetProperty("RESOURCE")) {
4419
0
    cmList relFiles{ *files };
4420
0
    for (auto const& relFile : relFiles) {
4421
0
      if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
4422
0
        SourceFileFlags& flags = this->SourceFlagsMap[sf];
4423
0
        flags.MacFolder = "";
4424
0
        if (!this->GlobalGenerator->ShouldStripResourcePath(this->Makefile)) {
4425
0
          flags.MacFolder = "Resources";
4426
0
        }
4427
0
        flags.Type = cmGeneratorTarget::SourceFileTypeResource;
4428
0
      }
4429
0
    }
4430
0
  }
4431
0
}
4432
4433
bool cmGeneratorTarget::SetDeviceLink(bool deviceLink)
4434
0
{
4435
0
  bool previous = this->DeviceLink;
4436
0
  this->DeviceLink = deviceLink;
4437
0
  return previous;
4438
0
}
4439
4440
void cmGeneratorTarget::GetTargetVersion(int& major, int& minor) const
4441
0
{
4442
0
  int patch;
4443
0
  this->GetTargetVersion("VERSION", major, minor, patch);
4444
0
}
4445
4446
void cmGeneratorTarget::GetTargetVersionFallback(
4447
  std::string const& property, std::string const& fallback_property,
4448
  int& major, int& minor, int& patch) const
4449
0
{
4450
0
  if (this->GetProperty(property)) {
4451
0
    this->GetTargetVersion(property, major, minor, patch);
4452
0
  } else {
4453
0
    this->GetTargetVersion(fallback_property, major, minor, patch);
4454
0
  }
4455
0
}
4456
4457
void cmGeneratorTarget::GetTargetVersion(std::string const& property,
4458
                                         int& major, int& minor,
4459
                                         int& patch) const
4460
0
{
4461
  // Set the default values.
4462
0
  major = 0;
4463
0
  minor = 0;
4464
0
  patch = 0;
4465
4466
0
  assert(this->GetType() != cm::TargetType::INTERFACE_LIBRARY);
4467
4468
0
  if (cmValue version = this->GetProperty(property)) {
4469
    // Try to parse the version number and store the results that were
4470
    // successfully parsed.
4471
0
    int parsed_major;
4472
0
    int parsed_minor;
4473
0
    int parsed_patch;
4474
0
    switch (sscanf(version->c_str(), "%d.%d.%d", &parsed_major, &parsed_minor,
4475
0
                   &parsed_patch)) {
4476
0
      case 3:
4477
0
        patch = parsed_patch;
4478
0
        CM_FALLTHROUGH;
4479
0
      case 2:
4480
0
        minor = parsed_minor;
4481
0
        CM_FALLTHROUGH;
4482
0
      case 1:
4483
0
        major = parsed_major;
4484
0
        CM_FALLTHROUGH;
4485
0
      default:
4486
0
        break;
4487
0
    }
4488
0
  }
4489
0
}
4490
4491
std::string cmGeneratorTarget::GetRuntimeLinkLibrary(
4492
  std::string const& lang, std::string const& config) const
4493
0
{
4494
  // This is activated by the presence of a default selection whether or
4495
  // not it is overridden by a property.
4496
0
  cmValue runtimeLibraryDefault = this->Makefile->GetDefinition(
4497
0
    cmStrCat("CMAKE_", lang, "_RUNTIME_LIBRARY_DEFAULT"));
4498
0
  if (!cmNonempty(runtimeLibraryDefault)) {
4499
0
    return std::string();
4500
0
  }
4501
0
  cmValue runtimeLibraryValue =
4502
0
    this->Target->GetProperty(cmStrCat(lang, "_RUNTIME_LIBRARY"));
4503
0
  if (!runtimeLibraryValue) {
4504
0
    runtimeLibraryValue = runtimeLibraryDefault;
4505
0
  }
4506
0
  return cmSystemTools::UpperCase(cmGeneratorExpression::Evaluate(
4507
0
    *runtimeLibraryValue, this->LocalGenerator, config, this));
4508
0
}
4509
4510
std::string cmGeneratorTarget::GetFortranModuleDirectory(
4511
  std::string const& working_dir) const
4512
0
{
4513
0
  if (!this->FortranModuleDirectoryCreated) {
4514
0
    this->FortranModuleDirectory =
4515
0
      this->CreateFortranModuleDirectory(working_dir);
4516
0
    this->FortranModuleDirectoryCreated = true;
4517
0
  }
4518
4519
0
  return this->FortranModuleDirectory;
4520
0
}
4521
4522
bool cmGeneratorTarget::IsFortranBuildingIntrinsicModules() const
4523
0
{
4524
  // ATTENTION Before 4.0 the property name was misspelled.
4525
  // Check the correct name first and than the old name.
4526
0
  if (cmValue prop = this->GetProperty("Fortran_BUILDING_INTRINSIC_MODULES")) {
4527
0
    return prop.IsOn();
4528
0
  }
4529
0
  if (cmValue prop =
4530
0
        this->GetProperty("Fortran_BUILDING_INSTRINSIC_MODULES")) {
4531
0
    return prop.IsOn();
4532
0
  }
4533
0
  return false;
4534
0
}
4535
4536
std::string cmGeneratorTarget::CreateFortranModuleDirectory(
4537
  std::string const& working_dir) const
4538
0
{
4539
0
  std::string mod_dir;
4540
0
  std::string target_mod_dir;
4541
0
  if (cmValue prop = this->GetProperty("Fortran_MODULE_DIRECTORY")) {
4542
0
    target_mod_dir = *prop;
4543
0
  } else {
4544
0
    std::string const& default_mod_dir =
4545
0
      this->LocalGenerator->GetCurrentBinaryDirectory();
4546
0
    if (default_mod_dir != working_dir) {
4547
0
      target_mod_dir = default_mod_dir;
4548
0
    }
4549
0
  }
4550
0
  cmValue moddir_flag =
4551
0
    this->Makefile->GetDefinition("CMAKE_Fortran_MODDIR_FLAG");
4552
0
  if (!target_mod_dir.empty() && moddir_flag) {
4553
    // Compute the full path to the module directory.
4554
0
    if (cmSystemTools::FileIsFullPath(target_mod_dir)) {
4555
      // Already a full path.
4556
0
      mod_dir = target_mod_dir;
4557
0
    } else {
4558
      // Interpret relative to the current output directory.
4559
0
      mod_dir = cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(),
4560
0
                         '/', target_mod_dir);
4561
0
    }
4562
4563
    // Make sure the module output directory exists.
4564
0
    cmSystemTools::MakeDirectory(mod_dir);
4565
0
  }
4566
0
  return mod_dir;
4567
0
}
4568
4569
void cmGeneratorTarget::AddISPCGeneratedHeader(std::string const& header,
4570
                                               std::string const& config)
4571
0
{
4572
0
  std::string config_upper;
4573
0
  if (!config.empty()) {
4574
0
    config_upper = cmSystemTools::UpperCase(config);
4575
0
  }
4576
0
  auto iter = this->ISPCGeneratedHeaders.find(config_upper);
4577
0
  if (iter == this->ISPCGeneratedHeaders.end()) {
4578
0
    std::vector<std::string> headers;
4579
0
    headers.emplace_back(header);
4580
0
    this->ISPCGeneratedHeaders.insert({ config_upper, headers });
4581
0
  } else {
4582
0
    iter->second.emplace_back(header);
4583
0
  }
4584
0
}
4585
4586
std::vector<std::string> cmGeneratorTarget::GetGeneratedISPCHeaders(
4587
  std::string const& config) const
4588
0
{
4589
0
  std::string config_upper;
4590
0
  if (!config.empty()) {
4591
0
    config_upper = cmSystemTools::UpperCase(config);
4592
0
  }
4593
0
  auto iter = this->ISPCGeneratedHeaders.find(config_upper);
4594
0
  if (iter == this->ISPCGeneratedHeaders.end()) {
4595
0
    return std::vector<std::string>{};
4596
0
  }
4597
0
  return iter->second;
4598
0
}
4599
4600
void cmGeneratorTarget::AddISPCGeneratedObject(
4601
  std::vector<std::pair<cmSourceFile const*, std::string>>&& objs,
4602
  std::string const& config)
4603
0
{
4604
0
  std::string config_upper;
4605
0
  if (!config.empty()) {
4606
0
    config_upper = cmSystemTools::UpperCase(config);
4607
0
  }
4608
0
  auto iter = this->ISPCGeneratedObjects.find(config_upper);
4609
0
  if (iter == this->ISPCGeneratedObjects.end()) {
4610
0
    this->ISPCGeneratedObjects.insert({ config_upper, objs });
4611
0
  } else {
4612
0
    iter->second.insert(iter->second.end(), objs.begin(), objs.end());
4613
0
  }
4614
0
}
4615
4616
std::vector<std::pair<cmSourceFile const*, std::string>>
4617
cmGeneratorTarget::GetGeneratedISPCObjects(std::string const& config) const
4618
0
{
4619
0
  std::string config_upper;
4620
0
  if (!config.empty()) {
4621
0
    config_upper = cmSystemTools::UpperCase(config);
4622
0
  }
4623
0
  auto iter = this->ISPCGeneratedObjects.find(config_upper);
4624
0
  if (iter == this->ISPCGeneratedObjects.end()) {
4625
0
    return std::vector<std::pair<cmSourceFile const*, std::string>>{};
4626
0
  }
4627
0
  return iter->second;
4628
0
}
4629
4630
std::string cmGeneratorTarget::GetFrameworkVersion() const
4631
0
{
4632
0
  assert(this->GetType() != cm::TargetType::INTERFACE_LIBRARY);
4633
4634
0
  if (cmValue fversion = this->GetProperty("FRAMEWORK_VERSION")) {
4635
0
    return *fversion;
4636
0
  }
4637
0
  if (cmValue tversion = this->GetProperty("VERSION")) {
4638
0
    return *tversion;
4639
0
  }
4640
0
  return "A";
4641
0
}
4642
4643
std::string cmGeneratorTarget::ComputeVersionedName(std::string const& prefix,
4644
                                                    std::string const& base,
4645
                                                    std::string const& suffix,
4646
                                                    std::string const& name,
4647
                                                    cmValue version) const
4648
0
{
4649
0
  std::string vName = this->IsApple() ? (prefix + base) : name;
4650
0
  if (version) {
4651
0
    vName = cmStrCat(std::move(vName), '.', *version);
4652
0
  }
4653
0
  if (this->IsApple()) {
4654
0
    vName += suffix;
4655
0
  }
4656
0
  return vName;
4657
0
}
4658
4659
std::vector<std::string> cmGeneratorTarget::GetPropertyKeys() const
4660
0
{
4661
0
  return this->Target->GetDirectProperties().GetKeys();
4662
0
}
4663
4664
void cmGeneratorTarget::ReportPropertyOrigin(
4665
  std::string const& p, std::string const& result, std::string const& report,
4666
  std::string const& compatibilityType) const
4667
0
{
4668
0
  cmList debugProperties{ this->Target->GetMakefile()->GetDefinition(
4669
0
    "CMAKE_DEBUG_TARGET_PROPERTIES") };
4670
0
  bool debugOrigin = !this->DebugCompatiblePropertiesDone[p] &&
4671
0
    cm::contains(debugProperties, p);
4672
4673
0
  this->DebugCompatiblePropertiesDone[p] = true;
4674
0
  if (!debugOrigin) {
4675
0
    return;
4676
0
  }
4677
4678
0
  std::string areport =
4679
0
    cmStrCat(compatibilityType, " of property \"", p, "\" for target \"",
4680
0
             this->GetName(), "\" (result: \"", result, "\"):\n", report);
4681
4682
0
  this->LocalGenerator->GetCMakeInstance()->IssueMessage(MessageType::LOG,
4683
0
                                                         areport);
4684
0
}
4685
4686
std::string cmGeneratorTarget::GetDirectory(
4687
  std::string const& config, cmStateEnums::ArtifactType artifact) const
4688
0
{
4689
0
  if (this->IsImported()) {
4690
0
    auto fullPath = this->Target->ImportedGetFullPath(config, artifact);
4691
0
    if (this->IsFrameworkOnApple()) {
4692
0
      auto fwDescriptor = this->GetGlobalGenerator()->SplitFrameworkPath(
4693
0
        fullPath, cmGlobalGenerator::FrameworkFormat::Strict);
4694
0
      if (fwDescriptor) {
4695
0
        return fwDescriptor->Directory;
4696
0
      }
4697
0
    }
4698
    // Return the directory from which the target is imported.
4699
0
    return cmSystemTools::GetFilenamePath(fullPath);
4700
0
  }
4701
0
  if (OutputInfo const* info = this->GetOutputInfo(config)) {
4702
    // Return the directory in which the target will be built.
4703
0
    switch (artifact) {
4704
0
      case cmStateEnums::RuntimeBinaryArtifact:
4705
0
        return info->OutDir;
4706
0
      case cmStateEnums::ImportLibraryArtifact:
4707
0
        return info->ImpDir;
4708
0
    }
4709
0
  }
4710
0
  return "";
4711
0
}
4712
4713
bool cmGeneratorTarget::UsesDefaultOutputDir(
4714
  std::string const& config, cmStateEnums::ArtifactType artifact) const
4715
0
{
4716
0
  std::string dir;
4717
0
  return this->ComputeOutputDir(config, artifact, dir);
4718
0
}
4719
4720
cmGeneratorTarget::OutputInfo const* cmGeneratorTarget::GetOutputInfo(
4721
  std::string const& config) const
4722
0
{
4723
  // There is no output information for imported targets.
4724
0
  if (this->IsImported()) {
4725
0
    return nullptr;
4726
0
  }
4727
4728
  // Synthetic targets don't have output.
4729
0
  if (this->IsSynthetic()) {
4730
0
    return nullptr;
4731
0
  }
4732
4733
  // Only libraries and executables have well-defined output files.
4734
0
  if (!this->HaveWellDefinedOutputFiles()) {
4735
0
    std::string msg = cmStrCat("cmGeneratorTarget::GetOutputInfo called for ",
4736
0
                               this->GetName(), " which has type ",
4737
0
                               cmState::GetTargetTypeName(this->GetType()));
4738
0
    this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
4739
0
    return nullptr;
4740
0
  }
4741
4742
  // Lookup/compute/cache the output information for this configuration.
4743
0
  std::string config_upper;
4744
0
  if (!config.empty()) {
4745
0
    config_upper = cmSystemTools::UpperCase(config);
4746
0
  }
4747
0
  auto i = this->OutputInfoMap.find(config_upper);
4748
0
  if (i == this->OutputInfoMap.end()) {
4749
    // Add empty info in map to detect potential recursion.
4750
0
    OutputInfo info;
4751
0
    OutputInfoMapType::value_type entry(config_upper, info);
4752
0
    i = this->OutputInfoMap.insert(entry).first;
4753
4754
    // Compute output directories.
4755
0
    this->ComputeOutputDir(config, cmStateEnums::RuntimeBinaryArtifact,
4756
0
                           info.OutDir);
4757
0
    this->ComputeOutputDir(config, cmStateEnums::ImportLibraryArtifact,
4758
0
                           info.ImpDir);
4759
0
    if (!this->ComputePDBOutputDir("PDB", config, info.PdbDir)) {
4760
0
      info.PdbDir = info.OutDir;
4761
0
    }
4762
4763
    // Now update the previously-prepared map entry.
4764
0
    i->second = info;
4765
0
  } else if (i->second.empty()) {
4766
    // An empty map entry indicates we have been called recursively
4767
    // from the above block.
4768
0
    this->LocalGenerator->GetCMakeInstance()->IssueMessage(
4769
0
      MessageType::FATAL_ERROR,
4770
0
      cmStrCat("Target '", this->GetName(),
4771
0
               "' OUTPUT_DIRECTORY depends on itself."),
4772
0
      this->GetBacktrace());
4773
0
    return nullptr;
4774
0
  }
4775
0
  return &i->second;
4776
0
}
4777
4778
bool cmGeneratorTarget::ComputeOutputDir(std::string const& config,
4779
                                         cmStateEnums::ArtifactType artifact,
4780
                                         std::string& out) const
4781
0
{
4782
0
  bool usesDefaultOutputDir = false;
4783
0
  std::string conf = config;
4784
4785
  // Look for a target property defining the target output directory
4786
  // based on the target type.
4787
0
  std::string targetTypeName = this->GetOutputTargetType(artifact);
4788
0
  std::string propertyName;
4789
0
  if (!targetTypeName.empty()) {
4790
0
    propertyName = cmStrCat(targetTypeName, "_OUTPUT_DIRECTORY");
4791
0
  }
4792
4793
  // Check for a per-configuration output directory target property.
4794
0
  std::string configUpper = cmSystemTools::UpperCase(conf);
4795
0
  std::string configProp;
4796
0
  if (!targetTypeName.empty()) {
4797
0
    configProp = cmStrCat(targetTypeName, "_OUTPUT_DIRECTORY_", configUpper);
4798
0
  }
4799
4800
  // Select an output directory.
4801
0
  if (cmValue config_outdir = this->GetProperty(configProp)) {
4802
    // Use the user-specified per-configuration output directory.
4803
0
    out = cmGeneratorExpression::Evaluate(*config_outdir, this->LocalGenerator,
4804
0
                                          config, this);
4805
4806
    // Skip per-configuration subdirectory.
4807
0
    conf.clear();
4808
0
  } else if (cmValue outdir = this->GetProperty(propertyName)) {
4809
    // Use the user-specified output directory.
4810
0
    out = cmGeneratorExpression::Evaluate(*outdir, this->LocalGenerator,
4811
0
                                          config, this);
4812
    // Skip per-configuration subdirectory if the value contained a
4813
    // generator expression.
4814
0
    if (out != *outdir) {
4815
0
      conf.clear();
4816
0
    }
4817
0
  } else if (this->GetType() == cm::TargetType::EXECUTABLE) {
4818
    // Lookup the output path for executables.
4819
0
    out = this->Makefile->GetSafeDefinition("EXECUTABLE_OUTPUT_PATH");
4820
0
  } else if (this->GetType() == cm::TargetType::STATIC_LIBRARY ||
4821
0
             this->GetType() == cm::TargetType::SHARED_LIBRARY ||
4822
0
             this->GetType() == cm::TargetType::MODULE_LIBRARY) {
4823
    // Lookup the output path for libraries.
4824
0
    out = this->Makefile->GetSafeDefinition("LIBRARY_OUTPUT_PATH");
4825
0
  }
4826
0
  if (out.empty()) {
4827
    // Default to the current output directory.
4828
0
    usesDefaultOutputDir = true;
4829
0
    out = ".";
4830
0
  }
4831
4832
  // Convert the output path to a full path in case it is
4833
  // specified as a relative path.  Treat a relative path as
4834
  // relative to the current output directory for this makefile.
4835
0
  out = (cmSystemTools::CollapseFullPath(
4836
0
    out, this->LocalGenerator->GetCurrentBinaryDirectory()));
4837
4838
  // The generator may add the configuration's subdirectory.
4839
0
  if (!conf.empty()) {
4840
0
    bool useEPN =
4841
0
      this->GlobalGenerator->UseEffectivePlatformName(this->Makefile);
4842
0
    std::string suffix =
4843
0
      usesDefaultOutputDir && useEPN ? "${EFFECTIVE_PLATFORM_NAME}" : "";
4844
0
    this->LocalGenerator->GetGlobalGenerator()->AppendDirectoryForConfig(
4845
0
      "/", conf, suffix, out);
4846
0
  }
4847
4848
0
  return usesDefaultOutputDir;
4849
0
}
4850
4851
bool cmGeneratorTarget::ComputePDBOutputDir(std::string const& kind,
4852
                                            std::string const& config,
4853
                                            std::string& out) const
4854
0
{
4855
  // Look for a target property defining the target output directory
4856
  // based on the target type.
4857
0
  std::string propertyName;
4858
0
  if (!kind.empty()) {
4859
0
    propertyName = cmStrCat(kind, "_OUTPUT_DIRECTORY");
4860
0
  }
4861
0
  std::string conf = config;
4862
4863
  // Check for a per-configuration output directory target property.
4864
0
  std::string configUpper = cmSystemTools::UpperCase(conf);
4865
0
  std::string configProp;
4866
0
  if (!kind.empty()) {
4867
0
    configProp = cmStrCat(kind, "_OUTPUT_DIRECTORY_", configUpper);
4868
0
  }
4869
4870
  // Select an output directory.
4871
0
  if (cmValue config_outdir = this->GetProperty(configProp)) {
4872
    // Use the user-specified per-configuration output directory.
4873
0
    out = cmGeneratorExpression::Evaluate(*config_outdir, this->LocalGenerator,
4874
0
                                          config);
4875
4876
    // Skip per-configuration subdirectory.
4877
0
    conf.clear();
4878
0
  } else if (cmValue outdir = this->GetProperty(propertyName)) {
4879
    // Use the user-specified output directory.
4880
0
    out =
4881
0
      cmGeneratorExpression::Evaluate(*outdir, this->LocalGenerator, config);
4882
4883
    // Skip per-configuration subdirectory if the value contained a
4884
    // generator expression.
4885
0
    if (out != *outdir) {
4886
0
      conf.clear();
4887
0
    }
4888
0
  }
4889
0
  if (out.empty()) {
4890
0
    cmGeneratorTarget const* reuseTarget = this->GetPchReuseTarget();
4891
0
    bool const hasReuse = reuseTarget && reuseTarget != this;
4892
    // Compiler-generated PDB output always needed for REUSE_FROM.
4893
0
    if (kind == "COMPILE_PDB"_s && (this->PchReused || hasReuse)) {
4894
0
      out = this->GetSupportDirectory();
4895
0
    } else {
4896
0
      return false;
4897
0
    }
4898
0
  }
4899
4900
  // Convert the output path to a full path in case it is
4901
  // specified as a relative path.  Treat a relative path as
4902
  // relative to the current output directory for this makefile.
4903
0
  out = (cmSystemTools::CollapseFullPath(
4904
0
    out, this->LocalGenerator->GetCurrentBinaryDirectory()));
4905
4906
  // The generator may add the configuration's subdirectory.
4907
0
  if (!conf.empty()) {
4908
0
    this->LocalGenerator->GetGlobalGenerator()->AppendDirectoryForConfig(
4909
0
      "/", conf, "", out);
4910
0
  }
4911
0
  return true;
4912
0
}
4913
4914
bool cmGeneratorTarget::HaveInstallTreeRPATH(std::string const& config) const
4915
0
{
4916
0
  std::string install_rpath;
4917
0
  this->GetInstallRPATH(config, install_rpath);
4918
0
  return !install_rpath.empty() &&
4919
0
    !this->Makefile->IsOn("CMAKE_SKIP_INSTALL_RPATH");
4920
0
}
4921
4922
bool cmGeneratorTarget::GetBuildRPATH(std::string const& config,
4923
                                      std::string& rpath) const
4924
0
{
4925
0
  return this->GetRPATH(config, "BUILD_RPATH", rpath);
4926
0
}
4927
4928
bool cmGeneratorTarget::GetInstallRPATH(std::string const& config,
4929
                                        std::string& rpath) const
4930
0
{
4931
0
  return this->GetRPATH(config, "INSTALL_RPATH", rpath);
4932
0
}
4933
4934
bool cmGeneratorTarget::GetRPATH(std::string const& config,
4935
                                 std::string const& prop,
4936
                                 std::string& rpath) const
4937
0
{
4938
0
  cmValue value = this->GetProperty(prop);
4939
0
  if (!value) {
4940
0
    return false;
4941
0
  }
4942
4943
0
  rpath =
4944
0
    cmGeneratorExpression::Evaluate(*value, this->LocalGenerator, config);
4945
4946
0
  return true;
4947
0
}
4948
4949
cmGeneratorTarget::ImportInfo const* cmGeneratorTarget::GetImportInfo(
4950
  std::string const& config) const
4951
0
{
4952
  // There is no imported information for non-imported targets.
4953
0
  if (!this->IsImported()) {
4954
0
    return nullptr;
4955
0
  }
4956
4957
  // Lookup/compute/cache the import information for this
4958
  // configuration.
4959
0
  std::string config_upper;
4960
0
  if (!config.empty()) {
4961
0
    config_upper = cmSystemTools::UpperCase(config);
4962
0
  } else {
4963
0
    config_upper = "NOCONFIG";
4964
0
  }
4965
4966
0
  auto i = this->ImportInfoMap.find(config_upper);
4967
0
  if (i == this->ImportInfoMap.end()) {
4968
0
    ImportInfo info;
4969
0
    this->ComputeImportInfo(config_upper, info);
4970
0
    ImportInfoMapType::value_type entry(config_upper, info);
4971
0
    i = this->ImportInfoMap.insert(entry).first;
4972
0
  }
4973
4974
0
  if (this->GetType() == cm::TargetType::INTERFACE_LIBRARY) {
4975
0
    return &i->second;
4976
0
  }
4977
  // If the location is empty then the target is not available for
4978
  // this configuration.
4979
0
  if (i->second.Location.empty() && i->second.ImportLibrary.empty()) {
4980
0
    return nullptr;
4981
0
  }
4982
4983
  // Return the import information.
4984
0
  return &i->second;
4985
0
}
4986
4987
void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config,
4988
                                          ImportInfo& info) const
4989
0
{
4990
  // This method finds information about an imported target from its
4991
  // properties.  The "IMPORTED_" namespace is reserved for properties
4992
  // defined by the project exporting the target.
4993
4994
  // Initialize members.
4995
0
  info.NoSOName = false;
4996
4997
0
  cmValue loc = nullptr;
4998
0
  cmValue imp = nullptr;
4999
0
  std::string suffix;
5000
0
  if (!this->Target->GetMappedConfig(desired_config, loc, imp, suffix)) {
5001
0
    return;
5002
0
  }
5003
5004
  // Get the link interface.
5005
0
  {
5006
    // Use the INTERFACE_LINK_LIBRARIES special representation directly
5007
    // to get backtraces.
5008
0
    cmBTStringRange entries = this->Target->GetLinkInterfaceEntries();
5009
0
    if (!entries.empty()) {
5010
0
      info.LibrariesProp = "INTERFACE_LINK_LIBRARIES";
5011
0
      for (BT<std::string> const& entry : entries) {
5012
0
        info.Libraries.emplace_back(entry);
5013
0
      }
5014
0
    } else if (this->GetType() != cm::TargetType::INTERFACE_LIBRARY) {
5015
0
      std::string linkProp =
5016
0
        cmStrCat("IMPORTED_LINK_INTERFACE_LIBRARIES", suffix);
5017
0
      cmValue propertyLibs = this->GetProperty(linkProp);
5018
0
      if (!propertyLibs) {
5019
0
        linkProp = "IMPORTED_LINK_INTERFACE_LIBRARIES";
5020
0
        propertyLibs = this->GetProperty(linkProp);
5021
0
      }
5022
0
      if (propertyLibs) {
5023
0
        info.LibrariesProp = linkProp;
5024
0
        info.Libraries.emplace_back(*propertyLibs);
5025
0
      }
5026
0
    }
5027
0
  }
5028
0
  for (BT<std::string> const& entry :
5029
0
       this->Target->GetLinkInterfaceDirectEntries()) {
5030
0
    info.LibrariesHeadInclude.emplace_back(entry);
5031
0
  }
5032
0
  for (BT<std::string> const& entry :
5033
0
       this->Target->GetLinkInterfaceDirectExcludeEntries()) {
5034
0
    info.LibrariesHeadExclude.emplace_back(entry);
5035
0
  }
5036
0
  if (this->GetType() == cm::TargetType::INTERFACE_LIBRARY) {
5037
0
    if (loc) {
5038
0
      info.LibName = *loc;
5039
0
    }
5040
0
    return;
5041
0
  }
5042
5043
  // A provided configuration has been chosen.  Load the
5044
  // configuration's properties.
5045
5046
  // Get the location.
5047
0
  if (loc) {
5048
0
    info.Location = *loc;
5049
0
  } else {
5050
0
    std::string impProp = cmStrCat("IMPORTED_LOCATION", suffix);
5051
0
    if (cmValue config_location = this->GetProperty(impProp)) {
5052
0
      info.Location = *config_location;
5053
0
    } else if (cmValue location = this->GetProperty("IMPORTED_LOCATION")) {
5054
0
      info.Location = *location;
5055
0
    }
5056
0
  }
5057
5058
  // Get the soname.
5059
0
  if (this->GetType() == cm::TargetType::SHARED_LIBRARY) {
5060
0
    std::string soProp = cmStrCat("IMPORTED_SONAME", suffix);
5061
0
    if (cmValue config_soname = this->GetProperty(soProp)) {
5062
0
      info.SOName = *config_soname;
5063
0
    } else if (cmValue soname = this->GetProperty("IMPORTED_SONAME")) {
5064
0
      info.SOName = *soname;
5065
0
    }
5066
0
  }
5067
5068
  // Get the "no-soname" mark.
5069
0
  if (this->GetType() == cm::TargetType::SHARED_LIBRARY) {
5070
0
    std::string soProp = cmStrCat("IMPORTED_NO_SONAME", suffix);
5071
0
    if (cmValue config_no_soname = this->GetProperty(soProp)) {
5072
0
      info.NoSOName = config_no_soname.IsOn();
5073
0
    } else if (cmValue no_soname = this->GetProperty("IMPORTED_NO_SONAME")) {
5074
0
      info.NoSOName = no_soname.IsOn();
5075
0
    }
5076
0
  }
5077
5078
  // Get the import library.
5079
0
  if (imp) {
5080
0
    info.ImportLibrary = *imp;
5081
0
  } else if (this->GetType() == cm::TargetType::SHARED_LIBRARY ||
5082
0
             this->IsExecutableWithExports()) {
5083
0
    std::string impProp = cmStrCat("IMPORTED_IMPLIB", suffix);
5084
0
    if (cmValue config_implib = this->GetProperty(impProp)) {
5085
0
      info.ImportLibrary = *config_implib;
5086
0
    } else if (cmValue implib = this->GetProperty("IMPORTED_IMPLIB")) {
5087
0
      info.ImportLibrary = *implib;
5088
0
    }
5089
0
  }
5090
5091
  // Get the link dependencies.
5092
0
  {
5093
0
    std::string linkProp =
5094
0
      cmStrCat("IMPORTED_LINK_DEPENDENT_LIBRARIES", suffix);
5095
0
    if (cmValue config_libs = this->GetProperty(linkProp)) {
5096
0
      info.SharedDeps = *config_libs;
5097
0
    } else if (cmValue libs =
5098
0
                 this->GetProperty("IMPORTED_LINK_DEPENDENT_LIBRARIES")) {
5099
0
      info.SharedDeps = *libs;
5100
0
    }
5101
0
  }
5102
5103
  // Get the link languages.
5104
0
  if (this->LinkLanguagePropagatesToDependents()) {
5105
0
    std::string linkProp =
5106
0
      cmStrCat("IMPORTED_LINK_INTERFACE_LANGUAGES", suffix);
5107
0
    if (cmValue config_libs = this->GetProperty(linkProp)) {
5108
0
      info.Languages = *config_libs;
5109
0
    } else if (cmValue libs =
5110
0
                 this->GetProperty("IMPORTED_LINK_INTERFACE_LANGUAGES")) {
5111
0
      info.Languages = *libs;
5112
0
    }
5113
0
  }
5114
5115
  // Get information if target is managed assembly.
5116
0
  {
5117
0
    std::string linkProp = "IMPORTED_COMMON_LANGUAGE_RUNTIME";
5118
0
    if (cmValue pc = this->GetProperty(linkProp + suffix)) {
5119
0
      info.Managed = this->CheckManagedType(*pc);
5120
0
    } else if (cmValue p = this->GetProperty(linkProp)) {
5121
0
      info.Managed = this->CheckManagedType(*p);
5122
0
    }
5123
0
  }
5124
5125
  // Get the cyclic repetition count.
5126
0
  if (this->GetType() == cm::TargetType::STATIC_LIBRARY) {
5127
0
    std::string linkProp =
5128
0
      cmStrCat("IMPORTED_LINK_INTERFACE_MULTIPLICITY", suffix);
5129
0
    if (cmValue config_reps = this->GetProperty(linkProp)) {
5130
0
      sscanf(config_reps->c_str(), "%u", &info.Multiplicity);
5131
0
    } else if (cmValue reps =
5132
0
                 this->GetProperty("IMPORTED_LINK_INTERFACE_MULTIPLICITY")) {
5133
0
      sscanf(reps->c_str(), "%u", &info.Multiplicity);
5134
0
    }
5135
0
  }
5136
0
}
5137
5138
bool cmGeneratorTarget::GetConfigCommonSourceFilesForXcode(
5139
  std::vector<cmSourceFile*>& files) const
5140
0
{
5141
0
  std::vector<std::string> const& configs =
5142
0
    this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
5143
5144
0
  auto it = configs.begin();
5145
0
  std::string const& firstConfig = *it;
5146
0
  this->GetSourceFilesWithoutObjectLibraries(files, firstConfig);
5147
5148
0
  for (; it != configs.end(); ++it) {
5149
0
    std::vector<cmSourceFile*> configFiles;
5150
0
    this->GetSourceFilesWithoutObjectLibraries(configFiles, *it);
5151
0
    if (configFiles != files) {
5152
0
      std::string firstConfigFiles;
5153
0
      char const* sep = "";
5154
0
      for (cmSourceFile* f : files) {
5155
0
        firstConfigFiles =
5156
0
          cmStrCat(std::move(firstConfigFiles), sep, f->ResolveFullPath());
5157
0
        sep = "\n  ";
5158
0
      }
5159
5160
0
      std::string thisConfigFiles;
5161
0
      sep = "";
5162
0
      for (cmSourceFile* f : configFiles) {
5163
0
        thisConfigFiles =
5164
0
          cmStrCat(std::move(thisConfigFiles), sep, f->ResolveFullPath());
5165
0
        sep = "\n  ";
5166
0
      }
5167
      /* clang-format off */
5168
0
      std::string e = cmStrCat("Target \"", this->GetName(),
5169
0
        "\" has source files which vary by "
5170
0
        "configuration. This is not supported by the \"",
5171
0
         this->GlobalGenerator->GetName(),
5172
0
         "\" generator.\n"
5173
0
          "Config \"", firstConfig, "\":\n"
5174
0
          "  ", firstConfigFiles, "\n"
5175
0
          "Config \"", *it, "\":\n"
5176
0
          "  ", thisConfigFiles, '\n');
5177
      /* clang-format on */
5178
0
      this->LocalGenerator->IssueMessage(MessageType::FATAL_ERROR, e);
5179
0
      return false;
5180
0
    }
5181
0
  }
5182
0
  return true;
5183
0
}
5184
5185
void cmGeneratorTarget::GetObjectLibrariesInSources(
5186
  std::vector<BT<cmGeneratorTarget*>>& objlibs) const
5187
0
{
5188
  // FIXME: This searches SOURCES for TARGET_OBJECTS for backwards
5189
  // compatibility with the OLD behavior of CMP0026 since this
5190
  // could be called at configure time.  CMP0026 has been removed,
5191
  // so this should now be called only at generate time.
5192
  // Therefore we should be able to improve the implementation
5193
  // with generate-time information.
5194
0
  cmBTStringRange rng = this->Target->GetSourceEntries();
5195
0
  for (auto const& entry : rng) {
5196
0
    cmList files{ entry.Value };
5197
0
    for (auto const& li : files) {
5198
0
      if (cmHasLiteralPrefix(li, "$<TARGET_OBJECTS:") && li.back() == '>') {
5199
0
        std::string objLibName = li.substr(17, li.size() - 18);
5200
5201
0
        if (cmGeneratorExpression::Find(objLibName) != std::string::npos) {
5202
0
          continue;
5203
0
        }
5204
0
        cmGeneratorTarget* objLib =
5205
0
          this->LocalGenerator->FindGeneratorTargetToUse(objLibName);
5206
0
        if (objLib) {
5207
0
          objlibs.emplace_back(objLib, entry.Backtrace);
5208
0
        }
5209
0
      }
5210
0
    }
5211
0
  }
5212
0
}
5213
5214
std::string cmGeneratorTarget::CheckCMP0004(std::string const& item) const
5215
0
{
5216
  // Strip whitespace off the library names because we used to do this
5217
  // in case variables were expanded at generate time.  We no longer
5218
  // do the expansion but users link to libraries like " ${VAR} ".
5219
0
  std::string lib = item;
5220
0
  std::string::size_type pos = lib.find_first_not_of(" \t\r\n");
5221
0
  if (pos != std::string::npos) {
5222
0
    lib = lib.substr(pos);
5223
0
  }
5224
0
  pos = lib.find_last_not_of(" \t\r\n");
5225
0
  if (pos != std::string::npos) {
5226
0
    lib.resize(pos + 1);
5227
0
  }
5228
0
  if (lib != item) {
5229
0
    cmake* cm = this->LocalGenerator->GetCMakeInstance();
5230
0
    std::ostringstream e;
5231
0
    e << "Target \"" << this->GetName() << "\" links to item \"" << item
5232
0
      << "\" which has leading or trailing whitespace.  "
5233
0
      << "This is now an error according to policy CMP0004.";
5234
0
    cm->IssueMessage(MessageType::FATAL_ERROR, e.str(), this->GetBacktrace());
5235
0
  }
5236
0
  return lib;
5237
0
}
5238
5239
bool cmGeneratorTarget::IsDeprecated() const
5240
0
{
5241
0
  cmValue deprecation = this->GetProperty("DEPRECATION");
5242
0
  return cmNonempty(deprecation);
5243
0
}
5244
5245
std::string cmGeneratorTarget::GetDeprecation() const
5246
0
{
5247
  // find DEPRECATION property
5248
0
  if (cmValue deprecation = this->GetProperty("DEPRECATION")) {
5249
0
    return *deprecation;
5250
0
  }
5251
0
  return std::string();
5252
0
}
5253
5254
void cmGeneratorTarget::GetLanguages(std::set<std::string>& languages,
5255
                                     std::string const& config) const
5256
0
{
5257
  // Targets that do not compile anything have no languages.
5258
0
  if (!this->CanCompileSources()) {
5259
0
    return;
5260
0
  }
5261
5262
0
  std::vector<cmSourceFile*> sourceFiles;
5263
0
  this->GetSourceFiles(sourceFiles, config);
5264
0
  for (cmSourceFile* src : sourceFiles) {
5265
0
    std::string const& lang = src->GetOrDetermineLanguage();
5266
0
    if (!lang.empty()) {
5267
0
      languages.insert(lang);
5268
0
    }
5269
0
  }
5270
5271
0
  std::set<cmGeneratorTarget const*> objectLibraries =
5272
0
    this->GetSourceObjectLibraries(config);
5273
0
  for (cmGeneratorTarget const* objLib : objectLibraries) {
5274
0
    objLib->GetLanguages(languages, config);
5275
0
  }
5276
0
}
5277
5278
std::set<cmGeneratorTarget const*> cmGeneratorTarget::GetSourceObjectLibraries(
5279
  std::string const& config) const
5280
0
{
5281
0
  std::set<cmGeneratorTarget const*> objectLibraries;
5282
0
  std::vector<cmSourceFile const*> externalObjects;
5283
0
  this->GetExternalObjects(externalObjects, config);
5284
0
  for (cmSourceFile const* extObj : externalObjects) {
5285
0
    std::string objLib = extObj->GetObjectLibrary();
5286
0
    if (cmGeneratorTarget* tgt =
5287
0
          this->LocalGenerator->FindGeneratorTargetToUse(objLib)) {
5288
0
      objectLibraries.insert(tgt);
5289
0
    }
5290
0
  }
5291
5292
0
  return objectLibraries;
5293
0
}
5294
5295
bool cmGeneratorTarget::IsLanguageUsed(std::string const& language,
5296
                                       std::string const& config) const
5297
0
{
5298
0
  std::set<std::string> languages;
5299
0
  this->GetLanguages(languages, config);
5300
0
  return languages.count(language);
5301
0
}
5302
5303
bool cmGeneratorTarget::IsCSharpOnly() const
5304
0
{
5305
  // Only certain target types may compile CSharp.
5306
0
  if (this->GetType() != cm::TargetType::SHARED_LIBRARY &&
5307
0
      this->GetType() != cm::TargetType::STATIC_LIBRARY &&
5308
0
      this->GetType() != cm::TargetType::EXECUTABLE) {
5309
0
    return false;
5310
0
  }
5311
0
  std::set<std::string> languages = this->GetAllConfigCompileLanguages();
5312
  // Consider an explicit linker language property, but *not* the
5313
  // computed linker language that may depend on linked targets.
5314
0
  cmValue linkLang = this->GetProperty("LINKER_LANGUAGE");
5315
0
  if (cmNonempty(linkLang)) {
5316
0
    languages.insert(*linkLang);
5317
0
  }
5318
0
  return languages.size() == 1 && languages.count("CSharp") > 0;
5319
0
}
5320
5321
bool cmGeneratorTarget::IsDotNetSdkTarget() const
5322
0
{
5323
0
  return !this->GetProperty("DOTNET_SDK").IsEmpty();
5324
0
}
5325
5326
void cmGeneratorTarget::ComputeLinkImplementationLanguages(
5327
  std::string const& config, cmOptionalLinkImplementation& impl) const
5328
0
{
5329
  // This target needs runtime libraries for its source languages.
5330
0
  std::set<std::string> languages;
5331
  // Get languages used in our source files.
5332
0
  this->GetLanguages(languages, config);
5333
  // Copy the set of languages to the link implementation.
5334
0
  impl.Languages.insert(impl.Languages.begin(), languages.begin(),
5335
0
                        languages.end());
5336
0
}
5337
5338
bool cmGeneratorTarget::HaveBuildTreeRPATH(std::string const& config) const
5339
0
{
5340
0
  if (this->GetPropertyAsBool("SKIP_BUILD_RPATH")) {
5341
0
    return false;
5342
0
  }
5343
0
  std::string build_rpath;
5344
0
  if (this->GetBuildRPATH(config, build_rpath)) {
5345
0
    return true;
5346
0
  }
5347
0
  if (cmLinkImplementationLibraries const* impl =
5348
0
        this->GetLinkImplementationLibraries(config, UseTo::Link)) {
5349
0
    return !impl->Libraries.empty();
5350
0
  }
5351
0
  return false;
5352
0
}
5353
5354
bool cmGeneratorTarget::IsNullImpliedByLinkLibraries(
5355
  std::string const& p) const
5356
0
{
5357
0
  return cm::contains(this->LinkImplicitNullProperties, p);
5358
0
}
5359
5360
namespace {
5361
bool CreateCxxStdlibTarget(cmMakefile* makefile, cmLocalGenerator* lg,
5362
                           std::vector<std::string> const& configs)
5363
0
{
5364
0
#ifndef CMAKE_BOOTSTRAP
5365
5366
0
  static cm::optional<cmCxxModuleMetadata> metadata;
5367
5368
  // Load metadata only when we need to create a target
5369
0
  if (!metadata) {
5370
0
    auto errorMessage =
5371
0
      makefile->GetDefinition("CMAKE_CXX_COMPILER_IMPORT_STD_ERROR_MESSAGE");
5372
0
    if (!errorMessage.IsEmpty()) {
5373
0
      auto* stdlibTgt = makefile->AddImportedTarget(
5374
0
        "@cmake_cxx_std", cm::TargetType::INTERFACE_LIBRARY,
5375
0
        cm::ImportedTargetScope::Global);
5376
0
      stdlibTgt->SetProperty("CXX_IMPORT_ERROR_MESSAGE", *errorMessage);
5377
0
      stdlibTgt->SetProperty("CXX_IMPORT_ERROR_MODULES", "std;std.compat");
5378
5379
0
      auto gt = cm::make_unique<cmGeneratorTarget>(stdlibTgt, lg);
5380
0
      lg->AddImportedGeneratorTarget(gt.get());
5381
0
      lg->AddOwnedImportedGeneratorTarget(std::move(gt));
5382
0
      return true;
5383
0
    }
5384
5385
0
    auto metadataPath =
5386
0
      makefile->GetDefinition("CMAKE_CXX_STDLIB_MODULES_JSON");
5387
0
    if (metadataPath.IsEmpty()) {
5388
0
      auto* stdlibTgt = makefile->AddImportedTarget(
5389
0
        "@cmake_cxx_std", cm::TargetType::INTERFACE_LIBRARY,
5390
0
        cm::ImportedTargetScope::Global);
5391
0
      stdlibTgt->SetProperty(
5392
0
        "CXX_IMPORT_ERROR_MESSAGE",
5393
0
        R"(CMAKE_CXX_STDLIB_MODULES_JSON set to empty string)");
5394
0
      stdlibTgt->SetProperty("CXX_IMPORT_ERROR_MODULES", "std;std.compat");
5395
5396
0
      auto gt = cm::make_unique<cmGeneratorTarget>(stdlibTgt, lg);
5397
0
      lg->AddImportedGeneratorTarget(gt.get());
5398
0
      lg->AddOwnedImportedGeneratorTarget(std::move(gt));
5399
0
      return true;
5400
0
    }
5401
5402
0
    auto parseResult = cmCxxModuleMetadata::LoadFromFile(*metadataPath);
5403
0
    if (!parseResult) {
5404
0
      makefile->IssueMessage(
5405
0
        MessageType::FATAL_ERROR,
5406
0
        cmStrCat("Failed to load C++ standard library modules metadata "
5407
0
                 "from \"",
5408
0
                 *metadataPath, "\": ", parseResult.Error));
5409
0
      return false;
5410
0
    }
5411
5412
0
    metadata = std::move(*parseResult.Meta);
5413
0
  }
5414
5415
0
  auto* stdlibTgt = makefile->AddImportedTarget(
5416
0
    "@cmake_cxx_std", cm::TargetType::INTERFACE_LIBRARY,
5417
0
    cm::ImportedTargetScope::Global);
5418
0
  cmCxxModuleMetadata::PopulateTarget(*stdlibTgt, *metadata, configs);
5419
0
  cmStandardLevelResolver standardResolver(makefile);
5420
0
  standardResolver.AddRequiredTargetFeature(stdlibTgt, "cxx_std_20");
5421
0
  auto gt = cm::make_unique<cmGeneratorTarget>(stdlibTgt, lg);
5422
0
  for (auto const& config : configs) {
5423
0
    gt->ComputeCompileFeatures(config);
5424
0
  }
5425
5426
0
  auto compilerId = makefile->GetSafeDefinition("CMAKE_CXX_COMPILER_ID");
5427
0
  if (compilerId == "MSVC") {
5428
0
    stdlibTgt->SetCxxModuleNeedsInterfaceObjects(true);
5429
0
  }
5430
5431
0
  lg->AddImportedGeneratorTarget(gt.get());
5432
0
  lg->AddOwnedImportedGeneratorTarget(std::move(gt));
5433
5434
0
#endif // CMAKE_BOOTSTRAP
5435
5436
0
  return true;
5437
0
}
5438
} // namespace
5439
5440
bool cmGeneratorTarget::ApplyCXXStdTarget()
5441
0
{
5442
0
  if (!cmExperimental::HasSupportEnabled(
5443
0
        *this->Makefile, cmExperimental::Feature::CxxImportStd)) {
5444
0
    return true;
5445
0
  }
5446
5447
0
  std::vector<std::string> const& configs =
5448
0
    this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
5449
5450
0
  bool needsStd = false;
5451
0
  if (this->Target->IsImported()) {
5452
0
    needsStd = this->HaveInterfaceCxx20ModuleSources();
5453
0
  } else {
5454
0
    for (auto const& config : configs) {
5455
0
      if (this->NeedCxxDyndep(config) == CxxModuleSupport::Enabled) {
5456
0
        needsStd = true;
5457
0
        break;
5458
0
      }
5459
0
    }
5460
0
  }
5461
0
  if (!needsStd) {
5462
0
    return true;
5463
0
  }
5464
5465
  // Create the single, unreferenceable import std target if it doesn't
5466
  // already exist. BMI compatibility handles per-consumer standard level
5467
  // differences by creating synthetic targets as needed.
5468
0
  if (!this->Makefile->FindTargetToUse("@cmake_cxx_std") &&
5469
0
      !CreateCxxStdlibTarget(this->Makefile, this->LocalGenerator, configs)) {
5470
0
    return false;
5471
0
  }
5472
5473
0
  if (this->Target->IsImported()) {
5474
0
    this->Target->AppendProperty("IMPORTED_CXX_MODULES_LINK_LIBRARIES",
5475
0
                                 "@cmake_cxx_std");
5476
0
  } else {
5477
0
    this->Target->AppendProperty("LINK_LIBRARIES",
5478
0
                                 "$<BUILD_LOCAL_INTERFACE:@cmake_cxx_std>");
5479
0
  }
5480
5481
0
  return true;
5482
0
}
5483
5484
bool cmGeneratorTarget::HasCxxImportModuleErrors() const
5485
0
{
5486
0
  return this->Target->GetProperty("CXX_IMPORT_ERROR_MODULES") != nullptr;
5487
0
}
5488
5489
cmCxxModuleUsageEffects const& cmGeneratorTarget::GetCxxModuleUsageEffects(
5490
  std::string const& config) const
5491
0
{
5492
5493
0
  auto iter = this->CxxModuleUsageEffects.find(config);
5494
0
  if (iter == this->CxxModuleUsageEffects.end()) {
5495
0
    auto result = this->CxxModuleUsageEffects.emplace(
5496
0
      std::pair<std::string, cmCxxModuleUsageEffects>{
5497
0
        config, cmCxxModuleUsageEffects(this, config) });
5498
0
    return result.first->second;
5499
0
  }
5500
5501
0
  return iter->second;
5502
0
}
5503
5504
cmGeneratorTarget const* cmGeneratorTarget::GetTargetForCxxModules(
5505
  std::string const& config, cmGeneratorTarget const& bmiConsumer) const
5506
0
{
5507
0
  auto const& consumingUsage = bmiConsumer.GetCxxModuleUsageEffects(config);
5508
0
  auto const& owningUsage = this->GetCxxModuleUsageEffects(config);
5509
0
  if (consumingUsage.GetHash() == owningUsage.GetHash()) {
5510
0
    if (this->IsImported()) {
5511
0
      return this->GetCxxSyntheticTarget(config, *this);
5512
0
    }
5513
0
    return this;
5514
0
  }
5515
5516
0
  return this->GetCxxSyntheticTarget(config, bmiConsumer);
5517
0
}
5518
5519
cmGeneratorTarget const* cmGeneratorTarget::GetCxxSyntheticTarget(
5520
  std::string const& config, cmGeneratorTarget const& bmiConsumer) const
5521
0
{
5522
0
  auto const& usageHash =
5523
0
    bmiConsumer.GetCxxModuleUsageEffects(config).GetHash();
5524
0
  auto cached = this->SynthCxxTargets.find(usageHash);
5525
0
  if (cached != this->SynthCxxTargets.end()) {
5526
0
    return cached->second;
5527
0
  }
5528
5529
0
  auto targetNameBase = this->GetName();
5530
0
  if (this->IsImported()) {
5531
0
    cmSystemTools::ReplaceString(targetNameBase, "::", "__");
5532
0
  }
5533
0
  auto const targetName =
5534
0
    cmStrCat(targetNameBase, "@synth_", this->SynthCxxTargets.size());
5535
5536
0
  std::vector<std::string> allConfigs =
5537
0
    this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
5538
0
  auto const* model = this->Target;
5539
0
  auto* mf = this->Makefile;
5540
0
  auto* lg = this->GetLocalGenerator();
5541
0
  auto* tgt =
5542
0
    mf->AddSynthesizedTarget(cm::TargetType::INTERFACE_LIBRARY, targetName);
5543
0
  if (model->CxxModuleNeedsInterfaceObjects()) {
5544
0
    tgt->SetCxxModuleNeedsInterfaceObjects(true);
5545
0
  }
5546
5547
  // Copy relevant information from the existing target.
5548
5549
  // Copy policies to the target.
5550
0
  tgt->CopyPolicyStatuses(model);
5551
5552
  // Copy file sets.
5553
0
  {
5554
0
    for (auto const* gfs :
5555
0
         this->GetInterfaceFileSets(cm::FileSetMetadata::CXX_MODULES)) {
5556
0
      auto* newFs =
5557
0
        tgt
5558
0
          ->GetOrCreateFileSet(gfs->GetName(), gfs->GetType(),
5559
0
                               cm::FileSetMetadata::Visibility::Public)
5560
0
          .first;
5561
0
      newFs->CopyEntries(gfs->GetFileSet());
5562
0
    }
5563
0
  }
5564
5565
  // Copy properties which effect consumer compatibility.
5566
  // CopyUsageEffects now uses the consumer's full (own + transitive)
5567
  // compile features and options.
5568
0
  tgt->CopyUsageEffects(&bmiConsumer, config);
5569
5570
0
  auto const& preprocessorCompileOptions =
5571
0
    this->GetCxxModuleUsageEffects(config).GetPreprocessorCompileOptions();
5572
0
  for (auto it = preprocessorCompileOptions.rbegin();
5573
0
       it != preprocessorCompileOptions.rend(); ++it) {
5574
0
    tgt->InsertCompileOption(*it, true);
5575
0
  }
5576
5577
  // Copy properties which don't effect consumer compatibility
5578
0
  tgt->CopyCxxModulesEntries(model);
5579
5580
  // Copy other properties which may affect the C++ module BMI generation.
5581
0
  tgt->CopyCxxModulesProperties(model);
5582
5583
0
  tgt->AddLinkLibrary(*mf, cmStrCat("$<COMPILE_ONLY:", model->GetName(), '>'),
5584
0
                      GENERAL_LibraryType);
5585
5586
  // Create the generator target and attach it to the local generator.
5587
0
  auto gtp = cm::make_unique<cmGeneratorTarget>(tgt, lg);
5588
0
  auto* syntheticTarget = gtp.get();
5589
5590
  // See `localGen->ComputeTargetCompileFeatures()` call in
5591
  // `cmGlobalGenerator::Compute` for where non-synthetic targets resolve
5592
  // this.
5593
0
  for (auto const& innerConfig : allConfigs) {
5594
0
    gtp->ComputeCompileFeatures(innerConfig);
5595
0
  }
5596
5597
0
  lg->AddGeneratorTarget(std::move(gtp));
5598
0
  this->SynthCxxTargets[usageHash] = syntheticTarget;
5599
0
  for (auto const& innerConfig : allConfigs) {
5600
0
    if (!syntheticTarget->DiscoverSyntheticTargets(innerConfig,
5601
0
                                                   &bmiConsumer)) {
5602
0
      return nullptr;
5603
0
    }
5604
0
  }
5605
5606
0
  return syntheticTarget;
5607
0
}
5608
5609
bool cmGeneratorTarget::DiscoverSyntheticTargets(
5610
  std::string const& config, cmGeneratorTarget const* bmiConsumer)
5611
0
{
5612
0
  auto& configInfo = this->Configs[config];
5613
0
  cmOptionalLinkImplementation impl;
5614
0
  this->ComputeLinkImplementationLibraries(config, impl, UseTo::Link);
5615
5616
0
  if (!bmiConsumer) {
5617
0
    bmiConsumer = this;
5618
0
  }
5619
5620
0
  auto& SyntheticDeps = configInfo.SyntheticDeps;
5621
5622
0
  for (auto const& entry : impl.Libraries) {
5623
0
    auto const* gt = entry.Target;
5624
0
    if (!gt || !gt->HaveInterfaceCxx20ModuleSources()) {
5625
0
      continue;
5626
0
    }
5627
5628
    // Visual Studio generators do not currently support BMI-only compilation,
5629
    // so they can't generate synthetic targets. For consuming native modules,
5630
    // skip so that the native target is used directly. For imported modules,
5631
    // create the synth target anyway and diagnose later, in the VS generator.
5632
0
    if (!gt->IsImported() && this->GlobalGenerator->IsVisualStudio()) {
5633
0
      continue;
5634
0
    }
5635
5636
0
    auto const* dep = gt->GetTargetForCxxModules(config, *bmiConsumer);
5637
0
    if (!dep) {
5638
0
      return false;
5639
0
    }
5640
0
    if (dep->IsSynthetic()) {
5641
0
      SyntheticDeps[gt].insert(dep);
5642
0
    }
5643
0
  }
5644
5645
0
  return true;
5646
0
}
5647
5648
cmGeneratorTarget::SyntheticDepsMap const& cmGeneratorTarget::GetSyntheticDeps(
5649
  std::string const& config) const
5650
0
{
5651
0
  return this->Configs[config].SyntheticDeps;
5652
0
}
5653
5654
bool cmGeneratorTarget::HasPackageReferences() const
5655
0
{
5656
0
  return this->IsInBuildSystem() &&
5657
0
    !this->GetProperty("VS_PACKAGE_REFERENCES")->empty();
5658
0
}
5659
5660
std::vector<std::string> cmGeneratorTarget::GetPackageReferences() const
5661
0
{
5662
0
  cmList packageReferences;
5663
5664
0
  if (this->IsInBuildSystem()) {
5665
0
    if (cmValue vsPackageReferences =
5666
0
          this->GetProperty("VS_PACKAGE_REFERENCES")) {
5667
0
      packageReferences.assign(*vsPackageReferences);
5668
0
    }
5669
0
  }
5670
5671
0
  return std::move(packageReferences.data());
5672
0
}
5673
5674
std::string cmGeneratorTarget::GetPDBDirectory(std::string const& config) const
5675
0
{
5676
0
  if (OutputInfo const* info = this->GetOutputInfo(config)) {
5677
    // Return the directory in which the target will be built.
5678
0
    return info->PdbDir;
5679
0
  }
5680
0
  return "";
5681
0
}
5682
5683
bool cmGeneratorTarget::HasImplibGNUtoMS(std::string const& config) const
5684
0
{
5685
0
  return this->HasImportLibrary(config) && this->GetPropertyAsBool("GNUtoMS");
5686
0
}
5687
5688
bool cmGeneratorTarget::GetImplibGNUtoMS(std::string const& config,
5689
                                         std::string const& gnuName,
5690
                                         std::string& out,
5691
                                         char const* newExt) const
5692
0
{
5693
0
  if (this->HasImplibGNUtoMS(config) && gnuName.size() > 6 &&
5694
0
      gnuName.substr(gnuName.size() - 6) == ".dll.a") {
5695
0
    out = cmStrCat(cm::string_view(gnuName).substr(0, gnuName.size() - 6),
5696
0
                   newExt ? newExt : ".lib");
5697
0
    return true;
5698
0
  }
5699
0
  return false;
5700
0
}
5701
5702
bool cmGeneratorTarget::HasContextDependentSources() const
5703
0
{
5704
0
  return this->SourcesAreContextDependent == Tribool::True;
5705
0
}
5706
5707
bool cmGeneratorTarget::IsExecutableWithExports() const
5708
0
{
5709
0
  return this->Target->IsExecutableWithExports();
5710
0
}
5711
5712
bool cmGeneratorTarget::IsSharedLibraryWithExports() const
5713
0
{
5714
0
  return this->Target->IsSharedLibraryWithExports();
5715
0
}
5716
5717
bool cmGeneratorTarget::HasImportLibrary(std::string const& config) const
5718
0
{
5719
0
  bool generate_Stubs = true;
5720
0
  if (this->GetGlobalGenerator()->IsXcode()) {
5721
    // take care of CMAKE_XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS variable
5722
    // as well as XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS property
5723
0
    if (cmValue propGenStubs =
5724
0
          this->GetProperty("XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS")) {
5725
0
      generate_Stubs = propGenStubs == "YES";
5726
0
    } else if (cmValue varGenStubs = this->Makefile->GetDefinition(
5727
0
                 "CMAKE_XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS")) {
5728
0
      generate_Stubs = varGenStubs == "YES";
5729
0
    }
5730
0
  }
5731
5732
0
  return (this->IsDLLPlatform() &&
5733
0
          (this->GetType() == cm::TargetType::SHARED_LIBRARY ||
5734
0
           this->IsExecutableWithExports()) &&
5735
          // Assemblies which have only managed code do not have
5736
          // import libraries.
5737
0
          this->GetManagedType(config) != ManagedType::Managed) ||
5738
0
    (this->IsAIX() && this->IsExecutableWithExports()) ||
5739
0
    (this->Makefile->PlatformSupportsAppleTextStubs() &&
5740
0
     this->IsSharedLibraryWithExports() && generate_Stubs);
5741
0
}
5742
5743
bool cmGeneratorTarget::NeedImportLibraryName(std::string const& config) const
5744
0
{
5745
0
  return this->HasImportLibrary(config) ||
5746
    // On DLL platforms we always generate the import library name
5747
    // just in case the sources have export markup.
5748
0
    (this->IsDLLPlatform() &&
5749
0
     (this->GetType() == cm::TargetType::EXECUTABLE ||
5750
0
      this->GetType() == cm::TargetType::MODULE_LIBRARY));
5751
0
}
5752
5753
bool cmGeneratorTarget::GetUseShortObjectNames(
5754
  cmStateEnums::IntermediateDirKind kind) const
5755
0
{
5756
0
  return this->LocalGenerator->UseShortObjectNames(kind);
5757
0
}
5758
5759
cmObjectLocations::UseShortPath
5760
cmGeneratorTarget::GetUseShortObjectNamesForInstall() const
5761
0
{
5762
0
  auto prop = this->Target->GetProperty("INSTALL_OBJECT_NAME_STRATEGY");
5763
0
  if (prop == "SHORT"_s) {
5764
0
    return cmObjectLocations::UseShortPath::Yes;
5765
0
  }
5766
0
  if (prop == "FULL"_s) {
5767
0
    return cmObjectLocations::UseShortPath::No;
5768
0
  }
5769
0
  if (prop.IsSet()) {
5770
0
    this->Makefile->IssueMessage(
5771
0
      MessageType::FATAL_ERROR,
5772
0
      cmStrCat("Property INSTALL_OBJECT_NAME_STRATEGY of target \"",
5773
0
               this->GetName(), "\" set to the unsupported strategy ", prop));
5774
0
  }
5775
0
  return cmObjectLocations::UseShortPath::No;
5776
0
}
5777
5778
std::string cmGeneratorTarget::GetSupportDirectory(
5779
  cmStateEnums::IntermediateDirKind kind) const
5780
0
{
5781
0
  cmLocalGenerator* lg = this->GetLocalGenerator();
5782
0
  auto targetDir = cmStrCat(lg->GetObjectOutputRoot(kind), '/',
5783
0
                            lg->GetTargetDirectory(this, kind));
5784
5785
0
#ifndef CMAKE_BOOTSTRAP
5786
0
  auto& tdr =
5787
0
    this->GetGlobalGenerator()->RegisterTargetDirectory(this, targetDir);
5788
0
  if (tdr.CollidesWith && !tdr.Warned) {
5789
0
    this->Makefile->IssueMessage(
5790
0
      MessageType::WARNING,
5791
0
      cmStrCat("The '", tdr.CollidesWith->GetName(), "' and '",
5792
0
               this->GetName(),
5793
0
               "' targets share an intermediate directory\n    ", targetDir,
5794
0
               "\nwhich may cause problems with the build graph. This project "
5795
0
               "is not compatible with the `SHORT` target intermediate "
5796
0
               "directory strategy. Possible remedies include: moving the "
5797
0
               "target into different directories or renaming a target."));
5798
0
    tdr.Warned = true;
5799
0
  }
5800
0
#endif
5801
5802
0
  return targetDir;
5803
0
}
5804
5805
std::string cmGeneratorTarget::GetCMFSupportDirectory(
5806
  cmStateEnums::IntermediateDirKind kind) const
5807
0
{
5808
0
  cmLocalGenerator* lg = this->GetLocalGenerator();
5809
0
  if (!lg->AlwaysUsesCMFPaths()) {
5810
0
    return cmStrCat(lg->GetCurrentBinaryDirectory(), "/CMakeFiles/",
5811
0
                    lg->GetTargetDirectory(this, kind));
5812
0
  }
5813
0
  return cmStrCat(lg->GetObjectOutputRoot(kind), '/',
5814
0
                  lg->GetTargetDirectory(this, kind));
5815
0
}
5816
5817
bool cmGeneratorTarget::IsLinkable() const
5818
0
{
5819
0
  return (this->GetType() == cm::TargetType::STATIC_LIBRARY ||
5820
0
          this->GetType() == cm::TargetType::SHARED_LIBRARY ||
5821
0
          this->GetType() == cm::TargetType::MODULE_LIBRARY ||
5822
0
          this->GetType() == cm::TargetType::UNKNOWN_LIBRARY ||
5823
0
          this->GetType() == cm::TargetType::OBJECT_LIBRARY ||
5824
0
          this->GetType() == cm::TargetType::INTERFACE_LIBRARY ||
5825
0
          this->IsExecutableWithExports());
5826
0
}
5827
5828
bool cmGeneratorTarget::HasLinkDependencyFile(std::string const& config) const
5829
0
{
5830
0
  if (this->GetType() != cm::TargetType::EXECUTABLE &&
5831
0
      this->GetType() != cm::TargetType::SHARED_LIBRARY &&
5832
0
      this->GetType() != cm::TargetType::MODULE_LIBRARY) {
5833
0
    return false;
5834
0
  }
5835
5836
0
  if (this->Target->GetProperty("LINK_DEPENDS_NO_SHARED").IsOn()) {
5837
    // Do not use the linker dependency file because it includes shared
5838
    // libraries as well
5839
0
    return false;
5840
0
  }
5841
5842
0
  std::string const depsUseLinker{ "CMAKE_LINK_DEPENDS_USE_LINKER" };
5843
0
  auto linkLanguage = this->GetLinkerLanguage(config);
5844
0
  std::string const langDepsUseLinker{ cmStrCat("CMAKE_", linkLanguage,
5845
0
                                                "_LINK_DEPENDS_USE_LINKER") };
5846
5847
0
  return (!this->Makefile->IsDefinitionSet(depsUseLinker) ||
5848
0
          this->Makefile->IsOn(depsUseLinker)) &&
5849
0
    this->Makefile->IsOn(langDepsUseLinker);
5850
0
}
5851
5852
bool cmGeneratorTarget::IsFrameworkOnApple() const
5853
0
{
5854
0
  return this->Target->IsFrameworkOnApple();
5855
0
}
5856
5857
bool cmGeneratorTarget::IsArchivedAIXSharedLibrary() const
5858
0
{
5859
0
  return this->Target->IsArchivedAIXSharedLibrary();
5860
0
}
5861
5862
bool cmGeneratorTarget::IsImportedFrameworkFolderOnApple(
5863
  std::string const& config) const
5864
0
{
5865
0
  if (this->IsApple() && this->IsImported() &&
5866
0
      (this->GetType() == cm::TargetType::STATIC_LIBRARY ||
5867
0
       this->GetType() == cm::TargetType::SHARED_LIBRARY ||
5868
0
       this->GetType() == cm::TargetType::UNKNOWN_LIBRARY)) {
5869
0
    std::string cfg = config;
5870
0
    if (cfg.empty() && this->GetGlobalGenerator()->IsXcode()) {
5871
      // FIXME(#25515): Remove the need for this workaround.
5872
      // The Xcode generator queries include directories without any
5873
      // specific configuration.  Pick one in case this target does
5874
      // not set either IMPORTED_LOCATION or IMPORTED_CONFIGURATIONS.
5875
0
      cfg =
5876
0
        this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig)[0];
5877
0
    }
5878
0
    return cmSystemTools::IsPathToFramework(this->GetLocation(cfg));
5879
0
  }
5880
5881
0
  return false;
5882
0
}
5883
5884
bool cmGeneratorTarget::IsAppBundleOnApple() const
5885
0
{
5886
0
  return this->Target->IsAppBundleOnApple();
5887
0
}
5888
5889
bool cmGeneratorTarget::IsXCTestOnApple() const
5890
0
{
5891
0
  return (this->IsCFBundleOnApple() && this->GetPropertyAsBool("XCTEST"));
5892
0
}
5893
5894
bool cmGeneratorTarget::IsCFBundleOnApple() const
5895
0
{
5896
0
  return (this->GetType() == cm::TargetType::MODULE_LIBRARY &&
5897
0
          this->IsApple() && this->GetPropertyAsBool("BUNDLE"));
5898
0
}
5899
5900
cmGeneratorTarget::ManagedType cmGeneratorTarget::CheckManagedType(
5901
  std::string const& propval) const
5902
0
{
5903
  // The type of the managed assembly (mixed unmanaged C++ and C++/CLI,
5904
  // or only C++/CLI) does only depend on whether the property is an empty
5905
  // string or contains any value at all. In Visual Studio generators
5906
  // this propval is prepended with /clr[:] which results in:
5907
  //
5908
  // 1. propval does not exist: no /clr flag, unmanaged target, has import
5909
  //                            lib
5910
  // 2. empty propval:          add /clr as flag, mixed unmanaged/managed
5911
  //                            target, has import lib
5912
  // 3. netcore propval:        add /clr:netcore as flag, mixed
5913
  //                            unmanaged/managed target, has import lib.
5914
  // 4. any value (safe,pure):  add /clr:[propval] as flag, target with
5915
  //                            managed code only, no import lib
5916
0
  if (propval.empty() || propval == "netcore") {
5917
0
    return ManagedType::Mixed;
5918
0
  }
5919
0
  return ManagedType::Managed;
5920
0
}
5921
5922
cmGeneratorTarget::ManagedType cmGeneratorTarget::GetManagedType(
5923
  std::string const& config) const
5924
0
{
5925
  // Only libraries and executables can be managed targets.
5926
0
  if (this->GetType() > cm::TargetType::SHARED_LIBRARY) {
5927
0
    return ManagedType::Undefined;
5928
0
  }
5929
5930
0
  if (this->GetType() == cm::TargetType::STATIC_LIBRARY) {
5931
0
    return ManagedType::Native;
5932
0
  }
5933
5934
  // Check imported target.
5935
0
  if (this->IsImported()) {
5936
0
    if (cmGeneratorTarget::ImportInfo const* info =
5937
0
          this->GetImportInfo(config)) {
5938
0
      return info->Managed;
5939
0
    }
5940
0
    return ManagedType::Undefined;
5941
0
  }
5942
5943
  // Check for explicitly set clr target property.
5944
0
  if (cmValue clr = this->GetProperty("COMMON_LANGUAGE_RUNTIME")) {
5945
0
    return this->CheckManagedType(*clr);
5946
0
  }
5947
5948
  // C# targets are always managed. This language specific check
5949
  // is added to avoid that the COMMON_LANGUAGE_RUNTIME target property
5950
  // has to be set manually for C# targets.
5951
0
  return this->IsCSharpOnly() ? ManagedType::Managed : ManagedType::Native;
5952
0
}
5953
5954
std::string cmGeneratorTarget::GetImportedXcFrameworkPath(
5955
  std::string const& config) const
5956
0
{
5957
0
  if (!(this->IsApple() && this->IsImported() &&
5958
0
        (this->GetType() == cm::TargetType::SHARED_LIBRARY ||
5959
0
         this->GetType() == cm::TargetType::STATIC_LIBRARY ||
5960
0
         this->GetType() == cm::TargetType::UNKNOWN_LIBRARY))) {
5961
0
    return {};
5962
0
  }
5963
5964
0
  std::string desiredConfig = config;
5965
0
  if (config.empty()) {
5966
0
    desiredConfig = "NOCONFIG";
5967
0
  }
5968
5969
0
  std::string result;
5970
5971
0
  cmValue loc = nullptr;
5972
0
  cmValue imp = nullptr;
5973
0
  std::string suffix;
5974
5975
0
  if (this->Target->GetMappedConfig(desiredConfig, loc, imp, suffix)) {
5976
0
    if (loc) {
5977
0
      result = *loc;
5978
0
    } else {
5979
0
      std::string impProp = cmStrCat("IMPORTED_LOCATION", suffix);
5980
0
      if (cmValue configLocation = this->GetProperty(impProp)) {
5981
0
        result = *configLocation;
5982
0
      } else if (cmValue location = this->GetProperty("IMPORTED_LOCATION")) {
5983
0
        result = *location;
5984
0
      }
5985
0
    }
5986
5987
0
    if (cmSystemTools::IsPathToXcFramework(result)) {
5988
0
      return result;
5989
0
    }
5990
0
  }
5991
5992
0
  return {};
5993
0
}
5994
5995
bool cmGeneratorTarget::HaveFortranSources(std::string const& config) const
5996
0
{
5997
0
  auto sources = this->GetSourceFiles(config);
5998
0
  bool const have_direct = std::any_of(
5999
0
    sources.begin(), sources.end(), [](BT<cmSourceFile*> const& sf) -> bool {
6000
0
      return sf.Value->GetLanguage() == "Fortran"_s;
6001
0
    });
6002
0
  bool have_via_target_objects = false;
6003
0
  if (!have_direct) {
6004
0
    auto const sourceObjectLibraries = this->GetSourceObjectLibraries(config);
6005
0
    have_via_target_objects =
6006
0
      std::any_of(sourceObjectLibraries.begin(), sourceObjectLibraries.end(),
6007
0
                  [&config](cmGeneratorTarget const* tgt) -> bool {
6008
0
                    return tgt->HaveFortranSources(config);
6009
0
                  });
6010
0
  }
6011
0
  return have_direct || have_via_target_objects;
6012
0
}
6013
6014
bool cmGeneratorTarget::HaveFortranSources() const
6015
0
{
6016
0
  auto sources = this->GetAllConfigSources();
6017
0
  bool const have_direct = std::any_of(
6018
0
    sources.begin(), sources.end(), [](AllConfigSource const& sf) -> bool {
6019
0
      return sf.Source->GetLanguage() == "Fortran"_s;
6020
0
    });
6021
0
  bool have_via_target_objects = false;
6022
0
  if (!have_direct) {
6023
0
    std::vector<std::string> configs =
6024
0
      this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
6025
0
    for (auto const& config : configs) {
6026
0
      auto const sourceObjectLibraries =
6027
0
        this->GetSourceObjectLibraries(config);
6028
0
      have_via_target_objects =
6029
0
        std::any_of(sourceObjectLibraries.begin(), sourceObjectLibraries.end(),
6030
0
                    [&config](cmGeneratorTarget const* tgt) -> bool {
6031
0
                      return tgt->HaveFortranSources(config);
6032
0
                    });
6033
0
      if (have_via_target_objects) {
6034
0
        break;
6035
0
      }
6036
0
    }
6037
0
  }
6038
0
  return have_direct || have_via_target_objects;
6039
0
}
6040
6041
bool cmGeneratorTarget::HaveInterfaceCxx20ModuleSources() const
6042
0
{
6043
0
  return !this->GetInterfaceFileSets(cm::FileSetMetadata::CXX_MODULES).empty();
6044
0
}
6045
bool cmGeneratorTarget::HaveCxx20ModuleSources() const
6046
0
{
6047
0
  return !this->GetFileSets(cm::FileSetMetadata::CXX_MODULES).empty() ||
6048
0
    !this->GetInterfaceFileSets(cm::FileSetMetadata::CXX_MODULES).empty();
6049
0
}
6050
6051
cmGeneratorTarget::Cxx20SupportLevel cmGeneratorTarget::HaveCxxModuleSupport(
6052
  std::string const& config) const
6053
0
{
6054
0
  auto const* state = this->Makefile->GetState();
6055
0
  if (!state->GetLanguageEnabled("CXX")) {
6056
0
    return Cxx20SupportLevel::MissingCxx;
6057
0
  }
6058
6059
0
  cmValue standardDefault =
6060
0
    this->Makefile->GetDefinition("CMAKE_CXX_STANDARD_DEFAULT");
6061
0
  if (!standardDefault || standardDefault->empty()) {
6062
    // We do not know any meaningful C++ standard levels for this compiler.
6063
0
    return Cxx20SupportLevel::NoCxx20;
6064
0
  }
6065
6066
0
  cmStandardLevelResolver standardResolver(this->Makefile);
6067
0
  cmStandardLevel const cxxStd20 =
6068
0
    *standardResolver.LanguageStandardLevel("CXX", "20");
6069
0
  cm::optional<cmStandardLevel> explicitLevel =
6070
0
    this->GetExplicitStandardLevel("CXX", config);
6071
0
  if (!explicitLevel || *explicitLevel < cxxStd20) {
6072
0
    return Cxx20SupportLevel::NoCxx20;
6073
0
  }
6074
6075
0
  cmValue scandepRule =
6076
0
    this->Makefile->GetDefinition("CMAKE_CXX_SCANDEP_SOURCE");
6077
0
  if (!scandepRule) {
6078
0
    return Cxx20SupportLevel::MissingRule;
6079
0
  }
6080
0
  return Cxx20SupportLevel::Supported;
6081
0
}
6082
6083
void cmGeneratorTarget::CheckCxxModuleStatus(std::string const& config) const
6084
0
{
6085
0
  bool haveScannableSources = false;
6086
6087
  // Check for `CXX_MODULE*` file sets and a lack of support.
6088
0
  if (this->HaveCxx20ModuleSources()) {
6089
0
    haveScannableSources = true;
6090
0
  }
6091
6092
0
  if (!haveScannableSources) {
6093
    // Check to see if there are regular sources that have requested scanning.
6094
0
    auto sources = this->GetSourceFiles(config);
6095
0
    for (auto const& source : sources) {
6096
0
      auto const* sf = source.Value;
6097
0
      auto const& lang = sf->GetLanguage();
6098
0
      if (lang != "CXX"_s) {
6099
0
        continue;
6100
0
      }
6101
      // Ignore sources which do not need dyndep.
6102
0
      if (this->NeedDyndepForSource(lang, config, sf)) {
6103
0
        haveScannableSources = true;
6104
0
      }
6105
0
    }
6106
0
  }
6107
6108
  // If there isn't anything scannable, ignore it.
6109
0
  if (!haveScannableSources) {
6110
0
    return;
6111
0
  }
6112
6113
  // If the generator doesn't support modules at all, error that we have
6114
  // sources that require the support.
6115
0
  if (!this->GetGlobalGenerator()->CheckCxxModuleSupport(
6116
0
        cmGlobalGenerator::CxxModuleSupportQuery::Expected)) {
6117
0
    this->Makefile->IssueMessage(
6118
0
      MessageType::FATAL_ERROR,
6119
0
      cmStrCat("The target named \"", this->GetName(),
6120
0
               "\" has C++ sources that may use modules, but modules are not "
6121
0
               "supported by this generator:\n  ",
6122
0
               this->GetGlobalGenerator()->GetName(),
6123
0
               "\n"
6124
0
               "Modules are supported only by Ninja, Ninja Multi-Config, "
6125
0
               "and Visual Studio generators for VS 17.4 and newer.  "
6126
0
               "See the cmake-cxxmodules(7) manual for details.  "
6127
0
               "Use the CMAKE_CXX_SCAN_FOR_MODULES variable to enable or "
6128
0
               "disable scanning."));
6129
0
    return;
6130
0
  }
6131
6132
0
  switch (this->HaveCxxModuleSupport(config)) {
6133
0
    case cmGeneratorTarget::Cxx20SupportLevel::MissingCxx:
6134
0
      this->Makefile->IssueMessage(
6135
0
        MessageType::FATAL_ERROR,
6136
0
        cmStrCat("The target named \"", this->GetName(),
6137
0
                 "\" has C++ sources that use modules, but the \"CXX\" "
6138
0
                 "language has not been enabled."));
6139
0
      break;
6140
0
    case cmGeneratorTarget::Cxx20SupportLevel::NoCxx20: {
6141
0
      cmStandardLevelResolver standardResolver(this->Makefile);
6142
0
      auto effStandard =
6143
0
        standardResolver.GetEffectiveStandard(this, "CXX", config);
6144
0
      if (effStandard.empty()) {
6145
0
        effStandard = "; no C++ standard found";
6146
0
      } else {
6147
0
        effStandard = cmStrCat("; found \"cxx_std_", effStandard, '"');
6148
0
      }
6149
0
      this->Makefile->IssueMessage(
6150
0
        MessageType::FATAL_ERROR,
6151
0
        cmStrCat(
6152
0
          "The target named \"", this->GetName(),
6153
0
          "\" has C++ sources that use modules, but does not include "
6154
0
          "\"cxx_std_20\" (or newer) among its `target_compile_features`",
6155
0
          effStandard, '.'));
6156
0
    } break;
6157
0
    case cmGeneratorTarget::Cxx20SupportLevel::MissingRule: {
6158
0
      this->Makefile->IssueMessage(
6159
0
        MessageType::FATAL_ERROR,
6160
0
        cmStrCat("The target named \"", this->GetName(),
6161
0
                 "\" has C++ sources that may use modules, but the compiler "
6162
0
                 "does not provide a way to discover the import graph "
6163
0
                 "dependencies.  See the cmake-cxxmodules(7) manual for "
6164
0
                 "details.  Use the CMAKE_CXX_SCAN_FOR_MODULES variable to "
6165
0
                 "enable or disable scanning."));
6166
0
    } break;
6167
0
    case cmGeneratorTarget::Cxx20SupportLevel::Supported:
6168
      // All is well.
6169
0
      break;
6170
0
  }
6171
0
}
6172
6173
bool cmGeneratorTarget::NeedCxxModuleSupport(std::string const& lang,
6174
                                             std::string const& config) const
6175
0
{
6176
0
  if (lang != "CXX"_s) {
6177
0
    return false;
6178
0
  }
6179
0
  return this->HaveCxxModuleSupport(config) == Cxx20SupportLevel::Supported &&
6180
0
    this->GetGlobalGenerator()->CheckCxxModuleSupport(
6181
0
      cmGlobalGenerator::CxxModuleSupportQuery::Inspect);
6182
0
}
6183
6184
bool cmGeneratorTarget::NeedDyndep(std::string const& lang,
6185
                                   std::string const& config) const
6186
0
{
6187
0
  return lang == "Fortran"_s || this->NeedCxxModuleSupport(lang, config);
6188
0
}
6189
6190
bool cmGeneratorTarget::NeedDyndepForSource(std::string const& lang,
6191
                                            std::string const& config,
6192
                                            cmSourceFile const* sf) const
6193
0
{
6194
  // Fortran always needs to be scanned.
6195
0
  if (lang == "Fortran"_s) {
6196
0
    return true;
6197
0
  }
6198
  // Only C++ code needs scanned otherwise.
6199
0
  if (lang != "CXX"_s) {
6200
0
    return false;
6201
0
  }
6202
6203
  // Any file in `CXX_MODULES` file sets need scanned (it being `CXX` is
6204
  // enforced elsewhere).
6205
0
  auto const* fs = this->GetFileSetForSource(config, sf);
6206
0
  if (fs && fs->GetType() == cm::FileSetMetadata::CXX_MODULES) {
6207
0
    return true;
6208
0
  }
6209
6210
0
  auto targetDyndep = this->NeedCxxDyndep(config);
6211
0
  if (targetDyndep == CxxModuleSupport::Unavailable) {
6212
0
    return false;
6213
0
  }
6214
0
  if (fs) {
6215
0
    auto const fsProp = fs->GetProperty("CXX_SCAN_FOR_MODULES");
6216
0
    if (fsProp.IsSet()) {
6217
0
      return fsProp.IsOn();
6218
0
    }
6219
0
  }
6220
0
  auto const sfProp = sf->GetProperty("CXX_SCAN_FOR_MODULES");
6221
0
  if (sfProp.IsSet()) {
6222
0
    return sfProp.IsOn();
6223
0
  }
6224
0
  return targetDyndep == CxxModuleSupport::Enabled;
6225
0
}
6226
6227
cmGeneratorTarget::CxxModuleSupport cmGeneratorTarget::NeedCxxDyndep(
6228
  std::string const& config) const
6229
0
{
6230
0
  bool haveRule = false;
6231
0
  switch (this->HaveCxxModuleSupport(config)) {
6232
0
    case Cxx20SupportLevel::MissingCxx:
6233
0
    case Cxx20SupportLevel::NoCxx20:
6234
0
      return CxxModuleSupport::Unavailable;
6235
0
    case Cxx20SupportLevel::MissingRule:
6236
0
      break;
6237
0
    case Cxx20SupportLevel::Supported:
6238
0
      haveRule = true;
6239
0
      break;
6240
0
  }
6241
0
  bool haveGeneratorSupport =
6242
0
    this->GetGlobalGenerator()->CheckCxxModuleSupport(
6243
0
      cmGlobalGenerator::CxxModuleSupportQuery::Inspect);
6244
0
  auto const tgtProp = this->GetProperty("CXX_SCAN_FOR_MODULES");
6245
0
  if (tgtProp.IsSet()) {
6246
0
    return tgtProp.IsOn() ? CxxModuleSupport::Enabled
6247
0
                          : CxxModuleSupport::Disabled;
6248
0
  }
6249
6250
0
  CxxModuleSupport policyAnswer = CxxModuleSupport::Unavailable;
6251
0
  switch (this->GetPolicyStatusCMP0155()) {
6252
0
    case cmPolicies::WARN:
6253
0
    case cmPolicies::OLD:
6254
      // The OLD behavior is to not scan the source.
6255
0
      policyAnswer = CxxModuleSupport::Disabled;
6256
0
      break;
6257
0
    case cmPolicies::NEW:
6258
      // The NEW behavior is to scan the source if the compiler supports
6259
      // scanning and the generator supports it.
6260
0
      if (haveRule && haveGeneratorSupport) {
6261
0
        policyAnswer = CxxModuleSupport::Enabled;
6262
0
      } else {
6263
0
        policyAnswer = CxxModuleSupport::Disabled;
6264
0
      }
6265
0
      break;
6266
0
  }
6267
0
  return policyAnswer;
6268
0
}
6269
6270
bool cmGeneratorTarget::HasFileSets() const
6271
0
{
6272
0
  return !this->FileSets->Empty();
6273
0
}
6274
6275
std::vector<cmGeneratorFileSet const*> const&
6276
cmGeneratorTarget::GetAllFileSets() const
6277
0
{
6278
0
  return this->FileSets->GetAllFileSets();
6279
0
}
6280
6281
std::vector<cmGeneratorFileSet const*> const& cmGeneratorTarget::GetFileSets(
6282
  cm::string_view type) const
6283
0
{
6284
0
  return this->FileSets->GetFileSets(type);
6285
0
}
6286
std::vector<cmGeneratorFileSet const*> const&
6287
cmGeneratorTarget::GetInterfaceFileSets(cm::string_view type) const
6288
0
{
6289
0
  return this->FileSets->GetInterfaceFileSets(type);
6290
0
}
6291
6292
cmGeneratorFileSet const* cmGeneratorTarget::GetFileSet(
6293
  std::string const& name) const
6294
0
{
6295
0
  return this->FileSets->GetFileSet(name);
6296
0
}
6297
6298
cmGeneratorFileSet const* cmGeneratorTarget::GetFileSetForSource(
6299
  std::string const& config, cmSourceFile const* sf) const
6300
0
{
6301
0
  return this->FileSets->GetFileSetForSource(config, sf);
6302
0
}
6303
6304
std::string cmGeneratorTarget::BuildDatabasePath(
6305
  std::string const& lang, std::string const& config) const
6306
0
{
6307
  // Check to see if the target wants it.
6308
0
  if (!this->GetPropertyAsBool("EXPORT_BUILD_DATABASE")) {
6309
0
    return {};
6310
0
  }
6311
0
  if (!cmExperimental::HasSupportEnabled(
6312
0
        *this->Makefile, cmExperimental::Feature::ExportBuildDatabase)) {
6313
0
    return {};
6314
0
  }
6315
  // Check to see if the generator supports it.
6316
0
  if (!this->GetGlobalGenerator()->SupportsBuildDatabase()) {
6317
0
    return {};
6318
0
  }
6319
6320
0
  if (this->GetGlobalGenerator()->IsMultiConfig()) {
6321
0
    return cmStrCat(this->GetSupportDirectory(), '/', config, '/', lang,
6322
0
                    "_build_database.json");
6323
0
  }
6324
6325
0
  return cmStrCat(this->GetSupportDirectory(), '/', lang,
6326
0
                  "_build_database.json");
6327
0
}
6328
6329
std::string cmGeneratorTarget::GetSwiftPackageName() const
6330
0
{
6331
0
  std::string packageName;
6332
0
  if (cmValue projectName = this->GetProperty("Swift_PACKAGE_NAME")) {
6333
0
    packageName = *projectName;
6334
0
  } else if (this->GetPolicyStatusCMP0216() == cmPolicies::NEW) {
6335
0
    packageName = this->Makefile->GetSafeDefinition("PROJECT_NAME");
6336
0
  }
6337
0
  return packageName;
6338
0
}
6339
6340
std::string cmGeneratorTarget::GetSwiftModuleName() const
6341
0
{
6342
0
  if (cmValue name = this->GetProperty("Swift_MODULE_NAME")) {
6343
0
    return *name;
6344
0
  }
6345
  // Hyphens are not valid in Swift module identifiers.
6346
0
  std::string name = this->GetName();
6347
0
  std::replace(name.begin(), name.end(), '-', '_');
6348
0
  return name;
6349
0
}
6350
6351
std::string cmGeneratorTarget::GetSwiftModuleFileName() const
6352
0
{
6353
0
  std::string moduleFilename = this->GetPropertyOrDefault(
6354
0
    "Swift_MODULE", this->GetSwiftModuleName() + ".swiftmodule");
6355
0
  if (this->GetPolicyStatusCMP0195() == cmPolicies::NEW) {
6356
0
    if (cmValue moduleTriple =
6357
0
          this->Makefile->GetDefinition("CMAKE_Swift_MODULE_TRIPLE")) {
6358
0
      moduleFilename = cmStrCat(std::move(moduleFilename), '/', *moduleTriple,
6359
0
                                ".swiftmodule");
6360
0
    }
6361
0
  }
6362
0
  return moduleFilename;
6363
0
}
6364
6365
std::string cmGeneratorTarget::GetSwiftModuleDirectory(
6366
  std::string const& config) const
6367
0
{
6368
  // This is like the *_OUTPUT_DIRECTORY properties except that we don't have a
6369
  // separate per-configuration target property.
6370
  //
6371
  // The property expands generator expressions. Multi-config generators append
6372
  // a per-configuration subdirectory to the specified directory unless a
6373
  // generator expression is used.
6374
0
  bool appendConfigDir = true;
6375
0
  std::string moduleDirectory;
6376
6377
0
  if (cmValue value = this->GetProperty("Swift_MODULE_DIRECTORY")) {
6378
0
    moduleDirectory = cmGeneratorExpression::Evaluate(
6379
0
      *value, this->LocalGenerator, config, this);
6380
0
    appendConfigDir = *value == moduleDirectory;
6381
0
  }
6382
0
  if (moduleDirectory.empty()) {
6383
0
    moduleDirectory = this->LocalGenerator->GetCurrentBinaryDirectory();
6384
0
  }
6385
0
  if (appendConfigDir) {
6386
0
    this->LocalGenerator->GetGlobalGenerator()->AppendDirectoryForConfig(
6387
0
      "/", config, "", moduleDirectory);
6388
0
  }
6389
0
  return moduleDirectory;
6390
0
}
6391
6392
std::string cmGeneratorTarget::GetSwiftModulePath(
6393
  std::string const& config) const
6394
0
{
6395
0
  return cmStrCat(this->GetSwiftModuleDirectory(config), '/',
6396
0
                  this->GetSwiftModuleFileName());
6397
0
}
6398
6399
std::string cmGeneratorTarget::GetPropertyOrDefault(
6400
  std::string const& property, std::string defaultValue) const
6401
0
{
6402
0
  if (cmValue name = this->GetProperty(property)) {
6403
0
    return *name;
6404
0
  }
6405
0
  return defaultValue;
6406
0
}