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