LLVM API Documentation

LinkModules.cpp
Go to the documentation of this file.
00001 //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the LLVM module linker.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Linker/Linker.h"
00015 #include "llvm-c/Linker.h"
00016 #include "llvm/ADT/Optional.h"
00017 #include "llvm/ADT/SetVector.h"
00018 #include "llvm/ADT/SmallString.h"
00019 #include "llvm/IR/Constants.h"
00020 #include "llvm/IR/Module.h"
00021 #include "llvm/IR/TypeFinder.h"
00022 #include "llvm/Support/CommandLine.h"
00023 #include "llvm/Support/Debug.h"
00024 #include "llvm/Support/raw_ostream.h"
00025 #include "llvm/Transforms/Utils/Cloning.h"
00026 #include <cctype>
00027 #include <tuple>
00028 using namespace llvm;
00029 
00030 
00031 //===----------------------------------------------------------------------===//
00032 // TypeMap implementation.
00033 //===----------------------------------------------------------------------===//
00034 
00035 namespace {
00036   typedef SmallPtrSet<StructType*, 32> TypeSet;
00037 
00038 class TypeMapTy : public ValueMapTypeRemapper {
00039   /// MappedTypes - This is a mapping from a source type to a destination type
00040   /// to use.
00041   DenseMap<Type*, Type*> MappedTypes;
00042 
00043   /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
00044   /// we speculatively add types to MappedTypes, but keep track of them here in
00045   /// case we need to roll back.
00046   SmallVector<Type*, 16> SpeculativeTypes;
00047 
00048   /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
00049   /// source module that are mapped to an opaque struct in the destination
00050   /// module.
00051   SmallVector<StructType*, 16> SrcDefinitionsToResolve;
00052 
00053   /// DstResolvedOpaqueTypes - This is the set of opaque types in the
00054   /// destination modules who are getting a body from the source module.
00055   SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
00056 
00057 public:
00058   TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {}
00059 
00060   TypeSet &DstStructTypesSet;
00061   /// addTypeMapping - Indicate that the specified type in the destination
00062   /// module is conceptually equivalent to the specified type in the source
00063   /// module.
00064   void addTypeMapping(Type *DstTy, Type *SrcTy);
00065 
00066   /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
00067   /// module from a type definition in the source module.
00068   void linkDefinedTypeBodies();
00069 
00070   /// get - Return the mapped type to use for the specified input type from the
00071   /// source module.
00072   Type *get(Type *SrcTy);
00073 
00074   FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
00075 
00076   /// dump - Dump out the type map for debugging purposes.
00077   void dump() const {
00078     for (DenseMap<Type*, Type*>::const_iterator
00079            I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
00080       dbgs() << "TypeMap: ";
00081       I->first->print(dbgs());
00082       dbgs() << " => ";
00083       I->second->print(dbgs());
00084       dbgs() << '\n';
00085     }
00086   }
00087 
00088 private:
00089   Type *getImpl(Type *T);
00090   /// remapType - Implement the ValueMapTypeRemapper interface.
00091   Type *remapType(Type *SrcTy) override {
00092     return get(SrcTy);
00093   }
00094 
00095   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
00096 };
00097 }
00098 
00099 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
00100   Type *&Entry = MappedTypes[SrcTy];
00101   if (Entry) return;
00102 
00103   if (DstTy == SrcTy) {
00104     Entry = DstTy;
00105     return;
00106   }
00107 
00108   // Check to see if these types are recursively isomorphic and establish a
00109   // mapping between them if so.
00110   if (!areTypesIsomorphic(DstTy, SrcTy)) {
00111     // Oops, they aren't isomorphic.  Just discard this request by rolling out
00112     // any speculative mappings we've established.
00113     for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
00114       MappedTypes.erase(SpeculativeTypes[i]);
00115   }
00116   SpeculativeTypes.clear();
00117 }
00118 
00119 /// areTypesIsomorphic - Recursively walk this pair of types, returning true
00120 /// if they are isomorphic, false if they are not.
00121 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
00122   // Two types with differing kinds are clearly not isomorphic.
00123   if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
00124 
00125   // If we have an entry in the MappedTypes table, then we have our answer.
00126   Type *&Entry = MappedTypes[SrcTy];
00127   if (Entry)
00128     return Entry == DstTy;
00129 
00130   // Two identical types are clearly isomorphic.  Remember this
00131   // non-speculatively.
00132   if (DstTy == SrcTy) {
00133     Entry = DstTy;
00134     return true;
00135   }
00136 
00137   // Okay, we have two types with identical kinds that we haven't seen before.
00138 
00139   // If this is an opaque struct type, special case it.
00140   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
00141     // Mapping an opaque type to any struct, just keep the dest struct.
00142     if (SSTy->isOpaque()) {
00143       Entry = DstTy;
00144       SpeculativeTypes.push_back(SrcTy);
00145       return true;
00146     }
00147 
00148     // Mapping a non-opaque source type to an opaque dest.  If this is the first
00149     // type that we're mapping onto this destination type then we succeed.  Keep
00150     // the dest, but fill it in later.  This doesn't need to be speculative.  If
00151     // this is the second (different) type that we're trying to map onto the
00152     // same opaque type then we fail.
00153     if (cast<StructType>(DstTy)->isOpaque()) {
00154       // We can only map one source type onto the opaque destination type.
00155       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
00156         return false;
00157       SrcDefinitionsToResolve.push_back(SSTy);
00158       Entry = DstTy;
00159       return true;
00160     }
00161   }
00162 
00163   // If the number of subtypes disagree between the two types, then we fail.
00164   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
00165     return false;
00166 
00167   // Fail if any of the extra properties (e.g. array size) of the type disagree.
00168   if (isa<IntegerType>(DstTy))
00169     return false;  // bitwidth disagrees.
00170   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
00171     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
00172       return false;
00173 
00174   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
00175     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
00176       return false;
00177   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
00178     StructType *SSTy = cast<StructType>(SrcTy);
00179     if (DSTy->isLiteral() != SSTy->isLiteral() ||
00180         DSTy->isPacked() != SSTy->isPacked())
00181       return false;
00182   } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
00183     if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
00184       return false;
00185   } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
00186     if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
00187       return false;
00188   }
00189 
00190   // Otherwise, we speculate that these two types will line up and recursively
00191   // check the subelements.
00192   Entry = DstTy;
00193   SpeculativeTypes.push_back(SrcTy);
00194 
00195   for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
00196     if (!areTypesIsomorphic(DstTy->getContainedType(i),
00197                             SrcTy->getContainedType(i)))
00198       return false;
00199 
00200   // If everything seems to have lined up, then everything is great.
00201   return true;
00202 }
00203 
00204 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
00205 /// module from a type definition in the source module.
00206 void TypeMapTy::linkDefinedTypeBodies() {
00207   SmallVector<Type*, 16> Elements;
00208   SmallString<16> TmpName;
00209 
00210   // Note that processing entries in this loop (calling 'get') can add new
00211   // entries to the SrcDefinitionsToResolve vector.
00212   while (!SrcDefinitionsToResolve.empty()) {
00213     StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
00214     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
00215 
00216     // TypeMap is a many-to-one mapping, if there were multiple types that
00217     // provide a body for DstSTy then previous iterations of this loop may have
00218     // already handled it.  Just ignore this case.
00219     if (!DstSTy->isOpaque()) continue;
00220     assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
00221 
00222     // Map the body of the source type over to a new body for the dest type.
00223     Elements.resize(SrcSTy->getNumElements());
00224     for (unsigned i = 0, e = Elements.size(); i != e; ++i)
00225       Elements[i] = getImpl(SrcSTy->getElementType(i));
00226 
00227     DstSTy->setBody(Elements, SrcSTy->isPacked());
00228 
00229     // If DstSTy has no name or has a longer name than STy, then viciously steal
00230     // STy's name.
00231     if (!SrcSTy->hasName()) continue;
00232     StringRef SrcName = SrcSTy->getName();
00233 
00234     if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
00235       TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
00236       SrcSTy->setName("");
00237       DstSTy->setName(TmpName.str());
00238       TmpName.clear();
00239     }
00240   }
00241 
00242   DstResolvedOpaqueTypes.clear();
00243 }
00244 
00245 /// get - Return the mapped type to use for the specified input type from the
00246 /// source module.
00247 Type *TypeMapTy::get(Type *Ty) {
00248   Type *Result = getImpl(Ty);
00249 
00250   // If this caused a reference to any struct type, resolve it before returning.
00251   if (!SrcDefinitionsToResolve.empty())
00252     linkDefinedTypeBodies();
00253   return Result;
00254 }
00255 
00256 /// getImpl - This is the recursive version of get().
00257 Type *TypeMapTy::getImpl(Type *Ty) {
00258   // If we already have an entry for this type, return it.
00259   Type **Entry = &MappedTypes[Ty];
00260   if (*Entry) return *Entry;
00261 
00262   // If this is not a named struct type, then just map all of the elements and
00263   // then rebuild the type from inside out.
00264   if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
00265     // If there are no element types to map, then the type is itself.  This is
00266     // true for the anonymous {} struct, things like 'float', integers, etc.
00267     if (Ty->getNumContainedTypes() == 0)
00268       return *Entry = Ty;
00269 
00270     // Remap all of the elements, keeping track of whether any of them change.
00271     bool AnyChange = false;
00272     SmallVector<Type*, 4> ElementTypes;
00273     ElementTypes.resize(Ty->getNumContainedTypes());
00274     for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
00275       ElementTypes[i] = getImpl(Ty->getContainedType(i));
00276       AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
00277     }
00278 
00279     // If we found our type while recursively processing stuff, just use it.
00280     Entry = &MappedTypes[Ty];
00281     if (*Entry) return *Entry;
00282 
00283     // If all of the element types mapped directly over, then the type is usable
00284     // as-is.
00285     if (!AnyChange)
00286       return *Entry = Ty;
00287 
00288     // Otherwise, rebuild a modified type.
00289     switch (Ty->getTypeID()) {
00290     default: llvm_unreachable("unknown derived type to remap");
00291     case Type::ArrayTyID:
00292       return *Entry = ArrayType::get(ElementTypes[0],
00293                                      cast<ArrayType>(Ty)->getNumElements());
00294     case Type::VectorTyID:
00295       return *Entry = VectorType::get(ElementTypes[0],
00296                                       cast<VectorType>(Ty)->getNumElements());
00297     case Type::PointerTyID:
00298       return *Entry = PointerType::get(ElementTypes[0],
00299                                       cast<PointerType>(Ty)->getAddressSpace());
00300     case Type::FunctionTyID:
00301       return *Entry = FunctionType::get(ElementTypes[0],
00302                                         makeArrayRef(ElementTypes).slice(1),
00303                                         cast<FunctionType>(Ty)->isVarArg());
00304     case Type::StructTyID:
00305       // Note that this is only reached for anonymous structs.
00306       return *Entry = StructType::get(Ty->getContext(), ElementTypes,
00307                                       cast<StructType>(Ty)->isPacked());
00308     }
00309   }
00310 
00311   // Otherwise, this is an unmapped named struct.  If the struct can be directly
00312   // mapped over, just use it as-is.  This happens in a case when the linked-in
00313   // module has something like:
00314   //   %T = type {%T*, i32}
00315   //   @GV = global %T* null
00316   // where T does not exist at all in the destination module.
00317   //
00318   // The other case we watch for is when the type is not in the destination
00319   // module, but that it has to be rebuilt because it refers to something that
00320   // is already mapped.  For example, if the destination module has:
00321   //  %A = type { i32 }
00322   // and the source module has something like
00323   //  %A' = type { i32 }
00324   //  %B = type { %A'* }
00325   //  @GV = global %B* null
00326   // then we want to create a new type: "%B = type { %A*}" and have it take the
00327   // pristine "%B" name from the source module.
00328   //
00329   // To determine which case this is, we have to recursively walk the type graph
00330   // speculating that we'll be able to reuse it unmodified.  Only if this is
00331   // safe would we map the entire thing over.  Because this is an optimization,
00332   // and is not required for the prettiness of the linked module, we just skip
00333   // it and always rebuild a type here.
00334   StructType *STy = cast<StructType>(Ty);
00335 
00336   // If the type is opaque, we can just use it directly.
00337   if (STy->isOpaque()) {
00338     // A named structure type from src module is used. Add it to the Set of
00339     // identified structs in the destination module.
00340     DstStructTypesSet.insert(STy);
00341     return *Entry = STy;
00342   }
00343 
00344   // Otherwise we create a new type and resolve its body later.  This will be
00345   // resolved by the top level of get().
00346   SrcDefinitionsToResolve.push_back(STy);
00347   StructType *DTy = StructType::create(STy->getContext());
00348   // A new identified structure type was created. Add it to the set of
00349   // identified structs in the destination module.
00350   DstStructTypesSet.insert(DTy);
00351   DstResolvedOpaqueTypes.insert(DTy);
00352   return *Entry = DTy;
00353 }
00354 
00355 //===----------------------------------------------------------------------===//
00356 // ModuleLinker implementation.
00357 //===----------------------------------------------------------------------===//
00358 
00359 namespace {
00360   class ModuleLinker;
00361 
00362   /// ValueMaterializerTy - Creates prototypes for functions that are lazily
00363   /// linked on the fly. This speeds up linking for modules with many
00364   /// lazily linked functions of which few get used.
00365   class ValueMaterializerTy : public ValueMaterializer {
00366     TypeMapTy &TypeMap;
00367     Module *DstM;
00368     std::vector<Function*> &LazilyLinkFunctions;
00369   public:
00370     ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
00371                         std::vector<Function*> &LazilyLinkFunctions) :
00372       ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
00373       LazilyLinkFunctions(LazilyLinkFunctions) {
00374     }
00375 
00376     Value *materializeValueFor(Value *V) override;
00377   };
00378 
00379   /// ModuleLinker - This is an implementation class for the LinkModules
00380   /// function, which is the entrypoint for this file.
00381   class ModuleLinker {
00382     Module *DstM, *SrcM;
00383 
00384     TypeMapTy TypeMap;
00385     ValueMaterializerTy ValMaterializer;
00386 
00387     /// ValueMap - Mapping of values from what they used to be in Src, to what
00388     /// they are now in DstM.  ValueToValueMapTy is a ValueMap, which involves
00389     /// some overhead due to the use of Value handles which the Linker doesn't
00390     /// actually need, but this allows us to reuse the ValueMapper code.
00391     ValueToValueMapTy ValueMap;
00392 
00393     struct AppendingVarInfo {
00394       GlobalVariable *NewGV;  // New aggregate global in dest module.
00395       Constant *DstInit;      // Old initializer from dest module.
00396       Constant *SrcInit;      // Old initializer from src module.
00397     };
00398 
00399     std::vector<AppendingVarInfo> AppendingVars;
00400 
00401     unsigned Mode; // Mode to treat source module.
00402 
00403     // Set of items not to link in from source.
00404     SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
00405 
00406     // Vector of functions to lazily link in.
00407     std::vector<Function*> LazilyLinkFunctions;
00408 
00409     bool SuppressWarnings;
00410 
00411   public:
00412     std::string ErrorMsg;
00413 
00414     ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, unsigned mode,
00415                  bool SuppressWarnings=false)
00416         : DstM(dstM), SrcM(srcM), TypeMap(Set),
00417           ValMaterializer(TypeMap, DstM, LazilyLinkFunctions), Mode(mode),
00418           SuppressWarnings(SuppressWarnings) {}
00419 
00420     bool run();
00421 
00422   private:
00423     bool shouldLinkFromSource(const GlobalValue &Dest, const GlobalValue &Src);
00424 
00425     /// emitError - Helper method for setting a message and returning an error
00426     /// code.
00427     bool emitError(const Twine &Message) {
00428       ErrorMsg = Message.str();
00429       return true;
00430     }
00431 
00432     bool getComdatLeader(Module *M, StringRef ComdatName,
00433                          const GlobalVariable *&GVar);
00434     bool computeResultingSelectionKind(StringRef ComdatName,
00435                                        Comdat::SelectionKind Src,
00436                                        Comdat::SelectionKind Dst,
00437                                        Comdat::SelectionKind &Result,
00438                                        bool &LinkFromSrc);
00439     std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
00440         ComdatsChosen;
00441     bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
00442                          bool &LinkFromSrc);
00443 
00444     /// getLinkageResult - This analyzes the two global values and determines
00445     /// what the result will look like in the destination module.
00446     bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
00447                           GlobalValue::LinkageTypes &LT,
00448                           GlobalValue::VisibilityTypes &Vis,
00449                           bool &LinkFromSrc);
00450 
00451     /// getLinkedToGlobal - Given a global in the source module, return the
00452     /// global in the destination module that is being linked to, if any.
00453     GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
00454       // If the source has no name it can't link.  If it has local linkage,
00455       // there is no name match-up going on.
00456       if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
00457         return nullptr;
00458 
00459       // Otherwise see if we have a match in the destination module's symtab.
00460       GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
00461       if (!DGV) return nullptr;
00462 
00463       // If we found a global with the same name in the dest module, but it has
00464       // internal linkage, we are really not doing any linkage here.
00465       if (DGV->hasLocalLinkage())
00466         return nullptr;
00467 
00468       // Otherwise, we do in fact link to the destination global.
00469       return DGV;
00470     }
00471 
00472     void computeTypeMapping();
00473 
00474     void upgradeMismatchedGlobalArray(StringRef Name);
00475     void upgradeMismatchedGlobals();
00476 
00477     bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
00478     bool linkGlobalProto(GlobalVariable *SrcGV);
00479     bool linkFunctionProto(Function *SrcF);
00480     bool linkAliasProto(GlobalAlias *SrcA);
00481     bool linkModuleFlagsMetadata();
00482 
00483     void linkAppendingVarInit(const AppendingVarInfo &AVI);
00484     void linkGlobalInits();
00485     void linkFunctionBody(Function *Dst, Function *Src);
00486     void linkAliasBodies();
00487     void linkNamedMDNodes();
00488   };
00489 }
00490 
00491 /// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
00492 /// in the symbol table.  This is good for all clients except for us.  Go
00493 /// through the trouble to force this back.
00494 static void forceRenaming(GlobalValue *GV, StringRef Name) {
00495   // If the global doesn't force its name or if it already has the right name,
00496   // there is nothing for us to do.
00497   if (GV->hasLocalLinkage() || GV->getName() == Name)
00498     return;
00499 
00500   Module *M = GV->getParent();
00501 
00502   // If there is a conflict, rename the conflict.
00503   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
00504     GV->takeName(ConflictGV);
00505     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
00506     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
00507   } else {
00508     GV->setName(Name);              // Force the name back
00509   }
00510 }
00511 
00512 /// copyGVAttributes - copy additional attributes (those not needed to construct
00513 /// a GlobalValue) from the SrcGV to the DestGV.
00514 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
00515   // Use the maximum alignment, rather than just copying the alignment of SrcGV.
00516   auto *DestGO = dyn_cast<GlobalObject>(DestGV);
00517   unsigned Alignment;
00518   if (DestGO)
00519     Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
00520 
00521   DestGV->copyAttributesFrom(SrcGV);
00522 
00523   if (DestGO)
00524     DestGO->setAlignment(Alignment);
00525 
00526   forceRenaming(DestGV, SrcGV->getName());
00527 }
00528 
00529 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
00530                                GlobalValue::VisibilityTypes b) {
00531   if (a == GlobalValue::HiddenVisibility)
00532     return false;
00533   if (b == GlobalValue::HiddenVisibility)
00534     return true;
00535   if (a == GlobalValue::ProtectedVisibility)
00536     return false;
00537   if (b == GlobalValue::ProtectedVisibility)
00538     return true;
00539   return false;
00540 }
00541 
00542 Value *ValueMaterializerTy::materializeValueFor(Value *V) {
00543   Function *SF = dyn_cast<Function>(V);
00544   if (!SF)
00545     return nullptr;
00546 
00547   Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
00548                                   SF->getLinkage(), SF->getName(), DstM);
00549   copyGVAttributes(DF, SF);
00550 
00551   if (Comdat *SC = SF->getComdat()) {
00552     Comdat *DC = DstM->getOrInsertComdat(SC->getName());
00553     DF->setComdat(DC);
00554   }
00555 
00556   LazilyLinkFunctions.push_back(SF);
00557   return DF;
00558 }
00559 
00560 bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
00561                                    const GlobalVariable *&GVar) {
00562   const GlobalValue *GVal = M->getNamedValue(ComdatName);
00563   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
00564     GVal = GA->getBaseObject();
00565     if (!GVal)
00566       // We cannot resolve the size of the aliasee yet.
00567       return emitError("Linking COMDATs named '" + ComdatName +
00568                        "': COMDAT key involves incomputable alias size.");
00569   }
00570 
00571   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
00572   if (!GVar)
00573     return emitError(
00574         "Linking COMDATs named '" + ComdatName +
00575         "': GlobalVariable required for data dependent selection!");
00576 
00577   return false;
00578 }
00579 
00580 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
00581                                                  Comdat::SelectionKind Src,
00582                                                  Comdat::SelectionKind Dst,
00583                                                  Comdat::SelectionKind &Result,
00584                                                  bool &LinkFromSrc) {
00585   // The ability to mix Comdat::SelectionKind::Any with
00586   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
00587   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
00588                          Dst == Comdat::SelectionKind::Largest;
00589   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
00590                          Src == Comdat::SelectionKind::Largest;
00591   if (DstAnyOrLargest && SrcAnyOrLargest) {
00592     if (Dst == Comdat::SelectionKind::Largest ||
00593         Src == Comdat::SelectionKind::Largest)
00594       Result = Comdat::SelectionKind::Largest;
00595     else
00596       Result = Comdat::SelectionKind::Any;
00597   } else if (Src == Dst) {
00598     Result = Dst;
00599   } else {
00600     return emitError("Linking COMDATs named '" + ComdatName +
00601                      "': invalid selection kinds!");
00602   }
00603 
00604   switch (Result) {
00605   case Comdat::SelectionKind::Any:
00606     // Go with Dst.
00607     LinkFromSrc = false;
00608     break;
00609   case Comdat::SelectionKind::NoDuplicates:
00610     return emitError("Linking COMDATs named '" + ComdatName +
00611                      "': noduplicates has been violated!");
00612   case Comdat::SelectionKind::ExactMatch:
00613   case Comdat::SelectionKind::Largest:
00614   case Comdat::SelectionKind::SameSize: {
00615     const GlobalVariable *DstGV;
00616     const GlobalVariable *SrcGV;
00617     if (getComdatLeader(DstM, ComdatName, DstGV) ||
00618         getComdatLeader(SrcM, ComdatName, SrcGV))
00619       return true;
00620 
00621     const DataLayout *DstDL = DstM->getDataLayout();
00622     const DataLayout *SrcDL = SrcM->getDataLayout();
00623     if (!DstDL || !SrcDL) {
00624       return emitError(
00625           "Linking COMDATs named '" + ComdatName +
00626           "': can't do size dependent selection without DataLayout!");
00627     }
00628     uint64_t DstSize =
00629         DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
00630     uint64_t SrcSize =
00631         SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
00632     if (Result == Comdat::SelectionKind::ExactMatch) {
00633       if (SrcGV->getInitializer() != DstGV->getInitializer())
00634         return emitError("Linking COMDATs named '" + ComdatName +
00635                          "': ExactMatch violated!");
00636       LinkFromSrc = false;
00637     } else if (Result == Comdat::SelectionKind::Largest) {
00638       LinkFromSrc = SrcSize > DstSize;
00639     } else if (Result == Comdat::SelectionKind::SameSize) {
00640       if (SrcSize != DstSize)
00641         return emitError("Linking COMDATs named '" + ComdatName +
00642                          "': SameSize violated!");
00643       LinkFromSrc = false;
00644     } else {
00645       llvm_unreachable("unknown selection kind");
00646     }
00647     break;
00648   }
00649   }
00650 
00651   return false;
00652 }
00653 
00654 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
00655                                    Comdat::SelectionKind &Result,
00656                                    bool &LinkFromSrc) {
00657   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
00658   StringRef ComdatName = SrcC->getName();
00659   Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
00660   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
00661 
00662   if (DstCI == ComdatSymTab.end()) {
00663     // Use the comdat if it is only available in one of the modules.
00664     LinkFromSrc = true;
00665     Result = SSK;
00666     return false;
00667   }
00668 
00669   const Comdat *DstC = &DstCI->second;
00670   Comdat::SelectionKind DSK = DstC->getSelectionKind();
00671   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
00672                                        LinkFromSrc);
00673 }
00674 
00675 // FIXME: Duplicated from the gold plugin. This should be refactored somewhere.
00676 static bool isDeclaration(const GlobalValue &V) {
00677   if (V.hasAvailableExternallyLinkage())
00678     return true;
00679 
00680   if (V.isMaterializable())
00681     return false;
00682 
00683   return V.isDeclaration();
00684 }
00685 
00686 bool ModuleLinker::shouldLinkFromSource(const GlobalValue &Dest,
00687                                         const GlobalValue &Src) {
00688   bool SrcIsDeclaration = isDeclaration(Src);
00689   bool DestIsDeclaration = isDeclaration(Dest);
00690 
00691   // FIXME: Make datalayout mandatory and just use getDataLayout().
00692   DataLayout DL(Dest.getParent());
00693 
00694   if (SrcIsDeclaration) {
00695     // If Src is external or if both Src & Dest are external..  Just link the
00696     // external globals, we aren't adding anything.
00697     if (Src.hasDLLImportStorageClass())
00698       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
00699       return DestIsDeclaration;
00700     // If the Dest is weak, use the source linkage.
00701     return Dest.hasExternalWeakLinkage();
00702   }
00703 
00704   if (DestIsDeclaration)
00705     // If Dest is external but Src is not:
00706     return true;
00707 
00708   if (Src.hasCommonLinkage()) {
00709     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage())
00710       return true;
00711 
00712     if (!Dest.hasCommonLinkage())
00713       return false;
00714 
00715     uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
00716     uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
00717     return SrcSize > DestSize;
00718   }
00719 
00720   if (Src.isWeakForLinker()) {
00721     assert(!Dest.hasExternalWeakLinkage());
00722     assert(!Dest.hasAvailableExternallyLinkage());
00723 
00724     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage())
00725       return true;
00726 
00727     return false;
00728   }
00729 
00730   if (Dest.isWeakForLinker()) {
00731     assert(Src.hasExternalLinkage());
00732     return true;
00733   }
00734 
00735   assert(!Src.hasExternalWeakLinkage());
00736   assert(!Dest.hasExternalWeakLinkage());
00737   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
00738          "Unexpected linkage type!");
00739   return emitError("Linking globals named '" + Src.getName() +
00740                    "': symbol multiply defined!");
00741 }
00742 
00743 /// This analyzes the two global values and determines what the result will look
00744 /// like in the destination module. In particular, it computes the resultant
00745 /// linkage type and visibility, computes whether the global in the source
00746 /// should be copied over to the destination (replacing the existing one), and
00747 /// computes whether this linkage is an error or not.
00748 bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
00749                                     GlobalValue::LinkageTypes &LT,
00750                                     GlobalValue::VisibilityTypes &Vis,
00751                                     bool &LinkFromSrc) {
00752   assert(Dest && "Must have two globals being queried");
00753   assert(!Src->hasLocalLinkage() &&
00754          "If Src has internal linkage, Dest shouldn't be set!");
00755 
00756   assert(ErrorMsg.empty());
00757   LinkFromSrc = shouldLinkFromSource(*Dest, *Src);
00758   if (!ErrorMsg.empty())
00759     return true;
00760 
00761   if (LinkFromSrc)
00762     LT = Src->getLinkage();
00763   else
00764     LT = Dest->getLinkage();
00765 
00766   // Compute the visibility. We follow the rules in the System V Application
00767   // Binary Interface.
00768   assert(!GlobalValue::isLocalLinkage(LT) &&
00769          "Symbols with local linkage should not be merged");
00770   Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
00771     Dest->getVisibility() : Src->getVisibility();
00772   return false;
00773 }
00774 
00775 /// computeTypeMapping - Loop over all of the linked values to compute type
00776 /// mappings.  For example, if we link "extern Foo *x" and "Foo *x = NULL", then
00777 /// we have two struct types 'Foo' but one got renamed when the module was
00778 /// loaded into the same LLVMContext.
00779 void ModuleLinker::computeTypeMapping() {
00780   // Incorporate globals.
00781   for (Module::global_iterator I = SrcM->global_begin(),
00782        E = SrcM->global_end(); I != E; ++I) {
00783     GlobalValue *DGV = getLinkedToGlobal(I);
00784     if (!DGV) continue;
00785 
00786     if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
00787       TypeMap.addTypeMapping(DGV->getType(), I->getType());
00788       continue;
00789     }
00790 
00791     // Unify the element type of appending arrays.
00792     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
00793     ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
00794     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
00795   }
00796 
00797   // Incorporate functions.
00798   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
00799     if (GlobalValue *DGV = getLinkedToGlobal(I))
00800       TypeMap.addTypeMapping(DGV->getType(), I->getType());
00801   }
00802 
00803   // Incorporate types by name, scanning all the types in the source module.
00804   // At this point, the destination module may have a type "%foo = { i32 }" for
00805   // example.  When the source module got loaded into the same LLVMContext, if
00806   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
00807   TypeFinder SrcStructTypes;
00808   SrcStructTypes.run(*SrcM, true);
00809   SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
00810                                                  SrcStructTypes.end());
00811 
00812   for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
00813     StructType *ST = SrcStructTypes[i];
00814     if (!ST->hasName()) continue;
00815 
00816     // Check to see if there is a dot in the name followed by a digit.
00817     size_t DotPos = ST->getName().rfind('.');
00818     if (DotPos == 0 || DotPos == StringRef::npos ||
00819         ST->getName().back() == '.' ||
00820         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
00821       continue;
00822 
00823     // Check to see if the destination module has a struct with the prefix name.
00824     if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
00825       // Don't use it if this actually came from the source module. They're in
00826       // the same LLVMContext after all. Also don't use it unless the type is
00827       // actually used in the destination module. This can happen in situations
00828       // like this:
00829       //
00830       //      Module A                         Module B
00831       //      --------                         --------
00832       //   %Z = type { %A }                %B = type { %C.1 }
00833       //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
00834       //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
00835       //   %C = type { i8* }               %B.3 = type { %C.1 }
00836       //
00837       // When we link Module B with Module A, the '%B' in Module B is
00838       // used. However, that would then use '%C.1'. But when we process '%C.1',
00839       // we prefer to take the '%C' version. So we are then left with both
00840       // '%C.1' and '%C' being used for the same types. This leads to some
00841       // variables using one type and some using the other.
00842       if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
00843         TypeMap.addTypeMapping(DST, ST);
00844   }
00845 
00846   // Don't bother incorporating aliases, they aren't generally typed well.
00847 
00848   // Now that we have discovered all of the type equivalences, get a body for
00849   // any 'opaque' types in the dest module that are now resolved.
00850   TypeMap.linkDefinedTypeBodies();
00851 }
00852 
00853 static void upgradeGlobalArray(GlobalVariable *GV) {
00854   ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
00855   StructType *OldTy = cast<StructType>(ATy->getElementType());
00856   assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
00857 
00858   // Get the upgraded 3 element type.
00859   PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
00860   Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
00861                   VoidPtrTy};
00862   StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
00863 
00864   // Build new constants with a null third field filled in.
00865   Constant *OldInitC = GV->getInitializer();
00866   ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
00867   if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
00868     // Invalid initializer; give up.
00869     return;
00870   std::vector<Constant *> Initializers;
00871   if (OldInit && OldInit->getNumOperands()) {
00872     Value *Null = Constant::getNullValue(VoidPtrTy);
00873     for (Use &U : OldInit->operands()) {
00874       ConstantStruct *Init = cast<ConstantStruct>(U.get());
00875       Initializers.push_back(ConstantStruct::get(
00876           NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
00877     }
00878   }
00879   assert(Initializers.size() == ATy->getNumElements() &&
00880          "Failed to copy all array elements");
00881 
00882   // Replace the old GV with a new one.
00883   ATy = ArrayType::get(NewTy, Initializers.size());
00884   Constant *NewInit = ConstantArray::get(ATy, Initializers);
00885   GlobalVariable *NewGV = new GlobalVariable(
00886       *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
00887       GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
00888       GV->isExternallyInitialized());
00889   NewGV->copyAttributesFrom(GV);
00890   NewGV->takeName(GV);
00891   assert(GV->use_empty() && "program cannot use initializer list");
00892   GV->eraseFromParent();
00893 }
00894 
00895 void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
00896   // Look for the global arrays.
00897   auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
00898   if (!DstGV)
00899     return;
00900   auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
00901   if (!SrcGV)
00902     return;
00903 
00904   // Check if the types already match.
00905   auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
00906   auto *SrcTy =
00907       cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
00908   if (DstTy == SrcTy)
00909     return;
00910 
00911   // Grab the element types.  We can only upgrade an array of a two-field
00912   // struct.  Only bother if the other one has three-fields.
00913   auto *DstEltTy = cast<StructType>(DstTy->getElementType());
00914   auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
00915   if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
00916     upgradeGlobalArray(DstGV);
00917     return;
00918   }
00919   if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
00920     upgradeGlobalArray(SrcGV);
00921 
00922   // We can't upgrade any other differences.
00923 }
00924 
00925 void ModuleLinker::upgradeMismatchedGlobals() {
00926   upgradeMismatchedGlobalArray("llvm.global_ctors");
00927   upgradeMismatchedGlobalArray("llvm.global_dtors");
00928 }
00929 
00930 /// linkAppendingVarProto - If there were any appending global variables, link
00931 /// them together now.  Return true on error.
00932 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
00933                                          GlobalVariable *SrcGV) {
00934 
00935   if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
00936     return emitError("Linking globals named '" + SrcGV->getName() +
00937            "': can only link appending global with another appending global!");
00938 
00939   ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
00940   ArrayType *SrcTy =
00941     cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
00942   Type *EltTy = DstTy->getElementType();
00943 
00944   // Check to see that they two arrays agree on type.
00945   if (EltTy != SrcTy->getElementType())
00946     return emitError("Appending variables with different element types!");
00947   if (DstGV->isConstant() != SrcGV->isConstant())
00948     return emitError("Appending variables linked with different const'ness!");
00949 
00950   if (DstGV->getAlignment() != SrcGV->getAlignment())
00951     return emitError(
00952              "Appending variables with different alignment need to be linked!");
00953 
00954   if (DstGV->getVisibility() != SrcGV->getVisibility())
00955     return emitError(
00956             "Appending variables with different visibility need to be linked!");
00957 
00958   if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
00959     return emitError(
00960         "Appending variables with different unnamed_addr need to be linked!");
00961 
00962   if (StringRef(DstGV->getSection()) != SrcGV->getSection())
00963     return emitError(
00964           "Appending variables with different section name need to be linked!");
00965 
00966   uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
00967   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
00968 
00969   // Create the new global variable.
00970   GlobalVariable *NG =
00971     new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
00972                        DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
00973                        DstGV->getThreadLocalMode(),
00974                        DstGV->getType()->getAddressSpace());
00975 
00976   // Propagate alignment, visibility and section info.
00977   copyGVAttributes(NG, DstGV);
00978 
00979   AppendingVarInfo AVI;
00980   AVI.NewGV = NG;
00981   AVI.DstInit = DstGV->getInitializer();
00982   AVI.SrcInit = SrcGV->getInitializer();
00983   AppendingVars.push_back(AVI);
00984 
00985   // Replace any uses of the two global variables with uses of the new
00986   // global.
00987   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
00988 
00989   DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
00990   DstGV->eraseFromParent();
00991 
00992   // Track the source variable so we don't try to link it.
00993   DoNotLinkFromSource.insert(SrcGV);
00994 
00995   return false;
00996 }
00997 
00998 /// linkGlobalProto - Loop through the global variables in the src module and
00999 /// merge them into the dest module.
01000 bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
01001   GlobalValue *DGV = getLinkedToGlobal(SGV);
01002   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
01003   bool HasUnnamedAddr = SGV->hasUnnamedAddr();
01004   unsigned Alignment = SGV->getAlignment();
01005 
01006   bool LinkFromSrc = false;
01007   Comdat *DC = nullptr;
01008   if (const Comdat *SC = SGV->getComdat()) {
01009     Comdat::SelectionKind SK;
01010     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
01011     DC = DstM->getOrInsertComdat(SC->getName());
01012     DC->setSelectionKind(SK);
01013   }
01014 
01015   if (DGV) {
01016     if (!DC) {
01017       // Concatenation of appending linkage variables is magic and handled later.
01018       if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
01019         return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
01020 
01021       // Determine whether linkage of these two globals follows the source
01022       // module's definition or the destination module's definition.
01023       GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
01024       GlobalValue::VisibilityTypes NV;
01025       if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
01026         return true;
01027       NewVisibility = NV;
01028       HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
01029       if (DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
01030         Alignment = std::max(Alignment, DGV->getAlignment());
01031       else if (!LinkFromSrc)
01032         Alignment = DGV->getAlignment();
01033 
01034       // If we're not linking from the source, then keep the definition that we
01035       // have.
01036       if (!LinkFromSrc) {
01037         // Special case for const propagation.
01038         if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
01039           DGVar->setAlignment(Alignment);
01040 
01041           if (DGVar->isDeclaration() && SGV->isConstant() &&
01042               !DGVar->isConstant())
01043             DGVar->setConstant(true);
01044         }
01045 
01046         // Set calculated linkage, visibility and unnamed_addr.
01047         DGV->setLinkage(NewLinkage);
01048         DGV->setVisibility(*NewVisibility);
01049         DGV->setUnnamedAddr(HasUnnamedAddr);
01050       }
01051     }
01052 
01053     if (!LinkFromSrc) {
01054       // Make sure to remember this mapping.
01055       ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
01056 
01057       // Track the source global so that we don't attempt to copy it over when
01058       // processing global initializers.
01059       DoNotLinkFromSource.insert(SGV);
01060 
01061       return false;
01062     }
01063   }
01064 
01065   // If the Comdat this variable was inside of wasn't selected, skip it.
01066   if (DC && !DGV && !LinkFromSrc) {
01067     DoNotLinkFromSource.insert(SGV);
01068     return false;
01069   }
01070 
01071   // No linking to be performed or linking from the source: simply create an
01072   // identical version of the symbol over in the dest module... the
01073   // initializer will be filled in later by LinkGlobalInits.
01074   GlobalVariable *NewDGV =
01075     new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
01076                        SGV->isConstant(), SGV->getLinkage(), /*init*/nullptr,
01077                        SGV->getName(), /*insertbefore*/nullptr,
01078                        SGV->getThreadLocalMode(),
01079                        SGV->getType()->getAddressSpace());
01080   // Propagate alignment, visibility and section info.
01081   copyGVAttributes(NewDGV, SGV);
01082   NewDGV->setAlignment(Alignment);
01083   if (NewVisibility)
01084     NewDGV->setVisibility(*NewVisibility);
01085   NewDGV->setUnnamedAddr(HasUnnamedAddr);
01086 
01087   if (DC)
01088     NewDGV->setComdat(DC);
01089 
01090   if (DGV) {
01091     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
01092     DGV->eraseFromParent();
01093   }
01094 
01095   // Make sure to remember this mapping.
01096   ValueMap[SGV] = NewDGV;
01097   return false;
01098 }
01099 
01100 /// linkFunctionProto - Link the function in the source module into the
01101 /// destination module if needed, setting up mapping information.
01102 bool ModuleLinker::linkFunctionProto(Function *SF) {
01103   GlobalValue *DGV = getLinkedToGlobal(SF);
01104   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
01105   bool HasUnnamedAddr = SF->hasUnnamedAddr();
01106 
01107   bool LinkFromSrc = false;
01108   Comdat *DC = nullptr;
01109   if (const Comdat *SC = SF->getComdat()) {
01110     Comdat::SelectionKind SK;
01111     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
01112     DC = DstM->getOrInsertComdat(SC->getName());
01113     DC->setSelectionKind(SK);
01114   }
01115 
01116   if (DGV) {
01117     if (!DC) {
01118       GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
01119       GlobalValue::VisibilityTypes NV;
01120       if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
01121         return true;
01122       NewVisibility = NV;
01123       HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
01124 
01125       if (!LinkFromSrc) {
01126         // Set calculated linkage
01127         DGV->setLinkage(NewLinkage);
01128         DGV->setVisibility(*NewVisibility);
01129         DGV->setUnnamedAddr(HasUnnamedAddr);
01130       }
01131     }
01132 
01133     if (!LinkFromSrc) {
01134       // Make sure to remember this mapping.
01135       ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
01136 
01137       // Track the function from the source module so we don't attempt to remap
01138       // it.
01139       DoNotLinkFromSource.insert(SF);
01140 
01141       return false;
01142     }
01143   }
01144 
01145   // If the function is to be lazily linked, don't create it just yet.
01146   // The ValueMaterializerTy will deal with creating it if it's used.
01147   if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
01148                SF->hasAvailableExternallyLinkage())) {
01149     DoNotLinkFromSource.insert(SF);
01150     return false;
01151   }
01152 
01153   // If the Comdat this function was inside of wasn't selected, skip it.
01154   if (DC && !DGV && !LinkFromSrc) {
01155     DoNotLinkFromSource.insert(SF);
01156     return false;
01157   }
01158 
01159   // If there is no linkage to be performed or we are linking from the source,
01160   // bring SF over.
01161   Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
01162                                      SF->getLinkage(), SF->getName(), DstM);
01163   copyGVAttributes(NewDF, SF);
01164   if (NewVisibility)
01165     NewDF->setVisibility(*NewVisibility);
01166   NewDF->setUnnamedAddr(HasUnnamedAddr);
01167 
01168   if (DC)
01169     NewDF->setComdat(DC);
01170 
01171   if (DGV) {
01172     // Any uses of DF need to change to NewDF, with cast.
01173     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
01174     DGV->eraseFromParent();
01175   }
01176 
01177   ValueMap[SF] = NewDF;
01178   return false;
01179 }
01180 
01181 /// LinkAliasProto - Set up prototypes for any aliases that come over from the
01182 /// source module.
01183 bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
01184   GlobalValue *DGV = getLinkedToGlobal(SGA);
01185   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
01186   bool HasUnnamedAddr = SGA->hasUnnamedAddr();
01187 
01188   bool LinkFromSrc = false;
01189   Comdat *DC = nullptr;
01190   if (const Comdat *SC = SGA->getComdat()) {
01191     Comdat::SelectionKind SK;
01192     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
01193     DC = DstM->getOrInsertComdat(SC->getName());
01194     DC->setSelectionKind(SK);
01195   }
01196 
01197   if (DGV) {
01198     if (!DC) {
01199       GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
01200       GlobalValue::VisibilityTypes NV;
01201       if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
01202         return true;
01203       NewVisibility = NV;
01204       HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
01205 
01206       if (!LinkFromSrc) {
01207         // Set calculated linkage.
01208         DGV->setLinkage(NewLinkage);
01209         DGV->setVisibility(*NewVisibility);
01210         DGV->setUnnamedAddr(HasUnnamedAddr);
01211       }
01212     }
01213 
01214     if (!LinkFromSrc) {
01215       // Make sure to remember this mapping.
01216       ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
01217 
01218       // Track the alias from the source module so we don't attempt to remap it.
01219       DoNotLinkFromSource.insert(SGA);
01220 
01221       return false;
01222     }
01223   }
01224 
01225   // If the Comdat this alias was inside of wasn't selected, skip it.
01226   if (DC && !DGV && !LinkFromSrc) {
01227     DoNotLinkFromSource.insert(SGA);
01228     return false;
01229   }
01230 
01231   // If there is no linkage to be performed or we're linking from the source,
01232   // bring over SGA.
01233   auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
01234   auto *NewDA =
01235       GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
01236                           SGA->getLinkage(), SGA->getName(), DstM);
01237   copyGVAttributes(NewDA, SGA);
01238   if (NewVisibility)
01239     NewDA->setVisibility(*NewVisibility);
01240   NewDA->setUnnamedAddr(HasUnnamedAddr);
01241 
01242   if (DGV) {
01243     // Any uses of DGV need to change to NewDA, with cast.
01244     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
01245     DGV->eraseFromParent();
01246   }
01247 
01248   ValueMap[SGA] = NewDA;
01249   return false;
01250 }
01251 
01252 static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
01253   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
01254 
01255   for (unsigned i = 0; i != NumElements; ++i)
01256     Dest.push_back(C->getAggregateElement(i));
01257 }
01258 
01259 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
01260   // Merge the initializer.
01261   SmallVector<Constant *, 16> DstElements;
01262   getArrayElements(AVI.DstInit, DstElements);
01263 
01264   SmallVector<Constant *, 16> SrcElements;
01265   getArrayElements(AVI.SrcInit, SrcElements);
01266 
01267   ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
01268 
01269   StringRef Name = AVI.NewGV->getName();
01270   bool IsNewStructor =
01271       (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
01272       cast<StructType>(NewType->getElementType())->getNumElements() == 3;
01273 
01274   for (auto *V : SrcElements) {
01275     if (IsNewStructor) {
01276       Constant *Key = V->getAggregateElement(2);
01277       if (DoNotLinkFromSource.count(Key))
01278         continue;
01279     }
01280     DstElements.push_back(
01281         MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
01282   }
01283   if (IsNewStructor) {
01284     NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
01285     AVI.NewGV->mutateType(PointerType::get(NewType, 0));
01286   }
01287 
01288   AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
01289 }
01290 
01291 /// linkGlobalInits - Update the initializers in the Dest module now that all
01292 /// globals that may be referenced are in Dest.
01293 void ModuleLinker::linkGlobalInits() {
01294   // Loop over all of the globals in the src module, mapping them over as we go
01295   for (Module::const_global_iterator I = SrcM->global_begin(),
01296        E = SrcM->global_end(); I != E; ++I) {
01297 
01298     // Only process initialized GV's or ones not already in dest.
01299     if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
01300 
01301     // Grab destination global variable.
01302     GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
01303     // Figure out what the initializer looks like in the dest module.
01304     DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
01305                                  RF_None, &TypeMap, &ValMaterializer));
01306   }
01307 }
01308 
01309 /// linkFunctionBody - Copy the source function over into the dest function and
01310 /// fix up references to values.  At this point we know that Dest is an external
01311 /// function, and that Src is not.
01312 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
01313   assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
01314 
01315   // Go through and convert function arguments over, remembering the mapping.
01316   Function::arg_iterator DI = Dst->arg_begin();
01317   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
01318        I != E; ++I, ++DI) {
01319     DI->setName(I->getName());  // Copy the name over.
01320 
01321     // Add a mapping to our mapping.
01322     ValueMap[I] = DI;
01323   }
01324 
01325   if (Mode == Linker::DestroySource) {
01326     // Splice the body of the source function into the dest function.
01327     Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
01328 
01329     // At this point, all of the instructions and values of the function are now
01330     // copied over.  The only problem is that they are still referencing values in
01331     // the Source function as operands.  Loop through all of the operands of the
01332     // functions and patch them up to point to the local versions.
01333     for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
01334       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
01335         RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries,
01336                          &TypeMap, &ValMaterializer);
01337 
01338   } else {
01339     // Clone the body of the function into the dest function.
01340     SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
01341     CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", nullptr,
01342                       &TypeMap, &ValMaterializer);
01343   }
01344 
01345   // There is no need to map the arguments anymore.
01346   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
01347        I != E; ++I)
01348     ValueMap.erase(I);
01349 
01350 }
01351 
01352 /// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
01353 void ModuleLinker::linkAliasBodies() {
01354   for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
01355        I != E; ++I) {
01356     if (DoNotLinkFromSource.count(I))
01357       continue;
01358     if (Constant *Aliasee = I->getAliasee()) {
01359       GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
01360       Constant *Val =
01361           MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
01362       DA->setAliasee(Val);
01363     }
01364   }
01365 }
01366 
01367 /// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
01368 /// module.
01369 void ModuleLinker::linkNamedMDNodes() {
01370   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
01371   for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
01372        E = SrcM->named_metadata_end(); I != E; ++I) {
01373     // Don't link module flags here. Do them separately.
01374     if (&*I == SrcModFlags) continue;
01375     NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
01376     // Add Src elements into Dest node.
01377     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
01378       DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
01379                                    RF_None, &TypeMap, &ValMaterializer));
01380   }
01381 }
01382 
01383 /// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
01384 /// module.
01385 bool ModuleLinker::linkModuleFlagsMetadata() {
01386   // If the source module has no module flags, we are done.
01387   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
01388   if (!SrcModFlags) return false;
01389 
01390   // If the destination module doesn't have module flags yet, then just copy
01391   // over the source module's flags.
01392   NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
01393   if (DstModFlags->getNumOperands() == 0) {
01394     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
01395       DstModFlags->addOperand(SrcModFlags->getOperand(I));
01396 
01397     return false;
01398   }
01399 
01400   // First build a map of the existing module flags and requirements.
01401   DenseMap<MDString*, MDNode*> Flags;
01402   SmallSetVector<MDNode*, 16> Requirements;
01403   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
01404     MDNode *Op = DstModFlags->getOperand(I);
01405     ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
01406     MDString *ID = cast<MDString>(Op->getOperand(1));
01407 
01408     if (Behavior->getZExtValue() == Module::Require) {
01409       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
01410     } else {
01411       Flags[ID] = Op;
01412     }
01413   }
01414 
01415   // Merge in the flags from the source module, and also collect its set of
01416   // requirements.
01417   bool HasErr = false;
01418   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
01419     MDNode *SrcOp = SrcModFlags->getOperand(I);
01420     ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
01421     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
01422     MDNode *DstOp = Flags.lookup(ID);
01423     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
01424 
01425     // If this is a requirement, add it and continue.
01426     if (SrcBehaviorValue == Module::Require) {
01427       // If the destination module does not already have this requirement, add
01428       // it.
01429       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
01430         DstModFlags->addOperand(SrcOp);
01431       }
01432       continue;
01433     }
01434 
01435     // If there is no existing flag with this ID, just add it.
01436     if (!DstOp) {
01437       Flags[ID] = SrcOp;
01438       DstModFlags->addOperand(SrcOp);
01439       continue;
01440     }
01441 
01442     // Otherwise, perform a merge.
01443     ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
01444     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
01445 
01446     // If either flag has override behavior, handle it first.
01447     if (DstBehaviorValue == Module::Override) {
01448       // Diagnose inconsistent flags which both have override behavior.
01449       if (SrcBehaviorValue == Module::Override &&
01450           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
01451         HasErr |= emitError("linking module flags '" + ID->getString() +
01452                             "': IDs have conflicting override values");
01453       }
01454       continue;
01455     } else if (SrcBehaviorValue == Module::Override) {
01456       // Update the destination flag to that of the source.
01457       DstOp->replaceOperandWith(0, SrcBehavior);
01458       DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
01459       continue;
01460     }
01461 
01462     // Diagnose inconsistent merge behavior types.
01463     if (SrcBehaviorValue != DstBehaviorValue) {
01464       HasErr |= emitError("linking module flags '" + ID->getString() +
01465                           "': IDs have conflicting behaviors");
01466       continue;
01467     }
01468 
01469     // Perform the merge for standard behavior types.
01470     switch (SrcBehaviorValue) {
01471     case Module::Require:
01472     case Module::Override: llvm_unreachable("not possible");
01473     case Module::Error: {
01474       // Emit an error if the values differ.
01475       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
01476         HasErr |= emitError("linking module flags '" + ID->getString() +
01477                             "': IDs have conflicting values");
01478       }
01479       continue;
01480     }
01481     case Module::Warning: {
01482       // Emit a warning if the values differ.
01483       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
01484         if (!SuppressWarnings) {
01485           errs() << "WARNING: linking module flags '" << ID->getString()
01486                  << "': IDs have conflicting values";
01487         }
01488       }
01489       continue;
01490     }
01491     case Module::Append: {
01492       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
01493       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
01494       unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
01495       Value **VP, **Values = VP = new Value*[NumOps];
01496       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
01497         *VP = DstValue->getOperand(i);
01498       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
01499         *VP = SrcValue->getOperand(i);
01500       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
01501                                                ArrayRef<Value*>(Values,
01502                                                                 NumOps)));
01503       delete[] Values;
01504       break;
01505     }
01506     case Module::AppendUnique: {
01507       SmallSetVector<Value*, 16> Elts;
01508       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
01509       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
01510       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
01511         Elts.insert(DstValue->getOperand(i));
01512       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
01513         Elts.insert(SrcValue->getOperand(i));
01514       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
01515                                                ArrayRef<Value*>(Elts.begin(),
01516                                                                 Elts.end())));
01517       break;
01518     }
01519     }
01520   }
01521 
01522   // Check all of the requirements.
01523   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
01524     MDNode *Requirement = Requirements[I];
01525     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
01526     Value *ReqValue = Requirement->getOperand(1);
01527 
01528     MDNode *Op = Flags[Flag];
01529     if (!Op || Op->getOperand(2) != ReqValue) {
01530       HasErr |= emitError("linking module flags '" + Flag->getString() +
01531                           "': does not have the required value");
01532       continue;
01533     }
01534   }
01535 
01536   return HasErr;
01537 }
01538 
01539 bool ModuleLinker::run() {
01540   assert(DstM && "Null destination module");
01541   assert(SrcM && "Null source module");
01542 
01543   // Inherit the target data from the source module if the destination module
01544   // doesn't have one already.
01545   if (!DstM->getDataLayout() && SrcM->getDataLayout())
01546     DstM->setDataLayout(SrcM->getDataLayout());
01547 
01548   // Copy the target triple from the source to dest if the dest's is empty.
01549   if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
01550     DstM->setTargetTriple(SrcM->getTargetTriple());
01551 
01552   if (SrcM->getDataLayout() && DstM->getDataLayout() &&
01553       *SrcM->getDataLayout() != *DstM->getDataLayout()) {
01554     if (!SuppressWarnings) {
01555       errs() << "WARNING: Linking two modules of different data layouts: '"
01556              << SrcM->getModuleIdentifier() << "' is '"
01557              << SrcM->getDataLayoutStr() << "' whereas '"
01558              << DstM->getModuleIdentifier() << "' is '"
01559              << DstM->getDataLayoutStr() << "'\n";
01560     }
01561   }
01562   if (!SrcM->getTargetTriple().empty() &&
01563       DstM->getTargetTriple() != SrcM->getTargetTriple()) {
01564     if (!SuppressWarnings) {
01565       errs() << "WARNING: Linking two modules of different target triples: "
01566              << SrcM->getModuleIdentifier() << "' is '"
01567              << SrcM->getTargetTriple() << "' whereas '"
01568              << DstM->getModuleIdentifier() << "' is '"
01569              << DstM->getTargetTriple() << "'\n";
01570     }
01571   }
01572 
01573   // Append the module inline asm string.
01574   if (!SrcM->getModuleInlineAsm().empty()) {
01575     if (DstM->getModuleInlineAsm().empty())
01576       DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
01577     else
01578       DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
01579                                SrcM->getModuleInlineAsm());
01580   }
01581 
01582   // Loop over all of the linked values to compute type mappings.
01583   computeTypeMapping();
01584 
01585   ComdatsChosen.clear();
01586   for (const StringMapEntry<llvm::Comdat> &SMEC : SrcM->getComdatSymbolTable()) {
01587     const Comdat &C = SMEC.getValue();
01588     if (ComdatsChosen.count(&C))
01589       continue;
01590     Comdat::SelectionKind SK;
01591     bool LinkFromSrc;
01592     if (getComdatResult(&C, SK, LinkFromSrc))
01593       return true;
01594     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
01595   }
01596 
01597   // Upgrade mismatched global arrays.
01598   upgradeMismatchedGlobals();
01599 
01600   // Insert all of the globals in src into the DstM module... without linking
01601   // initializers (which could refer to functions not yet mapped over).
01602   for (Module::global_iterator I = SrcM->global_begin(),
01603        E = SrcM->global_end(); I != E; ++I)
01604     if (linkGlobalProto(I))
01605       return true;
01606 
01607   // Link the functions together between the two modules, without doing function
01608   // bodies... this just adds external function prototypes to the DstM
01609   // function...  We do this so that when we begin processing function bodies,
01610   // all of the global values that may be referenced are available in our
01611   // ValueMap.
01612   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
01613     if (linkFunctionProto(I))
01614       return true;
01615 
01616   // If there were any aliases, link them now.
01617   for (Module::alias_iterator I = SrcM->alias_begin(),
01618        E = SrcM->alias_end(); I != E; ++I)
01619     if (linkAliasProto(I))
01620       return true;
01621 
01622   for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
01623     linkAppendingVarInit(AppendingVars[i]);
01624 
01625   // Link in the function bodies that are defined in the source module into
01626   // DstM.
01627   for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
01628     // Skip if not linking from source.
01629     if (DoNotLinkFromSource.count(SF)) continue;
01630 
01631     Function *DF = cast<Function>(ValueMap[SF]);
01632     if (SF->hasPrefixData()) {
01633       // Link in the prefix data.
01634       DF->setPrefixData(MapValue(
01635           SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
01636     }
01637 
01638     // Skip if no body (function is external) or materialize.
01639     if (SF->isDeclaration()) {
01640       if (!SF->isMaterializable())
01641         continue;
01642       if (SF->Materialize(&ErrorMsg))
01643         return true;
01644     }
01645 
01646     linkFunctionBody(DF, SF);
01647     SF->Dematerialize();
01648   }
01649 
01650   // Resolve all uses of aliases with aliasees.
01651   linkAliasBodies();
01652 
01653   // Remap all of the named MDNodes in Src into the DstM module. We do this
01654   // after linking GlobalValues so that MDNodes that reference GlobalValues
01655   // are properly remapped.
01656   linkNamedMDNodes();
01657 
01658   // Merge the module flags into the DstM module.
01659   if (linkModuleFlagsMetadata())
01660     return true;
01661 
01662   // Update the initializers in the DstM module now that all globals that may
01663   // be referenced are in DstM.
01664   linkGlobalInits();
01665 
01666   // Process vector of lazily linked in functions.
01667   bool LinkedInAnyFunctions;
01668   do {
01669     LinkedInAnyFunctions = false;
01670 
01671     for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
01672         E = LazilyLinkFunctions.end(); I != E; ++I) {
01673       Function *SF = *I;
01674       if (!SF)
01675         continue;
01676 
01677       Function *DF = cast<Function>(ValueMap[SF]);
01678       if (SF->hasPrefixData()) {
01679         // Link in the prefix data.
01680         DF->setPrefixData(MapValue(SF->getPrefixData(),
01681                                    ValueMap,
01682                                    RF_None,
01683                                    &TypeMap,
01684                                    &ValMaterializer));
01685       }
01686 
01687       // Materialize if necessary.
01688       if (SF->isDeclaration()) {
01689         if (!SF->isMaterializable())
01690           continue;
01691         if (SF->Materialize(&ErrorMsg))
01692           return true;
01693       }
01694 
01695       // Erase from vector *before* the function body is linked - linkFunctionBody could
01696       // invalidate I.
01697       LazilyLinkFunctions.erase(I);
01698 
01699       // Link in function body.
01700       linkFunctionBody(DF, SF);
01701       SF->Dematerialize();
01702 
01703       // Set flag to indicate we may have more functions to lazily link in
01704       // since we linked in a function.
01705       LinkedInAnyFunctions = true;
01706       break;
01707     }
01708   } while (LinkedInAnyFunctions);
01709 
01710   // Now that all of the types from the source are used, resolve any structs
01711   // copied over to the dest that didn't exist there.
01712   TypeMap.linkDefinedTypeBodies();
01713 
01714   return false;
01715 }
01716 
01717 Linker::Linker(Module *M, bool SuppressWarnings)
01718     : Composite(M), SuppressWarnings(SuppressWarnings) {
01719   TypeFinder StructTypes;
01720   StructTypes.run(*M, true);
01721   IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
01722 }
01723 
01724 Linker::~Linker() {
01725 }
01726 
01727 void Linker::deleteModule() {
01728   delete Composite;
01729   Composite = nullptr;
01730 }
01731 
01732 bool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) {
01733   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode,
01734                          SuppressWarnings);
01735   if (TheLinker.run()) {
01736     if (ErrorMsg)
01737       *ErrorMsg = TheLinker.ErrorMsg;
01738     return true;
01739   }
01740   return false;
01741 }
01742 
01743 //===----------------------------------------------------------------------===//
01744 // LinkModules entrypoint.
01745 //===----------------------------------------------------------------------===//
01746 
01747 /// LinkModules - This function links two modules together, with the resulting
01748 /// Dest module modified to be the composite of the two input modules.  If an
01749 /// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
01750 /// the problem.  Upon failure, the Dest module could be in a modified state,
01751 /// and shouldn't be relied on to be consistent.
01752 bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
01753                          std::string *ErrorMsg) {
01754   Linker L(Dest);
01755   return L.linkInModule(Src, Mode, ErrorMsg);
01756 }
01757 
01758 //===----------------------------------------------------------------------===//
01759 // C API.
01760 //===----------------------------------------------------------------------===//
01761 
01762 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
01763                          LLVMLinkerMode Mode, char **OutMessages) {
01764   std::string Messages;
01765   LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
01766                                         Mode, OutMessages? &Messages : nullptr);
01767   if (OutMessages)
01768     *OutMessages = strdup(Messages.c_str());
01769   return Result;
01770 }