0313e2b8a7e085f55453873d2898276537c90f0e
[oota-llvm.git] / lib / Linker / LinkModules.cpp
1 //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the LLVM module linker.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Linker/Linker.h"
15 #include "llvm-c/Linker.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IR/TypeFinder.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Transforms/Utils/Cloning.h"
26 #include <cctype>
27 #include <tuple>
28 using namespace llvm;
29
30
31 //===----------------------------------------------------------------------===//
32 // TypeMap implementation.
33 //===----------------------------------------------------------------------===//
34
35 namespace {
36   typedef SmallPtrSet<StructType*, 32> TypeSet;
37
38 class TypeMapTy : public ValueMapTypeRemapper {
39   /// MappedTypes - This is a mapping from a source type to a destination type
40   /// to use.
41   DenseMap<Type*, Type*> MappedTypes;
42
43   /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
44   /// we speculatively add types to MappedTypes, but keep track of them here in
45   /// case we need to roll back.
46   SmallVector<Type*, 16> SpeculativeTypes;
47
48   /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
49   /// source module that are mapped to an opaque struct in the destination
50   /// module.
51   SmallVector<StructType*, 16> SrcDefinitionsToResolve;
52
53   /// DstResolvedOpaqueTypes - This is the set of opaque types in the
54   /// destination modules who are getting a body from the source module.
55   SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
56
57 public:
58   TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {}
59
60   TypeSet &DstStructTypesSet;
61   /// addTypeMapping - Indicate that the specified type in the destination
62   /// module is conceptually equivalent to the specified type in the source
63   /// module.
64   void addTypeMapping(Type *DstTy, Type *SrcTy);
65
66   /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
67   /// module from a type definition in the source module.
68   void linkDefinedTypeBodies();
69
70   /// get - Return the mapped type to use for the specified input type from the
71   /// source module.
72   Type *get(Type *SrcTy);
73
74   FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
75
76   /// dump - Dump out the type map for debugging purposes.
77   void dump() const {
78     for (DenseMap<Type*, Type*>::const_iterator
79            I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
80       dbgs() << "TypeMap: ";
81       I->first->print(dbgs());
82       dbgs() << " => ";
83       I->second->print(dbgs());
84       dbgs() << '\n';
85     }
86   }
87
88 private:
89   Type *getImpl(Type *T);
90   /// remapType - Implement the ValueMapTypeRemapper interface.
91   Type *remapType(Type *SrcTy) override {
92     return get(SrcTy);
93   }
94
95   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
96 };
97 }
98
99 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
100   Type *&Entry = MappedTypes[SrcTy];
101   if (Entry) return;
102
103   if (DstTy == SrcTy) {
104     Entry = DstTy;
105     return;
106   }
107
108   // Check to see if these types are recursively isomorphic and establish a
109   // mapping between them if so.
110   if (!areTypesIsomorphic(DstTy, SrcTy)) {
111     // Oops, they aren't isomorphic.  Just discard this request by rolling out
112     // any speculative mappings we've established.
113     for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
114       MappedTypes.erase(SpeculativeTypes[i]);
115   }
116   SpeculativeTypes.clear();
117 }
118
119 /// areTypesIsomorphic - Recursively walk this pair of types, returning true
120 /// if they are isomorphic, false if they are not.
121 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
122   // Two types with differing kinds are clearly not isomorphic.
123   if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
124
125   // If we have an entry in the MappedTypes table, then we have our answer.
126   Type *&Entry = MappedTypes[SrcTy];
127   if (Entry)
128     return Entry == DstTy;
129
130   // Two identical types are clearly isomorphic.  Remember this
131   // non-speculatively.
132   if (DstTy == SrcTy) {
133     Entry = DstTy;
134     return true;
135   }
136
137   // Okay, we have two types with identical kinds that we haven't seen before.
138
139   // If this is an opaque struct type, special case it.
140   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
141     // Mapping an opaque type to any struct, just keep the dest struct.
142     if (SSTy->isOpaque()) {
143       Entry = DstTy;
144       SpeculativeTypes.push_back(SrcTy);
145       return true;
146     }
147
148     // Mapping a non-opaque source type to an opaque dest.  If this is the first
149     // type that we're mapping onto this destination type then we succeed.  Keep
150     // the dest, but fill it in later.  This doesn't need to be speculative.  If
151     // this is the second (different) type that we're trying to map onto the
152     // same opaque type then we fail.
153     if (cast<StructType>(DstTy)->isOpaque()) {
154       // We can only map one source type onto the opaque destination type.
155       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
156         return false;
157       SrcDefinitionsToResolve.push_back(SSTy);
158       Entry = DstTy;
159       return true;
160     }
161   }
162
163   // If the number of subtypes disagree between the two types, then we fail.
164   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
165     return false;
166
167   // Fail if any of the extra properties (e.g. array size) of the type disagree.
168   if (isa<IntegerType>(DstTy))
169     return false;  // bitwidth disagrees.
170   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
171     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
172       return false;
173
174   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
175     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
176       return false;
177   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
178     StructType *SSTy = cast<StructType>(SrcTy);
179     if (DSTy->isLiteral() != SSTy->isLiteral() ||
180         DSTy->isPacked() != SSTy->isPacked())
181       return false;
182   } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
183     if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
184       return false;
185   } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
186     if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
187       return false;
188   }
189
190   // Otherwise, we speculate that these two types will line up and recursively
191   // check the subelements.
192   Entry = DstTy;
193   SpeculativeTypes.push_back(SrcTy);
194
195   for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
196     if (!areTypesIsomorphic(DstTy->getContainedType(i),
197                             SrcTy->getContainedType(i)))
198       return false;
199
200   // If everything seems to have lined up, then everything is great.
201   return true;
202 }
203
204 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
205 /// module from a type definition in the source module.
206 void TypeMapTy::linkDefinedTypeBodies() {
207   SmallVector<Type*, 16> Elements;
208   SmallString<16> TmpName;
209
210   // Note that processing entries in this loop (calling 'get') can add new
211   // entries to the SrcDefinitionsToResolve vector.
212   while (!SrcDefinitionsToResolve.empty()) {
213     StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
214     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
215
216     // TypeMap is a many-to-one mapping, if there were multiple types that
217     // provide a body for DstSTy then previous iterations of this loop may have
218     // already handled it.  Just ignore this case.
219     if (!DstSTy->isOpaque()) continue;
220     assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
221
222     // Map the body of the source type over to a new body for the dest type.
223     Elements.resize(SrcSTy->getNumElements());
224     for (unsigned i = 0, e = Elements.size(); i != e; ++i)
225       Elements[i] = getImpl(SrcSTy->getElementType(i));
226
227     DstSTy->setBody(Elements, SrcSTy->isPacked());
228
229     // If DstSTy has no name or has a longer name than STy, then viciously steal
230     // STy's name.
231     if (!SrcSTy->hasName()) continue;
232     StringRef SrcName = SrcSTy->getName();
233
234     if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
235       TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
236       SrcSTy->setName("");
237       DstSTy->setName(TmpName.str());
238       TmpName.clear();
239     }
240   }
241
242   DstResolvedOpaqueTypes.clear();
243 }
244
245 /// get - Return the mapped type to use for the specified input type from the
246 /// source module.
247 Type *TypeMapTy::get(Type *Ty) {
248   Type *Result = getImpl(Ty);
249
250   // If this caused a reference to any struct type, resolve it before returning.
251   if (!SrcDefinitionsToResolve.empty())
252     linkDefinedTypeBodies();
253   return Result;
254 }
255
256 /// getImpl - This is the recursive version of get().
257 Type *TypeMapTy::getImpl(Type *Ty) {
258   // If we already have an entry for this type, return it.
259   Type **Entry = &MappedTypes[Ty];
260   if (*Entry) return *Entry;
261
262   // If this is not a named struct type, then just map all of the elements and
263   // then rebuild the type from inside out.
264   if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
265     // If there are no element types to map, then the type is itself.  This is
266     // true for the anonymous {} struct, things like 'float', integers, etc.
267     if (Ty->getNumContainedTypes() == 0)
268       return *Entry = Ty;
269
270     // Remap all of the elements, keeping track of whether any of them change.
271     bool AnyChange = false;
272     SmallVector<Type*, 4> ElementTypes;
273     ElementTypes.resize(Ty->getNumContainedTypes());
274     for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
275       ElementTypes[i] = getImpl(Ty->getContainedType(i));
276       AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
277     }
278
279     // If we found our type while recursively processing stuff, just use it.
280     Entry = &MappedTypes[Ty];
281     if (*Entry) return *Entry;
282
283     // If all of the element types mapped directly over, then the type is usable
284     // as-is.
285     if (!AnyChange)
286       return *Entry = Ty;
287
288     // Otherwise, rebuild a modified type.
289     switch (Ty->getTypeID()) {
290     default: llvm_unreachable("unknown derived type to remap");
291     case Type::ArrayTyID:
292       return *Entry = ArrayType::get(ElementTypes[0],
293                                      cast<ArrayType>(Ty)->getNumElements());
294     case Type::VectorTyID:
295       return *Entry = VectorType::get(ElementTypes[0],
296                                       cast<VectorType>(Ty)->getNumElements());
297     case Type::PointerTyID:
298       return *Entry = PointerType::get(ElementTypes[0],
299                                       cast<PointerType>(Ty)->getAddressSpace());
300     case Type::FunctionTyID:
301       return *Entry = FunctionType::get(ElementTypes[0],
302                                         makeArrayRef(ElementTypes).slice(1),
303                                         cast<FunctionType>(Ty)->isVarArg());
304     case Type::StructTyID:
305       // Note that this is only reached for anonymous structs.
306       return *Entry = StructType::get(Ty->getContext(), ElementTypes,
307                                       cast<StructType>(Ty)->isPacked());
308     }
309   }
310
311   // Otherwise, this is an unmapped named struct.  If the struct can be directly
312   // mapped over, just use it as-is.  This happens in a case when the linked-in
313   // module has something like:
314   //   %T = type {%T*, i32}
315   //   @GV = global %T* null
316   // where T does not exist at all in the destination module.
317   //
318   // The other case we watch for is when the type is not in the destination
319   // module, but that it has to be rebuilt because it refers to something that
320   // is already mapped.  For example, if the destination module has:
321   //  %A = type { i32 }
322   // and the source module has something like
323   //  %A' = type { i32 }
324   //  %B = type { %A'* }
325   //  @GV = global %B* null
326   // then we want to create a new type: "%B = type { %A*}" and have it take the
327   // pristine "%B" name from the source module.
328   //
329   // To determine which case this is, we have to recursively walk the type graph
330   // speculating that we'll be able to reuse it unmodified.  Only if this is
331   // safe would we map the entire thing over.  Because this is an optimization,
332   // and is not required for the prettiness of the linked module, we just skip
333   // it and always rebuild a type here.
334   StructType *STy = cast<StructType>(Ty);
335
336   // If the type is opaque, we can just use it directly.
337   if (STy->isOpaque()) {
338     // A named structure type from src module is used. Add it to the Set of
339     // identified structs in the destination module.
340     DstStructTypesSet.insert(STy);
341     return *Entry = STy;
342   }
343
344   // Otherwise we create a new type and resolve its body later.  This will be
345   // resolved by the top level of get().
346   SrcDefinitionsToResolve.push_back(STy);
347   StructType *DTy = StructType::create(STy->getContext());
348   // A new identified structure type was created. Add it to the set of
349   // identified structs in the destination module.
350   DstStructTypesSet.insert(DTy);
351   DstResolvedOpaqueTypes.insert(DTy);
352   return *Entry = DTy;
353 }
354
355 //===----------------------------------------------------------------------===//
356 // ModuleLinker implementation.
357 //===----------------------------------------------------------------------===//
358
359 namespace {
360   class ModuleLinker;
361
362   /// ValueMaterializerTy - Creates prototypes for functions that are lazily
363   /// linked on the fly. This speeds up linking for modules with many
364   /// lazily linked functions of which few get used.
365   class ValueMaterializerTy : public ValueMaterializer {
366     TypeMapTy &TypeMap;
367     Module *DstM;
368     std::vector<Function*> &LazilyLinkFunctions;
369   public:
370     ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
371                         std::vector<Function*> &LazilyLinkFunctions) :
372       ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
373       LazilyLinkFunctions(LazilyLinkFunctions) {
374     }
375
376     Value *materializeValueFor(Value *V) override;
377   };
378
379   /// ModuleLinker - This is an implementation class for the LinkModules
380   /// function, which is the entrypoint for this file.
381   class ModuleLinker {
382     Module *DstM, *SrcM;
383
384     TypeMapTy TypeMap;
385     ValueMaterializerTy ValMaterializer;
386
387     /// ValueMap - Mapping of values from what they used to be in Src, to what
388     /// they are now in DstM.  ValueToValueMapTy is a ValueMap, which involves
389     /// some overhead due to the use of Value handles which the Linker doesn't
390     /// actually need, but this allows us to reuse the ValueMapper code.
391     ValueToValueMapTy ValueMap;
392
393     struct AppendingVarInfo {
394       GlobalVariable *NewGV;  // New aggregate global in dest module.
395       Constant *DstInit;      // Old initializer from dest module.
396       Constant *SrcInit;      // Old initializer from src module.
397     };
398
399     std::vector<AppendingVarInfo> AppendingVars;
400
401     unsigned Mode; // Mode to treat source module.
402
403     // Set of items not to link in from source.
404     SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
405
406     // Vector of functions to lazily link in.
407     std::vector<Function*> LazilyLinkFunctions;
408
409     bool SuppressWarnings;
410
411   public:
412     std::string ErrorMsg;
413
414     ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, unsigned mode,
415                  bool SuppressWarnings=false)
416         : DstM(dstM), SrcM(srcM), TypeMap(Set),
417           ValMaterializer(TypeMap, DstM, LazilyLinkFunctions), Mode(mode),
418           SuppressWarnings(SuppressWarnings) {}
419
420     bool run();
421
422   private:
423     bool shouldLinkFromSource(const GlobalValue &Dest, const GlobalValue &Src);
424
425     /// emitError - Helper method for setting a message and returning an error
426     /// code.
427     bool emitError(const Twine &Message) {
428       ErrorMsg = Message.str();
429       return true;
430     }
431
432     bool getComdatLeader(Module *M, StringRef ComdatName,
433                          const GlobalVariable *&GVar);
434     bool computeResultingSelectionKind(StringRef ComdatName,
435                                        Comdat::SelectionKind Src,
436                                        Comdat::SelectionKind Dst,
437                                        Comdat::SelectionKind &Result,
438                                        bool &LinkFromSrc);
439     std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
440         ComdatsChosen;
441     bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
442                          bool &LinkFromSrc);
443
444     /// getLinkageResult - This analyzes the two global values and determines
445     /// what the result will look like in the destination module.
446     bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
447                           GlobalValue::LinkageTypes &LT,
448                           GlobalValue::VisibilityTypes &Vis,
449                           bool &LinkFromSrc);
450
451     /// getLinkedToGlobal - Given a global in the source module, return the
452     /// global in the destination module that is being linked to, if any.
453     GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
454       // If the source has no name it can't link.  If it has local linkage,
455       // there is no name match-up going on.
456       if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
457         return nullptr;
458
459       // Otherwise see if we have a match in the destination module's symtab.
460       GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
461       if (!DGV) return nullptr;
462
463       // If we found a global with the same name in the dest module, but it has
464       // internal linkage, we are really not doing any linkage here.
465       if (DGV->hasLocalLinkage())
466         return nullptr;
467
468       // Otherwise, we do in fact link to the destination global.
469       return DGV;
470     }
471
472     void computeTypeMapping();
473
474     void upgradeMismatchedGlobalArray(StringRef Name);
475     void upgradeMismatchedGlobals();
476
477     bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
478     bool linkGlobalProto(GlobalVariable *SrcGV);
479     bool linkFunctionProto(Function *SrcF);
480     bool linkAliasProto(GlobalAlias *SrcA);
481     bool linkModuleFlagsMetadata();
482
483     void linkAppendingVarInit(const AppendingVarInfo &AVI);
484     void linkGlobalInits();
485     void linkFunctionBody(Function *Dst, Function *Src);
486     void linkAliasBodies();
487     void linkNamedMDNodes();
488   };
489 }
490
491 /// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
492 /// in the symbol table.  This is good for all clients except for us.  Go
493 /// through the trouble to force this back.
494 static void forceRenaming(GlobalValue *GV, StringRef Name) {
495   // If the global doesn't force its name or if it already has the right name,
496   // there is nothing for us to do.
497   if (GV->hasLocalLinkage() || GV->getName() == Name)
498     return;
499
500   Module *M = GV->getParent();
501
502   // If there is a conflict, rename the conflict.
503   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
504     GV->takeName(ConflictGV);
505     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
506     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
507   } else {
508     GV->setName(Name);              // Force the name back
509   }
510 }
511
512 /// copyGVAttributes - copy additional attributes (those not needed to construct
513 /// a GlobalValue) from the SrcGV to the DestGV.
514 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
515   // Use the maximum alignment, rather than just copying the alignment of SrcGV.
516   auto *DestGO = dyn_cast<GlobalObject>(DestGV);
517   unsigned Alignment;
518   if (DestGO)
519     Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
520
521   DestGV->copyAttributesFrom(SrcGV);
522
523   if (DestGO)
524     DestGO->setAlignment(Alignment);
525
526   forceRenaming(DestGV, SrcGV->getName());
527 }
528
529 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
530                                GlobalValue::VisibilityTypes b) {
531   if (a == GlobalValue::HiddenVisibility)
532     return false;
533   if (b == GlobalValue::HiddenVisibility)
534     return true;
535   if (a == GlobalValue::ProtectedVisibility)
536     return false;
537   if (b == GlobalValue::ProtectedVisibility)
538     return true;
539   return false;
540 }
541
542 Value *ValueMaterializerTy::materializeValueFor(Value *V) {
543   Function *SF = dyn_cast<Function>(V);
544   if (!SF)
545     return nullptr;
546
547   Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
548                                   SF->getLinkage(), SF->getName(), DstM);
549   copyGVAttributes(DF, SF);
550
551   if (Comdat *SC = SF->getComdat()) {
552     Comdat *DC = DstM->getOrInsertComdat(SC->getName());
553     DF->setComdat(DC);
554   }
555
556   LazilyLinkFunctions.push_back(SF);
557   return DF;
558 }
559
560 bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
561                                    const GlobalVariable *&GVar) {
562   const GlobalValue *GVal = M->getNamedValue(ComdatName);
563   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
564     GVal = GA->getBaseObject();
565     if (!GVal)
566       // We cannot resolve the size of the aliasee yet.
567       return emitError("Linking COMDATs named '" + ComdatName +
568                        "': COMDAT key involves incomputable alias size.");
569   }
570
571   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
572   if (!GVar)
573     return emitError(
574         "Linking COMDATs named '" + ComdatName +
575         "': GlobalVariable required for data dependent selection!");
576
577   return false;
578 }
579
580 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
581                                                  Comdat::SelectionKind Src,
582                                                  Comdat::SelectionKind Dst,
583                                                  Comdat::SelectionKind &Result,
584                                                  bool &LinkFromSrc) {
585   // The ability to mix Comdat::SelectionKind::Any with
586   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
587   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
588                          Dst == Comdat::SelectionKind::Largest;
589   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
590                          Src == Comdat::SelectionKind::Largest;
591   if (DstAnyOrLargest && SrcAnyOrLargest) {
592     if (Dst == Comdat::SelectionKind::Largest ||
593         Src == Comdat::SelectionKind::Largest)
594       Result = Comdat::SelectionKind::Largest;
595     else
596       Result = Comdat::SelectionKind::Any;
597   } else if (Src == Dst) {
598     Result = Dst;
599   } else {
600     return emitError("Linking COMDATs named '" + ComdatName +
601                      "': invalid selection kinds!");
602   }
603
604   switch (Result) {
605   case Comdat::SelectionKind::Any:
606     // Go with Dst.
607     LinkFromSrc = false;
608     break;
609   case Comdat::SelectionKind::NoDuplicates:
610     return emitError("Linking COMDATs named '" + ComdatName +
611                      "': noduplicates has been violated!");
612   case Comdat::SelectionKind::ExactMatch:
613   case Comdat::SelectionKind::Largest:
614   case Comdat::SelectionKind::SameSize: {
615     const GlobalVariable *DstGV;
616     const GlobalVariable *SrcGV;
617     if (getComdatLeader(DstM, ComdatName, DstGV) ||
618         getComdatLeader(SrcM, ComdatName, SrcGV))
619       return true;
620
621     const DataLayout *DstDL = DstM->getDataLayout();
622     const DataLayout *SrcDL = SrcM->getDataLayout();
623     if (!DstDL || !SrcDL) {
624       return emitError(
625           "Linking COMDATs named '" + ComdatName +
626           "': can't do size dependent selection without DataLayout!");
627     }
628     uint64_t DstSize =
629         DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
630     uint64_t SrcSize =
631         SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
632     if (Result == Comdat::SelectionKind::ExactMatch) {
633       if (SrcGV->getInitializer() != DstGV->getInitializer())
634         return emitError("Linking COMDATs named '" + ComdatName +
635                          "': ExactMatch violated!");
636       LinkFromSrc = false;
637     } else if (Result == Comdat::SelectionKind::Largest) {
638       LinkFromSrc = SrcSize > DstSize;
639     } else if (Result == Comdat::SelectionKind::SameSize) {
640       if (SrcSize != DstSize)
641         return emitError("Linking COMDATs named '" + ComdatName +
642                          "': SameSize violated!");
643       LinkFromSrc = false;
644     } else {
645       llvm_unreachable("unknown selection kind");
646     }
647     break;
648   }
649   }
650
651   return false;
652 }
653
654 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
655                                    Comdat::SelectionKind &Result,
656                                    bool &LinkFromSrc) {
657   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
658   StringRef ComdatName = SrcC->getName();
659   Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
660   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
661
662   if (DstCI == ComdatSymTab.end()) {
663     // Use the comdat if it is only available in one of the modules.
664     LinkFromSrc = true;
665     Result = SSK;
666     return false;
667   }
668
669   const Comdat *DstC = &DstCI->second;
670   Comdat::SelectionKind DSK = DstC->getSelectionKind();
671   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
672                                        LinkFromSrc);
673 }
674
675 // FIXME: Duplicated from the gold plugin. This should be refactored somewhere.
676 static bool isDeclaration(const GlobalValue &V) {
677   if (V.hasAvailableExternallyLinkage())
678     return true;
679
680   if (V.isMaterializable())
681     return false;
682
683   return V.isDeclaration();
684 }
685
686 bool ModuleLinker::shouldLinkFromSource(const GlobalValue &Dest,
687                                         const GlobalValue &Src) {
688   bool SrcIsDeclaration = isDeclaration(Src);
689   bool DestIsDeclaration = isDeclaration(Dest);
690
691   // FIXME: Make datalayout mandatory and just use getDataLayout().
692   DataLayout DL(Dest.getParent());
693
694   if (SrcIsDeclaration) {
695     // If Src is external or if both Src & Dest are external..  Just link the
696     // external globals, we aren't adding anything.
697     if (Src.hasDLLImportStorageClass())
698       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
699       return DestIsDeclaration;
700     // If the Dest is weak, use the source linkage.
701     return Dest.hasExternalWeakLinkage();
702   }
703
704   if (DestIsDeclaration)
705     // If Dest is external but Src is not:
706     return true;
707
708   if (Src.hasCommonLinkage()) {
709     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage())
710       return true;
711
712     if (!Dest.hasCommonLinkage())
713       return false;
714
715     uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
716     uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
717     return SrcSize > DestSize;
718   }
719
720   if (Src.isWeakForLinker()) {
721     assert(!Dest.hasExternalWeakLinkage());
722     assert(!Dest.hasAvailableExternallyLinkage());
723
724     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage())
725       return true;
726
727     return false;
728   }
729
730   if (Dest.isWeakForLinker()) {
731     assert(Src.hasExternalLinkage());
732     return true;
733   }
734
735   assert(!Src.hasExternalWeakLinkage());
736   assert(!Dest.hasExternalWeakLinkage());
737   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
738          "Unexpected linkage type!");
739   return emitError("Linking globals named '" + Src.getName() +
740                    "': symbol multiply defined!");
741 }
742
743 /// This analyzes the two global values and determines what the result will look
744 /// like in the destination module. In particular, it computes the resultant
745 /// linkage type and visibility, computes whether the global in the source
746 /// should be copied over to the destination (replacing the existing one), and
747 /// computes whether this linkage is an error or not.
748 bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
749                                     GlobalValue::LinkageTypes &LT,
750                                     GlobalValue::VisibilityTypes &Vis,
751                                     bool &LinkFromSrc) {
752   assert(Dest && "Must have two globals being queried");
753   assert(!Src->hasLocalLinkage() &&
754          "If Src has internal linkage, Dest shouldn't be set!");
755
756   assert(ErrorMsg.empty());
757   LinkFromSrc = shouldLinkFromSource(*Dest, *Src);
758   if (!ErrorMsg.empty())
759     return true;
760
761   if (LinkFromSrc)
762     LT = Src->getLinkage();
763   else
764     LT = Dest->getLinkage();
765
766   // Compute the visibility. We follow the rules in the System V Application
767   // Binary Interface.
768   assert(!GlobalValue::isLocalLinkage(LT) &&
769          "Symbols with local linkage should not be merged");
770   Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
771     Dest->getVisibility() : Src->getVisibility();
772   return false;
773 }
774
775 /// computeTypeMapping - Loop over all of the linked values to compute type
776 /// mappings.  For example, if we link "extern Foo *x" and "Foo *x = NULL", then
777 /// we have two struct types 'Foo' but one got renamed when the module was
778 /// loaded into the same LLVMContext.
779 void ModuleLinker::computeTypeMapping() {
780   // Incorporate globals.
781   for (Module::global_iterator I = SrcM->global_begin(),
782        E = SrcM->global_end(); I != E; ++I) {
783     GlobalValue *DGV = getLinkedToGlobal(I);
784     if (!DGV) continue;
785
786     if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
787       TypeMap.addTypeMapping(DGV->getType(), I->getType());
788       continue;
789     }
790
791     // Unify the element type of appending arrays.
792     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
793     ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
794     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
795   }
796
797   // Incorporate functions.
798   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
799     if (GlobalValue *DGV = getLinkedToGlobal(I))
800       TypeMap.addTypeMapping(DGV->getType(), I->getType());
801   }
802
803   // Incorporate types by name, scanning all the types in the source module.
804   // At this point, the destination module may have a type "%foo = { i32 }" for
805   // example.  When the source module got loaded into the same LLVMContext, if
806   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
807   TypeFinder SrcStructTypes;
808   SrcStructTypes.run(*SrcM, true);
809   SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
810                                                  SrcStructTypes.end());
811
812   for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
813     StructType *ST = SrcStructTypes[i];
814     if (!ST->hasName()) continue;
815
816     // Check to see if there is a dot in the name followed by a digit.
817     size_t DotPos = ST->getName().rfind('.');
818     if (DotPos == 0 || DotPos == StringRef::npos ||
819         ST->getName().back() == '.' ||
820         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
821       continue;
822
823     // Check to see if the destination module has a struct with the prefix name.
824     if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
825       // Don't use it if this actually came from the source module. They're in
826       // the same LLVMContext after all. Also don't use it unless the type is
827       // actually used in the destination module. This can happen in situations
828       // like this:
829       //
830       //      Module A                         Module B
831       //      --------                         --------
832       //   %Z = type { %A }                %B = type { %C.1 }
833       //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
834       //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
835       //   %C = type { i8* }               %B.3 = type { %C.1 }
836       //
837       // When we link Module B with Module A, the '%B' in Module B is
838       // used. However, that would then use '%C.1'. But when we process '%C.1',
839       // we prefer to take the '%C' version. So we are then left with both
840       // '%C.1' and '%C' being used for the same types. This leads to some
841       // variables using one type and some using the other.
842       if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
843         TypeMap.addTypeMapping(DST, ST);
844   }
845
846   // Don't bother incorporating aliases, they aren't generally typed well.
847
848   // Now that we have discovered all of the type equivalences, get a body for
849   // any 'opaque' types in the dest module that are now resolved.
850   TypeMap.linkDefinedTypeBodies();
851 }
852
853 static void upgradeGlobalArray(GlobalVariable *GV) {
854   ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
855   StructType *OldTy = cast<StructType>(ATy->getElementType());
856   assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
857
858   // Get the upgraded 3 element type.
859   PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
860   Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
861                   VoidPtrTy};
862   StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
863
864   // Build new constants with a null third field filled in.
865   Constant *OldInitC = GV->getInitializer();
866   ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
867   if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
868     // Invalid initializer; give up.
869     return;
870   std::vector<Constant *> Initializers;
871   if (OldInit && OldInit->getNumOperands()) {
872     Value *Null = Constant::getNullValue(VoidPtrTy);
873     for (Use &U : OldInit->operands()) {
874       ConstantStruct *Init = cast<ConstantStruct>(U.get());
875       Initializers.push_back(ConstantStruct::get(
876           NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
877     }
878   }
879   assert(Initializers.size() == ATy->getNumElements() &&
880          "Failed to copy all array elements");
881
882   // Replace the old GV with a new one.
883   ATy = ArrayType::get(NewTy, Initializers.size());
884   Constant *NewInit = ConstantArray::get(ATy, Initializers);
885   GlobalVariable *NewGV = new GlobalVariable(
886       *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
887       GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
888       GV->isExternallyInitialized());
889   NewGV->copyAttributesFrom(GV);
890   NewGV->takeName(GV);
891   assert(GV->use_empty() && "program cannot use initializer list");
892   GV->eraseFromParent();
893 }
894
895 void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
896   // Look for the global arrays.
897   auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
898   if (!DstGV)
899     return;
900   auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
901   if (!SrcGV)
902     return;
903
904   // Check if the types already match.
905   auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
906   auto *SrcTy =
907       cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
908   if (DstTy == SrcTy)
909     return;
910
911   // Grab the element types.  We can only upgrade an array of a two-field
912   // struct.  Only bother if the other one has three-fields.
913   auto *DstEltTy = cast<StructType>(DstTy->getElementType());
914   auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
915   if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
916     upgradeGlobalArray(DstGV);
917     return;
918   }
919   if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
920     upgradeGlobalArray(SrcGV);
921
922   // We can't upgrade any other differences.
923 }
924
925 void ModuleLinker::upgradeMismatchedGlobals() {
926   upgradeMismatchedGlobalArray("llvm.global_ctors");
927   upgradeMismatchedGlobalArray("llvm.global_dtors");
928 }
929
930 /// linkAppendingVarProto - If there were any appending global variables, link
931 /// them together now.  Return true on error.
932 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
933                                          GlobalVariable *SrcGV) {
934
935   if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
936     return emitError("Linking globals named '" + SrcGV->getName() +
937            "': can only link appending global with another appending global!");
938
939   ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
940   ArrayType *SrcTy =
941     cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
942   Type *EltTy = DstTy->getElementType();
943
944   // Check to see that they two arrays agree on type.
945   if (EltTy != SrcTy->getElementType())
946     return emitError("Appending variables with different element types!");
947   if (DstGV->isConstant() != SrcGV->isConstant())
948     return emitError("Appending variables linked with different const'ness!");
949
950   if (DstGV->getAlignment() != SrcGV->getAlignment())
951     return emitError(
952              "Appending variables with different alignment need to be linked!");
953
954   if (DstGV->getVisibility() != SrcGV->getVisibility())
955     return emitError(
956             "Appending variables with different visibility need to be linked!");
957
958   if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
959     return emitError(
960         "Appending variables with different unnamed_addr need to be linked!");
961
962   if (StringRef(DstGV->getSection()) != SrcGV->getSection())
963     return emitError(
964           "Appending variables with different section name need to be linked!");
965
966   uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
967   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
968
969   // Create the new global variable.
970   GlobalVariable *NG =
971     new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
972                        DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
973                        DstGV->getThreadLocalMode(),
974                        DstGV->getType()->getAddressSpace());
975
976   // Propagate alignment, visibility and section info.
977   copyGVAttributes(NG, DstGV);
978
979   AppendingVarInfo AVI;
980   AVI.NewGV = NG;
981   AVI.DstInit = DstGV->getInitializer();
982   AVI.SrcInit = SrcGV->getInitializer();
983   AppendingVars.push_back(AVI);
984
985   // Replace any uses of the two global variables with uses of the new
986   // global.
987   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
988
989   DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
990   DstGV->eraseFromParent();
991
992   // Track the source variable so we don't try to link it.
993   DoNotLinkFromSource.insert(SrcGV);
994
995   return false;
996 }
997
998 /// linkGlobalProto - Loop through the global variables in the src module and
999 /// merge them into the dest module.
1000 bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
1001   GlobalValue *DGV = getLinkedToGlobal(SGV);
1002   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
1003   bool HasUnnamedAddr = SGV->hasUnnamedAddr();
1004   unsigned Alignment = SGV->getAlignment();
1005
1006   bool LinkFromSrc = false;
1007   Comdat *DC = nullptr;
1008   if (const Comdat *SC = SGV->getComdat()) {
1009     Comdat::SelectionKind SK;
1010     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1011     DC = DstM->getOrInsertComdat(SC->getName());
1012     DC->setSelectionKind(SK);
1013   }
1014
1015   if (DGV) {
1016     if (!DC) {
1017       // Concatenation of appending linkage variables is magic and handled later.
1018       if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
1019         return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
1020
1021       // Determine whether linkage of these two globals follows the source
1022       // module's definition or the destination module's definition.
1023       GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1024       GlobalValue::VisibilityTypes NV;
1025       if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
1026         return true;
1027       NewVisibility = NV;
1028       HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1029       if (DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1030         Alignment = std::max(Alignment, DGV->getAlignment());
1031       else if (!LinkFromSrc)
1032         Alignment = DGV->getAlignment();
1033
1034       // If we're not linking from the source, then keep the definition that we
1035       // have.
1036       if (!LinkFromSrc) {
1037         // Special case for const propagation.
1038         if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
1039           DGVar->setAlignment(Alignment);
1040
1041           if (DGVar->isDeclaration() && SGV->isConstant() &&
1042               !DGVar->isConstant())
1043             DGVar->setConstant(true);
1044         }
1045
1046         // Set calculated linkage, visibility and unnamed_addr.
1047         DGV->setLinkage(NewLinkage);
1048         DGV->setVisibility(*NewVisibility);
1049         DGV->setUnnamedAddr(HasUnnamedAddr);
1050       }
1051     }
1052
1053     if (!LinkFromSrc) {
1054       // Make sure to remember this mapping.
1055       ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
1056
1057       // Track the source global so that we don't attempt to copy it over when
1058       // processing global initializers.
1059       DoNotLinkFromSource.insert(SGV);
1060
1061       return false;
1062     }
1063   }
1064
1065   // If the Comdat this variable was inside of wasn't selected, skip it.
1066   if (DC && !DGV && !LinkFromSrc) {
1067     DoNotLinkFromSource.insert(SGV);
1068     return false;
1069   }
1070
1071   // No linking to be performed or linking from the source: simply create an
1072   // identical version of the symbol over in the dest module... the
1073   // initializer will be filled in later by LinkGlobalInits.
1074   GlobalVariable *NewDGV =
1075     new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
1076                        SGV->isConstant(), SGV->getLinkage(), /*init*/nullptr,
1077                        SGV->getName(), /*insertbefore*/nullptr,
1078                        SGV->getThreadLocalMode(),
1079                        SGV->getType()->getAddressSpace());
1080   // Propagate alignment, visibility and section info.
1081   copyGVAttributes(NewDGV, SGV);
1082   NewDGV->setAlignment(Alignment);
1083   if (NewVisibility)
1084     NewDGV->setVisibility(*NewVisibility);
1085   NewDGV->setUnnamedAddr(HasUnnamedAddr);
1086
1087   if (DC)
1088     NewDGV->setComdat(DC);
1089
1090   if (DGV) {
1091     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
1092     DGV->eraseFromParent();
1093   }
1094
1095   // Make sure to remember this mapping.
1096   ValueMap[SGV] = NewDGV;
1097   return false;
1098 }
1099
1100 /// linkFunctionProto - Link the function in the source module into the
1101 /// destination module if needed, setting up mapping information.
1102 bool ModuleLinker::linkFunctionProto(Function *SF) {
1103   GlobalValue *DGV = getLinkedToGlobal(SF);
1104   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
1105   bool HasUnnamedAddr = SF->hasUnnamedAddr();
1106
1107   bool LinkFromSrc = false;
1108   Comdat *DC = nullptr;
1109   if (const Comdat *SC = SF->getComdat()) {
1110     Comdat::SelectionKind SK;
1111     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1112     DC = DstM->getOrInsertComdat(SC->getName());
1113     DC->setSelectionKind(SK);
1114   }
1115
1116   if (DGV) {
1117     if (!DC) {
1118       GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1119       GlobalValue::VisibilityTypes NV;
1120       if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
1121         return true;
1122       NewVisibility = NV;
1123       HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1124
1125       if (!LinkFromSrc) {
1126         // Set calculated linkage
1127         DGV->setLinkage(NewLinkage);
1128         DGV->setVisibility(*NewVisibility);
1129         DGV->setUnnamedAddr(HasUnnamedAddr);
1130       }
1131     }
1132
1133     if (!LinkFromSrc) {
1134       // Make sure to remember this mapping.
1135       ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
1136
1137       // Track the function from the source module so we don't attempt to remap
1138       // it.
1139       DoNotLinkFromSource.insert(SF);
1140
1141       return false;
1142     }
1143   }
1144
1145   // If the function is to be lazily linked, don't create it just yet.
1146   // The ValueMaterializerTy will deal with creating it if it's used.
1147   if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1148                SF->hasAvailableExternallyLinkage())) {
1149     DoNotLinkFromSource.insert(SF);
1150     return false;
1151   }
1152
1153   // If the Comdat this function was inside of wasn't selected, skip it.
1154   if (DC && !DGV && !LinkFromSrc) {
1155     DoNotLinkFromSource.insert(SF);
1156     return false;
1157   }
1158
1159   // If there is no linkage to be performed or we are linking from the source,
1160   // bring SF over.
1161   Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
1162                                      SF->getLinkage(), SF->getName(), DstM);
1163   copyGVAttributes(NewDF, SF);
1164   if (NewVisibility)
1165     NewDF->setVisibility(*NewVisibility);
1166   NewDF->setUnnamedAddr(HasUnnamedAddr);
1167
1168   if (DC)
1169     NewDF->setComdat(DC);
1170
1171   if (DGV) {
1172     // Any uses of DF need to change to NewDF, with cast.
1173     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
1174     DGV->eraseFromParent();
1175   }
1176
1177   ValueMap[SF] = NewDF;
1178   return false;
1179 }
1180
1181 /// LinkAliasProto - Set up prototypes for any aliases that come over from the
1182 /// source module.
1183 bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
1184   GlobalValue *DGV = getLinkedToGlobal(SGA);
1185   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
1186   bool HasUnnamedAddr = SGA->hasUnnamedAddr();
1187
1188   bool LinkFromSrc = false;
1189   Comdat *DC = nullptr;
1190   if (const Comdat *SC = SGA->getComdat()) {
1191     Comdat::SelectionKind SK;
1192     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1193     DC = DstM->getOrInsertComdat(SC->getName());
1194     DC->setSelectionKind(SK);
1195   }
1196
1197   if (DGV) {
1198     if (!DC) {
1199       GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1200       GlobalValue::VisibilityTypes NV;
1201       if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
1202         return true;
1203       NewVisibility = NV;
1204       HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1205
1206       if (!LinkFromSrc) {
1207         // Set calculated linkage.
1208         DGV->setLinkage(NewLinkage);
1209         DGV->setVisibility(*NewVisibility);
1210         DGV->setUnnamedAddr(HasUnnamedAddr);
1211       }
1212     }
1213
1214     if (!LinkFromSrc) {
1215       // Make sure to remember this mapping.
1216       ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
1217
1218       // Track the alias from the source module so we don't attempt to remap it.
1219       DoNotLinkFromSource.insert(SGA);
1220
1221       return false;
1222     }
1223   }
1224
1225   // If the Comdat this alias was inside of wasn't selected, skip it.
1226   if (DC && !DGV && !LinkFromSrc) {
1227     DoNotLinkFromSource.insert(SGA);
1228     return false;
1229   }
1230
1231   // If there is no linkage to be performed or we're linking from the source,
1232   // bring over SGA.
1233   auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
1234   auto *NewDA =
1235       GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1236                           SGA->getLinkage(), SGA->getName(), DstM);
1237   copyGVAttributes(NewDA, SGA);
1238   if (NewVisibility)
1239     NewDA->setVisibility(*NewVisibility);
1240   NewDA->setUnnamedAddr(HasUnnamedAddr);
1241
1242   if (DGV) {
1243     // Any uses of DGV need to change to NewDA, with cast.
1244     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
1245     DGV->eraseFromParent();
1246   }
1247
1248   ValueMap[SGA] = NewDA;
1249   return false;
1250 }
1251
1252 static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
1253   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1254
1255   for (unsigned i = 0; i != NumElements; ++i)
1256     Dest.push_back(C->getAggregateElement(i));
1257 }
1258
1259 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1260   // Merge the initializer.
1261   SmallVector<Constant *, 16> DstElements;
1262   getArrayElements(AVI.DstInit, DstElements);
1263
1264   SmallVector<Constant *, 16> SrcElements;
1265   getArrayElements(AVI.SrcInit, SrcElements);
1266
1267   ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1268
1269   StringRef Name = AVI.NewGV->getName();
1270   bool IsNewStructor =
1271       (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1272       cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1273
1274   for (auto *V : SrcElements) {
1275     if (IsNewStructor) {
1276       Constant *Key = V->getAggregateElement(2);
1277       if (DoNotLinkFromSource.count(Key))
1278         continue;
1279     }
1280     DstElements.push_back(
1281         MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1282   }
1283   if (IsNewStructor) {
1284     NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1285     AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1286   }
1287
1288   AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1289 }
1290
1291 /// linkGlobalInits - Update the initializers in the Dest module now that all
1292 /// globals that may be referenced are in Dest.
1293 void ModuleLinker::linkGlobalInits() {
1294   // Loop over all of the globals in the src module, mapping them over as we go
1295   for (Module::const_global_iterator I = SrcM->global_begin(),
1296        E = SrcM->global_end(); I != E; ++I) {
1297
1298     // Only process initialized GV's or ones not already in dest.
1299     if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1300
1301     // Grab destination global variable.
1302     GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1303     // Figure out what the initializer looks like in the dest module.
1304     DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
1305                                  RF_None, &TypeMap, &ValMaterializer));
1306   }
1307 }
1308
1309 /// linkFunctionBody - Copy the source function over into the dest function and
1310 /// fix up references to values.  At this point we know that Dest is an external
1311 /// function, and that Src is not.
1312 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1313   assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
1314
1315   // Go through and convert function arguments over, remembering the mapping.
1316   Function::arg_iterator DI = Dst->arg_begin();
1317   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1318        I != E; ++I, ++DI) {
1319     DI->setName(I->getName());  // Copy the name over.
1320
1321     // Add a mapping to our mapping.
1322     ValueMap[I] = DI;
1323   }
1324
1325   if (Mode == Linker::DestroySource) {
1326     // Splice the body of the source function into the dest function.
1327     Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
1328
1329     // At this point, all of the instructions and values of the function are now
1330     // copied over.  The only problem is that they are still referencing values in
1331     // the Source function as operands.  Loop through all of the operands of the
1332     // functions and patch them up to point to the local versions.
1333     for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1334       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1335         RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries,
1336                          &TypeMap, &ValMaterializer);
1337
1338   } else {
1339     // Clone the body of the function into the dest function.
1340     SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
1341     CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", nullptr,
1342                       &TypeMap, &ValMaterializer);
1343   }
1344
1345   // There is no need to map the arguments anymore.
1346   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1347        I != E; ++I)
1348     ValueMap.erase(I);
1349
1350 }
1351
1352 /// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
1353 void ModuleLinker::linkAliasBodies() {
1354   for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
1355        I != E; ++I) {
1356     if (DoNotLinkFromSource.count(I))
1357       continue;
1358     if (Constant *Aliasee = I->getAliasee()) {
1359       GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
1360       Constant *Val =
1361           MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1362       DA->setAliasee(Val);
1363     }
1364   }
1365 }
1366
1367 /// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
1368 /// module.
1369 void ModuleLinker::linkNamedMDNodes() {
1370   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1371   for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1372        E = SrcM->named_metadata_end(); I != E; ++I) {
1373     // Don't link module flags here. Do them separately.
1374     if (&*I == SrcModFlags) continue;
1375     NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1376     // Add Src elements into Dest node.
1377     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1378       DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
1379                                    RF_None, &TypeMap, &ValMaterializer));
1380   }
1381 }
1382
1383 /// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1384 /// module.
1385 bool ModuleLinker::linkModuleFlagsMetadata() {
1386   // If the source module has no module flags, we are done.
1387   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1388   if (!SrcModFlags) return false;
1389
1390   // If the destination module doesn't have module flags yet, then just copy
1391   // over the source module's flags.
1392   NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1393   if (DstModFlags->getNumOperands() == 0) {
1394     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1395       DstModFlags->addOperand(SrcModFlags->getOperand(I));
1396
1397     return false;
1398   }
1399
1400   // First build a map of the existing module flags and requirements.
1401   DenseMap<MDString*, MDNode*> Flags;
1402   SmallSetVector<MDNode*, 16> Requirements;
1403   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1404     MDNode *Op = DstModFlags->getOperand(I);
1405     ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1406     MDString *ID = cast<MDString>(Op->getOperand(1));
1407
1408     if (Behavior->getZExtValue() == Module::Require) {
1409       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1410     } else {
1411       Flags[ID] = Op;
1412     }
1413   }
1414
1415   // Merge in the flags from the source module, and also collect its set of
1416   // requirements.
1417   bool HasErr = false;
1418   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1419     MDNode *SrcOp = SrcModFlags->getOperand(I);
1420     ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1421     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1422     MDNode *DstOp = Flags.lookup(ID);
1423     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1424
1425     // If this is a requirement, add it and continue.
1426     if (SrcBehaviorValue == Module::Require) {
1427       // If the destination module does not already have this requirement, add
1428       // it.
1429       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1430         DstModFlags->addOperand(SrcOp);
1431       }
1432       continue;
1433     }
1434
1435     // If there is no existing flag with this ID, just add it.
1436     if (!DstOp) {
1437       Flags[ID] = SrcOp;
1438       DstModFlags->addOperand(SrcOp);
1439       continue;
1440     }
1441
1442     // Otherwise, perform a merge.
1443     ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1444     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1445
1446     // If either flag has override behavior, handle it first.
1447     if (DstBehaviorValue == Module::Override) {
1448       // Diagnose inconsistent flags which both have override behavior.
1449       if (SrcBehaviorValue == Module::Override &&
1450           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1451         HasErr |= emitError("linking module flags '" + ID->getString() +
1452                             "': IDs have conflicting override values");
1453       }
1454       continue;
1455     } else if (SrcBehaviorValue == Module::Override) {
1456       // Update the destination flag to that of the source.
1457       DstOp->replaceOperandWith(0, SrcBehavior);
1458       DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1459       continue;
1460     }
1461
1462     // Diagnose inconsistent merge behavior types.
1463     if (SrcBehaviorValue != DstBehaviorValue) {
1464       HasErr |= emitError("linking module flags '" + ID->getString() +
1465                           "': IDs have conflicting behaviors");
1466       continue;
1467     }
1468
1469     // Perform the merge for standard behavior types.
1470     switch (SrcBehaviorValue) {
1471     case Module::Require:
1472     case Module::Override: llvm_unreachable("not possible");
1473     case Module::Error: {
1474       // Emit an error if the values differ.
1475       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1476         HasErr |= emitError("linking module flags '" + ID->getString() +
1477                             "': IDs have conflicting values");
1478       }
1479       continue;
1480     }
1481     case Module::Warning: {
1482       // Emit a warning if the values differ.
1483       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1484         if (!SuppressWarnings) {
1485           errs() << "WARNING: linking module flags '" << ID->getString()
1486                  << "': IDs have conflicting values";
1487         }
1488       }
1489       continue;
1490     }
1491     case Module::Append: {
1492       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1493       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1494       unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1495       Value **VP, **Values = VP = new Value*[NumOps];
1496       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1497         *VP = DstValue->getOperand(i);
1498       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1499         *VP = SrcValue->getOperand(i);
1500       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1501                                                ArrayRef<Value*>(Values,
1502                                                                 NumOps)));
1503       delete[] Values;
1504       break;
1505     }
1506     case Module::AppendUnique: {
1507       SmallSetVector<Value*, 16> Elts;
1508       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1509       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1510       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1511         Elts.insert(DstValue->getOperand(i));
1512       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1513         Elts.insert(SrcValue->getOperand(i));
1514       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1515                                                ArrayRef<Value*>(Elts.begin(),
1516                                                                 Elts.end())));
1517       break;
1518     }
1519     }
1520   }
1521
1522   // Check all of the requirements.
1523   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1524     MDNode *Requirement = Requirements[I];
1525     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1526     Value *ReqValue = Requirement->getOperand(1);
1527
1528     MDNode *Op = Flags[Flag];
1529     if (!Op || Op->getOperand(2) != ReqValue) {
1530       HasErr |= emitError("linking module flags '" + Flag->getString() +
1531                           "': does not have the required value");
1532       continue;
1533     }
1534   }
1535
1536   return HasErr;
1537 }
1538
1539 bool ModuleLinker::run() {
1540   assert(DstM && "Null destination module");
1541   assert(SrcM && "Null source module");
1542
1543   // Inherit the target data from the source module if the destination module
1544   // doesn't have one already.
1545   if (!DstM->getDataLayout() && SrcM->getDataLayout())
1546     DstM->setDataLayout(SrcM->getDataLayout());
1547
1548   // Copy the target triple from the source to dest if the dest's is empty.
1549   if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1550     DstM->setTargetTriple(SrcM->getTargetTriple());
1551
1552   if (SrcM->getDataLayout() && DstM->getDataLayout() &&
1553       *SrcM->getDataLayout() != *DstM->getDataLayout()) {
1554     if (!SuppressWarnings) {
1555       errs() << "WARNING: Linking two modules of different data layouts: '"
1556              << SrcM->getModuleIdentifier() << "' is '"
1557              << SrcM->getDataLayoutStr() << "' whereas '"
1558              << DstM->getModuleIdentifier() << "' is '"
1559              << DstM->getDataLayoutStr() << "'\n";
1560     }
1561   }
1562   if (!SrcM->getTargetTriple().empty() &&
1563       DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1564     if (!SuppressWarnings) {
1565       errs() << "WARNING: Linking two modules of different target triples: "
1566              << SrcM->getModuleIdentifier() << "' is '"
1567              << SrcM->getTargetTriple() << "' whereas '"
1568              << DstM->getModuleIdentifier() << "' is '"
1569              << DstM->getTargetTriple() << "'\n";
1570     }
1571   }
1572
1573   // Append the module inline asm string.
1574   if (!SrcM->getModuleInlineAsm().empty()) {
1575     if (DstM->getModuleInlineAsm().empty())
1576       DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1577     else
1578       DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1579                                SrcM->getModuleInlineAsm());
1580   }
1581
1582   // Loop over all of the linked values to compute type mappings.
1583   computeTypeMapping();
1584
1585   ComdatsChosen.clear();
1586   for (const StringMapEntry<llvm::Comdat> &SMEC : SrcM->getComdatSymbolTable()) {
1587     const Comdat &C = SMEC.getValue();
1588     if (ComdatsChosen.count(&C))
1589       continue;
1590     Comdat::SelectionKind SK;
1591     bool LinkFromSrc;
1592     if (getComdatResult(&C, SK, LinkFromSrc))
1593       return true;
1594     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1595   }
1596
1597   // Upgrade mismatched global arrays.
1598   upgradeMismatchedGlobals();
1599
1600   // Insert all of the globals in src into the DstM module... without linking
1601   // initializers (which could refer to functions not yet mapped over).
1602   for (Module::global_iterator I = SrcM->global_begin(),
1603        E = SrcM->global_end(); I != E; ++I)
1604     if (linkGlobalProto(I))
1605       return true;
1606
1607   // Link the functions together between the two modules, without doing function
1608   // bodies... this just adds external function prototypes to the DstM
1609   // function...  We do this so that when we begin processing function bodies,
1610   // all of the global values that may be referenced are available in our
1611   // ValueMap.
1612   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1613     if (linkFunctionProto(I))
1614       return true;
1615
1616   // If there were any aliases, link them now.
1617   for (Module::alias_iterator I = SrcM->alias_begin(),
1618        E = SrcM->alias_end(); I != E; ++I)
1619     if (linkAliasProto(I))
1620       return true;
1621
1622   for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1623     linkAppendingVarInit(AppendingVars[i]);
1624
1625   // Link in the function bodies that are defined in the source module into
1626   // DstM.
1627   for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1628     // Skip if not linking from source.
1629     if (DoNotLinkFromSource.count(SF)) continue;
1630
1631     Function *DF = cast<Function>(ValueMap[SF]);
1632     if (SF->hasPrefixData()) {
1633       // Link in the prefix data.
1634       DF->setPrefixData(MapValue(
1635           SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1636     }
1637
1638     // Skip if no body (function is external) or materialize.
1639     if (SF->isDeclaration()) {
1640       if (!SF->isMaterializable())
1641         continue;
1642       if (SF->Materialize(&ErrorMsg))
1643         return true;
1644     }
1645
1646     linkFunctionBody(DF, SF);
1647     SF->Dematerialize();
1648   }
1649
1650   // Resolve all uses of aliases with aliasees.
1651   linkAliasBodies();
1652
1653   // Remap all of the named MDNodes in Src into the DstM module. We do this
1654   // after linking GlobalValues so that MDNodes that reference GlobalValues
1655   // are properly remapped.
1656   linkNamedMDNodes();
1657
1658   // Merge the module flags into the DstM module.
1659   if (linkModuleFlagsMetadata())
1660     return true;
1661
1662   // Update the initializers in the DstM module now that all globals that may
1663   // be referenced are in DstM.
1664   linkGlobalInits();
1665
1666   // Process vector of lazily linked in functions.
1667   bool LinkedInAnyFunctions;
1668   do {
1669     LinkedInAnyFunctions = false;
1670
1671     for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1672         E = LazilyLinkFunctions.end(); I != E; ++I) {
1673       Function *SF = *I;
1674       if (!SF)
1675         continue;
1676
1677       Function *DF = cast<Function>(ValueMap[SF]);
1678       if (SF->hasPrefixData()) {
1679         // Link in the prefix data.
1680         DF->setPrefixData(MapValue(SF->getPrefixData(),
1681                                    ValueMap,
1682                                    RF_None,
1683                                    &TypeMap,
1684                                    &ValMaterializer));
1685       }
1686
1687       // Materialize if necessary.
1688       if (SF->isDeclaration()) {
1689         if (!SF->isMaterializable())
1690           continue;
1691         if (SF->Materialize(&ErrorMsg))
1692           return true;
1693       }
1694
1695       // Erase from vector *before* the function body is linked - linkFunctionBody could
1696       // invalidate I.
1697       LazilyLinkFunctions.erase(I);
1698
1699       // Link in function body.
1700       linkFunctionBody(DF, SF);
1701       SF->Dematerialize();
1702
1703       // Set flag to indicate we may have more functions to lazily link in
1704       // since we linked in a function.
1705       LinkedInAnyFunctions = true;
1706       break;
1707     }
1708   } while (LinkedInAnyFunctions);
1709
1710   // Now that all of the types from the source are used, resolve any structs
1711   // copied over to the dest that didn't exist there.
1712   TypeMap.linkDefinedTypeBodies();
1713
1714   return false;
1715 }
1716
1717 Linker::Linker(Module *M, bool SuppressWarnings)
1718     : Composite(M), SuppressWarnings(SuppressWarnings) {
1719   TypeFinder StructTypes;
1720   StructTypes.run(*M, true);
1721   IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1722 }
1723
1724 Linker::~Linker() {
1725 }
1726
1727 void Linker::deleteModule() {
1728   delete Composite;
1729   Composite = nullptr;
1730 }
1731
1732 bool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) {
1733   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode,
1734                          SuppressWarnings);
1735   if (TheLinker.run()) {
1736     if (ErrorMsg)
1737       *ErrorMsg = TheLinker.ErrorMsg;
1738     return true;
1739   }
1740   return false;
1741 }
1742
1743 //===----------------------------------------------------------------------===//
1744 // LinkModules entrypoint.
1745 //===----------------------------------------------------------------------===//
1746
1747 /// LinkModules - This function links two modules together, with the resulting
1748 /// Dest module modified to be the composite of the two input modules.  If an
1749 /// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1750 /// the problem.  Upon failure, the Dest module could be in a modified state,
1751 /// and shouldn't be relied on to be consistent.
1752 bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1753                          std::string *ErrorMsg) {
1754   Linker L(Dest);
1755   return L.linkInModule(Src, Mode, ErrorMsg);
1756 }
1757
1758 //===----------------------------------------------------------------------===//
1759 // C API.
1760 //===----------------------------------------------------------------------===//
1761
1762 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1763                          LLVMLinkerMode Mode, char **OutMessages) {
1764   std::string Messages;
1765   LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
1766                                         Mode, OutMessages? &Messages : nullptr);
1767   if (OutMessages)
1768     *OutMessages = strdup(Messages.c_str());
1769   return Result;
1770 }