1193323Sed//===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===// 2193323Sed// 3193323Sed// The LLVM Compiler Infrastructure 4193323Sed// 5193323Sed// This file is distributed under the University of Illinois Open Source 6193323Sed// License. See LICENSE.TXT for details. 7193323Sed// 8193323Sed//===----------------------------------------------------------------------===// 9193323Sed// 10193323Sed// This file implements the LLVM module linker. 11193323Sed// 12193323Sed//===----------------------------------------------------------------------===// 13193323Sed 14193323Sed#include "llvm/Linker.h" 15249423Sdim#include "llvm-c/Linker.h" 16234353Sdim#include "llvm/ADT/Optional.h" 17234353Sdim#include "llvm/ADT/SetVector.h" 18249423Sdim#include "llvm/ADT/SmallString.h" 19249423Sdim#include "llvm/IR/Constants.h" 20249423Sdim#include "llvm/IR/Module.h" 21249423Sdim#include "llvm/IR/TypeFinder.h" 22234353Sdim#include "llvm/Support/Debug.h" 23198090Srdivacky#include "llvm/Support/raw_ostream.h" 24226633Sdim#include "llvm/Transforms/Utils/Cloning.h" 25193323Sedusing namespace llvm; 26193323Sed 27224145Sdim//===----------------------------------------------------------------------===// 28224145Sdim// TypeMap implementation. 29224145Sdim//===----------------------------------------------------------------------===// 30193323Sed 31193323Sednamespace { 32251662Sdim typedef SmallPtrSet<StructType*, 32> TypeSet; 33251662Sdim 34224145Sdimclass TypeMapTy : public ValueMapTypeRemapper { 35224145Sdim /// MappedTypes - This is a mapping from a source type to a destination type 36224145Sdim /// to use. 37224145Sdim DenseMap<Type*, Type*> MappedTypes; 38193323Sed 39224145Sdim /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic, 40224145Sdim /// we speculatively add types to MappedTypes, but keep track of them here in 41224145Sdim /// case we need to roll back. 42224145Sdim SmallVector<Type*, 16> SpeculativeTypes; 43224145Sdim 44234353Sdim /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the 45234353Sdim /// source module that are mapped to an opaque struct in the destination 46234353Sdim /// module. 47234353Sdim SmallVector<StructType*, 16> SrcDefinitionsToResolve; 48234353Sdim 49234353Sdim /// DstResolvedOpaqueTypes - This is the set of opaque types in the 50234353Sdim /// destination modules who are getting a body from the source module. 51234353Sdim SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes; 52234353Sdim 53193323Sedpublic: 54251662Sdim TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {} 55251662Sdim 56251662Sdim TypeSet &DstStructTypesSet; 57224145Sdim /// addTypeMapping - Indicate that the specified type in the destination 58224145Sdim /// module is conceptually equivalent to the specified type in the source 59224145Sdim /// module. 60224145Sdim void addTypeMapping(Type *DstTy, Type *SrcTy); 61193323Sed 62224145Sdim /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest 63224145Sdim /// module from a type definition in the source module. 64224145Sdim void linkDefinedTypeBodies(); 65224145Sdim 66224145Sdim /// get - Return the mapped type to use for the specified input type from the 67224145Sdim /// source module. 68224145Sdim Type *get(Type *SrcTy); 69193323Sed 70224145Sdim FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));} 71193323Sed 72234353Sdim /// dump - Dump out the type map for debugging purposes. 73234353Sdim void dump() const { 74234353Sdim for (DenseMap<Type*, Type*>::const_iterator 75234353Sdim I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) { 76234353Sdim dbgs() << "TypeMap: "; 77234353Sdim I->first->dump(); 78234353Sdim dbgs() << " => "; 79234353Sdim I->second->dump(); 80234353Sdim dbgs() << '\n'; 81234353Sdim } 82234353Sdim } 83234353Sdim 84224145Sdimprivate: 85224145Sdim Type *getImpl(Type *T); 86224145Sdim /// remapType - Implement the ValueMapTypeRemapper interface. 87224145Sdim Type *remapType(Type *SrcTy) { 88224145Sdim return get(SrcTy); 89193323Sed } 90224145Sdim 91224145Sdim bool areTypesIsomorphic(Type *DstTy, Type *SrcTy); 92224145Sdim}; 93224145Sdim} 94193323Sed 95224145Sdimvoid TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) { 96224145Sdim Type *&Entry = MappedTypes[SrcTy]; 97224145Sdim if (Entry) return; 98224145Sdim 99224145Sdim if (DstTy == SrcTy) { 100224145Sdim Entry = DstTy; 101224145Sdim return; 102193323Sed } 103224145Sdim 104224145Sdim // Check to see if these types are recursively isomorphic and establish a 105224145Sdim // mapping between them if so. 106224145Sdim if (!areTypesIsomorphic(DstTy, SrcTy)) { 107224145Sdim // Oops, they aren't isomorphic. Just discard this request by rolling out 108224145Sdim // any speculative mappings we've established. 109224145Sdim for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i) 110224145Sdim MappedTypes.erase(SpeculativeTypes[i]); 111193323Sed } 112224145Sdim SpeculativeTypes.clear(); 113193323Sed} 114193323Sed 115224145Sdim/// areTypesIsomorphic - Recursively walk this pair of types, returning true 116224145Sdim/// if they are isomorphic, false if they are not. 117224145Sdimbool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) { 118224145Sdim // Two types with differing kinds are clearly not isomorphic. 119224145Sdim if (DstTy->getTypeID() != SrcTy->getTypeID()) return false; 120193323Sed 121224145Sdim // If we have an entry in the MappedTypes table, then we have our answer. 122224145Sdim Type *&Entry = MappedTypes[SrcTy]; 123224145Sdim if (Entry) 124224145Sdim return Entry == DstTy; 125193323Sed 126224145Sdim // Two identical types are clearly isomorphic. Remember this 127224145Sdim // non-speculatively. 128224145Sdim if (DstTy == SrcTy) { 129224145Sdim Entry = DstTy; 130193323Sed return true; 131224145Sdim } 132224145Sdim 133224145Sdim // Okay, we have two types with identical kinds that we haven't seen before. 134193323Sed 135224145Sdim // If this is an opaque struct type, special case it. 136224145Sdim if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) { 137224145Sdim // Mapping an opaque type to any struct, just keep the dest struct. 138224145Sdim if (SSTy->isOpaque()) { 139224145Sdim Entry = DstTy; 140224145Sdim SpeculativeTypes.push_back(SrcTy); 141193323Sed return true; 142224145Sdim } 143193323Sed 144234353Sdim // Mapping a non-opaque source type to an opaque dest. If this is the first 145234353Sdim // type that we're mapping onto this destination type then we succeed. Keep 146234353Sdim // the dest, but fill it in later. This doesn't need to be speculative. If 147234353Sdim // this is the second (different) type that we're trying to map onto the 148234353Sdim // same opaque type then we fail. 149224145Sdim if (cast<StructType>(DstTy)->isOpaque()) { 150234353Sdim // We can only map one source type onto the opaque destination type. 151234353Sdim if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy))) 152234353Sdim return false; 153234353Sdim SrcDefinitionsToResolve.push_back(SSTy); 154224145Sdim Entry = DstTy; 155224145Sdim return true; 156193323Sed } 157193323Sed } 158224145Sdim 159224145Sdim // If the number of subtypes disagree between the two types, then we fail. 160224145Sdim if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes()) 161193323Sed return false; 162224145Sdim 163224145Sdim // Fail if any of the extra properties (e.g. array size) of the type disagree. 164224145Sdim if (isa<IntegerType>(DstTy)) 165224145Sdim return false; // bitwidth disagrees. 166224145Sdim if (PointerType *PT = dyn_cast<PointerType>(DstTy)) { 167224145Sdim if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace()) 168224145Sdim return false; 169234353Sdim 170224145Sdim } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) { 171224145Sdim if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg()) 172224145Sdim return false; 173224145Sdim } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) { 174224145Sdim StructType *SSTy = cast<StructType>(SrcTy); 175226633Sdim if (DSTy->isLiteral() != SSTy->isLiteral() || 176224145Sdim DSTy->isPacked() != SSTy->isPacked()) 177224145Sdim return false; 178224145Sdim } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) { 179224145Sdim if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements()) 180224145Sdim return false; 181224145Sdim } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) { 182249423Sdim if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements()) 183224145Sdim return false; 184193323Sed } 185193323Sed 186224145Sdim // Otherwise, we speculate that these two types will line up and recursively 187224145Sdim // check the subelements. 188224145Sdim Entry = DstTy; 189224145Sdim SpeculativeTypes.push_back(SrcTy); 190193323Sed 191224145Sdim for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i) 192224145Sdim if (!areTypesIsomorphic(DstTy->getContainedType(i), 193224145Sdim SrcTy->getContainedType(i))) 194224145Sdim return false; 195224145Sdim 196224145Sdim // If everything seems to have lined up, then everything is great. 197224145Sdim return true; 198224145Sdim} 199193323Sed 200224145Sdim/// linkDefinedTypeBodies - Produce a body for an opaque type in the dest 201224145Sdim/// module from a type definition in the source module. 202224145Sdimvoid TypeMapTy::linkDefinedTypeBodies() { 203224145Sdim SmallVector<Type*, 16> Elements; 204224145Sdim SmallString<16> TmpName; 205224145Sdim 206224145Sdim // Note that processing entries in this loop (calling 'get') can add new 207234353Sdim // entries to the SrcDefinitionsToResolve vector. 208234353Sdim while (!SrcDefinitionsToResolve.empty()) { 209234353Sdim StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val(); 210224145Sdim StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]); 211224145Sdim 212224145Sdim // TypeMap is a many-to-one mapping, if there were multiple types that 213224145Sdim // provide a body for DstSTy then previous iterations of this loop may have 214224145Sdim // already handled it. Just ignore this case. 215224145Sdim if (!DstSTy->isOpaque()) continue; 216224145Sdim assert(!SrcSTy->isOpaque() && "Not resolving a definition?"); 217224145Sdim 218224145Sdim // Map the body of the source type over to a new body for the dest type. 219224145Sdim Elements.resize(SrcSTy->getNumElements()); 220224145Sdim for (unsigned i = 0, e = Elements.size(); i != e; ++i) 221224145Sdim Elements[i] = getImpl(SrcSTy->getElementType(i)); 222224145Sdim 223224145Sdim DstSTy->setBody(Elements, SrcSTy->isPacked()); 224224145Sdim 225224145Sdim // If DstSTy has no name or has a longer name than STy, then viciously steal 226224145Sdim // STy's name. 227224145Sdim if (!SrcSTy->hasName()) continue; 228224145Sdim StringRef SrcName = SrcSTy->getName(); 229224145Sdim 230224145Sdim if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) { 231224145Sdim TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end()); 232224145Sdim SrcSTy->setName(""); 233224145Sdim DstSTy->setName(TmpName.str()); 234224145Sdim TmpName.clear(); 235224145Sdim } 236193323Sed } 237234353Sdim 238234353Sdim DstResolvedOpaqueTypes.clear(); 239193323Sed} 240193323Sed 241224145Sdim/// get - Return the mapped type to use for the specified input type from the 242224145Sdim/// source module. 243224145SdimType *TypeMapTy::get(Type *Ty) { 244224145Sdim Type *Result = getImpl(Ty); 245224145Sdim 246224145Sdim // If this caused a reference to any struct type, resolve it before returning. 247234353Sdim if (!SrcDefinitionsToResolve.empty()) 248224145Sdim linkDefinedTypeBodies(); 249224145Sdim return Result; 250193323Sed} 251193323Sed 252224145Sdim/// getImpl - This is the recursive version of get(). 253224145SdimType *TypeMapTy::getImpl(Type *Ty) { 254224145Sdim // If we already have an entry for this type, return it. 255224145Sdim Type **Entry = &MappedTypes[Ty]; 256224145Sdim if (*Entry) return *Entry; 257224145Sdim 258224145Sdim // If this is not a named struct type, then just map all of the elements and 259224145Sdim // then rebuild the type from inside out. 260226633Sdim if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) { 261224145Sdim // If there are no element types to map, then the type is itself. This is 262224145Sdim // true for the anonymous {} struct, things like 'float', integers, etc. 263224145Sdim if (Ty->getNumContainedTypes() == 0) 264224145Sdim return *Entry = Ty; 265224145Sdim 266224145Sdim // Remap all of the elements, keeping track of whether any of them change. 267224145Sdim bool AnyChange = false; 268224145Sdim SmallVector<Type*, 4> ElementTypes; 269224145Sdim ElementTypes.resize(Ty->getNumContainedTypes()); 270224145Sdim for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) { 271224145Sdim ElementTypes[i] = getImpl(Ty->getContainedType(i)); 272224145Sdim AnyChange |= ElementTypes[i] != Ty->getContainedType(i); 273224145Sdim } 274224145Sdim 275224145Sdim // If we found our type while recursively processing stuff, just use it. 276224145Sdim Entry = &MappedTypes[Ty]; 277224145Sdim if (*Entry) return *Entry; 278224145Sdim 279224145Sdim // If all of the element types mapped directly over, then the type is usable 280224145Sdim // as-is. 281224145Sdim if (!AnyChange) 282224145Sdim return *Entry = Ty; 283224145Sdim 284224145Sdim // Otherwise, rebuild a modified type. 285224145Sdim switch (Ty->getTypeID()) { 286234353Sdim default: llvm_unreachable("unknown derived type to remap"); 287224145Sdim case Type::ArrayTyID: 288224145Sdim return *Entry = ArrayType::get(ElementTypes[0], 289224145Sdim cast<ArrayType>(Ty)->getNumElements()); 290224145Sdim case Type::VectorTyID: 291224145Sdim return *Entry = VectorType::get(ElementTypes[0], 292224145Sdim cast<VectorType>(Ty)->getNumElements()); 293224145Sdim case Type::PointerTyID: 294224145Sdim return *Entry = PointerType::get(ElementTypes[0], 295224145Sdim cast<PointerType>(Ty)->getAddressSpace()); 296224145Sdim case Type::FunctionTyID: 297224145Sdim return *Entry = FunctionType::get(ElementTypes[0], 298226633Sdim makeArrayRef(ElementTypes).slice(1), 299224145Sdim cast<FunctionType>(Ty)->isVarArg()); 300224145Sdim case Type::StructTyID: 301224145Sdim // Note that this is only reached for anonymous structs. 302224145Sdim return *Entry = StructType::get(Ty->getContext(), ElementTypes, 303224145Sdim cast<StructType>(Ty)->isPacked()); 304224145Sdim } 305224145Sdim } 306193323Sed 307224145Sdim // Otherwise, this is an unmapped named struct. If the struct can be directly 308224145Sdim // mapped over, just use it as-is. This happens in a case when the linked-in 309224145Sdim // module has something like: 310224145Sdim // %T = type {%T*, i32} 311224145Sdim // @GV = global %T* null 312224145Sdim // where T does not exist at all in the destination module. 313224145Sdim // 314224145Sdim // The other case we watch for is when the type is not in the destination 315224145Sdim // module, but that it has to be rebuilt because it refers to something that 316224145Sdim // is already mapped. For example, if the destination module has: 317224145Sdim // %A = type { i32 } 318224145Sdim // and the source module has something like 319224145Sdim // %A' = type { i32 } 320224145Sdim // %B = type { %A'* } 321224145Sdim // @GV = global %B* null 322224145Sdim // then we want to create a new type: "%B = type { %A*}" and have it take the 323224145Sdim // pristine "%B" name from the source module. 324224145Sdim // 325224145Sdim // To determine which case this is, we have to recursively walk the type graph 326224145Sdim // speculating that we'll be able to reuse it unmodified. Only if this is 327224145Sdim // safe would we map the entire thing over. Because this is an optimization, 328224145Sdim // and is not required for the prettiness of the linked module, we just skip 329224145Sdim // it and always rebuild a type here. 330224145Sdim StructType *STy = cast<StructType>(Ty); 331224145Sdim 332224145Sdim // If the type is opaque, we can just use it directly. 333251662Sdim if (STy->isOpaque()) { 334251662Sdim // A named structure type from src module is used. Add it to the Set of 335251662Sdim // identified structs in the destination module. 336251662Sdim DstStructTypesSet.insert(STy); 337224145Sdim return *Entry = STy; 338251662Sdim } 339224145Sdim 340224145Sdim // Otherwise we create a new type and resolve its body later. This will be 341224145Sdim // resolved by the top level of get(). 342234353Sdim SrcDefinitionsToResolve.push_back(STy); 343234353Sdim StructType *DTy = StructType::create(STy->getContext()); 344251662Sdim // A new identified structure type was created. Add it to the set of 345251662Sdim // identified structs in the destination module. 346251662Sdim DstStructTypesSet.insert(DTy); 347234353Sdim DstResolvedOpaqueTypes.insert(DTy); 348234353Sdim return *Entry = DTy; 349224145Sdim} 350193323Sed 351224145Sdim//===----------------------------------------------------------------------===// 352224145Sdim// ModuleLinker implementation. 353224145Sdim//===----------------------------------------------------------------------===// 354193323Sed 355224145Sdimnamespace { 356224145Sdim /// ModuleLinker - This is an implementation class for the LinkModules 357224145Sdim /// function, which is the entrypoint for this file. 358224145Sdim class ModuleLinker { 359224145Sdim Module *DstM, *SrcM; 360224145Sdim 361224145Sdim TypeMapTy TypeMap; 362193323Sed 363224145Sdim /// ValueMap - Mapping of values from what they used to be in Src, to what 364224145Sdim /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves 365224145Sdim /// some overhead due to the use of Value handles which the Linker doesn't 366224145Sdim /// actually need, but this allows us to reuse the ValueMapper code. 367224145Sdim ValueToValueMapTy ValueMap; 368224145Sdim 369224145Sdim struct AppendingVarInfo { 370224145Sdim GlobalVariable *NewGV; // New aggregate global in dest module. 371224145Sdim Constant *DstInit; // Old initializer from dest module. 372224145Sdim Constant *SrcInit; // Old initializer from src module. 373224145Sdim }; 374224145Sdim 375224145Sdim std::vector<AppendingVarInfo> AppendingVars; 376224145Sdim 377226633Sdim unsigned Mode; // Mode to treat source module. 378226633Sdim 379226633Sdim // Set of items not to link in from source. 380226633Sdim SmallPtrSet<const Value*, 16> DoNotLinkFromSource; 381226633Sdim 382234353Sdim // Vector of functions to lazily link in. 383234353Sdim std::vector<Function*> LazilyLinkFunctions; 384234353Sdim 385224145Sdim public: 386224145Sdim std::string ErrorMsg; 387224145Sdim 388251662Sdim ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, unsigned mode) 389251662Sdim : DstM(dstM), SrcM(srcM), TypeMap(Set), Mode(mode) { } 390224145Sdim 391224145Sdim bool run(); 392224145Sdim 393224145Sdim private: 394224145Sdim /// emitError - Helper method for setting a message and returning an error 395224145Sdim /// code. 396224145Sdim bool emitError(const Twine &Message) { 397224145Sdim ErrorMsg = Message.str(); 398224145Sdim return true; 399193323Sed } 400224145Sdim 401224145Sdim /// getLinkageResult - This analyzes the two global values and determines 402224145Sdim /// what the result will look like in the destination module. 403224145Sdim bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src, 404234353Sdim GlobalValue::LinkageTypes <, 405234353Sdim GlobalValue::VisibilityTypes &Vis, 406234353Sdim bool &LinkFromSrc); 407193323Sed 408224145Sdim /// getLinkedToGlobal - Given a global in the source module, return the 409224145Sdim /// global in the destination module that is being linked to, if any. 410224145Sdim GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) { 411224145Sdim // If the source has no name it can't link. If it has local linkage, 412224145Sdim // there is no name match-up going on. 413224145Sdim if (!SrcGV->hasName() || SrcGV->hasLocalLinkage()) 414224145Sdim return 0; 415224145Sdim 416224145Sdim // Otherwise see if we have a match in the destination module's symtab. 417224145Sdim GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName()); 418224145Sdim if (DGV == 0) return 0; 419224145Sdim 420224145Sdim // If we found a global with the same name in the dest module, but it has 421224145Sdim // internal linkage, we are really not doing any linkage here. 422224145Sdim if (DGV->hasLocalLinkage()) 423224145Sdim return 0; 424193323Sed 425224145Sdim // Otherwise, we do in fact link to the destination global. 426224145Sdim return DGV; 427193323Sed } 428224145Sdim 429224145Sdim void computeTypeMapping(); 430224145Sdim 431224145Sdim bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV); 432224145Sdim bool linkGlobalProto(GlobalVariable *SrcGV); 433224145Sdim bool linkFunctionProto(Function *SrcF); 434224145Sdim bool linkAliasProto(GlobalAlias *SrcA); 435234353Sdim bool linkModuleFlagsMetadata(); 436224145Sdim 437224145Sdim void linkAppendingVarInit(const AppendingVarInfo &AVI); 438224145Sdim void linkGlobalInits(); 439224145Sdim void linkFunctionBody(Function *Dst, Function *Src); 440224145Sdim void linkAliasBodies(); 441224145Sdim void linkNamedMDNodes(); 442224145Sdim }; 443224145Sdim} 444193323Sed 445224145Sdim/// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict 446193323Sed/// in the symbol table. This is good for all clients except for us. Go 447193323Sed/// through the trouble to force this back. 448224145Sdimstatic void forceRenaming(GlobalValue *GV, StringRef Name) { 449224145Sdim // If the global doesn't force its name or if it already has the right name, 450224145Sdim // there is nothing for us to do. 451224145Sdim if (GV->hasLocalLinkage() || GV->getName() == Name) 452224145Sdim return; 453193323Sed 454224145Sdim Module *M = GV->getParent(); 455224145Sdim 456193323Sed // If there is a conflict, rename the conflict. 457224145Sdim if (GlobalValue *ConflictGV = M->getNamedValue(Name)) { 458193323Sed GV->takeName(ConflictGV); 459193323Sed ConflictGV->setName(Name); // This will cause ConflictGV to get renamed 460224145Sdim assert(ConflictGV->getName() != Name && "forceRenaming didn't work"); 461193323Sed } else { 462193323Sed GV->setName(Name); // Force the name back 463193323Sed } 464193323Sed} 465193323Sed 466234353Sdim/// copyGVAttributes - copy additional attributes (those not needed to construct 467193323Sed/// a GlobalValue) from the SrcGV to the DestGV. 468234353Sdimstatic void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) { 469193323Sed // Use the maximum alignment, rather than just copying the alignment of SrcGV. 470193323Sed unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment()); 471193323Sed DestGV->copyAttributesFrom(SrcGV); 472193323Sed DestGV->setAlignment(Alignment); 473224145Sdim 474224145Sdim forceRenaming(DestGV, SrcGV->getName()); 475193323Sed} 476193323Sed 477234353Sdimstatic bool isLessConstraining(GlobalValue::VisibilityTypes a, 478234353Sdim GlobalValue::VisibilityTypes b) { 479234353Sdim if (a == GlobalValue::HiddenVisibility) 480234353Sdim return false; 481234353Sdim if (b == GlobalValue::HiddenVisibility) 482234353Sdim return true; 483234353Sdim if (a == GlobalValue::ProtectedVisibility) 484234353Sdim return false; 485234353Sdim if (b == GlobalValue::ProtectedVisibility) 486234353Sdim return true; 487234353Sdim return false; 488234353Sdim} 489234353Sdim 490224145Sdim/// getLinkageResult - This analyzes the two global values and determines what 491193323Sed/// the result will look like in the destination module. In particular, it 492234353Sdim/// computes the resultant linkage type and visibility, computes whether the 493234353Sdim/// global in the source should be copied over to the destination (replacing 494234353Sdim/// the existing one), and computes whether this linkage is an error or not. 495224145Sdimbool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src, 496234353Sdim GlobalValue::LinkageTypes <, 497234353Sdim GlobalValue::VisibilityTypes &Vis, 498224145Sdim bool &LinkFromSrc) { 499224145Sdim assert(Dest && "Must have two globals being queried"); 500224145Sdim assert(!Src->hasLocalLinkage() && 501193323Sed "If Src has internal linkage, Dest shouldn't be set!"); 502224145Sdim 503234353Sdim bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable(); 504224145Sdim bool DestIsDeclaration = Dest->isDeclaration(); 505224145Sdim 506224145Sdim if (SrcIsDeclaration) { 507193323Sed // If Src is external or if both Src & Dest are external.. Just link the 508193323Sed // external globals, we aren't adding anything. 509193323Sed if (Src->hasDLLImportLinkage()) { 510193323Sed // If one of GVs has DLLImport linkage, result should be dllimport'ed. 511224145Sdim if (DestIsDeclaration) { 512193323Sed LinkFromSrc = true; 513193323Sed LT = Src->getLinkage(); 514193323Sed } 515193323Sed } else if (Dest->hasExternalWeakLinkage()) { 516193323Sed // If the Dest is weak, use the source linkage. 517193323Sed LinkFromSrc = true; 518193323Sed LT = Src->getLinkage(); 519193323Sed } else { 520193323Sed LinkFromSrc = false; 521193323Sed LT = Dest->getLinkage(); 522193323Sed } 523224145Sdim } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) { 524193323Sed // If Dest is external but Src is not: 525193323Sed LinkFromSrc = true; 526193323Sed LT = Src->getLinkage(); 527193323Sed } else if (Src->isWeakForLinker()) { 528193323Sed // At this point we know that Dest has LinkOnce, External*, Weak, Common, 529193323Sed // or DLL* linkage. 530193323Sed if (Dest->hasExternalWeakLinkage() || 531193323Sed Dest->hasAvailableExternallyLinkage() || 532193323Sed (Dest->hasLinkOnceLinkage() && 533193323Sed (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) { 534193323Sed LinkFromSrc = true; 535193323Sed LT = Src->getLinkage(); 536193323Sed } else { 537193323Sed LinkFromSrc = false; 538193323Sed LT = Dest->getLinkage(); 539193323Sed } 540193323Sed } else if (Dest->isWeakForLinker()) { 541193323Sed // At this point we know that Src has External* or DLL* linkage. 542193323Sed if (Src->hasExternalWeakLinkage()) { 543193323Sed LinkFromSrc = false; 544193323Sed LT = Dest->getLinkage(); 545193323Sed } else { 546193323Sed LinkFromSrc = true; 547193323Sed LT = GlobalValue::ExternalLinkage; 548193323Sed } 549193323Sed } else { 550224145Sdim assert((Dest->hasExternalLinkage() || Dest->hasDLLImportLinkage() || 551224145Sdim Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) && 552224145Sdim (Src->hasExternalLinkage() || Src->hasDLLImportLinkage() || 553224145Sdim Src->hasDLLExportLinkage() || Src->hasExternalWeakLinkage()) && 554193323Sed "Unexpected linkage type!"); 555224145Sdim return emitError("Linking globals named '" + Src->getName() + 556193323Sed "': symbol multiply defined!"); 557193323Sed } 558193323Sed 559234353Sdim // Compute the visibility. We follow the rules in the System V Application 560234353Sdim // Binary Interface. 561234353Sdim Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ? 562234353Sdim Dest->getVisibility() : Src->getVisibility(); 563193323Sed return false; 564193323Sed} 565193323Sed 566224145Sdim/// computeTypeMapping - Loop over all of the linked values to compute type 567224145Sdim/// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then 568224145Sdim/// we have two struct types 'Foo' but one got renamed when the module was 569224145Sdim/// loaded into the same LLVMContext. 570224145Sdimvoid ModuleLinker::computeTypeMapping() { 571224145Sdim // Incorporate globals. 572224145Sdim for (Module::global_iterator I = SrcM->global_begin(), 573224145Sdim E = SrcM->global_end(); I != E; ++I) { 574224145Sdim GlobalValue *DGV = getLinkedToGlobal(I); 575224145Sdim if (DGV == 0) continue; 576224145Sdim 577224145Sdim if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) { 578224145Sdim TypeMap.addTypeMapping(DGV->getType(), I->getType()); 579224145Sdim continue; 580224145Sdim } 581224145Sdim 582224145Sdim // Unify the element type of appending arrays. 583224145Sdim ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType()); 584224145Sdim ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType()); 585224145Sdim TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType()); 586198090Srdivacky } 587224145Sdim 588224145Sdim // Incorporate functions. 589224145Sdim for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) { 590224145Sdim if (GlobalValue *DGV = getLinkedToGlobal(I)) 591224145Sdim TypeMap.addTypeMapping(DGV->getType(), I->getType()); 592224145Sdim } 593234353Sdim 594234353Sdim // Incorporate types by name, scanning all the types in the source module. 595234353Sdim // At this point, the destination module may have a type "%foo = { i32 }" for 596234353Sdim // example. When the source module got loaded into the same LLVMContext, if 597234353Sdim // it had the same type, it would have been renamed to "%foo.42 = { i32 }". 598239462Sdim TypeFinder SrcStructTypes; 599239462Sdim SrcStructTypes.run(*SrcM, true); 600234353Sdim SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(), 601234353Sdim SrcStructTypes.end()); 602234353Sdim 603234353Sdim for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) { 604234353Sdim StructType *ST = SrcStructTypes[i]; 605234353Sdim if (!ST->hasName()) continue; 606234353Sdim 607234353Sdim // Check to see if there is a dot in the name followed by a digit. 608234353Sdim size_t DotPos = ST->getName().rfind('.'); 609234353Sdim if (DotPos == 0 || DotPos == StringRef::npos || 610249423Sdim ST->getName().back() == '.' || 611249423Sdim !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1]))) 612234353Sdim continue; 613234353Sdim 614234353Sdim // Check to see if the destination module has a struct with the prefix name. 615234353Sdim if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos))) 616234353Sdim // Don't use it if this actually came from the source module. They're in 617234353Sdim // the same LLVMContext after all. Also don't use it unless the type is 618234353Sdim // actually used in the destination module. This can happen in situations 619234353Sdim // like this: 620234353Sdim // 621234353Sdim // Module A Module B 622234353Sdim // -------- -------- 623234353Sdim // %Z = type { %A } %B = type { %C.1 } 624234353Sdim // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* } 625234353Sdim // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] } 626234353Sdim // %C = type { i8* } %B.3 = type { %C.1 } 627234353Sdim // 628234353Sdim // When we link Module B with Module A, the '%B' in Module B is 629234353Sdim // used. However, that would then use '%C.1'. But when we process '%C.1', 630234353Sdim // we prefer to take the '%C' version. So we are then left with both 631234353Sdim // '%C.1' and '%C' being used for the same types. This leads to some 632234353Sdim // variables using one type and some using the other. 633251662Sdim if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST)) 634234353Sdim TypeMap.addTypeMapping(DST, ST); 635234353Sdim } 636234353Sdim 637224145Sdim // Don't bother incorporating aliases, they aren't generally typed well. 638224145Sdim 639224145Sdim // Now that we have discovered all of the type equivalences, get a body for 640224145Sdim // any 'opaque' types in the dest module that are now resolved. 641224145Sdim TypeMap.linkDefinedTypeBodies(); 642198090Srdivacky} 643198090Srdivacky 644224145Sdim/// linkAppendingVarProto - If there were any appending global variables, link 645224145Sdim/// them together now. Return true on error. 646224145Sdimbool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV, 647224145Sdim GlobalVariable *SrcGV) { 648224145Sdim 649224145Sdim if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) 650224145Sdim return emitError("Linking globals named '" + SrcGV->getName() + 651224145Sdim "': can only link appending global with another appending global!"); 652224145Sdim 653224145Sdim ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType()); 654224145Sdim ArrayType *SrcTy = 655224145Sdim cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType())); 656224145Sdim Type *EltTy = DstTy->getElementType(); 657224145Sdim 658224145Sdim // Check to see that they two arrays agree on type. 659224145Sdim if (EltTy != SrcTy->getElementType()) 660224145Sdim return emitError("Appending variables with different element types!"); 661224145Sdim if (DstGV->isConstant() != SrcGV->isConstant()) 662224145Sdim return emitError("Appending variables linked with different const'ness!"); 663224145Sdim 664224145Sdim if (DstGV->getAlignment() != SrcGV->getAlignment()) 665224145Sdim return emitError( 666224145Sdim "Appending variables with different alignment need to be linked!"); 667224145Sdim 668224145Sdim if (DstGV->getVisibility() != SrcGV->getVisibility()) 669224145Sdim return emitError( 670224145Sdim "Appending variables with different visibility need to be linked!"); 671224145Sdim 672224145Sdim if (DstGV->getSection() != SrcGV->getSection()) 673224145Sdim return emitError( 674224145Sdim "Appending variables with different section name need to be linked!"); 675224145Sdim 676224145Sdim uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements(); 677224145Sdim ArrayType *NewType = ArrayType::get(EltTy, NewSize); 678224145Sdim 679224145Sdim // Create the new global variable. 680224145Sdim GlobalVariable *NG = 681224145Sdim new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(), 682224145Sdim DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV, 683239462Sdim DstGV->getThreadLocalMode(), 684224145Sdim DstGV->getType()->getAddressSpace()); 685224145Sdim 686224145Sdim // Propagate alignment, visibility and section info. 687234353Sdim copyGVAttributes(NG, DstGV); 688224145Sdim 689224145Sdim AppendingVarInfo AVI; 690224145Sdim AVI.NewGV = NG; 691224145Sdim AVI.DstInit = DstGV->getInitializer(); 692224145Sdim AVI.SrcInit = SrcGV->getInitializer(); 693224145Sdim AppendingVars.push_back(AVI); 694193323Sed 695224145Sdim // Replace any uses of the two global variables with uses of the new 696224145Sdim // global. 697224145Sdim ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType())); 698193323Sed 699224145Sdim DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType())); 700224145Sdim DstGV->eraseFromParent(); 701224145Sdim 702226633Sdim // Track the source variable so we don't try to link it. 703226633Sdim DoNotLinkFromSource.insert(SrcGV); 704226633Sdim 705224145Sdim return false; 706224145Sdim} 707193323Sed 708224145Sdim/// linkGlobalProto - Loop through the global variables in the src module and 709224145Sdim/// merge them into the dest module. 710224145Sdimbool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) { 711224145Sdim GlobalValue *DGV = getLinkedToGlobal(SGV); 712234353Sdim llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility; 713193323Sed 714224145Sdim if (DGV) { 715224145Sdim // Concatenation of appending linkage variables is magic and handled later. 716224145Sdim if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage()) 717224145Sdim return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV); 718224145Sdim 719224145Sdim // Determine whether linkage of these two globals follows the source 720224145Sdim // module's definition or the destination module's definition. 721193323Sed GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage; 722234353Sdim GlobalValue::VisibilityTypes NV; 723193323Sed bool LinkFromSrc = false; 724234353Sdim if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc)) 725193323Sed return true; 726234353Sdim NewVisibility = NV; 727193323Sed 728224145Sdim // If we're not linking from the source, then keep the definition that we 729224145Sdim // have. 730224145Sdim if (!LinkFromSrc) { 731224145Sdim // Special case for const propagation. 732224145Sdim if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) 733224145Sdim if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant()) 734224145Sdim DGVar->setConstant(true); 735224145Sdim 736234353Sdim // Set calculated linkage and visibility. 737224145Sdim DGV->setLinkage(NewLinkage); 738234353Sdim DGV->setVisibility(*NewVisibility); 739234353Sdim 740193323Sed // Make sure to remember this mapping. 741224145Sdim ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType())); 742224145Sdim 743226633Sdim // Track the source global so that we don't attempt to copy it over when 744226633Sdim // processing global initializers. 745226633Sdim DoNotLinkFromSource.insert(SGV); 746226633Sdim 747224145Sdim return false; 748193323Sed } 749224145Sdim } 750224145Sdim 751224145Sdim // No linking to be performed or linking from the source: simply create an 752224145Sdim // identical version of the symbol over in the dest module... the 753224145Sdim // initializer will be filled in later by LinkGlobalInits. 754224145Sdim GlobalVariable *NewDGV = 755224145Sdim new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()), 756224145Sdim SGV->isConstant(), SGV->getLinkage(), /*init*/0, 757224145Sdim SGV->getName(), /*insertbefore*/0, 758239462Sdim SGV->getThreadLocalMode(), 759224145Sdim SGV->getType()->getAddressSpace()); 760224145Sdim // Propagate alignment, visibility and section info. 761234353Sdim copyGVAttributes(NewDGV, SGV); 762234353Sdim if (NewVisibility) 763234353Sdim NewDGV->setVisibility(*NewVisibility); 764193323Sed 765224145Sdim if (DGV) { 766224145Sdim DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType())); 767224145Sdim DGV->eraseFromParent(); 768193323Sed } 769224145Sdim 770224145Sdim // Make sure to remember this mapping. 771224145Sdim ValueMap[SGV] = NewDGV; 772193323Sed return false; 773193323Sed} 774193323Sed 775224145Sdim/// linkFunctionProto - Link the function in the source module into the 776224145Sdim/// destination module if needed, setting up mapping information. 777224145Sdimbool ModuleLinker::linkFunctionProto(Function *SF) { 778224145Sdim GlobalValue *DGV = getLinkedToGlobal(SF); 779234353Sdim llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility; 780193323Sed 781224145Sdim if (DGV) { 782224145Sdim GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage; 783224145Sdim bool LinkFromSrc = false; 784234353Sdim GlobalValue::VisibilityTypes NV; 785234353Sdim if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc)) 786224145Sdim return true; 787234353Sdim NewVisibility = NV; 788234353Sdim 789224145Sdim if (!LinkFromSrc) { 790224145Sdim // Set calculated linkage 791224145Sdim DGV->setLinkage(NewLinkage); 792234353Sdim DGV->setVisibility(*NewVisibility); 793234353Sdim 794224145Sdim // Make sure to remember this mapping. 795224145Sdim ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType())); 796224145Sdim 797226633Sdim // Track the function from the source module so we don't attempt to remap 798226633Sdim // it. 799226633Sdim DoNotLinkFromSource.insert(SF); 800226633Sdim 801224145Sdim return false; 802193323Sed } 803193323Sed } 804224145Sdim 805224145Sdim // If there is no linkage to be performed or we are linking from the source, 806224145Sdim // bring SF over. 807224145Sdim Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()), 808224145Sdim SF->getLinkage(), SF->getName(), DstM); 809234353Sdim copyGVAttributes(NewDF, SF); 810234353Sdim if (NewVisibility) 811234353Sdim NewDF->setVisibility(*NewVisibility); 812193323Sed 813224145Sdim if (DGV) { 814224145Sdim // Any uses of DF need to change to NewDF, with cast. 815224145Sdim DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType())); 816224145Sdim DGV->eraseFromParent(); 817234353Sdim } else { 818234353Sdim // Internal, LO_ODR, or LO linkage - stick in set to ignore and lazily link. 819234353Sdim if (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() || 820234353Sdim SF->hasAvailableExternallyLinkage()) { 821234353Sdim DoNotLinkFromSource.insert(SF); 822234353Sdim LazilyLinkFunctions.push_back(SF); 823234353Sdim } 824193323Sed } 825224145Sdim 826224145Sdim ValueMap[SF] = NewDF; 827193323Sed return false; 828193323Sed} 829193323Sed 830224145Sdim/// LinkAliasProto - Set up prototypes for any aliases that come over from the 831224145Sdim/// source module. 832224145Sdimbool ModuleLinker::linkAliasProto(GlobalAlias *SGA) { 833224145Sdim GlobalValue *DGV = getLinkedToGlobal(SGA); 834234353Sdim llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility; 835234353Sdim 836224145Sdim if (DGV) { 837193323Sed GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage; 838234353Sdim GlobalValue::VisibilityTypes NV; 839193323Sed bool LinkFromSrc = false; 840234353Sdim if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc)) 841193323Sed return true; 842234353Sdim NewVisibility = NV; 843234353Sdim 844224145Sdim if (!LinkFromSrc) { 845224145Sdim // Set calculated linkage. 846224145Sdim DGV->setLinkage(NewLinkage); 847234353Sdim DGV->setVisibility(*NewVisibility); 848234353Sdim 849224145Sdim // Make sure to remember this mapping. 850224145Sdim ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType())); 851224145Sdim 852226633Sdim // Track the alias from the source module so we don't attempt to remap it. 853226633Sdim DoNotLinkFromSource.insert(SGA); 854226633Sdim 855224145Sdim return false; 856193323Sed } 857224145Sdim } 858224145Sdim 859224145Sdim // If there is no linkage to be performed or we're linking from the source, 860224145Sdim // bring over SGA. 861224145Sdim GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()), 862224145Sdim SGA->getLinkage(), SGA->getName(), 863224145Sdim /*aliasee*/0, DstM); 864234353Sdim copyGVAttributes(NewDA, SGA); 865234353Sdim if (NewVisibility) 866234353Sdim NewDA->setVisibility(*NewVisibility); 867193323Sed 868224145Sdim if (DGV) { 869224145Sdim // Any uses of DGV need to change to NewDA, with cast. 870224145Sdim DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType())); 871224145Sdim DGV->eraseFromParent(); 872224145Sdim } 873224145Sdim 874224145Sdim ValueMap[SGA] = NewDA; 875224145Sdim return false; 876224145Sdim} 877193323Sed 878234353Sdimstatic void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) { 879234353Sdim unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements(); 880234353Sdim 881234353Sdim for (unsigned i = 0; i != NumElements; ++i) 882234353Sdim Dest.push_back(C->getAggregateElement(i)); 883234353Sdim} 884234353Sdim 885224145Sdimvoid ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) { 886224145Sdim // Merge the initializer. 887224145Sdim SmallVector<Constant*, 16> Elements; 888234353Sdim getArrayElements(AVI.DstInit, Elements); 889224145Sdim 890224145Sdim Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap); 891234353Sdim getArrayElements(SrcInit, Elements); 892234353Sdim 893224145Sdim ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType()); 894224145Sdim AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements)); 895224145Sdim} 896193323Sed 897234353Sdim/// linkGlobalInits - Update the initializers in the Dest module now that all 898234353Sdim/// globals that may be referenced are in Dest. 899224145Sdimvoid ModuleLinker::linkGlobalInits() { 900224145Sdim // Loop over all of the globals in the src module, mapping them over as we go 901224145Sdim for (Module::const_global_iterator I = SrcM->global_begin(), 902224145Sdim E = SrcM->global_end(); I != E; ++I) { 903224145Sdim 904226633Sdim // Only process initialized GV's or ones not already in dest. 905226633Sdim if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue; 906226633Sdim 907224145Sdim // Grab destination global variable. 908224145Sdim GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]); 909224145Sdim // Figure out what the initializer looks like in the dest module. 910224145Sdim DGV->setInitializer(MapValue(I->getInitializer(), ValueMap, 911224145Sdim RF_None, &TypeMap)); 912193323Sed } 913193323Sed} 914193323Sed 915234353Sdim/// linkFunctionBody - Copy the source function over into the dest function and 916234353Sdim/// fix up references to values. At this point we know that Dest is an external 917234353Sdim/// function, and that Src is not. 918224145Sdimvoid ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) { 919224145Sdim assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration()); 920193323Sed 921193323Sed // Go through and convert function arguments over, remembering the mapping. 922224145Sdim Function::arg_iterator DI = Dst->arg_begin(); 923193323Sed for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end(); 924193323Sed I != E; ++I, ++DI) { 925224145Sdim DI->setName(I->getName()); // Copy the name over. 926193323Sed 927224145Sdim // Add a mapping to our mapping. 928193323Sed ValueMap[I] = DI; 929193323Sed } 930193323Sed 931226633Sdim if (Mode == Linker::DestroySource) { 932226633Sdim // Splice the body of the source function into the dest function. 933226633Sdim Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList()); 934226633Sdim 935226633Sdim // At this point, all of the instructions and values of the function are now 936226633Sdim // copied over. The only problem is that they are still referencing values in 937226633Sdim // the Source function as operands. Loop through all of the operands of the 938226633Sdim // functions and patch them up to point to the local versions. 939226633Sdim for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB) 940226633Sdim for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 941226633Sdim RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap); 942226633Sdim 943226633Sdim } else { 944226633Sdim // Clone the body of the function into the dest function. 945226633Sdim SmallVector<ReturnInst*, 8> Returns; // Ignore returns. 946234353Sdim CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL, &TypeMap); 947226633Sdim } 948226633Sdim 949193323Sed // There is no need to map the arguments anymore. 950193323Sed for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end(); 951193323Sed I != E; ++I) 952193323Sed ValueMap.erase(I); 953226633Sdim 954193323Sed} 955193323Sed 956234353Sdim/// linkAliasBodies - Insert all of the aliases in Src into the Dest module. 957224145Sdimvoid ModuleLinker::linkAliasBodies() { 958224145Sdim for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end(); 959226633Sdim I != E; ++I) { 960226633Sdim if (DoNotLinkFromSource.count(I)) 961226633Sdim continue; 962224145Sdim if (Constant *Aliasee = I->getAliasee()) { 963224145Sdim GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]); 964224145Sdim DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None, &TypeMap)); 965193323Sed } 966226633Sdim } 967193323Sed} 968193323Sed 969234353Sdim/// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest 970224145Sdim/// module. 971224145Sdimvoid ModuleLinker::linkNamedMDNodes() { 972234353Sdim const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); 973224145Sdim for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(), 974224145Sdim E = SrcM->named_metadata_end(); I != E; ++I) { 975234353Sdim // Don't link module flags here. Do them separately. 976234353Sdim if (&*I == SrcModFlags) continue; 977224145Sdim NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName()); 978224145Sdim // Add Src elements into Dest node. 979224145Sdim for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 980224145Sdim DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap, 981224145Sdim RF_None, &TypeMap)); 982193323Sed } 983193323Sed} 984234353Sdim 985234353Sdim/// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest 986234353Sdim/// module. 987234353Sdimbool ModuleLinker::linkModuleFlagsMetadata() { 988249423Sdim // If the source module has no module flags, we are done. 989234353Sdim const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); 990234353Sdim if (!SrcModFlags) return false; 991234353Sdim 992234353Sdim // If the destination module doesn't have module flags yet, then just copy 993234353Sdim // over the source module's flags. 994249423Sdim NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata(); 995234353Sdim if (DstModFlags->getNumOperands() == 0) { 996234353Sdim for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) 997234353Sdim DstModFlags->addOperand(SrcModFlags->getOperand(I)); 998234353Sdim 999234353Sdim return false; 1000234353Sdim } 1001234353Sdim 1002249423Sdim // First build a map of the existing module flags and requirements. 1003249423Sdim DenseMap<MDString*, MDNode*> Flags; 1004249423Sdim SmallSetVector<MDNode*, 16> Requirements; 1005249423Sdim for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) { 1006249423Sdim MDNode *Op = DstModFlags->getOperand(I); 1007249423Sdim ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0)); 1008249423Sdim MDString *ID = cast<MDString>(Op->getOperand(1)); 1009234353Sdim 1010249423Sdim if (Behavior->getZExtValue() == Module::Require) { 1011249423Sdim Requirements.insert(cast<MDNode>(Op->getOperand(2))); 1012249423Sdim } else { 1013249423Sdim Flags[ID] = Op; 1014249423Sdim } 1015234353Sdim } 1016234353Sdim 1017249423Sdim // Merge in the flags from the source module, and also collect its set of 1018249423Sdim // requirements. 1019249423Sdim bool HasErr = false; 1020249423Sdim for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) { 1021249423Sdim MDNode *SrcOp = SrcModFlags->getOperand(I); 1022249423Sdim ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0)); 1023249423Sdim MDString *ID = cast<MDString>(SrcOp->getOperand(1)); 1024249423Sdim MDNode *DstOp = Flags.lookup(ID); 1025249423Sdim unsigned SrcBehaviorValue = SrcBehavior->getZExtValue(); 1026234353Sdim 1027249423Sdim // If this is a requirement, add it and continue. 1028249423Sdim if (SrcBehaviorValue == Module::Require) { 1029249423Sdim // If the destination module does not already have this requirement, add 1030249423Sdim // it. 1031249423Sdim if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) { 1032249423Sdim DstModFlags->addOperand(SrcOp); 1033249423Sdim } 1034249423Sdim continue; 1035249423Sdim } 1036234353Sdim 1037249423Sdim // If there is no existing flag with this ID, just add it. 1038249423Sdim if (!DstOp) { 1039249423Sdim Flags[ID] = SrcOp; 1040249423Sdim DstModFlags->addOperand(SrcOp); 1041249423Sdim continue; 1042234353Sdim } 1043234353Sdim 1044249423Sdim // Otherwise, perform a merge. 1045249423Sdim ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0)); 1046249423Sdim unsigned DstBehaviorValue = DstBehavior->getZExtValue(); 1047234353Sdim 1048249423Sdim // If either flag has override behavior, handle it first. 1049249423Sdim if (DstBehaviorValue == Module::Override) { 1050249423Sdim // Diagnose inconsistent flags which both have override behavior. 1051249423Sdim if (SrcBehaviorValue == Module::Override && 1052249423Sdim SrcOp->getOperand(2) != DstOp->getOperand(2)) { 1053249423Sdim HasErr |= emitError("linking module flags '" + ID->getString() + 1054249423Sdim "': IDs have conflicting override values"); 1055249423Sdim } 1056249423Sdim continue; 1057249423Sdim } else if (SrcBehaviorValue == Module::Override) { 1058249423Sdim // Update the destination flag to that of the source. 1059249423Sdim DstOp->replaceOperandWith(0, SrcBehavior); 1060249423Sdim DstOp->replaceOperandWith(2, SrcOp->getOperand(2)); 1061249423Sdim continue; 1062249423Sdim } 1063234353Sdim 1064249423Sdim // Diagnose inconsistent merge behavior types. 1065249423Sdim if (SrcBehaviorValue != DstBehaviorValue) { 1066249423Sdim HasErr |= emitError("linking module flags '" + ID->getString() + 1067249423Sdim "': IDs have conflicting behaviors"); 1068249423Sdim continue; 1069249423Sdim } 1070234353Sdim 1071249423Sdim // Perform the merge for standard behavior types. 1072249423Sdim switch (SrcBehaviorValue) { 1073249423Sdim case Module::Require: 1074249423Sdim case Module::Override: assert(0 && "not possible"); break; 1075249423Sdim case Module::Error: { 1076249423Sdim // Emit an error if the values differ. 1077249423Sdim if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { 1078249423Sdim HasErr |= emitError("linking module flags '" + ID->getString() + 1079249423Sdim "': IDs have conflicting values"); 1080234353Sdim } 1081249423Sdim continue; 1082249423Sdim } 1083249423Sdim case Module::Warning: { 1084249423Sdim // Emit a warning if the values differ. 1085249423Sdim if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { 1086249423Sdim errs() << "WARNING: linking module flags '" << ID->getString() 1087249423Sdim << "': IDs have conflicting values"; 1088249423Sdim } 1089249423Sdim continue; 1090249423Sdim } 1091249423Sdim case Module::Append: { 1092249423Sdim MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); 1093249423Sdim MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); 1094249423Sdim unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands(); 1095249423Sdim Value **VP, **Values = VP = new Value*[NumOps]; 1096249423Sdim for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP) 1097249423Sdim *VP = DstValue->getOperand(i); 1098249423Sdim for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP) 1099249423Sdim *VP = SrcValue->getOperand(i); 1100249423Sdim DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(), 1101249423Sdim ArrayRef<Value*>(Values, 1102249423Sdim NumOps))); 1103249423Sdim delete[] Values; 1104249423Sdim break; 1105249423Sdim } 1106249423Sdim case Module::AppendUnique: { 1107249423Sdim SmallSetVector<Value*, 16> Elts; 1108249423Sdim MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); 1109249423Sdim MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); 1110249423Sdim for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i) 1111249423Sdim Elts.insert(DstValue->getOperand(i)); 1112249423Sdim for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i) 1113249423Sdim Elts.insert(SrcValue->getOperand(i)); 1114249423Sdim DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(), 1115249423Sdim ArrayRef<Value*>(Elts.begin(), 1116249423Sdim Elts.end()))); 1117249423Sdim break; 1118249423Sdim } 1119249423Sdim } 1120249423Sdim } 1121234353Sdim 1122249423Sdim // Check all of the requirements. 1123249423Sdim for (unsigned I = 0, E = Requirements.size(); I != E; ++I) { 1124249423Sdim MDNode *Requirement = Requirements[I]; 1125249423Sdim MDString *Flag = cast<MDString>(Requirement->getOperand(0)); 1126249423Sdim Value *ReqValue = Requirement->getOperand(1); 1127249423Sdim 1128249423Sdim MDNode *Op = Flags[Flag]; 1129249423Sdim if (!Op || Op->getOperand(2) != ReqValue) { 1130249423Sdim HasErr |= emitError("linking module flags '" + Flag->getString() + 1131249423Sdim "': does not have the required value"); 1132249423Sdim continue; 1133234353Sdim } 1134234353Sdim } 1135234353Sdim 1136234353Sdim return HasErr; 1137234353Sdim} 1138224145Sdim 1139224145Sdimbool ModuleLinker::run() { 1140234353Sdim assert(DstM && "Null destination module"); 1141234353Sdim assert(SrcM && "Null source module"); 1142193323Sed 1143224145Sdim // Inherit the target data from the source module if the destination module 1144224145Sdim // doesn't have one already. 1145224145Sdim if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty()) 1146224145Sdim DstM->setDataLayout(SrcM->getDataLayout()); 1147193323Sed 1148193323Sed // Copy the target triple from the source to dest if the dest's is empty. 1149224145Sdim if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty()) 1150224145Sdim DstM->setTargetTriple(SrcM->getTargetTriple()); 1151193323Sed 1152224145Sdim if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() && 1153224145Sdim SrcM->getDataLayout() != DstM->getDataLayout()) 1154198090Srdivacky errs() << "WARNING: Linking two modules of different data layouts!\n"; 1155224145Sdim if (!SrcM->getTargetTriple().empty() && 1156224145Sdim DstM->getTargetTriple() != SrcM->getTargetTriple()) { 1157218893Sdim errs() << "WARNING: Linking two modules of different target triples: "; 1158224145Sdim if (!SrcM->getModuleIdentifier().empty()) 1159224145Sdim errs() << SrcM->getModuleIdentifier() << ": "; 1160224145Sdim errs() << "'" << SrcM->getTargetTriple() << "' and '" 1161224145Sdim << DstM->getTargetTriple() << "'\n"; 1162218893Sdim } 1163193323Sed 1164193323Sed // Append the module inline asm string. 1165224145Sdim if (!SrcM->getModuleInlineAsm().empty()) { 1166224145Sdim if (DstM->getModuleInlineAsm().empty()) 1167224145Sdim DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm()); 1168193323Sed else 1169224145Sdim DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+ 1170224145Sdim SrcM->getModuleInlineAsm()); 1171193323Sed } 1172193323Sed 1173224145Sdim // Loop over all of the linked values to compute type mappings. 1174224145Sdim computeTypeMapping(); 1175193323Sed 1176224145Sdim // Insert all of the globals in src into the DstM module... without linking 1177193323Sed // initializers (which could refer to functions not yet mapped over). 1178224145Sdim for (Module::global_iterator I = SrcM->global_begin(), 1179224145Sdim E = SrcM->global_end(); I != E; ++I) 1180224145Sdim if (linkGlobalProto(I)) 1181224145Sdim return true; 1182193323Sed 1183193323Sed // Link the functions together between the two modules, without doing function 1184224145Sdim // bodies... this just adds external function prototypes to the DstM 1185193323Sed // function... We do this so that when we begin processing function bodies, 1186193323Sed // all of the global values that may be referenced are available in our 1187193323Sed // ValueMap. 1188224145Sdim for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) 1189224145Sdim if (linkFunctionProto(I)) 1190224145Sdim return true; 1191193323Sed 1192224145Sdim // If there were any aliases, link them now. 1193224145Sdim for (Module::alias_iterator I = SrcM->alias_begin(), 1194224145Sdim E = SrcM->alias_end(); I != E; ++I) 1195224145Sdim if (linkAliasProto(I)) 1196224145Sdim return true; 1197193323Sed 1198224145Sdim for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i) 1199224145Sdim linkAppendingVarInit(AppendingVars[i]); 1200224145Sdim 1201224145Sdim // Update the initializers in the DstM module now that all globals that may 1202224145Sdim // be referenced are in DstM. 1203224145Sdim linkGlobalInits(); 1204193323Sed 1205224145Sdim // Link in the function bodies that are defined in the source module into 1206224145Sdim // DstM. 1207224145Sdim for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) { 1208226633Sdim // Skip if not linking from source. 1209226633Sdim if (DoNotLinkFromSource.count(SF)) continue; 1210226633Sdim 1211226633Sdim // Skip if no body (function is external) or materialize. 1212226633Sdim if (SF->isDeclaration()) { 1213226633Sdim if (!SF->isMaterializable()) 1214226633Sdim continue; 1215226633Sdim if (SF->Materialize(&ErrorMsg)) 1216226633Sdim return true; 1217226633Sdim } 1218226633Sdim 1219224145Sdim linkFunctionBody(cast<Function>(ValueMap[SF]), SF); 1220234353Sdim SF->Dematerialize(); 1221224145Sdim } 1222193323Sed 1223224145Sdim // Resolve all uses of aliases with aliasees. 1224224145Sdim linkAliasBodies(); 1225193323Sed 1226234353Sdim // Remap all of the named MDNodes in Src into the DstM module. We do this 1227226633Sdim // after linking GlobalValues so that MDNodes that reference GlobalValues 1228226633Sdim // are properly remapped. 1229226633Sdim linkNamedMDNodes(); 1230226633Sdim 1231234353Sdim // Merge the module flags into the DstM module. 1232234353Sdim if (linkModuleFlagsMetadata()) 1233234353Sdim return true; 1234234353Sdim 1235234353Sdim // Process vector of lazily linked in functions. 1236234353Sdim bool LinkedInAnyFunctions; 1237234353Sdim do { 1238234353Sdim LinkedInAnyFunctions = false; 1239234353Sdim 1240234353Sdim for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(), 1241234353Sdim E = LazilyLinkFunctions.end(); I != E; ++I) { 1242234353Sdim if (!*I) 1243234353Sdim continue; 1244234353Sdim 1245234353Sdim Function *SF = *I; 1246234353Sdim Function *DF = cast<Function>(ValueMap[SF]); 1247234353Sdim 1248234353Sdim if (!DF->use_empty()) { 1249234353Sdim 1250234353Sdim // Materialize if necessary. 1251234353Sdim if (SF->isDeclaration()) { 1252234353Sdim if (!SF->isMaterializable()) 1253234353Sdim continue; 1254234353Sdim if (SF->Materialize(&ErrorMsg)) 1255234353Sdim return true; 1256234353Sdim } 1257234353Sdim 1258234353Sdim // Link in function body. 1259234353Sdim linkFunctionBody(DF, SF); 1260234353Sdim SF->Dematerialize(); 1261234353Sdim 1262234353Sdim // "Remove" from vector by setting the element to 0. 1263234353Sdim *I = 0; 1264234353Sdim 1265234353Sdim // Set flag to indicate we may have more functions to lazily link in 1266234353Sdim // since we linked in a function. 1267234353Sdim LinkedInAnyFunctions = true; 1268234353Sdim } 1269234353Sdim } 1270234353Sdim } while (LinkedInAnyFunctions); 1271234353Sdim 1272234353Sdim // Remove any prototypes of functions that were not actually linked in. 1273234353Sdim for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(), 1274234353Sdim E = LazilyLinkFunctions.end(); I != E; ++I) { 1275234353Sdim if (!*I) 1276234353Sdim continue; 1277234353Sdim 1278234353Sdim Function *SF = *I; 1279234353Sdim Function *DF = cast<Function>(ValueMap[SF]); 1280234353Sdim if (DF->use_empty()) 1281234353Sdim DF->eraseFromParent(); 1282234353Sdim } 1283234353Sdim 1284224145Sdim // Now that all of the types from the source are used, resolve any structs 1285224145Sdim // copied over to the dest that didn't exist there. 1286224145Sdim TypeMap.linkDefinedTypeBodies(); 1287224145Sdim 1288224145Sdim return false; 1289224145Sdim} 1290193323Sed 1291251662SdimLinker::Linker(Module *M) : Composite(M) { 1292251662Sdim TypeFinder StructTypes; 1293251662Sdim StructTypes.run(*M, true); 1294251662Sdim IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end()); 1295251662Sdim} 1296251662Sdim 1297251662SdimLinker::~Linker() { 1298251662Sdim} 1299251662Sdim 1300251662Sdimbool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) { 1301251662Sdim ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode); 1302251662Sdim if (TheLinker.run()) { 1303251662Sdim if (ErrorMsg) 1304251662Sdim *ErrorMsg = TheLinker.ErrorMsg; 1305251662Sdim return true; 1306251662Sdim } 1307251662Sdim return false; 1308251662Sdim} 1309251662Sdim 1310224145Sdim//===----------------------------------------------------------------------===// 1311224145Sdim// LinkModules entrypoint. 1312224145Sdim//===----------------------------------------------------------------------===// 1313212904Sdim 1314234353Sdim/// LinkModules - This function links two modules together, with the resulting 1315249423Sdim/// Dest module modified to be the composite of the two input modules. If an 1316234353Sdim/// error occurs, true is returned and ErrorMsg (if not null) is set to indicate 1317234353Sdim/// the problem. Upon failure, the Dest module could be in a modified state, 1318234353Sdim/// and shouldn't be relied on to be consistent. 1319226633Sdimbool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode, 1320226633Sdim std::string *ErrorMsg) { 1321251662Sdim Linker L(Dest); 1322251662Sdim return L.linkInModule(Src, Mode, ErrorMsg); 1323193323Sed} 1324239462Sdim 1325239462Sdim//===----------------------------------------------------------------------===// 1326239462Sdim// C API. 1327239462Sdim//===----------------------------------------------------------------------===// 1328239462Sdim 1329239462SdimLLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src, 1330239462Sdim LLVMLinkerMode Mode, char **OutMessages) { 1331239462Sdim std::string Messages; 1332239462Sdim LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src), 1333239462Sdim Mode, OutMessages? &Messages : 0); 1334239462Sdim if (OutMessages) 1335239462Sdim *OutMessages = strdup(Messages.c_str()); 1336239462Sdim return Result; 1337239462Sdim} 1338