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" 1631ad468dSRafael Espindola #include "llvm/ADT/Hashing.h" 1723f8d64bSRafael Espindola #include "llvm/ADT/Optional.h" 1866f02413SBill Wendling #include "llvm/ADT/SetVector.h" 190f7fd36fSEli Bendersky #include "llvm/ADT/SmallString.h" 2031ad468dSRafael Espindola #include "llvm/ADT/Statistic.h" 219fb823bbSChandler Carruth #include "llvm/IR/Constants.h" 22d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticInfo.h" 23d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticPrinter.h" 24d12b4a33SRafael Espindola #include "llvm/IR/LLVMContext.h" 259fb823bbSChandler Carruth #include "llvm/IR/Module.h" 26dcb603feSChandler Carruth #include "llvm/IR/TypeFinder.h" 27e17f3708SEli Bendersky #include "llvm/Support/CommandLine.h" 28b6af2f36SBill Wendling #include "llvm/Support/Debug.h" 29b6af2f36SBill Wendling #include "llvm/Support/raw_ostream.h" 30cbb91408STanya Lattner #include "llvm/Transforms/Utils/Cloning.h" 31981af002SWill Dietz #include <cctype> 3282d6ff6bSDavid Majnemer #include <tuple> 33361e513dSReid Spencer using namespace llvm; 34361e513dSReid Spencer 35e17f3708SEli Bendersky 36b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 37b1ed91f3SChris Lattner // TypeMap implementation. 38b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 39b1ed91f3SChris Lattner 40b1ed91f3SChris Lattner namespace { 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 50a96f235cSRafael Espindola SmallVector<StructType*, 16> SpeculativeDstOpaqueTypes; 51a96f235cSRafael Espindola 5218c89411SRafael Espindola /// This is a list of non-opaque structs in the source module that are mapped 5318c89411SRafael Espindola /// to an opaque struct in the destination module. 545e3bd972SChris Lattner SmallVector<StructType*, 16> SrcDefinitionsToResolve; 555e3bd972SChris Lattner 5618c89411SRafael Espindola /// This is the set of opaque types in the destination modules who are 5718c89411SRafael Espindola /// getting a body from the source module. 585e3bd972SChris Lattner SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes; 59d48b7783SBill Wendling 608c2cc416SBill Wendling public: 6131ad468dSRafael Espindola TypeMapTy(Linker::IdentifiedStructTypeSet &DstStructTypesSet) 6231ad468dSRafael Espindola : DstStructTypesSet(DstStructTypesSet) {} 63aa9918aaSRafael Espindola 6431ad468dSRafael Espindola Linker::IdentifiedStructTypeSet &DstStructTypesSet; 6518c89411SRafael Espindola /// Indicate that the specified type in the destination module is conceptually 6618c89411SRafael Espindola /// equivalent to the specified type in the source module. 67b1ed91f3SChris Lattner void addTypeMapping(Type *DstTy, Type *SrcTy); 68b1ed91f3SChris Lattner 69d2a13a2eSRafael Espindola /// Produce a body for an opaque type in the dest module from a type 70d2a13a2eSRafael Espindola /// definition in the source module. 71b1ed91f3SChris Lattner void linkDefinedTypeBodies(); 72b1ed91f3SChris Lattner 7318c89411SRafael Espindola /// Return the mapped type to use for the specified input type from the 74b1ed91f3SChris Lattner /// source module. 75b1ed91f3SChris Lattner Type *get(Type *SrcTy); 7631ad468dSRafael Espindola Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited); 7731ad468dSRafael Espindola 7831ad468dSRafael Espindola void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes); 79b1ed91f3SChris Lattner 80290e2cc5SRafael Espindola FunctionType *get(FunctionType *T) { 81290e2cc5SRafael Espindola return cast<FunctionType>(get((Type *)T)); 82290e2cc5SRafael Espindola } 83b1ed91f3SChris Lattner 8418c89411SRafael Espindola /// Dump out the type map for debugging purposes. 85b6af2f36SBill Wendling void dump() const { 868f14471eSRafael Espindola for (auto &Pair : MappedTypes) { 87b6af2f36SBill Wendling dbgs() << "TypeMap: "; 888f14471eSRafael Espindola Pair.first->print(dbgs()); 89b6af2f36SBill Wendling dbgs() << " => "; 908f14471eSRafael Espindola Pair.second->print(dbgs()); 91b6af2f36SBill Wendling dbgs() << '\n'; 92b6af2f36SBill Wendling } 93b6af2f36SBill Wendling } 94b6af2f36SBill Wendling 95b1ed91f3SChris Lattner private: 96290e2cc5SRafael Espindola Type *remapType(Type *SrcTy) override { return get(SrcTy); } 97b1ed91f3SChris Lattner 98b1ed91f3SChris Lattner bool areTypesIsomorphic(Type *DstTy, Type *SrcTy); 99b1ed91f3SChris Lattner }; 100b1ed91f3SChris Lattner } 101b1ed91f3SChris Lattner 102b1ed91f3SChris Lattner void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) { 1033d097410SRafael Espindola assert(SpeculativeTypes.empty()); 104a96f235cSRafael Espindola assert(SpeculativeDstOpaqueTypes.empty()); 1053d097410SRafael Espindola 106b1ed91f3SChris Lattner // Check to see if these types are recursively isomorphic and establish a 107b1ed91f3SChris Lattner // mapping between them if so. 108c586eaa1SDuncan P. N. Exon Smith if (!areTypesIsomorphic(DstTy, SrcTy)) { 109b1ed91f3SChris Lattner // Oops, they aren't isomorphic. Just discard this request by rolling out 110b1ed91f3SChris Lattner // any speculative mappings we've established. 1113d097410SRafael Espindola for (Type *Ty : SpeculativeTypes) 1123d097410SRafael Espindola MappedTypes.erase(Ty); 113a96f235cSRafael Espindola 114a96f235cSRafael Espindola SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() - 115a96f235cSRafael Espindola SpeculativeDstOpaqueTypes.size()); 116a96f235cSRafael Espindola for (StructType *Ty : SpeculativeDstOpaqueTypes) 117a96f235cSRafael Espindola DstResolvedOpaqueTypes.erase(Ty); 11804a74af7SRafael Espindola } else { 11904a74af7SRafael Espindola for (Type *Ty : SpeculativeTypes) 12004a74af7SRafael Espindola if (auto *STy = dyn_cast<StructType>(Ty)) 12104a74af7SRafael Espindola if (STy->hasName()) 12204a74af7SRafael Espindola STy->setName(""); 123d48b7783SBill Wendling } 124b1ed91f3SChris Lattner SpeculativeTypes.clear(); 125a96f235cSRafael Espindola SpeculativeDstOpaqueTypes.clear(); 126b1ed91f3SChris Lattner } 127b1ed91f3SChris Lattner 12818c89411SRafael Espindola /// Recursively walk this pair of types, returning true if they are isomorphic, 12918c89411SRafael Espindola /// false if they are not. 130b1ed91f3SChris Lattner bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) { 131b1ed91f3SChris Lattner // Two types with differing kinds are clearly not isomorphic. 132290e2cc5SRafael Espindola if (DstTy->getTypeID() != SrcTy->getTypeID()) 133290e2cc5SRafael Espindola return false; 134b1ed91f3SChris Lattner 135b1ed91f3SChris Lattner // If we have an entry in the MappedTypes table, then we have our answer. 136b1ed91f3SChris Lattner Type *&Entry = MappedTypes[SrcTy]; 137b1ed91f3SChris Lattner if (Entry) 138b1ed91f3SChris Lattner return Entry == DstTy; 139b1ed91f3SChris Lattner 140b1ed91f3SChris Lattner // Two identical types are clearly isomorphic. Remember this 141b1ed91f3SChris Lattner // non-speculatively. 142b1ed91f3SChris Lattner if (DstTy == SrcTy) { 143b1ed91f3SChris Lattner Entry = DstTy; 144361e513dSReid Spencer return true; 145361e513dSReid Spencer } 146361e513dSReid Spencer 147b1ed91f3SChris Lattner // Okay, we have two types with identical kinds that we haven't seen before. 148361e513dSReid Spencer 149b1ed91f3SChris Lattner // If this is an opaque struct type, special case it. 150b1ed91f3SChris Lattner if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) { 151b1ed91f3SChris Lattner // Mapping an opaque type to any struct, just keep the dest struct. 152b1ed91f3SChris Lattner if (SSTy->isOpaque()) { 153b1ed91f3SChris Lattner Entry = DstTy; 154b1ed91f3SChris Lattner SpeculativeTypes.push_back(SrcTy); 155b1ed91f3SChris Lattner return true; 156361e513dSReid Spencer } 157b1ed91f3SChris Lattner 1585e3bd972SChris Lattner // Mapping a non-opaque source type to an opaque dest. If this is the first 1595e3bd972SChris Lattner // type that we're mapping onto this destination type then we succeed. Keep 160a96f235cSRafael Espindola // the dest, but fill it in later. If this is the second (different) type 161a96f235cSRafael Espindola // that we're trying to map onto the same opaque type then we fail. 162b1ed91f3SChris Lattner if (cast<StructType>(DstTy)->isOpaque()) { 1635e3bd972SChris Lattner // We can only map one source type onto the opaque destination type. 16470573dcdSDavid Blaikie if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second) 1655e3bd972SChris Lattner return false; 1665e3bd972SChris Lattner SrcDefinitionsToResolve.push_back(SSTy); 167a96f235cSRafael Espindola SpeculativeTypes.push_back(SrcTy); 168a96f235cSRafael Espindola SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy)); 169b1ed91f3SChris Lattner Entry = DstTy; 170b1ed91f3SChris Lattner return true; 171b1ed91f3SChris Lattner } 172b1ed91f3SChris Lattner } 173b1ed91f3SChris Lattner 174b1ed91f3SChris Lattner // If the number of subtypes disagree between the two types, then we fail. 175b1ed91f3SChris Lattner if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes()) 176b1ed91f3SChris Lattner return false; 177b1ed91f3SChris Lattner 178b1ed91f3SChris Lattner // Fail if any of the extra properties (e.g. array size) of the type disagree. 179b1ed91f3SChris Lattner if (isa<IntegerType>(DstTy)) 180b1ed91f3SChris Lattner return false; // bitwidth disagrees. 181b1ed91f3SChris Lattner if (PointerType *PT = dyn_cast<PointerType>(DstTy)) { 182b1ed91f3SChris Lattner if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace()) 183b1ed91f3SChris Lattner return false; 184eaf9b762SChris Lattner 185b1ed91f3SChris Lattner } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) { 186b1ed91f3SChris Lattner if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg()) 187b1ed91f3SChris Lattner return false; 188b1ed91f3SChris Lattner } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) { 189b1ed91f3SChris Lattner StructType *SSTy = cast<StructType>(SrcTy); 19044f7ab45SChris Lattner if (DSTy->isLiteral() != SSTy->isLiteral() || 191b1ed91f3SChris Lattner DSTy->isPacked() != SSTy->isPacked()) 192b1ed91f3SChris Lattner return false; 193b1ed91f3SChris Lattner } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) { 194b1ed91f3SChris Lattner if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements()) 195b1ed91f3SChris Lattner return false; 196b1ed91f3SChris Lattner } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) { 1975fad3e9aSJoey Gouly if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements()) 198361e513dSReid Spencer return false; 199361e513dSReid Spencer } 200361e513dSReid Spencer 201b1ed91f3SChris Lattner // Otherwise, we speculate that these two types will line up and recursively 202b1ed91f3SChris Lattner // check the subelements. 203b1ed91f3SChris Lattner Entry = DstTy; 204b1ed91f3SChris Lattner SpeculativeTypes.push_back(SrcTy); 205eee6f995SChris Lattner 206290e2cc5SRafael Espindola for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I) 207290e2cc5SRafael Espindola if (!areTypesIsomorphic(DstTy->getContainedType(I), 208290e2cc5SRafael Espindola SrcTy->getContainedType(I))) 209b1ed91f3SChris Lattner return false; 210eee6f995SChris Lattner 211b1ed91f3SChris Lattner // If everything seems to have lined up, then everything is great. 212eee6f995SChris Lattner return true; 213eee6f995SChris Lattner } 214eee6f995SChris Lattner 215b1ed91f3SChris Lattner void TypeMapTy::linkDefinedTypeBodies() { 216b1ed91f3SChris Lattner SmallVector<Type*, 16> Elements; 217c81c3f55SRafael Espindola for (StructType *SrcSTy : SrcDefinitionsToResolve) { 218b1ed91f3SChris Lattner StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]); 219c81c3f55SRafael Espindola assert(DstSTy->isOpaque()); 220b1ed91f3SChris Lattner 221b1ed91f3SChris Lattner // Map the body of the source type over to a new body for the dest type. 222b1ed91f3SChris Lattner Elements.resize(SrcSTy->getNumElements()); 223290e2cc5SRafael Espindola for (unsigned I = 0, E = Elements.size(); I != E; ++I) 224c81c3f55SRafael Espindola Elements[I] = get(SrcSTy->getElementType(I)); 225b1ed91f3SChris Lattner 226b1ed91f3SChris Lattner DstSTy->setBody(Elements, SrcSTy->isPacked()); 227b1ed91f3SChris Lattner } 228c81c3f55SRafael Espindola SrcDefinitionsToResolve.clear(); 2295e3bd972SChris Lattner DstResolvedOpaqueTypes.clear(); 230eee6f995SChris Lattner } 231eee6f995SChris Lattner 23231ad468dSRafael Espindola void TypeMapTy::finishType(StructType *DTy, StructType *STy, 23331ad468dSRafael Espindola ArrayRef<Type *> ETypes) { 23431ad468dSRafael Espindola DTy->setBody(ETypes, STy->isPacked()); 235a4e85e3dSRafael Espindola 23631ad468dSRafael Espindola // Steal STy's name. 23731ad468dSRafael Espindola if (STy->hasName()) { 23831ad468dSRafael Espindola SmallString<16> TmpName = STy->getName(); 23931ad468dSRafael Espindola STy->setName(""); 24031ad468dSRafael Espindola DTy->setName(TmpName); 24131ad468dSRafael Espindola } 24231ad468dSRafael Espindola 24331ad468dSRafael Espindola DstStructTypesSet.addNonOpaque(DTy); 24431ad468dSRafael Espindola } 24531ad468dSRafael Espindola 24631ad468dSRafael Espindola Type *TypeMapTy::get(Type *Ty) { 24731ad468dSRafael Espindola SmallPtrSet<StructType *, 8> Visited; 24831ad468dSRafael Espindola return get(Ty, Visited); 24931ad468dSRafael Espindola } 25031ad468dSRafael Espindola 25131ad468dSRafael Espindola Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) { 252b1ed91f3SChris Lattner // If we already have an entry for this type, return it. 253b1ed91f3SChris Lattner Type **Entry = &MappedTypes[Ty]; 254290e2cc5SRafael Espindola if (*Entry) 255290e2cc5SRafael Espindola return *Entry; 256b1ed91f3SChris Lattner 25731ad468dSRafael Espindola // These are types that LLVM itself will unique. 25831ad468dSRafael Espindola bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral(); 25931ad468dSRafael Espindola 26031ad468dSRafael Espindola #ifndef NDEBUG 26131ad468dSRafael Espindola if (!IsUniqued) { 26231ad468dSRafael Espindola for (auto &Pair : MappedTypes) { 26331ad468dSRafael Espindola assert(!(Pair.first != Ty && Pair.second == Ty) && 26431ad468dSRafael Espindola "mapping to a source type"); 26531ad468dSRafael Espindola } 26631ad468dSRafael Espindola } 26731ad468dSRafael Espindola #endif 26831ad468dSRafael Espindola 26931ad468dSRafael Espindola if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) { 27031ad468dSRafael Espindola StructType *DTy = StructType::create(Ty->getContext()); 27131ad468dSRafael Espindola return *Entry = DTy; 27231ad468dSRafael Espindola } 27331ad468dSRafael Espindola 27431ad468dSRafael Espindola // If this is not a recursive type, then just map all of the elements and 275b1ed91f3SChris Lattner // then rebuild the type from inside out. 27631ad468dSRafael Espindola SmallVector<Type *, 4> ElementTypes; 27731ad468dSRafael Espindola 278b1ed91f3SChris Lattner // If there are no element types to map, then the type is itself. This is 279b1ed91f3SChris Lattner // true for the anonymous {} struct, things like 'float', integers, etc. 28031ad468dSRafael Espindola if (Ty->getNumContainedTypes() == 0 && IsUniqued) 281b1ed91f3SChris Lattner return *Entry = Ty; 282b1ed91f3SChris Lattner 283b1ed91f3SChris Lattner // Remap all of the elements, keeping track of whether any of them change. 284b1ed91f3SChris Lattner bool AnyChange = false; 285b1ed91f3SChris Lattner ElementTypes.resize(Ty->getNumContainedTypes()); 286290e2cc5SRafael Espindola for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) { 28731ad468dSRafael Espindola ElementTypes[I] = get(Ty->getContainedType(I), Visited); 288290e2cc5SRafael Espindola AnyChange |= ElementTypes[I] != Ty->getContainedType(I); 289eee6f995SChris Lattner } 290b1ed91f3SChris Lattner 291b1ed91f3SChris Lattner // If we found our type while recursively processing stuff, just use it. 292b1ed91f3SChris Lattner Entry = &MappedTypes[Ty]; 29331ad468dSRafael Espindola if (*Entry) { 29431ad468dSRafael Espindola if (auto *DTy = dyn_cast<StructType>(*Entry)) { 29531ad468dSRafael Espindola if (DTy->isOpaque()) { 29631ad468dSRafael Espindola auto *STy = cast<StructType>(Ty); 29731ad468dSRafael Espindola finishType(DTy, STy, ElementTypes); 29831ad468dSRafael Espindola } 29931ad468dSRafael Espindola } 300290e2cc5SRafael Espindola return *Entry; 30131ad468dSRafael Espindola } 302b1ed91f3SChris Lattner 30331ad468dSRafael Espindola // If all of the element types mapped directly over and the type is not 30431ad468dSRafael Espindola // a nomed struct, then the type is usable as-is. 30531ad468dSRafael Espindola if (!AnyChange && IsUniqued) 306b1ed91f3SChris Lattner return *Entry = Ty; 307b1ed91f3SChris Lattner 308b1ed91f3SChris Lattner // Otherwise, rebuild a modified type. 309b1ed91f3SChris Lattner switch (Ty->getTypeID()) { 310290e2cc5SRafael Espindola default: 311290e2cc5SRafael Espindola llvm_unreachable("unknown derived type to remap"); 312b1ed91f3SChris Lattner case Type::ArrayTyID: 313b1ed91f3SChris Lattner return *Entry = ArrayType::get(ElementTypes[0], 314b1ed91f3SChris Lattner cast<ArrayType>(Ty)->getNumElements()); 315b1ed91f3SChris Lattner case Type::VectorTyID: 316b1ed91f3SChris Lattner return *Entry = VectorType::get(ElementTypes[0], 317b1ed91f3SChris Lattner cast<VectorType>(Ty)->getNumElements()); 318b1ed91f3SChris Lattner case Type::PointerTyID: 31931ad468dSRafael Espindola return *Entry = PointerType::get(ElementTypes[0], 32031ad468dSRafael Espindola cast<PointerType>(Ty)->getAddressSpace()); 321b1ed91f3SChris Lattner case Type::FunctionTyID: 322b1ed91f3SChris Lattner return *Entry = FunctionType::get(ElementTypes[0], 323717d7eddSFrits van Bommel makeArrayRef(ElementTypes).slice(1), 324b1ed91f3SChris Lattner cast<FunctionType>(Ty)->isVarArg()); 32531ad468dSRafael Espindola case Type::StructTyID: { 32631ad468dSRafael Espindola auto *STy = cast<StructType>(Ty); 32731ad468dSRafael Espindola bool IsPacked = STy->isPacked(); 32831ad468dSRafael Espindola if (IsUniqued) 32931ad468dSRafael Espindola return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked); 330b1ed91f3SChris Lattner 331b1ed91f3SChris Lattner // If the type is opaque, we can just use it directly. 332aa9918aaSRafael Espindola if (STy->isOpaque()) { 33331ad468dSRafael Espindola DstStructTypesSet.addOpaque(STy); 33431ad468dSRafael Espindola return *Entry = Ty; 335aa9918aaSRafael Espindola } 336b1ed91f3SChris Lattner 33731ad468dSRafael Espindola if (StructType *OldT = 33831ad468dSRafael Espindola DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) { 339c81c3f55SRafael Espindola STy->setName(""); 34031ad468dSRafael Espindola return *Entry = OldT; 341c81c3f55SRafael Espindola } 342c81c3f55SRafael Espindola 34331ad468dSRafael Espindola if (!AnyChange) { 34431ad468dSRafael Espindola DstStructTypesSet.addNonOpaque(STy); 34531ad468dSRafael Espindola return *Entry = Ty; 34631ad468dSRafael Espindola } 34731ad468dSRafael Espindola 34831ad468dSRafael Espindola StructType *DTy = StructType::create(Ty->getContext()); 34931ad468dSRafael Espindola finishType(DTy, STy, ElementTypes); 35031ad468dSRafael Espindola return *Entry = DTy; 35131ad468dSRafael Espindola } 35231ad468dSRafael Espindola } 353b1ed91f3SChris Lattner } 354b1ed91f3SChris Lattner 355b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 356b1ed91f3SChris Lattner // ModuleLinker implementation. 357b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 358b1ed91f3SChris Lattner 359b1ed91f3SChris Lattner namespace { 360f6f121e2SJames Molloy class ModuleLinker; 361f6f121e2SJames Molloy 36218c89411SRafael Espindola /// Creates prototypes for functions that are lazily linked on the fly. This 36318c89411SRafael Espindola /// speeds up linking for modules with many/ lazily linked functions of which 36418c89411SRafael Espindola /// few get used. 365f6f121e2SJames Molloy class ValueMaterializerTy : public ValueMaterializer { 366f6f121e2SJames Molloy TypeMapTy &TypeMap; 367f6f121e2SJames Molloy Module *DstM; 368ef23711eSRafael Espindola std::vector<GlobalValue *> &LazilyLinkGlobalValues; 369c84f608bSRafael Espindola 370f6f121e2SJames Molloy public: 371f6f121e2SJames Molloy ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM, 372ef23711eSRafael Espindola std::vector<GlobalValue *> &LazilyLinkGlobalValues) 373c84f608bSRafael Espindola : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM), 374ef23711eSRafael Espindola LazilyLinkGlobalValues(LazilyLinkGlobalValues) {} 375f6f121e2SJames Molloy 3768548299aSCraig Topper Value *materializeValueFor(Value *V) override; 377f6f121e2SJames Molloy }; 378f6f121e2SJames Molloy 379d12b4a33SRafael Espindola class LinkDiagnosticInfo : public DiagnosticInfo { 380d12b4a33SRafael Espindola const Twine &Msg; 381d12b4a33SRafael Espindola 382d12b4a33SRafael Espindola public: 383d12b4a33SRafael Espindola LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg); 384d12b4a33SRafael Espindola void print(DiagnosticPrinter &DP) const override; 385d12b4a33SRafael Espindola }; 386d12b4a33SRafael Espindola LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity, 387d12b4a33SRafael Espindola const Twine &Msg) 388d12b4a33SRafael Espindola : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {} 389d12b4a33SRafael Espindola void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; } 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 416ef23711eSRafael Espindola // Vector of GlobalValues to lazily link in. 417ef23711eSRafael Espindola std::vector<GlobalValue *> LazilyLinkGlobalValues; 4180a48b877STanya Lattner 4194160f5d3SRafael Espindola Linker::DiagnosticHandlerFunction DiagnosticHandler; 4204160f5d3SRafael Espindola 421b1ed91f3SChris Lattner public: 42231ad468dSRafael Espindola ModuleLinker(Module *dstM, Linker::IdentifiedStructTypeSet &Set, Module *srcM, 4234160f5d3SRafael Espindola Linker::DiagnosticHandlerFunction DiagnosticHandler) 424a4e85e3dSRafael Espindola : DstM(dstM), SrcM(srcM), TypeMap(Set), 425ef23711eSRafael Espindola ValMaterializer(TypeMap, DstM, LazilyLinkGlobalValues), 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()); 466c84f608bSRafael Espindola if (!DGV) 467c84f608bSRafael Espindola return nullptr; 468b1ed91f3SChris Lattner 469b1ed91f3SChris Lattner // If we found a global with the same name in the dest module, but it has 470b1ed91f3SChris Lattner // internal linkage, we are really not doing any linkage here. 471b1ed91f3SChris Lattner if (DGV->hasLocalLinkage()) 4722617dcceSCraig Topper return nullptr; 473b1ed91f3SChris Lattner 474b1ed91f3SChris Lattner // Otherwise, we do in fact link to the destination global. 475b1ed91f3SChris Lattner return DGV; 476b1ed91f3SChris Lattner } 477b1ed91f3SChris Lattner 478b1ed91f3SChris Lattner void computeTypeMapping(); 479b1ed91f3SChris Lattner 48009d84addSDuncan P. N. Exon Smith void upgradeMismatchedGlobalArray(StringRef Name); 48109d84addSDuncan P. N. Exon Smith void upgradeMismatchedGlobals(); 48209d84addSDuncan P. N. Exon Smith 4833e8bc6a8SRafael Espindola bool linkAppendingVarProto(GlobalVariable *DstGV, 4843e8bc6a8SRafael Espindola const GlobalVariable *SrcGV); 485778fcc77SRafael Espindola 486778fcc77SRafael Espindola bool linkGlobalValueProto(GlobalValue *GV); 48766f02413SBill Wendling bool linkModuleFlagsMetadata(); 488b1ed91f3SChris Lattner 489b1ed91f3SChris Lattner void linkAppendingVarInit(const AppendingVarInfo &AVI); 490ef23711eSRafael Espindola 491ef23711eSRafael Espindola void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src); 492ef23711eSRafael Espindola bool linkFunctionBody(Function &Dst, Function &Src); 493ef23711eSRafael Espindola void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src); 494ef23711eSRafael Espindola bool linkGlobalValueBody(GlobalValue &Src); 495ef23711eSRafael Espindola 496b1ed91f3SChris Lattner void linkNamedMDNodes(); 497eee6f995SChris Lattner }; 498d48b7783SBill Wendling } 499d48b7783SBill Wendling 50018c89411SRafael Espindola /// The LLVM SymbolTable class autorenames globals that conflict in the symbol 50118c89411SRafael Espindola /// table. This is good for all clients except for us. Go through the trouble 50218c89411SRafael Espindola /// to force this back. 503b1ed91f3SChris Lattner static void forceRenaming(GlobalValue *GV, StringRef Name) { 504b1ed91f3SChris Lattner // If the global doesn't force its name or if it already has the right name, 505b1ed91f3SChris Lattner // there is nothing for us to do. 506b1ed91f3SChris Lattner if (GV->hasLocalLinkage() || GV->getName() == Name) 507b1ed91f3SChris Lattner return; 508b1ed91f3SChris Lattner 509b1ed91f3SChris Lattner Module *M = GV->getParent(); 510361e513dSReid Spencer 511361e513dSReid Spencer // If there is a conflict, rename the conflict. 512b1ed91f3SChris Lattner if (GlobalValue *ConflictGV = M->getNamedValue(Name)) { 5132a8d2e0eSChris Lattner GV->takeName(ConflictGV); 514361e513dSReid Spencer ConflictGV->setName(Name); // This will cause ConflictGV to get renamed 515b1ed91f3SChris Lattner assert(ConflictGV->getName() != Name && "forceRenaming didn't work"); 5162a8d2e0eSChris Lattner } else { 5172a8d2e0eSChris Lattner GV->setName(Name); // Force the name back 5183aaaa0b2SReid Spencer } 5193aaaa0b2SReid Spencer } 5203aaaa0b2SReid Spencer 52118c89411SRafael Espindola /// copy additional attributes (those not needed to construct a GlobalValue) 52218c89411SRafael Espindola /// from the SrcGV to the DestGV. 523b6af2f36SBill Wendling static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) { 524dd7daee8SDuncan Sands DestGV->copyAttributesFrom(SrcGV); 525b1ed91f3SChris Lattner forceRenaming(DestGV, SrcGV->getName()); 526361e513dSReid Spencer } 527361e513dSReid Spencer 52823f8d64bSRafael Espindola static bool isLessConstraining(GlobalValue::VisibilityTypes a, 52923f8d64bSRafael Espindola GlobalValue::VisibilityTypes b) { 53023f8d64bSRafael Espindola if (a == GlobalValue::HiddenVisibility) 53123f8d64bSRafael Espindola return false; 53223f8d64bSRafael Espindola if (b == GlobalValue::HiddenVisibility) 53323f8d64bSRafael Espindola return true; 53423f8d64bSRafael Espindola if (a == GlobalValue::ProtectedVisibility) 53523f8d64bSRafael Espindola return false; 53623f8d64bSRafael Espindola if (b == GlobalValue::ProtectedVisibility) 53723f8d64bSRafael Espindola return true; 53823f8d64bSRafael Espindola return false; 53923f8d64bSRafael Espindola } 54023f8d64bSRafael Espindola 541ef23711eSRafael Espindola /// Loop through the global variables in the src module and merge them into the 542ef23711eSRafael Espindola /// dest module. 543ef23711eSRafael Espindola static GlobalVariable *copyGlobalVariableProto(TypeMapTy &TypeMap, Module &DstM, 544ef23711eSRafael Espindola const GlobalVariable *SGVar) { 545ef23711eSRafael Espindola // No linking to be performed or linking from the source: simply create an 546ef23711eSRafael Espindola // identical version of the symbol over in the dest module... the 547ef23711eSRafael Espindola // initializer will be filled in later by LinkGlobalInits. 548ef23711eSRafael Espindola GlobalVariable *NewDGV = new GlobalVariable( 549ef23711eSRafael Espindola DstM, TypeMap.get(SGVar->getType()->getElementType()), 550ef23711eSRafael Espindola SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr, 551ef23711eSRafael Espindola SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(), 552ef23711eSRafael Espindola SGVar->getType()->getAddressSpace()); 553f6f121e2SJames Molloy 554ef23711eSRafael Espindola return NewDGV; 5553931c28bSRafael Espindola } 5563931c28bSRafael Espindola 557ef23711eSRafael Espindola /// Link the function in the source module into the destination module if 558ef23711eSRafael Espindola /// needed, setting up mapping information. 559ef23711eSRafael Espindola static Function *copyFunctionProto(TypeMapTy &TypeMap, Module &DstM, 560ef23711eSRafael Espindola const Function *SF) { 561ef23711eSRafael Espindola // If there is no linkage to be performed or we are linking from the source, 562ef23711eSRafael Espindola // bring SF over. 563ef23711eSRafael Espindola return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(), 564ef23711eSRafael Espindola SF->getName(), &DstM); 565ef23711eSRafael Espindola } 566ef23711eSRafael Espindola 567ef23711eSRafael Espindola /// Set up prototypes for any aliases that come over from the source module. 568ef23711eSRafael Espindola static GlobalAlias *copyGlobalAliasProto(TypeMapTy &TypeMap, Module &DstM, 569ef23711eSRafael Espindola const GlobalAlias *SGA) { 570ef23711eSRafael Espindola // If there is no linkage to be performed or we're linking from the source, 571ef23711eSRafael Espindola // bring over SGA. 572ef23711eSRafael Espindola auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType())); 573ef23711eSRafael Espindola return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(), 574ef23711eSRafael Espindola SGA->getLinkage(), SGA->getName(), &DstM); 575ef23711eSRafael Espindola } 576ef23711eSRafael Espindola 577ef23711eSRafael Espindola static GlobalValue *copyGlobalValueProto(TypeMapTy &TypeMap, Module &DstM, 578ef23711eSRafael Espindola const GlobalValue *SGV) { 579ef23711eSRafael Espindola GlobalValue *NewGV; 580ef23711eSRafael Espindola if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) 581ef23711eSRafael Espindola NewGV = copyGlobalVariableProto(TypeMap, DstM, SGVar); 582ef23711eSRafael Espindola else if (auto *SF = dyn_cast<Function>(SGV)) 583ef23711eSRafael Espindola NewGV = copyFunctionProto(TypeMap, DstM, SF); 584ef23711eSRafael Espindola else 585ef23711eSRafael Espindola NewGV = copyGlobalAliasProto(TypeMap, DstM, cast<GlobalAlias>(SGV)); 586ef23711eSRafael Espindola copyGVAttributes(NewGV, SGV); 587ef23711eSRafael Espindola return NewGV; 588ef23711eSRafael Espindola } 589ef23711eSRafael Espindola 590ef23711eSRafael Espindola Value *ValueMaterializerTy::materializeValueFor(Value *V) { 591ef23711eSRafael Espindola auto *SGV = dyn_cast<GlobalValue>(V); 592ef23711eSRafael Espindola if (!SGV) 593ef23711eSRafael Espindola return nullptr; 594ef23711eSRafael Espindola 595ef23711eSRafael Espindola GlobalValue *DGV = copyGlobalValueProto(TypeMap, *DstM, SGV); 596ef23711eSRafael Espindola 597ef23711eSRafael Espindola if (Comdat *SC = SGV->getComdat()) { 598ef23711eSRafael Espindola if (auto *DGO = dyn_cast<GlobalObject>(DGV)) { 599ef23711eSRafael Espindola Comdat *DC = DstM->getOrInsertComdat(SC->getName()); 600ef23711eSRafael Espindola DGO->setComdat(DC); 601ef23711eSRafael Espindola } 602ef23711eSRafael Espindola } 603ef23711eSRafael Espindola 604ef23711eSRafael Espindola LazilyLinkGlobalValues.push_back(SGV); 605ef23711eSRafael Espindola return DGV; 606f6f121e2SJames Molloy } 607f6f121e2SJames Molloy 608dad0a645SDavid Majnemer bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName, 609dad0a645SDavid Majnemer const GlobalVariable *&GVar) { 610dad0a645SDavid Majnemer const GlobalValue *GVal = M->getNamedValue(ComdatName); 611dad0a645SDavid Majnemer if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) { 612dad0a645SDavid Majnemer GVal = GA->getBaseObject(); 613dad0a645SDavid Majnemer if (!GVal) 614dad0a645SDavid Majnemer // We cannot resolve the size of the aliasee yet. 615dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 616dad0a645SDavid Majnemer "': COMDAT key involves incomputable alias size."); 617dad0a645SDavid Majnemer } 618dad0a645SDavid Majnemer 619dad0a645SDavid Majnemer GVar = dyn_cast_or_null<GlobalVariable>(GVal); 620dad0a645SDavid Majnemer if (!GVar) 621dad0a645SDavid Majnemer return emitError( 622dad0a645SDavid Majnemer "Linking COMDATs named '" + ComdatName + 623dad0a645SDavid Majnemer "': GlobalVariable required for data dependent selection!"); 624dad0a645SDavid Majnemer 625dad0a645SDavid Majnemer return false; 626dad0a645SDavid Majnemer } 627dad0a645SDavid Majnemer 628dad0a645SDavid Majnemer bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName, 629dad0a645SDavid Majnemer Comdat::SelectionKind Src, 630dad0a645SDavid Majnemer Comdat::SelectionKind Dst, 631dad0a645SDavid Majnemer Comdat::SelectionKind &Result, 632dad0a645SDavid Majnemer bool &LinkFromSrc) { 633dad0a645SDavid Majnemer // The ability to mix Comdat::SelectionKind::Any with 634dad0a645SDavid Majnemer // Comdat::SelectionKind::Largest is a behavior that comes from COFF. 635dad0a645SDavid Majnemer bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any || 636dad0a645SDavid Majnemer Dst == Comdat::SelectionKind::Largest; 637dad0a645SDavid Majnemer bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any || 638dad0a645SDavid Majnemer Src == Comdat::SelectionKind::Largest; 639dad0a645SDavid Majnemer if (DstAnyOrLargest && SrcAnyOrLargest) { 640dad0a645SDavid Majnemer if (Dst == Comdat::SelectionKind::Largest || 641dad0a645SDavid Majnemer Src == Comdat::SelectionKind::Largest) 642dad0a645SDavid Majnemer Result = Comdat::SelectionKind::Largest; 643dad0a645SDavid Majnemer else 644dad0a645SDavid Majnemer Result = Comdat::SelectionKind::Any; 645dad0a645SDavid Majnemer } else if (Src == Dst) { 646dad0a645SDavid Majnemer Result = Dst; 647dad0a645SDavid Majnemer } else { 648dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 649dad0a645SDavid Majnemer "': invalid selection kinds!"); 650dad0a645SDavid Majnemer } 651dad0a645SDavid Majnemer 652dad0a645SDavid Majnemer switch (Result) { 653dad0a645SDavid Majnemer case Comdat::SelectionKind::Any: 654dad0a645SDavid Majnemer // Go with Dst. 655dad0a645SDavid Majnemer LinkFromSrc = false; 656dad0a645SDavid Majnemer break; 657dad0a645SDavid Majnemer case Comdat::SelectionKind::NoDuplicates: 658dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 659dad0a645SDavid Majnemer "': noduplicates has been violated!"); 660dad0a645SDavid Majnemer case Comdat::SelectionKind::ExactMatch: 661dad0a645SDavid Majnemer case Comdat::SelectionKind::Largest: 662dad0a645SDavid Majnemer case Comdat::SelectionKind::SameSize: { 663dad0a645SDavid Majnemer const GlobalVariable *DstGV; 664dad0a645SDavid Majnemer const GlobalVariable *SrcGV; 665dad0a645SDavid Majnemer if (getComdatLeader(DstM, ComdatName, DstGV) || 666dad0a645SDavid Majnemer getComdatLeader(SrcM, ComdatName, SrcGV)) 667dad0a645SDavid Majnemer return true; 668dad0a645SDavid Majnemer 669dad0a645SDavid Majnemer const DataLayout *DstDL = DstM->getDataLayout(); 670dad0a645SDavid Majnemer const DataLayout *SrcDL = SrcM->getDataLayout(); 671dad0a645SDavid Majnemer if (!DstDL || !SrcDL) { 672dad0a645SDavid Majnemer return emitError( 673dad0a645SDavid Majnemer "Linking COMDATs named '" + ComdatName + 674dad0a645SDavid Majnemer "': can't do size dependent selection without DataLayout!"); 675dad0a645SDavid Majnemer } 676dad0a645SDavid Majnemer uint64_t DstSize = 677dad0a645SDavid Majnemer DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType()); 678dad0a645SDavid Majnemer uint64_t SrcSize = 679dad0a645SDavid Majnemer SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType()); 680dad0a645SDavid Majnemer if (Result == Comdat::SelectionKind::ExactMatch) { 681dad0a645SDavid Majnemer if (SrcGV->getInitializer() != DstGV->getInitializer()) 682dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 683dad0a645SDavid Majnemer "': ExactMatch violated!"); 684dad0a645SDavid Majnemer LinkFromSrc = false; 685dad0a645SDavid Majnemer } else if (Result == Comdat::SelectionKind::Largest) { 686dad0a645SDavid Majnemer LinkFromSrc = SrcSize > DstSize; 687dad0a645SDavid Majnemer } else if (Result == Comdat::SelectionKind::SameSize) { 688dad0a645SDavid Majnemer if (SrcSize != DstSize) 689dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 690dad0a645SDavid Majnemer "': SameSize violated!"); 691dad0a645SDavid Majnemer LinkFromSrc = false; 692dad0a645SDavid Majnemer } else { 693dad0a645SDavid Majnemer llvm_unreachable("unknown selection kind"); 694dad0a645SDavid Majnemer } 695dad0a645SDavid Majnemer break; 696dad0a645SDavid Majnemer } 697dad0a645SDavid Majnemer } 698dad0a645SDavid Majnemer 699dad0a645SDavid Majnemer return false; 700dad0a645SDavid Majnemer } 701dad0a645SDavid Majnemer 702dad0a645SDavid Majnemer bool ModuleLinker::getComdatResult(const Comdat *SrcC, 703dad0a645SDavid Majnemer Comdat::SelectionKind &Result, 704dad0a645SDavid Majnemer bool &LinkFromSrc) { 705b16196a3SRafael Espindola Comdat::SelectionKind SSK = SrcC->getSelectionKind(); 706dad0a645SDavid Majnemer StringRef ComdatName = SrcC->getName(); 707dad0a645SDavid Majnemer Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable(); 708dad0a645SDavid Majnemer Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName); 7092ef3f299SRafael Espindola 710b16196a3SRafael Espindola if (DstCI == ComdatSymTab.end()) { 711b16196a3SRafael Espindola // Use the comdat if it is only available in one of the modules. 712b16196a3SRafael Espindola LinkFromSrc = true; 713b16196a3SRafael Espindola Result = SSK; 7142ef3f299SRafael Espindola return false; 715b16196a3SRafael Espindola } 7162ef3f299SRafael Espindola 717dad0a645SDavid Majnemer const Comdat *DstC = &DstCI->second; 718dad0a645SDavid Majnemer Comdat::SelectionKind DSK = DstC->getSelectionKind(); 7192ef3f299SRafael Espindola return computeResultingSelectionKind(ComdatName, SSK, DSK, Result, 7202ef3f299SRafael Espindola LinkFromSrc); 721dad0a645SDavid Majnemer } 722f6f121e2SJames Molloy 723d12b4a33SRafael Espindola bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc, 724d12b4a33SRafael Espindola const GlobalValue &Dest, 725dbb0bd1aSRafael Espindola const GlobalValue &Src) { 726778fcc77SRafael Espindola // We always have to add Src if it has appending linkage. 727778fcc77SRafael Espindola if (Src.hasAppendingLinkage()) { 728778fcc77SRafael Espindola LinkFromSrc = true; 729778fcc77SRafael Espindola return false; 730778fcc77SRafael Espindola } 731778fcc77SRafael Espindola 732d4bcefc7SRafael Espindola bool SrcIsDeclaration = Src.isDeclarationForLinker(); 733d4bcefc7SRafael Espindola bool DestIsDeclaration = Dest.isDeclarationForLinker(); 734dbb0bd1aSRafael Espindola 735dbb0bd1aSRafael Espindola if (SrcIsDeclaration) { 736dbb0bd1aSRafael Espindola // If Src is external or if both Src & Dest are external.. Just link the 737dbb0bd1aSRafael Espindola // external globals, we aren't adding anything. 738d12b4a33SRafael Espindola if (Src.hasDLLImportStorageClass()) { 739dbb0bd1aSRafael Espindola // If one of GVs is marked as DLLImport, result should be dllimport'ed. 740d12b4a33SRafael Espindola LinkFromSrc = DestIsDeclaration; 741d12b4a33SRafael Espindola return false; 742d12b4a33SRafael Espindola } 743dbb0bd1aSRafael Espindola // If the Dest is weak, use the source linkage. 744d12b4a33SRafael Espindola LinkFromSrc = Dest.hasExternalWeakLinkage(); 745d12b4a33SRafael Espindola return false; 746dbb0bd1aSRafael Espindola } 747dbb0bd1aSRafael Espindola 748d12b4a33SRafael Espindola if (DestIsDeclaration) { 749dbb0bd1aSRafael Espindola // If Dest is external but Src is not: 750d12b4a33SRafael Espindola LinkFromSrc = true; 751d12b4a33SRafael Espindola return false; 752d12b4a33SRafael Espindola } 753dbb0bd1aSRafael Espindola 7540910605aSRafael Espindola if (Src.hasCommonLinkage()) { 755d12b4a33SRafael Espindola if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) { 756d12b4a33SRafael Espindola LinkFromSrc = true; 7570910605aSRafael Espindola return false; 758d12b4a33SRafael Espindola } 759d12b4a33SRafael Espindola 760d12b4a33SRafael Espindola if (!Dest.hasCommonLinkage()) { 761d12b4a33SRafael Espindola LinkFromSrc = false; 762d12b4a33SRafael Espindola return false; 763d12b4a33SRafael Espindola } 7640910605aSRafael Espindola 7650ae225b6SRafael Espindola // FIXME: Make datalayout mandatory and just use getDataLayout(). 7660ae225b6SRafael Espindola DataLayout DL(Dest.getParent()); 7670ae225b6SRafael Espindola 7680910605aSRafael Espindola uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType()); 7690910605aSRafael Espindola uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType()); 770d12b4a33SRafael Espindola LinkFromSrc = SrcSize > DestSize; 771d12b4a33SRafael Espindola return false; 7720910605aSRafael Espindola } 7730910605aSRafael Espindola 774dbb0bd1aSRafael Espindola if (Src.isWeakForLinker()) { 775dbb0bd1aSRafael Espindola assert(!Dest.hasExternalWeakLinkage()); 776dbb0bd1aSRafael Espindola assert(!Dest.hasAvailableExternallyLinkage()); 7770910605aSRafael Espindola 778d12b4a33SRafael Espindola if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) { 779d12b4a33SRafael Espindola LinkFromSrc = true; 780d12b4a33SRafael Espindola return false; 781d12b4a33SRafael Espindola } 782dbb0bd1aSRafael Espindola 783d12b4a33SRafael Espindola LinkFromSrc = false; 7840910605aSRafael Espindola return false; 785dbb0bd1aSRafael Espindola } 786dbb0bd1aSRafael Espindola 787dbb0bd1aSRafael Espindola if (Dest.isWeakForLinker()) { 788dbb0bd1aSRafael Espindola assert(Src.hasExternalLinkage()); 789d12b4a33SRafael Espindola LinkFromSrc = true; 790d12b4a33SRafael Espindola return false; 791dbb0bd1aSRafael Espindola } 792dbb0bd1aSRafael Espindola 793dbb0bd1aSRafael Espindola assert(!Src.hasExternalWeakLinkage()); 794dbb0bd1aSRafael Espindola assert(!Dest.hasExternalWeakLinkage()); 795dbb0bd1aSRafael Espindola assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() && 796dbb0bd1aSRafael Espindola "Unexpected linkage type!"); 797dbb0bd1aSRafael Espindola return emitError("Linking globals named '" + Src.getName() + 798dbb0bd1aSRafael Espindola "': symbol multiply defined!"); 799dbb0bd1aSRafael Espindola } 800dbb0bd1aSRafael Espindola 80118c89411SRafael Espindola /// Loop over all of the linked values to compute type mappings. For example, 80218c89411SRafael Espindola /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct 80318c89411SRafael Espindola /// types 'Foo' but one got renamed when the module was loaded into the same 80418c89411SRafael Espindola /// LLVMContext. 805b1ed91f3SChris Lattner void ModuleLinker::computeTypeMapping() { 806c8a476eeSRafael Espindola for (GlobalValue &SGV : SrcM->globals()) { 807c8a476eeSRafael Espindola GlobalValue *DGV = getLinkedToGlobal(&SGV); 808c8a476eeSRafael Espindola if (!DGV) 809c8a476eeSRafael Espindola continue; 810b1ed91f3SChris Lattner 811c8a476eeSRafael Espindola if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) { 812c8a476eeSRafael Espindola TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); 813b1ed91f3SChris Lattner continue; 8145c310be0SDevang Patel } 8155c310be0SDevang Patel 816b1ed91f3SChris Lattner // Unify the element type of appending arrays. 817b1ed91f3SChris Lattner ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType()); 818c8a476eeSRafael Espindola ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType()); 819b1ed91f3SChris Lattner TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType()); 820b1ed91f3SChris Lattner } 82134fc5a0eSChris Lattner 822c8a476eeSRafael Espindola for (GlobalValue &SGV : *SrcM) { 823c8a476eeSRafael Espindola if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) 824c8a476eeSRafael Espindola TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); 825b1ed91f3SChris Lattner } 826e79f4c77SAnton Korobeynikov 827e96d7eb8SRafael Espindola for (GlobalValue &SGV : SrcM->aliases()) { 828e96d7eb8SRafael Espindola if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) 829e96d7eb8SRafael Espindola TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); 830e96d7eb8SRafael Espindola } 831e96d7eb8SRafael Espindola 832d48b7783SBill Wendling // Incorporate types by name, scanning all the types in the source module. 833d48b7783SBill Wendling // At this point, the destination module may have a type "%foo = { i32 }" for 8342b3f61afSBill Wendling // example. When the source module got loaded into the same LLVMContext, if 8352b3f61afSBill Wendling // it had the same type, it would have been renamed to "%foo.42 = { i32 }". 8362fa1e43aSRafael Espindola std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes(); 8372fa1e43aSRafael Espindola for (StructType *ST : Types) { 8384d4c9387SRafael Espindola if (!ST->hasName()) 8394d4c9387SRafael Espindola continue; 8402b3f61afSBill Wendling 8412b3f61afSBill Wendling // Check to see if there is a dot in the name followed by a digit. 842d48b7783SBill Wendling size_t DotPos = ST->getName().rfind('.'); 843d48b7783SBill Wendling if (DotPos == 0 || DotPos == StringRef::npos || 84483c74e9fSGuy Benyei ST->getName().back() == '.' || 84583c74e9fSGuy Benyei !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1]))) 846d48b7783SBill Wendling continue; 8472b3f61afSBill Wendling 8482b3f61afSBill Wendling // Check to see if the destination module has a struct with the prefix name. 849973b3612SRafael Espindola StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)); 850973b3612SRafael Espindola if (!DST) 851973b3612SRafael Espindola continue; 852973b3612SRafael Espindola 8532b3f61afSBill Wendling // Don't use it if this actually came from the source module. They're in 8548737480dSBill Wendling // the same LLVMContext after all. Also don't use it unless the type is 8558737480dSBill Wendling // actually used in the destination module. This can happen in situations 8568737480dSBill Wendling // like this: 8578737480dSBill Wendling // 8588737480dSBill Wendling // Module A Module B 8598737480dSBill Wendling // -------- -------- 8608737480dSBill Wendling // %Z = type { %A } %B = type { %C.1 } 8618737480dSBill Wendling // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* } 8628737480dSBill Wendling // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] } 8638737480dSBill Wendling // %C = type { i8* } %B.3 = type { %C.1 } 8648737480dSBill Wendling // 8658737480dSBill Wendling // When we link Module B with Module A, the '%B' in Module B is 8668737480dSBill Wendling // used. However, that would then use '%C.1'. But when we process '%C.1', 8678737480dSBill Wendling // we prefer to take the '%C' version. So we are then left with both 8688737480dSBill Wendling // '%C.1' and '%C' being used for the same types. This leads to some 8698737480dSBill Wendling // variables using one type and some using the other. 87031ad468dSRafael Espindola if (TypeMap.DstStructTypesSet.hasType(DST)) 8712b3f61afSBill Wendling TypeMap.addTypeMapping(DST, ST); 8722b3f61afSBill Wendling } 8732b3f61afSBill Wendling 874b1ed91f3SChris Lattner // Now that we have discovered all of the type equivalences, get a body for 875b1ed91f3SChris Lattner // any 'opaque' types in the dest module that are now resolved. 876b1ed91f3SChris Lattner TypeMap.linkDefinedTypeBodies(); 877b1ed91f3SChris Lattner } 878c08e7a00SChris Lattner 87909d84addSDuncan P. N. Exon Smith static void upgradeGlobalArray(GlobalVariable *GV) { 88009d84addSDuncan P. N. Exon Smith ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType()); 88109d84addSDuncan P. N. Exon Smith StructType *OldTy = cast<StructType>(ATy->getElementType()); 88209d84addSDuncan P. N. Exon Smith assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements"); 88309d84addSDuncan P. N. Exon Smith 88409d84addSDuncan P. N. Exon Smith // Get the upgraded 3 element type. 88509d84addSDuncan P. N. Exon Smith PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo(); 88609d84addSDuncan P. N. Exon Smith Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1), 88709d84addSDuncan P. N. Exon Smith VoidPtrTy}; 88809d84addSDuncan P. N. Exon Smith StructType *NewTy = StructType::get(GV->getContext(), Tys, false); 88909d84addSDuncan P. N. Exon Smith 89009d84addSDuncan P. N. Exon Smith // Build new constants with a null third field filled in. 89109d84addSDuncan P. N. Exon Smith Constant *OldInitC = GV->getInitializer(); 89209d84addSDuncan P. N. Exon Smith ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC); 89309d84addSDuncan P. N. Exon Smith if (!OldInit && !isa<ConstantAggregateZero>(OldInitC)) 89409d84addSDuncan P. N. Exon Smith // Invalid initializer; give up. 89509d84addSDuncan P. N. Exon Smith return; 89609d84addSDuncan P. N. Exon Smith std::vector<Constant *> Initializers; 89709d84addSDuncan P. N. Exon Smith if (OldInit && OldInit->getNumOperands()) { 89809d84addSDuncan P. N. Exon Smith Value *Null = Constant::getNullValue(VoidPtrTy); 89909d84addSDuncan P. N. Exon Smith for (Use &U : OldInit->operands()) { 90009d84addSDuncan P. N. Exon Smith ConstantStruct *Init = cast<ConstantStruct>(U.get()); 90109d84addSDuncan P. N. Exon Smith Initializers.push_back(ConstantStruct::get( 90209d84addSDuncan P. N. Exon Smith NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr)); 90309d84addSDuncan P. N. Exon Smith } 90409d84addSDuncan P. N. Exon Smith } 90509d84addSDuncan P. N. Exon Smith assert(Initializers.size() == ATy->getNumElements() && 90609d84addSDuncan P. N. Exon Smith "Failed to copy all array elements"); 90709d84addSDuncan P. N. Exon Smith 90809d84addSDuncan P. N. Exon Smith // Replace the old GV with a new one. 90909d84addSDuncan P. N. Exon Smith ATy = ArrayType::get(NewTy, Initializers.size()); 91009d84addSDuncan P. N. Exon Smith Constant *NewInit = ConstantArray::get(ATy, Initializers); 91109d84addSDuncan P. N. Exon Smith GlobalVariable *NewGV = new GlobalVariable( 91209d84addSDuncan P. N. Exon Smith *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "", 91309d84addSDuncan P. N. Exon Smith GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(), 91409d84addSDuncan P. N. Exon Smith GV->isExternallyInitialized()); 91509d84addSDuncan P. N. Exon Smith NewGV->copyAttributesFrom(GV); 91609d84addSDuncan P. N. Exon Smith NewGV->takeName(GV); 91709d84addSDuncan P. N. Exon Smith assert(GV->use_empty() && "program cannot use initializer list"); 91809d84addSDuncan P. N. Exon Smith GV->eraseFromParent(); 91909d84addSDuncan P. N. Exon Smith } 92009d84addSDuncan P. N. Exon Smith 92109d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) { 92209d84addSDuncan P. N. Exon Smith // Look for the global arrays. 92309d84addSDuncan P. N. Exon Smith auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name)); 92409d84addSDuncan P. N. Exon Smith if (!DstGV) 92509d84addSDuncan P. N. Exon Smith return; 92609d84addSDuncan P. N. Exon Smith auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name)); 92709d84addSDuncan P. N. Exon Smith if (!SrcGV) 92809d84addSDuncan P. N. Exon Smith return; 92909d84addSDuncan P. N. Exon Smith 93009d84addSDuncan P. N. Exon Smith // Check if the types already match. 93109d84addSDuncan P. N. Exon Smith auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType()); 93209d84addSDuncan P. N. Exon Smith auto *SrcTy = 93309d84addSDuncan P. N. Exon Smith cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType())); 93409d84addSDuncan P. N. Exon Smith if (DstTy == SrcTy) 93509d84addSDuncan P. N. Exon Smith return; 93609d84addSDuncan P. N. Exon Smith 93709d84addSDuncan P. N. Exon Smith // Grab the element types. We can only upgrade an array of a two-field 93809d84addSDuncan P. N. Exon Smith // struct. Only bother if the other one has three-fields. 93909d84addSDuncan P. N. Exon Smith auto *DstEltTy = cast<StructType>(DstTy->getElementType()); 94009d84addSDuncan P. N. Exon Smith auto *SrcEltTy = cast<StructType>(SrcTy->getElementType()); 94109d84addSDuncan P. N. Exon Smith if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) { 94209d84addSDuncan P. N. Exon Smith upgradeGlobalArray(DstGV); 94309d84addSDuncan P. N. Exon Smith return; 94409d84addSDuncan P. N. Exon Smith } 94509d84addSDuncan P. N. Exon Smith if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2) 94609d84addSDuncan P. N. Exon Smith upgradeGlobalArray(SrcGV); 94709d84addSDuncan P. N. Exon Smith 94809d84addSDuncan P. N. Exon Smith // We can't upgrade any other differences. 94909d84addSDuncan P. N. Exon Smith } 95009d84addSDuncan P. N. Exon Smith 95109d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobals() { 95209d84addSDuncan P. N. Exon Smith upgradeMismatchedGlobalArray("llvm.global_ctors"); 95309d84addSDuncan P. N. Exon Smith upgradeMismatchedGlobalArray("llvm.global_dtors"); 95409d84addSDuncan P. N. Exon Smith } 95509d84addSDuncan P. N. Exon Smith 95618c89411SRafael Espindola /// If there were any appending global variables, link them together now. 95718c89411SRafael Espindola /// Return true on error. 958b1ed91f3SChris Lattner bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV, 9593e8bc6a8SRafael Espindola const GlobalVariable *SrcGV) { 960d48b7783SBill Wendling 961b1ed91f3SChris Lattner if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) 962b1ed91f3SChris Lattner return emitError("Linking globals named '" + SrcGV->getName() + 963b1ed91f3SChris Lattner "': can only link appending global with another appending global!"); 964361e513dSReid Spencer 965b1ed91f3SChris Lattner ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType()); 966b1ed91f3SChris Lattner ArrayType *SrcTy = 967b1ed91f3SChris Lattner cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType())); 968b1ed91f3SChris Lattner Type *EltTy = DstTy->getElementType(); 969b1ed91f3SChris Lattner 970b1ed91f3SChris Lattner // Check to see that they two arrays agree on type. 971b1ed91f3SChris Lattner if (EltTy != SrcTy->getElementType()) 972b1ed91f3SChris Lattner return emitError("Appending variables with different element types!"); 973b1ed91f3SChris Lattner if (DstGV->isConstant() != SrcGV->isConstant()) 974b1ed91f3SChris Lattner return emitError("Appending variables linked with different const'ness!"); 975b1ed91f3SChris Lattner 976b1ed91f3SChris Lattner if (DstGV->getAlignment() != SrcGV->getAlignment()) 977b1ed91f3SChris Lattner return emitError( 978b1ed91f3SChris Lattner "Appending variables with different alignment need to be linked!"); 979b1ed91f3SChris Lattner 980b1ed91f3SChris Lattner if (DstGV->getVisibility() != SrcGV->getVisibility()) 981b1ed91f3SChris Lattner return emitError( 982b1ed91f3SChris Lattner "Appending variables with different visibility need to be linked!"); 983b1ed91f3SChris Lattner 984fac3a018SRafael Espindola if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) 985fac3a018SRafael Espindola return emitError( 986fac3a018SRafael Espindola "Appending variables with different unnamed_addr need to be linked!"); 987fac3a018SRafael Espindola 98864c1e180SRafael Espindola if (StringRef(DstGV->getSection()) != SrcGV->getSection()) 989b1ed91f3SChris Lattner return emitError( 990b1ed91f3SChris Lattner "Appending variables with different section name need to be linked!"); 991b1ed91f3SChris Lattner 992b1ed91f3SChris Lattner uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements(); 993b1ed91f3SChris Lattner ArrayType *NewType = ArrayType::get(EltTy, NewSize); 994b1ed91f3SChris Lattner 995b1ed91f3SChris Lattner // Create the new global variable. 996b1ed91f3SChris Lattner GlobalVariable *NG = 997b1ed91f3SChris Lattner new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(), 9982617dcceSCraig Topper DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV, 999cbe34b4cSHans Wennborg DstGV->getThreadLocalMode(), 1000b1ed91f3SChris Lattner DstGV->getType()->getAddressSpace()); 1001b1ed91f3SChris Lattner 1002b1ed91f3SChris Lattner // Propagate alignment, visibility and section info. 1003b6af2f36SBill Wendling copyGVAttributes(NG, DstGV); 1004b1ed91f3SChris Lattner 1005b1ed91f3SChris Lattner AppendingVarInfo AVI; 1006b1ed91f3SChris Lattner AVI.NewGV = NG; 1007b1ed91f3SChris Lattner AVI.DstInit = DstGV->getInitializer(); 1008b1ed91f3SChris Lattner AVI.SrcInit = SrcGV->getInitializer(); 1009b1ed91f3SChris Lattner AppendingVars.push_back(AVI); 1010b1ed91f3SChris Lattner 1011b1ed91f3SChris Lattner // Replace any uses of the two global variables with uses of the new 1012b1ed91f3SChris Lattner // global. 1013b1ed91f3SChris Lattner ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType())); 1014b1ed91f3SChris Lattner 1015b1ed91f3SChris Lattner DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType())); 1016b1ed91f3SChris Lattner DstGV->eraseFromParent(); 1017b1ed91f3SChris Lattner 1018cbb91408STanya Lattner // Track the source variable so we don't try to link it. 1019cbb91408STanya Lattner DoNotLinkFromSource.insert(SrcGV); 1020cbb91408STanya Lattner 1021b1ed91f3SChris Lattner return false; 1022b1ed91f3SChris Lattner } 1023b1ed91f3SChris Lattner 1024778fcc77SRafael Espindola bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) { 1025b1ed91f3SChris Lattner GlobalValue *DGV = getLinkedToGlobal(SGV); 1026b1ed91f3SChris Lattner 1027778fcc77SRafael Espindola // Handle the ultra special appending linkage case first. 1028778fcc77SRafael Espindola if (DGV && DGV->hasAppendingLinkage()) 1029778fcc77SRafael Espindola return linkAppendingVarProto(cast<GlobalVariable>(DGV), 1030778fcc77SRafael Espindola cast<GlobalVariable>(SGV)); 1031778fcc77SRafael Espindola 1032778fcc77SRafael Espindola bool LinkFromSrc = true; 1033778fcc77SRafael Espindola Comdat *C = nullptr; 1034778fcc77SRafael Espindola GlobalValue::VisibilityTypes Visibility = SGV->getVisibility(); 1035778fcc77SRafael Espindola bool HasUnnamedAddr = SGV->hasUnnamedAddr(); 1036778fcc77SRafael Espindola 1037dad0a645SDavid Majnemer if (const Comdat *SC = SGV->getComdat()) { 1038dad0a645SDavid Majnemer Comdat::SelectionKind SK; 1039dad0a645SDavid Majnemer std::tie(SK, LinkFromSrc) = ComdatsChosen[SC]; 1040778fcc77SRafael Espindola C = DstM->getOrInsertComdat(SC->getName()); 1041778fcc77SRafael Espindola C->setSelectionKind(SK); 1042778fcc77SRafael Espindola } else if (DGV) { 1043778fcc77SRafael Espindola if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV)) 1044fc61de39SChris Lattner return true; 1045dad0a645SDavid Majnemer } 104634fc5a0eSChris Lattner 1047dad0a645SDavid Majnemer if (!LinkFromSrc) { 1048cbb91408STanya Lattner // Track the source global so that we don't attempt to copy it over when 1049cbb91408STanya Lattner // processing global initializers. 1050cbb91408STanya Lattner DoNotLinkFromSource.insert(SGV); 1051cbb91408STanya Lattner 1052778fcc77SRafael Espindola if (DGV) 1053778fcc77SRafael Espindola // Make sure to remember this mapping. 1054778fcc77SRafael Espindola ValueMap[SGV] = 1055778fcc77SRafael Espindola ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType())); 1056778fcc77SRafael Espindola } 1057778fcc77SRafael Espindola 1058778fcc77SRafael Espindola if (DGV) { 1059778fcc77SRafael Espindola Visibility = isLessConstraining(Visibility, DGV->getVisibility()) 1060778fcc77SRafael Espindola ? DGV->getVisibility() 1061778fcc77SRafael Espindola : Visibility; 1062778fcc77SRafael Espindola HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr(); 1063778fcc77SRafael Espindola } 1064778fcc77SRafael Espindola 1065778fcc77SRafael Espindola if (!LinkFromSrc && !DGV) 1066dad0a645SDavid Majnemer return false; 1067778fcc77SRafael Espindola 1068778fcc77SRafael Espindola GlobalValue *NewGV; 106926c29511SRafael Espindola if (!LinkFromSrc) { 107026c29511SRafael Espindola NewGV = DGV; 107126c29511SRafael Espindola } else { 1072ef23711eSRafael Espindola // If the GV is to be lazily linked, don't create it just yet. 1073ef23711eSRafael Espindola // The ValueMaterializerTy will deal with creating it if it's used. 1074ef23711eSRafael Espindola if (!DGV && (SGV->hasLocalLinkage() || SGV->hasLinkOnceLinkage() || 1075ef23711eSRafael Espindola SGV->hasAvailableExternallyLinkage())) { 1076ef23711eSRafael Espindola DoNotLinkFromSource.insert(SGV); 1077ef23711eSRafael Espindola return false; 107826c29511SRafael Espindola } 1079778fcc77SRafael Espindola 1080ef23711eSRafael Espindola NewGV = copyGlobalValueProto(TypeMap, *DstM, SGV); 1081ef23711eSRafael Espindola } 1082778fcc77SRafael Espindola 1083778fcc77SRafael Espindola NewGV->setUnnamedAddr(HasUnnamedAddr); 1084778fcc77SRafael Espindola NewGV->setVisibility(Visibility); 1085778fcc77SRafael Espindola 1086778fcc77SRafael Espindola if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) { 1087778fcc77SRafael Espindola if (C) 1088778fcc77SRafael Espindola NewGO->setComdat(C); 1089439835a6SRafael Espindola 1090439835a6SRafael Espindola if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage()) 1091439835a6SRafael Espindola NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment())); 1092778fcc77SRafael Espindola } 1093778fcc77SRafael Espindola 1094879aeb77SRafael Espindola if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) { 1095879aeb77SRafael Espindola auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV); 1096879aeb77SRafael Espindola auto *SGVar = dyn_cast<GlobalVariable>(SGV); 1097879aeb77SRafael Espindola if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() && 1098879aeb77SRafael Espindola (!DGVar->isConstant() || !SGVar->isConstant())) 1099879aeb77SRafael Espindola NewGVar->setConstant(false); 1100879aeb77SRafael Espindola } 1101879aeb77SRafael Espindola 1102778fcc77SRafael Espindola // Make sure to remember this mapping. 1103778fcc77SRafael Espindola if (NewGV != DGV) { 1104778fcc77SRafael Espindola if (DGV) { 1105ad9d0ca8SRafael Espindola DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType())); 1106778fcc77SRafael Espindola DGV->eraseFromParent(); 1107778fcc77SRafael Espindola } 1108778fcc77SRafael Espindola ValueMap[SGV] = NewGV; 1109dad0a645SDavid Majnemer } 11104e27567aSRafael Espindola 1111fd38af2dSChandler Carruth return false; 11124e27567aSRafael Espindola } 11134e27567aSRafael Espindola 11143e8bc6a8SRafael Espindola static void getArrayElements(const Constant *C, 11153e8bc6a8SRafael Espindola SmallVectorImpl<Constant *> &Dest) { 11166705883aSChris Lattner unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements(); 111700245f42SChris Lattner 11186705883aSChris Lattner for (unsigned i = 0; i != NumElements; ++i) 11196705883aSChris Lattner Dest.push_back(C->getAggregateElement(i)); 112000245f42SChris Lattner } 112100245f42SChris Lattner 1122b1ed91f3SChris Lattner void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) { 1123b1ed91f3SChris Lattner // Merge the initializer. 1124d31dc048SRafael Espindola SmallVector<Constant *, 16> DstElements; 1125d31dc048SRafael Espindola getArrayElements(AVI.DstInit, DstElements); 1126b1ed91f3SChris Lattner 1127d31dc048SRafael Espindola SmallVector<Constant *, 16> SrcElements; 1128d31dc048SRafael Espindola getArrayElements(AVI.SrcInit, SrcElements); 112900245f42SChris Lattner 1130b1ed91f3SChris Lattner ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType()); 1131d31dc048SRafael Espindola 1132d31dc048SRafael Espindola StringRef Name = AVI.NewGV->getName(); 1133d31dc048SRafael Espindola bool IsNewStructor = 1134d31dc048SRafael Espindola (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") && 1135d31dc048SRafael Espindola cast<StructType>(NewType->getElementType())->getNumElements() == 3; 1136d31dc048SRafael Espindola 1137d31dc048SRafael Espindola for (auto *V : SrcElements) { 1138d31dc048SRafael Espindola if (IsNewStructor) { 1139d31dc048SRafael Espindola Constant *Key = V->getAggregateElement(2); 1140d31dc048SRafael Espindola if (DoNotLinkFromSource.count(Key)) 1141d31dc048SRafael Espindola continue; 1142d31dc048SRafael Espindola } 1143d31dc048SRafael Espindola DstElements.push_back( 1144d31dc048SRafael Espindola MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer)); 1145d31dc048SRafael Espindola } 1146d31dc048SRafael Espindola if (IsNewStructor) { 1147d31dc048SRafael Espindola NewType = ArrayType::get(NewType->getElementType(), DstElements.size()); 1148d31dc048SRafael Espindola AVI.NewGV->mutateType(PointerType::get(NewType, 0)); 1149d31dc048SRafael Espindola } 1150d31dc048SRafael Espindola 1151d31dc048SRafael Espindola AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements)); 1152b1ed91f3SChris Lattner } 1153b1ed91f3SChris Lattner 115418c89411SRafael Espindola /// Update the initializers in the Dest module now that all globals that may be 115518c89411SRafael Espindola /// referenced are in Dest. 1156ef23711eSRafael Espindola void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) { 1157b1ed91f3SChris Lattner // Figure out what the initializer looks like in the dest module. 1158ef23711eSRafael Espindola Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap, RF_None, &TypeMap, 1159ef23711eSRafael Espindola &ValMaterializer)); 1160b1ed91f3SChris Lattner } 1161b1ed91f3SChris Lattner 116218c89411SRafael Espindola /// Copy the source function over into the dest function and fix up references 116318c89411SRafael Espindola /// to values. At this point we know that Dest is an external function, and 116418c89411SRafael Espindola /// that Src is not. 1165ef23711eSRafael Espindola bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) { 1166ef23711eSRafael Espindola assert(Dst.isDeclaration() && !Src.isDeclaration()); 1167361e513dSReid Spencer 116840d7ebedSRafael Espindola // Materialize if needed. 11693519da82SRafael Espindola if (std::error_code EC = Src.materialize()) 117040d7ebedSRafael Espindola return emitError(EC.message()); 117140d7ebedSRafael Espindola 1172869d1ce8SRafael Espindola // Link in the prefix data. 11733519da82SRafael Espindola if (Src.hasPrefixData()) 1174ef23711eSRafael Espindola Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap, RF_None, &TypeMap, 1175ef23711eSRafael Espindola &ValMaterializer)); 1176869d1ce8SRafael Espindola 1177869d1ce8SRafael Espindola // Link in the prologue data. 11783519da82SRafael Espindola if (Src.hasPrologueData()) 1179ef23711eSRafael Espindola Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap, RF_None, 1180869d1ce8SRafael Espindola &TypeMap, &ValMaterializer)); 1181869d1ce8SRafael Espindola 11827391dde1SChris Lattner // Go through and convert function arguments over, remembering the mapping. 1183ef23711eSRafael Espindola Function::arg_iterator DI = Dst.arg_begin(); 11843519da82SRafael Espindola for (Argument &Arg : Src.args()) { 1185a314d1acSRafael Espindola DI->setName(Arg.getName()); // Copy the name over. 1186361e513dSReid Spencer 1187b1ed91f3SChris Lattner // Add a mapping to our mapping. 1188a314d1acSRafael Espindola ValueMap[&Arg] = DI; 1189a314d1acSRafael Espindola ++DI; 1190361e513dSReid Spencer } 1191361e513dSReid Spencer 11922f0557d0SChris Lattner // Splice the body of the source function into the dest function. 1193ef23711eSRafael Espindola Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList()); 1194361e513dSReid Spencer 1195361e513dSReid Spencer // At this point, all of the instructions and values of the function are now 1196361e513dSReid Spencer // copied over. The only problem is that they are still referencing values in 1197361e513dSReid Spencer // the Source function as operands. Loop through all of the operands of the 119843f8d164SChris Lattner // functions and patch them up to point to the local versions. 1199ef23711eSRafael Espindola for (BasicBlock &BB : Dst) 1200a314d1acSRafael Espindola for (Instruction &I : BB) 1201a314d1acSRafael Espindola RemapInstruction(&I, ValueMap, RF_IgnoreMissingEntries, &TypeMap, 12029f8eff31SRafael Espindola &ValMaterializer); 1203cbb91408STanya Lattner 12047391dde1SChris Lattner // There is no need to map the arguments anymore. 12053519da82SRafael Espindola for (Argument &Arg : Src.args()) 1206a314d1acSRafael Espindola ValueMap.erase(&Arg); 1207cbb91408STanya Lattner 12083519da82SRafael Espindola Src.Dematerialize(); 120940d7ebedSRafael Espindola return false; 1210361e513dSReid Spencer } 1211361e513dSReid Spencer 1212ef23711eSRafael Espindola void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) { 1213ef23711eSRafael Espindola Constant *Aliasee = Src.getAliasee(); 12146b238633SRafael Espindola Constant *Val = 12156b238633SRafael Espindola MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer); 1216ef23711eSRafael Espindola Dst.setAliasee(Val); 12172c4a34aeSDavid Chisnall } 1218ef23711eSRafael Espindola 1219ef23711eSRafael Espindola bool ModuleLinker::linkGlobalValueBody(GlobalValue &Src) { 1220ef23711eSRafael Espindola Value *Dst = ValueMap[&Src]; 1221ef23711eSRafael Espindola assert(Dst); 1222ef23711eSRafael Espindola if (auto *F = dyn_cast<Function>(&Src)) 1223ef23711eSRafael Espindola return linkFunctionBody(cast<Function>(*Dst), *F); 1224ef23711eSRafael Espindola if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) { 1225ef23711eSRafael Espindola linkGlobalInit(cast<GlobalVariable>(*Dst), *GVar); 1226ef23711eSRafael Espindola return false; 1227b1ed91f3SChris Lattner } 1228ef23711eSRafael Espindola linkAliasBody(cast<GlobalAlias>(*Dst), cast<GlobalAlias>(Src)); 1229ef23711eSRafael Espindola return false; 1230cbb91408STanya Lattner } 1231b1ed91f3SChris Lattner 123218c89411SRafael Espindola /// Insert all of the named MDNodes in Src into the Dest module. 1233b1ed91f3SChris Lattner void ModuleLinker::linkNamedMDNodes() { 123466f02413SBill Wendling const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); 1235b1ed91f3SChris Lattner for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(), 1236b1ed91f3SChris Lattner E = SrcM->named_metadata_end(); I != E; ++I) { 123766f02413SBill Wendling // Don't link module flags here. Do them separately. 123866f02413SBill Wendling if (&*I == SrcModFlags) continue; 1239b1ed91f3SChris Lattner NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName()); 1240b1ed91f3SChris Lattner // Add Src elements into Dest node. 1241b1ed91f3SChris Lattner for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 1242b1ed91f3SChris Lattner DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap, 1243f6f121e2SJames Molloy RF_None, &TypeMap, &ValMaterializer)); 1244b1ed91f3SChris Lattner } 1245b1ed91f3SChris Lattner } 1246b1ed91f3SChris Lattner 124718c89411SRafael Espindola /// Merge the linker flags in Src into the Dest module. 124866f02413SBill Wendling bool ModuleLinker::linkModuleFlagsMetadata() { 12490ec72bbcSDaniel Dunbar // If the source module has no module flags, we are done. 125066f02413SBill Wendling const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); 125166f02413SBill Wendling if (!SrcModFlags) return false; 125266f02413SBill Wendling 125366f02413SBill Wendling // If the destination module doesn't have module flags yet, then just copy 125466f02413SBill Wendling // over the source module's flags. 12550ec72bbcSDaniel Dunbar NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata(); 125666f02413SBill Wendling if (DstModFlags->getNumOperands() == 0) { 125766f02413SBill Wendling for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) 125866f02413SBill Wendling DstModFlags->addOperand(SrcModFlags->getOperand(I)); 125966f02413SBill Wendling 126066f02413SBill Wendling return false; 126166f02413SBill Wendling } 126266f02413SBill Wendling 12630ec72bbcSDaniel Dunbar // First build a map of the existing module flags and requirements. 12640ec72bbcSDaniel Dunbar DenseMap<MDString*, MDNode*> Flags; 12650ec72bbcSDaniel Dunbar SmallSetVector<MDNode*, 16> Requirements; 12660ec72bbcSDaniel Dunbar for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) { 1267de36e804SDuncan P. N. Exon Smith MDNode *Op = DstModFlags->getOperand(I); 1268*5bf8fef5SDuncan P. N. Exon Smith ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0)); 12690ec72bbcSDaniel Dunbar MDString *ID = cast<MDString>(Op->getOperand(1)); 12700ec72bbcSDaniel Dunbar 12710ec72bbcSDaniel Dunbar if (Behavior->getZExtValue() == Module::Require) { 12720ec72bbcSDaniel Dunbar Requirements.insert(cast<MDNode>(Op->getOperand(2))); 12730ec72bbcSDaniel Dunbar } else { 12740ec72bbcSDaniel Dunbar Flags[ID] = Op; 12750ec72bbcSDaniel Dunbar } 12760ec72bbcSDaniel Dunbar } 12770ec72bbcSDaniel Dunbar 12780ec72bbcSDaniel Dunbar // Merge in the flags from the source module, and also collect its set of 12790ec72bbcSDaniel Dunbar // requirements. 128066f02413SBill Wendling bool HasErr = false; 12810ec72bbcSDaniel Dunbar for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) { 1282de36e804SDuncan P. N. Exon Smith MDNode *SrcOp = SrcModFlags->getOperand(I); 1283*5bf8fef5SDuncan P. N. Exon Smith ConstantInt *SrcBehavior = 1284*5bf8fef5SDuncan P. N. Exon Smith mdconst::extract<ConstantInt>(SrcOp->getOperand(0)); 12850ec72bbcSDaniel Dunbar MDString *ID = cast<MDString>(SrcOp->getOperand(1)); 12860ec72bbcSDaniel Dunbar MDNode *DstOp = Flags.lookup(ID); 12870ec72bbcSDaniel Dunbar unsigned SrcBehaviorValue = SrcBehavior->getZExtValue(); 128866f02413SBill Wendling 12890ec72bbcSDaniel Dunbar // If this is a requirement, add it and continue. 12900ec72bbcSDaniel Dunbar if (SrcBehaviorValue == Module::Require) { 12910ec72bbcSDaniel Dunbar // If the destination module does not already have this requirement, add 12920ec72bbcSDaniel Dunbar // it. 12930ec72bbcSDaniel Dunbar if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) { 12940ec72bbcSDaniel Dunbar DstModFlags->addOperand(SrcOp); 12950ec72bbcSDaniel Dunbar } 12960ec72bbcSDaniel Dunbar continue; 12970ec72bbcSDaniel Dunbar } 129866f02413SBill Wendling 12990ec72bbcSDaniel Dunbar // If there is no existing flag with this ID, just add it. 13000ec72bbcSDaniel Dunbar if (!DstOp) { 13010ec72bbcSDaniel Dunbar Flags[ID] = SrcOp; 13020ec72bbcSDaniel Dunbar DstModFlags->addOperand(SrcOp); 13030ec72bbcSDaniel Dunbar continue; 13040ec72bbcSDaniel Dunbar } 130566f02413SBill Wendling 13060ec72bbcSDaniel Dunbar // Otherwise, perform a merge. 1307*5bf8fef5SDuncan P. N. Exon Smith ConstantInt *DstBehavior = 1308*5bf8fef5SDuncan P. N. Exon Smith mdconst::extract<ConstantInt>(DstOp->getOperand(0)); 13090ec72bbcSDaniel Dunbar unsigned DstBehaviorValue = DstBehavior->getZExtValue(); 13100ec72bbcSDaniel Dunbar 13110ec72bbcSDaniel Dunbar // If either flag has override behavior, handle it first. 13120ec72bbcSDaniel Dunbar if (DstBehaviorValue == Module::Override) { 13130ec72bbcSDaniel Dunbar // Diagnose inconsistent flags which both have override behavior. 13140ec72bbcSDaniel Dunbar if (SrcBehaviorValue == Module::Override && 13150ec72bbcSDaniel Dunbar SrcOp->getOperand(2) != DstOp->getOperand(2)) { 13160ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + ID->getString() + 13170ec72bbcSDaniel Dunbar "': IDs have conflicting override values"); 13180ec72bbcSDaniel Dunbar } 13190ec72bbcSDaniel Dunbar continue; 13200ec72bbcSDaniel Dunbar } else if (SrcBehaviorValue == Module::Override) { 13210ec72bbcSDaniel Dunbar // Update the destination flag to that of the source. 1322*5bf8fef5SDuncan P. N. Exon Smith DstOp->replaceOperandWith(0, ConstantAsMetadata::get(SrcBehavior)); 13230ec72bbcSDaniel Dunbar DstOp->replaceOperandWith(2, SrcOp->getOperand(2)); 13240ec72bbcSDaniel Dunbar continue; 13250ec72bbcSDaniel Dunbar } 13260ec72bbcSDaniel Dunbar 13270ec72bbcSDaniel Dunbar // Diagnose inconsistent merge behavior types. 13280ec72bbcSDaniel Dunbar if (SrcBehaviorValue != DstBehaviorValue) { 13290ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + ID->getString() + 133066f02413SBill Wendling "': IDs have conflicting behaviors"); 13310ec72bbcSDaniel Dunbar continue; 133266f02413SBill Wendling } 133366f02413SBill Wendling 13340ec72bbcSDaniel Dunbar // Perform the merge for standard behavior types. 13350ec72bbcSDaniel Dunbar switch (SrcBehaviorValue) { 13360ec72bbcSDaniel Dunbar case Module::Require: 13372a30d788SCraig Topper case Module::Override: llvm_unreachable("not possible"); 13380ec72bbcSDaniel Dunbar case Module::Error: { 13390ec72bbcSDaniel Dunbar // Emit an error if the values differ. 13400ec72bbcSDaniel Dunbar if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { 13410ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + ID->getString() + 13420ec72bbcSDaniel Dunbar "': IDs have conflicting values"); 134366f02413SBill Wendling } 13440ec72bbcSDaniel Dunbar continue; 134566f02413SBill Wendling } 13460ec72bbcSDaniel Dunbar case Module::Warning: { 13470ec72bbcSDaniel Dunbar // Emit a warning if the values differ. 13480ec72bbcSDaniel Dunbar if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { 1349d12b4a33SRafael Espindola emitWarning("linking module flags '" + ID->getString() + 1350d12b4a33SRafael Espindola "': IDs have conflicting values"); 1351e17f3708SEli Bendersky } 13520ec72bbcSDaniel Dunbar continue; 13530ec72bbcSDaniel Dunbar } 1354d77d9fb0SDaniel Dunbar case Module::Append: { 1355d77d9fb0SDaniel Dunbar MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); 1356d77d9fb0SDaniel Dunbar MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); 1357*5bf8fef5SDuncan P. N. Exon Smith SmallVector<Metadata *, 8> MDs; 1358*5bf8fef5SDuncan P. N. Exon Smith MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands()); 1359*5bf8fef5SDuncan P. N. Exon Smith for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i) 1360*5bf8fef5SDuncan P. N. Exon Smith MDs.push_back(DstValue->getOperand(i)); 1361*5bf8fef5SDuncan P. N. Exon Smith for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i) 1362*5bf8fef5SDuncan P. N. Exon Smith MDs.push_back(SrcValue->getOperand(i)); 1363*5bf8fef5SDuncan P. N. Exon Smith DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(), MDs)); 1364d77d9fb0SDaniel Dunbar break; 1365d77d9fb0SDaniel Dunbar } 1366d77d9fb0SDaniel Dunbar case Module::AppendUnique: { 1367*5bf8fef5SDuncan P. N. Exon Smith SmallSetVector<Metadata *, 16> Elts; 1368d77d9fb0SDaniel Dunbar MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); 1369d77d9fb0SDaniel Dunbar MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); 1370d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i) 1371d77d9fb0SDaniel Dunbar Elts.insert(DstValue->getOperand(i)); 1372d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i) 1373d77d9fb0SDaniel Dunbar Elts.insert(SrcValue->getOperand(i)); 1374*5bf8fef5SDuncan P. N. Exon Smith DstOp->replaceOperandWith( 1375*5bf8fef5SDuncan P. N. Exon Smith 2, MDNode::get(DstM->getContext(), 1376*5bf8fef5SDuncan P. N. Exon Smith makeArrayRef(Elts.begin(), Elts.end()))); 1377d77d9fb0SDaniel Dunbar break; 1378d77d9fb0SDaniel Dunbar } 137966f02413SBill Wendling } 138066f02413SBill Wendling } 138166f02413SBill Wendling 13820ec72bbcSDaniel Dunbar // Check all of the requirements. 13830ec72bbcSDaniel Dunbar for (unsigned I = 0, E = Requirements.size(); I != E; ++I) { 13840ec72bbcSDaniel Dunbar MDNode *Requirement = Requirements[I]; 13850ec72bbcSDaniel Dunbar MDString *Flag = cast<MDString>(Requirement->getOperand(0)); 1386*5bf8fef5SDuncan P. N. Exon Smith Metadata *ReqValue = Requirement->getOperand(1); 13870ec72bbcSDaniel Dunbar 13880ec72bbcSDaniel Dunbar MDNode *Op = Flags[Flag]; 13890ec72bbcSDaniel Dunbar if (!Op || Op->getOperand(2) != ReqValue) { 13900ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + Flag->getString() + 13919273b539SBill Wendling "': does not have the required value"); 13920ec72bbcSDaniel Dunbar continue; 139366f02413SBill Wendling } 139466f02413SBill Wendling } 139566f02413SBill Wendling 139666f02413SBill Wendling return HasErr; 139766f02413SBill Wendling } 139866f02413SBill Wendling 1399b1ed91f3SChris Lattner bool ModuleLinker::run() { 140066f02413SBill Wendling assert(DstM && "Null destination module"); 140166f02413SBill Wendling assert(SrcM && "Null source module"); 1402b1ed91f3SChris Lattner 1403b1ed91f3SChris Lattner // Inherit the target data from the source module if the destination module 1404b1ed91f3SChris Lattner // doesn't have one already. 1405f863ee29SRafael Espindola if (!DstM->getDataLayout() && SrcM->getDataLayout()) 1406b1ed91f3SChris Lattner DstM->setDataLayout(SrcM->getDataLayout()); 1407b1ed91f3SChris Lattner 1408b1ed91f3SChris Lattner // Copy the target triple from the source to dest if the dest's is empty. 1409b1ed91f3SChris Lattner if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty()) 1410b1ed91f3SChris Lattner DstM->setTargetTriple(SrcM->getTargetTriple()); 1411b1ed91f3SChris Lattner 1412f863ee29SRafael Espindola if (SrcM->getDataLayout() && DstM->getDataLayout() && 1413ae593f15SRafael Espindola *SrcM->getDataLayout() != *DstM->getDataLayout()) { 1414d12b4a33SRafael Espindola emitWarning("Linking two modules of different data layouts: '" + 1415d12b4a33SRafael Espindola SrcM->getModuleIdentifier() + "' is '" + 1416d12b4a33SRafael Espindola SrcM->getDataLayoutStr() + "' whereas '" + 1417d12b4a33SRafael Espindola DstM->getModuleIdentifier() + "' is '" + 1418d12b4a33SRafael Espindola DstM->getDataLayoutStr() + "'\n"); 1419e17f3708SEli Bendersky } 1420b1ed91f3SChris Lattner if (!SrcM->getTargetTriple().empty() && 1421b1ed91f3SChris Lattner DstM->getTargetTriple() != SrcM->getTargetTriple()) { 1422d12b4a33SRafael Espindola emitWarning("Linking two modules of different target triples: " + 1423d12b4a33SRafael Espindola SrcM->getModuleIdentifier() + "' is '" + 1424d12b4a33SRafael Espindola SrcM->getTargetTriple() + "' whereas '" + 1425d12b4a33SRafael Espindola DstM->getModuleIdentifier() + "' is '" + 1426d12b4a33SRafael Espindola DstM->getTargetTriple() + "'\n"); 1427e17f3708SEli Bendersky } 1428b1ed91f3SChris Lattner 1429b1ed91f3SChris Lattner // Append the module inline asm string. 1430b1ed91f3SChris Lattner if (!SrcM->getModuleInlineAsm().empty()) { 1431b1ed91f3SChris Lattner if (DstM->getModuleInlineAsm().empty()) 1432b1ed91f3SChris Lattner DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm()); 1433b1ed91f3SChris Lattner else 1434b1ed91f3SChris Lattner DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+ 1435b1ed91f3SChris Lattner SrcM->getModuleInlineAsm()); 1436b1ed91f3SChris Lattner } 1437b1ed91f3SChris Lattner 1438b1ed91f3SChris Lattner // Loop over all of the linked values to compute type mappings. 1439b1ed91f3SChris Lattner computeTypeMapping(); 1440b1ed91f3SChris Lattner 1441dad0a645SDavid Majnemer ComdatsChosen.clear(); 14425106ce78SDavid Blaikie for (const auto &SMEC : SrcM->getComdatSymbolTable()) { 1443dad0a645SDavid Majnemer const Comdat &C = SMEC.getValue(); 1444dad0a645SDavid Majnemer if (ComdatsChosen.count(&C)) 1445dad0a645SDavid Majnemer continue; 1446dad0a645SDavid Majnemer Comdat::SelectionKind SK; 1447dad0a645SDavid Majnemer bool LinkFromSrc; 1448dad0a645SDavid Majnemer if (getComdatResult(&C, SK, LinkFromSrc)) 1449dad0a645SDavid Majnemer return true; 1450dad0a645SDavid Majnemer ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc); 1451dad0a645SDavid Majnemer } 1452dad0a645SDavid Majnemer 145309d84addSDuncan P. N. Exon Smith // Upgrade mismatched global arrays. 145409d84addSDuncan P. N. Exon Smith upgradeMismatchedGlobals(); 145509d84addSDuncan P. N. Exon Smith 1456b1ed91f3SChris Lattner // Insert all of the globals in src into the DstM module... without linking 1457b1ed91f3SChris Lattner // initializers (which could refer to functions not yet mapped over). 1458b1ed91f3SChris Lattner for (Module::global_iterator I = SrcM->global_begin(), 1459b1ed91f3SChris Lattner E = SrcM->global_end(); I != E; ++I) 1460778fcc77SRafael Espindola if (linkGlobalValueProto(I)) 1461b1ed91f3SChris Lattner return true; 1462b1ed91f3SChris Lattner 1463b1ed91f3SChris Lattner // Link the functions together between the two modules, without doing function 1464b1ed91f3SChris Lattner // bodies... this just adds external function prototypes to the DstM 1465b1ed91f3SChris Lattner // function... We do this so that when we begin processing function bodies, 1466b1ed91f3SChris Lattner // all of the global values that may be referenced are available in our 1467b1ed91f3SChris Lattner // ValueMap. 1468b1ed91f3SChris Lattner for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) 1469778fcc77SRafael Espindola if (linkGlobalValueProto(I)) 1470b1ed91f3SChris Lattner return true; 1471b1ed91f3SChris Lattner 1472b1ed91f3SChris Lattner // If there were any aliases, link them now. 1473b1ed91f3SChris Lattner for (Module::alias_iterator I = SrcM->alias_begin(), 1474b1ed91f3SChris Lattner E = SrcM->alias_end(); I != E; ++I) 1475778fcc77SRafael Espindola if (linkGlobalValueProto(I)) 1476b1ed91f3SChris Lattner return true; 1477b1ed91f3SChris Lattner 1478b1ed91f3SChris Lattner for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i) 1479b1ed91f3SChris Lattner linkAppendingVarInit(AppendingVars[i]); 1480b1ed91f3SChris Lattner 1481beadd56aSRafael Espindola for (const auto &Entry : DstM->getComdatSymbolTable()) { 1482beadd56aSRafael Espindola const Comdat &C = Entry.getValue(); 1483beadd56aSRafael Espindola if (C.getSelectionKind() == Comdat::Any) 1484beadd56aSRafael Espindola continue; 1485beadd56aSRafael Espindola const GlobalValue *GV = SrcM->getNamedValue(C.getName()); 1486beadd56aSRafael Espindola assert(GV); 1487beadd56aSRafael Espindola MapValue(GV, ValueMap, RF_None, &TypeMap, &ValMaterializer); 1488beadd56aSRafael Espindola } 1489beadd56aSRafael Espindola 1490b1ed91f3SChris Lattner // Link in the function bodies that are defined in the source module into 1491b1ed91f3SChris Lattner // DstM. 1492f97d0cbeSRafael Espindola for (Function &SF : *SrcM) { 1493d4bcefc7SRafael Espindola // Skip if no body (function is external). 1494f97d0cbeSRafael Espindola if (SF.isDeclaration()) 1495d4bcefc7SRafael Espindola continue; 1496d4bcefc7SRafael Espindola 1497f97d0cbeSRafael Espindola // Skip if not linking from source. 1498f97d0cbeSRafael Espindola if (DoNotLinkFromSource.count(&SF)) 1499f97d0cbeSRafael Espindola continue; 1500f97d0cbeSRafael Espindola 1501ef23711eSRafael Espindola if (linkGlobalValueBody(SF)) 150240d7ebedSRafael Espindola return true; 1503b1ed91f3SChris Lattner } 1504b1ed91f3SChris Lattner 1505b1ed91f3SChris Lattner // Resolve all uses of aliases with aliasees. 1506ef23711eSRafael Espindola for (GlobalAlias &Src : SrcM->aliases()) { 1507ef23711eSRafael Espindola if (DoNotLinkFromSource.count(&Src)) 1508ef23711eSRafael Espindola continue; 1509ef23711eSRafael Espindola linkGlobalValueBody(Src); 1510ef23711eSRafael Espindola } 1511b1ed91f3SChris Lattner 151266f02413SBill Wendling // Remap all of the named MDNodes in Src into the DstM module. We do this 15136ddbb2e2SDevang Patel // after linking GlobalValues so that MDNodes that reference GlobalValues 15146ddbb2e2SDevang Patel // are properly remapped. 15156ddbb2e2SDevang Patel linkNamedMDNodes(); 15166ddbb2e2SDevang Patel 151766f02413SBill Wendling // Merge the module flags into the DstM module. 151866f02413SBill Wendling if (linkModuleFlagsMetadata()) 151966f02413SBill Wendling return true; 152066f02413SBill Wendling 152191686d6dSBill Wendling // Update the initializers in the DstM module now that all globals that may 152291686d6dSBill Wendling // be referenced are in DstM. 1523ef23711eSRafael Espindola for (GlobalVariable &Src : SrcM->globals()) { 1524ef23711eSRafael Espindola // Only process initialized GV's or ones not already in dest. 1525ef23711eSRafael Espindola if (!Src.hasInitializer() || DoNotLinkFromSource.count(&Src)) 1526ef23711eSRafael Espindola continue; 1527ef23711eSRafael Espindola linkGlobalValueBody(Src); 1528ef23711eSRafael Espindola } 152991686d6dSBill Wendling 15300a48b877STanya Lattner // Process vector of lazily linked in functions. 1531ef23711eSRafael Espindola while (!LazilyLinkGlobalValues.empty()) { 1532ef23711eSRafael Espindola GlobalValue *SGV = LazilyLinkGlobalValues.back(); 1533ef23711eSRafael Espindola LazilyLinkGlobalValues.pop_back(); 15340a48b877STanya Lattner 15352770c2d6SMichael Ilseman if (auto F = dyn_cast<Function>(SGV)) 15362770c2d6SMichael Ilseman if (F->isDeclaration()) 15372770c2d6SMichael Ilseman continue; 1538ef23711eSRafael Espindola if (linkGlobalValueBody(*SGV)) 153940d7ebedSRafael Espindola return true; 15400a48b877STanya Lattner } 15410a48b877STanya Lattner 15422609888fSAnton Korobeynikov return false; 15432609888fSAnton Korobeynikov } 1544361e513dSReid Spencer 154531ad468dSRafael Espindola Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P) 154631ad468dSRafael Espindola : ETypes(E), IsPacked(P) {} 154731ad468dSRafael Espindola 154831ad468dSRafael Espindola Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST) 154931ad468dSRafael Espindola : ETypes(ST->elements()), IsPacked(ST->isPacked()) {} 155031ad468dSRafael Espindola 155131ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const { 155231ad468dSRafael Espindola if (IsPacked != That.IsPacked) 155331ad468dSRafael Espindola return false; 155431ad468dSRafael Espindola if (ETypes != That.ETypes) 155531ad468dSRafael Espindola return false; 155631ad468dSRafael Espindola return true; 155731ad468dSRafael Espindola } 155831ad468dSRafael Espindola 155931ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const { 156031ad468dSRafael Espindola return !this->operator==(That); 156131ad468dSRafael Espindola } 156231ad468dSRafael Espindola 156331ad468dSRafael Espindola StructType *Linker::StructTypeKeyInfo::getEmptyKey() { 156431ad468dSRafael Espindola return DenseMapInfo<StructType *>::getEmptyKey(); 156531ad468dSRafael Espindola } 156631ad468dSRafael Espindola 156731ad468dSRafael Espindola StructType *Linker::StructTypeKeyInfo::getTombstoneKey() { 156831ad468dSRafael Espindola return DenseMapInfo<StructType *>::getTombstoneKey(); 156931ad468dSRafael Espindola } 157031ad468dSRafael Espindola 157131ad468dSRafael Espindola unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) { 157231ad468dSRafael Espindola return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()), 157331ad468dSRafael Espindola Key.IsPacked); 157431ad468dSRafael Espindola } 157531ad468dSRafael Espindola 157631ad468dSRafael Espindola unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) { 157731ad468dSRafael Espindola return getHashValue(KeyTy(ST)); 157831ad468dSRafael Espindola } 157931ad468dSRafael Espindola 158031ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS, 158131ad468dSRafael Espindola const StructType *RHS) { 158231ad468dSRafael Espindola if (RHS == getEmptyKey() || RHS == getTombstoneKey()) 158331ad468dSRafael Espindola return false; 158431ad468dSRafael Espindola return LHS == KeyTy(RHS); 158531ad468dSRafael Espindola } 158631ad468dSRafael Espindola 158731ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS, 158831ad468dSRafael Espindola const StructType *RHS) { 158931ad468dSRafael Espindola if (RHS == getEmptyKey()) 159031ad468dSRafael Espindola return LHS == getEmptyKey(); 159131ad468dSRafael Espindola 159231ad468dSRafael Espindola if (RHS == getTombstoneKey()) 159331ad468dSRafael Espindola return LHS == getTombstoneKey(); 159431ad468dSRafael Espindola 159531ad468dSRafael Espindola return KeyTy(LHS) == KeyTy(RHS); 159631ad468dSRafael Espindola } 159731ad468dSRafael Espindola 159831ad468dSRafael Espindola void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) { 159931ad468dSRafael Espindola assert(!Ty->isOpaque()); 16003280a5d9SBenjamin Kramer NonOpaqueStructTypes.insert(Ty); 160131ad468dSRafael Espindola } 160231ad468dSRafael Espindola 160331ad468dSRafael Espindola void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) { 160431ad468dSRafael Espindola assert(Ty->isOpaque()); 160531ad468dSRafael Espindola OpaqueStructTypes.insert(Ty); 160631ad468dSRafael Espindola } 160731ad468dSRafael Espindola 160831ad468dSRafael Espindola StructType * 160931ad468dSRafael Espindola Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes, 161031ad468dSRafael Espindola bool IsPacked) { 161131ad468dSRafael Espindola Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked); 161231ad468dSRafael Espindola auto I = NonOpaqueStructTypes.find_as(Key); 161331ad468dSRafael Espindola if (I == NonOpaqueStructTypes.end()) 161431ad468dSRafael Espindola return nullptr; 16153280a5d9SBenjamin Kramer return *I; 161631ad468dSRafael Espindola } 161731ad468dSRafael Espindola 161831ad468dSRafael Espindola bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) { 161931ad468dSRafael Espindola if (Ty->isOpaque()) 162031ad468dSRafael Espindola return OpaqueStructTypes.count(Ty); 162131ad468dSRafael Espindola auto I = NonOpaqueStructTypes.find(Ty); 162231ad468dSRafael Espindola if (I == NonOpaqueStructTypes.end()) 162331ad468dSRafael Espindola return false; 16243280a5d9SBenjamin Kramer return *I == Ty; 162531ad468dSRafael Espindola } 162631ad468dSRafael Espindola 16275cb9c82aSRafael Espindola void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) { 16285cb9c82aSRafael Espindola this->Composite = M; 16295cb9c82aSRafael Espindola this->DiagnosticHandler = DiagnosticHandler; 1630a4e85e3dSRafael Espindola 1631a4e85e3dSRafael Espindola TypeFinder StructTypes; 1632a4e85e3dSRafael Espindola StructTypes.run(*M, true); 163331ad468dSRafael Espindola for (StructType *Ty : StructTypes) { 163431ad468dSRafael Espindola if (Ty->isOpaque()) 163531ad468dSRafael Espindola IdentifiedStructTypes.addOpaque(Ty); 163631ad468dSRafael Espindola else 163731ad468dSRafael Espindola IdentifiedStructTypes.addNonOpaque(Ty); 163831ad468dSRafael Espindola } 1639aa9918aaSRafael Espindola } 16403df61b7bSRafael Espindola 16415cb9c82aSRafael Espindola Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) { 16425cb9c82aSRafael Espindola init(M, DiagnosticHandler); 16435cb9c82aSRafael Espindola } 16445cb9c82aSRafael Espindola 16455cb9c82aSRafael Espindola Linker::Linker(Module *M) { 16465cb9c82aSRafael Espindola init(M, [this](const DiagnosticInfo &DI) { 16475cb9c82aSRafael Espindola Composite->getContext().diagnose(DI); 16485cb9c82aSRafael Espindola }); 16495cb9c82aSRafael Espindola } 16505cb9c82aSRafael Espindola 16513df61b7bSRafael Espindola Linker::~Linker() { 16523df61b7bSRafael Espindola } 16533df61b7bSRafael Espindola 165491e6f6e1SBill Wendling void Linker::deleteModule() { 165591e6f6e1SBill Wendling delete Composite; 16562617dcceSCraig Topper Composite = nullptr; 165791e6f6e1SBill Wendling } 165891e6f6e1SBill Wendling 16599f8eff31SRafael Espindola bool Linker::linkInModule(Module *Src) { 1660a4e85e3dSRafael Espindola ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, 1661a4e85e3dSRafael Espindola DiagnosticHandler); 1662d12b4a33SRafael Espindola return TheLinker.run(); 16633df61b7bSRafael Espindola } 16643df61b7bSRafael Espindola 1665b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 1666b1ed91f3SChris Lattner // LinkModules entrypoint. 1667b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 1668b1ed91f3SChris Lattner 166918c89411SRafael Espindola /// This function links two modules together, with the resulting Dest module 167018c89411SRafael Espindola /// modified to be the composite of the two input modules. If an error occurs, 167118c89411SRafael Espindola /// true is returned and ErrorMsg (if not null) is set to indicate the problem. 167218c89411SRafael Espindola /// Upon failure, the Dest module could be in a modified state, and shouldn't be 167318c89411SRafael Espindola /// relied on to be consistent. 16749f8eff31SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src, 16754160f5d3SRafael Espindola DiagnosticHandlerFunction DiagnosticHandler) { 16764160f5d3SRafael Espindola Linker L(Dest, DiagnosticHandler); 16779f8eff31SRafael Espindola return L.linkInModule(Src); 16784160f5d3SRafael Espindola } 16794160f5d3SRafael Espindola 16809f8eff31SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src) { 1681287f18b4SRafael Espindola Linker L(Dest); 16829f8eff31SRafael Espindola return L.linkInModule(Src); 1683361e513dSReid Spencer } 1684a3aeb980SBill Wendling 1685a3aeb980SBill Wendling //===----------------------------------------------------------------------===// 1686a3aeb980SBill Wendling // C API. 1687a3aeb980SBill Wendling //===----------------------------------------------------------------------===// 1688a3aeb980SBill Wendling 1689a3aeb980SBill Wendling LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src, 1690a3aeb980SBill Wendling LLVMLinkerMode Mode, char **OutMessages) { 169198ab63ceSRafael Espindola Module *D = unwrap(Dest); 169298ab63ceSRafael Espindola std::string Message; 16934160f5d3SRafael Espindola raw_string_ostream Stream(Message); 16944160f5d3SRafael Espindola DiagnosticPrinterRawOStream DP(Stream); 16954160f5d3SRafael Espindola 16964160f5d3SRafael Espindola LLVMBool Result = Linker::LinkModules( 16979f8eff31SRafael Espindola D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); }); 169898ab63ceSRafael Espindola 169998ab63ceSRafael Espindola if (OutMessages && Result) 170098ab63ceSRafael Espindola *OutMessages = strdup(Message.c_str()); 1701a3aeb980SBill Wendling return Result; 1702a3aeb980SBill Wendling } 1703