Don't ever call materializeAllPermanently during LTO.
[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 bool ModuleLinker::shouldLinkFromSource(const GlobalValue &Dest,
676                                         const GlobalValue &Src) {
677   bool SrcIsDeclaration = Src.isDeclarationForLinker();
678   bool DestIsDeclaration = Dest.isDeclarationForLinker();
679
680   // FIXME: Make datalayout mandatory and just use getDataLayout().
681   DataLayout DL(Dest.getParent());
682
683   if (SrcIsDeclaration) {
684     // If Src is external or if both Src & Dest are external..  Just link the
685     // external globals, we aren't adding anything.
686     if (Src.hasDLLImportStorageClass())
687       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
688       return DestIsDeclaration;
689     // If the Dest is weak, use the source linkage.
690     return Dest.hasExternalWeakLinkage();
691   }
692
693   if (DestIsDeclaration)
694     // If Dest is external but Src is not:
695     return true;
696
697   if (Src.hasCommonLinkage()) {
698     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage())
699       return true;
700
701     if (!Dest.hasCommonLinkage())
702       return false;
703
704     uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
705     uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
706     return SrcSize > DestSize;
707   }
708
709   if (Src.isWeakForLinker()) {
710     assert(!Dest.hasExternalWeakLinkage());
711     assert(!Dest.hasAvailableExternallyLinkage());
712
713     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage())
714       return true;
715
716     return false;
717   }
718
719   if (Dest.isWeakForLinker()) {
720     assert(Src.hasExternalLinkage());
721     return true;
722   }
723
724   assert(!Src.hasExternalWeakLinkage());
725   assert(!Dest.hasExternalWeakLinkage());
726   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
727          "Unexpected linkage type!");
728   return emitError("Linking globals named '" + Src.getName() +
729                    "': symbol multiply defined!");
730 }
731
732 /// This analyzes the two global values and determines what the result will look
733 /// like in the destination module. In particular, it computes the resultant
734 /// linkage type and visibility, computes whether the global in the source
735 /// should be copied over to the destination (replacing the existing one), and
736 /// computes whether this linkage is an error or not.
737 bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
738                                     GlobalValue::LinkageTypes &LT,
739                                     GlobalValue::VisibilityTypes &Vis,
740                                     bool &LinkFromSrc) {
741   assert(Dest && "Must have two globals being queried");
742   assert(!Src->hasLocalLinkage() &&
743          "If Src has internal linkage, Dest shouldn't be set!");
744
745   assert(ErrorMsg.empty());
746   LinkFromSrc = shouldLinkFromSource(*Dest, *Src);
747   if (!ErrorMsg.empty())
748     return true;
749
750   if (LinkFromSrc)
751     LT = Src->getLinkage();
752   else
753     LT = Dest->getLinkage();
754
755   // Compute the visibility. We follow the rules in the System V Application
756   // Binary Interface.
757   assert(!GlobalValue::isLocalLinkage(LT) &&
758          "Symbols with local linkage should not be merged");
759   Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
760     Dest->getVisibility() : Src->getVisibility();
761   return false;
762 }
763
764 /// computeTypeMapping - Loop over all of the linked values to compute type
765 /// mappings.  For example, if we link "extern Foo *x" and "Foo *x = NULL", then
766 /// we have two struct types 'Foo' but one got renamed when the module was
767 /// loaded into the same LLVMContext.
768 void ModuleLinker::computeTypeMapping() {
769   // Incorporate globals.
770   for (Module::global_iterator I = SrcM->global_begin(),
771        E = SrcM->global_end(); I != E; ++I) {
772     GlobalValue *DGV = getLinkedToGlobal(I);
773     if (!DGV) continue;
774
775     if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
776       TypeMap.addTypeMapping(DGV->getType(), I->getType());
777       continue;
778     }
779
780     // Unify the element type of appending arrays.
781     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
782     ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
783     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
784   }
785
786   // Incorporate functions.
787   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
788     if (GlobalValue *DGV = getLinkedToGlobal(I))
789       TypeMap.addTypeMapping(DGV->getType(), I->getType());
790   }
791
792   // Incorporate types by name, scanning all the types in the source module.
793   // At this point, the destination module may have a type "%foo = { i32 }" for
794   // example.  When the source module got loaded into the same LLVMContext, if
795   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
796   TypeFinder SrcStructTypes;
797   SrcStructTypes.run(*SrcM, true);
798   SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
799                                                  SrcStructTypes.end());
800
801   for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
802     StructType *ST = SrcStructTypes[i];
803     if (!ST->hasName()) continue;
804
805     // Check to see if there is a dot in the name followed by a digit.
806     size_t DotPos = ST->getName().rfind('.');
807     if (DotPos == 0 || DotPos == StringRef::npos ||
808         ST->getName().back() == '.' ||
809         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
810       continue;
811
812     // Check to see if the destination module has a struct with the prefix name.
813     if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
814       // Don't use it if this actually came from the source module. They're in
815       // the same LLVMContext after all. Also don't use it unless the type is
816       // actually used in the destination module. This can happen in situations
817       // like this:
818       //
819       //      Module A                         Module B
820       //      --------                         --------
821       //   %Z = type { %A }                %B = type { %C.1 }
822       //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
823       //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
824       //   %C = type { i8* }               %B.3 = type { %C.1 }
825       //
826       // When we link Module B with Module A, the '%B' in Module B is
827       // used. However, that would then use '%C.1'. But when we process '%C.1',
828       // we prefer to take the '%C' version. So we are then left with both
829       // '%C.1' and '%C' being used for the same types. This leads to some
830       // variables using one type and some using the other.
831       if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
832         TypeMap.addTypeMapping(DST, ST);
833   }
834
835   // Don't bother incorporating aliases, they aren't generally typed well.
836
837   // Now that we have discovered all of the type equivalences, get a body for
838   // any 'opaque' types in the dest module that are now resolved.
839   TypeMap.linkDefinedTypeBodies();
840 }
841
842 static void upgradeGlobalArray(GlobalVariable *GV) {
843   ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
844   StructType *OldTy = cast<StructType>(ATy->getElementType());
845   assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
846
847   // Get the upgraded 3 element type.
848   PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
849   Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
850                   VoidPtrTy};
851   StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
852
853   // Build new constants with a null third field filled in.
854   Constant *OldInitC = GV->getInitializer();
855   ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
856   if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
857     // Invalid initializer; give up.
858     return;
859   std::vector<Constant *> Initializers;
860   if (OldInit && OldInit->getNumOperands()) {
861     Value *Null = Constant::getNullValue(VoidPtrTy);
862     for (Use &U : OldInit->operands()) {
863       ConstantStruct *Init = cast<ConstantStruct>(U.get());
864       Initializers.push_back(ConstantStruct::get(
865           NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
866     }
867   }
868   assert(Initializers.size() == ATy->getNumElements() &&
869          "Failed to copy all array elements");
870
871   // Replace the old GV with a new one.
872   ATy = ArrayType::get(NewTy, Initializers.size());
873   Constant *NewInit = ConstantArray::get(ATy, Initializers);
874   GlobalVariable *NewGV = new GlobalVariable(
875       *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
876       GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
877       GV->isExternallyInitialized());
878   NewGV->copyAttributesFrom(GV);
879   NewGV->takeName(GV);
880   assert(GV->use_empty() && "program cannot use initializer list");
881   GV->eraseFromParent();
882 }
883
884 void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
885   // Look for the global arrays.
886   auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
887   if (!DstGV)
888     return;
889   auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
890   if (!SrcGV)
891     return;
892
893   // Check if the types already match.
894   auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
895   auto *SrcTy =
896       cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
897   if (DstTy == SrcTy)
898     return;
899
900   // Grab the element types.  We can only upgrade an array of a two-field
901   // struct.  Only bother if the other one has three-fields.
902   auto *DstEltTy = cast<StructType>(DstTy->getElementType());
903   auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
904   if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
905     upgradeGlobalArray(DstGV);
906     return;
907   }
908   if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
909     upgradeGlobalArray(SrcGV);
910
911   // We can't upgrade any other differences.
912 }
913
914 void ModuleLinker::upgradeMismatchedGlobals() {
915   upgradeMismatchedGlobalArray("llvm.global_ctors");
916   upgradeMismatchedGlobalArray("llvm.global_dtors");
917 }
918
919 /// linkAppendingVarProto - If there were any appending global variables, link
920 /// them together now.  Return true on error.
921 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
922                                          GlobalVariable *SrcGV) {
923
924   if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
925     return emitError("Linking globals named '" + SrcGV->getName() +
926            "': can only link appending global with another appending global!");
927
928   ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
929   ArrayType *SrcTy =
930     cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
931   Type *EltTy = DstTy->getElementType();
932
933   // Check to see that they two arrays agree on type.
934   if (EltTy != SrcTy->getElementType())
935     return emitError("Appending variables with different element types!");
936   if (DstGV->isConstant() != SrcGV->isConstant())
937     return emitError("Appending variables linked with different const'ness!");
938
939   if (DstGV->getAlignment() != SrcGV->getAlignment())
940     return emitError(
941              "Appending variables with different alignment need to be linked!");
942
943   if (DstGV->getVisibility() != SrcGV->getVisibility())
944     return emitError(
945             "Appending variables with different visibility need to be linked!");
946
947   if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
948     return emitError(
949         "Appending variables with different unnamed_addr need to be linked!");
950
951   if (StringRef(DstGV->getSection()) != SrcGV->getSection())
952     return emitError(
953           "Appending variables with different section name need to be linked!");
954
955   uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
956   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
957
958   // Create the new global variable.
959   GlobalVariable *NG =
960     new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
961                        DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
962                        DstGV->getThreadLocalMode(),
963                        DstGV->getType()->getAddressSpace());
964
965   // Propagate alignment, visibility and section info.
966   copyGVAttributes(NG, DstGV);
967
968   AppendingVarInfo AVI;
969   AVI.NewGV = NG;
970   AVI.DstInit = DstGV->getInitializer();
971   AVI.SrcInit = SrcGV->getInitializer();
972   AppendingVars.push_back(AVI);
973
974   // Replace any uses of the two global variables with uses of the new
975   // global.
976   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
977
978   DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
979   DstGV->eraseFromParent();
980
981   // Track the source variable so we don't try to link it.
982   DoNotLinkFromSource.insert(SrcGV);
983
984   return false;
985 }
986
987 /// linkGlobalProto - Loop through the global variables in the src module and
988 /// merge them into the dest module.
989 bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
990   GlobalValue *DGV = getLinkedToGlobal(SGV);
991   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
992   bool HasUnnamedAddr = SGV->hasUnnamedAddr();
993   unsigned Alignment = SGV->getAlignment();
994
995   bool LinkFromSrc = false;
996   Comdat *DC = nullptr;
997   if (const Comdat *SC = SGV->getComdat()) {
998     Comdat::SelectionKind SK;
999     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1000     DC = DstM->getOrInsertComdat(SC->getName());
1001     DC->setSelectionKind(SK);
1002   }
1003
1004   if (DGV) {
1005     if (!DC) {
1006       // Concatenation of appending linkage variables is magic and handled later.
1007       if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
1008         return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
1009
1010       // Determine whether linkage of these two globals follows the source
1011       // module's definition or the destination module's definition.
1012       GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1013       GlobalValue::VisibilityTypes NV;
1014       if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
1015         return true;
1016       NewVisibility = NV;
1017       HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1018       if (DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1019         Alignment = std::max(Alignment, DGV->getAlignment());
1020       else if (!LinkFromSrc)
1021         Alignment = DGV->getAlignment();
1022
1023       // If we're not linking from the source, then keep the definition that we
1024       // have.
1025       if (!LinkFromSrc) {
1026         // Special case for const propagation.
1027         if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
1028           DGVar->setAlignment(Alignment);
1029
1030           if (DGVar->isDeclaration() && SGV->isConstant() &&
1031               !DGVar->isConstant())
1032             DGVar->setConstant(true);
1033         }
1034
1035         // Set calculated linkage, visibility and unnamed_addr.
1036         DGV->setLinkage(NewLinkage);
1037         DGV->setVisibility(*NewVisibility);
1038         DGV->setUnnamedAddr(HasUnnamedAddr);
1039       }
1040     }
1041
1042     if (!LinkFromSrc) {
1043       // Make sure to remember this mapping.
1044       ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
1045
1046       // Track the source global so that we don't attempt to copy it over when
1047       // processing global initializers.
1048       DoNotLinkFromSource.insert(SGV);
1049
1050       return false;
1051     }
1052   }
1053
1054   // If the Comdat this variable was inside of wasn't selected, skip it.
1055   if (DC && !DGV && !LinkFromSrc) {
1056     DoNotLinkFromSource.insert(SGV);
1057     return false;
1058   }
1059
1060   // No linking to be performed or linking from the source: simply create an
1061   // identical version of the symbol over in the dest module... the
1062   // initializer will be filled in later by LinkGlobalInits.
1063   GlobalVariable *NewDGV =
1064     new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
1065                        SGV->isConstant(), SGV->getLinkage(), /*init*/nullptr,
1066                        SGV->getName(), /*insertbefore*/nullptr,
1067                        SGV->getThreadLocalMode(),
1068                        SGV->getType()->getAddressSpace());
1069   // Propagate alignment, visibility and section info.
1070   copyGVAttributes(NewDGV, SGV);
1071   NewDGV->setAlignment(Alignment);
1072   if (NewVisibility)
1073     NewDGV->setVisibility(*NewVisibility);
1074   NewDGV->setUnnamedAddr(HasUnnamedAddr);
1075
1076   if (DC)
1077     NewDGV->setComdat(DC);
1078
1079   if (DGV) {
1080     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
1081     DGV->eraseFromParent();
1082   }
1083
1084   // Make sure to remember this mapping.
1085   ValueMap[SGV] = NewDGV;
1086   return false;
1087 }
1088
1089 /// linkFunctionProto - Link the function in the source module into the
1090 /// destination module if needed, setting up mapping information.
1091 bool ModuleLinker::linkFunctionProto(Function *SF) {
1092   GlobalValue *DGV = getLinkedToGlobal(SF);
1093   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
1094   bool HasUnnamedAddr = SF->hasUnnamedAddr();
1095
1096   bool LinkFromSrc = false;
1097   Comdat *DC = nullptr;
1098   if (const Comdat *SC = SF->getComdat()) {
1099     Comdat::SelectionKind SK;
1100     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1101     DC = DstM->getOrInsertComdat(SC->getName());
1102     DC->setSelectionKind(SK);
1103   }
1104
1105   if (DGV) {
1106     if (!DC) {
1107       GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1108       GlobalValue::VisibilityTypes NV;
1109       if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
1110         return true;
1111       NewVisibility = NV;
1112       HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1113
1114       if (!LinkFromSrc) {
1115         // Set calculated linkage
1116         DGV->setLinkage(NewLinkage);
1117         DGV->setVisibility(*NewVisibility);
1118         DGV->setUnnamedAddr(HasUnnamedAddr);
1119       }
1120     }
1121
1122     if (!LinkFromSrc) {
1123       // Make sure to remember this mapping.
1124       ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
1125
1126       // Track the function from the source module so we don't attempt to remap
1127       // it.
1128       DoNotLinkFromSource.insert(SF);
1129
1130       return false;
1131     }
1132   }
1133
1134   // If the function is to be lazily linked, don't create it just yet.
1135   // The ValueMaterializerTy will deal with creating it if it's used.
1136   if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1137                SF->hasAvailableExternallyLinkage())) {
1138     DoNotLinkFromSource.insert(SF);
1139     return false;
1140   }
1141
1142   // If the Comdat this function was inside of wasn't selected, skip it.
1143   if (DC && !DGV && !LinkFromSrc) {
1144     DoNotLinkFromSource.insert(SF);
1145     return false;
1146   }
1147
1148   // If there is no linkage to be performed or we are linking from the source,
1149   // bring SF over.
1150   Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
1151                                      SF->getLinkage(), SF->getName(), DstM);
1152   copyGVAttributes(NewDF, SF);
1153   if (NewVisibility)
1154     NewDF->setVisibility(*NewVisibility);
1155   NewDF->setUnnamedAddr(HasUnnamedAddr);
1156
1157   if (DC)
1158     NewDF->setComdat(DC);
1159
1160   if (DGV) {
1161     // Any uses of DF need to change to NewDF, with cast.
1162     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
1163     DGV->eraseFromParent();
1164   }
1165
1166   ValueMap[SF] = NewDF;
1167   return false;
1168 }
1169
1170 /// LinkAliasProto - Set up prototypes for any aliases that come over from the
1171 /// source module.
1172 bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
1173   GlobalValue *DGV = getLinkedToGlobal(SGA);
1174   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
1175   bool HasUnnamedAddr = SGA->hasUnnamedAddr();
1176
1177   bool LinkFromSrc = false;
1178   Comdat *DC = nullptr;
1179   if (const Comdat *SC = SGA->getComdat()) {
1180     Comdat::SelectionKind SK;
1181     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1182     DC = DstM->getOrInsertComdat(SC->getName());
1183     DC->setSelectionKind(SK);
1184   }
1185
1186   if (DGV) {
1187     if (!DC) {
1188       GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1189       GlobalValue::VisibilityTypes NV;
1190       if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
1191         return true;
1192       NewVisibility = NV;
1193       HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1194
1195       if (!LinkFromSrc) {
1196         // Set calculated linkage.
1197         DGV->setLinkage(NewLinkage);
1198         DGV->setVisibility(*NewVisibility);
1199         DGV->setUnnamedAddr(HasUnnamedAddr);
1200       }
1201     }
1202
1203     if (!LinkFromSrc) {
1204       // Make sure to remember this mapping.
1205       ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
1206
1207       // Track the alias from the source module so we don't attempt to remap it.
1208       DoNotLinkFromSource.insert(SGA);
1209
1210       return false;
1211     }
1212   }
1213
1214   // If the Comdat this alias was inside of wasn't selected, skip it.
1215   if (DC && !DGV && !LinkFromSrc) {
1216     DoNotLinkFromSource.insert(SGA);
1217     return false;
1218   }
1219
1220   // If there is no linkage to be performed or we're linking from the source,
1221   // bring over SGA.
1222   auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
1223   auto *NewDA =
1224       GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1225                           SGA->getLinkage(), SGA->getName(), DstM);
1226   copyGVAttributes(NewDA, SGA);
1227   if (NewVisibility)
1228     NewDA->setVisibility(*NewVisibility);
1229   NewDA->setUnnamedAddr(HasUnnamedAddr);
1230
1231   if (DGV) {
1232     // Any uses of DGV need to change to NewDA, with cast.
1233     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
1234     DGV->eraseFromParent();
1235   }
1236
1237   ValueMap[SGA] = NewDA;
1238   return false;
1239 }
1240
1241 static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
1242   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1243
1244   for (unsigned i = 0; i != NumElements; ++i)
1245     Dest.push_back(C->getAggregateElement(i));
1246 }
1247
1248 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1249   // Merge the initializer.
1250   SmallVector<Constant *, 16> DstElements;
1251   getArrayElements(AVI.DstInit, DstElements);
1252
1253   SmallVector<Constant *, 16> SrcElements;
1254   getArrayElements(AVI.SrcInit, SrcElements);
1255
1256   ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1257
1258   StringRef Name = AVI.NewGV->getName();
1259   bool IsNewStructor =
1260       (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1261       cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1262
1263   for (auto *V : SrcElements) {
1264     if (IsNewStructor) {
1265       Constant *Key = V->getAggregateElement(2);
1266       if (DoNotLinkFromSource.count(Key))
1267         continue;
1268     }
1269     DstElements.push_back(
1270         MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1271   }
1272   if (IsNewStructor) {
1273     NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1274     AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1275   }
1276
1277   AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1278 }
1279
1280 /// linkGlobalInits - Update the initializers in the Dest module now that all
1281 /// globals that may be referenced are in Dest.
1282 void ModuleLinker::linkGlobalInits() {
1283   // Loop over all of the globals in the src module, mapping them over as we go
1284   for (Module::const_global_iterator I = SrcM->global_begin(),
1285        E = SrcM->global_end(); I != E; ++I) {
1286
1287     // Only process initialized GV's or ones not already in dest.
1288     if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1289
1290     // Grab destination global variable.
1291     GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1292     // Figure out what the initializer looks like in the dest module.
1293     DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
1294                                  RF_None, &TypeMap, &ValMaterializer));
1295   }
1296 }
1297
1298 /// linkFunctionBody - Copy the source function over into the dest function and
1299 /// fix up references to values.  At this point we know that Dest is an external
1300 /// function, and that Src is not.
1301 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1302   assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
1303
1304   // Go through and convert function arguments over, remembering the mapping.
1305   Function::arg_iterator DI = Dst->arg_begin();
1306   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1307        I != E; ++I, ++DI) {
1308     DI->setName(I->getName());  // Copy the name over.
1309
1310     // Add a mapping to our mapping.
1311     ValueMap[I] = DI;
1312   }
1313
1314   if (Mode == Linker::DestroySource) {
1315     // Splice the body of the source function into the dest function.
1316     Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
1317
1318     // At this point, all of the instructions and values of the function are now
1319     // copied over.  The only problem is that they are still referencing values in
1320     // the Source function as operands.  Loop through all of the operands of the
1321     // functions and patch them up to point to the local versions.
1322     for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1323       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1324         RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries,
1325                          &TypeMap, &ValMaterializer);
1326
1327   } else {
1328     // Clone the body of the function into the dest function.
1329     SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
1330     CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", nullptr,
1331                       &TypeMap, &ValMaterializer);
1332   }
1333
1334   // There is no need to map the arguments anymore.
1335   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1336        I != E; ++I)
1337     ValueMap.erase(I);
1338
1339 }
1340
1341 /// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
1342 void ModuleLinker::linkAliasBodies() {
1343   for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
1344        I != E; ++I) {
1345     if (DoNotLinkFromSource.count(I))
1346       continue;
1347     if (Constant *Aliasee = I->getAliasee()) {
1348       GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
1349       Constant *Val =
1350           MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1351       DA->setAliasee(Val);
1352     }
1353   }
1354 }
1355
1356 /// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
1357 /// module.
1358 void ModuleLinker::linkNamedMDNodes() {
1359   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1360   for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1361        E = SrcM->named_metadata_end(); I != E; ++I) {
1362     // Don't link module flags here. Do them separately.
1363     if (&*I == SrcModFlags) continue;
1364     NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1365     // Add Src elements into Dest node.
1366     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1367       DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
1368                                    RF_None, &TypeMap, &ValMaterializer));
1369   }
1370 }
1371
1372 /// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1373 /// module.
1374 bool ModuleLinker::linkModuleFlagsMetadata() {
1375   // If the source module has no module flags, we are done.
1376   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1377   if (!SrcModFlags) return false;
1378
1379   // If the destination module doesn't have module flags yet, then just copy
1380   // over the source module's flags.
1381   NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1382   if (DstModFlags->getNumOperands() == 0) {
1383     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1384       DstModFlags->addOperand(SrcModFlags->getOperand(I));
1385
1386     return false;
1387   }
1388
1389   // First build a map of the existing module flags and requirements.
1390   DenseMap<MDString*, MDNode*> Flags;
1391   SmallSetVector<MDNode*, 16> Requirements;
1392   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1393     MDNode *Op = DstModFlags->getOperand(I);
1394     ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1395     MDString *ID = cast<MDString>(Op->getOperand(1));
1396
1397     if (Behavior->getZExtValue() == Module::Require) {
1398       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1399     } else {
1400       Flags[ID] = Op;
1401     }
1402   }
1403
1404   // Merge in the flags from the source module, and also collect its set of
1405   // requirements.
1406   bool HasErr = false;
1407   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1408     MDNode *SrcOp = SrcModFlags->getOperand(I);
1409     ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1410     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1411     MDNode *DstOp = Flags.lookup(ID);
1412     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1413
1414     // If this is a requirement, add it and continue.
1415     if (SrcBehaviorValue == Module::Require) {
1416       // If the destination module does not already have this requirement, add
1417       // it.
1418       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1419         DstModFlags->addOperand(SrcOp);
1420       }
1421       continue;
1422     }
1423
1424     // If there is no existing flag with this ID, just add it.
1425     if (!DstOp) {
1426       Flags[ID] = SrcOp;
1427       DstModFlags->addOperand(SrcOp);
1428       continue;
1429     }
1430
1431     // Otherwise, perform a merge.
1432     ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1433     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1434
1435     // If either flag has override behavior, handle it first.
1436     if (DstBehaviorValue == Module::Override) {
1437       // Diagnose inconsistent flags which both have override behavior.
1438       if (SrcBehaviorValue == Module::Override &&
1439           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1440         HasErr |= emitError("linking module flags '" + ID->getString() +
1441                             "': IDs have conflicting override values");
1442       }
1443       continue;
1444     } else if (SrcBehaviorValue == Module::Override) {
1445       // Update the destination flag to that of the source.
1446       DstOp->replaceOperandWith(0, SrcBehavior);
1447       DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1448       continue;
1449     }
1450
1451     // Diagnose inconsistent merge behavior types.
1452     if (SrcBehaviorValue != DstBehaviorValue) {
1453       HasErr |= emitError("linking module flags '" + ID->getString() +
1454                           "': IDs have conflicting behaviors");
1455       continue;
1456     }
1457
1458     // Perform the merge for standard behavior types.
1459     switch (SrcBehaviorValue) {
1460     case Module::Require:
1461     case Module::Override: llvm_unreachable("not possible");
1462     case Module::Error: {
1463       // Emit an error if the values differ.
1464       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1465         HasErr |= emitError("linking module flags '" + ID->getString() +
1466                             "': IDs have conflicting values");
1467       }
1468       continue;
1469     }
1470     case Module::Warning: {
1471       // Emit a warning if the values differ.
1472       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1473         if (!SuppressWarnings) {
1474           errs() << "WARNING: linking module flags '" << ID->getString()
1475                  << "': IDs have conflicting values";
1476         }
1477       }
1478       continue;
1479     }
1480     case Module::Append: {
1481       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1482       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1483       unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1484       Value **VP, **Values = VP = new Value*[NumOps];
1485       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1486         *VP = DstValue->getOperand(i);
1487       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1488         *VP = SrcValue->getOperand(i);
1489       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1490                                                ArrayRef<Value*>(Values,
1491                                                                 NumOps)));
1492       delete[] Values;
1493       break;
1494     }
1495     case Module::AppendUnique: {
1496       SmallSetVector<Value*, 16> Elts;
1497       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1498       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1499       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1500         Elts.insert(DstValue->getOperand(i));
1501       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1502         Elts.insert(SrcValue->getOperand(i));
1503       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1504                                                ArrayRef<Value*>(Elts.begin(),
1505                                                                 Elts.end())));
1506       break;
1507     }
1508     }
1509   }
1510
1511   // Check all of the requirements.
1512   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1513     MDNode *Requirement = Requirements[I];
1514     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1515     Value *ReqValue = Requirement->getOperand(1);
1516
1517     MDNode *Op = Flags[Flag];
1518     if (!Op || Op->getOperand(2) != ReqValue) {
1519       HasErr |= emitError("linking module flags '" + Flag->getString() +
1520                           "': does not have the required value");
1521       continue;
1522     }
1523   }
1524
1525   return HasErr;
1526 }
1527
1528 bool ModuleLinker::run() {
1529   assert(DstM && "Null destination module");
1530   assert(SrcM && "Null source module");
1531
1532   // Inherit the target data from the source module if the destination module
1533   // doesn't have one already.
1534   if (!DstM->getDataLayout() && SrcM->getDataLayout())
1535     DstM->setDataLayout(SrcM->getDataLayout());
1536
1537   // Copy the target triple from the source to dest if the dest's is empty.
1538   if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1539     DstM->setTargetTriple(SrcM->getTargetTriple());
1540
1541   if (SrcM->getDataLayout() && DstM->getDataLayout() &&
1542       *SrcM->getDataLayout() != *DstM->getDataLayout()) {
1543     if (!SuppressWarnings) {
1544       errs() << "WARNING: Linking two modules of different data layouts: '"
1545              << SrcM->getModuleIdentifier() << "' is '"
1546              << SrcM->getDataLayoutStr() << "' whereas '"
1547              << DstM->getModuleIdentifier() << "' is '"
1548              << DstM->getDataLayoutStr() << "'\n";
1549     }
1550   }
1551   if (!SrcM->getTargetTriple().empty() &&
1552       DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1553     if (!SuppressWarnings) {
1554       errs() << "WARNING: Linking two modules of different target triples: "
1555              << SrcM->getModuleIdentifier() << "' is '"
1556              << SrcM->getTargetTriple() << "' whereas '"
1557              << DstM->getModuleIdentifier() << "' is '"
1558              << DstM->getTargetTriple() << "'\n";
1559     }
1560   }
1561
1562   // Append the module inline asm string.
1563   if (!SrcM->getModuleInlineAsm().empty()) {
1564     if (DstM->getModuleInlineAsm().empty())
1565       DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1566     else
1567       DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1568                                SrcM->getModuleInlineAsm());
1569   }
1570
1571   // Loop over all of the linked values to compute type mappings.
1572   computeTypeMapping();
1573
1574   ComdatsChosen.clear();
1575   for (const StringMapEntry<llvm::Comdat> &SMEC : SrcM->getComdatSymbolTable()) {
1576     const Comdat &C = SMEC.getValue();
1577     if (ComdatsChosen.count(&C))
1578       continue;
1579     Comdat::SelectionKind SK;
1580     bool LinkFromSrc;
1581     if (getComdatResult(&C, SK, LinkFromSrc))
1582       return true;
1583     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1584   }
1585
1586   // Upgrade mismatched global arrays.
1587   upgradeMismatchedGlobals();
1588
1589   // Insert all of the globals in src into the DstM module... without linking
1590   // initializers (which could refer to functions not yet mapped over).
1591   for (Module::global_iterator I = SrcM->global_begin(),
1592        E = SrcM->global_end(); I != E; ++I)
1593     if (linkGlobalProto(I))
1594       return true;
1595
1596   // Link the functions together between the two modules, without doing function
1597   // bodies... this just adds external function prototypes to the DstM
1598   // function...  We do this so that when we begin processing function bodies,
1599   // all of the global values that may be referenced are available in our
1600   // ValueMap.
1601   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1602     if (linkFunctionProto(I))
1603       return true;
1604
1605   // If there were any aliases, link them now.
1606   for (Module::alias_iterator I = SrcM->alias_begin(),
1607        E = SrcM->alias_end(); I != E; ++I)
1608     if (linkAliasProto(I))
1609       return true;
1610
1611   for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1612     linkAppendingVarInit(AppendingVars[i]);
1613
1614   // Link in the function bodies that are defined in the source module into
1615   // DstM.
1616   for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1617     // Skip if not linking from source.
1618     if (DoNotLinkFromSource.count(SF)) continue;
1619
1620     Function *DF = cast<Function>(ValueMap[SF]);
1621     if (SF->hasPrefixData()) {
1622       // Link in the prefix data.
1623       DF->setPrefixData(MapValue(
1624           SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1625     }
1626
1627     // Materialize if needed.
1628     if (SF->isMaterializable()) {
1629       if (SF->Materialize(&ErrorMsg))
1630         return true;
1631     }
1632
1633     // Skip if no body (function is external).
1634     if (SF->isDeclaration())
1635       continue;
1636
1637     linkFunctionBody(DF, SF);
1638     SF->Dematerialize();
1639   }
1640
1641   // Resolve all uses of aliases with aliasees.
1642   linkAliasBodies();
1643
1644   // Remap all of the named MDNodes in Src into the DstM module. We do this
1645   // after linking GlobalValues so that MDNodes that reference GlobalValues
1646   // are properly remapped.
1647   linkNamedMDNodes();
1648
1649   // Merge the module flags into the DstM module.
1650   if (linkModuleFlagsMetadata())
1651     return true;
1652
1653   // Update the initializers in the DstM module now that all globals that may
1654   // be referenced are in DstM.
1655   linkGlobalInits();
1656
1657   // Process vector of lazily linked in functions.
1658   bool LinkedInAnyFunctions;
1659   do {
1660     LinkedInAnyFunctions = false;
1661
1662     for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1663         E = LazilyLinkFunctions.end(); I != E; ++I) {
1664       Function *SF = *I;
1665       if (!SF)
1666         continue;
1667
1668       Function *DF = cast<Function>(ValueMap[SF]);
1669       if (SF->hasPrefixData()) {
1670         // Link in the prefix data.
1671         DF->setPrefixData(MapValue(SF->getPrefixData(),
1672                                    ValueMap,
1673                                    RF_None,
1674                                    &TypeMap,
1675                                    &ValMaterializer));
1676       }
1677
1678       // Materialize if needed.
1679       if (SF->isMaterializable()) {
1680         if (SF->Materialize(&ErrorMsg))
1681           return true;
1682       }
1683
1684       // Skip if no body (function is external).
1685       if (SF->isDeclaration())
1686         continue;
1687
1688       // Erase from vector *before* the function body is linked - linkFunctionBody could
1689       // invalidate I.
1690       LazilyLinkFunctions.erase(I);
1691
1692       // Link in function body.
1693       linkFunctionBody(DF, SF);
1694       SF->Dematerialize();
1695
1696       // Set flag to indicate we may have more functions to lazily link in
1697       // since we linked in a function.
1698       LinkedInAnyFunctions = true;
1699       break;
1700     }
1701   } while (LinkedInAnyFunctions);
1702
1703   // Now that all of the types from the source are used, resolve any structs
1704   // copied over to the dest that didn't exist there.
1705   TypeMap.linkDefinedTypeBodies();
1706
1707   return false;
1708 }
1709
1710 Linker::Linker(Module *M, bool SuppressWarnings)
1711     : Composite(M), SuppressWarnings(SuppressWarnings) {
1712   TypeFinder StructTypes;
1713   StructTypes.run(*M, true);
1714   IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1715 }
1716
1717 Linker::~Linker() {
1718 }
1719
1720 void Linker::deleteModule() {
1721   delete Composite;
1722   Composite = nullptr;
1723 }
1724
1725 bool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) {
1726   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode,
1727                          SuppressWarnings);
1728   if (TheLinker.run()) {
1729     if (ErrorMsg)
1730       *ErrorMsg = TheLinker.ErrorMsg;
1731     return true;
1732   }
1733   return false;
1734 }
1735
1736 //===----------------------------------------------------------------------===//
1737 // LinkModules entrypoint.
1738 //===----------------------------------------------------------------------===//
1739
1740 /// LinkModules - This function links two modules together, with the resulting
1741 /// Dest module modified to be the composite of the two input modules.  If an
1742 /// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1743 /// the problem.  Upon failure, the Dest module could be in a modified state,
1744 /// and shouldn't be relied on to be consistent.
1745 bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1746                          std::string *ErrorMsg) {
1747   Linker L(Dest);
1748   return L.linkInModule(Src, Mode, ErrorMsg);
1749 }
1750
1751 //===----------------------------------------------------------------------===//
1752 // C API.
1753 //===----------------------------------------------------------------------===//
1754
1755 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1756                          LLVMLinkerMode Mode, char **OutMessages) {
1757   std::string Messages;
1758   LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
1759                                         Mode, OutMessages? &Messages : nullptr);
1760   if (OutMessages)
1761     *OutMessages = strdup(Messages.c_str());
1762   return Result;
1763 }