Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Linker/LinkModules.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file implements the LLVM module linker.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "LinkDiagnosticInfo.h"
14
#include "llvm-c/Linker.h"
15
#include "llvm/ADT/SetVector.h"
16
#include "llvm/IR/Comdat.h"
17
#include "llvm/IR/DiagnosticPrinter.h"
18
#include "llvm/IR/GlobalValue.h"
19
#include "llvm/IR/LLVMContext.h"
20
#include "llvm/IR/Module.h"
21
#include "llvm/Linker/Linker.h"
22
#include "llvm/Support/Error.h"
23
using namespace llvm;
24
25
namespace {
26
27
/// This is an implementation class for the LinkModules function, which is the
28
/// entrypoint for this file.
29
class ModuleLinker {
30
  IRMover &Mover;
31
  std::unique_ptr<Module> SrcM;
32
33
  SetVector<GlobalValue *> ValuesToLink;
34
35
  /// For symbol clashes, prefer those from Src.
36
  unsigned Flags;
37
38
  /// List of global value names that should be internalized.
39
  StringSet<> Internalize;
40
41
  /// Function that will perform the actual internalization. The reason for a
42
  /// callback is that the linker cannot call internalizeModule without
43
  /// creating a circular dependency between IPO and the linker.
44
  std::function<void(Module &, const StringSet<> &)> InternalizeCallback;
45
46
  /// Used as the callback for lazy linking.
47
  /// The mover has just hit GV and we have to decide if it, and other members
48
  /// of the same comdat, should be linked. Every member to be linked is passed
49
  /// to Add.
50
  void addLazyFor(GlobalValue &GV, const IRMover::ValueAdder &Add);
51
52
1.30k
  bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
53
1.47k
  bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
54
55
  bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
56
                            const GlobalValue &Src);
57
58
  /// Should we have mover and linker error diag info?
59
10
  bool emitError(const Twine &Message) {
60
10
    SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
61
10
    return true;
62
10
  }
63
64
  bool getComdatLeader(Module &M, StringRef ComdatName,
65
                       const GlobalVariable *&GVar);
66
  bool computeResultingSelectionKind(StringRef ComdatName,
67
                                     Comdat::SelectionKind Src,
68
                                     Comdat::SelectionKind Dst,
69
                                     Comdat::SelectionKind &Result,
70
                                     bool &LinkFromSrc);
71
  std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
72
      ComdatsChosen;
73
  bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
74
                       bool &LinkFromSrc);
75
  // Keep track of the lazy linked global members of each comdat in source.
76
  DenseMap<const Comdat *, std::vector<GlobalValue *>> LazyComdatMembers;
77
78
  /// Given a global in the source module, return the global in the
79
  /// destination module that is being linked to, if any.
80
1.45k
  GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
81
1.45k
    Module &DstM = Mover.getModule();
82
1.45k
    // If the source has no name it can't link.  If it has local linkage,
83
1.45k
    // there is no name match-up going on.
84
1.45k
    if (!SrcGV->hasName() || 
GlobalValue::isLocalLinkage(SrcGV->getLinkage())1.44k
)
85
110
      return nullptr;
86
1.34k
87
1.34k
    // Otherwise see if we have a match in the destination module's symtab.
88
1.34k
    GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
89
1.34k
    if (!DGV)
90
1.09k
      return nullptr;
91
246
92
246
    // If we found a global with the same name in the dest module, but it has
93
246
    // internal linkage, we are really not doing any linkage here.
94
246
    if (DGV->hasLocalLinkage())
95
6
      return nullptr;
96
240
97
240
    // Otherwise, we do in fact link to the destination global.
98
240
    return DGV;
99
240
  }
100
101
  /// Drop GV if it is a member of a comdat that we are dropping.
102
  /// This can happen with COFF's largest selection kind.
103
  void dropReplacedComdat(GlobalValue &GV,
104
                          const DenseSet<const Comdat *> &ReplacedDstComdats);
105
106
  bool linkIfNeeded(GlobalValue &GV);
107
108
public:
109
  ModuleLinker(IRMover &Mover, std::unique_ptr<Module> SrcM, unsigned Flags,
110
               std::function<void(Module &, const StringSet<> &)>
111
                   InternalizeCallback = {})
112
      : Mover(Mover), SrcM(std::move(SrcM)), Flags(Flags),
113
570
        InternalizeCallback(std::move(InternalizeCallback)) {}
114
115
  bool run();
116
};
117
}
118
119
static GlobalValue::VisibilityTypes
120
getMinVisibility(GlobalValue::VisibilityTypes A,
121
223
                 GlobalValue::VisibilityTypes B) {
122
223
  if (A == GlobalValue::HiddenVisibility || 
B == GlobalValue::HiddenVisibility216
)
123
14
    return GlobalValue::HiddenVisibility;
124
209
  if (A == GlobalValue::ProtectedVisibility ||
125
209
      
B == GlobalValue::ProtectedVisibility206
)
126
7
    return GlobalValue::ProtectedVisibility;
127
202
  return GlobalValue::DefaultVisibility;
128
202
}
129
130
bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
131
12
                                   const GlobalVariable *&GVar) {
132
12
  const GlobalValue *GVal = M.getNamedValue(ComdatName);
133
12
  if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
134
2
    GVal = GA->getBaseObject();
135
2
    if (!GVal)
136
1
      // We cannot resolve the size of the aliasee yet.
137
1
      return emitError("Linking COMDATs named '" + ComdatName +
138
1
                       "': COMDAT key involves incomputable alias size.");
139
11
  }
140
11
141
11
  GVar = dyn_cast_or_null<GlobalVariable>(GVal);
142
11
  if (!GVar)
143
1
    return emitError(
144
1
        "Linking COMDATs named '" + ComdatName +
145
1
        "': GlobalVariable required for data dependent selection!");
146
10
147
10
  return false;
148
10
}
149
150
bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
151
                                                 Comdat::SelectionKind Src,
152
                                                 Comdat::SelectionKind Dst,
153
                                                 Comdat::SelectionKind &Result,
154
19
                                                 bool &LinkFromSrc) {
155
19
  Module &DstM = Mover.getModule();
156
19
  // The ability to mix Comdat::SelectionKind::Any with
157
19
  // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
158
19
  bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
159
19
                         
Dst == Comdat::SelectionKind::Largest9
;
160
19
  bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
161
19
                         
Src == Comdat::SelectionKind::Largest9
;
162
19
  if (DstAnyOrLargest && 
SrcAnyOrLargest16
) {
163
16
    if (Dst == Comdat::SelectionKind::Largest ||
164
16
        
Src == Comdat::SelectionKind::Largest10
)
165
6
      Result = Comdat::SelectionKind::Largest;
166
10
    else
167
10
      Result = Comdat::SelectionKind::Any;
168
16
  } else 
if (3
Src == Dst3
) {
169
2
    Result = Dst;
170
2
  } else {
171
1
    return emitError("Linking COMDATs named '" + ComdatName +
172
1
                     "': invalid selection kinds!");
173
1
  }
174
18
175
18
  switch (Result) {
176
18
  case Comdat::SelectionKind::Any:
177
10
    // Go with Dst.
178
10
    LinkFromSrc = false;
179
10
    break;
180
18
  case Comdat::SelectionKind::NoDuplicates:
181
1
    return emitError("Linking COMDATs named '" + ComdatName +
182
1
                     "': noduplicates has been violated!");
183
18
  case Comdat::SelectionKind::ExactMatch:
184
7
  case Comdat::SelectionKind::Largest:
185
7
  case Comdat::SelectionKind::SameSize: {
186
7
    const GlobalVariable *DstGV;
187
7
    const GlobalVariable *SrcGV;
188
7
    if (getComdatLeader(DstM, ComdatName, DstGV) ||
189
7
        
getComdatLeader(*SrcM, ComdatName, SrcGV)5
)
190
2
      return true;
191
5
192
5
    const DataLayout &DstDL = DstM.getDataLayout();
193
5
    const DataLayout &SrcDL = SrcM->getDataLayout();
194
5
    uint64_t DstSize = DstDL.getTypeAllocSize(DstGV->getValueType());
195
5
    uint64_t SrcSize = SrcDL.getTypeAllocSize(SrcGV->getValueType());
196
5
    if (Result == Comdat::SelectionKind::ExactMatch) {
197
0
      if (SrcGV->getInitializer() != DstGV->getInitializer())
198
0
        return emitError("Linking COMDATs named '" + ComdatName +
199
0
                         "': ExactMatch violated!");
200
0
      LinkFromSrc = false;
201
5
    } else if (Result == Comdat::SelectionKind::Largest) {
202
4
      LinkFromSrc = SrcSize > DstSize;
203
4
    } else 
if (1
Result == Comdat::SelectionKind::SameSize1
) {
204
1
      if (SrcSize != DstSize)
205
1
        return emitError("Linking COMDATs named '" + ComdatName +
206
1
                         "': SameSize violated!");
207
0
      LinkFromSrc = false;
208
0
    } else {
209
0
      llvm_unreachable("unknown selection kind");
210
0
    }
211
4
    break;
212
4
  }
213
14
  }
214
14
215
14
  return false;
216
14
}
217
218
bool ModuleLinker::getComdatResult(const Comdat *SrcC,
219
                                   Comdat::SelectionKind &Result,
220
53
                                   bool &LinkFromSrc) {
221
53
  Module &DstM = Mover.getModule();
222
53
  Comdat::SelectionKind SSK = SrcC->getSelectionKind();
223
53
  StringRef ComdatName = SrcC->getName();
224
53
  Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
225
53
  Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
226
53
227
53
  if (DstCI == ComdatSymTab.end()) {
228
34
    // Use the comdat if it is only available in one of the modules.
229
34
    LinkFromSrc = true;
230
34
    Result = SSK;
231
34
    return false;
232
34
  }
233
19
234
19
  const Comdat *DstC = &DstCI->second;
235
19
  Comdat::SelectionKind DSK = DstC->getSelectionKind();
236
19
  return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
237
19
                                       LinkFromSrc);
238
19
}
239
240
bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
241
                                        const GlobalValue &Dest,
242
188
                                        const GlobalValue &Src) {
243
188
244
188
  // Should we unconditionally use the Src?
245
188
  if (shouldOverrideFromSrc()) {
246
4
    LinkFromSrc = true;
247
4
    return false;
248
4
  }
249
184
250
184
  // We always have to add Src if it has appending linkage.
251
184
  if (Src.hasAppendingLinkage()) {
252
15
    LinkFromSrc = true;
253
15
    return false;
254
15
  }
255
169
256
169
  bool SrcIsDeclaration = Src.isDeclarationForLinker();
257
169
  bool DestIsDeclaration = Dest.isDeclarationForLinker();
258
169
259
169
  if (SrcIsDeclaration) {
260
3
    // If Src is external or if both Src & Dest are external..  Just link the
261
3
    // external globals, we aren't adding anything.
262
3
    if (Src.hasDLLImportStorageClass()) {
263
0
      // If one of GVs is marked as DLLImport, result should be dllimport'ed.
264
0
      LinkFromSrc = DestIsDeclaration;
265
0
      return false;
266
0
    }
267
3
    // If the Dest is weak, use the source linkage.
268
3
    if (Dest.hasExternalWeakLinkage()) {
269
0
      LinkFromSrc = true;
270
0
      return false;
271
0
    }
272
3
    // Link an available_externally over a declaration.
273
3
    LinkFromSrc = !Src.isDeclaration() && Dest.isDeclaration();
274
3
    return false;
275
3
  }
276
166
277
166
  if (DestIsDeclaration) {
278
76
    // If Dest is external but Src is not:
279
76
    LinkFromSrc = true;
280
76
    return false;
281
76
  }
282
90
283
90
  if (Src.hasCommonLinkage()) {
284
9
    if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
285
1
      LinkFromSrc = true;
286
1
      return false;
287
1
    }
288
8
289
8
    if (!Dest.hasCommonLinkage()) {
290
0
      LinkFromSrc = false;
291
0
      return false;
292
0
    }
293
8
294
8
    const DataLayout &DL = Dest.getParent()->getDataLayout();
295
8
    uint64_t DestSize = DL.getTypeAllocSize(Dest.getValueType());
296
8
    uint64_t SrcSize = DL.getTypeAllocSize(Src.getValueType());
297
8
    LinkFromSrc = SrcSize > DestSize;
298
8
    return false;
299
8
  }
300
81
301
81
  if (Src.isWeakForLinker()) {
302
51
    assert(!Dest.hasExternalWeakLinkage());
303
51
    assert(!Dest.hasAvailableExternallyLinkage());
304
51
305
51
    if (Dest.hasLinkOnceLinkage() && 
Src.hasWeakLinkage()5
) {
306
1
      LinkFromSrc = true;
307
1
      return false;
308
1
    }
309
50
310
50
    LinkFromSrc = false;
311
50
    return false;
312
50
  }
313
30
314
30
  if (Dest.isWeakForLinker()) {
315
25
    assert(Src.hasExternalLinkage());
316
25
    LinkFromSrc = true;
317
25
    return false;
318
25
  }
319
5
320
5
  assert(!Src.hasExternalWeakLinkage());
321
5
  assert(!Dest.hasExternalWeakLinkage());
322
5
  assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
323
5
         "Unexpected linkage type!");
324
5
  return emitError("Linking globals named '" + Src.getName() +
325
5
                   "': symbol multiply defined!");
326
5
}
327
328
1.44k
bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
329
1.44k
  GlobalValue *DGV = getLinkedToGlobal(&GV);
330
1.44k
331
1.44k
  if (shouldLinkOnlyNeeded()) {
332
121
    // Always import variables with appending linkage.
333
121
    if (!GV.hasAppendingLinkage()) {
334
109
      // Don't import globals unless they are referenced by the destination
335
109
      // module.
336
109
      if (!DGV)
337
89
        return false;
338
20
      // Don't import globals that are already defined in the destination module
339
20
      if (!DGV->isDeclaration())
340
0
        return false;
341
1.35k
    }
342
121
  }
343
1.35k
344
1.35k
  if (DGV && 
!GV.hasLocalLinkage()238
&&
!GV.hasAppendingLinkage()238
) {
345
223
    auto *DGVar = dyn_cast<GlobalVariable>(DGV);
346
223
    auto *SGVar = dyn_cast<GlobalVariable>(&GV);
347
223
    if (DGVar && 
SGVar81
) {
348
73
      if (DGVar->isDeclaration() && 
SGVar->isDeclaration()20
&&
349
73
          
(2
!DGVar->isConstant()2
||
!SGVar->isConstant()0
)) {
350
2
        DGVar->setConstant(false);
351
2
        SGVar->setConstant(false);
352
2
      }
353
73
      if (DGVar->hasCommonLinkage() && 
SGVar->hasCommonLinkage()9
) {
354
8
        unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment());
355
8
        SGVar->setAlignment(Align);
356
8
        DGVar->setAlignment(Align);
357
8
      }
358
73
    }
359
223
360
223
    GlobalValue::VisibilityTypes Visibility =
361
223
        getMinVisibility(DGV->getVisibility(), GV.getVisibility());
362
223
    DGV->setVisibility(Visibility);
363
223
    GV.setVisibility(Visibility);
364
223
365
223
    GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::getMinUnnamedAddr(
366
223
        DGV->getUnnamedAddr(), GV.getUnnamedAddr());
367
223
    DGV->setUnnamedAddr(UnnamedAddr);
368
223
    GV.setUnnamedAddr(UnnamedAddr);
369
223
  }
370
1.35k
371
1.35k
  if (!DGV && 
!shouldOverrideFromSrc()1.11k
&&
372
1.35k
      
(1.11k
GV.hasLocalLinkage()1.11k
||
GV.hasLinkOnceLinkage()1.02k
||
373
1.11k
       
GV.hasAvailableExternallyLinkage()969
))
374
147
    return false;
375
1.20k
376
1.20k
  if (GV.isDeclaration())
377
313
    return false;
378
893
379
893
  if (const Comdat *SC = GV.getComdat()) {
380
66
    bool LinkFromSrc;
381
66
    Comdat::SelectionKind SK;
382
66
    std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
383
66
    if (!LinkFromSrc)
384
15
      return false;
385
878
  }
386
878
387
878
  bool LinkFromSrc = true;
388
878
  if (DGV && 
shouldLinkFromSource(LinkFromSrc, *DGV, GV)186
)
389
5
    return true;
390
873
  if (LinkFromSrc)
391
818
    ValuesToLink.insert(&GV);
392
873
  return false;
393
873
}
394
395
67
void ModuleLinker::addLazyFor(GlobalValue &GV, const IRMover::ValueAdder &Add) {
396
67
  // Add these to the internalize list
397
67
  if (!GV.hasLinkOnceLinkage() && 
!GV.hasAvailableExternallyLinkage()33
&&
398
67
      
!shouldLinkOnlyNeeded()29
)
399
8
    return;
400
59
401
59
  if (InternalizeCallback)
402
13
    Internalize.insert(GV.getName());
403
59
  Add(GV);
404
59
405
59
  const Comdat *SC = GV.getComdat();
406
59
  if (!SC)
407
57
    return;
408
5
  
for (GlobalValue *GV2 : LazyComdatMembers[SC])2
{
409
5
    GlobalValue *DGV = getLinkedToGlobal(GV2);
410
5
    bool LinkFromSrc = true;
411
5
    if (DGV && 
shouldLinkFromSource(LinkFromSrc, *DGV, *GV2)1
)
412
0
      return;
413
5
    if (!LinkFromSrc)
414
1
      continue;
415
4
    if (InternalizeCallback)
416
0
      Internalize.insert(GV2->getName());
417
4
    Add(*GV2);
418
4
  }
419
2
}
420
421
void ModuleLinker::dropReplacedComdat(
422
517
    GlobalValue &GV, const DenseSet<const Comdat *> &ReplacedDstComdats) {
423
517
  Comdat *C = GV.getComdat();
424
517
  if (!C)
425
486
    return;
426
31
  if (!ReplacedDstComdats.count(C))
427
23
    return;
428
8
  if (GV.use_empty()) {
429
6
    GV.eraseFromParent();
430
6
    return;
431
6
  }
432
2
433
2
  if (auto *F = dyn_cast<Function>(&GV)) {
434
0
    F->deleteBody();
435
2
  } else if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
436
0
    Var->setInitializer(nullptr);
437
2
  } else {
438
2
    auto &Alias = cast<GlobalAlias>(GV);
439
2
    Module &M = *Alias.getParent();
440
2
    PointerType &Ty = *cast<PointerType>(Alias.getType());
441
2
    GlobalValue *Declaration;
442
2
    if (auto *FTy = dyn_cast<FunctionType>(Alias.getValueType())) {
443
1
      Declaration = Function::Create(FTy, GlobalValue::ExternalLinkage, "", &M);
444
1
    } else {
445
1
      Declaration =
446
1
          new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false,
447
1
                             GlobalValue::ExternalLinkage,
448
1
                             /*Initializer*/ nullptr);
449
1
    }
450
2
    Declaration->takeName(&Alias);
451
2
    Alias.replaceAllUsesWith(Declaration);
452
2
    Alias.eraseFromParent();
453
2
  }
454
2
}
455
456
570
bool ModuleLinker::run() {
457
570
  Module &DstM = Mover.getModule();
458
570
  DenseSet<const Comdat *> ReplacedDstComdats;
459
570
460
570
  for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
461
53
    const Comdat &C = SMEC.getValue();
462
53
    if (ComdatsChosen.count(&C))
463
0
      continue;
464
53
    Comdat::SelectionKind SK;
465
53
    bool LinkFromSrc;
466
53
    if (getComdatResult(&C, SK, LinkFromSrc))
467
5
      return true;
468
48
    ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
469
48
470
48
    if (!LinkFromSrc)
471
12
      continue;
472
36
473
36
    Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
474
36
    Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(C.getName());
475
36
    if (DstCI == ComdatSymTab.end())
476
34
      continue;
477
2
478
2
    // The source comdat is replacing the dest one.
479
2
    const Comdat *DstC = &DstCI->second;
480
2
    ReplacedDstComdats.insert(DstC);
481
2
  }
482
570
483
570
  // Alias have to go first, since we are not able to find their comdats
484
570
  // otherwise.
485
591
  
for (auto I = DstM.alias_begin(), E = DstM.alias_end(); 565
I != E;) {
486
26
    GlobalAlias &GV = *I++;
487
26
    dropReplacedComdat(GV, ReplacedDstComdats);
488
26
  }
489
565
490
735
  for (auto I = DstM.global_begin(), E = DstM.global_end(); I != E;) {
491
170
    GlobalVariable &GV = *I++;
492
170
    dropReplacedComdat(GV, ReplacedDstComdats);
493
170
  }
494
565
495
886
  for (auto I = DstM.begin(), E = DstM.end(); I != E;) {
496
321
    Function &GV = *I++;
497
321
    dropReplacedComdat(GV, ReplacedDstComdats);
498
321
  }
499
565
500
565
  for (GlobalVariable &GV : SrcM->globals())
501
471
    if (GV.hasLinkOnceLinkage())
502
35
      if (const Comdat *SC = GV.getComdat())
503
4
        LazyComdatMembers[SC].push_back(&GV);
504
565
505
565
  for (Function &SF : *SrcM)
506
890
    if (SF.hasLinkOnceLinkage())
507
42
      if (const Comdat *SC = SF.getComdat())
508
8
        LazyComdatMembers[SC].push_back(&SF);
509
565
510
565
  for (GlobalAlias &GA : SrcM->aliases())
511
82
    if (GA.hasLinkOnceLinkage())
512
2
      if (const Comdat *SC = GA.getComdat())
513
0
        LazyComdatMembers[SC].push_back(&GA);
514
565
515
565
  // Insert all of the globals in src into the DstM module... without linking
516
565
  // initializers (which could refer to functions not yet mapped over).
517
565
  for (GlobalVariable &GV : SrcM->globals())
518
471
    if (linkIfNeeded(GV))
519
1
      return true;
520
565
521
565
  
for (Function &SF : *SrcM)564
522
889
    if (linkIfNeeded(SF))
523
4
      return true;
524
564
525
564
  
for (GlobalAlias &GA : SrcM->aliases())560
526
82
    if (linkIfNeeded(GA))
527
0
      return true;
528
560
529
1.38k
  
for (unsigned I = 0; 560
I < ValuesToLink.size();
++I820
) {
530
820
    GlobalValue *GV = ValuesToLink[I];
531
820
    const Comdat *SC = GV->getComdat();
532
820
    if (!SC)
533
773
      continue;
534
47
    for (GlobalValue *GV2 : LazyComdatMembers[SC]) {
535
5
      GlobalValue *DGV = getLinkedToGlobal(GV2);
536
5
      bool LinkFromSrc = true;
537
5
      if (DGV && 
shouldLinkFromSource(LinkFromSrc, *DGV, *GV2)1
)
538
0
        return true;
539
5
      if (LinkFromSrc)
540
4
        ValuesToLink.insert(GV2);
541
5
    }
542
47
  }
543
560
544
560
  if (InternalizeCallback) {
545
26
    for (GlobalValue *GV : ValuesToLink)
546
49
      Internalize.insert(GV->getName());
547
26
  }
548
560
549
560
  // FIXME: Propagate Errors through to the caller instead of emitting
550
560
  // diagnostics.
551
560
  bool HasErrors = false;
552
560
  if (Error E = Mover.move(std::move(SrcM), ValuesToLink.getArrayRef(),
553
67
                           [this](GlobalValue &GV, IRMover::ValueAdder Add) {
554
67
                             addLazyFor(GV, Add);
555
67
                           },
556
5
                           /* IsPerformingImport */ false)) {
557
5
    handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
558
5
      DstM.getContext().diagnose(LinkDiagnosticInfo(DS_Error, EIB.message()));
559
5
      HasErrors = true;
560
5
    });
561
5
  }
562
560
  if (HasErrors)
563
5
    return true;
564
555
565
555
  if (InternalizeCallback)
566
26
    InternalizeCallback(DstM, Internalize);
567
555
568
555
  return false;
569
555
}
570
571
339
Linker::Linker(Module &M) : Mover(M) {}
572
573
bool Linker::linkInModule(
574
    std::unique_ptr<Module> Src, unsigned Flags,
575
570
    std::function<void(Module &, const StringSet<> &)> InternalizeCallback) {
576
570
  ModuleLinker ModLinker(Mover, std::move(Src), Flags,
577
570
                         std::move(InternalizeCallback));
578
570
  return ModLinker.run();
579
570
}
580
581
//===----------------------------------------------------------------------===//
582
// LinkModules entrypoint.
583
//===----------------------------------------------------------------------===//
584
585
/// This function links two modules together, with the resulting Dest module
586
/// modified to be the composite of the two input modules. If an error occurs,
587
/// true is returned and ErrorMsg (if not null) is set to indicate the problem.
588
/// Upon failure, the Dest module could be in a modified state, and shouldn't be
589
/// relied on to be consistent.
590
bool Linker::linkModules(
591
    Module &Dest, std::unique_ptr<Module> Src, unsigned Flags,
592
21
    std::function<void(Module &, const StringSet<> &)> InternalizeCallback) {
593
21
  Linker L(Dest);
594
21
  return L.linkInModule(std::move(Src), Flags, std::move(InternalizeCallback));
595
21
}
596
597
//===----------------------------------------------------------------------===//
598
// C API.
599
//===----------------------------------------------------------------------===//
600
601
2
LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src) {
602
2
  Module *D = unwrap(Dest);
603
2
  std::unique_ptr<Module> M(unwrap(Src));
604
2
  return Linker::linkModules(*D, std::move(M));
605
2
}