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