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 //===----------------------------------------------------------------------===// 13361e513dSReid Spencer 146cc07df4SChandler Carruth #include "llvm/Linker/Linker.h" 15ed0881b2SChandler Carruth #include "llvm-c/Linker.h" 1623f8d64bSRafael Espindola #include "llvm/ADT/Optional.h" 1766f02413SBill Wendling #include "llvm/ADT/SetVector.h" 180f7fd36fSEli Bendersky #include "llvm/ADT/SmallString.h" 199fb823bbSChandler Carruth #include "llvm/IR/Constants.h" 20d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticInfo.h" 21d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticPrinter.h" 22d12b4a33SRafael Espindola #include "llvm/IR/LLVMContext.h" 239fb823bbSChandler Carruth #include "llvm/IR/Module.h" 24dcb603feSChandler Carruth #include "llvm/IR/TypeFinder.h" 25e17f3708SEli Bendersky #include "llvm/Support/CommandLine.h" 26b6af2f36SBill Wendling #include "llvm/Support/Debug.h" 27b6af2f36SBill Wendling #include "llvm/Support/raw_ostream.h" 28cbb91408STanya Lattner #include "llvm/Transforms/Utils/Cloning.h" 29981af002SWill Dietz #include <cctype> 3082d6ff6bSDavid Majnemer #include <tuple> 31361e513dSReid Spencer using namespace llvm; 32361e513dSReid Spencer 33e17f3708SEli Bendersky 34b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 35b1ed91f3SChris Lattner // TypeMap implementation. 36b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 37b1ed91f3SChris Lattner 38b1ed91f3SChris Lattner namespace { 39aa9918aaSRafael Espindola typedef SmallPtrSet<StructType *, 32> TypeSet; 40aa9918aaSRafael Espindola 41b1ed91f3SChris Lattner class TypeMapTy : public ValueMapTypeRemapper { 4218c89411SRafael Espindola /// This is a mapping from a source type to a destination type to use. 43b1ed91f3SChris Lattner DenseMap<Type*, Type*> MappedTypes; 44b1ed91f3SChris Lattner 4518c89411SRafael Espindola /// When checking to see if two subgraphs are isomorphic, we speculatively 4618c89411SRafael Espindola /// add types to MappedTypes, but keep track of them here in case we need to 4718c89411SRafael Espindola /// roll back. 48b1ed91f3SChris Lattner SmallVector<Type*, 16> SpeculativeTypes; 49b1ed91f3SChris Lattner 5018c89411SRafael Espindola /// This is a list of non-opaque structs in the source module that are mapped 5118c89411SRafael Espindola /// to an opaque struct in the destination module. 525e3bd972SChris Lattner SmallVector<StructType*, 16> SrcDefinitionsToResolve; 535e3bd972SChris Lattner 5418c89411SRafael Espindola /// This is the set of opaque types in the destination modules who are 5518c89411SRafael Espindola /// getting a body from the source module. 565e3bd972SChris Lattner SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes; 57d48b7783SBill Wendling 588c2cc416SBill Wendling public: 59aa9918aaSRafael Espindola TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {} 60aa9918aaSRafael Espindola 61aa9918aaSRafael Espindola TypeSet &DstStructTypesSet; 6218c89411SRafael Espindola /// Indicate that the specified type in the destination module is conceptually 6318c89411SRafael Espindola /// equivalent to the specified type in the source module. 64b1ed91f3SChris Lattner void addTypeMapping(Type *DstTy, Type *SrcTy); 65b1ed91f3SChris Lattner 66b1ed91f3SChris Lattner /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest 67b1ed91f3SChris Lattner /// module from a type definition in the source module. 68b1ed91f3SChris Lattner void linkDefinedTypeBodies(); 69b1ed91f3SChris Lattner 7018c89411SRafael Espindola /// Return the mapped type to use for the specified input type from the 71b1ed91f3SChris Lattner /// source module. 72b1ed91f3SChris Lattner Type *get(Type *SrcTy); 73b1ed91f3SChris Lattner 74b1ed91f3SChris Lattner FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));} 75b1ed91f3SChris Lattner 7618c89411SRafael Espindola /// Dump out the type map for debugging purposes. 77b6af2f36SBill Wendling void dump() const { 78b6af2f36SBill Wendling for (DenseMap<Type*, Type*>::const_iterator 79b6af2f36SBill Wendling I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) { 80b6af2f36SBill Wendling dbgs() << "TypeMap: "; 81c0087f36SJustin Bogner I->first->print(dbgs()); 82b6af2f36SBill Wendling dbgs() << " => "; 83c0087f36SJustin Bogner I->second->print(dbgs()); 84b6af2f36SBill Wendling dbgs() << '\n'; 85b6af2f36SBill Wendling } 86b6af2f36SBill Wendling } 87b6af2f36SBill Wendling 88b1ed91f3SChris Lattner private: 89b1ed91f3SChris Lattner Type *getImpl(Type *T); 9018c89411SRafael Espindola /// Implement the ValueMapTypeRemapper interface. 918548299aSCraig Topper Type *remapType(Type *SrcTy) override { 92b1ed91f3SChris Lattner return get(SrcTy); 93b1ed91f3SChris Lattner } 94b1ed91f3SChris Lattner 95b1ed91f3SChris Lattner bool areTypesIsomorphic(Type *DstTy, Type *SrcTy); 96b1ed91f3SChris Lattner }; 97b1ed91f3SChris Lattner } 98b1ed91f3SChris Lattner 99b1ed91f3SChris Lattner void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) { 100b1ed91f3SChris Lattner Type *&Entry = MappedTypes[SrcTy]; 101b1ed91f3SChris Lattner if (Entry) return; 102b1ed91f3SChris Lattner 103b1ed91f3SChris Lattner if (DstTy == SrcTy) { 104b1ed91f3SChris Lattner Entry = DstTy; 105b1ed91f3SChris Lattner return; 106b1ed91f3SChris Lattner } 107b1ed91f3SChris Lattner 108b1ed91f3SChris Lattner // Check to see if these types are recursively isomorphic and establish a 109b1ed91f3SChris Lattner // mapping between them if so. 110d48b7783SBill Wendling if (!areTypesIsomorphic(DstTy, SrcTy)) { 111b1ed91f3SChris Lattner // Oops, they aren't isomorphic. Just discard this request by rolling out 112b1ed91f3SChris Lattner // any speculative mappings we've established. 113b1ed91f3SChris Lattner for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i) 114b1ed91f3SChris Lattner MappedTypes.erase(SpeculativeTypes[i]); 115d48b7783SBill Wendling } 116b1ed91f3SChris Lattner SpeculativeTypes.clear(); 117b1ed91f3SChris Lattner } 118b1ed91f3SChris Lattner 11918c89411SRafael Espindola /// Recursively walk this pair of types, returning true if they are isomorphic, 12018c89411SRafael Espindola /// false if they are not. 121b1ed91f3SChris Lattner bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) { 122b1ed91f3SChris Lattner // Two types with differing kinds are clearly not isomorphic. 123b1ed91f3SChris Lattner if (DstTy->getTypeID() != SrcTy->getTypeID()) return false; 124b1ed91f3SChris Lattner 125b1ed91f3SChris Lattner // If we have an entry in the MappedTypes table, then we have our answer. 126b1ed91f3SChris Lattner Type *&Entry = MappedTypes[SrcTy]; 127b1ed91f3SChris Lattner if (Entry) 128b1ed91f3SChris Lattner return Entry == DstTy; 129b1ed91f3SChris Lattner 130b1ed91f3SChris Lattner // Two identical types are clearly isomorphic. Remember this 131b1ed91f3SChris Lattner // non-speculatively. 132b1ed91f3SChris Lattner if (DstTy == SrcTy) { 133b1ed91f3SChris Lattner Entry = DstTy; 134361e513dSReid Spencer return true; 135361e513dSReid Spencer } 136361e513dSReid Spencer 137b1ed91f3SChris Lattner // Okay, we have two types with identical kinds that we haven't seen before. 138361e513dSReid Spencer 139b1ed91f3SChris Lattner // If this is an opaque struct type, special case it. 140b1ed91f3SChris Lattner if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) { 141b1ed91f3SChris Lattner // Mapping an opaque type to any struct, just keep the dest struct. 142b1ed91f3SChris Lattner if (SSTy->isOpaque()) { 143b1ed91f3SChris Lattner Entry = DstTy; 144b1ed91f3SChris Lattner SpeculativeTypes.push_back(SrcTy); 145b1ed91f3SChris Lattner return true; 146361e513dSReid Spencer } 147b1ed91f3SChris Lattner 1485e3bd972SChris Lattner // Mapping a non-opaque source type to an opaque dest. If this is the first 1495e3bd972SChris Lattner // type that we're mapping onto this destination type then we succeed. Keep 1505e3bd972SChris Lattner // the dest, but fill it in later. This doesn't need to be speculative. If 1515e3bd972SChris Lattner // this is the second (different) type that we're trying to map onto the 1525e3bd972SChris Lattner // same opaque type then we fail. 153b1ed91f3SChris Lattner if (cast<StructType>(DstTy)->isOpaque()) { 1545e3bd972SChris Lattner // We can only map one source type onto the opaque destination type. 15570573dcdSDavid Blaikie if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second) 1565e3bd972SChris Lattner return false; 1575e3bd972SChris Lattner SrcDefinitionsToResolve.push_back(SSTy); 158b1ed91f3SChris Lattner Entry = DstTy; 159b1ed91f3SChris Lattner return true; 160b1ed91f3SChris Lattner } 161b1ed91f3SChris Lattner } 162b1ed91f3SChris Lattner 163b1ed91f3SChris Lattner // If the number of subtypes disagree between the two types, then we fail. 164b1ed91f3SChris Lattner if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes()) 165b1ed91f3SChris Lattner return false; 166b1ed91f3SChris Lattner 167b1ed91f3SChris Lattner // Fail if any of the extra properties (e.g. array size) of the type disagree. 168b1ed91f3SChris Lattner if (isa<IntegerType>(DstTy)) 169b1ed91f3SChris Lattner return false; // bitwidth disagrees. 170b1ed91f3SChris Lattner if (PointerType *PT = dyn_cast<PointerType>(DstTy)) { 171b1ed91f3SChris Lattner if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace()) 172b1ed91f3SChris Lattner return false; 173eaf9b762SChris Lattner 174b1ed91f3SChris Lattner } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) { 175b1ed91f3SChris Lattner if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg()) 176b1ed91f3SChris Lattner return false; 177b1ed91f3SChris Lattner } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) { 178b1ed91f3SChris Lattner StructType *SSTy = cast<StructType>(SrcTy); 17944f7ab45SChris Lattner if (DSTy->isLiteral() != SSTy->isLiteral() || 180b1ed91f3SChris Lattner DSTy->isPacked() != SSTy->isPacked()) 181b1ed91f3SChris Lattner return false; 182b1ed91f3SChris Lattner } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) { 183b1ed91f3SChris Lattner if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements()) 184b1ed91f3SChris Lattner return false; 185b1ed91f3SChris Lattner } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) { 1865fad3e9aSJoey Gouly if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements()) 187361e513dSReid Spencer return false; 188361e513dSReid Spencer } 189361e513dSReid Spencer 190b1ed91f3SChris Lattner // Otherwise, we speculate that these two types will line up and recursively 191b1ed91f3SChris Lattner // check the subelements. 192b1ed91f3SChris Lattner Entry = DstTy; 193b1ed91f3SChris Lattner SpeculativeTypes.push_back(SrcTy); 194eee6f995SChris Lattner 195d48b7783SBill Wendling for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i) 196d48b7783SBill Wendling if (!areTypesIsomorphic(DstTy->getContainedType(i), 197d48b7783SBill Wendling SrcTy->getContainedType(i))) 198b1ed91f3SChris Lattner return false; 199eee6f995SChris Lattner 200b1ed91f3SChris Lattner // If everything seems to have lined up, then everything is great. 201eee6f995SChris Lattner return true; 202eee6f995SChris Lattner } 203eee6f995SChris Lattner 20418c89411SRafael Espindola /// Produce a body for an opaque type in the dest module from a type definition 20518c89411SRafael Espindola /// in the source module. 206b1ed91f3SChris Lattner void TypeMapTy::linkDefinedTypeBodies() { 207b1ed91f3SChris Lattner SmallVector<Type*, 16> Elements; 208b1ed91f3SChris Lattner SmallString<16> TmpName; 209eee6f995SChris Lattner 210b1ed91f3SChris Lattner // Note that processing entries in this loop (calling 'get') can add new 2115e3bd972SChris Lattner // entries to the SrcDefinitionsToResolve vector. 2125e3bd972SChris Lattner while (!SrcDefinitionsToResolve.empty()) { 2135e3bd972SChris Lattner StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val(); 214b1ed91f3SChris Lattner StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]); 215eee6f995SChris Lattner 216b1ed91f3SChris Lattner // TypeMap is a many-to-one mapping, if there were multiple types that 217b1ed91f3SChris Lattner // provide a body for DstSTy then previous iterations of this loop may have 218b1ed91f3SChris Lattner // already handled it. Just ignore this case. 219b1ed91f3SChris Lattner if (!DstSTy->isOpaque()) continue; 220b1ed91f3SChris Lattner assert(!SrcSTy->isOpaque() && "Not resolving a definition?"); 221b1ed91f3SChris Lattner 222b1ed91f3SChris Lattner // Map the body of the source type over to a new body for the dest type. 223b1ed91f3SChris Lattner Elements.resize(SrcSTy->getNumElements()); 224b1ed91f3SChris Lattner for (unsigned i = 0, e = Elements.size(); i != e; ++i) 225b1ed91f3SChris Lattner Elements[i] = getImpl(SrcSTy->getElementType(i)); 226b1ed91f3SChris Lattner 227b1ed91f3SChris Lattner DstSTy->setBody(Elements, SrcSTy->isPacked()); 228b1ed91f3SChris Lattner 229b1ed91f3SChris Lattner // If DstSTy has no name or has a longer name than STy, then viciously steal 230b1ed91f3SChris Lattner // STy's name. 231b1ed91f3SChris Lattner if (!SrcSTy->hasName()) continue; 232b1ed91f3SChris Lattner StringRef SrcName = SrcSTy->getName(); 233b1ed91f3SChris Lattner 234b1ed91f3SChris Lattner if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) { 235b1ed91f3SChris Lattner TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end()); 236b1ed91f3SChris Lattner SrcSTy->setName(""); 237b1ed91f3SChris Lattner DstSTy->setName(TmpName.str()); 238b1ed91f3SChris Lattner TmpName.clear(); 239b1ed91f3SChris Lattner } 240b1ed91f3SChris Lattner } 2415e3bd972SChris Lattner 2425e3bd972SChris Lattner DstResolvedOpaqueTypes.clear(); 243eee6f995SChris Lattner } 244eee6f995SChris Lattner 245b1ed91f3SChris Lattner Type *TypeMapTy::get(Type *Ty) { 246b1ed91f3SChris Lattner Type *Result = getImpl(Ty); 247b1ed91f3SChris Lattner 248b1ed91f3SChris Lattner // If this caused a reference to any struct type, resolve it before returning. 2495e3bd972SChris Lattner if (!SrcDefinitionsToResolve.empty()) 250b1ed91f3SChris Lattner linkDefinedTypeBodies(); 251b1ed91f3SChris Lattner return Result; 252eee6f995SChris Lattner } 253eee6f995SChris Lattner 25418c89411SRafael Espindola /// This is the recursive version of get(). 255b1ed91f3SChris Lattner Type *TypeMapTy::getImpl(Type *Ty) { 256b1ed91f3SChris Lattner // If we already have an entry for this type, return it. 257b1ed91f3SChris Lattner Type **Entry = &MappedTypes[Ty]; 258b1ed91f3SChris Lattner if (*Entry) return *Entry; 259b1ed91f3SChris Lattner 260b1ed91f3SChris Lattner // If this is not a named struct type, then just map all of the elements and 261b1ed91f3SChris Lattner // then rebuild the type from inside out. 26244f7ab45SChris Lattner if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) { 263b1ed91f3SChris Lattner // If there are no element types to map, then the type is itself. This is 264b1ed91f3SChris Lattner // true for the anonymous {} struct, things like 'float', integers, etc. 265b1ed91f3SChris Lattner if (Ty->getNumContainedTypes() == 0) 266b1ed91f3SChris Lattner return *Entry = Ty; 267b1ed91f3SChris Lattner 268b1ed91f3SChris Lattner // Remap all of the elements, keeping track of whether any of them change. 269b1ed91f3SChris Lattner bool AnyChange = false; 270b1ed91f3SChris Lattner SmallVector<Type*, 4> ElementTypes; 271b1ed91f3SChris Lattner ElementTypes.resize(Ty->getNumContainedTypes()); 272b1ed91f3SChris Lattner for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) { 273b1ed91f3SChris Lattner ElementTypes[i] = getImpl(Ty->getContainedType(i)); 274b1ed91f3SChris Lattner AnyChange |= ElementTypes[i] != Ty->getContainedType(i); 275eee6f995SChris Lattner } 276b1ed91f3SChris Lattner 277b1ed91f3SChris Lattner // If we found our type while recursively processing stuff, just use it. 278b1ed91f3SChris Lattner Entry = &MappedTypes[Ty]; 279b1ed91f3SChris Lattner if (*Entry) return *Entry; 280b1ed91f3SChris Lattner 281b1ed91f3SChris Lattner // If all of the element types mapped directly over, then the type is usable 282b1ed91f3SChris Lattner // as-is. 283b1ed91f3SChris Lattner if (!AnyChange) 284b1ed91f3SChris Lattner return *Entry = Ty; 285b1ed91f3SChris Lattner 286b1ed91f3SChris Lattner // Otherwise, rebuild a modified type. 287b1ed91f3SChris Lattner switch (Ty->getTypeID()) { 288a2886c21SCraig Topper default: llvm_unreachable("unknown derived type to remap"); 289b1ed91f3SChris Lattner case Type::ArrayTyID: 290b1ed91f3SChris Lattner return *Entry = ArrayType::get(ElementTypes[0], 291b1ed91f3SChris Lattner cast<ArrayType>(Ty)->getNumElements()); 292b1ed91f3SChris Lattner case Type::VectorTyID: 293b1ed91f3SChris Lattner return *Entry = VectorType::get(ElementTypes[0], 294b1ed91f3SChris Lattner cast<VectorType>(Ty)->getNumElements()); 295b1ed91f3SChris Lattner case Type::PointerTyID: 296b1ed91f3SChris Lattner return *Entry = PointerType::get(ElementTypes[0], 297b1ed91f3SChris Lattner cast<PointerType>(Ty)->getAddressSpace()); 298b1ed91f3SChris Lattner case Type::FunctionTyID: 299b1ed91f3SChris Lattner return *Entry = FunctionType::get(ElementTypes[0], 300717d7eddSFrits van Bommel makeArrayRef(ElementTypes).slice(1), 301b1ed91f3SChris Lattner cast<FunctionType>(Ty)->isVarArg()); 302b1ed91f3SChris Lattner case Type::StructTyID: 303b1ed91f3SChris Lattner // Note that this is only reached for anonymous structs. 304b1ed91f3SChris Lattner return *Entry = StructType::get(Ty->getContext(), ElementTypes, 305b1ed91f3SChris Lattner cast<StructType>(Ty)->isPacked()); 306b1ed91f3SChris Lattner } 307b1ed91f3SChris Lattner } 308b1ed91f3SChris Lattner 309b1ed91f3SChris Lattner // Otherwise, this is an unmapped named struct. If the struct can be directly 310b1ed91f3SChris Lattner // mapped over, just use it as-is. This happens in a case when the linked-in 311b1ed91f3SChris Lattner // module has something like: 312b1ed91f3SChris Lattner // %T = type {%T*, i32} 313b1ed91f3SChris Lattner // @GV = global %T* null 314b1ed91f3SChris Lattner // where T does not exist at all in the destination module. 315b1ed91f3SChris Lattner // 316b1ed91f3SChris Lattner // The other case we watch for is when the type is not in the destination 317b1ed91f3SChris Lattner // module, but that it has to be rebuilt because it refers to something that 318b1ed91f3SChris Lattner // is already mapped. For example, if the destination module has: 319b1ed91f3SChris Lattner // %A = type { i32 } 320b1ed91f3SChris Lattner // and the source module has something like 321b1ed91f3SChris Lattner // %A' = type { i32 } 322b1ed91f3SChris Lattner // %B = type { %A'* } 323b1ed91f3SChris Lattner // @GV = global %B* null 324b1ed91f3SChris Lattner // then we want to create a new type: "%B = type { %A*}" and have it take the 325b1ed91f3SChris Lattner // pristine "%B" name from the source module. 326b1ed91f3SChris Lattner // 327b1ed91f3SChris Lattner // To determine which case this is, we have to recursively walk the type graph 328b1ed91f3SChris Lattner // speculating that we'll be able to reuse it unmodified. Only if this is 329b1ed91f3SChris Lattner // safe would we map the entire thing over. Because this is an optimization, 330b1ed91f3SChris Lattner // and is not required for the prettiness of the linked module, we just skip 331b1ed91f3SChris Lattner // it and always rebuild a type here. 332b1ed91f3SChris Lattner StructType *STy = cast<StructType>(Ty); 333b1ed91f3SChris Lattner 334b1ed91f3SChris Lattner // If the type is opaque, we can just use it directly. 335aa9918aaSRafael Espindola if (STy->isOpaque()) { 336aa9918aaSRafael Espindola // A named structure type from src module is used. Add it to the Set of 337aa9918aaSRafael Espindola // identified structs in the destination module. 338aa9918aaSRafael Espindola DstStructTypesSet.insert(STy); 339b1ed91f3SChris Lattner return *Entry = STy; 340aa9918aaSRafael Espindola } 341b1ed91f3SChris Lattner 342b1ed91f3SChris Lattner // Otherwise we create a new type and resolve its body later. This will be 343b1ed91f3SChris Lattner // resolved by the top level of get(). 3445e3bd972SChris Lattner SrcDefinitionsToResolve.push_back(STy); 3455e3bd972SChris Lattner StructType *DTy = StructType::create(STy->getContext()); 346aa9918aaSRafael Espindola // A new identified structure type was created. Add it to the set of 347aa9918aaSRafael Espindola // identified structs in the destination module. 348aa9918aaSRafael Espindola DstStructTypesSet.insert(DTy); 3495e3bd972SChris Lattner DstResolvedOpaqueTypes.insert(DTy); 3505e3bd972SChris Lattner return *Entry = DTy; 351b1ed91f3SChris Lattner } 352b1ed91f3SChris Lattner 353b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 354b1ed91f3SChris Lattner // ModuleLinker implementation. 355b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 356b1ed91f3SChris Lattner 357b1ed91f3SChris Lattner namespace { 358f6f121e2SJames Molloy class ModuleLinker; 359f6f121e2SJames Molloy 36018c89411SRafael Espindola /// Creates prototypes for functions that are lazily linked on the fly. This 36118c89411SRafael Espindola /// speeds up linking for modules with many/ lazily linked functions of which 36218c89411SRafael Espindola /// few get used. 363f6f121e2SJames Molloy class ValueMaterializerTy : public ValueMaterializer { 364f6f121e2SJames Molloy TypeMapTy &TypeMap; 365f6f121e2SJames Molloy Module *DstM; 366f6f121e2SJames Molloy std::vector<Function*> &LazilyLinkFunctions; 367f6f121e2SJames Molloy public: 368f6f121e2SJames Molloy ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM, 369f6f121e2SJames Molloy std::vector<Function*> &LazilyLinkFunctions) : 370f6f121e2SJames Molloy ValueMaterializer(), TypeMap(TypeMap), DstM(DstM), 371f6f121e2SJames Molloy LazilyLinkFunctions(LazilyLinkFunctions) { 372f6f121e2SJames Molloy } 373f6f121e2SJames Molloy 3748548299aSCraig Topper Value *materializeValueFor(Value *V) override; 375f6f121e2SJames Molloy }; 376f6f121e2SJames Molloy 377d12b4a33SRafael Espindola namespace { 378d12b4a33SRafael Espindola class LinkDiagnosticInfo : public DiagnosticInfo { 379d12b4a33SRafael Espindola const Twine &Msg; 380d12b4a33SRafael Espindola 381d12b4a33SRafael Espindola public: 382d12b4a33SRafael Espindola LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg); 383d12b4a33SRafael Espindola void print(DiagnosticPrinter &DP) const override; 384d12b4a33SRafael Espindola }; 385d12b4a33SRafael Espindola LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity, 386d12b4a33SRafael Espindola const Twine &Msg) 387d12b4a33SRafael Espindola : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {} 388d12b4a33SRafael Espindola void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; } 389d12b4a33SRafael Espindola } 390d12b4a33SRafael Espindola 39118c89411SRafael Espindola /// This is an implementation class for the LinkModules function, which is the 39218c89411SRafael Espindola /// entrypoint for this file. 393b1ed91f3SChris Lattner class ModuleLinker { 394b1ed91f3SChris Lattner Module *DstM, *SrcM; 395b1ed91f3SChris Lattner 396b1ed91f3SChris Lattner TypeMapTy TypeMap; 397f6f121e2SJames Molloy ValueMaterializerTy ValMaterializer; 398b1ed91f3SChris Lattner 39918c89411SRafael Espindola /// Mapping of values from what they used to be in Src, to what they are now 40018c89411SRafael Espindola /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead 40118c89411SRafael Espindola /// due to the use of Value handles which the Linker doesn't actually need, 40218c89411SRafael Espindola /// but this allows us to reuse the ValueMapper code. 403b1ed91f3SChris Lattner ValueToValueMapTy ValueMap; 404b1ed91f3SChris Lattner 405b1ed91f3SChris Lattner struct AppendingVarInfo { 406b1ed91f3SChris Lattner GlobalVariable *NewGV; // New aggregate global in dest module. 4073e8bc6a8SRafael Espindola const Constant *DstInit; // Old initializer from dest module. 4083e8bc6a8SRafael Espindola const Constant *SrcInit; // Old initializer from src module. 409b1ed91f3SChris Lattner }; 410b1ed91f3SChris Lattner 411b1ed91f3SChris Lattner std::vector<AppendingVarInfo> AppendingVars; 412b1ed91f3SChris Lattner 413cbb91408STanya Lattner // Set of items not to link in from source. 414cbb91408STanya Lattner SmallPtrSet<const Value*, 16> DoNotLinkFromSource; 415cbb91408STanya Lattner 4160a48b877STanya Lattner // Vector of functions to lazily link in. 417fa228782SBill Wendling std::vector<Function*> LazilyLinkFunctions; 4180a48b877STanya Lattner 4194160f5d3SRafael Espindola Linker::DiagnosticHandlerFunction DiagnosticHandler; 4204160f5d3SRafael Espindola 421b1ed91f3SChris Lattner public: 4229f8eff31SRafael Espindola ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, 4234160f5d3SRafael Espindola Linker::DiagnosticHandlerFunction DiagnosticHandler) 424f6f121e2SJames Molloy : DstM(dstM), SrcM(srcM), TypeMap(Set), 4259f8eff31SRafael Espindola ValMaterializer(TypeMap, DstM, LazilyLinkFunctions), 4264160f5d3SRafael Espindola DiagnosticHandler(DiagnosticHandler) {} 427b1ed91f3SChris Lattner 428b1ed91f3SChris Lattner bool run(); 429b1ed91f3SChris Lattner 430b1ed91f3SChris Lattner private: 431d12b4a33SRafael Espindola bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest, 432d12b4a33SRafael Espindola const GlobalValue &Src); 433dbb0bd1aSRafael Espindola 434d12b4a33SRafael Espindola /// Helper method for setting a message and returning an error code. 435b1ed91f3SChris Lattner bool emitError(const Twine &Message) { 4364160f5d3SRafael Espindola DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message)); 437b1ed91f3SChris Lattner return true; 438b1ed91f3SChris Lattner } 439b1ed91f3SChris Lattner 440d12b4a33SRafael Espindola void emitWarning(const Twine &Message) { 4414160f5d3SRafael Espindola DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message)); 442d12b4a33SRafael Espindola } 443d12b4a33SRafael Espindola 444dad0a645SDavid Majnemer bool getComdatLeader(Module *M, StringRef ComdatName, 445dad0a645SDavid Majnemer const GlobalVariable *&GVar); 446dad0a645SDavid Majnemer bool computeResultingSelectionKind(StringRef ComdatName, 447dad0a645SDavid Majnemer Comdat::SelectionKind Src, 448dad0a645SDavid Majnemer Comdat::SelectionKind Dst, 449dad0a645SDavid Majnemer Comdat::SelectionKind &Result, 450dad0a645SDavid Majnemer bool &LinkFromSrc); 451dad0a645SDavid Majnemer std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>> 452dad0a645SDavid Majnemer ComdatsChosen; 453dad0a645SDavid Majnemer bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK, 454dad0a645SDavid Majnemer bool &LinkFromSrc); 455dad0a645SDavid Majnemer 45618c89411SRafael Espindola /// Given a global in the source module, return the global in the 45718c89411SRafael Espindola /// destination module that is being linked to, if any. 4583e8bc6a8SRafael Espindola GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) { 459b1ed91f3SChris Lattner // If the source has no name it can't link. If it has local linkage, 460b1ed91f3SChris Lattner // there is no name match-up going on. 461b1ed91f3SChris Lattner if (!SrcGV->hasName() || SrcGV->hasLocalLinkage()) 4622617dcceSCraig Topper return nullptr; 463b1ed91f3SChris Lattner 464b1ed91f3SChris Lattner // Otherwise see if we have a match in the destination module's symtab. 465b1ed91f3SChris Lattner GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName()); 4662617dcceSCraig Topper if (!DGV) return nullptr; 467b1ed91f3SChris Lattner 468b1ed91f3SChris Lattner // If we found a global with the same name in the dest module, but it has 469b1ed91f3SChris Lattner // internal linkage, we are really not doing any linkage here. 470b1ed91f3SChris Lattner if (DGV->hasLocalLinkage()) 4712617dcceSCraig Topper return nullptr; 472b1ed91f3SChris Lattner 473b1ed91f3SChris Lattner // Otherwise, we do in fact link to the destination global. 474b1ed91f3SChris Lattner return DGV; 475b1ed91f3SChris Lattner } 476b1ed91f3SChris Lattner 477b1ed91f3SChris Lattner void computeTypeMapping(); 478b1ed91f3SChris Lattner 47909d84addSDuncan P. N. Exon Smith void upgradeMismatchedGlobalArray(StringRef Name); 48009d84addSDuncan P. N. Exon Smith void upgradeMismatchedGlobals(); 48109d84addSDuncan P. N. Exon Smith 4823e8bc6a8SRafael Espindola bool linkAppendingVarProto(GlobalVariable *DstGV, 4833e8bc6a8SRafael Espindola const GlobalVariable *SrcGV); 484778fcc77SRafael Espindola 485778fcc77SRafael Espindola bool linkGlobalValueProto(GlobalValue *GV); 486778fcc77SRafael Espindola GlobalValue *linkGlobalVariableProto(const GlobalVariable *SGVar, 487778fcc77SRafael Espindola GlobalValue *DGV, bool LinkFromSrc); 488778fcc77SRafael Espindola GlobalValue *linkFunctionProto(const Function *SF, GlobalValue *DGV, 489778fcc77SRafael Espindola bool LinkFromSrc); 490778fcc77SRafael Espindola GlobalValue *linkGlobalAliasProto(const GlobalAlias *SGA, GlobalValue *DGV, 491778fcc77SRafael Espindola bool LinkFromSrc); 492778fcc77SRafael Espindola 49366f02413SBill Wendling bool linkModuleFlagsMetadata(); 494b1ed91f3SChris Lattner 495b1ed91f3SChris Lattner void linkAppendingVarInit(const AppendingVarInfo &AVI); 496b1ed91f3SChris Lattner void linkGlobalInits(); 497b1ed91f3SChris Lattner void linkFunctionBody(Function *Dst, Function *Src); 498b1ed91f3SChris Lattner void linkAliasBodies(); 499b1ed91f3SChris Lattner void linkNamedMDNodes(); 500eee6f995SChris Lattner }; 501d48b7783SBill Wendling } 502d48b7783SBill Wendling 50318c89411SRafael Espindola /// The LLVM SymbolTable class autorenames globals that conflict in the symbol 50418c89411SRafael Espindola /// table. This is good for all clients except for us. Go through the trouble 50518c89411SRafael Espindola /// to force this back. 506b1ed91f3SChris Lattner static void forceRenaming(GlobalValue *GV, StringRef Name) { 507b1ed91f3SChris Lattner // If the global doesn't force its name or if it already has the right name, 508b1ed91f3SChris Lattner // there is nothing for us to do. 509b1ed91f3SChris Lattner if (GV->hasLocalLinkage() || GV->getName() == Name) 510b1ed91f3SChris Lattner return; 511b1ed91f3SChris Lattner 512b1ed91f3SChris Lattner Module *M = GV->getParent(); 513361e513dSReid Spencer 514361e513dSReid Spencer // If there is a conflict, rename the conflict. 515b1ed91f3SChris Lattner if (GlobalValue *ConflictGV = M->getNamedValue(Name)) { 5162a8d2e0eSChris Lattner GV->takeName(ConflictGV); 517361e513dSReid Spencer ConflictGV->setName(Name); // This will cause ConflictGV to get renamed 518b1ed91f3SChris Lattner assert(ConflictGV->getName() != Name && "forceRenaming didn't work"); 5192a8d2e0eSChris Lattner } else { 5202a8d2e0eSChris Lattner GV->setName(Name); // Force the name back 5213aaaa0b2SReid Spencer } 5223aaaa0b2SReid Spencer } 5233aaaa0b2SReid Spencer 52418c89411SRafael Espindola /// copy additional attributes (those not needed to construct a GlobalValue) 52518c89411SRafael Espindola /// from the SrcGV to the DestGV. 526b6af2f36SBill Wendling static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) { 527dd7daee8SDuncan Sands // Use the maximum alignment, rather than just copying the alignment of SrcGV. 52899e05cf1SRafael Espindola auto *DestGO = dyn_cast<GlobalObject>(DestGV); 529a7d9c69cSRafael Espindola unsigned Alignment; 53099e05cf1SRafael Espindola if (DestGO) 53199e05cf1SRafael Espindola Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment()); 532a7d9c69cSRafael Espindola 533dd7daee8SDuncan Sands DestGV->copyAttributesFrom(SrcGV); 534a7d9c69cSRafael Espindola 53599e05cf1SRafael Espindola if (DestGO) 53699e05cf1SRafael Espindola DestGO->setAlignment(Alignment); 537b1ed91f3SChris Lattner 538b1ed91f3SChris Lattner forceRenaming(DestGV, SrcGV->getName()); 539361e513dSReid Spencer } 540361e513dSReid Spencer 54123f8d64bSRafael Espindola static bool isLessConstraining(GlobalValue::VisibilityTypes a, 54223f8d64bSRafael Espindola GlobalValue::VisibilityTypes b) { 54323f8d64bSRafael Espindola if (a == GlobalValue::HiddenVisibility) 54423f8d64bSRafael Espindola return false; 54523f8d64bSRafael Espindola if (b == GlobalValue::HiddenVisibility) 54623f8d64bSRafael Espindola return true; 54723f8d64bSRafael Espindola if (a == GlobalValue::ProtectedVisibility) 54823f8d64bSRafael Espindola return false; 54923f8d64bSRafael Espindola if (b == GlobalValue::ProtectedVisibility) 55023f8d64bSRafael Espindola return true; 55123f8d64bSRafael Espindola return false; 55223f8d64bSRafael Espindola } 55323f8d64bSRafael Espindola 554f6f121e2SJames Molloy Value *ValueMaterializerTy::materializeValueFor(Value *V) { 555f6f121e2SJames Molloy Function *SF = dyn_cast<Function>(V); 556f6f121e2SJames Molloy if (!SF) 5572617dcceSCraig Topper return nullptr; 558f6f121e2SJames Molloy 559f6f121e2SJames Molloy Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()), 560f6f121e2SJames Molloy SF->getLinkage(), SF->getName(), DstM); 561f6f121e2SJames Molloy copyGVAttributes(DF, SF); 562f6f121e2SJames Molloy 5633931c28bSRafael Espindola if (Comdat *SC = SF->getComdat()) { 5643931c28bSRafael Espindola Comdat *DC = DstM->getOrInsertComdat(SC->getName()); 5653931c28bSRafael Espindola DF->setComdat(DC); 5663931c28bSRafael Espindola } 5673931c28bSRafael Espindola 568f6f121e2SJames Molloy LazilyLinkFunctions.push_back(SF); 569f6f121e2SJames Molloy return DF; 570f6f121e2SJames Molloy } 571f6f121e2SJames Molloy 572dad0a645SDavid Majnemer bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName, 573dad0a645SDavid Majnemer const GlobalVariable *&GVar) { 574dad0a645SDavid Majnemer const GlobalValue *GVal = M->getNamedValue(ComdatName); 575dad0a645SDavid Majnemer if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) { 576dad0a645SDavid Majnemer GVal = GA->getBaseObject(); 577dad0a645SDavid Majnemer if (!GVal) 578dad0a645SDavid Majnemer // We cannot resolve the size of the aliasee yet. 579dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 580dad0a645SDavid Majnemer "': COMDAT key involves incomputable alias size."); 581dad0a645SDavid Majnemer } 582dad0a645SDavid Majnemer 583dad0a645SDavid Majnemer GVar = dyn_cast_or_null<GlobalVariable>(GVal); 584dad0a645SDavid Majnemer if (!GVar) 585dad0a645SDavid Majnemer return emitError( 586dad0a645SDavid Majnemer "Linking COMDATs named '" + ComdatName + 587dad0a645SDavid Majnemer "': GlobalVariable required for data dependent selection!"); 588dad0a645SDavid Majnemer 589dad0a645SDavid Majnemer return false; 590dad0a645SDavid Majnemer } 591dad0a645SDavid Majnemer 592dad0a645SDavid Majnemer bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName, 593dad0a645SDavid Majnemer Comdat::SelectionKind Src, 594dad0a645SDavid Majnemer Comdat::SelectionKind Dst, 595dad0a645SDavid Majnemer Comdat::SelectionKind &Result, 596dad0a645SDavid Majnemer bool &LinkFromSrc) { 597dad0a645SDavid Majnemer // The ability to mix Comdat::SelectionKind::Any with 598dad0a645SDavid Majnemer // Comdat::SelectionKind::Largest is a behavior that comes from COFF. 599dad0a645SDavid Majnemer bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any || 600dad0a645SDavid Majnemer Dst == Comdat::SelectionKind::Largest; 601dad0a645SDavid Majnemer bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any || 602dad0a645SDavid Majnemer Src == Comdat::SelectionKind::Largest; 603dad0a645SDavid Majnemer if (DstAnyOrLargest && SrcAnyOrLargest) { 604dad0a645SDavid Majnemer if (Dst == Comdat::SelectionKind::Largest || 605dad0a645SDavid Majnemer Src == Comdat::SelectionKind::Largest) 606dad0a645SDavid Majnemer Result = Comdat::SelectionKind::Largest; 607dad0a645SDavid Majnemer else 608dad0a645SDavid Majnemer Result = Comdat::SelectionKind::Any; 609dad0a645SDavid Majnemer } else if (Src == Dst) { 610dad0a645SDavid Majnemer Result = Dst; 611dad0a645SDavid Majnemer } else { 612dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 613dad0a645SDavid Majnemer "': invalid selection kinds!"); 614dad0a645SDavid Majnemer } 615dad0a645SDavid Majnemer 616dad0a645SDavid Majnemer switch (Result) { 617dad0a645SDavid Majnemer case Comdat::SelectionKind::Any: 618dad0a645SDavid Majnemer // Go with Dst. 619dad0a645SDavid Majnemer LinkFromSrc = false; 620dad0a645SDavid Majnemer break; 621dad0a645SDavid Majnemer case Comdat::SelectionKind::NoDuplicates: 622dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 623dad0a645SDavid Majnemer "': noduplicates has been violated!"); 624dad0a645SDavid Majnemer case Comdat::SelectionKind::ExactMatch: 625dad0a645SDavid Majnemer case Comdat::SelectionKind::Largest: 626dad0a645SDavid Majnemer case Comdat::SelectionKind::SameSize: { 627dad0a645SDavid Majnemer const GlobalVariable *DstGV; 628dad0a645SDavid Majnemer const GlobalVariable *SrcGV; 629dad0a645SDavid Majnemer if (getComdatLeader(DstM, ComdatName, DstGV) || 630dad0a645SDavid Majnemer getComdatLeader(SrcM, ComdatName, SrcGV)) 631dad0a645SDavid Majnemer return true; 632dad0a645SDavid Majnemer 633dad0a645SDavid Majnemer const DataLayout *DstDL = DstM->getDataLayout(); 634dad0a645SDavid Majnemer const DataLayout *SrcDL = SrcM->getDataLayout(); 635dad0a645SDavid Majnemer if (!DstDL || !SrcDL) { 636dad0a645SDavid Majnemer return emitError( 637dad0a645SDavid Majnemer "Linking COMDATs named '" + ComdatName + 638dad0a645SDavid Majnemer "': can't do size dependent selection without DataLayout!"); 639dad0a645SDavid Majnemer } 640dad0a645SDavid Majnemer uint64_t DstSize = 641dad0a645SDavid Majnemer DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType()); 642dad0a645SDavid Majnemer uint64_t SrcSize = 643dad0a645SDavid Majnemer SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType()); 644dad0a645SDavid Majnemer if (Result == Comdat::SelectionKind::ExactMatch) { 645dad0a645SDavid Majnemer if (SrcGV->getInitializer() != DstGV->getInitializer()) 646dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 647dad0a645SDavid Majnemer "': ExactMatch violated!"); 648dad0a645SDavid Majnemer LinkFromSrc = false; 649dad0a645SDavid Majnemer } else if (Result == Comdat::SelectionKind::Largest) { 650dad0a645SDavid Majnemer LinkFromSrc = SrcSize > DstSize; 651dad0a645SDavid Majnemer } else if (Result == Comdat::SelectionKind::SameSize) { 652dad0a645SDavid Majnemer if (SrcSize != DstSize) 653dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 654dad0a645SDavid Majnemer "': SameSize violated!"); 655dad0a645SDavid Majnemer LinkFromSrc = false; 656dad0a645SDavid Majnemer } else { 657dad0a645SDavid Majnemer llvm_unreachable("unknown selection kind"); 658dad0a645SDavid Majnemer } 659dad0a645SDavid Majnemer break; 660dad0a645SDavid Majnemer } 661dad0a645SDavid Majnemer } 662dad0a645SDavid Majnemer 663dad0a645SDavid Majnemer return false; 664dad0a645SDavid Majnemer } 665dad0a645SDavid Majnemer 666dad0a645SDavid Majnemer bool ModuleLinker::getComdatResult(const Comdat *SrcC, 667dad0a645SDavid Majnemer Comdat::SelectionKind &Result, 668dad0a645SDavid Majnemer bool &LinkFromSrc) { 669b16196a3SRafael Espindola Comdat::SelectionKind SSK = SrcC->getSelectionKind(); 670dad0a645SDavid Majnemer StringRef ComdatName = SrcC->getName(); 671dad0a645SDavid Majnemer Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable(); 672dad0a645SDavid Majnemer Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName); 6732ef3f299SRafael Espindola 674b16196a3SRafael Espindola if (DstCI == ComdatSymTab.end()) { 675b16196a3SRafael Espindola // Use the comdat if it is only available in one of the modules. 676b16196a3SRafael Espindola LinkFromSrc = true; 677b16196a3SRafael Espindola Result = SSK; 6782ef3f299SRafael Espindola return false; 679b16196a3SRafael Espindola } 6802ef3f299SRafael Espindola 681dad0a645SDavid Majnemer const Comdat *DstC = &DstCI->second; 682dad0a645SDavid Majnemer Comdat::SelectionKind DSK = DstC->getSelectionKind(); 6832ef3f299SRafael Espindola return computeResultingSelectionKind(ComdatName, SSK, DSK, Result, 6842ef3f299SRafael Espindola LinkFromSrc); 685dad0a645SDavid Majnemer } 686f6f121e2SJames Molloy 687d12b4a33SRafael Espindola bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc, 688d12b4a33SRafael Espindola const GlobalValue &Dest, 689dbb0bd1aSRafael Espindola const GlobalValue &Src) { 690778fcc77SRafael Espindola // We always have to add Src if it has appending linkage. 691778fcc77SRafael Espindola if (Src.hasAppendingLinkage()) { 692778fcc77SRafael Espindola LinkFromSrc = true; 693778fcc77SRafael Espindola return false; 694778fcc77SRafael Espindola } 695778fcc77SRafael Espindola 696d4bcefc7SRafael Espindola bool SrcIsDeclaration = Src.isDeclarationForLinker(); 697d4bcefc7SRafael Espindola bool DestIsDeclaration = Dest.isDeclarationForLinker(); 698dbb0bd1aSRafael Espindola 699dbb0bd1aSRafael Espindola if (SrcIsDeclaration) { 700dbb0bd1aSRafael Espindola // If Src is external or if both Src & Dest are external.. Just link the 701dbb0bd1aSRafael Espindola // external globals, we aren't adding anything. 702d12b4a33SRafael Espindola if (Src.hasDLLImportStorageClass()) { 703dbb0bd1aSRafael Espindola // If one of GVs is marked as DLLImport, result should be dllimport'ed. 704d12b4a33SRafael Espindola LinkFromSrc = DestIsDeclaration; 705d12b4a33SRafael Espindola return false; 706d12b4a33SRafael Espindola } 707dbb0bd1aSRafael Espindola // If the Dest is weak, use the source linkage. 708d12b4a33SRafael Espindola LinkFromSrc = Dest.hasExternalWeakLinkage(); 709d12b4a33SRafael Espindola return false; 710dbb0bd1aSRafael Espindola } 711dbb0bd1aSRafael Espindola 712d12b4a33SRafael Espindola if (DestIsDeclaration) { 713dbb0bd1aSRafael Espindola // If Dest is external but Src is not: 714d12b4a33SRafael Espindola LinkFromSrc = true; 715d12b4a33SRafael Espindola return false; 716d12b4a33SRafael Espindola } 717dbb0bd1aSRafael Espindola 7180910605aSRafael Espindola if (Src.hasCommonLinkage()) { 719d12b4a33SRafael Espindola if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) { 720d12b4a33SRafael Espindola LinkFromSrc = true; 7210910605aSRafael Espindola return false; 722d12b4a33SRafael Espindola } 723d12b4a33SRafael Espindola 724d12b4a33SRafael Espindola if (!Dest.hasCommonLinkage()) { 725d12b4a33SRafael Espindola LinkFromSrc = false; 726d12b4a33SRafael Espindola return false; 727d12b4a33SRafael Espindola } 7280910605aSRafael Espindola 7290ae225b6SRafael Espindola // FIXME: Make datalayout mandatory and just use getDataLayout(). 7300ae225b6SRafael Espindola DataLayout DL(Dest.getParent()); 7310ae225b6SRafael Espindola 7320910605aSRafael Espindola uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType()); 7330910605aSRafael Espindola uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType()); 734d12b4a33SRafael Espindola LinkFromSrc = SrcSize > DestSize; 735d12b4a33SRafael Espindola return false; 7360910605aSRafael Espindola } 7370910605aSRafael Espindola 738dbb0bd1aSRafael Espindola if (Src.isWeakForLinker()) { 739dbb0bd1aSRafael Espindola assert(!Dest.hasExternalWeakLinkage()); 740dbb0bd1aSRafael Espindola assert(!Dest.hasAvailableExternallyLinkage()); 7410910605aSRafael Espindola 742d12b4a33SRafael Espindola if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) { 743d12b4a33SRafael Espindola LinkFromSrc = true; 744d12b4a33SRafael Espindola return false; 745d12b4a33SRafael Espindola } 746dbb0bd1aSRafael Espindola 747d12b4a33SRafael Espindola LinkFromSrc = false; 7480910605aSRafael Espindola return false; 749dbb0bd1aSRafael Espindola } 750dbb0bd1aSRafael Espindola 751dbb0bd1aSRafael Espindola if (Dest.isWeakForLinker()) { 752dbb0bd1aSRafael Espindola assert(Src.hasExternalLinkage()); 753d12b4a33SRafael Espindola LinkFromSrc = true; 754d12b4a33SRafael Espindola return false; 755dbb0bd1aSRafael Espindola } 756dbb0bd1aSRafael Espindola 757dbb0bd1aSRafael Espindola assert(!Src.hasExternalWeakLinkage()); 758dbb0bd1aSRafael Espindola assert(!Dest.hasExternalWeakLinkage()); 759dbb0bd1aSRafael Espindola assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() && 760dbb0bd1aSRafael Espindola "Unexpected linkage type!"); 761dbb0bd1aSRafael Espindola return emitError("Linking globals named '" + Src.getName() + 762dbb0bd1aSRafael Espindola "': symbol multiply defined!"); 763dbb0bd1aSRafael Espindola } 764dbb0bd1aSRafael Espindola 76518c89411SRafael Espindola /// Loop over all of the linked values to compute type mappings. For example, 76618c89411SRafael Espindola /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct 76718c89411SRafael Espindola /// types 'Foo' but one got renamed when the module was loaded into the same 76818c89411SRafael Espindola /// LLVMContext. 769b1ed91f3SChris Lattner void ModuleLinker::computeTypeMapping() { 770*c8a476eeSRafael Espindola for (GlobalValue &SGV : SrcM->globals()) { 771*c8a476eeSRafael Espindola GlobalValue *DGV = getLinkedToGlobal(&SGV); 772*c8a476eeSRafael Espindola if (!DGV) 773*c8a476eeSRafael Espindola continue; 774b1ed91f3SChris Lattner 775*c8a476eeSRafael Espindola if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) { 776*c8a476eeSRafael Espindola TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); 777b1ed91f3SChris Lattner continue; 7785c310be0SDevang Patel } 7795c310be0SDevang Patel 780b1ed91f3SChris Lattner // Unify the element type of appending arrays. 781b1ed91f3SChris Lattner ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType()); 782*c8a476eeSRafael Espindola ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType()); 783b1ed91f3SChris Lattner TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType()); 784b1ed91f3SChris Lattner } 78534fc5a0eSChris Lattner 786*c8a476eeSRafael Espindola for (GlobalValue &SGV : *SrcM) { 787*c8a476eeSRafael Espindola if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) 788*c8a476eeSRafael Espindola TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); 789b1ed91f3SChris Lattner } 790e79f4c77SAnton Korobeynikov 791d48b7783SBill Wendling // Incorporate types by name, scanning all the types in the source module. 792d48b7783SBill Wendling // At this point, the destination module may have a type "%foo = { i32 }" for 7932b3f61afSBill Wendling // example. When the source module got loaded into the same LLVMContext, if 7942b3f61afSBill Wendling // it had the same type, it would have been renamed to "%foo.42 = { i32 }". 7958555a37cSBill Wendling TypeFinder SrcStructTypes; 7968555a37cSBill Wendling SrcStructTypes.run(*SrcM, true); 7972b3f61afSBill Wendling SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(), 7982b3f61afSBill Wendling SrcStructTypes.end()); 7992b3f61afSBill Wendling 8002b3f61afSBill Wendling for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) { 8012b3f61afSBill Wendling StructType *ST = SrcStructTypes[i]; 8022b3f61afSBill Wendling if (!ST->hasName()) continue; 8032b3f61afSBill Wendling 8042b3f61afSBill Wendling // Check to see if there is a dot in the name followed by a digit. 805d48b7783SBill Wendling size_t DotPos = ST->getName().rfind('.'); 806d48b7783SBill Wendling if (DotPos == 0 || DotPos == StringRef::npos || 80783c74e9fSGuy Benyei ST->getName().back() == '.' || 80883c74e9fSGuy Benyei !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1]))) 809d48b7783SBill Wendling continue; 8102b3f61afSBill Wendling 8112b3f61afSBill Wendling // Check to see if the destination module has a struct with the prefix name. 812d48b7783SBill Wendling if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos))) 8132b3f61afSBill Wendling // Don't use it if this actually came from the source module. They're in 8148737480dSBill Wendling // the same LLVMContext after all. Also don't use it unless the type is 8158737480dSBill Wendling // actually used in the destination module. This can happen in situations 8168737480dSBill Wendling // like this: 8178737480dSBill Wendling // 8188737480dSBill Wendling // Module A Module B 8198737480dSBill Wendling // -------- -------- 8208737480dSBill Wendling // %Z = type { %A } %B = type { %C.1 } 8218737480dSBill Wendling // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* } 8228737480dSBill Wendling // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] } 8238737480dSBill Wendling // %C = type { i8* } %B.3 = type { %C.1 } 8248737480dSBill Wendling // 8258737480dSBill Wendling // When we link Module B with Module A, the '%B' in Module B is 8268737480dSBill Wendling // used. However, that would then use '%C.1'. But when we process '%C.1', 8278737480dSBill Wendling // we prefer to take the '%C' version. So we are then left with both 8288737480dSBill Wendling // '%C.1' and '%C' being used for the same types. This leads to some 8298737480dSBill Wendling // variables using one type and some using the other. 830aa9918aaSRafael Espindola if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST)) 8312b3f61afSBill Wendling TypeMap.addTypeMapping(DST, ST); 8322b3f61afSBill Wendling } 8332b3f61afSBill Wendling 834b1ed91f3SChris Lattner // Don't bother incorporating aliases, they aren't generally typed well. 835361e513dSReid Spencer 836b1ed91f3SChris Lattner // Now that we have discovered all of the type equivalences, get a body for 837b1ed91f3SChris Lattner // any 'opaque' types in the dest module that are now resolved. 838b1ed91f3SChris Lattner TypeMap.linkDefinedTypeBodies(); 839b1ed91f3SChris Lattner } 840c08e7a00SChris Lattner 84109d84addSDuncan P. N. Exon Smith static void upgradeGlobalArray(GlobalVariable *GV) { 84209d84addSDuncan P. N. Exon Smith ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType()); 84309d84addSDuncan P. N. Exon Smith StructType *OldTy = cast<StructType>(ATy->getElementType()); 84409d84addSDuncan P. N. Exon Smith assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements"); 84509d84addSDuncan P. N. Exon Smith 84609d84addSDuncan P. N. Exon Smith // Get the upgraded 3 element type. 84709d84addSDuncan P. N. Exon Smith PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo(); 84809d84addSDuncan P. N. Exon Smith Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1), 84909d84addSDuncan P. N. Exon Smith VoidPtrTy}; 85009d84addSDuncan P. N. Exon Smith StructType *NewTy = StructType::get(GV->getContext(), Tys, false); 85109d84addSDuncan P. N. Exon Smith 85209d84addSDuncan P. N. Exon Smith // Build new constants with a null third field filled in. 85309d84addSDuncan P. N. Exon Smith Constant *OldInitC = GV->getInitializer(); 85409d84addSDuncan P. N. Exon Smith ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC); 85509d84addSDuncan P. N. Exon Smith if (!OldInit && !isa<ConstantAggregateZero>(OldInitC)) 85609d84addSDuncan P. N. Exon Smith // Invalid initializer; give up. 85709d84addSDuncan P. N. Exon Smith return; 85809d84addSDuncan P. N. Exon Smith std::vector<Constant *> Initializers; 85909d84addSDuncan P. N. Exon Smith if (OldInit && OldInit->getNumOperands()) { 86009d84addSDuncan P. N. Exon Smith Value *Null = Constant::getNullValue(VoidPtrTy); 86109d84addSDuncan P. N. Exon Smith for (Use &U : OldInit->operands()) { 86209d84addSDuncan P. N. Exon Smith ConstantStruct *Init = cast<ConstantStruct>(U.get()); 86309d84addSDuncan P. N. Exon Smith Initializers.push_back(ConstantStruct::get( 86409d84addSDuncan P. N. Exon Smith NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr)); 86509d84addSDuncan P. N. Exon Smith } 86609d84addSDuncan P. N. Exon Smith } 86709d84addSDuncan P. N. Exon Smith assert(Initializers.size() == ATy->getNumElements() && 86809d84addSDuncan P. N. Exon Smith "Failed to copy all array elements"); 86909d84addSDuncan P. N. Exon Smith 87009d84addSDuncan P. N. Exon Smith // Replace the old GV with a new one. 87109d84addSDuncan P. N. Exon Smith ATy = ArrayType::get(NewTy, Initializers.size()); 87209d84addSDuncan P. N. Exon Smith Constant *NewInit = ConstantArray::get(ATy, Initializers); 87309d84addSDuncan P. N. Exon Smith GlobalVariable *NewGV = new GlobalVariable( 87409d84addSDuncan P. N. Exon Smith *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "", 87509d84addSDuncan P. N. Exon Smith GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(), 87609d84addSDuncan P. N. Exon Smith GV->isExternallyInitialized()); 87709d84addSDuncan P. N. Exon Smith NewGV->copyAttributesFrom(GV); 87809d84addSDuncan P. N. Exon Smith NewGV->takeName(GV); 87909d84addSDuncan P. N. Exon Smith assert(GV->use_empty() && "program cannot use initializer list"); 88009d84addSDuncan P. N. Exon Smith GV->eraseFromParent(); 88109d84addSDuncan P. N. Exon Smith } 88209d84addSDuncan P. N. Exon Smith 88309d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) { 88409d84addSDuncan P. N. Exon Smith // Look for the global arrays. 88509d84addSDuncan P. N. Exon Smith auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name)); 88609d84addSDuncan P. N. Exon Smith if (!DstGV) 88709d84addSDuncan P. N. Exon Smith return; 88809d84addSDuncan P. N. Exon Smith auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name)); 88909d84addSDuncan P. N. Exon Smith if (!SrcGV) 89009d84addSDuncan P. N. Exon Smith return; 89109d84addSDuncan P. N. Exon Smith 89209d84addSDuncan P. N. Exon Smith // Check if the types already match. 89309d84addSDuncan P. N. Exon Smith auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType()); 89409d84addSDuncan P. N. Exon Smith auto *SrcTy = 89509d84addSDuncan P. N. Exon Smith cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType())); 89609d84addSDuncan P. N. Exon Smith if (DstTy == SrcTy) 89709d84addSDuncan P. N. Exon Smith return; 89809d84addSDuncan P. N. Exon Smith 89909d84addSDuncan P. N. Exon Smith // Grab the element types. We can only upgrade an array of a two-field 90009d84addSDuncan P. N. Exon Smith // struct. Only bother if the other one has three-fields. 90109d84addSDuncan P. N. Exon Smith auto *DstEltTy = cast<StructType>(DstTy->getElementType()); 90209d84addSDuncan P. N. Exon Smith auto *SrcEltTy = cast<StructType>(SrcTy->getElementType()); 90309d84addSDuncan P. N. Exon Smith if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) { 90409d84addSDuncan P. N. Exon Smith upgradeGlobalArray(DstGV); 90509d84addSDuncan P. N. Exon Smith return; 90609d84addSDuncan P. N. Exon Smith } 90709d84addSDuncan P. N. Exon Smith if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2) 90809d84addSDuncan P. N. Exon Smith upgradeGlobalArray(SrcGV); 90909d84addSDuncan P. N. Exon Smith 91009d84addSDuncan P. N. Exon Smith // We can't upgrade any other differences. 91109d84addSDuncan P. N. Exon Smith } 91209d84addSDuncan P. N. Exon Smith 91309d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobals() { 91409d84addSDuncan P. N. Exon Smith upgradeMismatchedGlobalArray("llvm.global_ctors"); 91509d84addSDuncan P. N. Exon Smith upgradeMismatchedGlobalArray("llvm.global_dtors"); 91609d84addSDuncan P. N. Exon Smith } 91709d84addSDuncan P. N. Exon Smith 91818c89411SRafael Espindola /// If there were any appending global variables, link them together now. 91918c89411SRafael Espindola /// Return true on error. 920b1ed91f3SChris Lattner bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV, 9213e8bc6a8SRafael Espindola const GlobalVariable *SrcGV) { 922d48b7783SBill Wendling 923b1ed91f3SChris Lattner if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) 924b1ed91f3SChris Lattner return emitError("Linking globals named '" + SrcGV->getName() + 925b1ed91f3SChris Lattner "': can only link appending global with another appending global!"); 926361e513dSReid Spencer 927b1ed91f3SChris Lattner ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType()); 928b1ed91f3SChris Lattner ArrayType *SrcTy = 929b1ed91f3SChris Lattner cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType())); 930b1ed91f3SChris Lattner Type *EltTy = DstTy->getElementType(); 931b1ed91f3SChris Lattner 932b1ed91f3SChris Lattner // Check to see that they two arrays agree on type. 933b1ed91f3SChris Lattner if (EltTy != SrcTy->getElementType()) 934b1ed91f3SChris Lattner return emitError("Appending variables with different element types!"); 935b1ed91f3SChris Lattner if (DstGV->isConstant() != SrcGV->isConstant()) 936b1ed91f3SChris Lattner return emitError("Appending variables linked with different const'ness!"); 937b1ed91f3SChris Lattner 938b1ed91f3SChris Lattner if (DstGV->getAlignment() != SrcGV->getAlignment()) 939b1ed91f3SChris Lattner return emitError( 940b1ed91f3SChris Lattner "Appending variables with different alignment need to be linked!"); 941b1ed91f3SChris Lattner 942b1ed91f3SChris Lattner if (DstGV->getVisibility() != SrcGV->getVisibility()) 943b1ed91f3SChris Lattner return emitError( 944b1ed91f3SChris Lattner "Appending variables with different visibility need to be linked!"); 945b1ed91f3SChris Lattner 946fac3a018SRafael Espindola if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) 947fac3a018SRafael Espindola return emitError( 948fac3a018SRafael Espindola "Appending variables with different unnamed_addr need to be linked!"); 949fac3a018SRafael Espindola 95064c1e180SRafael Espindola if (StringRef(DstGV->getSection()) != SrcGV->getSection()) 951b1ed91f3SChris Lattner return emitError( 952b1ed91f3SChris Lattner "Appending variables with different section name need to be linked!"); 953b1ed91f3SChris Lattner 954b1ed91f3SChris Lattner uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements(); 955b1ed91f3SChris Lattner ArrayType *NewType = ArrayType::get(EltTy, NewSize); 956b1ed91f3SChris Lattner 957b1ed91f3SChris Lattner // Create the new global variable. 958b1ed91f3SChris Lattner GlobalVariable *NG = 959b1ed91f3SChris Lattner new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(), 9602617dcceSCraig Topper DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV, 961cbe34b4cSHans Wennborg DstGV->getThreadLocalMode(), 962b1ed91f3SChris Lattner DstGV->getType()->getAddressSpace()); 963b1ed91f3SChris Lattner 964b1ed91f3SChris Lattner // Propagate alignment, visibility and section info. 965b6af2f36SBill Wendling copyGVAttributes(NG, DstGV); 966b1ed91f3SChris Lattner 967b1ed91f3SChris Lattner AppendingVarInfo AVI; 968b1ed91f3SChris Lattner AVI.NewGV = NG; 969b1ed91f3SChris Lattner AVI.DstInit = DstGV->getInitializer(); 970b1ed91f3SChris Lattner AVI.SrcInit = SrcGV->getInitializer(); 971b1ed91f3SChris Lattner AppendingVars.push_back(AVI); 972b1ed91f3SChris Lattner 973b1ed91f3SChris Lattner // Replace any uses of the two global variables with uses of the new 974b1ed91f3SChris Lattner // global. 975b1ed91f3SChris Lattner ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType())); 976b1ed91f3SChris Lattner 977b1ed91f3SChris Lattner DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType())); 978b1ed91f3SChris Lattner DstGV->eraseFromParent(); 979b1ed91f3SChris Lattner 980cbb91408STanya Lattner // Track the source variable so we don't try to link it. 981cbb91408STanya Lattner DoNotLinkFromSource.insert(SrcGV); 982cbb91408STanya Lattner 983b1ed91f3SChris Lattner return false; 984b1ed91f3SChris Lattner } 985b1ed91f3SChris Lattner 986778fcc77SRafael Espindola bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) { 987b1ed91f3SChris Lattner GlobalValue *DGV = getLinkedToGlobal(SGV); 988b1ed91f3SChris Lattner 989778fcc77SRafael Espindola // Handle the ultra special appending linkage case first. 990778fcc77SRafael Espindola if (DGV && DGV->hasAppendingLinkage()) 991778fcc77SRafael Espindola return linkAppendingVarProto(cast<GlobalVariable>(DGV), 992778fcc77SRafael Espindola cast<GlobalVariable>(SGV)); 993778fcc77SRafael Espindola 994778fcc77SRafael Espindola bool LinkFromSrc = true; 995778fcc77SRafael Espindola Comdat *C = nullptr; 996778fcc77SRafael Espindola GlobalValue::VisibilityTypes Visibility = SGV->getVisibility(); 997778fcc77SRafael Espindola bool HasUnnamedAddr = SGV->hasUnnamedAddr(); 998778fcc77SRafael Espindola 999dad0a645SDavid Majnemer if (const Comdat *SC = SGV->getComdat()) { 1000dad0a645SDavid Majnemer Comdat::SelectionKind SK; 1001dad0a645SDavid Majnemer std::tie(SK, LinkFromSrc) = ComdatsChosen[SC]; 1002778fcc77SRafael Espindola C = DstM->getOrInsertComdat(SC->getName()); 1003778fcc77SRafael Espindola C->setSelectionKind(SK); 1004778fcc77SRafael Espindola } else if (DGV) { 1005778fcc77SRafael Espindola if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV)) 1006fc61de39SChris Lattner return true; 1007dad0a645SDavid Majnemer } 100834fc5a0eSChris Lattner 1009dad0a645SDavid Majnemer if (!LinkFromSrc) { 1010cbb91408STanya Lattner // Track the source global so that we don't attempt to copy it over when 1011cbb91408STanya Lattner // processing global initializers. 1012cbb91408STanya Lattner DoNotLinkFromSource.insert(SGV); 1013cbb91408STanya Lattner 1014778fcc77SRafael Espindola if (DGV) 1015778fcc77SRafael Espindola // Make sure to remember this mapping. 1016778fcc77SRafael Espindola ValueMap[SGV] = 1017778fcc77SRafael Espindola ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType())); 1018778fcc77SRafael Espindola } 1019778fcc77SRafael Espindola 1020778fcc77SRafael Espindola if (DGV) { 1021778fcc77SRafael Espindola Visibility = isLessConstraining(Visibility, DGV->getVisibility()) 1022778fcc77SRafael Espindola ? DGV->getVisibility() 1023778fcc77SRafael Espindola : Visibility; 1024778fcc77SRafael Espindola HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr(); 1025778fcc77SRafael Espindola } 1026778fcc77SRafael Espindola 1027778fcc77SRafael Espindola if (!LinkFromSrc && !DGV) 1028dad0a645SDavid Majnemer return false; 1029778fcc77SRafael Espindola 1030778fcc77SRafael Espindola GlobalValue *NewGV; 1031778fcc77SRafael Espindola if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) { 1032778fcc77SRafael Espindola NewGV = linkGlobalVariableProto(SGVar, DGV, LinkFromSrc); 1033778fcc77SRafael Espindola if (!NewGV) 1034778fcc77SRafael Espindola return true; 1035778fcc77SRafael Espindola } else if (auto *SF = dyn_cast<Function>(SGV)) { 1036778fcc77SRafael Espindola NewGV = linkFunctionProto(SF, DGV, LinkFromSrc); 1037778fcc77SRafael Espindola } else { 1038778fcc77SRafael Espindola NewGV = linkGlobalAliasProto(cast<GlobalAlias>(SGV), DGV, LinkFromSrc); 1039778fcc77SRafael Espindola } 1040778fcc77SRafael Espindola 1041778fcc77SRafael Espindola if (NewGV) { 1042778fcc77SRafael Espindola if (NewGV != DGV) 1043778fcc77SRafael Espindola copyGVAttributes(NewGV, SGV); 1044778fcc77SRafael Espindola 1045778fcc77SRafael Espindola NewGV->setUnnamedAddr(HasUnnamedAddr); 1046778fcc77SRafael Espindola NewGV->setVisibility(Visibility); 1047778fcc77SRafael Espindola 1048778fcc77SRafael Espindola if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) { 1049778fcc77SRafael Espindola if (C) 1050778fcc77SRafael Espindola NewGO->setComdat(C); 1051778fcc77SRafael Espindola } 1052778fcc77SRafael Espindola 1053778fcc77SRafael Espindola // Make sure to remember this mapping. 1054778fcc77SRafael Espindola if (NewGV != DGV) { 1055778fcc77SRafael Espindola if (DGV) { 1056778fcc77SRafael Espindola DGV->replaceAllUsesWith( 1057778fcc77SRafael Espindola ConstantExpr::getBitCast(NewGV, DGV->getType())); 1058778fcc77SRafael Espindola DGV->eraseFromParent(); 1059778fcc77SRafael Espindola } 1060778fcc77SRafael Espindola ValueMap[SGV] = NewGV; 1061dad0a645SDavid Majnemer } 10624e27567aSRafael Espindola } 10634e27567aSRafael Espindola 1064fd38af2dSChandler Carruth return false; 10654e27567aSRafael Espindola } 10664e27567aSRafael Espindola 1067778fcc77SRafael Espindola /// Loop through the global variables in the src module and merge them into the 1068778fcc77SRafael Espindola /// dest module. 1069778fcc77SRafael Espindola GlobalValue *ModuleLinker::linkGlobalVariableProto(const GlobalVariable *SGVar, 1070778fcc77SRafael Espindola GlobalValue *DGV, 1071778fcc77SRafael Espindola bool LinkFromSrc) { 1072778fcc77SRafael Espindola unsigned Alignment = 0; 1073778fcc77SRafael Espindola bool ClearConstant = false; 1074778fcc77SRafael Espindola 1075778fcc77SRafael Espindola if (DGV) { 1076778fcc77SRafael Espindola if (DGV->hasCommonLinkage() && SGVar->hasCommonLinkage()) 1077778fcc77SRafael Espindola Alignment = std::max(SGVar->getAlignment(), DGV->getAlignment()); 1078778fcc77SRafael Espindola 1079778fcc77SRafael Espindola auto *DGVar = dyn_cast<GlobalVariable>(DGV); 1080778fcc77SRafael Espindola if (!SGVar->isConstant() || (DGVar && !DGVar->isConstant())) 1081778fcc77SRafael Espindola ClearConstant = true; 1082778fcc77SRafael Espindola } 1083778fcc77SRafael Espindola 1084778fcc77SRafael Espindola if (!LinkFromSrc) { 1085778fcc77SRafael Espindola if (auto *NewGVar = dyn_cast<GlobalVariable>(DGV)) { 1086778fcc77SRafael Espindola if (Alignment) 1087778fcc77SRafael Espindola NewGVar->setAlignment(Alignment); 1088778fcc77SRafael Espindola if (NewGVar->isDeclaration() && ClearConstant) 1089778fcc77SRafael Espindola NewGVar->setConstant(false); 1090778fcc77SRafael Espindola } 1091778fcc77SRafael Espindola return DGV; 1092778fcc77SRafael Espindola } 1093778fcc77SRafael Espindola 1094b1ed91f3SChris Lattner // No linking to be performed or linking from the source: simply create an 1095b1ed91f3SChris Lattner // identical version of the symbol over in the dest module... the 1096b1ed91f3SChris Lattner // initializer will be filled in later by LinkGlobalInits. 1097778fcc77SRafael Espindola GlobalVariable *NewDGV = new GlobalVariable( 1098778fcc77SRafael Espindola *DstM, TypeMap.get(SGVar->getType()->getElementType()), 1099778fcc77SRafael Espindola SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr, 1100778fcc77SRafael Espindola SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(), 1101778fcc77SRafael Espindola SGVar->getType()->getAddressSpace()); 1102778fcc77SRafael Espindola 1103778fcc77SRafael Espindola if (Alignment) 1104fe3842cdSRafael Espindola NewDGV->setAlignment(Alignment); 1105b1ed91f3SChris Lattner 1106778fcc77SRafael Espindola return NewDGV; 1107361e513dSReid Spencer } 1108361e513dSReid Spencer 110918c89411SRafael Espindola /// Link the function in the source module into the destination module if 111018c89411SRafael Espindola /// needed, setting up mapping information. 1111778fcc77SRafael Espindola GlobalValue *ModuleLinker::linkFunctionProto(const Function *SF, 1112778fcc77SRafael Espindola GlobalValue *DGV, 1113778fcc77SRafael Espindola bool LinkFromSrc) { 1114778fcc77SRafael Espindola if (!LinkFromSrc) 1115778fcc77SRafael Espindola return DGV; 1116b1ed91f3SChris Lattner 1117f6f121e2SJames Molloy // If the function is to be lazily linked, don't create it just yet. 1118f6f121e2SJames Molloy // The ValueMaterializerTy will deal with creating it if it's used. 1119f6f121e2SJames Molloy if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() || 1120f6f121e2SJames Molloy SF->hasAvailableExternallyLinkage())) { 1121f6f121e2SJames Molloy DoNotLinkFromSource.insert(SF); 1122778fcc77SRafael Espindola return nullptr; 1123dad0a645SDavid Majnemer } 1124dad0a645SDavid Majnemer 1125b1ed91f3SChris Lattner // If there is no linkage to be performed or we are linking from the source, 1126b1ed91f3SChris Lattner // bring SF over. 1127778fcc77SRafael Espindola return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(), 1128778fcc77SRafael Espindola SF->getName(), DstM); 1129361e513dSReid Spencer } 1130361e513dSReid Spencer 113118c89411SRafael Espindola /// Set up prototypes for any aliases that come over from the source module. 1132778fcc77SRafael Espindola GlobalValue *ModuleLinker::linkGlobalAliasProto(const GlobalAlias *SGA, 1133778fcc77SRafael Espindola GlobalValue *DGV, 1134778fcc77SRafael Espindola bool LinkFromSrc) { 1135778fcc77SRafael Espindola if (!LinkFromSrc) 1136778fcc77SRafael Espindola return DGV; 1137dad0a645SDavid Majnemer 1138b1ed91f3SChris Lattner // If there is no linkage to be performed or we're linking from the source, 1139b1ed91f3SChris Lattner // bring over SGA. 11404fe0094fSRafael Espindola auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType())); 1141778fcc77SRafael Espindola return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(), 114283705658SRafael Espindola SGA->getLinkage(), SGA->getName(), DstM); 1143b1ed91f3SChris Lattner } 1144b1ed91f3SChris Lattner 11453e8bc6a8SRafael Espindola static void getArrayElements(const Constant *C, 11463e8bc6a8SRafael Espindola SmallVectorImpl<Constant *> &Dest) { 11476705883aSChris Lattner unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements(); 114800245f42SChris Lattner 11496705883aSChris Lattner for (unsigned i = 0; i != NumElements; ++i) 11506705883aSChris Lattner Dest.push_back(C->getAggregateElement(i)); 115100245f42SChris Lattner } 115200245f42SChris Lattner 1153b1ed91f3SChris Lattner void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) { 1154b1ed91f3SChris Lattner // Merge the initializer. 1155d31dc048SRafael Espindola SmallVector<Constant *, 16> DstElements; 1156d31dc048SRafael Espindola getArrayElements(AVI.DstInit, DstElements); 1157b1ed91f3SChris Lattner 1158d31dc048SRafael Espindola SmallVector<Constant *, 16> SrcElements; 1159d31dc048SRafael Espindola getArrayElements(AVI.SrcInit, SrcElements); 116000245f42SChris Lattner 1161b1ed91f3SChris Lattner ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType()); 1162d31dc048SRafael Espindola 1163d31dc048SRafael Espindola StringRef Name = AVI.NewGV->getName(); 1164d31dc048SRafael Espindola bool IsNewStructor = 1165d31dc048SRafael Espindola (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") && 1166d31dc048SRafael Espindola cast<StructType>(NewType->getElementType())->getNumElements() == 3; 1167d31dc048SRafael Espindola 1168d31dc048SRafael Espindola for (auto *V : SrcElements) { 1169d31dc048SRafael Espindola if (IsNewStructor) { 1170d31dc048SRafael Espindola Constant *Key = V->getAggregateElement(2); 1171d31dc048SRafael Espindola if (DoNotLinkFromSource.count(Key)) 1172d31dc048SRafael Espindola continue; 1173d31dc048SRafael Espindola } 1174d31dc048SRafael Espindola DstElements.push_back( 1175d31dc048SRafael Espindola MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer)); 1176d31dc048SRafael Espindola } 1177d31dc048SRafael Espindola if (IsNewStructor) { 1178d31dc048SRafael Espindola NewType = ArrayType::get(NewType->getElementType(), DstElements.size()); 1179d31dc048SRafael Espindola AVI.NewGV->mutateType(PointerType::get(NewType, 0)); 1180d31dc048SRafael Espindola } 1181d31dc048SRafael Espindola 1182d31dc048SRafael Espindola AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements)); 1183b1ed91f3SChris Lattner } 1184b1ed91f3SChris Lattner 118518c89411SRafael Espindola /// Update the initializers in the Dest module now that all globals that may be 118618c89411SRafael Espindola /// referenced are in Dest. 1187b1ed91f3SChris Lattner void ModuleLinker::linkGlobalInits() { 1188b1ed91f3SChris Lattner // Loop over all of the globals in the src module, mapping them over as we go 1189b1ed91f3SChris Lattner for (Module::const_global_iterator I = SrcM->global_begin(), 1190b1ed91f3SChris Lattner E = SrcM->global_end(); I != E; ++I) { 1191cbb91408STanya Lattner 1192cbb91408STanya Lattner // Only process initialized GV's or ones not already in dest. 1193cbb91408STanya Lattner if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue; 1194b1ed91f3SChris Lattner 1195b1ed91f3SChris Lattner // Grab destination global variable. 1196b1ed91f3SChris Lattner GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]); 1197b1ed91f3SChris Lattner // Figure out what the initializer looks like in the dest module. 1198b1ed91f3SChris Lattner DGV->setInitializer(MapValue(I->getInitializer(), ValueMap, 1199f6f121e2SJames Molloy RF_None, &TypeMap, &ValMaterializer)); 1200b1ed91f3SChris Lattner } 1201b1ed91f3SChris Lattner } 1202b1ed91f3SChris Lattner 120318c89411SRafael Espindola /// Copy the source function over into the dest function and fix up references 120418c89411SRafael Espindola /// to values. At this point we know that Dest is an external function, and 120518c89411SRafael Espindola /// that Src is not. 1206b1ed91f3SChris Lattner void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) { 1207b1ed91f3SChris Lattner assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration()); 1208361e513dSReid Spencer 12097391dde1SChris Lattner // Go through and convert function arguments over, remembering the mapping. 1210b1ed91f3SChris Lattner Function::arg_iterator DI = Dst->arg_begin(); 1211531f9e92SChris Lattner for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end(); 1212361e513dSReid Spencer I != E; ++I, ++DI) { 1213b1ed91f3SChris Lattner DI->setName(I->getName()); // Copy the name over. 1214361e513dSReid Spencer 1215b1ed91f3SChris Lattner // Add a mapping to our mapping. 121666a6271cSAnton Korobeynikov ValueMap[I] = DI; 1217361e513dSReid Spencer } 1218361e513dSReid Spencer 12192f0557d0SChris Lattner // Splice the body of the source function into the dest function. 1220b1ed91f3SChris Lattner Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList()); 1221361e513dSReid Spencer 1222361e513dSReid Spencer // At this point, all of the instructions and values of the function are now 1223361e513dSReid Spencer // copied over. The only problem is that they are still referencing values in 1224361e513dSReid Spencer // the Source function as operands. Loop through all of the operands of the 122543f8d164SChris Lattner // functions and patch them up to point to the local versions. 1226b1ed91f3SChris Lattner for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB) 122743f8d164SChris Lattner for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 12289f8eff31SRafael Espindola RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap, 12299f8eff31SRafael Espindola &ValMaterializer); 1230cbb91408STanya Lattner 12317391dde1SChris Lattner // There is no need to map the arguments anymore. 123244ab8aefSChris Lattner for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end(); 123344ab8aefSChris Lattner I != E; ++I) 12343aaaa0b2SReid Spencer ValueMap.erase(I); 1235cbb91408STanya Lattner 1236361e513dSReid Spencer } 1237361e513dSReid Spencer 123818c89411SRafael Espindola /// Insert all of the aliases in Src into the Dest module. 1239b1ed91f3SChris Lattner void ModuleLinker::linkAliasBodies() { 1240b1ed91f3SChris Lattner for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end(); 1241cbb91408STanya Lattner I != E; ++I) { 1242cbb91408STanya Lattner if (DoNotLinkFromSource.count(I)) 1243cbb91408STanya Lattner continue; 1244b1ed91f3SChris Lattner if (Constant *Aliasee = I->getAliasee()) { 1245b1ed91f3SChris Lattner GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]); 12466b238633SRafael Espindola Constant *Val = 12476b238633SRafael Espindola MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer); 124864c1e180SRafael Espindola DA->setAliasee(Val); 12492c4a34aeSDavid Chisnall } 1250b1ed91f3SChris Lattner } 1251cbb91408STanya Lattner } 1252b1ed91f3SChris Lattner 125318c89411SRafael Espindola /// Insert all of the named MDNodes in Src into the Dest module. 1254b1ed91f3SChris Lattner void ModuleLinker::linkNamedMDNodes() { 125566f02413SBill Wendling const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); 1256b1ed91f3SChris Lattner for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(), 1257b1ed91f3SChris Lattner E = SrcM->named_metadata_end(); I != E; ++I) { 125866f02413SBill Wendling // Don't link module flags here. Do them separately. 125966f02413SBill Wendling if (&*I == SrcModFlags) continue; 1260b1ed91f3SChris Lattner NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName()); 1261b1ed91f3SChris Lattner // Add Src elements into Dest node. 1262b1ed91f3SChris Lattner for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 1263b1ed91f3SChris Lattner DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap, 1264f6f121e2SJames Molloy RF_None, &TypeMap, &ValMaterializer)); 1265b1ed91f3SChris Lattner } 1266b1ed91f3SChris Lattner } 1267b1ed91f3SChris Lattner 126818c89411SRafael Espindola /// Merge the linker flags in Src into the Dest module. 126966f02413SBill Wendling bool ModuleLinker::linkModuleFlagsMetadata() { 12700ec72bbcSDaniel Dunbar // If the source module has no module flags, we are done. 127166f02413SBill Wendling const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); 127266f02413SBill Wendling if (!SrcModFlags) return false; 127366f02413SBill Wendling 127466f02413SBill Wendling // If the destination module doesn't have module flags yet, then just copy 127566f02413SBill Wendling // over the source module's flags. 12760ec72bbcSDaniel Dunbar NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata(); 127766f02413SBill Wendling if (DstModFlags->getNumOperands() == 0) { 127866f02413SBill Wendling for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) 127966f02413SBill Wendling DstModFlags->addOperand(SrcModFlags->getOperand(I)); 128066f02413SBill Wendling 128166f02413SBill Wendling return false; 128266f02413SBill Wendling } 128366f02413SBill Wendling 12840ec72bbcSDaniel Dunbar // First build a map of the existing module flags and requirements. 12850ec72bbcSDaniel Dunbar DenseMap<MDString*, MDNode*> Flags; 12860ec72bbcSDaniel Dunbar SmallSetVector<MDNode*, 16> Requirements; 12870ec72bbcSDaniel Dunbar for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) { 1288de36e804SDuncan P. N. Exon Smith MDNode *Op = DstModFlags->getOperand(I); 12890ec72bbcSDaniel Dunbar ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0)); 12900ec72bbcSDaniel Dunbar MDString *ID = cast<MDString>(Op->getOperand(1)); 12910ec72bbcSDaniel Dunbar 12920ec72bbcSDaniel Dunbar if (Behavior->getZExtValue() == Module::Require) { 12930ec72bbcSDaniel Dunbar Requirements.insert(cast<MDNode>(Op->getOperand(2))); 12940ec72bbcSDaniel Dunbar } else { 12950ec72bbcSDaniel Dunbar Flags[ID] = Op; 12960ec72bbcSDaniel Dunbar } 12970ec72bbcSDaniel Dunbar } 12980ec72bbcSDaniel Dunbar 12990ec72bbcSDaniel Dunbar // Merge in the flags from the source module, and also collect its set of 13000ec72bbcSDaniel Dunbar // requirements. 130166f02413SBill Wendling bool HasErr = false; 13020ec72bbcSDaniel Dunbar for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) { 1303de36e804SDuncan P. N. Exon Smith MDNode *SrcOp = SrcModFlags->getOperand(I); 13040ec72bbcSDaniel Dunbar ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0)); 13050ec72bbcSDaniel Dunbar MDString *ID = cast<MDString>(SrcOp->getOperand(1)); 13060ec72bbcSDaniel Dunbar MDNode *DstOp = Flags.lookup(ID); 13070ec72bbcSDaniel Dunbar unsigned SrcBehaviorValue = SrcBehavior->getZExtValue(); 130866f02413SBill Wendling 13090ec72bbcSDaniel Dunbar // If this is a requirement, add it and continue. 13100ec72bbcSDaniel Dunbar if (SrcBehaviorValue == Module::Require) { 13110ec72bbcSDaniel Dunbar // If the destination module does not already have this requirement, add 13120ec72bbcSDaniel Dunbar // it. 13130ec72bbcSDaniel Dunbar if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) { 13140ec72bbcSDaniel Dunbar DstModFlags->addOperand(SrcOp); 13150ec72bbcSDaniel Dunbar } 13160ec72bbcSDaniel Dunbar continue; 13170ec72bbcSDaniel Dunbar } 131866f02413SBill Wendling 13190ec72bbcSDaniel Dunbar // If there is no existing flag with this ID, just add it. 13200ec72bbcSDaniel Dunbar if (!DstOp) { 13210ec72bbcSDaniel Dunbar Flags[ID] = SrcOp; 13220ec72bbcSDaniel Dunbar DstModFlags->addOperand(SrcOp); 13230ec72bbcSDaniel Dunbar continue; 13240ec72bbcSDaniel Dunbar } 132566f02413SBill Wendling 13260ec72bbcSDaniel Dunbar // Otherwise, perform a merge. 13270ec72bbcSDaniel Dunbar ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0)); 13280ec72bbcSDaniel Dunbar unsigned DstBehaviorValue = DstBehavior->getZExtValue(); 13290ec72bbcSDaniel Dunbar 13300ec72bbcSDaniel Dunbar // If either flag has override behavior, handle it first. 13310ec72bbcSDaniel Dunbar if (DstBehaviorValue == Module::Override) { 13320ec72bbcSDaniel Dunbar // Diagnose inconsistent flags which both have override behavior. 13330ec72bbcSDaniel Dunbar if (SrcBehaviorValue == Module::Override && 13340ec72bbcSDaniel Dunbar SrcOp->getOperand(2) != DstOp->getOperand(2)) { 13350ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + ID->getString() + 13360ec72bbcSDaniel Dunbar "': IDs have conflicting override values"); 13370ec72bbcSDaniel Dunbar } 13380ec72bbcSDaniel Dunbar continue; 13390ec72bbcSDaniel Dunbar } else if (SrcBehaviorValue == Module::Override) { 13400ec72bbcSDaniel Dunbar // Update the destination flag to that of the source. 13410ec72bbcSDaniel Dunbar DstOp->replaceOperandWith(0, SrcBehavior); 13420ec72bbcSDaniel Dunbar DstOp->replaceOperandWith(2, SrcOp->getOperand(2)); 13430ec72bbcSDaniel Dunbar continue; 13440ec72bbcSDaniel Dunbar } 13450ec72bbcSDaniel Dunbar 13460ec72bbcSDaniel Dunbar // Diagnose inconsistent merge behavior types. 13470ec72bbcSDaniel Dunbar if (SrcBehaviorValue != DstBehaviorValue) { 13480ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + ID->getString() + 134966f02413SBill Wendling "': IDs have conflicting behaviors"); 13500ec72bbcSDaniel Dunbar continue; 135166f02413SBill Wendling } 135266f02413SBill Wendling 13530ec72bbcSDaniel Dunbar // Perform the merge for standard behavior types. 13540ec72bbcSDaniel Dunbar switch (SrcBehaviorValue) { 13550ec72bbcSDaniel Dunbar case Module::Require: 13562a30d788SCraig Topper case Module::Override: llvm_unreachable("not possible"); 13570ec72bbcSDaniel Dunbar case Module::Error: { 13580ec72bbcSDaniel Dunbar // Emit an error if the values differ. 13590ec72bbcSDaniel Dunbar if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { 13600ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + ID->getString() + 13610ec72bbcSDaniel Dunbar "': IDs have conflicting values"); 136266f02413SBill Wendling } 13630ec72bbcSDaniel Dunbar continue; 136466f02413SBill Wendling } 13650ec72bbcSDaniel Dunbar case Module::Warning: { 13660ec72bbcSDaniel Dunbar // Emit a warning if the values differ. 13670ec72bbcSDaniel Dunbar if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { 1368d12b4a33SRafael Espindola emitWarning("linking module flags '" + ID->getString() + 1369d12b4a33SRafael Espindola "': IDs have conflicting values"); 1370e17f3708SEli Bendersky } 13710ec72bbcSDaniel Dunbar continue; 13720ec72bbcSDaniel Dunbar } 1373d77d9fb0SDaniel Dunbar case Module::Append: { 1374d77d9fb0SDaniel Dunbar MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); 1375d77d9fb0SDaniel Dunbar MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); 1376d77d9fb0SDaniel Dunbar unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands(); 1377d77d9fb0SDaniel Dunbar Value **VP, **Values = VP = new Value*[NumOps]; 1378d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP) 1379d77d9fb0SDaniel Dunbar *VP = DstValue->getOperand(i); 1380d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP) 1381d77d9fb0SDaniel Dunbar *VP = SrcValue->getOperand(i); 1382d77d9fb0SDaniel Dunbar DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(), 1383d77d9fb0SDaniel Dunbar ArrayRef<Value*>(Values, 1384d77d9fb0SDaniel Dunbar NumOps))); 1385d77d9fb0SDaniel Dunbar delete[] Values; 1386d77d9fb0SDaniel Dunbar break; 1387d77d9fb0SDaniel Dunbar } 1388d77d9fb0SDaniel Dunbar case Module::AppendUnique: { 1389d77d9fb0SDaniel Dunbar SmallSetVector<Value*, 16> Elts; 1390d77d9fb0SDaniel Dunbar MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); 1391d77d9fb0SDaniel Dunbar MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); 1392d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i) 1393d77d9fb0SDaniel Dunbar Elts.insert(DstValue->getOperand(i)); 1394d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i) 1395d77d9fb0SDaniel Dunbar Elts.insert(SrcValue->getOperand(i)); 1396d77d9fb0SDaniel Dunbar DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(), 1397d77d9fb0SDaniel Dunbar ArrayRef<Value*>(Elts.begin(), 1398d77d9fb0SDaniel Dunbar Elts.end()))); 1399d77d9fb0SDaniel Dunbar break; 1400d77d9fb0SDaniel Dunbar } 140166f02413SBill Wendling } 140266f02413SBill Wendling } 140366f02413SBill Wendling 14040ec72bbcSDaniel Dunbar // Check all of the requirements. 14050ec72bbcSDaniel Dunbar for (unsigned I = 0, E = Requirements.size(); I != E; ++I) { 14060ec72bbcSDaniel Dunbar MDNode *Requirement = Requirements[I]; 14070ec72bbcSDaniel Dunbar MDString *Flag = cast<MDString>(Requirement->getOperand(0)); 14080ec72bbcSDaniel Dunbar Value *ReqValue = Requirement->getOperand(1); 14090ec72bbcSDaniel Dunbar 14100ec72bbcSDaniel Dunbar MDNode *Op = Flags[Flag]; 14110ec72bbcSDaniel Dunbar if (!Op || Op->getOperand(2) != ReqValue) { 14120ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + Flag->getString() + 14139273b539SBill Wendling "': does not have the required value"); 14140ec72bbcSDaniel Dunbar continue; 141566f02413SBill Wendling } 141666f02413SBill Wendling } 141766f02413SBill Wendling 141866f02413SBill Wendling return HasErr; 141966f02413SBill Wendling } 142066f02413SBill Wendling 1421b1ed91f3SChris Lattner bool ModuleLinker::run() { 142266f02413SBill Wendling assert(DstM && "Null destination module"); 142366f02413SBill Wendling assert(SrcM && "Null source module"); 1424b1ed91f3SChris Lattner 1425b1ed91f3SChris Lattner // Inherit the target data from the source module if the destination module 1426b1ed91f3SChris Lattner // doesn't have one already. 1427f863ee29SRafael Espindola if (!DstM->getDataLayout() && SrcM->getDataLayout()) 1428b1ed91f3SChris Lattner DstM->setDataLayout(SrcM->getDataLayout()); 1429b1ed91f3SChris Lattner 1430b1ed91f3SChris Lattner // Copy the target triple from the source to dest if the dest's is empty. 1431b1ed91f3SChris Lattner if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty()) 1432b1ed91f3SChris Lattner DstM->setTargetTriple(SrcM->getTargetTriple()); 1433b1ed91f3SChris Lattner 1434f863ee29SRafael Espindola if (SrcM->getDataLayout() && DstM->getDataLayout() && 1435ae593f15SRafael Espindola *SrcM->getDataLayout() != *DstM->getDataLayout()) { 1436d12b4a33SRafael Espindola emitWarning("Linking two modules of different data layouts: '" + 1437d12b4a33SRafael Espindola SrcM->getModuleIdentifier() + "' is '" + 1438d12b4a33SRafael Espindola SrcM->getDataLayoutStr() + "' whereas '" + 1439d12b4a33SRafael Espindola DstM->getModuleIdentifier() + "' is '" + 1440d12b4a33SRafael Espindola DstM->getDataLayoutStr() + "'\n"); 1441e17f3708SEli Bendersky } 1442b1ed91f3SChris Lattner if (!SrcM->getTargetTriple().empty() && 1443b1ed91f3SChris Lattner DstM->getTargetTriple() != SrcM->getTargetTriple()) { 1444d12b4a33SRafael Espindola emitWarning("Linking two modules of different target triples: " + 1445d12b4a33SRafael Espindola SrcM->getModuleIdentifier() + "' is '" + 1446d12b4a33SRafael Espindola SrcM->getTargetTriple() + "' whereas '" + 1447d12b4a33SRafael Espindola DstM->getModuleIdentifier() + "' is '" + 1448d12b4a33SRafael Espindola DstM->getTargetTriple() + "'\n"); 1449e17f3708SEli Bendersky } 1450b1ed91f3SChris Lattner 1451b1ed91f3SChris Lattner // Append the module inline asm string. 1452b1ed91f3SChris Lattner if (!SrcM->getModuleInlineAsm().empty()) { 1453b1ed91f3SChris Lattner if (DstM->getModuleInlineAsm().empty()) 1454b1ed91f3SChris Lattner DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm()); 1455b1ed91f3SChris Lattner else 1456b1ed91f3SChris Lattner DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+ 1457b1ed91f3SChris Lattner SrcM->getModuleInlineAsm()); 1458b1ed91f3SChris Lattner } 1459b1ed91f3SChris Lattner 1460b1ed91f3SChris Lattner // Loop over all of the linked values to compute type mappings. 1461b1ed91f3SChris Lattner computeTypeMapping(); 1462b1ed91f3SChris Lattner 1463dad0a645SDavid Majnemer ComdatsChosen.clear(); 14645106ce78SDavid Blaikie for (const auto &SMEC : SrcM->getComdatSymbolTable()) { 1465dad0a645SDavid Majnemer const Comdat &C = SMEC.getValue(); 1466dad0a645SDavid Majnemer if (ComdatsChosen.count(&C)) 1467dad0a645SDavid Majnemer continue; 1468dad0a645SDavid Majnemer Comdat::SelectionKind SK; 1469dad0a645SDavid Majnemer bool LinkFromSrc; 1470dad0a645SDavid Majnemer if (getComdatResult(&C, SK, LinkFromSrc)) 1471dad0a645SDavid Majnemer return true; 1472dad0a645SDavid Majnemer ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc); 1473dad0a645SDavid Majnemer } 1474dad0a645SDavid Majnemer 147509d84addSDuncan P. N. Exon Smith // Upgrade mismatched global arrays. 147609d84addSDuncan P. N. Exon Smith upgradeMismatchedGlobals(); 147709d84addSDuncan P. N. Exon Smith 1478b1ed91f3SChris Lattner // Insert all of the globals in src into the DstM module... without linking 1479b1ed91f3SChris Lattner // initializers (which could refer to functions not yet mapped over). 1480b1ed91f3SChris Lattner for (Module::global_iterator I = SrcM->global_begin(), 1481b1ed91f3SChris Lattner E = SrcM->global_end(); I != E; ++I) 1482778fcc77SRafael Espindola if (linkGlobalValueProto(I)) 1483b1ed91f3SChris Lattner return true; 1484b1ed91f3SChris Lattner 1485b1ed91f3SChris Lattner // Link the functions together between the two modules, without doing function 1486b1ed91f3SChris Lattner // bodies... this just adds external function prototypes to the DstM 1487b1ed91f3SChris Lattner // function... We do this so that when we begin processing function bodies, 1488b1ed91f3SChris Lattner // all of the global values that may be referenced are available in our 1489b1ed91f3SChris Lattner // ValueMap. 1490b1ed91f3SChris Lattner for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) 1491778fcc77SRafael Espindola if (linkGlobalValueProto(I)) 1492b1ed91f3SChris Lattner return true; 1493b1ed91f3SChris Lattner 1494b1ed91f3SChris Lattner // If there were any aliases, link them now. 1495b1ed91f3SChris Lattner for (Module::alias_iterator I = SrcM->alias_begin(), 1496b1ed91f3SChris Lattner E = SrcM->alias_end(); I != E; ++I) 1497778fcc77SRafael Espindola if (linkGlobalValueProto(I)) 1498b1ed91f3SChris Lattner return true; 1499b1ed91f3SChris Lattner 1500b1ed91f3SChris Lattner for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i) 1501b1ed91f3SChris Lattner linkAppendingVarInit(AppendingVars[i]); 1502b1ed91f3SChris Lattner 1503b1ed91f3SChris Lattner // Link in the function bodies that are defined in the source module into 1504b1ed91f3SChris Lattner // DstM. 1505b1ed91f3SChris Lattner for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) { 1506ea166d44STanya Lattner // Skip if not linking from source. 1507ea166d44STanya Lattner if (DoNotLinkFromSource.count(SF)) continue; 1508ea166d44STanya Lattner 15093fa50f9bSPeter Collingbourne Function *DF = cast<Function>(ValueMap[SF]); 15103fa50f9bSPeter Collingbourne if (SF->hasPrefixData()) { 15113fa50f9bSPeter Collingbourne // Link in the prefix data. 15123fa50f9bSPeter Collingbourne DF->setPrefixData(MapValue( 15133fa50f9bSPeter Collingbourne SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer)); 15143fa50f9bSPeter Collingbourne } 15153fa50f9bSPeter Collingbourne 1516d4bcefc7SRafael Espindola // Materialize if needed. 1517d12b4a33SRafael Espindola if (std::error_code EC = SF->materialize()) 1518d12b4a33SRafael Espindola return emitError(EC.message()); 1519b1ed91f3SChris Lattner 1520d4bcefc7SRafael Espindola // Skip if no body (function is external). 1521d4bcefc7SRafael Espindola if (SF->isDeclaration()) 1522d4bcefc7SRafael Espindola continue; 1523d4bcefc7SRafael Espindola 15243fa50f9bSPeter Collingbourne linkFunctionBody(DF, SF); 152500623787SBill Wendling SF->Dematerialize(); 1526b1ed91f3SChris Lattner } 1527b1ed91f3SChris Lattner 1528b1ed91f3SChris Lattner // Resolve all uses of aliases with aliasees. 1529b1ed91f3SChris Lattner linkAliasBodies(); 1530b1ed91f3SChris Lattner 153166f02413SBill Wendling // Remap all of the named MDNodes in Src into the DstM module. We do this 15326ddbb2e2SDevang Patel // after linking GlobalValues so that MDNodes that reference GlobalValues 15336ddbb2e2SDevang Patel // are properly remapped. 15346ddbb2e2SDevang Patel linkNamedMDNodes(); 15356ddbb2e2SDevang Patel 153666f02413SBill Wendling // Merge the module flags into the DstM module. 153766f02413SBill Wendling if (linkModuleFlagsMetadata()) 153866f02413SBill Wendling return true; 153966f02413SBill Wendling 154091686d6dSBill Wendling // Update the initializers in the DstM module now that all globals that may 154191686d6dSBill Wendling // be referenced are in DstM. 154291686d6dSBill Wendling linkGlobalInits(); 154391686d6dSBill Wendling 15440a48b877STanya Lattner // Process vector of lazily linked in functions. 15450a48b877STanya Lattner bool LinkedInAnyFunctions; 15460a48b877STanya Lattner do { 15470a48b877STanya Lattner LinkedInAnyFunctions = false; 15480a48b877STanya Lattner 1549fa228782SBill Wendling for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(), 15500a48b877STanya Lattner E = LazilyLinkFunctions.end(); I != E; ++I) { 1551f6f121e2SJames Molloy Function *SF = *I; 1552f6f121e2SJames Molloy if (!SF) 15530a48b877STanya Lattner continue; 15540a48b877STanya Lattner 1555fa228782SBill Wendling Function *DF = cast<Function>(ValueMap[SF]); 15563fa50f9bSPeter Collingbourne if (SF->hasPrefixData()) { 15573fa50f9bSPeter Collingbourne // Link in the prefix data. 15583fa50f9bSPeter Collingbourne DF->setPrefixData(MapValue(SF->getPrefixData(), 15593fa50f9bSPeter Collingbourne ValueMap, 15603fa50f9bSPeter Collingbourne RF_None, 15613fa50f9bSPeter Collingbourne &TypeMap, 15623fa50f9bSPeter Collingbourne &ValMaterializer)); 15633fa50f9bSPeter Collingbourne } 15640a48b877STanya Lattner 1565d4bcefc7SRafael Espindola // Materialize if needed. 1566d12b4a33SRafael Espindola if (std::error_code EC = SF->materialize()) 1567d12b4a33SRafael Espindola return emitError(EC.message()); 15680a48b877STanya Lattner 1569d4bcefc7SRafael Espindola // Skip if no body (function is external). 1570d4bcefc7SRafael Espindola if (SF->isDeclaration()) 1571d4bcefc7SRafael Espindola continue; 1572d4bcefc7SRafael Espindola 1573f6f121e2SJames Molloy // Erase from vector *before* the function body is linked - linkFunctionBody could 1574f6f121e2SJames Molloy // invalidate I. 1575f6f121e2SJames Molloy LazilyLinkFunctions.erase(I); 1576f6f121e2SJames Molloy 15770a48b877STanya Lattner // Link in function body. 15780a48b877STanya Lattner linkFunctionBody(DF, SF); 157900623787SBill Wendling SF->Dematerialize(); 15800a48b877STanya Lattner 15810a48b877STanya Lattner // Set flag to indicate we may have more functions to lazily link in 15820a48b877STanya Lattner // since we linked in a function. 15830a48b877STanya Lattner LinkedInAnyFunctions = true; 1584f6f121e2SJames Molloy break; 15850a48b877STanya Lattner } 15860a48b877STanya Lattner } while (LinkedInAnyFunctions); 15870a48b877STanya Lattner 1588b1ed91f3SChris Lattner // Now that all of the types from the source are used, resolve any structs 1589b1ed91f3SChris Lattner // copied over to the dest that didn't exist there. 1590b1ed91f3SChris Lattner TypeMap.linkDefinedTypeBodies(); 15912609888fSAnton Korobeynikov 15922609888fSAnton Korobeynikov return false; 15932609888fSAnton Korobeynikov } 1594361e513dSReid Spencer 15955cb9c82aSRafael Espindola void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) { 15965cb9c82aSRafael Espindola this->Composite = M; 15975cb9c82aSRafael Espindola this->DiagnosticHandler = DiagnosticHandler; 15984160f5d3SRafael Espindola 1599aa9918aaSRafael Espindola TypeFinder StructTypes; 1600aa9918aaSRafael Espindola StructTypes.run(*M, true); 1601aa9918aaSRafael Espindola IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end()); 1602aa9918aaSRafael Espindola } 16033df61b7bSRafael Espindola 16045cb9c82aSRafael Espindola Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) { 16055cb9c82aSRafael Espindola init(M, DiagnosticHandler); 16065cb9c82aSRafael Espindola } 16075cb9c82aSRafael Espindola 16085cb9c82aSRafael Espindola Linker::Linker(Module *M) { 16095cb9c82aSRafael Espindola init(M, [this](const DiagnosticInfo &DI) { 16105cb9c82aSRafael Espindola Composite->getContext().diagnose(DI); 16115cb9c82aSRafael Espindola }); 16125cb9c82aSRafael Espindola } 16135cb9c82aSRafael Espindola 16143df61b7bSRafael Espindola Linker::~Linker() { 16153df61b7bSRafael Espindola } 16163df61b7bSRafael Espindola 161791e6f6e1SBill Wendling void Linker::deleteModule() { 161891e6f6e1SBill Wendling delete Composite; 16192617dcceSCraig Topper Composite = nullptr; 162091e6f6e1SBill Wendling } 162191e6f6e1SBill Wendling 16229f8eff31SRafael Espindola bool Linker::linkInModule(Module *Src) { 16239f8eff31SRafael Espindola ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, 16249f8eff31SRafael Espindola DiagnosticHandler); 1625d12b4a33SRafael Espindola return TheLinker.run(); 16263df61b7bSRafael Espindola } 16273df61b7bSRafael Espindola 1628b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 1629b1ed91f3SChris Lattner // LinkModules entrypoint. 1630b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 1631b1ed91f3SChris Lattner 163218c89411SRafael Espindola /// This function links two modules together, with the resulting Dest module 163318c89411SRafael Espindola /// modified to be the composite of the two input modules. If an error occurs, 163418c89411SRafael Espindola /// true is returned and ErrorMsg (if not null) is set to indicate the problem. 163518c89411SRafael Espindola /// Upon failure, the Dest module could be in a modified state, and shouldn't be 163618c89411SRafael Espindola /// relied on to be consistent. 16379f8eff31SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src, 16384160f5d3SRafael Espindola DiagnosticHandlerFunction DiagnosticHandler) { 16394160f5d3SRafael Espindola Linker L(Dest, DiagnosticHandler); 16409f8eff31SRafael Espindola return L.linkInModule(Src); 16414160f5d3SRafael Espindola } 16424160f5d3SRafael Espindola 16439f8eff31SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src) { 1644287f18b4SRafael Espindola Linker L(Dest); 16459f8eff31SRafael Espindola return L.linkInModule(Src); 1646361e513dSReid Spencer } 1647a3aeb980SBill Wendling 1648a3aeb980SBill Wendling //===----------------------------------------------------------------------===// 1649a3aeb980SBill Wendling // C API. 1650a3aeb980SBill Wendling //===----------------------------------------------------------------------===// 1651a3aeb980SBill Wendling 1652a3aeb980SBill Wendling LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src, 1653a3aeb980SBill Wendling LLVMLinkerMode Mode, char **OutMessages) { 165498ab63ceSRafael Espindola Module *D = unwrap(Dest); 165598ab63ceSRafael Espindola std::string Message; 16564160f5d3SRafael Espindola raw_string_ostream Stream(Message); 16574160f5d3SRafael Espindola DiagnosticPrinterRawOStream DP(Stream); 16584160f5d3SRafael Espindola 16594160f5d3SRafael Espindola LLVMBool Result = Linker::LinkModules( 16609f8eff31SRafael Espindola D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); }); 166198ab63ceSRafael Espindola 166298ab63ceSRafael Espindola if (OutMessages && Result) 166398ab63ceSRafael Espindola *OutMessages = strdup(Message.c_str()); 1664a3aeb980SBill Wendling return Result; 1665a3aeb980SBill Wendling } 1666