159a5afa9SMikhail Glushenkov //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===// 2361e513dSReid Spencer // 3361e513dSReid Spencer // The LLVM Compiler Infrastructure 4361e513dSReid Spencer // 5f3ebc3f3SChris Lattner // This file is distributed under the University of Illinois Open Source 6f3ebc3f3SChris Lattner // License. See LICENSE.TXT for details. 7361e513dSReid Spencer // 8361e513dSReid Spencer //===----------------------------------------------------------------------===// 9361e513dSReid Spencer // 10361e513dSReid Spencer // This file implements the LLVM module linker. 11361e513dSReid Spencer // 12361e513dSReid Spencer // Specifically, this: 13361e513dSReid Spencer // * Merges global variables between the two modules 14361e513dSReid Spencer // * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if != 15361e513dSReid Spencer // * Merges functions between two modules 16361e513dSReid Spencer // 17361e513dSReid Spencer //===----------------------------------------------------------------------===// 18361e513dSReid Spencer 199b0ddbbeSReid Spencer #include "llvm/Linker.h" 20361e513dSReid Spencer #include "llvm/Constants.h" 21361e513dSReid Spencer #include "llvm/DerivedTypes.h" 22fac7b595SOwen Anderson #include "llvm/LLVMContext.h" 23361e513dSReid Spencer #include "llvm/Module.h" 2432af9e8cSReid Spencer #include "llvm/TypeSymbolTable.h" 253aaaa0b2SReid Spencer #include "llvm/ValueSymbolTable.h" 265ed50b61SBill Wendling #include "llvm/Instructions.h" 275ed50b61SBill Wendling #include "llvm/Assembly/Writer.h" 283d552423SDavid Greene #include "llvm/Support/Debug.h" 2956d06597STorok Edwin #include "llvm/Support/ErrorHandling.h" 30c521f541SChris Lattner #include "llvm/Support/raw_ostream.h" 31361e513dSReid Spencer #include "llvm/System/Path.h" 32a2095034SDan Gohman #include "llvm/Transforms/Utils/ValueMapper.h" 335ed50b61SBill Wendling #include "llvm/ADT/DenseMap.h" 34361e513dSReid Spencer using namespace llvm; 35361e513dSReid Spencer 36361e513dSReid Spencer // Error - Simple wrapper function to conditionally assign to E and return true. 37361e513dSReid Spencer // This just makes error return conditions a little bit simpler... 384975db62SDaniel Dunbar static inline bool Error(std::string *E, const Twine &Message) { 394975db62SDaniel Dunbar if (E) *E = Message.str(); 40361e513dSReid Spencer return true; 41361e513dSReid Spencer } 42361e513dSReid Spencer 43361e513dSReid Spencer // Function: ResolveTypes() 44361e513dSReid Spencer // 45361e513dSReid Spencer // Description: 46361e513dSReid Spencer // Attempt to link the two specified types together. 47361e513dSReid Spencer // 48361e513dSReid Spencer // Inputs: 49361e513dSReid Spencer // DestTy - The type to which we wish to resolve. 50361e513dSReid Spencer // SrcTy - The original type which we want to resolve. 51361e513dSReid Spencer // 52361e513dSReid Spencer // Outputs: 53361e513dSReid Spencer // DestST - The symbol table in which the new type should be placed. 54361e513dSReid Spencer // 55361e513dSReid Spencer // Return value: 56361e513dSReid Spencer // true - There is an error and the types cannot yet be linked. 57361e513dSReid Spencer // false - No errors. 58361e513dSReid Spencer // 598aa89e41SChris Lattner static bool ResolveTypes(const Type *DestTy, const Type *SrcTy) { 60361e513dSReid Spencer if (DestTy == SrcTy) return false; // If already equal, noop 618aa89e41SChris Lattner assert(DestTy && SrcTy && "Can't handle null types"); 62361e513dSReid Spencer 638aa89e41SChris Lattner if (const OpaqueType *OT = dyn_cast<OpaqueType>(DestTy)) { 648aa89e41SChris Lattner // Type _is_ in module, just opaque... 658aa89e41SChris Lattner const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(SrcTy); 668aa89e41SChris Lattner } else if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) { 67361e513dSReid Spencer const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy); 68361e513dSReid Spencer } else { 698aa89e41SChris Lattner return true; // Cannot link types... not-equal and neither is opaque. 70361e513dSReid Spencer } 71361e513dSReid Spencer return false; 72361e513dSReid Spencer } 73361e513dSReid Spencer 74eee6f995SChris Lattner /// LinkerTypeMap - This implements a map of types that is stable 75eee6f995SChris Lattner /// even if types are resolved/refined to other types. This is not a general 76eee6f995SChris Lattner /// purpose map, it is specific to the linker's use. 77eee6f995SChris Lattner namespace { 78eee6f995SChris Lattner class LinkerTypeMap : public AbstractTypeUser { 79eee6f995SChris Lattner typedef DenseMap<const Type*, PATypeHolder> TheMapTy; 80eee6f995SChris Lattner TheMapTy TheMap; 81eee6f995SChris Lattner 82d0fcc9a8SArgyrios Kyrtzidis LinkerTypeMap(const LinkerTypeMap&); // DO NOT IMPLEMENT 83d0fcc9a8SArgyrios Kyrtzidis void operator=(const LinkerTypeMap&); // DO NOT IMPLEMENT 8456cdea6bSChris Lattner public: 8556cdea6bSChris Lattner LinkerTypeMap() {} 8656cdea6bSChris Lattner ~LinkerTypeMap() { 87eee6f995SChris Lattner for (DenseMap<const Type*, PATypeHolder>::iterator I = TheMap.begin(), 88eee6f995SChris Lattner E = TheMap.end(); I != E; ++I) 89eee6f995SChris Lattner I->first->removeAbstractTypeUser(this); 90eee6f995SChris Lattner } 91eee6f995SChris Lattner 92eee6f995SChris Lattner /// lookup - Return the value for the specified type or null if it doesn't 93eee6f995SChris Lattner /// exist. 94eee6f995SChris Lattner const Type *lookup(const Type *Ty) const { 95eee6f995SChris Lattner TheMapTy::const_iterator I = TheMap.find(Ty); 96eee6f995SChris Lattner if (I != TheMap.end()) return I->second; 97eee6f995SChris Lattner return 0; 98eee6f995SChris Lattner } 99eee6f995SChris Lattner 100eee6f995SChris Lattner /// insert - This returns true if the pointer was new to the set, false if it 101eee6f995SChris Lattner /// was already in the set. 102eee6f995SChris Lattner bool insert(const Type *Src, const Type *Dst) { 10338740a98SDan Gohman if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))).second) 104eee6f995SChris Lattner return false; // Already in map. 105eee6f995SChris Lattner if (Src->isAbstract()) 106eee6f995SChris Lattner Src->addAbstractTypeUser(this); 107eee6f995SChris Lattner return true; 108eee6f995SChris Lattner } 109eee6f995SChris Lattner 110eee6f995SChris Lattner protected: 111eee6f995SChris Lattner /// refineAbstractType - The callback method invoked when an abstract type is 112eee6f995SChris Lattner /// resolved to another type. An object must override this method to update 113eee6f995SChris Lattner /// its internal state to reference NewType instead of OldType. 114eee6f995SChris Lattner /// 115eee6f995SChris Lattner virtual void refineAbstractType(const DerivedType *OldTy, 116eee6f995SChris Lattner const Type *NewTy) { 117eee6f995SChris Lattner TheMapTy::iterator I = TheMap.find(OldTy); 118eee6f995SChris Lattner const Type *DstTy = I->second; 119eee6f995SChris Lattner 120eee6f995SChris Lattner TheMap.erase(I); 121eee6f995SChris Lattner if (OldTy->isAbstract()) 122eee6f995SChris Lattner OldTy->removeAbstractTypeUser(this); 123eee6f995SChris Lattner 124eee6f995SChris Lattner // Don't reinsert into the map if the key is concrete now. 125eee6f995SChris Lattner if (NewTy->isAbstract()) 126eee6f995SChris Lattner insert(NewTy, DstTy); 127eee6f995SChris Lattner } 128eee6f995SChris Lattner 129eee6f995SChris Lattner /// The other case which AbstractTypeUsers must be aware of is when a type 130eee6f995SChris Lattner /// makes the transition from being abstract (where it has clients on it's 131eee6f995SChris Lattner /// AbstractTypeUsers list) to concrete (where it does not). This method 132eee6f995SChris Lattner /// notifies ATU's when this occurs for a type. 133eee6f995SChris Lattner virtual void typeBecameConcrete(const DerivedType *AbsTy) { 134eee6f995SChris Lattner TheMap.erase(AbsTy); 135eee6f995SChris Lattner AbsTy->removeAbstractTypeUser(this); 136eee6f995SChris Lattner } 137eee6f995SChris Lattner 138eee6f995SChris Lattner // for debugging... 139eee6f995SChris Lattner virtual void dump() const { 1403d552423SDavid Greene dbgs() << "AbstractTypeSet!\n"; 141eee6f995SChris Lattner } 142eee6f995SChris Lattner }; 143eee6f995SChris Lattner } 144eee6f995SChris Lattner 145eee6f995SChris Lattner 146361e513dSReid Spencer // RecursiveResolveTypes - This is just like ResolveTypes, except that it 147361e513dSReid Spencer // recurses down into derived types, merging the used types if the parent types 148361e513dSReid Spencer // are compatible. 1499be15893SChris Lattner static bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy, 150eee6f995SChris Lattner LinkerTypeMap &Pointers) { 1519be15893SChris Lattner if (DstTy == SrcTy) return false; // If already equal, noop 152361e513dSReid Spencer 153361e513dSReid Spencer // If we found our opaque type, resolve it now! 154cbd43f89SDuncan Sands if (DstTy->isOpaqueTy() || SrcTy->isOpaqueTy()) 1559be15893SChris Lattner return ResolveTypes(DstTy, SrcTy); 156361e513dSReid Spencer 157361e513dSReid Spencer // Two types cannot be resolved together if they are of different primitive 158361e513dSReid Spencer // type. For example, we cannot resolve an int to a float. 1599be15893SChris Lattner if (DstTy->getTypeID() != SrcTy->getTypeID()) return true; 160361e513dSReid Spencer 161fe677e95SChris Lattner // If neither type is abstract, then they really are just different types. 1629be15893SChris Lattner if (!DstTy->isAbstract() && !SrcTy->isAbstract()) 163fe677e95SChris Lattner return true; 164fe677e95SChris Lattner 165361e513dSReid Spencer // Otherwise, resolve the used type used by this derived type... 1669be15893SChris Lattner switch (DstTy->getTypeID()) { 1679995302bSChris Lattner default: 1687a9c62baSReid Spencer return true; 169361e513dSReid Spencer case Type::FunctionTyID: { 1709be15893SChris Lattner const FunctionType *DstFT = cast<FunctionType>(DstTy); 1719be15893SChris Lattner const FunctionType *SrcFT = cast<FunctionType>(SrcTy); 17285b66d18SChris Lattner if (DstFT->isVarArg() != SrcFT->isVarArg() || 17385b66d18SChris Lattner DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes()) 174361e513dSReid Spencer return true; 1759be15893SChris Lattner 1769be15893SChris Lattner // Use TypeHolder's so recursive resolution won't break us. 1779be15893SChris Lattner PATypeHolder ST(SrcFT), DT(DstFT); 1789be15893SChris Lattner for (unsigned i = 0, e = DstFT->getNumContainedTypes(); i != e; ++i) { 1799be15893SChris Lattner const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i); 1809be15893SChris Lattner if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers)) 181361e513dSReid Spencer return true; 1829be15893SChris Lattner } 183361e513dSReid Spencer return false; 184361e513dSReid Spencer } 185361e513dSReid Spencer case Type::StructTyID: { 1869be15893SChris Lattner const StructType *DstST = cast<StructType>(DstTy); 1879be15893SChris Lattner const StructType *SrcST = cast<StructType>(SrcTy); 18885b66d18SChris Lattner if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes()) 1899995302bSChris Lattner return true; 1909be15893SChris Lattner 1919be15893SChris Lattner PATypeHolder ST(SrcST), DT(DstST); 1929be15893SChris Lattner for (unsigned i = 0, e = DstST->getNumContainedTypes(); i != e; ++i) { 1939be15893SChris Lattner const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i); 1949be15893SChris Lattner if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers)) 195361e513dSReid Spencer return true; 1969be15893SChris Lattner } 197361e513dSReid Spencer return false; 198361e513dSReid Spencer } 199361e513dSReid Spencer case Type::ArrayTyID: { 2009be15893SChris Lattner const ArrayType *DAT = cast<ArrayType>(DstTy); 2019be15893SChris Lattner const ArrayType *SAT = cast<ArrayType>(SrcTy); 202361e513dSReid Spencer if (DAT->getNumElements() != SAT->getNumElements()) return true; 203361e513dSReid Spencer return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(), 2048aa89e41SChris Lattner Pointers); 205361e513dSReid Spencer } 2069995302bSChris Lattner case Type::VectorTyID: { 2079be15893SChris Lattner const VectorType *DVT = cast<VectorType>(DstTy); 2089be15893SChris Lattner const VectorType *SVT = cast<VectorType>(SrcTy); 2099995302bSChris Lattner if (DVT->getNumElements() != SVT->getNumElements()) return true; 2109995302bSChris Lattner return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(), 2119995302bSChris Lattner Pointers); 2129995302bSChris Lattner } 213361e513dSReid Spencer case Type::PointerTyID: { 2149be15893SChris Lattner const PointerType *DstPT = cast<PointerType>(DstTy); 2159be15893SChris Lattner const PointerType *SrcPT = cast<PointerType>(SrcTy); 21685b66d18SChris Lattner 21785b66d18SChris Lattner if (DstPT->getAddressSpace() != SrcPT->getAddressSpace()) 21885b66d18SChris Lattner return true; 21985b66d18SChris Lattner 220361e513dSReid Spencer // If this is a pointer type, check to see if we have already seen it. If 221361e513dSReid Spencer // so, we are in a recursive branch. Cut off the search now. We cannot use 222361e513dSReid Spencer // an associative container for this search, because the type pointers (keys 223eee6f995SChris Lattner // in the container) change whenever types get resolved. 224eee6f995SChris Lattner if (SrcPT->isAbstract()) 225eee6f995SChris Lattner if (const Type *ExistingDestTy = Pointers.lookup(SrcPT)) 226eee6f995SChris Lattner return ExistingDestTy != DstPT; 227eee6f995SChris Lattner 228eee6f995SChris Lattner if (DstPT->isAbstract()) 229eee6f995SChris Lattner if (const Type *ExistingSrcTy = Pointers.lookup(DstPT)) 230eee6f995SChris Lattner return ExistingSrcTy != SrcPT; 231361e513dSReid Spencer // Otherwise, add the current pointers to the vector to stop recursion on 232361e513dSReid Spencer // this pair. 233eee6f995SChris Lattner if (DstPT->isAbstract()) 234eee6f995SChris Lattner Pointers.insert(DstPT, SrcPT); 235eee6f995SChris Lattner if (SrcPT->isAbstract()) 236eee6f995SChris Lattner Pointers.insert(SrcPT, DstPT); 2379be15893SChris Lattner 23885b66d18SChris Lattner return RecursiveResolveTypesI(DstPT->getElementType(), 23985b66d18SChris Lattner SrcPT->getElementType(), Pointers); 240361e513dSReid Spencer } 241361e513dSReid Spencer } 242361e513dSReid Spencer } 243361e513dSReid Spencer 2449be15893SChris Lattner static bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) { 245eee6f995SChris Lattner LinkerTypeMap PointerTypes; 2468aa89e41SChris Lattner return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes); 247361e513dSReid Spencer } 248361e513dSReid Spencer 249361e513dSReid Spencer 250361e513dSReid Spencer // LinkTypes - Go through the symbol table of the Src module and see if any 251361e513dSReid Spencer // types are named in the src module that are not named in the Dst module. 252361e513dSReid Spencer // Make sure there are no type name conflicts. 253361e513dSReid Spencer static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) { 25432af9e8cSReid Spencer TypeSymbolTable *DestST = &Dest->getTypeSymbolTable(); 25532af9e8cSReid Spencer const TypeSymbolTable *SrcST = &Src->getTypeSymbolTable(); 256361e513dSReid Spencer 257361e513dSReid Spencer // Look for a type plane for Type's... 25832af9e8cSReid Spencer TypeSymbolTable::const_iterator TI = SrcST->begin(); 25932af9e8cSReid Spencer TypeSymbolTable::const_iterator TE = SrcST->end(); 260361e513dSReid Spencer if (TI == TE) return false; // No named types, do nothing. 261361e513dSReid Spencer 262361e513dSReid Spencer // Some types cannot be resolved immediately because they depend on other 263361e513dSReid Spencer // types being resolved to each other first. This contains a list of types we 264361e513dSReid Spencer // are waiting to recheck. 265361e513dSReid Spencer std::vector<std::string> DelayedTypesToResolve; 266361e513dSReid Spencer 267361e513dSReid Spencer for ( ; TI != TE; ++TI ) { 268361e513dSReid Spencer const std::string &Name = TI->first; 269361e513dSReid Spencer const Type *RHS = TI->second; 270361e513dSReid Spencer 2718aa89e41SChris Lattner // Check to see if this type name is already in the dest module. 27232af9e8cSReid Spencer Type *Entry = DestST->lookup(Name); 273361e513dSReid Spencer 2748aa89e41SChris Lattner // If the name is just in the source module, bring it over to the dest. 2758aa89e41SChris Lattner if (Entry == 0) { 2768aa89e41SChris Lattner if (!Name.empty()) 277e9bb8552SChris Lattner DestST->insert(Name, const_cast<Type*>(RHS)); 2788aa89e41SChris Lattner } else if (ResolveTypes(Entry, RHS)) { 279361e513dSReid Spencer // They look different, save the types 'till later to resolve. 280361e513dSReid Spencer DelayedTypesToResolve.push_back(Name); 281361e513dSReid Spencer } 282361e513dSReid Spencer } 283361e513dSReid Spencer 284361e513dSReid Spencer // Iteratively resolve types while we can... 285361e513dSReid Spencer while (!DelayedTypesToResolve.empty()) { 286361e513dSReid Spencer // Loop over all of the types, attempting to resolve them if possible... 287361e513dSReid Spencer unsigned OldSize = DelayedTypesToResolve.size(); 288361e513dSReid Spencer 289361e513dSReid Spencer // Try direct resolution by name... 290361e513dSReid Spencer for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) { 291361e513dSReid Spencer const std::string &Name = DelayedTypesToResolve[i]; 29232af9e8cSReid Spencer Type *T1 = SrcST->lookup(Name); 29332af9e8cSReid Spencer Type *T2 = DestST->lookup(Name); 2948aa89e41SChris Lattner if (!ResolveTypes(T2, T1)) { 295361e513dSReid Spencer // We are making progress! 296361e513dSReid Spencer DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i); 297361e513dSReid Spencer --i; 298361e513dSReid Spencer } 299361e513dSReid Spencer } 300361e513dSReid Spencer 301361e513dSReid Spencer // Did we not eliminate any types? 302361e513dSReid Spencer if (DelayedTypesToResolve.size() == OldSize) { 303361e513dSReid Spencer // Attempt to resolve subelements of types. This allows us to merge these 304361e513dSReid Spencer // two types: { int* } and { opaque* } 305361e513dSReid Spencer for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) { 306361e513dSReid Spencer const std::string &Name = DelayedTypesToResolve[i]; 3079be15893SChris Lattner if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) { 308361e513dSReid Spencer // We are making progress! 309361e513dSReid Spencer DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i); 310361e513dSReid Spencer 311361e513dSReid Spencer // Go back to the main loop, perhaps we can resolve directly by name 312361e513dSReid Spencer // now... 313361e513dSReid Spencer break; 314361e513dSReid Spencer } 315361e513dSReid Spencer } 316361e513dSReid Spencer 317361e513dSReid Spencer // If we STILL cannot resolve the types, then there is something wrong. 318361e513dSReid Spencer if (DelayedTypesToResolve.size() == OldSize) { 319361e513dSReid Spencer // Remove the symbol name from the destination. 320361e513dSReid Spencer DelayedTypesToResolve.pop_back(); 321361e513dSReid Spencer } 322361e513dSReid Spencer } 323361e513dSReid Spencer } 324361e513dSReid Spencer 325361e513dSReid Spencer 326361e513dSReid Spencer return false; 327361e513dSReid Spencer } 328361e513dSReid Spencer 32990246aa7SReid Spencer /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict 33090246aa7SReid Spencer /// in the symbol table. This is good for all clients except for us. Go 33190246aa7SReid Spencer /// through the trouble to force this back. 332361e513dSReid Spencer static void ForceRenaming(GlobalValue *GV, const std::string &Name) { 333361e513dSReid Spencer assert(GV->getName() != Name && "Can't force rename to self"); 3343aaaa0b2SReid Spencer ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable(); 335361e513dSReid Spencer 336361e513dSReid Spencer // If there is a conflict, rename the conflict. 3372a8d2e0eSChris Lattner if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) { 3386de96a1bSRafael Espindola assert(ConflictGV->hasLocalLinkage() && 33990246aa7SReid Spencer "Not conflicting with a static global, should link instead!"); 3402a8d2e0eSChris Lattner GV->takeName(ConflictGV); 341361e513dSReid Spencer ConflictGV->setName(Name); // This will cause ConflictGV to get renamed 3423aaaa0b2SReid Spencer assert(ConflictGV->getName() != Name && "ForceRenaming didn't work"); 3432a8d2e0eSChris Lattner } else { 3442a8d2e0eSChris Lattner GV->setName(Name); // Force the name back 3453aaaa0b2SReid Spencer } 3463aaaa0b2SReid Spencer } 3473aaaa0b2SReid Spencer 3483aaaa0b2SReid Spencer /// CopyGVAttributes - copy additional attributes (those not needed to construct 3493aaaa0b2SReid Spencer /// a GlobalValue) from the SrcGV to the DestGV. 3503aaaa0b2SReid Spencer static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) { 351dd7daee8SDuncan Sands // Use the maximum alignment, rather than just copying the alignment of SrcGV. 352dd7daee8SDuncan Sands unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment()); 353dd7daee8SDuncan Sands DestGV->copyAttributesFrom(SrcGV); 354dd7daee8SDuncan Sands DestGV->setAlignment(Alignment); 355361e513dSReid Spencer } 356361e513dSReid Spencer 357fc61de39SChris Lattner /// GetLinkageResult - This analyzes the two global values and determines what 358fc61de39SChris Lattner /// the result will look like in the destination module. In particular, it 359fc61de39SChris Lattner /// computes the resultant linkage type, computes whether the global in the 360fc61de39SChris Lattner /// source should be copied over to the destination (replacing the existing 36131fc4f95SAnton Korobeynikov /// one), and computes whether this linkage is an error or not. It also performs 36231fc4f95SAnton Korobeynikov /// visibility checks: we cannot link together two symbols with different 36331fc4f95SAnton Korobeynikov /// visibilities. 364f6439246SAnton Korobeynikov static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src, 365fc61de39SChris Lattner GlobalValue::LinkageTypes <, bool &LinkFromSrc, 366fc61de39SChris Lattner std::string *Err) { 3676de96a1bSRafael Espindola assert((!Dest || !Src->hasLocalLinkage()) && 368fc61de39SChris Lattner "If Src has internal linkage, Dest shouldn't be set!"); 369fc61de39SChris Lattner if (!Dest) { 370fc61de39SChris Lattner // Linking something to nothing. 371fc61de39SChris Lattner LinkFromSrc = true; 372fc61de39SChris Lattner LT = Src->getLinkage(); 3735301e7c6SReid Spencer } else if (Src->isDeclaration()) { 3741f93c50aSAnton Korobeynikov // If Src is external or if both Src & Dest are external.. Just link the 375fc61de39SChris Lattner // external globals, we aren't adding anything. 376d61d39ecSAnton Korobeynikov if (Src->hasDLLImportLinkage()) { 37712c94949SAnton Korobeynikov // If one of GVs has DLLImport linkage, result should be dllimport'ed. 3785301e7c6SReid Spencer if (Dest->isDeclaration()) { 379d61d39ecSAnton Korobeynikov LinkFromSrc = true; 380d61d39ecSAnton Korobeynikov LT = Src->getLinkage(); 381d61d39ecSAnton Korobeynikov } 382e06036d2SAndrew Lenharth } else if (Dest->hasExternalWeakLinkage()) { 38312da8ce3SDuncan Sands // If the Dest is weak, use the source linkage. 384e06036d2SAndrew Lenharth LinkFromSrc = true; 385e06036d2SAndrew Lenharth LT = Src->getLinkage(); 386d61d39ecSAnton Korobeynikov } else { 387fc61de39SChris Lattner LinkFromSrc = false; 388fc61de39SChris Lattner LT = Dest->getLinkage(); 389d61d39ecSAnton Korobeynikov } 3905301e7c6SReid Spencer } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) { 391fc61de39SChris Lattner // If Dest is external but Src is not: 392fc61de39SChris Lattner LinkFromSrc = true; 393fc61de39SChris Lattner LT = Src->getLinkage(); 394fc61de39SChris Lattner } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) { 395fc61de39SChris Lattner if (Src->getLinkage() != Dest->getLinkage()) 396fc61de39SChris Lattner return Error(Err, "Linking globals named '" + Src->getName() + 397fc61de39SChris Lattner "': can only link appending global with another appending global!"); 398fc61de39SChris Lattner LinkFromSrc = true; // Special cased. 399fc61de39SChris Lattner LT = Src->getLinkage(); 400d725c991SDuncan Sands } else if (Src->isWeakForLinker()) { 401ce4396bcSDale Johannesen // At this point we know that Dest has LinkOnce, External*, Weak, Common, 402ce4396bcSDale Johannesen // or DLL* linkage. 403184f1be4SChris Lattner if (Dest->hasExternalWeakLinkage() || 404184f1be4SChris Lattner Dest->hasAvailableExternallyLinkage() || 405184f1be4SChris Lattner (Dest->hasLinkOnceLinkage() && 406184f1be4SChris Lattner (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) { 407fc61de39SChris Lattner LinkFromSrc = true; 408fc61de39SChris Lattner LT = Src->getLinkage(); 409fc61de39SChris Lattner } else { 410fc61de39SChris Lattner LinkFromSrc = false; 411fc61de39SChris Lattner LT = Dest->getLinkage(); 412fc61de39SChris Lattner } 413d725c991SDuncan Sands } else if (Dest->isWeakForLinker()) { 41412c94949SAnton Korobeynikov // At this point we know that Src has External* or DLL* linkage. 41512c94949SAnton Korobeynikov if (Src->hasExternalWeakLinkage()) { 41612c94949SAnton Korobeynikov LinkFromSrc = false; 41712c94949SAnton Korobeynikov LT = Dest->getLinkage(); 41812c94949SAnton Korobeynikov } else { 419fc61de39SChris Lattner LinkFromSrc = true; 420fc61de39SChris Lattner LT = GlobalValue::ExternalLinkage; 42112c94949SAnton Korobeynikov } 422fc61de39SChris Lattner } else { 423d61d39ecSAnton Korobeynikov assert((Dest->hasExternalLinkage() || 424d61d39ecSAnton Korobeynikov Dest->hasDLLImportLinkage() || 42512c94949SAnton Korobeynikov Dest->hasDLLExportLinkage() || 42612c94949SAnton Korobeynikov Dest->hasExternalWeakLinkage()) && 427d61d39ecSAnton Korobeynikov (Src->hasExternalLinkage() || 428d61d39ecSAnton Korobeynikov Src->hasDLLImportLinkage() || 42912c94949SAnton Korobeynikov Src->hasDLLExportLinkage() || 43012c94949SAnton Korobeynikov Src->hasExternalWeakLinkage()) && 431fc61de39SChris Lattner "Unexpected linkage type!"); 432fc61de39SChris Lattner return Error(Err, "Linking globals named '" + Src->getName() + 433fc61de39SChris Lattner "': symbol multiply defined!"); 434fc61de39SChris Lattner } 43531fc4f95SAnton Korobeynikov 43631fc4f95SAnton Korobeynikov // Check visibility 43731fc4f95SAnton Korobeynikov if (Dest && Src->getVisibility() != Dest->getVisibility()) 4381cc79985SChris Lattner if (!Src->isDeclaration() && !Dest->isDeclaration()) 43931fc4f95SAnton Korobeynikov return Error(Err, "Linking globals named '" + Src->getName() + 44031fc4f95SAnton Korobeynikov "': symbols have different visibilities!"); 441fc61de39SChris Lattner return false; 442fc61de39SChris Lattner } 443361e513dSReid Spencer 4445c310be0SDevang Patel // Insert all of the named mdnoes in Src into the Dest module. 44535351901SDan Gohman static void LinkNamedMDNodes(Module *Dest, Module *Src, 44635351901SDan Gohman ValueToValueMapTy &ValueMap) { 4475c310be0SDevang Patel for (Module::const_named_metadata_iterator I = Src->named_metadata_begin(), 4485c310be0SDevang Patel E = Src->named_metadata_end(); I != E; ++I) { 4495c310be0SDevang Patel const NamedMDNode *SrcNMD = I; 4502637cc1aSDan Gohman NamedMDNode *DestNMD = Dest->getOrInsertNamedMetadata(SrcNMD->getName()); 4515c310be0SDevang Patel // Add Src elements into Dest node. 4529b493028SChris Lattner for (unsigned i = 0, e = SrcNMD->getNumOperands(); i != e; ++i) 45335351901SDan Gohman DestNMD->addOperand(cast<MDNode>(MapValue(SrcNMD->getOperand(i), 454ca26f790SDan Gohman ValueMap, 455ca26f790SDan Gohman true))); 4565c310be0SDevang Patel } 4575c310be0SDevang Patel } 4585c310be0SDevang Patel 459361e513dSReid Spencer // LinkGlobals - Loop through the global variables in the src module and merge 460361e513dSReid Spencer // them into the dest module. 461f6439246SAnton Korobeynikov static bool LinkGlobals(Module *Dest, const Module *Src, 462a2095034SDan Gohman ValueToValueMapTy &ValueMap, 463361e513dSReid Spencer std::multimap<std::string, GlobalVariable *> &AppendingVars, 464361e513dSReid Spencer std::string *Err) { 46534fc5a0eSChris Lattner ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable(); 46634fc5a0eSChris Lattner 467361e513dSReid Spencer // Loop over all of the globals in the src module, mapping them over as we go 468177a3008SChris Lattner for (Module::const_global_iterator I = Src->global_begin(), 469177a3008SChris Lattner E = Src->global_end(); I != E; ++I) { 470f6439246SAnton Korobeynikov const GlobalVariable *SGV = I; 471e79f4c77SAnton Korobeynikov GlobalValue *DGV = 0; 472e79f4c77SAnton Korobeynikov 4735ed50b61SBill Wendling // Check to see if may have to link the global with the global, alias or 47434fc5a0eSChris Lattner // function. 4756de96a1bSRafael Espindola if (SGV->hasName() && !SGV->hasLocalLinkage()) 4765ed50b61SBill Wendling DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getName())); 477361e513dSReid Spencer 478c08e7a00SChris Lattner // If we found a global with the same name in the dest module, but it has 479c08e7a00SChris Lattner // internal linkage, we are really not doing any linkage here. 4806de96a1bSRafael Espindola if (DGV && DGV->hasLocalLinkage()) 481c08e7a00SChris Lattner DGV = 0; 482c08e7a00SChris Lattner 483e79f4c77SAnton Korobeynikov // If types don't agree due to opaque types, try to resolve them. 48434fc5a0eSChris Lattner if (DGV && DGV->getType() != SGV->getType()) 4858aa89e41SChris Lattner RecursiveResolveTypes(SGV->getType(), DGV->getType()); 486e79f4c77SAnton Korobeynikov 4875e79a610SDan Gohman assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() || 4885e79a610SDan Gohman SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) && 489361e513dSReid Spencer "Global must either be external or have an initializer!"); 490361e513dSReid Spencer 4911b9633d7SChris Lattner GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage; 4921b9633d7SChris Lattner bool LinkFromSrc = false; 493fc61de39SChris Lattner if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err)) 494fc61de39SChris Lattner return true; 495361e513dSReid Spencer 4960ead7a50SChris Lattner if (DGV == 0) { 497361e513dSReid Spencer // No linking to be performed, simply create an identical version of the 498361e513dSReid Spencer // symbol over in the dest module... the initializer will be filled in 49934fc5a0eSChris Lattner // later by LinkGlobalInits. 500361e513dSReid Spencer GlobalVariable *NewDGV = 501b17f3294SOwen Anderson new GlobalVariable(*Dest, SGV->getType()->getElementType(), 502361e513dSReid Spencer SGV->isConstant(), SGV->getLinkage(), /*init*/0, 503b17f3294SOwen Anderson SGV->getName(), 0, false, 504b32a9ef0SChris Lattner SGV->getType()->getAddressSpace()); 5052dc36535SReid Spencer // Propagate alignment, visibility and section info. 5063aaaa0b2SReid Spencer CopyGVAttributes(NewDGV, SGV); 507dd924e4eSAndrew Lenharth 508361e513dSReid Spencer // If the LLVM runtime renamed the global, but it is an externally visible 509361e513dSReid Spencer // symbol, DGV must be an existing global with internal linkage. Rename 510361e513dSReid Spencer // it. 5116de96a1bSRafael Espindola if (!NewDGV->hasLocalLinkage() && NewDGV->getName() != SGV->getName()) 512361e513dSReid Spencer ForceRenaming(NewDGV, SGV->getName()); 513361e513dSReid Spencer 5140ead7a50SChris Lattner // Make sure to remember this mapping. 51566a6271cSAnton Korobeynikov ValueMap[SGV] = NewDGV; 51666a6271cSAnton Korobeynikov 51734fc5a0eSChris Lattner // Keep track that this is an appending variable. 518361e513dSReid Spencer if (SGV->hasAppendingLinkage()) 519361e513dSReid Spencer AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV)); 5200ead7a50SChris Lattner continue; 5210ead7a50SChris Lattner } 5220ead7a50SChris Lattner 5230ead7a50SChris Lattner // If the visibilities of the symbols disagree and the destination is a 5240ead7a50SChris Lattner // prototype, take the visibility of its input. 5250ead7a50SChris Lattner if (DGV->isDeclaration()) 5260ead7a50SChris Lattner DGV->setVisibility(SGV->getVisibility()); 5270ead7a50SChris Lattner 5280ead7a50SChris Lattner if (DGV->hasAppendingLinkage()) { 529361e513dSReid Spencer // No linking is performed yet. Just insert a new copy of the global, and 530361e513dSReid Spencer // keep track of the fact that it is an appending variable in the 531361e513dSReid Spencer // AppendingVars map. The name is cleared out so that no linkage is 532361e513dSReid Spencer // performed. 533361e513dSReid Spencer GlobalVariable *NewDGV = 534b17f3294SOwen Anderson new GlobalVariable(*Dest, SGV->getType()->getElementType(), 535361e513dSReid Spencer SGV->isConstant(), SGV->getLinkage(), /*init*/0, 536b17f3294SOwen Anderson "", 0, false, 537b32a9ef0SChris Lattner SGV->getType()->getAddressSpace()); 538361e513dSReid Spencer 539e8a3e74bSAnton Korobeynikov // Set alignment allowing CopyGVAttributes merge it with alignment of SGV. 5403aaaa0b2SReid Spencer NewDGV->setAlignment(DGV->getAlignment()); 541e8a3e74bSAnton Korobeynikov // Propagate alignment, section and visibility info. 5423aaaa0b2SReid Spencer CopyGVAttributes(NewDGV, SGV); 543dd924e4eSAndrew Lenharth 544361e513dSReid Spencer // Make sure to remember this mapping... 54566a6271cSAnton Korobeynikov ValueMap[SGV] = NewDGV; 546361e513dSReid Spencer 547361e513dSReid Spencer // Keep track that this is an appending variable... 548361e513dSReid Spencer AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV)); 5490ead7a50SChris Lattner continue; 5500ead7a50SChris Lattner } 5510ead7a50SChris Lattner 5520ead7a50SChris Lattner if (LinkFromSrc) { 5530ead7a50SChris Lattner if (isa<GlobalAlias>(DGV)) 554eeb5ca6fSAnton Korobeynikov return Error(Err, "Global-Alias Collision on '" + SGV->getName() + 555eeb5ca6fSAnton Korobeynikov "': symbol multiple defined"); 556dd924e4eSAndrew Lenharth 5570074ea3aSAnton Korobeynikov // If the types don't match, and if we are to link from the source, nuke 55834fc5a0eSChris Lattner // DGV and create a new one of the appropriate type. Note that the thing 55934fc5a0eSChris Lattner // we are replacing may be a function (if a prototype, weak, etc) or a 56034fc5a0eSChris Lattner // global variable. 561fc61de39SChris Lattner GlobalVariable *NewDGV = 562b17f3294SOwen Anderson new GlobalVariable(*Dest, SGV->getType()->getElementType(), 5635948fdf6SOwen Anderson SGV->isConstant(), NewLinkage, /*init*/0, 564b17f3294SOwen Anderson DGV->getName(), 0, false, 565b32a9ef0SChris Lattner SGV->getType()->getAddressSpace()); 56634fc5a0eSChris Lattner 56734fc5a0eSChris Lattner // Propagate alignment, section, and visibility info. 56834fc5a0eSChris Lattner CopyGVAttributes(NewDGV, SGV); 569487375e9SOwen Anderson DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, 570fac7b595SOwen Anderson DGV->getType())); 57134fc5a0eSChris Lattner 57234fc5a0eSChris Lattner // DGV will conflict with NewDGV because they both had the same 573f6439246SAnton Korobeynikov // name. We must erase this now so ForceRenaming doesn't assert 574f6439246SAnton Korobeynikov // because DGV might not have internal linkage. 57534fc5a0eSChris Lattner if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV)) 57634fc5a0eSChris Lattner Var->eraseFromParent(); 57734fc5a0eSChris Lattner else 57834fc5a0eSChris Lattner cast<Function>(DGV)->eraseFromParent(); 579f6439246SAnton Korobeynikov 58034fc5a0eSChris Lattner // If the symbol table renamed the global, but it is an externally visible 58134fc5a0eSChris Lattner // symbol, DGV must be an existing global with internal linkage. Rename. 5826de96a1bSRafael Espindola if (NewDGV->getName() != SGV->getName() && !NewDGV->hasLocalLinkage()) 583f6439246SAnton Korobeynikov ForceRenaming(NewDGV, SGV->getName()); 584f6439246SAnton Korobeynikov 5850ead7a50SChris Lattner // Inherit const as appropriate. 58634fc5a0eSChris Lattner NewDGV->setConstant(SGV->isConstant()); 587fc61de39SChris Lattner 5880ead7a50SChris Lattner // Make sure to remember this mapping. 5890ead7a50SChris Lattner ValueMap[SGV] = NewDGV; 5900ead7a50SChris Lattner continue; 5910ead7a50SChris Lattner } 592f6439246SAnton Korobeynikov 59334fc5a0eSChris Lattner // Not "link from source", keep the one in the DestModule and remap the 59434fc5a0eSChris Lattner // input onto it. 59534fc5a0eSChris Lattner 59634fc5a0eSChris Lattner // Special case for const propagation. 59734fc5a0eSChris Lattner if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) 59834fc5a0eSChris Lattner if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant()) 59934fc5a0eSChris Lattner DGVar->setConstant(true); 60034fc5a0eSChris Lattner 601006659f0SAnton Korobeynikov // SGV is global, but DGV is alias. 602006659f0SAnton Korobeynikov if (isa<GlobalAlias>(DGV)) { 603006659f0SAnton Korobeynikov // The only valid mappings are: 604006659f0SAnton Korobeynikov // - SGV is external declaration, which is effectively a no-op. 605006659f0SAnton Korobeynikov // - SGV is weak, when we just need to throw SGV out. 606d725c991SDuncan Sands if (!SGV->isDeclaration() && !SGV->isWeakForLinker()) 6070ead7a50SChris Lattner return Error(Err, "Global-Alias Collision on '" + SGV->getName() + 6080ead7a50SChris Lattner "': symbol multiple defined"); 609006659f0SAnton Korobeynikov } 6100ead7a50SChris Lattner 61134fc5a0eSChris Lattner // Set calculated linkage 61234fc5a0eSChris Lattner DGV->setLinkage(NewLinkage); 61334fc5a0eSChris Lattner 61434fc5a0eSChris Lattner // Make sure to remember this mapping... 615487375e9SOwen Anderson ValueMap[SGV] = ConstantExpr::getBitCast(DGV, SGV->getType()); 616361e513dSReid Spencer } 617361e513dSReid Spencer return false; 618361e513dSReid Spencer } 619361e513dSReid Spencer 620dac5fa94SAnton Korobeynikov static GlobalValue::LinkageTypes 621dac5fa94SAnton Korobeynikov CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) { 62212da8ce3SDuncan Sands GlobalValue::LinkageTypes SL = SGV->getLinkage(); 62312da8ce3SDuncan Sands GlobalValue::LinkageTypes DL = DGV->getLinkage(); 62412da8ce3SDuncan Sands if (SL == GlobalValue::ExternalLinkage || DL == GlobalValue::ExternalLinkage) 625dac5fa94SAnton Korobeynikov return GlobalValue::ExternalLinkage; 62612da8ce3SDuncan Sands else if (SL == GlobalValue::WeakAnyLinkage || 62712da8ce3SDuncan Sands DL == GlobalValue::WeakAnyLinkage) 62812da8ce3SDuncan Sands return GlobalValue::WeakAnyLinkage; 62912da8ce3SDuncan Sands else if (SL == GlobalValue::WeakODRLinkage || 63012da8ce3SDuncan Sands DL == GlobalValue::WeakODRLinkage) 63112da8ce3SDuncan Sands return GlobalValue::WeakODRLinkage; 63212da8ce3SDuncan Sands else if (SL == GlobalValue::InternalLinkage && 63312da8ce3SDuncan Sands DL == GlobalValue::InternalLinkage) 634dac5fa94SAnton Korobeynikov return GlobalValue::InternalLinkage; 635a3c6f6bfSBill Wendling else if (SL == GlobalValue::LinkerPrivateLinkage && 636a3c6f6bfSBill Wendling DL == GlobalValue::LinkerPrivateLinkage) 637a3c6f6bfSBill Wendling return GlobalValue::LinkerPrivateLinkage; 6383aeedd1eSBill Wendling else if (SL == GlobalValue::LinkerPrivateWeakLinkage && 6393aeedd1eSBill Wendling DL == GlobalValue::LinkerPrivateWeakLinkage) 6403aeedd1eSBill Wendling return GlobalValue::LinkerPrivateWeakLinkage; 6413aeedd1eSBill Wendling else if (SL == GlobalValue::LinkerPrivateWeakDefAutoLinkage && 6423aeedd1eSBill Wendling DL == GlobalValue::LinkerPrivateWeakDefAutoLinkage) 6433aeedd1eSBill Wendling return GlobalValue::LinkerPrivateWeakDefAutoLinkage; 6446de96a1bSRafael Espindola else { 64512da8ce3SDuncan Sands assert (SL == GlobalValue::PrivateLinkage && 64612da8ce3SDuncan Sands DL == GlobalValue::PrivateLinkage && "Unexpected linkage type"); 6476de96a1bSRafael Espindola return GlobalValue::PrivateLinkage; 648dac5fa94SAnton Korobeynikov } 649dac5fa94SAnton Korobeynikov } 650dac5fa94SAnton Korobeynikov 651b00c9c0dSLauro Ramos Venancio // LinkAlias - Loop through the alias in the src module and link them into the 652dac5fa94SAnton Korobeynikov // dest module. We're assuming, that all functions/global variables were already 653dac5fa94SAnton Korobeynikov // linked in. 6542e13597fSAnton Korobeynikov static bool LinkAlias(Module *Dest, const Module *Src, 655a2095034SDan Gohman ValueToValueMapTy &ValueMap, 6562e13597fSAnton Korobeynikov std::string *Err) { 657b00c9c0dSLauro Ramos Venancio // Loop over all alias in the src module 658b00c9c0dSLauro Ramos Venancio for (Module::const_alias_iterator I = Src->alias_begin(), 659b00c9c0dSLauro Ramos Venancio E = Src->alias_end(); I != E; ++I) { 660dac5fa94SAnton Korobeynikov const GlobalAlias *SGA = I; 661dac5fa94SAnton Korobeynikov const GlobalValue *SAliasee = SGA->getAliasedGlobal(); 662dac5fa94SAnton Korobeynikov GlobalAlias *NewGA = NULL; 663b00c9c0dSLauro Ramos Venancio 664dac5fa94SAnton Korobeynikov // Globals were already linked, thus we can just query ValueMap for variant 665acbdaa24SAnton Korobeynikov // of SAliasee in Dest. 666a2095034SDan Gohman ValueToValueMapTy::const_iterator VMI = ValueMap.find(SAliasee); 667d48ed17dSTed Kremenek assert(VMI != ValueMap.end() && "Aliasee not linked"); 668d48ed17dSTed Kremenek GlobalValue* DAliasee = cast<GlobalValue>(VMI->second); 669acbdaa24SAnton Korobeynikov GlobalValue* DGV = NULL; 670b00c9c0dSLauro Ramos Venancio 671*e73bc890SRafael Espindola // Fixup aliases to bitcasts. Note that aliases to GEPs are still broken 672*e73bc890SRafael Espindola // by this, but aliases to GEPs are broken to a lot of other things, so 673*e73bc890SRafael Espindola // it's less important. 674*e73bc890SRafael Espindola Constant *DAliaseeConst = DAliasee; 675*e73bc890SRafael Espindola if (SGA->getType() != DAliasee->getType()) 676*e73bc890SRafael Espindola DAliaseeConst = ConstantExpr::getBitCast(DAliasee, SGA->getType()); 677*e73bc890SRafael Espindola 678dac5fa94SAnton Korobeynikov // Try to find something 'similar' to SGA in destination module. 6796de96a1bSRafael Espindola if (!DGV && !SGA->hasLocalLinkage()) { 680acbdaa24SAnton Korobeynikov DGV = Dest->getNamedAlias(SGA->getName()); 681acbdaa24SAnton Korobeynikov 682dac5fa94SAnton Korobeynikov // If types don't agree due to opaque types, try to resolve them. 683acbdaa24SAnton Korobeynikov if (DGV && DGV->getType() != SGA->getType()) 684683ed3d9SChris Lattner RecursiveResolveTypes(SGA->getType(), DGV->getType()); 685acbdaa24SAnton Korobeynikov } 6862e13597fSAnton Korobeynikov 6876de96a1bSRafael Espindola if (!DGV && !SGA->hasLocalLinkage()) { 688acbdaa24SAnton Korobeynikov DGV = Dest->getGlobalVariable(SGA->getName()); 689acbdaa24SAnton Korobeynikov 690acbdaa24SAnton Korobeynikov // If types don't agree due to opaque types, try to resolve them. 691acbdaa24SAnton Korobeynikov if (DGV && DGV->getType() != SGA->getType()) 692683ed3d9SChris Lattner RecursiveResolveTypes(SGA->getType(), DGV->getType()); 693acbdaa24SAnton Korobeynikov } 694acbdaa24SAnton Korobeynikov 6956de96a1bSRafael Espindola if (!DGV && !SGA->hasLocalLinkage()) { 696acbdaa24SAnton Korobeynikov DGV = Dest->getFunction(SGA->getName()); 697acbdaa24SAnton Korobeynikov 698acbdaa24SAnton Korobeynikov // If types don't agree due to opaque types, try to resolve them. 699acbdaa24SAnton Korobeynikov if (DGV && DGV->getType() != SGA->getType()) 700683ed3d9SChris Lattner RecursiveResolveTypes(SGA->getType(), DGV->getType()); 701acbdaa24SAnton Korobeynikov } 702acbdaa24SAnton Korobeynikov 703acbdaa24SAnton Korobeynikov // No linking to be performed on internal stuff. 7046de96a1bSRafael Espindola if (DGV && DGV->hasLocalLinkage()) 705acbdaa24SAnton Korobeynikov DGV = NULL; 706acbdaa24SAnton Korobeynikov 707acbdaa24SAnton Korobeynikov if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) { 708acbdaa24SAnton Korobeynikov // Types are known to be the same, check whether aliasees equal. As 709dac5fa94SAnton Korobeynikov // globals are already linked we just need query ValueMap to find the 710dac5fa94SAnton Korobeynikov // mapping. 711dac5fa94SAnton Korobeynikov if (DAliasee == DGA->getAliasedGlobal()) { 712dac5fa94SAnton Korobeynikov // This is just two copies of the same alias. Propagate linkage, if 713dac5fa94SAnton Korobeynikov // necessary. 714dac5fa94SAnton Korobeynikov DGA->setLinkage(CalculateAliasLinkage(SGA, DGA)); 715dac5fa94SAnton Korobeynikov 716dac5fa94SAnton Korobeynikov NewGA = DGA; 717dac5fa94SAnton Korobeynikov // Proceed to 'common' steps 718dac5fa94SAnton Korobeynikov } else 719eeb5ca6fSAnton Korobeynikov return Error(Err, "Alias Collision on '" + SGA->getName()+ 720eeb5ca6fSAnton Korobeynikov "': aliases have different aliasees"); 721acbdaa24SAnton Korobeynikov } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) { 7229cd0b50fSAnton Korobeynikov // The only allowed way is to link alias with external declaration or weak 7239cd0b50fSAnton Korobeynikov // symbol.. 724d725c991SDuncan Sands if (DGVar->isDeclaration() || DGVar->isWeakForLinker()) { 725510fc32dSAnton Korobeynikov // But only if aliasee is global too... 726510fc32dSAnton Korobeynikov if (!isa<GlobalVariable>(DAliasee)) 727510fc32dSAnton Korobeynikov return Error(Err, "Global-Alias Collision on '" + SGA->getName() + 728510fc32dSAnton Korobeynikov "': aliasee is not global variable"); 729510fc32dSAnton Korobeynikov 730dac5fa94SAnton Korobeynikov NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(), 731*e73bc890SRafael Espindola SGA->getName(), DAliaseeConst, Dest); 732dac5fa94SAnton Korobeynikov CopyGVAttributes(NewGA, SGA); 733dac5fa94SAnton Korobeynikov 734dac5fa94SAnton Korobeynikov // Any uses of DGV need to change to NewGA, with cast, if needed. 735acbdaa24SAnton Korobeynikov if (SGA->getType() != DGVar->getType()) 736487375e9SOwen Anderson DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA, 737acbdaa24SAnton Korobeynikov DGVar->getType())); 738dac5fa94SAnton Korobeynikov else 739acbdaa24SAnton Korobeynikov DGVar->replaceAllUsesWith(NewGA); 740dac5fa94SAnton Korobeynikov 741acbdaa24SAnton Korobeynikov // DGVar will conflict with NewGA because they both had the same 742dac5fa94SAnton Korobeynikov // name. We must erase this now so ForceRenaming doesn't assert 743dac5fa94SAnton Korobeynikov // because DGV might not have internal linkage. 744acbdaa24SAnton Korobeynikov DGVar->eraseFromParent(); 745dac5fa94SAnton Korobeynikov 746dac5fa94SAnton Korobeynikov // Proceed to 'common' steps 747dac5fa94SAnton Korobeynikov } else 748eeb5ca6fSAnton Korobeynikov return Error(Err, "Global-Alias Collision on '" + SGA->getName() + 749eeb5ca6fSAnton Korobeynikov "': symbol multiple defined"); 750acbdaa24SAnton Korobeynikov } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) { 7519cd0b50fSAnton Korobeynikov // The only allowed way is to link alias with external declaration or weak 7529cd0b50fSAnton Korobeynikov // symbol... 753d725c991SDuncan Sands if (DF->isDeclaration() || DF->isWeakForLinker()) { 754510fc32dSAnton Korobeynikov // But only if aliasee is function too... 755510fc32dSAnton Korobeynikov if (!isa<Function>(DAliasee)) 756510fc32dSAnton Korobeynikov return Error(Err, "Function-Alias Collision on '" + SGA->getName() + 757510fc32dSAnton Korobeynikov "': aliasee is not function"); 758510fc32dSAnton Korobeynikov 75924f65c3aSAnton Korobeynikov NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(), 760*e73bc890SRafael Espindola SGA->getName(), DAliaseeConst, Dest); 76124f65c3aSAnton Korobeynikov CopyGVAttributes(NewGA, SGA); 76224f65c3aSAnton Korobeynikov 76324f65c3aSAnton Korobeynikov // Any uses of DF need to change to NewGA, with cast, if needed. 76424f65c3aSAnton Korobeynikov if (SGA->getType() != DF->getType()) 765487375e9SOwen Anderson DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA, 76624f65c3aSAnton Korobeynikov DF->getType())); 76724f65c3aSAnton Korobeynikov else 76824f65c3aSAnton Korobeynikov DF->replaceAllUsesWith(NewGA); 76924f65c3aSAnton Korobeynikov 77024f65c3aSAnton Korobeynikov // DF will conflict with NewGA because they both had the same 77124f65c3aSAnton Korobeynikov // name. We must erase this now so ForceRenaming doesn't assert 77224f65c3aSAnton Korobeynikov // because DF might not have internal linkage. 77324f65c3aSAnton Korobeynikov DF->eraseFromParent(); 77424f65c3aSAnton Korobeynikov 77524f65c3aSAnton Korobeynikov // Proceed to 'common' steps 77624f65c3aSAnton Korobeynikov } else 777eeb5ca6fSAnton Korobeynikov return Error(Err, "Function-Alias Collision on '" + SGA->getName() + 778eeb5ca6fSAnton Korobeynikov "': symbol multiple defined"); 779dac5fa94SAnton Korobeynikov } else { 780acbdaa24SAnton Korobeynikov // No linking to be performed, simply create an identical version of the 781acbdaa24SAnton Korobeynikov // alias over in the dest module... 782dac5fa94SAnton Korobeynikov NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(), 783*e73bc890SRafael Espindola SGA->getName(), DAliaseeConst, Dest); 784dac5fa94SAnton Korobeynikov CopyGVAttributes(NewGA, SGA); 785dac5fa94SAnton Korobeynikov 786dac5fa94SAnton Korobeynikov // Proceed to 'common' steps 787b00c9c0dSLauro Ramos Venancio } 788dac5fa94SAnton Korobeynikov 789dac5fa94SAnton Korobeynikov assert(NewGA && "No alias was created in destination module!"); 790dac5fa94SAnton Korobeynikov 791d5160da5SAnton Korobeynikov // If the symbol table renamed the alias, but it is an externally visible 792acbdaa24SAnton Korobeynikov // symbol, DGA must be an global value with internal linkage. Rename it. 793dac5fa94SAnton Korobeynikov if (NewGA->getName() != SGA->getName() && 7946de96a1bSRafael Espindola !NewGA->hasLocalLinkage()) 795dac5fa94SAnton Korobeynikov ForceRenaming(NewGA, SGA->getName()); 796dac5fa94SAnton Korobeynikov 797dac5fa94SAnton Korobeynikov // Remember this mapping so uses in the source module get remapped 798a2095034SDan Gohman // later by MapValue. 79966a6271cSAnton Korobeynikov ValueMap[SGA] = NewGA; 800dac5fa94SAnton Korobeynikov } 801dac5fa94SAnton Korobeynikov 802b00c9c0dSLauro Ramos Venancio return false; 803b00c9c0dSLauro Ramos Venancio } 804b00c9c0dSLauro Ramos Venancio 805361e513dSReid Spencer 806361e513dSReid Spencer // LinkGlobalInits - Update the initializers in the Dest module now that all 807361e513dSReid Spencer // globals that may be referenced are in Dest. 808361e513dSReid Spencer static bool LinkGlobalInits(Module *Dest, const Module *Src, 809a2095034SDan Gohman ValueToValueMapTy &ValueMap, 810361e513dSReid Spencer std::string *Err) { 811361e513dSReid Spencer // Loop over all of the globals in the src module, mapping them over as we go 81244ab8aefSChris Lattner for (Module::const_global_iterator I = Src->global_begin(), 81344ab8aefSChris Lattner E = Src->global_end(); I != E; ++I) { 814361e513dSReid Spencer const GlobalVariable *SGV = I; 815361e513dSReid Spencer 816361e513dSReid Spencer if (SGV->hasInitializer()) { // Only process initialized GV's 817361e513dSReid Spencer // Figure out what the initializer looks like in the dest module... 818361e513dSReid Spencer Constant *SInit = 819ca26f790SDan Gohman cast<Constant>(MapValue(SGV->getInitializer(), ValueMap, true)); 820006659f0SAnton Korobeynikov // Grab destination global variable or alias. 821006659f0SAnton Korobeynikov GlobalValue *DGV = cast<GlobalValue>(ValueMap[SGV]->stripPointerCasts()); 822361e513dSReid Spencer 8235ed50b61SBill Wendling // If dest if global variable, check that initializers match. 824006659f0SAnton Korobeynikov if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) { 825006659f0SAnton Korobeynikov if (DGVar->hasInitializer()) { 8265ed50b61SBill Wendling if (SGV->hasExternalLinkage()) { 827006659f0SAnton Korobeynikov if (DGVar->getInitializer() != SInit) 828006659f0SAnton Korobeynikov return Error(Err, "Global Variable Collision on '" + 829006659f0SAnton Korobeynikov SGV->getName() + 830eeb5ca6fSAnton Korobeynikov "': global variables have different initializers"); 831d725c991SDuncan Sands } else if (DGVar->isWeakForLinker()) { 832361e513dSReid Spencer // Nothing is required, mapped values will take the new global 833361e513dSReid Spencer // automatically. 834d725c991SDuncan Sands } else if (SGV->isWeakForLinker()) { 835361e513dSReid Spencer // Nothing is required, mapped values will take the new global 836361e513dSReid Spencer // automatically. 837006659f0SAnton Korobeynikov } else if (DGVar->hasAppendingLinkage()) { 838fbcc663cSTorok Edwin llvm_unreachable("Appending linkage unimplemented!"); 839361e513dSReid Spencer } else { 840fbcc663cSTorok Edwin llvm_unreachable("Unknown linkage!"); 841361e513dSReid Spencer } 842361e513dSReid Spencer } else { 843361e513dSReid Spencer // Copy the initializer over now... 844006659f0SAnton Korobeynikov DGVar->setInitializer(SInit); 845006659f0SAnton Korobeynikov } 846006659f0SAnton Korobeynikov } else { 847006659f0SAnton Korobeynikov // Destination is alias, the only valid situation is when source is 848006659f0SAnton Korobeynikov // weak. Also, note, that we already checked linkage in LinkGlobals(), 849006659f0SAnton Korobeynikov // thus we assert here. 850006659f0SAnton Korobeynikov // FIXME: Should we weaken this assumption, 'dereference' alias and 851006659f0SAnton Korobeynikov // check for initializer of aliasee? 852d725c991SDuncan Sands assert(SGV->isWeakForLinker()); 853361e513dSReid Spencer } 854361e513dSReid Spencer } 855361e513dSReid Spencer } 856361e513dSReid Spencer return false; 857361e513dSReid Spencer } 858361e513dSReid Spencer 859361e513dSReid Spencer // LinkFunctionProtos - Link the functions together between the two modules, 860361e513dSReid Spencer // without doing function bodies... this just adds external function prototypes 861361e513dSReid Spencer // to the Dest function... 862361e513dSReid Spencer // 863361e513dSReid Spencer static bool LinkFunctionProtos(Module *Dest, const Module *Src, 864a2095034SDan Gohman ValueToValueMapTy &ValueMap, 865361e513dSReid Spencer std::string *Err) { 86634fc5a0eSChris Lattner ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable(); 86734fc5a0eSChris Lattner 868d3ba7d9bSReid Spencer // Loop over all of the functions in the src module, mapping them over 869361e513dSReid Spencer for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) { 870361e513dSReid Spencer const Function *SF = I; // SrcFunction 8711bb56dedSAnton Korobeynikov GlobalValue *DGV = 0; 872228a5f18SChris Lattner 87334fc5a0eSChris Lattner // Check to see if may have to link the function with the global, alias or 87434fc5a0eSChris Lattner // function. 8756de96a1bSRafael Espindola if (SF->hasName() && !SF->hasLocalLinkage()) 876e03eecb7SDaniel Dunbar DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getName())); 877361e513dSReid Spencer 878c08e7a00SChris Lattner // If we found a global with the same name in the dest module, but it has 879c08e7a00SChris Lattner // internal linkage, we are really not doing any linkage here. 8806de96a1bSRafael Espindola if (DGV && DGV->hasLocalLinkage()) 881c08e7a00SChris Lattner DGV = 0; 882c08e7a00SChris Lattner 8831bb56dedSAnton Korobeynikov // If types don't agree due to opaque types, try to resolve them. 88434fc5a0eSChris Lattner if (DGV && DGV->getType() != SF->getType()) 8851bb56dedSAnton Korobeynikov RecursiveResolveTypes(SF->getType(), DGV->getType()); 8861bb56dedSAnton Korobeynikov 8870ead7a50SChris Lattner GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage; 8880ead7a50SChris Lattner bool LinkFromSrc = false; 8890ead7a50SChris Lattner if (GetLinkageResult(DGV, SF, NewLinkage, LinkFromSrc, Err)) 8900ead7a50SChris Lattner return true; 8910ead7a50SChris Lattner 892228a5f18SChris Lattner // If there is no linkage to be performed, just bring over SF without 893228a5f18SChris Lattner // modifying it. 8941bb56dedSAnton Korobeynikov if (DGV == 0) { 895228a5f18SChris Lattner // Function does not already exist, simply insert an function signature 896228a5f18SChris Lattner // identical to SF into the dest module. 897228a5f18SChris Lattner Function *NewDF = Function::Create(SF->getFunctionType(), 898228a5f18SChris Lattner SF->getLinkage(), 899228a5f18SChris Lattner SF->getName(), Dest); 900228a5f18SChris Lattner CopyGVAttributes(NewDF, SF); 901ec7441b3SChris Lattner 902228a5f18SChris Lattner // If the LLVM runtime renamed the function, but it is an externally 903228a5f18SChris Lattner // visible symbol, DF must be an existing function with internal linkage. 904228a5f18SChris Lattner // Rename it. 9056de96a1bSRafael Espindola if (!NewDF->hasLocalLinkage() && NewDF->getName() != SF->getName()) 906228a5f18SChris Lattner ForceRenaming(NewDF, SF->getName()); 907228a5f18SChris Lattner 908228a5f18SChris Lattner // ... and remember this mapping... 909228a5f18SChris Lattner ValueMap[SF] = NewDF; 910228a5f18SChris Lattner continue; 9110ead7a50SChris Lattner } 9120ead7a50SChris Lattner 9130ead7a50SChris Lattner // If the visibilities of the symbols disagree and the destination is a 9140ead7a50SChris Lattner // prototype, take the visibility of its input. 9150ead7a50SChris Lattner if (DGV->isDeclaration()) 9160ead7a50SChris Lattner DGV->setVisibility(SF->getVisibility()); 9170ead7a50SChris Lattner 9180ead7a50SChris Lattner if (LinkFromSrc) { 9190ead7a50SChris Lattner if (isa<GlobalAlias>(DGV)) 9201bb56dedSAnton Korobeynikov return Error(Err, "Function-Alias Collision on '" + SF->getName() + 9211bb56dedSAnton Korobeynikov "': symbol multiple defined"); 9221bb56dedSAnton Korobeynikov 9233aaaa0b2SReid Spencer // We have a definition of the same name but different type in the 9243aaaa0b2SReid Spencer // source module. Copy the prototype to the destination and replace 9253aaaa0b2SReid Spencer // uses of the destination's prototype with the new prototype. 9260ead7a50SChris Lattner Function *NewDF = Function::Create(SF->getFunctionType(), NewLinkage, 9273aaaa0b2SReid Spencer SF->getName(), Dest); 9283aaaa0b2SReid Spencer CopyGVAttributes(NewDF, SF); 9293aaaa0b2SReid Spencer 9303aaaa0b2SReid Spencer // Any uses of DF need to change to NewDF, with cast 931487375e9SOwen Anderson DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, 932fac7b595SOwen Anderson DGV->getType())); 9333aaaa0b2SReid Spencer 9343aaaa0b2SReid Spencer // DF will conflict with NewDF because they both had the same. We must 9353aaaa0b2SReid Spencer // erase this now so ForceRenaming doesn't assert because DF might 9363aaaa0b2SReid Spencer // not have internal linkage. 9370ead7a50SChris Lattner if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV)) 9380ead7a50SChris Lattner Var->eraseFromParent(); 9390ead7a50SChris Lattner else 9400ead7a50SChris Lattner cast<Function>(DGV)->eraseFromParent(); 9413aaaa0b2SReid Spencer 9423aaaa0b2SReid Spencer // If the symbol table renamed the function, but it is an externally 9433aaaa0b2SReid Spencer // visible symbol, DF must be an existing function with internal 9443aaaa0b2SReid Spencer // linkage. Rename it. 9456de96a1bSRafael Espindola if (NewDF->getName() != SF->getName() && !NewDF->hasLocalLinkage()) 9463aaaa0b2SReid Spencer ForceRenaming(NewDF, SF->getName()); 9473aaaa0b2SReid Spencer 9483aaaa0b2SReid Spencer // Remember this mapping so uses in the source module get remapped 949a2095034SDan Gohman // later by MapValue. 9503aaaa0b2SReid Spencer ValueMap[SF] = NewDF; 951228a5f18SChris Lattner continue; 952228a5f18SChris Lattner } 953361e513dSReid Spencer 9540ead7a50SChris Lattner // Not "link from source", keep the one in the DestModule and remap the 9550ead7a50SChris Lattner // input onto it. 9560ead7a50SChris Lattner 9570ead7a50SChris Lattner if (isa<GlobalAlias>(DGV)) { 9580ead7a50SChris Lattner // The only valid mappings are: 9590ead7a50SChris Lattner // - SF is external declaration, which is effectively a no-op. 9600ead7a50SChris Lattner // - SF is weak, when we just need to throw SF out. 961d725c991SDuncan Sands if (!SF->isDeclaration() && !SF->isWeakForLinker()) 9620ead7a50SChris Lattner return Error(Err, "Function-Alias Collision on '" + SF->getName() + 9630ead7a50SChris Lattner "': symbol multiple defined"); 96477e8ac4dSChris Lattner } 96577e8ac4dSChris Lattner 9660ead7a50SChris Lattner // Set calculated linkage 9670ead7a50SChris Lattner DGV->setLinkage(NewLinkage); 96877e8ac4dSChris Lattner 9690ead7a50SChris Lattner // Make sure to remember this mapping. 970487375e9SOwen Anderson ValueMap[SF] = ConstantExpr::getBitCast(DGV, SF->getType()); 971361e513dSReid Spencer } 972361e513dSReid Spencer return false; 973361e513dSReid Spencer } 974361e513dSReid Spencer 975361e513dSReid Spencer // LinkFunctionBody - Copy the source function over into the dest function and 976361e513dSReid Spencer // fix up references to values. At this point we know that Dest is an external 977361e513dSReid Spencer // function, and that Src is not. 9782f0557d0SChris Lattner static bool LinkFunctionBody(Function *Dest, Function *Src, 979a2095034SDan Gohman ValueToValueMapTy &ValueMap, 980361e513dSReid Spencer std::string *Err) { 9815301e7c6SReid Spencer assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration()); 982361e513dSReid Spencer 9837391dde1SChris Lattner // Go through and convert function arguments over, remembering the mapping. 984531f9e92SChris Lattner Function::arg_iterator DI = Dest->arg_begin(); 985531f9e92SChris Lattner for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end(); 986361e513dSReid Spencer I != E; ++I, ++DI) { 9877629b71dSOwen Anderson DI->setName(I->getName()); // Copy the name information over... 988361e513dSReid Spencer 989361e513dSReid Spencer // Add a mapping to our local map 99066a6271cSAnton Korobeynikov ValueMap[I] = DI; 991361e513dSReid Spencer } 992361e513dSReid Spencer 9932f0557d0SChris Lattner // Splice the body of the source function into the dest function. 9942f0557d0SChris Lattner Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList()); 995361e513dSReid Spencer 996361e513dSReid Spencer // At this point, all of the instructions and values of the function are now 997361e513dSReid Spencer // copied over. The only problem is that they are still referencing values in 998361e513dSReid Spencer // the Source function as operands. Loop through all of the operands of the 999361e513dSReid Spencer // functions and patch them up to point to the local versions... 1000361e513dSReid Spencer // 1001ca26f790SDan Gohman // This is the same as RemapInstruction, except that it avoids remapping 1002ca26f790SDan Gohman // instruction and basic block operands. 1003ca26f790SDan Gohman // 1004361e513dSReid Spencer for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB) 1005ca26f790SDan Gohman for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 1006ca26f790SDan Gohman // Remap operands. 1007361e513dSReid Spencer for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end(); 1008361e513dSReid Spencer OI != OE; ++OI) 10092f0557d0SChris Lattner if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI)) 1010ca26f790SDan Gohman *OI = MapValue(*OI, ValueMap, true); 1011ca26f790SDan Gohman 1012ca26f790SDan Gohman // Remap attached metadata. 1013ca26f790SDan Gohman SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 1014ca26f790SDan Gohman I->getAllMetadata(MDs); 1015ca26f790SDan Gohman for (SmallVectorImpl<std::pair<unsigned, MDNode *> >::iterator 1016ca26f790SDan Gohman MI = MDs.begin(), ME = MDs.end(); MI != ME; ++MI) { 1017ca26f790SDan Gohman Value *Old = MI->second; 1018ca26f790SDan Gohman if (!isa<Instruction>(Old) && !isa<BasicBlock>(Old)) { 1019ca26f790SDan Gohman Value *New = MapValue(Old, ValueMap, true); 1020ca26f790SDan Gohman if (New != Old) 1021ca26f790SDan Gohman I->setMetadata(MI->first, cast<MDNode>(New)); 1022ca26f790SDan Gohman } 1023ca26f790SDan Gohman } 1024ca26f790SDan Gohman } 10257391dde1SChris Lattner 10267391dde1SChris Lattner // There is no need to map the arguments anymore. 102744ab8aefSChris Lattner for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end(); 102844ab8aefSChris Lattner I != E; ++I) 10293aaaa0b2SReid Spencer ValueMap.erase(I); 1030361e513dSReid Spencer 1031361e513dSReid Spencer return false; 1032361e513dSReid Spencer } 1033361e513dSReid Spencer 1034361e513dSReid Spencer 1035361e513dSReid Spencer // LinkFunctionBodies - Link in the function bodies that are defined in the 1036361e513dSReid Spencer // source module into the DestModule. This consists basically of copying the 1037361e513dSReid Spencer // function over and fixing up references to values. 10382f0557d0SChris Lattner static bool LinkFunctionBodies(Module *Dest, Module *Src, 1039a2095034SDan Gohman ValueToValueMapTy &ValueMap, 1040361e513dSReid Spencer std::string *Err) { 1041361e513dSReid Spencer 104290246aa7SReid Spencer // Loop over all of the functions in the src module, mapping them over as we 104390246aa7SReid Spencer // go 10442f0557d0SChris Lattner for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) { 10455301e7c6SReid Spencer if (!SF->isDeclaration()) { // No body if function is external 1046d53bd2daSChris Lattner Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function 1047361e513dSReid Spencer 1048361e513dSReid Spencer // DF not external SF external? 1049d53bd2daSChris Lattner if (DF && DF->isDeclaration()) 1050361e513dSReid Spencer // Only provide the function body if there isn't one already. 1051361e513dSReid Spencer if (LinkFunctionBody(DF, SF, ValueMap, Err)) 1052361e513dSReid Spencer return true; 105390246aa7SReid Spencer } 1054361e513dSReid Spencer } 1055361e513dSReid Spencer return false; 1056361e513dSReid Spencer } 1057361e513dSReid Spencer 1058361e513dSReid Spencer // LinkAppendingVars - If there were any appending global variables, link them 1059361e513dSReid Spencer // together now. Return true on error. 1060361e513dSReid Spencer static bool LinkAppendingVars(Module *M, 1061361e513dSReid Spencer std::multimap<std::string, GlobalVariable *> &AppendingVars, 1062361e513dSReid Spencer std::string *ErrorMsg) { 1063361e513dSReid Spencer if (AppendingVars.empty()) return false; // Nothing to do. 1064361e513dSReid Spencer 1065361e513dSReid Spencer // Loop over the multimap of appending vars, processing any variables with the 1066361e513dSReid Spencer // same name, forming a new appending global variable with both of the 1067361e513dSReid Spencer // initializers merged together, then rewrite references to the old variables 1068361e513dSReid Spencer // and delete them. 1069361e513dSReid Spencer std::vector<Constant*> Inits; 1070361e513dSReid Spencer while (AppendingVars.size() > 1) { 1071361e513dSReid Spencer // Get the first two elements in the map... 1072361e513dSReid Spencer std::multimap<std::string, 1073361e513dSReid Spencer GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++; 1074361e513dSReid Spencer 1075361e513dSReid Spencer // If the first two elements are for different names, there is no pair... 1076361e513dSReid Spencer // Otherwise there is a pair, so link them together... 1077361e513dSReid Spencer if (First->first == Second->first) { 1078361e513dSReid Spencer GlobalVariable *G1 = First->second, *G2 = Second->second; 1079361e513dSReid Spencer const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType()); 1080361e513dSReid Spencer const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType()); 1081361e513dSReid Spencer 1082361e513dSReid Spencer // Check to see that they two arrays agree on type... 1083361e513dSReid Spencer if (T1->getElementType() != T2->getElementType()) 1084361e513dSReid Spencer return Error(ErrorMsg, 1085361e513dSReid Spencer "Appending variables with different element types need to be linked!"); 1086361e513dSReid Spencer if (G1->isConstant() != G2->isConstant()) 1087361e513dSReid Spencer return Error(ErrorMsg, 1088361e513dSReid Spencer "Appending variables linked with different const'ness!"); 1089361e513dSReid Spencer 109085703e37SLauro Ramos Venancio if (G1->getAlignment() != G2->getAlignment()) 109185703e37SLauro Ramos Venancio return Error(ErrorMsg, 109285703e37SLauro Ramos Venancio "Appending variables with different alignment need to be linked!"); 109385703e37SLauro Ramos Venancio 109485703e37SLauro Ramos Venancio if (G1->getVisibility() != G2->getVisibility()) 109585703e37SLauro Ramos Venancio return Error(ErrorMsg, 109685703e37SLauro Ramos Venancio "Appending variables with different visibility need to be linked!"); 109785703e37SLauro Ramos Venancio 109885703e37SLauro Ramos Venancio if (G1->getSection() != G2->getSection()) 109985703e37SLauro Ramos Venancio return Error(ErrorMsg, 110085703e37SLauro Ramos Venancio "Appending variables with different section name need to be linked!"); 110185703e37SLauro Ramos Venancio 1102361e513dSReid Spencer unsigned NewSize = T1->getNumElements() + T2->getNumElements(); 11034056ca95SOwen Anderson ArrayType *NewType = ArrayType::get(T1->getElementType(), 1104fac7b595SOwen Anderson NewSize); 1105361e513dSReid Spencer 1106d490d4f0SChris Lattner G1->setName(""); // Clear G1's name in case of a conflict! 1107d490d4f0SChris Lattner 1108361e513dSReid Spencer // Create the new global variable... 1109361e513dSReid Spencer GlobalVariable *NG = 1110b17f3294SOwen Anderson new GlobalVariable(*M, NewType, G1->isConstant(), G1->getLinkage(), 1111b17f3294SOwen Anderson /*init*/0, First->first, 0, G1->isThreadLocal(), 1112b32a9ef0SChris Lattner G1->getType()->getAddressSpace()); 1113361e513dSReid Spencer 111485703e37SLauro Ramos Venancio // Propagate alignment, visibility and section info. 111585703e37SLauro Ramos Venancio CopyGVAttributes(NG, G1); 111685703e37SLauro Ramos Venancio 1117361e513dSReid Spencer // Merge the initializer... 1118361e513dSReid Spencer Inits.reserve(NewSize); 1119361e513dSReid Spencer if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) { 1120361e513dSReid Spencer for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i) 1121361e513dSReid Spencer Inits.push_back(I->getOperand(i)); 1122361e513dSReid Spencer } else { 1123361e513dSReid Spencer assert(isa<ConstantAggregateZero>(G1->getInitializer())); 11245a1acd99SOwen Anderson Constant *CV = Constant::getNullValue(T1->getElementType()); 1125361e513dSReid Spencer for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i) 1126361e513dSReid Spencer Inits.push_back(CV); 1127361e513dSReid Spencer } 1128361e513dSReid Spencer if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) { 1129361e513dSReid Spencer for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i) 1130361e513dSReid Spencer Inits.push_back(I->getOperand(i)); 1131361e513dSReid Spencer } else { 1132361e513dSReid Spencer assert(isa<ConstantAggregateZero>(G2->getInitializer())); 11335a1acd99SOwen Anderson Constant *CV = Constant::getNullValue(T2->getElementType()); 1134361e513dSReid Spencer for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i) 1135361e513dSReid Spencer Inits.push_back(CV); 1136361e513dSReid Spencer } 1137c2c7932cSOwen Anderson NG->setInitializer(ConstantArray::get(NewType, Inits)); 1138361e513dSReid Spencer Inits.clear(); 1139361e513dSReid Spencer 1140361e513dSReid Spencer // Replace any uses of the two global variables with uses of the new 1141361e513dSReid Spencer // global... 1142361e513dSReid Spencer 1143361e513dSReid Spencer // FIXME: This should rewrite simple/straight-forward uses such as 1144361e513dSReid Spencer // getelementptr instructions to not use the Cast! 1145487375e9SOwen Anderson G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG, 1146fac7b595SOwen Anderson G1->getType())); 1147487375e9SOwen Anderson G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG, 1148fac7b595SOwen Anderson G2->getType())); 1149361e513dSReid Spencer 1150361e513dSReid Spencer // Remove the two globals from the module now... 1151361e513dSReid Spencer M->getGlobalList().erase(G1); 1152361e513dSReid Spencer M->getGlobalList().erase(G2); 1153361e513dSReid Spencer 1154361e513dSReid Spencer // Put the new global into the AppendingVars map so that we can handle 1155361e513dSReid Spencer // linking of more than two vars... 1156361e513dSReid Spencer Second->second = NG; 1157361e513dSReid Spencer } 1158361e513dSReid Spencer AppendingVars.erase(First); 1159361e513dSReid Spencer } 1160361e513dSReid Spencer 1161361e513dSReid Spencer return false; 1162361e513dSReid Spencer } 1163361e513dSReid Spencer 11642609888fSAnton Korobeynikov static bool ResolveAliases(Module *Dest) { 11652609888fSAnton Korobeynikov for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end(); 1166e6d90f5aSAnton Korobeynikov I != E; ++I) 11672c4a34aeSDavid Chisnall // We can't sue resolveGlobalAlias here because we need to preserve 11682c4a34aeSDavid Chisnall // bitcasts and GEPs. 11692c4a34aeSDavid Chisnall if (const Constant *C = I->getAliasee()) { 11702c4a34aeSDavid Chisnall while (dyn_cast<GlobalAlias>(C)) 11712c4a34aeSDavid Chisnall C = cast<GlobalAlias>(C)->getAliasee(); 11722c4a34aeSDavid Chisnall const GlobalValue *GV = dyn_cast<GlobalValue>(C); 11732c4a34aeSDavid Chisnall if (C != I && !(GV && GV->isDeclaration())) 11742c4a34aeSDavid Chisnall I->replaceAllUsesWith(const_cast<Constant*>(C)); 11752c4a34aeSDavid Chisnall } 11762609888fSAnton Korobeynikov 11772609888fSAnton Korobeynikov return false; 11782609888fSAnton Korobeynikov } 1179361e513dSReid Spencer 1180361e513dSReid Spencer // LinkModules - This function links two modules together, with the resulting 1181361e513dSReid Spencer // left module modified to be the composite of the two input modules. If an 1182361e513dSReid Spencer // error occurs, true is returned and ErrorMsg (if not null) is set to indicate 1183361e513dSReid Spencer // the problem. Upon failure, the Dest module could be in a modified state, and 1184361e513dSReid Spencer // shouldn't be relied on to be consistent. 1185c4e31534SReid Spencer bool 1186c4e31534SReid Spencer Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) { 1187361e513dSReid Spencer assert(Dest != 0 && "Invalid Destination module"); 1188361e513dSReid Spencer assert(Src != 0 && "Invalid Source Module"); 1189361e513dSReid Spencer 11907f3bd82aSChris Lattner if (Dest->getDataLayout().empty()) { 11917f3bd82aSChris Lattner if (!Src->getDataLayout().empty()) { 119278bddc38SChris Lattner Dest->setDataLayout(Src->getDataLayout()); 11937f3bd82aSChris Lattner } else { 11943ac38e99SReid Spencer std::string DataLayout; 11953ac38e99SReid Spencer 1196bddf51bcSAnton Korobeynikov if (Dest->getEndianness() == Module::AnyEndianness) { 11973ac38e99SReid Spencer if (Src->getEndianness() == Module::BigEndian) 11983ac38e99SReid Spencer DataLayout.append("E"); 11993ac38e99SReid Spencer else if (Src->getEndianness() == Module::LittleEndian) 12003ac38e99SReid Spencer DataLayout.append("e"); 1201bddf51bcSAnton Korobeynikov } 1202bddf51bcSAnton Korobeynikov 1203bddf51bcSAnton Korobeynikov if (Dest->getPointerSize() == Module::AnyPointerSize) { 12043ac38e99SReid Spencer if (Src->getPointerSize() == Module::Pointer64) 12053ac38e99SReid Spencer DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64"); 12063ac38e99SReid Spencer else if (Src->getPointerSize() == Module::Pointer32) 12073ac38e99SReid Spencer DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32"); 1208bddf51bcSAnton Korobeynikov } 12093ac38e99SReid Spencer Dest->setDataLayout(DataLayout); 12107f3bd82aSChris Lattner } 12117f3bd82aSChris Lattner } 1212361e513dSReid Spencer 121390c2df5bSChris Lattner // Copy the target triple from the source to dest if the dest's is empty. 12147f3bd82aSChris Lattner if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty()) 12157f3bd82aSChris Lattner Dest->setTargetTriple(Src->getTargetTriple()); 12167f3bd82aSChris Lattner 12177f3bd82aSChris Lattner if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() && 12187f3bd82aSChris Lattner Src->getDataLayout() != Dest->getDataLayout()) 1219b25de3ffSChris Lattner errs() << "WARNING: Linking two modules of different data layouts!\n"; 1220b7f5916eSChris Lattner if (!Src->getTargetTriple().empty() && 1221b7f5916eSChris Lattner Dest->getTargetTriple() != Src->getTargetTriple()) 1222b25de3ffSChris Lattner errs() << "WARNING: Linking two modules of different target triples!\n"; 1223361e513dSReid Spencer 122490c2df5bSChris Lattner // Append the module inline asm string. 12258ebd2164SChris Lattner if (!Src->getModuleInlineAsm().empty()) { 12268ebd2164SChris Lattner if (Dest->getModuleInlineAsm().empty()) 12278ebd2164SChris Lattner Dest->setModuleInlineAsm(Src->getModuleInlineAsm()); 1228dd2d3fafSChris Lattner else 12298ebd2164SChris Lattner Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+ 12308ebd2164SChris Lattner Src->getModuleInlineAsm()); 1231dd2d3fafSChris Lattner } 1232dd2d3fafSChris Lattner 1233361e513dSReid Spencer // Update the destination module's dependent libraries list with the libraries 1234361e513dSReid Spencer // from the source module. There's no opportunity for duplicates here as the 1235361e513dSReid Spencer // Module ensures that duplicate insertions are discarded. 123690c2df5bSChris Lattner for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end(); 123790c2df5bSChris Lattner SI != SE; ++SI) 1238361e513dSReid Spencer Dest->addLibrary(*SI); 1239361e513dSReid Spencer 1240361e513dSReid Spencer // LinkTypes - Go through the symbol table of the Src module and see if any 1241361e513dSReid Spencer // types are named in the src module that are not named in the Dst module. 1242361e513dSReid Spencer // Make sure there are no type name conflicts. 1243d3ba7d9bSReid Spencer if (LinkTypes(Dest, Src, ErrorMsg)) 1244d3ba7d9bSReid Spencer return true; 1245361e513dSReid Spencer 1246361e513dSReid Spencer // ValueMap - Mapping of values from what they used to be in Src, to what they 1247a2095034SDan Gohman // are now in Dest. ValueToValueMapTy is a ValueMap, which involves some 1248a2095034SDan Gohman // overhead due to the use of Value handles which the Linker doesn't actually 1249a2095034SDan Gohman // need, but this allows us to reuse the ValueMapper code. 1250a2095034SDan Gohman ValueToValueMapTy ValueMap; 1251361e513dSReid Spencer 1252361e513dSReid Spencer // AppendingVars - Keep track of global variables in the destination module 1253361e513dSReid Spencer // with appending linkage. After the module is linked together, they are 1254361e513dSReid Spencer // appended and the module is rewritten. 1255361e513dSReid Spencer std::multimap<std::string, GlobalVariable *> AppendingVars; 125644ab8aefSChris Lattner for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end(); 125744ab8aefSChris Lattner I != E; ++I) { 1258361e513dSReid Spencer // Add all of the appending globals already in the Dest module to 1259361e513dSReid Spencer // AppendingVars. 1260361e513dSReid Spencer if (I->hasAppendingLinkage()) 1261361e513dSReid Spencer AppendingVars.insert(std::make_pair(I->getName(), I)); 1262361e513dSReid Spencer } 1263361e513dSReid Spencer 1264361e513dSReid Spencer // Insert all of the globals in src into the Dest module... without linking 1265361e513dSReid Spencer // initializers (which could refer to functions not yet mapped over). 12663aaaa0b2SReid Spencer if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg)) 1267361e513dSReid Spencer return true; 1268361e513dSReid Spencer 1269361e513dSReid Spencer // Link the functions together between the two modules, without doing function 1270361e513dSReid Spencer // bodies... this just adds external function prototypes to the Dest 1271361e513dSReid Spencer // function... We do this so that when we begin processing function bodies, 1272361e513dSReid Spencer // all of the global values that may be referenced are available in our 1273361e513dSReid Spencer // ValueMap. 12743aaaa0b2SReid Spencer if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg)) 1275361e513dSReid Spencer return true; 1276361e513dSReid Spencer 12772e13597fSAnton Korobeynikov // If there were any alias, link them now. We really need to do this now, 12782e13597fSAnton Korobeynikov // because all of the aliases that may be referenced need to be available in 12792e13597fSAnton Korobeynikov // ValueMap 12802e13597fSAnton Korobeynikov if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true; 12812e13597fSAnton Korobeynikov 1282361e513dSReid Spencer // Update the initializers in the Dest module now that all globals that may 1283361e513dSReid Spencer // be referenced are in Dest. 1284361e513dSReid Spencer if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true; 1285361e513dSReid Spencer 1286361e513dSReid Spencer // Link in the function bodies that are defined in the source module into the 1287361e513dSReid Spencer // DestModule. This consists basically of copying the function over and 1288361e513dSReid Spencer // fixing up references to values. 1289361e513dSReid Spencer if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true; 1290361e513dSReid Spencer 1291361e513dSReid Spencer // If there were any appending global variables, link them together now. 1292361e513dSReid Spencer if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true; 1293361e513dSReid Spencer 1294e43711d3SAnton Korobeynikov // Resolve all uses of aliases with aliasees 1295e43711d3SAnton Korobeynikov if (ResolveAliases(Dest)) return true; 1296e43711d3SAnton Korobeynikov 12978ad536a9SDan Gohman // Remap all of the named mdnoes in Src into the Dest module. We do this 12988ad536a9SDan Gohman // after linking GlobalValues so that MDNodes that reference GlobalValues 12998ad536a9SDan Gohman // are properly remapped. 13008ad536a9SDan Gohman LinkNamedMDNodes(Dest, Src, ValueMap); 13018ad536a9SDan Gohman 1302361e513dSReid Spencer // If the source library's module id is in the dependent library list of the 1303361e513dSReid Spencer // destination library, remove it since that module is now linked in. 1304361e513dSReid Spencer sys::Path modId; 1305c9c0473fSReid Spencer modId.set(Src->getModuleIdentifier()); 1306361e513dSReid Spencer if (!modId.isEmpty()) 1307361e513dSReid Spencer Dest->removeLibrary(modId.getBasename()); 1308361e513dSReid Spencer 1309361e513dSReid Spencer return false; 1310361e513dSReid Spencer } 1311361e513dSReid Spencer 1312361e513dSReid Spencer // vim: sw=2 1313