65fe30c94f7b81fe3bf4381a24f7366690b1c9aa
[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
1005   bool LinkFromSrc = false;
1006   Comdat *DC = nullptr;
1007   if (const Comdat *SC = SGV->getComdat()) {
1008     Comdat::SelectionKind SK;
1009     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1010     DC = DstM->getOrInsertComdat(SC->getName());
1011     DC->setSelectionKind(SK);
1012   }
1013
1014   if (DGV) {
1015     if (!DC) {
1016       // Concatenation of appending linkage variables is magic and handled later.
1017       if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
1018         return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
1019
1020       // Determine whether linkage of these two globals follows the source
1021       // module's definition or the destination module's definition.
1022       GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1023       GlobalValue::VisibilityTypes NV;
1024       if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
1025         return true;
1026       NewVisibility = NV;
1027       HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1028
1029       // If we're not linking from the source, then keep the definition that we
1030       // have.
1031       if (!LinkFromSrc) {
1032         // Special case for const propagation.
1033         if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
1034           if (DGVar->isDeclaration() && SGV->isConstant() &&
1035               !DGVar->isConstant())
1036             DGVar->setConstant(true);
1037
1038         // Set calculated linkage, visibility and unnamed_addr.
1039         DGV->setLinkage(NewLinkage);
1040         DGV->setVisibility(*NewVisibility);
1041         DGV->setUnnamedAddr(HasUnnamedAddr);
1042       }
1043     }
1044
1045     if (!LinkFromSrc) {
1046       // Make sure to remember this mapping.
1047       ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
1048
1049       // Track the source global so that we don't attempt to copy it over when
1050       // processing global initializers.
1051       DoNotLinkFromSource.insert(SGV);
1052
1053       return false;
1054     }
1055   }
1056
1057   // If the Comdat this variable was inside of wasn't selected, skip it.
1058   if (DC && !DGV && !LinkFromSrc) {
1059     DoNotLinkFromSource.insert(SGV);
1060     return false;
1061   }
1062
1063   // No linking to be performed or linking from the source: simply create an
1064   // identical version of the symbol over in the dest module... the
1065   // initializer will be filled in later by LinkGlobalInits.
1066   GlobalVariable *NewDGV =
1067     new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
1068                        SGV->isConstant(), SGV->getLinkage(), /*init*/nullptr,
1069                        SGV->getName(), /*insertbefore*/nullptr,
1070                        SGV->getThreadLocalMode(),
1071                        SGV->getType()->getAddressSpace());
1072   // Propagate alignment, visibility and section info.
1073   copyGVAttributes(NewDGV, SGV);
1074   if (NewVisibility)
1075     NewDGV->setVisibility(*NewVisibility);
1076   NewDGV->setUnnamedAddr(HasUnnamedAddr);
1077
1078   if (DC)
1079     NewDGV->setComdat(DC);
1080
1081   if (DGV) {
1082     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
1083     DGV->eraseFromParent();
1084   }
1085
1086   // Make sure to remember this mapping.
1087   ValueMap[SGV] = NewDGV;
1088   return false;
1089 }
1090
1091 /// linkFunctionProto - Link the function in the source module into the
1092 /// destination module if needed, setting up mapping information.
1093 bool ModuleLinker::linkFunctionProto(Function *SF) {
1094   GlobalValue *DGV = getLinkedToGlobal(SF);
1095   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
1096   bool HasUnnamedAddr = SF->hasUnnamedAddr();
1097
1098   bool LinkFromSrc = false;
1099   Comdat *DC = nullptr;
1100   if (const Comdat *SC = SF->getComdat()) {
1101     Comdat::SelectionKind SK;
1102     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1103     DC = DstM->getOrInsertComdat(SC->getName());
1104     DC->setSelectionKind(SK);
1105   }
1106
1107   if (DGV) {
1108     if (!DC) {
1109       GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1110       GlobalValue::VisibilityTypes NV;
1111       if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
1112         return true;
1113       NewVisibility = NV;
1114       HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1115
1116       if (!LinkFromSrc) {
1117         // Set calculated linkage
1118         DGV->setLinkage(NewLinkage);
1119         DGV->setVisibility(*NewVisibility);
1120         DGV->setUnnamedAddr(HasUnnamedAddr);
1121       }
1122     }
1123
1124     if (!LinkFromSrc) {
1125       // Make sure to remember this mapping.
1126       ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
1127
1128       // Track the function from the source module so we don't attempt to remap
1129       // it.
1130       DoNotLinkFromSource.insert(SF);
1131
1132       return false;
1133     }
1134   }
1135
1136   // If the function is to be lazily linked, don't create it just yet.
1137   // The ValueMaterializerTy will deal with creating it if it's used.
1138   if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1139                SF->hasAvailableExternallyLinkage())) {
1140     DoNotLinkFromSource.insert(SF);
1141     return false;
1142   }
1143
1144   // If the Comdat this function was inside of wasn't selected, skip it.
1145   if (DC && !DGV && !LinkFromSrc) {
1146     DoNotLinkFromSource.insert(SF);
1147     return false;
1148   }
1149
1150   // If there is no linkage to be performed or we are linking from the source,
1151   // bring SF over.
1152   Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
1153                                      SF->getLinkage(), SF->getName(), DstM);
1154   copyGVAttributes(NewDF, SF);
1155   if (NewVisibility)
1156     NewDF->setVisibility(*NewVisibility);
1157   NewDF->setUnnamedAddr(HasUnnamedAddr);
1158
1159   if (DC)
1160     NewDF->setComdat(DC);
1161
1162   if (DGV) {
1163     // Any uses of DF need to change to NewDF, with cast.
1164     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
1165     DGV->eraseFromParent();
1166   }
1167
1168   ValueMap[SF] = NewDF;
1169   return false;
1170 }
1171
1172 /// LinkAliasProto - Set up prototypes for any aliases that come over from the
1173 /// source module.
1174 bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
1175   GlobalValue *DGV = getLinkedToGlobal(SGA);
1176   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
1177   bool HasUnnamedAddr = SGA->hasUnnamedAddr();
1178
1179   bool LinkFromSrc = false;
1180   Comdat *DC = nullptr;
1181   if (const Comdat *SC = SGA->getComdat()) {
1182     Comdat::SelectionKind SK;
1183     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1184     DC = DstM->getOrInsertComdat(SC->getName());
1185     DC->setSelectionKind(SK);
1186   }
1187
1188   if (DGV) {
1189     if (!DC) {
1190       GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1191       GlobalValue::VisibilityTypes NV;
1192       if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
1193         return true;
1194       NewVisibility = NV;
1195       HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1196
1197       if (!LinkFromSrc) {
1198         // Set calculated linkage.
1199         DGV->setLinkage(NewLinkage);
1200         DGV->setVisibility(*NewVisibility);
1201         DGV->setUnnamedAddr(HasUnnamedAddr);
1202       }
1203     }
1204
1205     if (!LinkFromSrc) {
1206       // Make sure to remember this mapping.
1207       ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
1208
1209       // Track the alias from the source module so we don't attempt to remap it.
1210       DoNotLinkFromSource.insert(SGA);
1211
1212       return false;
1213     }
1214   }
1215
1216   // If the Comdat this alias was inside of wasn't selected, skip it.
1217   if (DC && !DGV && !LinkFromSrc) {
1218     DoNotLinkFromSource.insert(SGA);
1219     return false;
1220   }
1221
1222   // If there is no linkage to be performed or we're linking from the source,
1223   // bring over SGA.
1224   auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
1225   auto *NewDA =
1226       GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1227                           SGA->getLinkage(), SGA->getName(), DstM);
1228   copyGVAttributes(NewDA, SGA);
1229   if (NewVisibility)
1230     NewDA->setVisibility(*NewVisibility);
1231   NewDA->setUnnamedAddr(HasUnnamedAddr);
1232
1233   if (DGV) {
1234     // Any uses of DGV need to change to NewDA, with cast.
1235     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
1236     DGV->eraseFromParent();
1237   }
1238
1239   ValueMap[SGA] = NewDA;
1240   return false;
1241 }
1242
1243 static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
1244   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1245
1246   for (unsigned i = 0; i != NumElements; ++i)
1247     Dest.push_back(C->getAggregateElement(i));
1248 }
1249
1250 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1251   // Merge the initializer.
1252   SmallVector<Constant *, 16> DstElements;
1253   getArrayElements(AVI.DstInit, DstElements);
1254
1255   SmallVector<Constant *, 16> SrcElements;
1256   getArrayElements(AVI.SrcInit, SrcElements);
1257
1258   ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1259
1260   StringRef Name = AVI.NewGV->getName();
1261   bool IsNewStructor =
1262       (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1263       cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1264
1265   for (auto *V : SrcElements) {
1266     if (IsNewStructor) {
1267       Constant *Key = V->getAggregateElement(2);
1268       if (DoNotLinkFromSource.count(Key))
1269         continue;
1270     }
1271     DstElements.push_back(
1272         MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1273   }
1274   if (IsNewStructor) {
1275     NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1276     AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1277   }
1278
1279   AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1280 }
1281
1282 /// linkGlobalInits - Update the initializers in the Dest module now that all
1283 /// globals that may be referenced are in Dest.
1284 void ModuleLinker::linkGlobalInits() {
1285   // Loop over all of the globals in the src module, mapping them over as we go
1286   for (Module::const_global_iterator I = SrcM->global_begin(),
1287        E = SrcM->global_end(); I != E; ++I) {
1288
1289     // Only process initialized GV's or ones not already in dest.
1290     if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1291
1292     // Grab destination global variable.
1293     GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1294     // Figure out what the initializer looks like in the dest module.
1295     DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
1296                                  RF_None, &TypeMap, &ValMaterializer));
1297   }
1298 }
1299
1300 /// linkFunctionBody - Copy the source function over into the dest function and
1301 /// fix up references to values.  At this point we know that Dest is an external
1302 /// function, and that Src is not.
1303 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1304   assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
1305
1306   // Go through and convert function arguments over, remembering the mapping.
1307   Function::arg_iterator DI = Dst->arg_begin();
1308   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1309        I != E; ++I, ++DI) {
1310     DI->setName(I->getName());  // Copy the name over.
1311
1312     // Add a mapping to our mapping.
1313     ValueMap[I] = DI;
1314   }
1315
1316   if (Mode == Linker::DestroySource) {
1317     // Splice the body of the source function into the dest function.
1318     Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
1319
1320     // At this point, all of the instructions and values of the function are now
1321     // copied over.  The only problem is that they are still referencing values in
1322     // the Source function as operands.  Loop through all of the operands of the
1323     // functions and patch them up to point to the local versions.
1324     for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1325       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1326         RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries,
1327                          &TypeMap, &ValMaterializer);
1328
1329   } else {
1330     // Clone the body of the function into the dest function.
1331     SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
1332     CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", nullptr,
1333                       &TypeMap, &ValMaterializer);
1334   }
1335
1336   // There is no need to map the arguments anymore.
1337   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1338        I != E; ++I)
1339     ValueMap.erase(I);
1340
1341 }
1342
1343 /// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
1344 void ModuleLinker::linkAliasBodies() {
1345   for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
1346        I != E; ++I) {
1347     if (DoNotLinkFromSource.count(I))
1348       continue;
1349     if (Constant *Aliasee = I->getAliasee()) {
1350       GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
1351       Constant *Val =
1352           MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1353       DA->setAliasee(Val);
1354     }
1355   }
1356 }
1357
1358 /// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
1359 /// module.
1360 void ModuleLinker::linkNamedMDNodes() {
1361   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1362   for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1363        E = SrcM->named_metadata_end(); I != E; ++I) {
1364     // Don't link module flags here. Do them separately.
1365     if (&*I == SrcModFlags) continue;
1366     NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1367     // Add Src elements into Dest node.
1368     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1369       DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
1370                                    RF_None, &TypeMap, &ValMaterializer));
1371   }
1372 }
1373
1374 /// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1375 /// module.
1376 bool ModuleLinker::linkModuleFlagsMetadata() {
1377   // If the source module has no module flags, we are done.
1378   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1379   if (!SrcModFlags) return false;
1380
1381   // If the destination module doesn't have module flags yet, then just copy
1382   // over the source module's flags.
1383   NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1384   if (DstModFlags->getNumOperands() == 0) {
1385     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1386       DstModFlags->addOperand(SrcModFlags->getOperand(I));
1387
1388     return false;
1389   }
1390
1391   // First build a map of the existing module flags and requirements.
1392   DenseMap<MDString*, MDNode*> Flags;
1393   SmallSetVector<MDNode*, 16> Requirements;
1394   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1395     MDNode *Op = DstModFlags->getOperand(I);
1396     ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1397     MDString *ID = cast<MDString>(Op->getOperand(1));
1398
1399     if (Behavior->getZExtValue() == Module::Require) {
1400       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1401     } else {
1402       Flags[ID] = Op;
1403     }
1404   }
1405
1406   // Merge in the flags from the source module, and also collect its set of
1407   // requirements.
1408   bool HasErr = false;
1409   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1410     MDNode *SrcOp = SrcModFlags->getOperand(I);
1411     ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1412     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1413     MDNode *DstOp = Flags.lookup(ID);
1414     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1415
1416     // If this is a requirement, add it and continue.
1417     if (SrcBehaviorValue == Module::Require) {
1418       // If the destination module does not already have this requirement, add
1419       // it.
1420       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1421         DstModFlags->addOperand(SrcOp);
1422       }
1423       continue;
1424     }
1425
1426     // If there is no existing flag with this ID, just add it.
1427     if (!DstOp) {
1428       Flags[ID] = SrcOp;
1429       DstModFlags->addOperand(SrcOp);
1430       continue;
1431     }
1432
1433     // Otherwise, perform a merge.
1434     ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1435     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1436
1437     // If either flag has override behavior, handle it first.
1438     if (DstBehaviorValue == Module::Override) {
1439       // Diagnose inconsistent flags which both have override behavior.
1440       if (SrcBehaviorValue == Module::Override &&
1441           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1442         HasErr |= emitError("linking module flags '" + ID->getString() +
1443                             "': IDs have conflicting override values");
1444       }
1445       continue;
1446     } else if (SrcBehaviorValue == Module::Override) {
1447       // Update the destination flag to that of the source.
1448       DstOp->replaceOperandWith(0, SrcBehavior);
1449       DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1450       continue;
1451     }
1452
1453     // Diagnose inconsistent merge behavior types.
1454     if (SrcBehaviorValue != DstBehaviorValue) {
1455       HasErr |= emitError("linking module flags '" + ID->getString() +
1456                           "': IDs have conflicting behaviors");
1457       continue;
1458     }
1459
1460     // Perform the merge for standard behavior types.
1461     switch (SrcBehaviorValue) {
1462     case Module::Require:
1463     case Module::Override: llvm_unreachable("not possible");
1464     case Module::Error: {
1465       // Emit an error if the values differ.
1466       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1467         HasErr |= emitError("linking module flags '" + ID->getString() +
1468                             "': IDs have conflicting values");
1469       }
1470       continue;
1471     }
1472     case Module::Warning: {
1473       // Emit a warning if the values differ.
1474       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1475         if (!SuppressWarnings) {
1476           errs() << "WARNING: linking module flags '" << ID->getString()
1477                  << "': IDs have conflicting values";
1478         }
1479       }
1480       continue;
1481     }
1482     case Module::Append: {
1483       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1484       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1485       unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1486       Value **VP, **Values = VP = new Value*[NumOps];
1487       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1488         *VP = DstValue->getOperand(i);
1489       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1490         *VP = SrcValue->getOperand(i);
1491       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1492                                                ArrayRef<Value*>(Values,
1493                                                                 NumOps)));
1494       delete[] Values;
1495       break;
1496     }
1497     case Module::AppendUnique: {
1498       SmallSetVector<Value*, 16> Elts;
1499       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1500       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1501       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1502         Elts.insert(DstValue->getOperand(i));
1503       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1504         Elts.insert(SrcValue->getOperand(i));
1505       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1506                                                ArrayRef<Value*>(Elts.begin(),
1507                                                                 Elts.end())));
1508       break;
1509     }
1510     }
1511   }
1512
1513   // Check all of the requirements.
1514   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1515     MDNode *Requirement = Requirements[I];
1516     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1517     Value *ReqValue = Requirement->getOperand(1);
1518
1519     MDNode *Op = Flags[Flag];
1520     if (!Op || Op->getOperand(2) != ReqValue) {
1521       HasErr |= emitError("linking module flags '" + Flag->getString() +
1522                           "': does not have the required value");
1523       continue;
1524     }
1525   }
1526
1527   return HasErr;
1528 }
1529
1530 bool ModuleLinker::run() {
1531   assert(DstM && "Null destination module");
1532   assert(SrcM && "Null source module");
1533
1534   // Inherit the target data from the source module if the destination module
1535   // doesn't have one already.
1536   if (!DstM->getDataLayout() && SrcM->getDataLayout())
1537     DstM->setDataLayout(SrcM->getDataLayout());
1538
1539   // Copy the target triple from the source to dest if the dest's is empty.
1540   if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1541     DstM->setTargetTriple(SrcM->getTargetTriple());
1542
1543   if (SrcM->getDataLayout() && DstM->getDataLayout() &&
1544       *SrcM->getDataLayout() != *DstM->getDataLayout()) {
1545     if (!SuppressWarnings) {
1546       errs() << "WARNING: Linking two modules of different data layouts: '"
1547              << SrcM->getModuleIdentifier() << "' is '"
1548              << SrcM->getDataLayoutStr() << "' whereas '"
1549              << DstM->getModuleIdentifier() << "' is '"
1550              << DstM->getDataLayoutStr() << "'\n";
1551     }
1552   }
1553   if (!SrcM->getTargetTriple().empty() &&
1554       DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1555     if (!SuppressWarnings) {
1556       errs() << "WARNING: Linking two modules of different target triples: "
1557              << SrcM->getModuleIdentifier() << "' is '"
1558              << SrcM->getTargetTriple() << "' whereas '"
1559              << DstM->getModuleIdentifier() << "' is '"
1560              << DstM->getTargetTriple() << "'\n";
1561     }
1562   }
1563
1564   // Append the module inline asm string.
1565   if (!SrcM->getModuleInlineAsm().empty()) {
1566     if (DstM->getModuleInlineAsm().empty())
1567       DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1568     else
1569       DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1570                                SrcM->getModuleInlineAsm());
1571   }
1572
1573   // Loop over all of the linked values to compute type mappings.
1574   computeTypeMapping();
1575
1576   ComdatsChosen.clear();
1577   for (const StringMapEntry<llvm::Comdat> &SMEC : SrcM->getComdatSymbolTable()) {
1578     const Comdat &C = SMEC.getValue();
1579     if (ComdatsChosen.count(&C))
1580       continue;
1581     Comdat::SelectionKind SK;
1582     bool LinkFromSrc;
1583     if (getComdatResult(&C, SK, LinkFromSrc))
1584       return true;
1585     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1586   }
1587
1588   // Upgrade mismatched global arrays.
1589   upgradeMismatchedGlobals();
1590
1591   // Insert all of the globals in src into the DstM module... without linking
1592   // initializers (which could refer to functions not yet mapped over).
1593   for (Module::global_iterator I = SrcM->global_begin(),
1594        E = SrcM->global_end(); I != E; ++I)
1595     if (linkGlobalProto(I))
1596       return true;
1597
1598   // Link the functions together between the two modules, without doing function
1599   // bodies... this just adds external function prototypes to the DstM
1600   // function...  We do this so that when we begin processing function bodies,
1601   // all of the global values that may be referenced are available in our
1602   // ValueMap.
1603   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1604     if (linkFunctionProto(I))
1605       return true;
1606
1607   // If there were any aliases, link them now.
1608   for (Module::alias_iterator I = SrcM->alias_begin(),
1609        E = SrcM->alias_end(); I != E; ++I)
1610     if (linkAliasProto(I))
1611       return true;
1612
1613   for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1614     linkAppendingVarInit(AppendingVars[i]);
1615
1616   // Link in the function bodies that are defined in the source module into
1617   // DstM.
1618   for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1619     // Skip if not linking from source.
1620     if (DoNotLinkFromSource.count(SF)) continue;
1621
1622     Function *DF = cast<Function>(ValueMap[SF]);
1623     if (SF->hasPrefixData()) {
1624       // Link in the prefix data.
1625       DF->setPrefixData(MapValue(
1626           SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1627     }
1628
1629     // Skip if no body (function is external) or materialize.
1630     if (SF->isDeclaration()) {
1631       if (!SF->isMaterializable())
1632         continue;
1633       if (SF->Materialize(&ErrorMsg))
1634         return true;
1635     }
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 necessary.
1679       if (SF->isDeclaration()) {
1680         if (!SF->isMaterializable())
1681           continue;
1682         if (SF->Materialize(&ErrorMsg))
1683           return true;
1684       }
1685
1686       // Erase from vector *before* the function body is linked - linkFunctionBody could
1687       // invalidate I.
1688       LazilyLinkFunctions.erase(I);
1689
1690       // Link in function body.
1691       linkFunctionBody(DF, SF);
1692       SF->Dematerialize();
1693
1694       // Set flag to indicate we may have more functions to lazily link in
1695       // since we linked in a function.
1696       LinkedInAnyFunctions = true;
1697       break;
1698     }
1699   } while (LinkedInAnyFunctions);
1700
1701   // Now that all of the types from the source are used, resolve any structs
1702   // copied over to the dest that didn't exist there.
1703   TypeMap.linkDefinedTypeBodies();
1704
1705   return false;
1706 }
1707
1708 Linker::Linker(Module *M, bool SuppressWarnings)
1709     : Composite(M), SuppressWarnings(SuppressWarnings) {
1710   TypeFinder StructTypes;
1711   StructTypes.run(*M, true);
1712   IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1713 }
1714
1715 Linker::~Linker() {
1716 }
1717
1718 void Linker::deleteModule() {
1719   delete Composite;
1720   Composite = nullptr;
1721 }
1722
1723 bool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) {
1724   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode,
1725                          SuppressWarnings);
1726   if (TheLinker.run()) {
1727     if (ErrorMsg)
1728       *ErrorMsg = TheLinker.ErrorMsg;
1729     return true;
1730   }
1731   return false;
1732 }
1733
1734 //===----------------------------------------------------------------------===//
1735 // LinkModules entrypoint.
1736 //===----------------------------------------------------------------------===//
1737
1738 /// LinkModules - This function links two modules together, with the resulting
1739 /// Dest module modified to be the composite of the two input modules.  If an
1740 /// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1741 /// the problem.  Upon failure, the Dest module could be in a modified state,
1742 /// and shouldn't be relied on to be consistent.
1743 bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1744                          std::string *ErrorMsg) {
1745   Linker L(Dest);
1746   return L.linkInModule(Src, Mode, ErrorMsg);
1747 }
1748
1749 //===----------------------------------------------------------------------===//
1750 // C API.
1751 //===----------------------------------------------------------------------===//
1752
1753 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1754                          LLVMLinkerMode Mode, char **OutMessages) {
1755   std::string Messages;
1756   LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
1757                                         Mode, OutMessages? &Messages : nullptr);
1758   if (OutMessages)
1759     *OutMessages = strdup(Messages.c_str());
1760   return Result;
1761 }