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