Reduce abuse of default values in the GlobalAlias constructor.
[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     std::vector<std::pair<GlobalValue *, GlobalAlias *>> ReplaceWithAlias;
393
394     struct AppendingVarInfo {
395       GlobalVariable *NewGV;  // New aggregate global in dest module.
396       Constant *DstInit;      // Old initializer from dest module.
397       Constant *SrcInit;      // Old initializer from src module.
398     };
399
400     std::vector<AppendingVarInfo> AppendingVars;
401
402     unsigned Mode; // Mode to treat source module.
403
404     // Set of items not to link in from source.
405     SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
406
407     // Vector of functions to lazily link in.
408     std::vector<Function*> LazilyLinkFunctions;
409
410     bool SuppressWarnings;
411
412   public:
413     std::string ErrorMsg;
414
415     ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, unsigned mode,
416                  bool SuppressWarnings=false)
417         : DstM(dstM), SrcM(srcM), TypeMap(Set),
418           ValMaterializer(TypeMap, DstM, LazilyLinkFunctions), Mode(mode),
419           SuppressWarnings(SuppressWarnings) {}
420
421     bool run();
422
423   private:
424     /// emitError - Helper method for setting a message and returning an error
425     /// code.
426     bool emitError(const Twine &Message) {
427       ErrorMsg = Message.str();
428       return true;
429     }
430
431     /// getLinkageResult - This analyzes the two global values and determines
432     /// what the result will look like in the destination module.
433     bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
434                           GlobalValue::LinkageTypes &LT,
435                           GlobalValue::VisibilityTypes &Vis,
436                           bool &LinkFromSrc);
437
438     /// getLinkedToGlobal - Given a global in the source module, return the
439     /// global in the destination module that is being linked to, if any.
440     GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
441       // If the source has no name it can't link.  If it has local linkage,
442       // there is no name match-up going on.
443       if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
444         return nullptr;
445
446       // Otherwise see if we have a match in the destination module's symtab.
447       GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
448       if (!DGV) return nullptr;
449
450       // If we found a global with the same name in the dest module, but it has
451       // internal linkage, we are really not doing any linkage here.
452       if (DGV->hasLocalLinkage())
453         return nullptr;
454
455       // Otherwise, we do in fact link to the destination global.
456       return DGV;
457     }
458
459     void computeTypeMapping();
460
461     bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
462     bool linkGlobalProto(GlobalVariable *SrcGV);
463     bool linkFunctionProto(Function *SrcF);
464     bool linkAliasProto(GlobalAlias *SrcA);
465     bool linkModuleFlagsMetadata();
466
467     void linkAppendingVarInit(const AppendingVarInfo &AVI);
468     void linkGlobalInits();
469     void linkFunctionBody(Function *Dst, Function *Src);
470     void linkAliasBodies();
471     void linkNamedMDNodes();
472   };
473 }
474
475 /// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
476 /// in the symbol table.  This is good for all clients except for us.  Go
477 /// through the trouble to force this back.
478 static void forceRenaming(GlobalValue *GV, StringRef Name) {
479   // If the global doesn't force its name or if it already has the right name,
480   // there is nothing for us to do.
481   if (GV->hasLocalLinkage() || GV->getName() == Name)
482     return;
483
484   Module *M = GV->getParent();
485
486   // If there is a conflict, rename the conflict.
487   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
488     GV->takeName(ConflictGV);
489     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
490     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
491   } else {
492     GV->setName(Name);              // Force the name back
493   }
494 }
495
496 /// copyGVAttributes - copy additional attributes (those not needed to construct
497 /// a GlobalValue) from the SrcGV to the DestGV.
498 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
499   // Use the maximum alignment, rather than just copying the alignment of SrcGV.
500   auto *DestGO = dyn_cast<GlobalObject>(DestGV);
501   unsigned Alignment;
502   if (DestGO)
503     Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
504
505   DestGV->copyAttributesFrom(SrcGV);
506
507   if (DestGO)
508     DestGO->setAlignment(Alignment);
509
510   forceRenaming(DestGV, SrcGV->getName());
511 }
512
513 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
514                                GlobalValue::VisibilityTypes b) {
515   if (a == GlobalValue::HiddenVisibility)
516     return false;
517   if (b == GlobalValue::HiddenVisibility)
518     return true;
519   if (a == GlobalValue::ProtectedVisibility)
520     return false;
521   if (b == GlobalValue::ProtectedVisibility)
522     return true;
523   return false;
524 }
525
526 Value *ValueMaterializerTy::materializeValueFor(Value *V) {
527   Function *SF = dyn_cast<Function>(V);
528   if (!SF)
529     return nullptr;
530
531   Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
532                                   SF->getLinkage(), SF->getName(), DstM);
533   copyGVAttributes(DF, SF);
534
535   LazilyLinkFunctions.push_back(SF);
536   return DF;
537 }
538
539
540 /// getLinkageResult - This analyzes the two global values and determines what
541 /// the result will look like in the destination module.  In particular, it
542 /// computes the resultant linkage type and visibility, computes whether the
543 /// global in the source should be copied over to the destination (replacing
544 /// the existing one), and computes whether this linkage is an error or not.
545 bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
546                                     GlobalValue::LinkageTypes &LT,
547                                     GlobalValue::VisibilityTypes &Vis,
548                                     bool &LinkFromSrc) {
549   assert(Dest && "Must have two globals being queried");
550   assert(!Src->hasLocalLinkage() &&
551          "If Src has internal linkage, Dest shouldn't be set!");
552
553   bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
554   bool DestIsDeclaration = Dest->isDeclaration();
555
556   if (SrcIsDeclaration) {
557     // If Src is external or if both Src & Dest are external..  Just link the
558     // external globals, we aren't adding anything.
559     if (Src->hasDLLImportStorageClass()) {
560       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
561       if (DestIsDeclaration) {
562         LinkFromSrc = true;
563         LT = Src->getLinkage();
564       }
565     } else if (Dest->hasExternalWeakLinkage()) {
566       // If the Dest is weak, use the source linkage.
567       LinkFromSrc = true;
568       LT = Src->getLinkage();
569     } else {
570       LinkFromSrc = false;
571       LT = Dest->getLinkage();
572     }
573   } else if (DestIsDeclaration && !Dest->hasDLLImportStorageClass()) {
574     // If Dest is external but Src is not:
575     LinkFromSrc = true;
576     LT = Src->getLinkage();
577   } else if (Src->isWeakForLinker()) {
578     // At this point we know that Dest has LinkOnce, External*, Weak, Common,
579     // or DLL* linkage.
580     if (Dest->hasExternalWeakLinkage() ||
581         Dest->hasAvailableExternallyLinkage() ||
582         (Dest->hasLinkOnceLinkage() &&
583          (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
584       LinkFromSrc = true;
585       LT = Src->getLinkage();
586     } else {
587       LinkFromSrc = false;
588       LT = Dest->getLinkage();
589     }
590   } else if (Dest->isWeakForLinker()) {
591     // At this point we know that Src has External* or DLL* linkage.
592     if (Src->hasExternalWeakLinkage()) {
593       LinkFromSrc = false;
594       LT = Dest->getLinkage();
595     } else {
596       LinkFromSrc = true;
597       LT = GlobalValue::ExternalLinkage;
598     }
599   } else {
600     assert((Dest->hasExternalLinkage()  || Dest->hasExternalWeakLinkage()) &&
601            (Src->hasExternalLinkage()   || Src->hasExternalWeakLinkage()) &&
602            "Unexpected linkage type!");
603     return emitError("Linking globals named '" + Src->getName() +
604                  "': symbol multiply defined!");
605   }
606
607   // Compute the visibility. We follow the rules in the System V Application
608   // Binary Interface.
609   assert(!GlobalValue::isLocalLinkage(LT) &&
610          "Symbols with local linkage should not be merged");
611   Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
612     Dest->getVisibility() : Src->getVisibility();
613   return false;
614 }
615
616 /// computeTypeMapping - Loop over all of the linked values to compute type
617 /// mappings.  For example, if we link "extern Foo *x" and "Foo *x = NULL", then
618 /// we have two struct types 'Foo' but one got renamed when the module was
619 /// loaded into the same LLVMContext.
620 void ModuleLinker::computeTypeMapping() {
621   // Incorporate globals.
622   for (Module::global_iterator I = SrcM->global_begin(),
623        E = SrcM->global_end(); I != E; ++I) {
624     GlobalValue *DGV = getLinkedToGlobal(I);
625     if (!DGV) continue;
626
627     if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
628       TypeMap.addTypeMapping(DGV->getType(), I->getType());
629       continue;
630     }
631
632     // Unify the element type of appending arrays.
633     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
634     ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
635     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
636   }
637
638   // Incorporate functions.
639   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
640     if (GlobalValue *DGV = getLinkedToGlobal(I))
641       TypeMap.addTypeMapping(DGV->getType(), I->getType());
642   }
643
644   // Incorporate types by name, scanning all the types in the source module.
645   // At this point, the destination module may have a type "%foo = { i32 }" for
646   // example.  When the source module got loaded into the same LLVMContext, if
647   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
648   TypeFinder SrcStructTypes;
649   SrcStructTypes.run(*SrcM, true);
650   SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
651                                                  SrcStructTypes.end());
652
653   for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
654     StructType *ST = SrcStructTypes[i];
655     if (!ST->hasName()) continue;
656
657     // Check to see if there is a dot in the name followed by a digit.
658     size_t DotPos = ST->getName().rfind('.');
659     if (DotPos == 0 || DotPos == StringRef::npos ||
660         ST->getName().back() == '.' ||
661         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
662       continue;
663
664     // Check to see if the destination module has a struct with the prefix name.
665     if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
666       // Don't use it if this actually came from the source module. They're in
667       // the same LLVMContext after all. Also don't use it unless the type is
668       // actually used in the destination module. This can happen in situations
669       // like this:
670       //
671       //      Module A                         Module B
672       //      --------                         --------
673       //   %Z = type { %A }                %B = type { %C.1 }
674       //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
675       //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
676       //   %C = type { i8* }               %B.3 = type { %C.1 }
677       //
678       // When we link Module B with Module A, the '%B' in Module B is
679       // used. However, that would then use '%C.1'. But when we process '%C.1',
680       // we prefer to take the '%C' version. So we are then left with both
681       // '%C.1' and '%C' being used for the same types. This leads to some
682       // variables using one type and some using the other.
683       if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
684         TypeMap.addTypeMapping(DST, ST);
685   }
686
687   // Don't bother incorporating aliases, they aren't generally typed well.
688
689   // Now that we have discovered all of the type equivalences, get a body for
690   // any 'opaque' types in the dest module that are now resolved.
691   TypeMap.linkDefinedTypeBodies();
692 }
693
694 /// linkAppendingVarProto - If there were any appending global variables, link
695 /// them together now.  Return true on error.
696 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
697                                          GlobalVariable *SrcGV) {
698
699   if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
700     return emitError("Linking globals named '" + SrcGV->getName() +
701            "': can only link appending global with another appending global!");
702
703   ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
704   ArrayType *SrcTy =
705     cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
706   Type *EltTy = DstTy->getElementType();
707
708   // Check to see that they two arrays agree on type.
709   if (EltTy != SrcTy->getElementType())
710     return emitError("Appending variables with different element types!");
711   if (DstGV->isConstant() != SrcGV->isConstant())
712     return emitError("Appending variables linked with different const'ness!");
713
714   if (DstGV->getAlignment() != SrcGV->getAlignment())
715     return emitError(
716              "Appending variables with different alignment need to be linked!");
717
718   if (DstGV->getVisibility() != SrcGV->getVisibility())
719     return emitError(
720             "Appending variables with different visibility need to be linked!");
721
722   if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
723     return emitError(
724         "Appending variables with different unnamed_addr need to be linked!");
725
726   if (DstGV->getSection() != SrcGV->getSection())
727     return emitError(
728           "Appending variables with different section name need to be linked!");
729
730   uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
731   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
732
733   // Create the new global variable.
734   GlobalVariable *NG =
735     new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
736                        DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
737                        DstGV->getThreadLocalMode(),
738                        DstGV->getType()->getAddressSpace());
739
740   // Propagate alignment, visibility and section info.
741   copyGVAttributes(NG, DstGV);
742
743   AppendingVarInfo AVI;
744   AVI.NewGV = NG;
745   AVI.DstInit = DstGV->getInitializer();
746   AVI.SrcInit = SrcGV->getInitializer();
747   AppendingVars.push_back(AVI);
748
749   // Replace any uses of the two global variables with uses of the new
750   // global.
751   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
752
753   DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
754   DstGV->eraseFromParent();
755
756   // Track the source variable so we don't try to link it.
757   DoNotLinkFromSource.insert(SrcGV);
758
759   return false;
760 }
761
762 /// linkGlobalProto - Loop through the global variables in the src module and
763 /// merge them into the dest module.
764 bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
765   GlobalValue *DGV = getLinkedToGlobal(SGV);
766   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
767   bool HasUnnamedAddr = SGV->hasUnnamedAddr();
768
769   if (DGV) {
770     // Concatenation of appending linkage variables is magic and handled later.
771     if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
772       return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
773
774     // Determine whether linkage of these two globals follows the source
775     // module's definition or the destination module's definition.
776     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
777     GlobalValue::VisibilityTypes NV;
778     bool LinkFromSrc = false;
779     if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
780       return true;
781     NewVisibility = NV;
782     HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
783
784     // If we're not linking from the source, then keep the definition that we
785     // have.
786     if (!LinkFromSrc) {
787       // Special case for const propagation.
788       if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
789         if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
790           DGVar->setConstant(true);
791
792       // Set calculated linkage, visibility and unnamed_addr.
793       DGV->setLinkage(NewLinkage);
794       DGV->setVisibility(*NewVisibility);
795       DGV->setUnnamedAddr(HasUnnamedAddr);
796
797       // Make sure to remember this mapping.
798       ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
799
800       // Track the source global so that we don't attempt to copy it over when
801       // processing global initializers.
802       DoNotLinkFromSource.insert(SGV);
803
804       return false;
805     }
806   }
807
808   // No linking to be performed or linking from the source: simply create an
809   // identical version of the symbol over in the dest module... the
810   // initializer will be filled in later by LinkGlobalInits.
811   GlobalVariable *NewDGV =
812     new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
813                        SGV->isConstant(), SGV->getLinkage(), /*init*/nullptr,
814                        SGV->getName(), /*insertbefore*/nullptr,
815                        SGV->getThreadLocalMode(),
816                        SGV->getType()->getAddressSpace());
817   // Propagate alignment, visibility and section info.
818   copyGVAttributes(NewDGV, SGV);
819   if (NewVisibility)
820     NewDGV->setVisibility(*NewVisibility);
821   NewDGV->setUnnamedAddr(HasUnnamedAddr);
822
823   if (DGV) {
824     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
825     DGV->eraseFromParent();
826   }
827
828   // Make sure to remember this mapping.
829   ValueMap[SGV] = NewDGV;
830   return false;
831 }
832
833 /// linkFunctionProto - Link the function in the source module into the
834 /// destination module if needed, setting up mapping information.
835 bool ModuleLinker::linkFunctionProto(Function *SF) {
836   GlobalValue *DGV = getLinkedToGlobal(SF);
837   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
838   bool HasUnnamedAddr = SF->hasUnnamedAddr();
839
840   if (DGV) {
841     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
842     bool LinkFromSrc = false;
843     GlobalValue::VisibilityTypes NV;
844     if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
845       return true;
846     NewVisibility = NV;
847     HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
848
849     if (!LinkFromSrc) {
850       // Set calculated linkage
851       DGV->setLinkage(NewLinkage);
852       DGV->setVisibility(*NewVisibility);
853       DGV->setUnnamedAddr(HasUnnamedAddr);
854
855       // Make sure to remember this mapping.
856       ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
857
858       // Track the function from the source module so we don't attempt to remap
859       // it.
860       DoNotLinkFromSource.insert(SF);
861
862       return false;
863     }
864   }
865
866   // If the function is to be lazily linked, don't create it just yet.
867   // The ValueMaterializerTy will deal with creating it if it's used.
868   if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
869                SF->hasAvailableExternallyLinkage())) {
870     DoNotLinkFromSource.insert(SF);
871     return false;
872   }
873
874   // If there is no linkage to be performed or we are linking from the source,
875   // bring SF over.
876   Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
877                                      SF->getLinkage(), SF->getName(), DstM);
878   copyGVAttributes(NewDF, SF);
879   if (NewVisibility)
880     NewDF->setVisibility(*NewVisibility);
881   NewDF->setUnnamedAddr(HasUnnamedAddr);
882
883   if (DGV) {
884     // Any uses of DF need to change to NewDF, with cast.
885     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
886     DGV->eraseFromParent();
887   }
888
889   ValueMap[SF] = NewDF;
890   return false;
891 }
892
893 /// LinkAliasProto - Set up prototypes for any aliases that come over from the
894 /// source module.
895 bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
896   GlobalValue *DGV = getLinkedToGlobal(SGA);
897   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
898
899   if (DGV) {
900     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
901     GlobalValue::VisibilityTypes NV;
902     bool LinkFromSrc = false;
903     if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
904       return true;
905     NewVisibility = NV;
906
907     if (!LinkFromSrc) {
908       // Set calculated linkage.
909       DGV->setLinkage(NewLinkage);
910       DGV->setVisibility(*NewVisibility);
911
912       // Make sure to remember this mapping.
913       ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
914
915       // Track the alias from the source module so we don't attempt to remap it.
916       DoNotLinkFromSource.insert(SGA);
917
918       return false;
919     }
920   }
921
922   // If there is no linkage to be performed or we're linking from the source,
923   // bring over SGA.
924   auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
925   auto *NewDA = new GlobalAlias(PTy->getElementType(), PTy->getAddressSpace(),
926                                 SGA->getLinkage(), SGA->getName(), DstM);
927   copyGVAttributes(NewDA, SGA);
928   if (NewVisibility)
929     NewDA->setVisibility(*NewVisibility);
930
931   if (DGV)
932     ReplaceWithAlias.push_back(std::make_pair(DGV, NewDA));
933
934   ValueMap[SGA] = NewDA;
935   return false;
936 }
937
938 static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
939   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
940
941   for (unsigned i = 0; i != NumElements; ++i)
942     Dest.push_back(C->getAggregateElement(i));
943 }
944
945 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
946   // Merge the initializer.
947   SmallVector<Constant*, 16> Elements;
948   getArrayElements(AVI.DstInit, Elements);
949
950   Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap, &ValMaterializer);
951   getArrayElements(SrcInit, Elements);
952
953   ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
954   AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
955 }
956
957 /// linkGlobalInits - Update the initializers in the Dest module now that all
958 /// globals that may be referenced are in Dest.
959 void ModuleLinker::linkGlobalInits() {
960   // Loop over all of the globals in the src module, mapping them over as we go
961   for (Module::const_global_iterator I = SrcM->global_begin(),
962        E = SrcM->global_end(); I != E; ++I) {
963
964     // Only process initialized GV's or ones not already in dest.
965     if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
966
967     // Grab destination global variable.
968     GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
969     // Figure out what the initializer looks like in the dest module.
970     DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
971                                  RF_None, &TypeMap, &ValMaterializer));
972   }
973 }
974
975 /// linkFunctionBody - Copy the source function over into the dest function and
976 /// fix up references to values.  At this point we know that Dest is an external
977 /// function, and that Src is not.
978 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
979   assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
980
981   // Go through and convert function arguments over, remembering the mapping.
982   Function::arg_iterator DI = Dst->arg_begin();
983   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
984        I != E; ++I, ++DI) {
985     DI->setName(I->getName());  // Copy the name over.
986
987     // Add a mapping to our mapping.
988     ValueMap[I] = DI;
989   }
990
991   if (Mode == Linker::DestroySource) {
992     // Splice the body of the source function into the dest function.
993     Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
994
995     // At this point, all of the instructions and values of the function are now
996     // copied over.  The only problem is that they are still referencing values in
997     // the Source function as operands.  Loop through all of the operands of the
998     // functions and patch them up to point to the local versions.
999     for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1000       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1001         RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries,
1002                          &TypeMap, &ValMaterializer);
1003
1004   } else {
1005     // Clone the body of the function into the dest function.
1006     SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
1007     CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", nullptr,
1008                       &TypeMap, &ValMaterializer);
1009   }
1010
1011   // There is no need to map the arguments anymore.
1012   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1013        I != E; ++I)
1014     ValueMap.erase(I);
1015
1016 }
1017
1018 static GlobalObject &getGlobalObjectInExpr(Constant &C) {
1019   auto *GO = dyn_cast<GlobalObject>(&C);
1020   if (GO)
1021     return *GO;
1022   auto *GA = dyn_cast<GlobalAlias>(&C);
1023   if (GA)
1024     return *GA->getAliasee();
1025   auto &CE = cast<ConstantExpr>(C);
1026   assert(CE.getOpcode() == Instruction::BitCast ||
1027          CE.getOpcode() == Instruction::AddrSpaceCast);
1028   return getGlobalObjectInExpr(*CE.getOperand(0));
1029 }
1030
1031 /// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
1032 void ModuleLinker::linkAliasBodies() {
1033   for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
1034        I != E; ++I) {
1035     if (DoNotLinkFromSource.count(I))
1036       continue;
1037     if (Constant *Aliasee = I->getAliasee()) {
1038       GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
1039       Constant *Val =
1040           MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1041       DA->setAliasee(&getGlobalObjectInExpr(*Val));
1042     }
1043   }
1044
1045   // Any uses of DGV need to change to NewDA, with cast.
1046   for (auto &Pair : ReplaceWithAlias) {
1047     GlobalValue *DGV = Pair.first;
1048     GlobalAlias *NewDA = Pair.second;
1049
1050     for (auto *User : DGV->users()) {
1051       if (auto *GA = dyn_cast<GlobalAlias>(User)) {
1052         if (GA == NewDA)
1053           report_fatal_error("Linking these modules creates an alias cycle.");
1054       }
1055     }
1056
1057     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
1058     DGV->eraseFromParent();
1059   }
1060 }
1061
1062 /// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
1063 /// module.
1064 void ModuleLinker::linkNamedMDNodes() {
1065   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1066   for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1067        E = SrcM->named_metadata_end(); I != E; ++I) {
1068     // Don't link module flags here. Do them separately.
1069     if (&*I == SrcModFlags) continue;
1070     NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1071     // Add Src elements into Dest node.
1072     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1073       DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
1074                                    RF_None, &TypeMap, &ValMaterializer));
1075   }
1076 }
1077
1078 /// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1079 /// module.
1080 bool ModuleLinker::linkModuleFlagsMetadata() {
1081   // If the source module has no module flags, we are done.
1082   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1083   if (!SrcModFlags) return false;
1084
1085   // If the destination module doesn't have module flags yet, then just copy
1086   // over the source module's flags.
1087   NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1088   if (DstModFlags->getNumOperands() == 0) {
1089     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1090       DstModFlags->addOperand(SrcModFlags->getOperand(I));
1091
1092     return false;
1093   }
1094
1095   // First build a map of the existing module flags and requirements.
1096   DenseMap<MDString*, MDNode*> Flags;
1097   SmallSetVector<MDNode*, 16> Requirements;
1098   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1099     MDNode *Op = DstModFlags->getOperand(I);
1100     ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1101     MDString *ID = cast<MDString>(Op->getOperand(1));
1102
1103     if (Behavior->getZExtValue() == Module::Require) {
1104       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1105     } else {
1106       Flags[ID] = Op;
1107     }
1108   }
1109
1110   // Merge in the flags from the source module, and also collect its set of
1111   // requirements.
1112   bool HasErr = false;
1113   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1114     MDNode *SrcOp = SrcModFlags->getOperand(I);
1115     ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1116     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1117     MDNode *DstOp = Flags.lookup(ID);
1118     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1119
1120     // If this is a requirement, add it and continue.
1121     if (SrcBehaviorValue == Module::Require) {
1122       // If the destination module does not already have this requirement, add
1123       // it.
1124       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1125         DstModFlags->addOperand(SrcOp);
1126       }
1127       continue;
1128     }
1129
1130     // If there is no existing flag with this ID, just add it.
1131     if (!DstOp) {
1132       Flags[ID] = SrcOp;
1133       DstModFlags->addOperand(SrcOp);
1134       continue;
1135     }
1136
1137     // Otherwise, perform a merge.
1138     ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1139     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1140
1141     // If either flag has override behavior, handle it first.
1142     if (DstBehaviorValue == Module::Override) {
1143       // Diagnose inconsistent flags which both have override behavior.
1144       if (SrcBehaviorValue == Module::Override &&
1145           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1146         HasErr |= emitError("linking module flags '" + ID->getString() +
1147                             "': IDs have conflicting override values");
1148       }
1149       continue;
1150     } else if (SrcBehaviorValue == Module::Override) {
1151       // Update the destination flag to that of the source.
1152       DstOp->replaceOperandWith(0, SrcBehavior);
1153       DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1154       continue;
1155     }
1156
1157     // Diagnose inconsistent merge behavior types.
1158     if (SrcBehaviorValue != DstBehaviorValue) {
1159       HasErr |= emitError("linking module flags '" + ID->getString() +
1160                           "': IDs have conflicting behaviors");
1161       continue;
1162     }
1163
1164     // Perform the merge for standard behavior types.
1165     switch (SrcBehaviorValue) {
1166     case Module::Require:
1167     case Module::Override: assert(0 && "not possible"); break;
1168     case Module::Error: {
1169       // Emit an error if the values differ.
1170       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1171         HasErr |= emitError("linking module flags '" + ID->getString() +
1172                             "': IDs have conflicting values");
1173       }
1174       continue;
1175     }
1176     case Module::Warning: {
1177       // Emit a warning if the values differ.
1178       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1179         if (!SuppressWarnings) {
1180           errs() << "WARNING: linking module flags '" << ID->getString()
1181                  << "': IDs have conflicting values";
1182         }
1183       }
1184       continue;
1185     }
1186     case Module::Append: {
1187       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1188       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1189       unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1190       Value **VP, **Values = VP = new Value*[NumOps];
1191       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1192         *VP = DstValue->getOperand(i);
1193       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1194         *VP = SrcValue->getOperand(i);
1195       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1196                                                ArrayRef<Value*>(Values,
1197                                                                 NumOps)));
1198       delete[] Values;
1199       break;
1200     }
1201     case Module::AppendUnique: {
1202       SmallSetVector<Value*, 16> Elts;
1203       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1204       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1205       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1206         Elts.insert(DstValue->getOperand(i));
1207       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1208         Elts.insert(SrcValue->getOperand(i));
1209       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1210                                                ArrayRef<Value*>(Elts.begin(),
1211                                                                 Elts.end())));
1212       break;
1213     }
1214     }
1215   }
1216
1217   // Check all of the requirements.
1218   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1219     MDNode *Requirement = Requirements[I];
1220     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1221     Value *ReqValue = Requirement->getOperand(1);
1222
1223     MDNode *Op = Flags[Flag];
1224     if (!Op || Op->getOperand(2) != ReqValue) {
1225       HasErr |= emitError("linking module flags '" + Flag->getString() +
1226                           "': does not have the required value");
1227       continue;
1228     }
1229   }
1230
1231   return HasErr;
1232 }
1233
1234 bool ModuleLinker::run() {
1235   assert(DstM && "Null destination module");
1236   assert(SrcM && "Null source module");
1237
1238   // Inherit the target data from the source module if the destination module
1239   // doesn't have one already.
1240   if (!DstM->getDataLayout() && SrcM->getDataLayout())
1241     DstM->setDataLayout(SrcM->getDataLayout());
1242
1243   // Copy the target triple from the source to dest if the dest's is empty.
1244   if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1245     DstM->setTargetTriple(SrcM->getTargetTriple());
1246
1247   if (SrcM->getDataLayout() && DstM->getDataLayout() &&
1248       *SrcM->getDataLayout() != *DstM->getDataLayout()) {
1249     if (!SuppressWarnings) {
1250       errs() << "WARNING: Linking two modules of different data layouts: '"
1251              << SrcM->getModuleIdentifier() << "' is '"
1252              << SrcM->getDataLayoutStr() << "' whereas '"
1253              << DstM->getModuleIdentifier() << "' is '"
1254              << DstM->getDataLayoutStr() << "'\n";
1255     }
1256   }
1257   if (!SrcM->getTargetTriple().empty() &&
1258       DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1259     if (!SuppressWarnings) {
1260       errs() << "WARNING: Linking two modules of different target triples: "
1261              << SrcM->getModuleIdentifier() << "' is '"
1262              << SrcM->getTargetTriple() << "' whereas '"
1263              << DstM->getModuleIdentifier() << "' is '"
1264              << DstM->getTargetTriple() << "'\n";
1265     }
1266   }
1267
1268   // Append the module inline asm string.
1269   if (!SrcM->getModuleInlineAsm().empty()) {
1270     if (DstM->getModuleInlineAsm().empty())
1271       DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1272     else
1273       DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1274                                SrcM->getModuleInlineAsm());
1275   }
1276
1277   // Loop over all of the linked values to compute type mappings.
1278   computeTypeMapping();
1279
1280   // Insert all of the globals in src into the DstM module... without linking
1281   // initializers (which could refer to functions not yet mapped over).
1282   for (Module::global_iterator I = SrcM->global_begin(),
1283        E = SrcM->global_end(); I != E; ++I)
1284     if (linkGlobalProto(I))
1285       return true;
1286
1287   // Link the functions together between the two modules, without doing function
1288   // bodies... this just adds external function prototypes to the DstM
1289   // function...  We do this so that when we begin processing function bodies,
1290   // all of the global values that may be referenced are available in our
1291   // ValueMap.
1292   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1293     if (linkFunctionProto(I))
1294       return true;
1295
1296   // If there were any aliases, link them now.
1297   for (Module::alias_iterator I = SrcM->alias_begin(),
1298        E = SrcM->alias_end(); I != E; ++I)
1299     if (linkAliasProto(I))
1300       return true;
1301
1302   for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1303     linkAppendingVarInit(AppendingVars[i]);
1304
1305   // Link in the function bodies that are defined in the source module into
1306   // DstM.
1307   for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1308     // Skip if not linking from source.
1309     if (DoNotLinkFromSource.count(SF)) continue;
1310
1311     Function *DF = cast<Function>(ValueMap[SF]);
1312     if (SF->hasPrefixData()) {
1313       // Link in the prefix data.
1314       DF->setPrefixData(MapValue(
1315           SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1316     }
1317
1318     // Skip if no body (function is external) or materialize.
1319     if (SF->isDeclaration()) {
1320       if (!SF->isMaterializable())
1321         continue;
1322       if (SF->Materialize(&ErrorMsg))
1323         return true;
1324     }
1325
1326     linkFunctionBody(DF, SF);
1327     SF->Dematerialize();
1328   }
1329
1330   // Resolve all uses of aliases with aliasees.
1331   linkAliasBodies();
1332
1333   // Remap all of the named MDNodes in Src into the DstM module. We do this
1334   // after linking GlobalValues so that MDNodes that reference GlobalValues
1335   // are properly remapped.
1336   linkNamedMDNodes();
1337
1338   // Merge the module flags into the DstM module.
1339   if (linkModuleFlagsMetadata())
1340     return true;
1341
1342   // Update the initializers in the DstM module now that all globals that may
1343   // be referenced are in DstM.
1344   linkGlobalInits();
1345
1346   // Process vector of lazily linked in functions.
1347   bool LinkedInAnyFunctions;
1348   do {
1349     LinkedInAnyFunctions = false;
1350
1351     for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1352         E = LazilyLinkFunctions.end(); I != E; ++I) {
1353       Function *SF = *I;
1354       if (!SF)
1355         continue;
1356
1357       Function *DF = cast<Function>(ValueMap[SF]);
1358       if (SF->hasPrefixData()) {
1359         // Link in the prefix data.
1360         DF->setPrefixData(MapValue(SF->getPrefixData(),
1361                                    ValueMap,
1362                                    RF_None,
1363                                    &TypeMap,
1364                                    &ValMaterializer));
1365       }
1366
1367       // Materialize if necessary.
1368       if (SF->isDeclaration()) {
1369         if (!SF->isMaterializable())
1370           continue;
1371         if (SF->Materialize(&ErrorMsg))
1372           return true;
1373       }
1374
1375       // Erase from vector *before* the function body is linked - linkFunctionBody could
1376       // invalidate I.
1377       LazilyLinkFunctions.erase(I);
1378
1379       // Link in function body.
1380       linkFunctionBody(DF, SF);
1381       SF->Dematerialize();
1382
1383       // Set flag to indicate we may have more functions to lazily link in
1384       // since we linked in a function.
1385       LinkedInAnyFunctions = true;
1386       break;
1387     }
1388   } while (LinkedInAnyFunctions);
1389
1390   // Now that all of the types from the source are used, resolve any structs
1391   // copied over to the dest that didn't exist there.
1392   TypeMap.linkDefinedTypeBodies();
1393
1394   return false;
1395 }
1396
1397 Linker::Linker(Module *M, bool SuppressWarnings)
1398     : Composite(M), SuppressWarnings(SuppressWarnings) {
1399   TypeFinder StructTypes;
1400   StructTypes.run(*M, true);
1401   IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1402 }
1403
1404 Linker::~Linker() {
1405 }
1406
1407 void Linker::deleteModule() {
1408   delete Composite;
1409   Composite = nullptr;
1410 }
1411
1412 bool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) {
1413   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode,
1414                          SuppressWarnings);
1415   if (TheLinker.run()) {
1416     if (ErrorMsg)
1417       *ErrorMsg = TheLinker.ErrorMsg;
1418     return true;
1419   }
1420   return false;
1421 }
1422
1423 //===----------------------------------------------------------------------===//
1424 // LinkModules entrypoint.
1425 //===----------------------------------------------------------------------===//
1426
1427 /// LinkModules - This function links two modules together, with the resulting
1428 /// Dest module modified to be the composite of the two input modules.  If an
1429 /// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1430 /// the problem.  Upon failure, the Dest module could be in a modified state,
1431 /// and shouldn't be relied on to be consistent.
1432 bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1433                          std::string *ErrorMsg) {
1434   Linker L(Dest);
1435   return L.linkInModule(Src, Mode, ErrorMsg);
1436 }
1437
1438 //===----------------------------------------------------------------------===//
1439 // C API.
1440 //===----------------------------------------------------------------------===//
1441
1442 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1443                          LLVMLinkerMode Mode, char **OutMessages) {
1444   std::string Messages;
1445   LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
1446                                         Mode, OutMessages? &Messages : nullptr);
1447   if (OutMessages)
1448     *OutMessages = strdup(Messages.c_str());
1449   return Result;
1450 }