Coverage Report

Created: 2026-07-14 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/CMake/Source/cmComputeLinkDepends.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 "cmComputeLinkDepends.h"
4
5
#include <algorithm>
6
#include <cassert>
7
#include <cstddef>
8
#include <cstdio>
9
#include <iterator>
10
#include <sstream>
11
#include <unordered_map>
12
#include <utility>
13
14
#include <cm/memory>
15
#include <cm/string_view>
16
#include <cmext/string_view>
17
18
#include "cmsys/RegularExpression.hxx"
19
20
#include "cmComputeComponentGraph.h"
21
#include "cmDiagnostics.h"
22
#include "cmGenExContext.h"
23
#include "cmGeneratorExpression.h"
24
#include "cmGeneratorExpressionDAGChecker.h"
25
#include "cmGeneratorTarget.h"
26
#include "cmGlobalGenerator.h"
27
#include "cmList.h"
28
#include "cmListFileCache.h"
29
#include "cmLocalGenerator.h"
30
#include "cmMakefile.h"
31
#include "cmMessageType.h"
32
#include "cmPolicies.h"
33
#include "cmRange.h"
34
#include "cmState.h"
35
#include "cmStringAlgorithms.h"
36
#include "cmTarget.h"
37
#include "cmTargetTypes.h"
38
#include "cmValue.h"
39
#include "cmake.h"
40
41
/*
42
43
This file computes an ordered list of link items to use when linking a
44
single target in one configuration.  Each link item is identified by
45
the string naming it.  A graph of dependencies is created in which
46
each node corresponds to one item and directed edges lead from nodes to
47
those which must *follow* them on the link line.  For example, the
48
graph
49
50
  A -> B -> C
51
52
will lead to the link line order
53
54
  A B C
55
56
The set of items placed in the graph is formed with a breadth-first
57
search of the link dependencies starting from the main target.
58
59
There are two types of items: those with known direct dependencies and
60
those without known dependencies.  We will call the two types "known
61
items" and "unknown items", respectively.  Known items are those whose
62
names correspond to targets (built or imported) and those for which an
63
old-style <item>_LIB_DEPENDS variable is defined.  All other items are
64
unknown and we must infer dependencies for them.  For items that look
65
like flags (beginning with '-') we trivially infer no dependencies,
66
and do not include them in the dependencies of other items.
67
68
Known items have dependency lists ordered based on how the user
69
specified them.  We can use this order to infer potential dependencies
70
of unknown items.  For example, if link items A and B are unknown and
71
items X and Y are known, then we might have the following dependency
72
lists:
73
74
  X: Y A B
75
  Y: A B
76
77
The explicitly known dependencies form graph edges
78
79
  X -> Y  ,  X -> A  ,  X -> B  ,  Y -> A  ,  Y -> B
80
81
We can also infer the edge
82
83
  A -> B
84
85
because *every* time A appears B is seen on its right.  We do not know
86
whether A really needs symbols from B to link, but it *might* so we
87
must preserve their order.  This is the case also for the following
88
explicit lists:
89
90
  X: A B Y
91
  Y: A B
92
93
Here, A is followed by the set {B,Y} in one list, and {B} in the other
94
list.  The intersection of these sets is {B}, so we can infer that A
95
depends on at most B.  Meanwhile B is followed by the set {Y} in one
96
list and {} in the other.  The intersection is {} so we can infer that
97
B has no dependencies.
98
99
Let's make a more complex example by adding unknown item C and
100
considering these dependency lists:
101
102
  X: A B Y C
103
  Y: A C B
104
105
The explicit edges are
106
107
  X -> Y  ,  X -> A  ,  X -> B  ,  X -> C  ,  Y -> A  ,  Y -> B  ,  Y -> C
108
109
For the unknown items, we infer dependencies by looking at the
110
"follow" sets:
111
112
  A: intersect( {B,Y,C} , {C,B} ) = {B,C} ; infer edges  A -> B  ,  A -> C
113
  B: intersect( {Y,C}   , {}    ) = {}    ; infer no edges
114
  C: intersect( {}      , {B}   ) = {}    ; infer no edges
115
116
Note that targets are never inferred as dependees because outside
117
libraries should not depend on them.
118
119
------------------------------------------------------------------------------
120
121
The initial exploration of dependencies using a BFS associates an
122
integer index with each link item.  When the graph is built outgoing
123
edges are sorted by this index.
124
125
After the initial exploration of the link interface tree, any
126
transitive (dependent) shared libraries that were encountered and not
127
included in the interface are processed in their own BFS.  This BFS
128
follows only the dependent library lists and not the link interfaces.
129
They are added to the link items with a mark indicating that the are
130
transitive dependencies.  Then cmComputeLinkInformation deals with
131
them on a per-platform basis.
132
133
The complete graph formed from all known and inferred dependencies may
134
not be acyclic, so an acyclic version must be created.
135
The original graph is converted to a directed acyclic graph in which
136
each node corresponds to a strongly connected component of the
137
original graph.  For example, the dependency graph
138
139
  X -> A -> B -> C -> A -> Y
140
141
contains strongly connected components {X}, {A,B,C}, and {Y}.  The
142
implied directed acyclic graph (DAG) is
143
144
  {X} -> {A,B,C} -> {Y}
145
146
We then compute a topological order for the DAG nodes to serve as a
147
reference for satisfying dependencies efficiently.  We perform the DFS
148
in reverse order and assign topological order indices counting down so
149
that the result is as close to the original BFS order as possible
150
without violating dependencies.
151
152
------------------------------------------------------------------------------
153
154
The final link entry order is constructed as follows.  We first walk
155
through and emit the *original* link line as specified by the user.
156
As each item is emitted, a set of pending nodes in the component DAG
157
is maintained.  When a pending component has been completely seen, it
158
is removed from the pending set and its dependencies (following edges
159
of the DAG) are added.  A trivial component (those with one item) is
160
complete as soon as its item is seen.  A non-trivial component (one
161
with more than one item; assumed to be static libraries) is complete
162
when *all* its entries have been seen *twice* (all entries seen once,
163
then all entries seen again, not just each entry twice).  A pending
164
component tracks which items have been seen and a count of how many
165
times the component needs to be seen (once for trivial components,
166
twice for non-trivial).  If at any time another component finishes and
167
re-adds an already pending component, the pending component is reset
168
so that it needs to be seen in its entirety again.  This ensures that
169
all dependencies of a component are satisfied no matter where it
170
appears.
171
172
After the original link line has been completed, we append to it the
173
remaining pending components and their dependencies.  This is done by
174
repeatedly emitting the first item from the first pending component
175
and following the same update rules as when traversing the original
176
link line.  Since the pending components are kept in topological order
177
they are emitted with minimal repeats (we do not want to emit a
178
component just to have it added again when another component is
179
completed later).  This process continues until no pending components
180
remain.  We know it will terminate because the component graph is
181
guaranteed to be acyclic.
182
183
The final list of items produced by this procedure consists of the
184
original user link line followed by minimal additional items needed to
185
satisfy dependencies.  The final list is then filtered to de-duplicate
186
items that we know the linker will reuse automatically (shared libs).
187
188
*/
189
190
namespace {
191
// LINK_LIBRARY helpers
192
bool IsFeatureSupported(cmMakefile* makefile, std::string const& linkLanguage,
193
                        std::string const& feature)
194
0
{
195
0
  auto featureSupported = cmStrCat(
196
0
    "CMAKE_", linkLanguage, "_LINK_LIBRARY_USING_", feature, "_SUPPORTED");
197
0
  if (cmValue perLangVar = makefile->GetDefinition(featureSupported)) {
198
0
    return perLangVar.IsOn();
199
0
  }
200
201
0
  featureSupported =
202
0
    cmStrCat("CMAKE_LINK_LIBRARY_USING_", feature, "_SUPPORTED");
203
0
  return makefile->GetDefinition(featureSupported).IsOn();
204
0
}
205
206
// LINK_LIBRARY feature attributes management
207
struct LinkLibraryFeatureAttributeSet
208
{
209
  std::set<cm::TargetType> LibraryTypes = { cm::TargetType::EXECUTABLE,
210
                                            cm::TargetType::STATIC_LIBRARY,
211
                                            cm::TargetType::SHARED_LIBRARY,
212
                                            cm::TargetType::MODULE_LIBRARY,
213
                                            cm::TargetType::UNKNOWN_LIBRARY };
214
  std::set<std::string> Override;
215
216
  enum DeduplicationKind
217
  {
218
    Default,
219
    Yes,
220
    No
221
  };
222
  DeduplicationKind Deduplication = Default;
223
};
224
std::map<std::string, LinkLibraryFeatureAttributeSet>
225
  LinkLibraryFeatureAttributes;
226
LinkLibraryFeatureAttributeSet const& GetLinkLibraryFeatureAttributes(
227
  cmMakefile* makefile, std::string const& linkLanguage,
228
  std::string const& feature)
229
0
{
230
0
  auto it = LinkLibraryFeatureAttributes.find(feature);
231
0
  if (it != LinkLibraryFeatureAttributes.end()) {
232
0
    return it->second;
233
0
  }
234
235
0
  auto featureAttributesVariable =
236
0
    cmStrCat("CMAKE_", linkLanguage, "_LINK_LIBRARY_", feature, "_ATTRIBUTES");
237
0
  auto featureAttributesValues =
238
0
    makefile->GetDefinition(featureAttributesVariable);
239
0
  if (featureAttributesValues.IsEmpty()) {
240
    // try language agnostic definition
241
0
    featureAttributesVariable =
242
0
      cmStrCat("CMAKE_LINK_LIBRARY_", feature, "_ATTRIBUTES");
243
0
    featureAttributesValues =
244
0
      makefile->GetDefinition(featureAttributesVariable);
245
0
  }
246
0
  if (!featureAttributesValues.IsEmpty()) {
247
0
    LinkLibraryFeatureAttributeSet featureAttributes;
248
0
    cmsys::RegularExpression processingOption{
249
0
      "^(LIBRARY_TYPE|DEDUPLICATION|OVERRIDE)=((STATIC|SHARED|MODULE|"
250
0
      "EXECUTABLE)(,("
251
0
      "STATIC|"
252
0
      "SHARED|MODULE|EXECUTABLE)"
253
0
      ")*|YES|NO|DEFAULT|[A-Za-z0-9_]+(,[A-Za-z0-9_]+)*)$"
254
0
    };
255
0
    std::string errorMessage;
256
0
    for (auto const& option : cmList{ featureAttributesValues }) {
257
0
      if (processingOption.find(option)) {
258
0
        if (processingOption.match(1) == "LIBRARY_TYPE") {
259
0
          featureAttributes.LibraryTypes.clear();
260
0
          for (auto const& value :
261
0
               cmTokenize(processingOption.match(2), ',')) {
262
0
            if (value == "STATIC") {
263
0
              featureAttributes.LibraryTypes.emplace(
264
0
                cm::TargetType::STATIC_LIBRARY);
265
0
            } else if (value == "SHARED") {
266
0
              featureAttributes.LibraryTypes.emplace(
267
0
                cm::TargetType::SHARED_LIBRARY);
268
0
            } else if (value == "MODULE") {
269
0
              featureAttributes.LibraryTypes.emplace(
270
0
                cm::TargetType::MODULE_LIBRARY);
271
0
            } else if (value == "EXECUTABLE") {
272
0
              featureAttributes.LibraryTypes.emplace(
273
0
                cm::TargetType::EXECUTABLE);
274
0
            } else {
275
0
              errorMessage += cmStrCat("  ", option, '\n');
276
0
              break;
277
0
            }
278
0
          }
279
          // Always add UNKNOWN type
280
0
          featureAttributes.LibraryTypes.emplace(
281
0
            cm::TargetType::UNKNOWN_LIBRARY);
282
0
        } else if (processingOption.match(1) == "DEDUPLICATION") {
283
0
          if (processingOption.match(2) == "YES") {
284
0
            featureAttributes.Deduplication =
285
0
              LinkLibraryFeatureAttributeSet::Yes;
286
0
          } else if (processingOption.match(2) == "NO") {
287
0
            featureAttributes.Deduplication =
288
0
              LinkLibraryFeatureAttributeSet::No;
289
0
          } else if (processingOption.match(2) == "DEFAULT") {
290
0
            featureAttributes.Deduplication =
291
0
              LinkLibraryFeatureAttributeSet::Default;
292
0
          } else {
293
0
            errorMessage += cmStrCat("  ", option, '\n');
294
0
          }
295
0
        } else if (processingOption.match(1) == "OVERRIDE") {
296
0
          featureAttributes.Override.clear();
297
0
          std::vector<std::string> values =
298
0
            cmTokenize(processingOption.match(2), ',');
299
0
          featureAttributes.Override.insert(values.begin(), values.end());
300
0
        }
301
0
      } else {
302
0
        errorMessage += cmStrCat("  ", option, '\n');
303
0
      }
304
0
    }
305
0
    if (!errorMessage.empty()) {
306
0
      makefile->GetCMakeInstance()->IssueMessage(
307
0
        MessageType::FATAL_ERROR,
308
0
        cmStrCat("Erroneous option(s) for '", featureAttributesVariable,
309
0
                 "':\n", errorMessage));
310
0
    }
311
0
    return LinkLibraryFeatureAttributes.emplace(feature, featureAttributes)
312
0
      .first->second;
313
0
  }
314
0
  return LinkLibraryFeatureAttributes
315
0
    .emplace(feature, LinkLibraryFeatureAttributeSet{})
316
0
    .first->second;
317
0
}
318
319
// LINK_GROUP helpers
320
cm::string_view const LG_BEGIN = "<LINK_GROUP:"_s;
321
cm::string_view const LG_END = "</LINK_GROUP:"_s;
322
cm::string_view const LG_ITEM_BEGIN = "<LINK_GROUP>"_s;
323
cm::string_view const LG_ITEM_END = "</LINK_GROUP>"_s;
324
325
inline std::string ExtractGroupFeature(std::string const& item)
326
0
{
327
0
  return item.substr(LG_BEGIN.length(),
328
0
                     item.find(':', LG_BEGIN.length()) - LG_BEGIN.length());
329
0
}
330
331
bool IsGroupFeatureSupported(cmMakefile* makefile,
332
                             std::string const& linkLanguage,
333
                             std::string const& feature)
334
0
{
335
0
  auto featureSupported = cmStrCat(
336
0
    "CMAKE_", linkLanguage, "_LINK_GROUP_USING_", feature, "_SUPPORTED");
337
0
  if (makefile->GetDefinition(featureSupported).IsOn()) {
338
0
    return true;
339
0
  }
340
341
0
  featureSupported =
342
0
    cmStrCat("CMAKE_LINK_GROUP_USING_", feature, "_SUPPORTED");
343
0
  return makefile->GetDefinition(featureSupported).IsOn();
344
0
}
345
346
class EntriesProcessing
347
{
348
public:
349
  using LinkEntry = cmComputeLinkDepends::LinkEntry;
350
  using EntryVector = cmComputeLinkDepends::EntryVector;
351
352
  EntriesProcessing(cmGeneratorTarget const* target,
353
                    std::string const& linkLanguage, EntryVector& entries,
354
                    EntryVector& finalEntries)
355
0
    : Target(target)
356
0
    , LinkLanguage(linkLanguage)
357
0
    , Entries(entries)
358
0
    , FinalEntries(finalEntries)
359
0
  {
360
0
    auto const* makefile = target->Makefile;
361
362
0
    switch (target->GetPolicyStatusCMP0156()) {
363
0
      case cmPolicies::WARN:
364
0
        if (!makefile->GetCMakeInstance()->GetIsInTryCompile() &&
365
0
            makefile->PolicyOptionalWarningEnabled(
366
0
              "CMAKE_POLICY_WARNING_CMP0156")) {
367
0
          makefile->IssuePolicyWarning(
368
0
            cmPolicies::CMP0156, {},
369
0
            "Since the policy is not set, legacy libraries "
370
0
            "de-duplication strategy will be applied."_s,
371
0
            target->GetBacktrace());
372
0
        }
373
0
        CM_FALLTHROUGH;
374
0
      case cmPolicies::OLD:
375
        // rely on default initialization of the class
376
0
        break;
377
0
      case cmPolicies::NEW: {
378
        // Policy 0179 applies only when policy 0156 is new
379
0
        if (target->GetPolicyStatusCMP0179() == cmPolicies::WARN &&
380
0
            !makefile->GetCMakeInstance()->GetIsInTryCompile() &&
381
0
            makefile->PolicyOptionalWarningEnabled(
382
0
              "CMAKE_POLICY_WARNING_CMP0179")) {
383
0
          makefile->IssuePolicyWarning(
384
0
            cmPolicies::CMP0179, {},
385
0
            "Since the policy is not set, static libraries de-duplication "
386
0
            "will keep the last occurrence of the static libraries."_s,
387
0
            target->GetBacktrace());
388
0
        }
389
390
0
        if (auto libProcessing = makefile->GetDefinition(cmStrCat(
391
0
              "CMAKE_", linkLanguage, "_LINK_LIBRARIES_PROCESSING"))) {
392
          // UNICITY keyword is just for compatibility with previous
393
          // implementation
394
0
          cmsys::RegularExpression processingOption{
395
0
            "^(ORDER|UNICITY|DEDUPLICATION)=(FORWARD|REVERSE|ALL|NONE|SHARED)$"
396
0
          };
397
0
          std::string errorMessage;
398
0
          for (auto const& option : cmList{ libProcessing }) {
399
0
            if (processingOption.find(option)) {
400
0
              if (processingOption.match(1) == "ORDER") {
401
0
                if (processingOption.match(2) == "FORWARD") {
402
0
                  this->Order = Forward;
403
0
                } else if (processingOption.match(2) == "REVERSE") {
404
0
                  this->Order = Reverse;
405
0
                } else {
406
0
                  errorMessage += cmStrCat("  ", option, '\n');
407
0
                }
408
0
              } else if (processingOption.match(1) == "UNICITY" ||
409
0
                         processingOption.match(1) == "DEDUPLICATION") {
410
0
                if (processingOption.match(2) == "ALL") {
411
0
                  this->Deduplication = All;
412
0
                } else if (processingOption.match(2) == "NONE") {
413
0
                  this->Deduplication = None;
414
0
                } else if (processingOption.match(2) == "SHARED") {
415
0
                  this->Deduplication = Shared;
416
0
                } else {
417
0
                  errorMessage += cmStrCat("  ", option, '\n');
418
0
                }
419
0
              }
420
0
            } else {
421
0
              errorMessage += cmStrCat("  ", option, '\n');
422
0
            }
423
0
          }
424
0
          if (!errorMessage.empty()) {
425
0
            makefile->GetCMakeInstance()->IssueMessage(
426
0
              MessageType::FATAL_ERROR,
427
0
              cmStrCat("Erroneous option(s) for 'CMAKE_", linkLanguage,
428
0
                       "_LINK_LIBRARIES_PROCESSING':\n", errorMessage),
429
0
              target->GetBacktrace());
430
0
          }
431
          // For some environments, deduplication should be activated only if
432
          // both policies CMP0156 and CMP0179 are NEW
433
0
          if (makefile->GetDefinition(cmStrCat(
434
0
                "CMAKE_", linkLanguage, "_PLATFORM_LINKER_ID")) == "LLD"_s &&
435
0
              makefile->GetDefinition("CMAKE_EXECUTABLE_FORMAT") == "ELF"_s &&
436
0
              target->GetPolicyStatusCMP0179() != cmPolicies::NEW &&
437
0
              this->Deduplication == All) {
438
0
            this->Deduplication = Shared;
439
0
          }
440
0
        }
441
0
      }
442
0
    }
443
0
  }
444
445
  void AddGroups(std::map<size_t, std::vector<size_t>> const& groups)
446
0
  {
447
0
    if (!groups.empty()) {
448
0
      this->Groups = &groups;
449
      // record all libraries as part of groups to ensure correct
450
      // deduplication: libraries as part of groups are always kept.
451
0
      for (auto const& g : groups) {
452
0
        for (auto index : g.second) {
453
0
          this->Emitted.insert(index);
454
0
        }
455
0
      }
456
0
    }
457
0
  }
458
459
  void AddLibraries(std::vector<size_t> const& libEntries)
460
0
  {
461
0
    if (this->Order == Reverse) {
462
0
      std::vector<size_t> entries;
463
0
      if (this->Deduplication == All &&
464
0
          this->Target->GetPolicyStatusCMP0179() == cmPolicies::NEW) {
465
        // keep the first occurrence of the static libraries
466
0
        std::set<size_t> emitted{ this->Emitted };
467
0
        for (auto index : libEntries) {
468
0
          LinkEntry const& entry = this->Entries[index];
469
0
          if (!entry.Target ||
470
0
              entry.Target->GetType() != cm::TargetType::STATIC_LIBRARY) {
471
0
            entries.emplace_back(index);
472
0
            continue;
473
0
          }
474
0
          if (this->IncludeEntry(entry) || emitted.insert(index).second) {
475
0
            entries.emplace_back(index);
476
0
          }
477
0
        }
478
0
      } else {
479
0
        entries = libEntries;
480
0
      }
481
      // Iterate in reverse order so we can keep only the last occurrence
482
      // of the shared libraries.
483
0
      this->AddLibraries(cmReverseRange(entries));
484
0
    } else {
485
0
      this->AddLibraries(cmMakeRange(libEntries));
486
0
    }
487
0
  }
488
489
  void AddObjects(std::vector<size_t> const& objectEntries)
490
0
  {
491
    // Place explicitly linked object files in the front.  The linker will
492
    // always use them anyway, and they may depend on symbols from libraries.
493
0
    if (this->Order == Reverse) {
494
      // Append in reverse order at the end since we reverse the final order.
495
0
      for (auto index : cmReverseRange(objectEntries)) {
496
0
        this->FinalEntries.emplace_back(this->Entries[index]);
497
0
      }
498
0
    } else {
499
      // Append in reverse order to ensure correct final order
500
0
      for (auto index : cmReverseRange(objectEntries)) {
501
0
        this->FinalEntries.emplace(this->FinalEntries.begin(),
502
0
                                   this->Entries[index]);
503
0
      }
504
0
    }
505
0
  }
506
507
  void Finalize()
508
0
  {
509
0
    if (this->Order == Reverse) {
510
      // Reverse the resulting order since we iterated in reverse.
511
0
      std::reverse(this->FinalEntries.begin(), this->FinalEntries.end());
512
0
    }
513
514
    // expand groups
515
0
    if (this->Groups) {
516
0
      for (auto const& g : *this->Groups) {
517
0
        LinkEntry const& groupEntry = this->Entries[g.first];
518
0
        auto it = this->FinalEntries.begin();
519
0
        while (true) {
520
0
          it = std::find_if(it, this->FinalEntries.end(),
521
0
                            [&groupEntry](LinkEntry const& entry) -> bool {
522
0
                              return groupEntry.Item == entry.Item;
523
0
                            });
524
0
          if (it == this->FinalEntries.end()) {
525
0
            break;
526
0
          }
527
0
          it->Item.Value = std::string(LG_ITEM_END);
528
0
          for (auto index = g.second.rbegin(); index != g.second.rend();
529
0
               ++index) {
530
0
            it = this->FinalEntries.insert(it, this->Entries[*index]);
531
0
          }
532
0
          it = this->FinalEntries.insert(it, groupEntry);
533
0
          it->Item.Value = std::string(LG_ITEM_BEGIN);
534
0
        }
535
0
      }
536
0
    }
537
0
  }
538
539
private:
540
  enum OrderKind
541
  {
542
    Forward,
543
    Reverse
544
  };
545
546
  enum DeduplicationKind
547
  {
548
    None,
549
    Shared,
550
    All
551
  };
552
553
  bool IncludeEntry(LinkEntry const& entry) const
554
0
  {
555
0
    if (entry.Feature != cmComputeLinkDepends::LinkEntry::DEFAULT) {
556
0
      auto const& featureAttributes = GetLinkLibraryFeatureAttributes(
557
0
        this->Target->Makefile, this->LinkLanguage, entry.Feature);
558
0
      if ((!entry.Target ||
559
0
           featureAttributes.LibraryTypes.find(entry.Target->GetType()) !=
560
0
             featureAttributes.LibraryTypes.end()) &&
561
0
          featureAttributes.Deduplication !=
562
0
            LinkLibraryFeatureAttributeSet::Default) {
563
0
        return featureAttributes.Deduplication ==
564
0
          LinkLibraryFeatureAttributeSet::No;
565
0
      }
566
0
    }
567
568
0
    return this->Deduplication == None ||
569
0
      (this->Deduplication == Shared &&
570
0
       (!entry.Target ||
571
0
        entry.Target->GetType() != cm::TargetType::SHARED_LIBRARY)) ||
572
0
      (this->Deduplication == All && entry.Kind != LinkEntry::Library);
573
0
  }
574
575
  template <typename Range>
576
  void AddLibraries(Range const& libEntries)
577
0
  {
578
0
    for (auto index : libEntries) {
579
0
      LinkEntry const& entry = this->Entries[index];
580
0
      if (this->IncludeEntry(entry) || this->Emitted.insert(index).second) {
581
0
        this->FinalEntries.emplace_back(entry);
582
0
      }
583
0
    }
584
0
  }
Unexecuted instantiation: cmComputeLinkDepends.cxx:void (anonymous namespace)::EntriesProcessing::AddLibraries<cmRange<std::__1::reverse_iterator<std::__1::__wrap_iter<unsigned long const*> > > >(cmRange<std::__1::reverse_iterator<std::__1::__wrap_iter<unsigned long const*> > > const&)
Unexecuted instantiation: cmComputeLinkDepends.cxx:void (anonymous namespace)::EntriesProcessing::AddLibraries<cmRange<std::__1::__wrap_iter<unsigned long const*> > >(cmRange<std::__1::__wrap_iter<unsigned long const*> > const&)
585
586
  OrderKind Order = Reverse;
587
  DeduplicationKind Deduplication = Shared;
588
  cmGeneratorTarget const* Target;
589
  std::string const& LinkLanguage;
590
  EntryVector& Entries;
591
  EntryVector& FinalEntries;
592
  std::set<size_t> Emitted;
593
  std::map<size_t, std::vector<size_t>> const* Groups = nullptr;
594
};
595
}
596
597
std::string const& cmComputeLinkDepends::LinkEntry::DEFAULT =
598
  cmLinkItem::DEFAULT;
599
600
cmComputeLinkDepends::cmComputeLinkDepends(cmGeneratorTarget const* target,
601
                                           std::string config,
602
                                           std::string linkLanguage,
603
                                           LinkLibrariesStrategy strategy)
604
0
  : Target(target)
605
0
  , Makefile(this->Target->Target->GetMakefile())
606
0
  , GlobalGenerator(this->Target->GetLocalGenerator()->GetGlobalGenerator())
607
0
  , CMakeInstance(this->GlobalGenerator->GetCMakeInstance())
608
0
  , Config(std::move(config))
609
0
  , DebugMode(this->Makefile->IsOn("CMAKE_LINK_DEPENDS_DEBUG_MODE") ||
610
0
              this->Target->GetProperty("LINK_DEPENDS_DEBUG_MODE").IsOn())
611
0
  , LinkLanguage(std::move(linkLanguage))
612
0
  , LinkType(ComputeLinkType(
613
0
      this->Config, this->Makefile->GetCMakeInstance()->GetDebugConfigs()))
614
0
  , Strategy(strategy)
615
616
0
{
617
0
  cm::GenEx::Context context(this->Target->LocalGenerator, this->Config,
618
0
                             this->LinkLanguage);
619
  // target oriented feature override property takes precedence over
620
  // global override property
621
0
  cm::string_view lloPrefix = "LINK_LIBRARY_OVERRIDE_"_s;
622
0
  auto const& keys = this->Target->GetPropertyKeys();
623
0
  std::for_each(
624
0
    keys.cbegin(), keys.cend(),
625
0
    [this, &lloPrefix, &context](std::string const& key) {
626
0
      if (cmHasPrefix(key, lloPrefix)) {
627
0
        if (cmValue feature = this->Target->GetProperty(key)) {
628
0
          if (!feature->empty() && key.length() > lloPrefix.length()) {
629
0
            auto item = key.substr(lloPrefix.length());
630
0
            cmGeneratorExpressionDAGChecker dagChecker{
631
0
              this->Target, "LINK_LIBRARY_OVERRIDE",      nullptr, nullptr,
632
0
              context,      this->Target->GetBacktrace(),
633
0
            };
634
0
            auto overrideFeature = cmGeneratorExpression::Evaluate(
635
0
              *feature, context.LG, context.Config, this->Target, &dagChecker,
636
0
              this->Target, context.Language);
637
0
            this->LinkLibraryOverride.emplace(item, overrideFeature);
638
0
          }
639
0
        }
640
0
      }
641
0
    });
642
  // global override property
643
0
  if (cmValue linkLibraryOverride =
644
0
        this->Target->GetProperty("LINK_LIBRARY_OVERRIDE")) {
645
0
    cmGeneratorExpressionDAGChecker dagChecker{
646
0
      this->Target, "LINK_LIBRARY_OVERRIDE",      nullptr, nullptr,
647
0
      context,      this->Target->GetBacktrace(),
648
0
    };
649
0
    auto overrideValue = cmGeneratorExpression::Evaluate(
650
0
      *linkLibraryOverride, context.LG, context.Config, this->Target,
651
0
      &dagChecker, this->Target, context.Language);
652
653
0
    std::vector<std::string> overrideList =
654
0
      cmTokenize(overrideValue, ',', cmTokenizerMode::New);
655
0
    if (overrideList.size() >= 2) {
656
0
      auto const& feature = overrideList.front();
657
0
      std::for_each(overrideList.cbegin() + 1, overrideList.cend(),
658
0
                    [this, &feature](std::string const& item) {
659
0
                      this->LinkLibraryOverride.emplace(item, feature);
660
0
                    });
661
0
    }
662
0
  }
663
0
}
664
665
0
cmComputeLinkDepends::~cmComputeLinkDepends() = default;
666
667
std::vector<cmComputeLinkDepends::LinkEntry> const&
668
cmComputeLinkDepends::Compute()
669
0
{
670
  // Follow the link dependencies of the target to be linked.
671
0
  this->AddDirectLinkEntries();
672
673
  // Complete the breadth-first search of dependencies.
674
0
  while (!this->BFSQueue.empty()) {
675
    // Get the next entry.
676
0
    BFSEntry qe = this->BFSQueue.front();
677
0
    this->BFSQueue.pop();
678
679
    // Follow the entry's dependencies.
680
0
    this->FollowLinkEntry(qe);
681
0
  }
682
683
  // Complete the search of shared library dependencies.
684
0
  while (!this->SharedDepQueue.empty()) {
685
    // Handle the next entry.
686
0
    this->HandleSharedDependency(this->SharedDepQueue.front());
687
0
    this->SharedDepQueue.pop();
688
0
  }
689
690
  // Infer dependencies of targets for which they were not known.
691
0
  this->InferDependencies();
692
693
  // finalize groups dependencies
694
  // All dependencies which are raw items must be replaced by the group
695
  // it belongs to, if any.
696
0
  this->UpdateGroupDependencies();
697
698
  // Cleanup the constraint graph.
699
0
  this->CleanConstraintGraph();
700
701
  // Display the constraint graph.
702
0
  if (this->DebugMode) {
703
0
    fprintf(stderr,
704
0
            "---------------------------------------"
705
0
            "---------------------------------------\n");
706
0
    fprintf(stderr, "Link dependency analysis for target %s, config %s\n",
707
0
            this->Target->GetName().c_str(),
708
0
            this->Config.empty() ? "noconfig" : this->Config.c_str());
709
0
    this->DisplayConstraintGraph();
710
0
  }
711
712
  // Compute the DAG of strongly connected components.  The algorithm
713
  // used by cmComputeComponentGraph should identify the components in
714
  // the same order in which the items were originally discovered in
715
  // the BFS.  This should preserve the original order when no
716
  // constraints disallow it.
717
0
  this->CCG =
718
0
    cm::make_unique<cmComputeComponentGraph>(this->EntryConstraintGraph);
719
0
  this->CCG->Compute();
720
721
0
  if (!this->CheckCircularDependencies()) {
722
0
    return this->FinalLinkEntries;
723
0
  }
724
725
  // Compute the final ordering.
726
0
  this->OrderLinkEntries();
727
728
  // Display the final ordering.
729
0
  if (this->DebugMode) {
730
0
    this->DisplayOrderedEntries();
731
0
  }
732
733
  // Compute the final set of link entries.
734
0
  EntriesProcessing entriesProcessing{ this->Target, this->LinkLanguage,
735
0
                                       this->EntryList,
736
0
                                       this->FinalLinkEntries };
737
  // Add groups first, to ensure that libraries of the groups are always kept.
738
0
  entriesProcessing.AddGroups(this->GroupItems);
739
0
  entriesProcessing.AddLibraries(this->FinalLinkOrder);
740
0
  entriesProcessing.AddObjects(this->ObjectEntries);
741
0
  entriesProcessing.Finalize();
742
743
  // Display the final set.
744
0
  if (this->DebugMode) {
745
0
    this->DisplayFinalEntries();
746
0
  }
747
748
0
  return this->FinalLinkEntries;
749
0
}
750
751
std::string const& cmComputeLinkDepends::GetCurrentFeature(
752
  std::string const& item, std::string const& defaultFeature) const
753
0
{
754
0
  auto it = this->LinkLibraryOverride.find(item);
755
0
  return it == this->LinkLibraryOverride.end() ? defaultFeature : it->second;
756
0
}
757
758
std::pair<std::map<cmLinkItem, size_t>::iterator, bool>
759
cmComputeLinkDepends::AllocateLinkEntry(cmLinkItem const& item)
760
0
{
761
0
  std::map<cmLinkItem, size_t>::value_type index_entry(
762
0
    item, static_cast<size_t>(this->EntryList.size()));
763
0
  auto lei = this->LinkEntryIndex.insert(index_entry);
764
0
  if (lei.second) {
765
0
    this->EntryList.emplace_back();
766
0
    this->InferredDependSets.emplace_back();
767
0
    this->EntryConstraintGraph.emplace_back();
768
0
  }
769
0
  return lei;
770
0
}
771
772
std::pair<size_t, bool> cmComputeLinkDepends::AddLinkEntry(
773
  cmLinkItem const& item, cm::optional<size_t> groupIndex)
774
0
{
775
  // Allocate a spot for the item entry.
776
0
  auto lei = this->AllocateLinkEntry(item);
777
778
  // Check if the item entry has already been added.
779
0
  if (!lei.second) {
780
    // Yes.  We do not need to follow the item's dependencies again.
781
0
    return { lei.first->second, false };
782
0
  }
783
784
  // Initialize the item entry.
785
0
  size_t index = lei.first->second;
786
0
  LinkEntry& entry = this->EntryList[index];
787
0
  entry.Item = BT<std::string>(item.AsStr(), item.Backtrace);
788
0
  entry.Target = item.Target;
789
0
  entry.Feature = item.Feature;
790
0
  if (!entry.Target && entry.Item.Value[0] == '-' &&
791
0
      entry.Item.Value[1] != 'l' &&
792
0
      entry.Item.Value.substr(0, 10) != "-framework") {
793
0
    entry.Kind = LinkEntry::Flag;
794
0
    entry.Feature = LinkEntry::DEFAULT;
795
0
  } else if (cmHasPrefix(entry.Item.Value, LG_BEGIN) &&
796
0
             cmHasSuffix(entry.Item.Value, '>')) {
797
0
    entry.Kind = LinkEntry::Group;
798
0
  }
799
800
0
  if (entry.Kind != LinkEntry::Group) {
801
    // If the item has dependencies queue it to follow them.
802
0
    if (entry.Target) {
803
      // Target dependencies are always known.  Follow them.
804
0
      BFSEntry qe = { index, groupIndex, nullptr };
805
0
      this->BFSQueue.push(qe);
806
0
    } else {
807
      // Look for an old-style <item>_LIB_DEPENDS variable.
808
0
      std::string var = cmStrCat(entry.Item.Value, "_LIB_DEPENDS");
809
0
      if (cmValue val = this->Makefile->GetDefinition(var)) {
810
        // The item dependencies are known.  Follow them.
811
0
        BFSEntry qe = { index, groupIndex, val->c_str() };
812
0
        this->BFSQueue.push(qe);
813
0
      } else if (entry.Kind != LinkEntry::Flag) {
814
        // The item dependencies are not known.  We need to infer them.
815
0
        this->InferredDependSets[index].Initialized = true;
816
0
      }
817
0
    }
818
0
  }
819
820
0
  return { index, true };
821
0
}
822
823
void cmComputeLinkDepends::AddLinkObject(cmLinkItem const& item)
824
0
{
825
0
  assert(!item.Target); // The item is an object file, not its target.
826
827
  // Allocate a spot for the item entry.
828
0
  auto lei = this->AllocateLinkEntry(item);
829
830
  // Check if the item entry has already been added.
831
0
  if (!lei.second) {
832
0
    return;
833
0
  }
834
835
  // Initialize the item entry.
836
0
  size_t index = lei.first->second;
837
0
  LinkEntry& entry = this->EntryList[index];
838
0
  entry.Item = BT<std::string>(item.AsStr(), item.Backtrace);
839
0
  entry.Kind = LinkEntry::Object;
840
0
  entry.ObjectSource = item.ObjectSource;
841
842
  // Record explicitly linked object files separately.
843
0
  this->ObjectEntries.emplace_back(index);
844
0
}
845
846
void cmComputeLinkDepends::FollowLinkEntry(BFSEntry qe)
847
0
{
848
  // Get this entry representation.
849
0
  size_t depender_index = qe.GroupIndex ? *qe.GroupIndex : qe.Index;
850
0
  LinkEntry const& entry = this->EntryList[qe.Index];
851
852
  // Follow the item's dependencies.
853
0
  if (entry.Target) {
854
    // Follow the target dependencies.
855
0
    if (cmLinkInterface const* iface =
856
0
          entry.Target->GetLinkInterface(this->Config, this->Target)) {
857
0
      bool const isIface =
858
0
        entry.Target->GetType() == cm::TargetType::INTERFACE_LIBRARY;
859
      // This target provides its own link interface information.
860
0
      this->AddLinkEntries(depender_index, iface->Libraries);
861
0
      this->AddLinkObjects(iface->Objects);
862
0
      for (auto const& language : iface->Languages) {
863
0
        auto runtimeEntries = iface->LanguageRuntimeLibraries.find(language);
864
0
        if (runtimeEntries != iface->LanguageRuntimeLibraries.end()) {
865
0
          this->AddLinkEntries(depender_index, runtimeEntries->second);
866
0
        }
867
0
      }
868
869
0
      if (isIface) {
870
0
        return;
871
0
      }
872
873
      // Handle dependent shared libraries.
874
0
      this->FollowSharedDeps(depender_index, iface);
875
0
    }
876
0
  } else {
877
    // Follow the old-style dependency list.
878
0
    this->AddVarLinkEntries(depender_index, qe.LibDepends);
879
0
  }
880
0
}
881
882
void cmComputeLinkDepends::FollowSharedDeps(size_t depender_index,
883
                                            cmLinkInterface const* iface,
884
                                            bool follow_interface)
885
0
{
886
  // Follow dependencies if we have not followed them already.
887
0
  if (this->SharedDepFollowed.insert(depender_index).second) {
888
0
    if (follow_interface) {
889
0
      this->QueueSharedDependencies(depender_index, iface->Libraries);
890
0
    }
891
0
    this->QueueSharedDependencies(depender_index, iface->SharedDeps);
892
0
  }
893
0
}
894
895
void cmComputeLinkDepends::QueueSharedDependencies(
896
  size_t depender_index, std::vector<cmLinkItem> const& deps)
897
0
{
898
0
  for (cmLinkItem const& li : deps) {
899
0
    SharedDepEntry qe;
900
0
    qe.Item = li;
901
0
    qe.DependerIndex = depender_index;
902
0
    this->SharedDepQueue.push(qe);
903
0
  }
904
0
}
905
906
void cmComputeLinkDepends::HandleSharedDependency(SharedDepEntry const& dep)
907
0
{
908
  // Allocate a spot for the item entry.
909
0
  auto lei = this->AllocateLinkEntry(dep.Item);
910
0
  size_t index = lei.first->second;
911
912
  // Check if the target does not already has an entry.
913
0
  if (lei.second) {
914
    // Initialize the item entry.
915
0
    LinkEntry& entry = this->EntryList[index];
916
0
    entry.Item = BT<std::string>(dep.Item.AsStr(), dep.Item.Backtrace);
917
0
    entry.Target = dep.Item.Target;
918
919
    // This item was added specifically because it is a dependent
920
    // shared library.  It may get special treatment
921
    // in cmComputeLinkInformation.
922
0
    entry.Kind = LinkEntry::SharedDep;
923
0
  }
924
925
  // Get the link entry for this target.
926
0
  LinkEntry& entry = this->EntryList[index];
927
928
  // This shared library dependency must follow the item that listed
929
  // it.
930
0
  this->EntryConstraintGraph[dep.DependerIndex].emplace_back(
931
0
    index, true, false, cmListFileBacktrace());
932
933
  // Target items may have their own dependencies.
934
0
  if (entry.Target) {
935
0
    if (cmLinkInterface const* iface =
936
0
          entry.Target->GetLinkInterface(this->Config, this->Target)) {
937
      // Follow public and private dependencies transitively.
938
0
      this->FollowSharedDeps(index, iface, true);
939
0
    }
940
0
  }
941
0
}
942
943
void cmComputeLinkDepends::AddVarLinkEntries(
944
  cm::optional<size_t> depender_index, char const* value)
945
0
{
946
  // This is called to add the dependencies named by
947
  // <item>_LIB_DEPENDS.  The variable contains a semicolon-separated
948
  // list.  The list contains link-type;item pairs and just items.
949
0
  cmList deplist{ value };
950
951
  // Look for entries meant for this configuration.
952
0
  std::vector<cmLinkItem> actual_libs;
953
0
  cmTargetLinkLibraryType llt = GENERAL_LibraryType;
954
0
  bool haveLLT = false;
955
0
  for (std::string const& d : deplist) {
956
0
    if (d == "debug") {
957
0
      llt = DEBUG_LibraryType;
958
0
      haveLLT = true;
959
0
    } else if (d == "optimized") {
960
0
      llt = OPTIMIZED_LibraryType;
961
0
      haveLLT = true;
962
0
    } else if (d == "general") {
963
0
      llt = GENERAL_LibraryType;
964
0
      haveLLT = true;
965
0
    } else if (!d.empty()) {
966
      // If no explicit link type was given prior to this entry then
967
      // check if the entry has its own link type variable.  This is
968
      // needed for compatibility with dependency files generated by
969
      // the export_library_dependencies command from CMake 2.4 and
970
      // lower.
971
0
      if (!haveLLT) {
972
0
        std::string var = cmStrCat(d, "_LINK_TYPE");
973
0
        if (cmValue val = this->Makefile->GetDefinition(var)) {
974
0
          if (*val == "debug") {
975
0
            llt = DEBUG_LibraryType;
976
0
          } else if (*val == "optimized") {
977
0
            llt = OPTIMIZED_LibraryType;
978
0
          }
979
0
        }
980
0
      }
981
982
      // If the library is meant for this link type then use it.
983
0
      if (llt == GENERAL_LibraryType || llt == this->LinkType) {
984
0
        actual_libs.emplace_back(this->ResolveLinkItem(depender_index, d));
985
0
      }
986
987
      // Reset the link type until another explicit type is given.
988
0
      llt = GENERAL_LibraryType;
989
0
      haveLLT = false;
990
0
    }
991
0
  }
992
993
  // Add the entries from this list.
994
0
  this->AddLinkEntries(depender_index, actual_libs);
995
0
}
996
997
void cmComputeLinkDepends::AddDirectLinkEntries()
998
0
{
999
  // Add direct link dependencies in this configuration.
1000
0
  cmLinkImplementation const* impl = this->Target->GetLinkImplementation(
1001
0
    this->Config, cmGeneratorTarget::UseTo::Link);
1002
0
  this->AddLinkEntries(cm::nullopt, impl->Libraries);
1003
0
  this->AddLinkObjects(impl->Objects);
1004
1005
0
  for (auto const& language : impl->Languages) {
1006
0
    auto runtimeEntries = impl->LanguageRuntimeLibraries.find(language);
1007
0
    if (runtimeEntries != impl->LanguageRuntimeLibraries.end()) {
1008
0
      this->AddLinkEntries(cm::nullopt, runtimeEntries->second);
1009
0
    }
1010
0
  }
1011
0
}
1012
1013
template <typename T>
1014
void cmComputeLinkDepends::AddLinkEntries(cm::optional<size_t> depender_index,
1015
                                          std::vector<T> const& libs)
1016
0
{
1017
  // Track inferred dependency sets implied by this list.
1018
0
  std::map<size_t, DependSet> dependSets;
1019
1020
0
  cm::optional<std::pair<size_t, bool>> group;
1021
0
  std::vector<size_t> groupItems;
1022
1023
  // Loop over the libraries linked directly by the depender.
1024
0
  for (T const& l : libs) {
1025
    // Skip entries that will resolve to the target getting linked or
1026
    // are empty.
1027
0
    cmLinkItem const& item = l;
1028
0
    if (item.AsStr() == this->Target->GetName() || item.AsStr().empty()) {
1029
0
      continue;
1030
0
    }
1031
1032
    // emit a warning if an undefined feature is used as part of
1033
    // an imported target
1034
0
    if (item.Feature != LinkEntry::DEFAULT && depender_index) {
1035
0
      auto const& depender = this->EntryList[*depender_index];
1036
0
      if (depender.Target && depender.Target->IsImported() &&
1037
0
          !IsFeatureSupported(this->Makefile, this->LinkLanguage,
1038
0
                              item.Feature)) {
1039
0
        this->CMakeInstance->IssueDiagnostic(
1040
0
          cmDiagnostics::CMD_AUTHOR,
1041
0
          cmStrCat("The 'IMPORTED' target '", depender.Target->GetName(),
1042
0
                   "' uses the generator-expression '$<LINK_LIBRARY>' with "
1043
0
                   "the feature '",
1044
0
                   item.Feature,
1045
0
                   "', which is undefined or unsupported.\nDid you miss to "
1046
0
                   "define it by setting variables \"CMAKE_",
1047
0
                   this->LinkLanguage, "_LINK_LIBRARY_USING_", item.Feature,
1048
0
                   "\" and \"CMAKE_", this->LinkLanguage,
1049
0
                   "_LINK_LIBRARY_USING_", item.Feature, "_SUPPORTED\"?"),
1050
0
          this->Target->GetBacktrace());
1051
0
      }
1052
0
    }
1053
1054
0
    if (cmHasPrefix(item.AsStr(), LG_BEGIN) &&
1055
0
        cmHasSuffix(item.AsStr(), '>')) {
1056
0
      group = this->AddLinkEntry(item, cm::nullopt);
1057
0
      if (group->second) {
1058
0
        LinkEntry& entry = this->EntryList[group->first];
1059
0
        entry.Feature = ExtractGroupFeature(item.AsStr());
1060
0
      }
1061
0
      if (depender_index) {
1062
0
        this->EntryConstraintGraph[*depender_index].emplace_back(
1063
0
          group->first, false, false, cmListFileBacktrace());
1064
0
      } else {
1065
        // This is a direct dependency of the target being linked.
1066
0
        this->OriginalEntries.push_back(group->first);
1067
0
      }
1068
0
      continue;
1069
0
    }
1070
1071
0
    size_t dependee_index;
1072
1073
0
    if (cmHasPrefix(item.AsStr(), LG_END) && cmHasSuffix(item.AsStr(), '>')) {
1074
0
      assert(group);
1075
0
      dependee_index = group->first;
1076
0
      if (group->second) {
1077
0
        this->GroupItems.emplace(group->first, std::move(groupItems));
1078
0
      }
1079
0
      group = cm::nullopt;
1080
0
      groupItems.clear();
1081
0
      continue;
1082
0
    }
1083
1084
0
    if (depender_index && group) {
1085
0
      auto const& depender = this->EntryList[*depender_index];
1086
0
      auto const& groupFeature = this->EntryList[group->first].Feature;
1087
0
      if (depender.Target && depender.Target->IsImported() &&
1088
0
          !IsGroupFeatureSupported(this->Makefile, this->LinkLanguage,
1089
0
                                   groupFeature)) {
1090
0
        this->CMakeInstance->IssueDiagnostic(
1091
0
          cmDiagnostics::CMD_AUTHOR,
1092
0
          cmStrCat("The 'IMPORTED' target '", depender.Target->GetName(),
1093
0
                   "' uses the generator-expression '$<LINK_GROUP>' with "
1094
0
                   "the feature '",
1095
0
                   groupFeature,
1096
0
                   "', which is undefined or unsupported.\nDid you miss to "
1097
0
                   "define it by setting variables \"CMAKE_",
1098
0
                   this->LinkLanguage, "_LINK_GROUP_USING_", groupFeature,
1099
0
                   "\" and \"CMAKE_", this->LinkLanguage, "_LINK_GROUP_USING_",
1100
0
                   groupFeature, "_SUPPORTED\"?"),
1101
0
          this->Target->GetBacktrace());
1102
0
      }
1103
0
    }
1104
1105
    // Add a link entry for this item.
1106
0
    auto ale = this->AddLinkEntry(
1107
0
      item, group ? cm::optional<size_t>(group->first) : cm::nullopt);
1108
0
    dependee_index = ale.first;
1109
0
    LinkEntry& entry = this->EntryList[dependee_index];
1110
0
    bool supportedItem = true;
1111
0
    auto const& itemFeature =
1112
0
      this->GetCurrentFeature(entry.Item.Value, item.Feature);
1113
0
    if (group && ale.second && entry.Target &&
1114
0
        (entry.Target->GetType() == cm::TargetType::OBJECT_LIBRARY ||
1115
0
         entry.Target->GetType() == cm::TargetType::INTERFACE_LIBRARY)) {
1116
0
      supportedItem = false;
1117
0
      auto const& groupFeature = this->EntryList[group->first].Feature;
1118
0
      this->CMakeInstance->IssueDiagnostic(
1119
0
        cmDiagnostics::CMD_AUTHOR,
1120
0
        cmStrCat("The feature '", groupFeature,
1121
0
                 "', specified as part of a generator-expression "
1122
0
                 "'$",
1123
0
                 LG_BEGIN, groupFeature, ">', will not be applied to the ",
1124
0
                 (entry.Target->GetType() == cm::TargetType::OBJECT_LIBRARY
1125
0
                    ? "OBJECT"
1126
0
                    : "INTERFACE"),
1127
0
                 " library '", entry.Item.Value, "'."),
1128
0
        this->Target->GetBacktrace());
1129
0
    }
1130
    // check if feature is applicable to this item
1131
0
    if (itemFeature != LinkEntry::DEFAULT && entry.Target) {
1132
0
      auto const& featureAttributes = GetLinkLibraryFeatureAttributes(
1133
0
        this->Makefile, this->LinkLanguage, itemFeature);
1134
0
      if (featureAttributes.LibraryTypes.find(entry.Target->GetType()) ==
1135
0
          featureAttributes.LibraryTypes.end()) {
1136
0
        supportedItem = false;
1137
0
        this->CMakeInstance->IssueDiagnostic(
1138
0
          cmDiagnostics::CMD_AUTHOR,
1139
0
          cmStrCat("The feature '", itemFeature,
1140
0
                   "', specified as part of a generator-expression "
1141
0
                   "'$<LINK_LIBRARY:",
1142
0
                   itemFeature, ">', will not be applied to the ",
1143
0
                   cmState::GetTargetTypeName(entry.Target->GetType()), " '",
1144
0
                   entry.Item.Value, "'."),
1145
0
          this->Target->GetBacktrace());
1146
0
      }
1147
0
    }
1148
0
    if (ale.second) {
1149
      // current item not yet defined
1150
0
      entry.Feature = itemFeature;
1151
0
      if (!supportedItem) {
1152
0
        entry.Feature = LinkEntry::DEFAULT;
1153
0
      }
1154
0
    }
1155
1156
0
    if (supportedItem) {
1157
0
      if (group) {
1158
0
        auto const& currentFeature = this->EntryList[group->first].Feature;
1159
0
        for (auto const& g : this->GroupItems) {
1160
0
          auto const& groupFeature = this->EntryList[g.first].Feature;
1161
0
          if (groupFeature == currentFeature) {
1162
0
            continue;
1163
0
          }
1164
0
          if (std::find(g.second.cbegin(), g.second.cend(), dependee_index) !=
1165
0
              g.second.cend()) {
1166
0
            this->CMakeInstance->IssueMessage(
1167
0
              MessageType::FATAL_ERROR,
1168
0
              cmStrCat("Impossible to link target '", this->Target->GetName(),
1169
0
                       "' because the link item '", entry.Item.Value,
1170
0
                       "', specified with the group feature '", currentFeature,
1171
0
                       "', has already occurred with the feature '",
1172
0
                       groupFeature, "', which is not allowed."),
1173
0
              this->Target->GetBacktrace());
1174
0
            continue;
1175
0
          }
1176
0
        }
1177
0
      }
1178
0
      if (entry.Feature != itemFeature) {
1179
0
        bool incompatibleFeatures = true;
1180
        // check if an override is possible
1181
0
        auto const& entryFeatureAttributes = GetLinkLibraryFeatureAttributes(
1182
0
          this->Makefile, this->LinkLanguage, entry.Feature);
1183
0
        auto const& itemFeatureAttributes = GetLinkLibraryFeatureAttributes(
1184
0
          this->Makefile, this->LinkLanguage, itemFeature);
1185
0
        if (itemFeatureAttributes.Override.find(entry.Feature) !=
1186
0
              itemFeatureAttributes.Override.end() &&
1187
0
            entryFeatureAttributes.Override.find(itemFeature) !=
1188
0
              entryFeatureAttributes.Override.end()) {
1189
          // features override each other
1190
0
          this->CMakeInstance->IssueMessage(
1191
0
            MessageType::FATAL_ERROR,
1192
0
            cmStrCat("Impossible to link target '", this->Target->GetName(),
1193
0
                     "' because the link item '", entry.Item.Value,
1194
0
                     "' is specified with the features '", itemFeature,
1195
0
                     "' and '", entry.Feature,
1196
0
                     "'"
1197
0
                     ", and both have an 'OVERRIDE' attribute that overrides "
1198
0
                     "the other. Such cycles are not allowed."),
1199
0
            this->Target->GetBacktrace());
1200
0
        } else {
1201
0
          if (itemFeatureAttributes.Override.find(entry.Feature) !=
1202
0
              itemFeatureAttributes.Override.end()) {
1203
0
            entry.Feature = itemFeature;
1204
0
            incompatibleFeatures = false;
1205
0
          } else if (entryFeatureAttributes.Override.find(itemFeature) !=
1206
0
                     entryFeatureAttributes.Override.end()) {
1207
0
            incompatibleFeatures = false;
1208
0
          }
1209
0
          if (incompatibleFeatures) {
1210
            // incompatibles features occurred
1211
0
            this->CMakeInstance->IssueMessage(
1212
0
              MessageType::FATAL_ERROR,
1213
0
              cmStrCat(
1214
0
                "Impossible to link target '", this->Target->GetName(),
1215
0
                "' because the link item '", entry.Item.Value, "', specified ",
1216
0
                (itemFeature == LinkEntry::DEFAULT
1217
0
                   ? "without any feature or 'DEFAULT' feature"
1218
0
                   : cmStrCat("with the feature '", itemFeature, '\'')),
1219
0
                ", has already occurred ",
1220
0
                (entry.Feature == LinkEntry::DEFAULT
1221
0
                   ? "without any feature or 'DEFAULT' feature"
1222
0
                   : cmStrCat("with the feature '", entry.Feature, '\'')),
1223
0
                ", which is not allowed."),
1224
0
              this->Target->GetBacktrace());
1225
0
          }
1226
0
        }
1227
0
      }
1228
0
    }
1229
1230
0
    if (group) {
1231
      // store item index for dependencies handling
1232
0
      groupItems.push_back(dependee_index);
1233
0
    } else {
1234
0
      std::vector<size_t> indexes;
1235
0
      bool entryHandled = false;
1236
      // search any occurrence of the library in already defined groups
1237
0
      for (auto const& g : this->GroupItems) {
1238
0
        for (auto index : g.second) {
1239
0
          if (entry.Item.Value == this->EntryList[index].Item.Value) {
1240
0
            indexes.push_back(g.first);
1241
0
            entryHandled = true;
1242
0
            break;
1243
0
          }
1244
0
        }
1245
0
      }
1246
0
      if (!entryHandled) {
1247
0
        indexes.push_back(dependee_index);
1248
0
      }
1249
1250
0
      for (auto index : indexes) {
1251
        // The dependee must come after the depender.
1252
0
        if (depender_index) {
1253
0
          this->EntryConstraintGraph[*depender_index].emplace_back(
1254
0
            index, false, false, cmListFileBacktrace());
1255
0
        } else {
1256
          // This is a direct dependency of the target being linked.
1257
0
          this->OriginalEntries.push_back(index);
1258
0
        }
1259
1260
        // Update the inferred dependencies for earlier items.
1261
0
        for (auto& dependSet : dependSets) {
1262
          // Add this item to the inferred dependencies of other items.
1263
          // Target items are never inferred dependees because unknown
1264
          // items are outside libraries that should not be depending on
1265
          // targets.
1266
0
          if (!this->EntryList[index].Target &&
1267
0
              this->EntryList[index].Kind != LinkEntry::Flag &&
1268
0
              this->EntryList[index].Kind != LinkEntry::Group &&
1269
0
              dependee_index != dependSet.first) {
1270
0
            dependSet.second.insert(index);
1271
0
          }
1272
0
        }
1273
1274
        // If this item needs to have dependencies inferred, do so.
1275
0
        if (this->InferredDependSets[index].Initialized) {
1276
          // Make sure an entry exists to hold the set for the item.
1277
0
          dependSets[index];
1278
0
        }
1279
0
      }
1280
0
    }
1281
0
  }
1282
1283
  // Store the inferred dependency sets discovered for this list.
1284
0
  for (auto const& dependSet : dependSets) {
1285
0
    this->InferredDependSets[dependSet.first].push_back(dependSet.second);
1286
0
  }
1287
0
}
1288
1289
void cmComputeLinkDepends::AddLinkObjects(std::vector<cmLinkItem> const& objs)
1290
0
{
1291
0
  for (cmLinkItem const& obj : objs) {
1292
0
    this->AddLinkObject(obj);
1293
0
  }
1294
0
}
1295
1296
cmLinkItem cmComputeLinkDepends::ResolveLinkItem(
1297
  cm::optional<size_t> depender_index, std::string const& name)
1298
0
{
1299
  // Look for a target in the scope of the depender.
1300
0
  cmGeneratorTarget const* from = this->Target;
1301
0
  if (depender_index) {
1302
0
    if (cmGeneratorTarget const* depender =
1303
0
          this->EntryList[*depender_index].Target) {
1304
0
      from = depender;
1305
0
    }
1306
0
  }
1307
0
  return from->ResolveLinkItem(BT<std::string>(name));
1308
0
}
1309
1310
void cmComputeLinkDepends::InferDependencies()
1311
0
{
1312
  // The inferred dependency sets for each item list the possible
1313
  // dependencies.  The intersection of the sets for one item form its
1314
  // inferred dependencies.
1315
0
  for (size_t depender_index = 0;
1316
0
       depender_index < this->InferredDependSets.size(); ++depender_index) {
1317
    // Skip items for which dependencies do not need to be inferred or
1318
    // for which the inferred dependency sets are empty.
1319
0
    DependSetList& sets = this->InferredDependSets[depender_index];
1320
0
    if (!sets.Initialized || sets.empty()) {
1321
0
      continue;
1322
0
    }
1323
1324
    // Intersect the sets for this item.
1325
0
    DependSet common = sets.front();
1326
0
    for (DependSet const& i : cmMakeRange(sets).advance(1)) {
1327
0
      DependSet intersection;
1328
0
      std::set_intersection(common.begin(), common.end(), i.begin(), i.end(),
1329
0
                            std::inserter(intersection, intersection.begin()));
1330
0
      common = intersection;
1331
0
    }
1332
1333
    // Add the inferred dependencies to the graph.
1334
0
    cmGraphEdgeList& edges = this->EntryConstraintGraph[depender_index];
1335
0
    edges.reserve(edges.size() + common.size());
1336
0
    for (auto const& c : common) {
1337
0
      edges.emplace_back(c, true, false, cmListFileBacktrace());
1338
0
    }
1339
0
  }
1340
0
}
1341
1342
void cmComputeLinkDepends::UpdateGroupDependencies()
1343
0
{
1344
0
  if (this->GroupItems.empty()) {
1345
0
    return;
1346
0
  }
1347
1348
  // Walks through all entries of the constraint graph to replace dependencies
1349
  // over raw items by the group it belongs to, if any.
1350
0
  for (auto& edgeList : this->EntryConstraintGraph) {
1351
0
    for (auto& edge : edgeList) {
1352
0
      size_t index = edge;
1353
0
      if (this->EntryList[index].Kind == LinkEntry::Group ||
1354
0
          this->EntryList[index].Kind == LinkEntry::Flag ||
1355
0
          this->EntryList[index].Kind == LinkEntry::Object) {
1356
0
        continue;
1357
0
      }
1358
      // search the item in the defined groups
1359
0
      for (auto const& groupItems : this->GroupItems) {
1360
0
        auto pos = std::find(groupItems.second.cbegin(),
1361
0
                             groupItems.second.cend(), index);
1362
0
        if (pos != groupItems.second.cend()) {
1363
          // replace lib dependency by the group it belongs to
1364
0
          edge = cmGraphEdge{ groupItems.first, false, false,
1365
0
                              cmListFileBacktrace() };
1366
0
        }
1367
0
      }
1368
0
    }
1369
0
  }
1370
0
}
1371
1372
void cmComputeLinkDepends::CleanConstraintGraph()
1373
0
{
1374
0
  for (cmGraphEdgeList& edgeList : this->EntryConstraintGraph) {
1375
    // Sort the outgoing edges for each graph node so that the
1376
    // original order will be preserved as much as possible.
1377
0
    std::sort(edgeList.begin(), edgeList.end());
1378
1379
    // Make the edge list unique.
1380
0
    edgeList.erase(std::unique(edgeList.begin(), edgeList.end()),
1381
0
                   edgeList.end());
1382
0
  }
1383
0
}
1384
1385
bool cmComputeLinkDepends::CheckCircularDependencies() const
1386
0
{
1387
0
  std::vector<NodeList> const& components = this->CCG->GetComponents();
1388
0
  size_t nc = components.size();
1389
0
  for (size_t c = 0; c < nc; ++c) {
1390
    // Get the current component.
1391
0
    NodeList const& nl = components[c];
1392
1393
    // Skip trivial components.
1394
0
    if (nl.size() < 2) {
1395
0
      continue;
1396
0
    }
1397
1398
    // no group must be evolved
1399
0
    bool cycleDetected = false;
1400
0
    for (size_t ni : nl) {
1401
0
      if (this->EntryList[ni].Kind == LinkEntry::Group) {
1402
0
        cycleDetected = true;
1403
0
        break;
1404
0
      }
1405
0
    }
1406
0
    if (!cycleDetected) {
1407
0
      continue;
1408
0
    }
1409
1410
    // Construct the error message.
1411
0
    auto formatItem = [](LinkEntry const& entry) -> std::string {
1412
0
      if (entry.Kind == LinkEntry::Group) {
1413
0
        auto items =
1414
0
          entry.Item.Value.substr(entry.Item.Value.find(':', 12) + 1);
1415
0
        items.pop_back();
1416
0
        std::replace(items.begin(), items.end(), '|', ',');
1417
0
        return cmStrCat("group \"", ExtractGroupFeature(entry.Item.Value),
1418
0
                        ":{", items, "}\"");
1419
0
      }
1420
0
      return cmStrCat('"', entry.Item.Value, '"');
1421
0
    };
1422
1423
0
    std::ostringstream e;
1424
0
    e << "The inter-target dependency graph, for the target \""
1425
0
      << this->Target->GetName()
1426
0
      << "\", contains the following strongly connected component "
1427
0
         "(cycle):\n";
1428
0
    std::vector<size_t> const& cmap = this->CCG->GetComponentMap();
1429
0
    for (size_t i : nl) {
1430
      // Get the depender.
1431
0
      LinkEntry const& depender = this->EntryList[i];
1432
1433
      // Describe the depender.
1434
0
      e << "  " << formatItem(depender) << "\n";
1435
1436
      // List its dependencies that are inside the component.
1437
0
      EdgeList const& el = this->EntryConstraintGraph[i];
1438
0
      for (cmGraphEdge const& ni : el) {
1439
0
        size_t j = ni;
1440
0
        if (cmap[j] == c) {
1441
0
          LinkEntry const& dependee = this->EntryList[j];
1442
0
          e << "    depends on " << formatItem(dependee) << "\n";
1443
0
        }
1444
0
      }
1445
0
    }
1446
0
    this->CMakeInstance->IssueMessage(MessageType::FATAL_ERROR, e.str(),
1447
0
                                      this->Target->GetBacktrace());
1448
1449
0
    return false;
1450
0
  }
1451
1452
0
  return true;
1453
0
}
1454
1455
void cmComputeLinkDepends::DisplayConstraintGraph()
1456
0
{
1457
  // Display the graph nodes and their edges.
1458
0
  std::ostringstream e;
1459
0
  for (size_t i = 0; i < this->EntryConstraintGraph.size(); ++i) {
1460
0
    EdgeList const& nl = this->EntryConstraintGraph[i];
1461
0
    e << "item " << i << " is [" << this->EntryList[i].Item << "]\n";
1462
0
    e << cmWrap("  item ", nl, " must follow it", "\n") << "\n";
1463
0
  }
1464
0
  fprintf(stderr, "%s\n", e.str().c_str());
1465
0
}
1466
1467
void cmComputeLinkDepends::OrderLinkEntries()
1468
0
{
1469
  // The component graph is guaranteed to be acyclic.  Start a DFS
1470
  // from every entry to compute a topological order for the
1471
  // components.
1472
0
  Graph const& cgraph = this->CCG->GetComponentGraph();
1473
0
  size_t n = cgraph.size();
1474
0
  this->ComponentVisited.resize(cgraph.size(), 0);
1475
0
  this->ComponentOrder.resize(cgraph.size(), n);
1476
0
  this->ComponentOrderId = n;
1477
  // Run in reverse order so the topological order will preserve the
1478
  // original order where there are no constraints.
1479
0
  for (size_t c = n; c > 0; --c) {
1480
0
    this->VisitComponent(c - 1);
1481
0
  }
1482
1483
  // Display the component graph.
1484
0
  if (this->DebugMode) {
1485
0
    this->DisplayComponents();
1486
0
  }
1487
1488
  // Start with the original link line.
1489
0
  switch (this->Strategy) {
1490
0
    case LinkLibrariesStrategy::REORDER_MINIMALLY: {
1491
      // Emit the direct dependencies in their original order.
1492
      // This gives projects control over ordering.
1493
0
      for (size_t originalEntry : this->OriginalEntries) {
1494
0
        this->VisitEntry(originalEntry);
1495
0
      }
1496
0
    } break;
1497
0
    case LinkLibrariesStrategy::REORDER_FREELY: {
1498
      // Schedule the direct dependencies for emission in topo order.
1499
      // This may produce more efficient link lines.
1500
0
      for (size_t originalEntry : this->OriginalEntries) {
1501
0
        this->MakePendingComponent(
1502
0
          this->CCG->GetComponentMap()[originalEntry]);
1503
0
      }
1504
0
    } break;
1505
0
  }
1506
1507
  // Now explore anything left pending.  Since the component graph is
1508
  // guaranteed to be acyclic we know this will terminate.
1509
0
  while (!this->PendingComponents.empty()) {
1510
    // Visit one entry from the first pending component.  The visit
1511
    // logic will update the pending components accordingly.  Since
1512
    // the pending components are kept in topological order this will
1513
    // not repeat one.
1514
0
    size_t e = *this->PendingComponents.begin()->second.Entries.begin();
1515
0
    this->VisitEntry(e);
1516
0
  }
1517
0
}
1518
1519
void cmComputeLinkDepends::DisplayComponents()
1520
0
{
1521
0
  fprintf(stderr, "The strongly connected components are:\n");
1522
0
  std::vector<NodeList> const& components = this->CCG->GetComponents();
1523
0
  for (size_t c = 0; c < components.size(); ++c) {
1524
0
    fprintf(stderr, "Component (%zu):\n", c);
1525
0
    NodeList const& nl = components[c];
1526
0
    for (size_t i : nl) {
1527
0
      fprintf(stderr, "  item %zu [%s]\n", i,
1528
0
              this->EntryList[i].Item.Value.c_str());
1529
0
    }
1530
0
    EdgeList const& ol = this->CCG->GetComponentGraphEdges(c);
1531
0
    for (cmGraphEdge const& oi : ol) {
1532
0
      size_t i = oi;
1533
0
      fprintf(stderr, "  followed by Component (%zu)\n", i);
1534
0
    }
1535
0
    fprintf(stderr, "  topo order index %zu\n", this->ComponentOrder[c]);
1536
0
  }
1537
0
  fprintf(stderr, "\n");
1538
0
}
1539
1540
void cmComputeLinkDepends::VisitComponent(size_t c)
1541
0
{
1542
  // Check if the node has already been visited.
1543
0
  if (this->ComponentVisited[c]) {
1544
0
    return;
1545
0
  }
1546
1547
  // We are now visiting this component so mark it.
1548
0
  this->ComponentVisited[c] = 1;
1549
1550
  // Visit the neighbors of the component first.
1551
  // Run in reverse order so the topological order will preserve the
1552
  // original order where there are no constraints.
1553
0
  EdgeList const& nl = this->CCG->GetComponentGraphEdges(c);
1554
0
  for (cmGraphEdge const& edge : cmReverseRange(nl)) {
1555
0
    this->VisitComponent(edge);
1556
0
  }
1557
1558
  // Assign an ordering id to this component.
1559
0
  this->ComponentOrder[c] = --this->ComponentOrderId;
1560
0
}
1561
1562
void cmComputeLinkDepends::VisitEntry(size_t index)
1563
0
{
1564
  // Include this entry on the link line.
1565
0
  this->FinalLinkOrder.push_back(index);
1566
1567
  // This entry has now been seen.  Update its component.
1568
0
  bool completed = false;
1569
0
  size_t component = this->CCG->GetComponentMap()[index];
1570
0
  auto mi = this->PendingComponents.find(this->ComponentOrder[component]);
1571
0
  if (mi != this->PendingComponents.end()) {
1572
    // The entry is in an already pending component.
1573
0
    PendingComponent& pc = mi->second;
1574
1575
    // Remove the entry from those pending in its component.
1576
0
    pc.Entries.erase(index);
1577
0
    if (pc.Entries.empty()) {
1578
      // The complete component has been seen since it was last needed.
1579
0
      --pc.Count;
1580
1581
0
      if (pc.Count == 0) {
1582
        // The component has been completed.
1583
0
        this->PendingComponents.erase(mi);
1584
0
        completed = true;
1585
0
      } else {
1586
        // The whole component needs to be seen again.
1587
0
        NodeList const& nl = this->CCG->GetComponent(component);
1588
0
        assert(nl.size() > 1);
1589
0
        pc.Entries.insert(nl.begin(), nl.end());
1590
0
      }
1591
0
    }
1592
0
  } else {
1593
    // The entry is not in an already pending component.
1594
0
    NodeList const& nl = this->CCG->GetComponent(component);
1595
0
    if (nl.size() > 1) {
1596
      // This is a non-trivial component.  It is now pending.
1597
0
      PendingComponent& pc = this->MakePendingComponent(component);
1598
1599
      // The starting entry has already been seen.
1600
0
      pc.Entries.erase(index);
1601
0
    } else {
1602
      // This is a trivial component, so it is already complete.
1603
0
      completed = true;
1604
0
    }
1605
0
  }
1606
1607
  // If the entry completed a component, the component's dependencies
1608
  // are now pending.
1609
0
  if (completed) {
1610
0
    EdgeList const& ol = this->CCG->GetComponentGraphEdges(component);
1611
0
    for (cmGraphEdge const& oi : ol) {
1612
      // This entire component is now pending no matter whether it has
1613
      // been partially seen already.
1614
0
      this->MakePendingComponent(oi);
1615
0
    }
1616
0
  }
1617
0
}
1618
1619
cmComputeLinkDepends::PendingComponent&
1620
cmComputeLinkDepends::MakePendingComponent(size_t component)
1621
0
{
1622
  // Create an entry (in topological order) for the component.
1623
0
  PendingComponent& pc =
1624
0
    this->PendingComponents[this->ComponentOrder[component]];
1625
0
  pc.Id = component;
1626
0
  NodeList const& nl = this->CCG->GetComponent(component);
1627
1628
0
  if (nl.size() == 1) {
1629
    // Trivial components need be seen only once.
1630
0
    pc.Count = 1;
1631
0
  } else {
1632
    // This is a non-trivial strongly connected component of the
1633
    // original graph.  It consists of two or more libraries
1634
    // (archives) that mutually require objects from one another.  In
1635
    // the worst case we may have to repeat the list of libraries as
1636
    // many times as there are object files in the biggest archive.
1637
    // For now we just list them twice.
1638
    //
1639
    // The list of items in the component has been sorted by the order
1640
    // of discovery in the original BFS of dependencies.  This has the
1641
    // advantage that the item directly linked by a target requiring
1642
    // this component will come first which minimizes the number of
1643
    // repeats needed.
1644
0
    pc.Count = this->ComputeComponentCount(nl);
1645
0
  }
1646
1647
  // Store the entries to be seen.
1648
0
  pc.Entries.insert(nl.begin(), nl.end());
1649
1650
0
  return pc;
1651
0
}
1652
1653
size_t cmComputeLinkDepends::ComputeComponentCount(NodeList const& nl)
1654
0
{
1655
0
  size_t count = 2;
1656
0
  for (size_t ni : nl) {
1657
0
    if (cmGeneratorTarget const* target = this->EntryList[ni].Target) {
1658
0
      if (cmLinkInterface const* iface =
1659
0
            target->GetLinkInterface(this->Config, this->Target)) {
1660
0
        if (iface->Multiplicity > count) {
1661
0
          count = iface->Multiplicity;
1662
0
        }
1663
0
      }
1664
0
    }
1665
0
  }
1666
0
  return count;
1667
0
}
1668
1669
namespace {
1670
void DisplayLinkEntry(int& count, cmComputeLinkDepends::LinkEntry const& entry)
1671
0
{
1672
0
  if (entry.Kind == cmComputeLinkDepends::LinkEntry::Group) {
1673
0
    if (entry.Item.Value == LG_ITEM_BEGIN) {
1674
0
      fprintf(stderr, "  start group");
1675
0
      count = 4;
1676
0
    } else if (entry.Item.Value == LG_ITEM_END) {
1677
0
      fprintf(stderr, "  end group");
1678
0
      count = 2;
1679
0
    } else {
1680
0
      fprintf(stderr, "  group");
1681
0
    }
1682
0
  } else if (entry.Target) {
1683
0
    fprintf(stderr, "%*starget [%s]", count, "",
1684
0
            entry.Target->GetName().c_str());
1685
0
  } else {
1686
0
    fprintf(stderr, "%*sitem [%s]", count, "", entry.Item.Value.c_str());
1687
0
  }
1688
0
  if (entry.Feature != cmComputeLinkDepends::LinkEntry::DEFAULT) {
1689
0
    fprintf(stderr, ", feature [%s]", entry.Feature.c_str());
1690
0
  }
1691
0
  fprintf(stderr, "\n");
1692
0
}
1693
}
1694
1695
void cmComputeLinkDepends::DisplayOrderedEntries()
1696
0
{
1697
0
  fprintf(stderr, "target [%s] link dependency ordering:\n",
1698
0
          this->Target->GetName().c_str());
1699
0
  int count = 2;
1700
0
  for (auto index : this->FinalLinkOrder) {
1701
0
    DisplayLinkEntry(count, this->EntryList[index]);
1702
0
  }
1703
0
  fprintf(stderr, "\n");
1704
0
}
1705
1706
void cmComputeLinkDepends::DisplayFinalEntries()
1707
0
{
1708
0
  fprintf(stderr, "target [%s] link line:\n", this->Target->GetName().c_str());
1709
0
  int count = 2;
1710
0
  for (LinkEntry const& entry : this->FinalLinkEntries) {
1711
0
    DisplayLinkEntry(count, entry);
1712
0
  }
1713
  fprintf(stderr, "\n");
1714
0
}