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"
21c43df518SAkira Hatanaka #include "llvm/ADT/Triple.h"
229fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
23fda0cee7SDuncan P. N. Exon Smith #include "llvm/IR/DebugInfo.h"
24d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticInfo.h"
25d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticPrinter.h"
26d12b4a33SRafael Espindola #include "llvm/IR/LLVMContext.h"
279fb823bbSChandler Carruth #include "llvm/IR/Module.h"
28dcb603feSChandler Carruth #include "llvm/IR/TypeFinder.h"
29e17f3708SEli Bendersky #include "llvm/Support/CommandLine.h"
30b6af2f36SBill Wendling #include "llvm/Support/Debug.h"
31b6af2f36SBill Wendling #include "llvm/Support/raw_ostream.h"
32cbb91408STanya Lattner #include "llvm/Transforms/Utils/Cloning.h"
33981af002SWill Dietz #include <cctype>
3482d6ff6bSDavid Majnemer #include <tuple>
35361e513dSReid Spencer using namespace llvm;
36361e513dSReid Spencer 
37e17f3708SEli Bendersky 
38b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
39b1ed91f3SChris Lattner // TypeMap implementation.
40b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
41b1ed91f3SChris Lattner 
42b1ed91f3SChris Lattner namespace {
43b1ed91f3SChris Lattner class TypeMapTy : public ValueMapTypeRemapper {
4418c89411SRafael Espindola   /// This is a mapping from a source type to a destination type to use.
45b1ed91f3SChris Lattner   DenseMap<Type*, Type*> MappedTypes;
46b1ed91f3SChris Lattner 
4718c89411SRafael Espindola   /// When checking to see if two subgraphs are isomorphic, we speculatively
4818c89411SRafael Espindola   /// add types to MappedTypes, but keep track of them here in case we need to
4918c89411SRafael Espindola   /// roll back.
50b1ed91f3SChris Lattner   SmallVector<Type*, 16> SpeculativeTypes;
51b1ed91f3SChris Lattner 
52a96f235cSRafael Espindola   SmallVector<StructType*, 16> SpeculativeDstOpaqueTypes;
53a96f235cSRafael Espindola 
5418c89411SRafael Espindola   /// This is a list of non-opaque structs in the source module that are mapped
5518c89411SRafael Espindola   /// to an opaque struct in the destination module.
565e3bd972SChris Lattner   SmallVector<StructType*, 16> SrcDefinitionsToResolve;
575e3bd972SChris Lattner 
5818c89411SRafael Espindola   /// This is the set of opaque types in the destination modules who are
5918c89411SRafael Espindola   /// getting a body from the source module.
605e3bd972SChris Lattner   SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
61d48b7783SBill Wendling 
628c2cc416SBill Wendling public:
6331ad468dSRafael Espindola   TypeMapTy(Linker::IdentifiedStructTypeSet &DstStructTypesSet)
6431ad468dSRafael Espindola       : DstStructTypesSet(DstStructTypesSet) {}
65aa9918aaSRafael Espindola 
6631ad468dSRafael Espindola   Linker::IdentifiedStructTypeSet &DstStructTypesSet;
6718c89411SRafael Espindola   /// Indicate that the specified type in the destination module is conceptually
6818c89411SRafael Espindola   /// equivalent to the specified type in the source module.
69b1ed91f3SChris Lattner   void addTypeMapping(Type *DstTy, Type *SrcTy);
70b1ed91f3SChris Lattner 
71d2a13a2eSRafael Espindola   /// Produce a body for an opaque type in the dest module from a type
72d2a13a2eSRafael Espindola   /// definition in the source module.
73b1ed91f3SChris Lattner   void linkDefinedTypeBodies();
74b1ed91f3SChris Lattner 
7518c89411SRafael Espindola   /// Return the mapped type to use for the specified input type from the
76b1ed91f3SChris Lattner   /// source module.
77b1ed91f3SChris Lattner   Type *get(Type *SrcTy);
7831ad468dSRafael Espindola   Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
7931ad468dSRafael Espindola 
8031ad468dSRafael Espindola   void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
81b1ed91f3SChris Lattner 
82290e2cc5SRafael Espindola   FunctionType *get(FunctionType *T) {
83290e2cc5SRafael Espindola     return cast<FunctionType>(get((Type *)T));
84290e2cc5SRafael Espindola   }
85b1ed91f3SChris Lattner 
8618c89411SRafael Espindola   /// Dump out the type map for debugging purposes.
87b6af2f36SBill Wendling   void dump() const {
888f14471eSRafael Espindola     for (auto &Pair : MappedTypes) {
89b6af2f36SBill Wendling       dbgs() << "TypeMap: ";
908f14471eSRafael Espindola       Pair.first->print(dbgs());
91b6af2f36SBill Wendling       dbgs() << " => ";
928f14471eSRafael Espindola       Pair.second->print(dbgs());
93b6af2f36SBill Wendling       dbgs() << '\n';
94b6af2f36SBill Wendling     }
95b6af2f36SBill Wendling   }
96b6af2f36SBill Wendling 
97b1ed91f3SChris Lattner private:
98290e2cc5SRafael Espindola   Type *remapType(Type *SrcTy) override { return get(SrcTy); }
99b1ed91f3SChris Lattner 
100b1ed91f3SChris Lattner   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
101b1ed91f3SChris Lattner };
102f00654e3SAlexander Kornienko }
103b1ed91f3SChris Lattner 
104b1ed91f3SChris Lattner void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
1053d097410SRafael Espindola   assert(SpeculativeTypes.empty());
106a96f235cSRafael Espindola   assert(SpeculativeDstOpaqueTypes.empty());
1073d097410SRafael Espindola 
108b1ed91f3SChris Lattner   // Check to see if these types are recursively isomorphic and establish a
109b1ed91f3SChris Lattner   // mapping between them if so.
110c586eaa1SDuncan P. N. Exon Smith   if (!areTypesIsomorphic(DstTy, SrcTy)) {
111b1ed91f3SChris Lattner     // Oops, they aren't isomorphic.  Just discard this request by rolling out
112b1ed91f3SChris Lattner     // any speculative mappings we've established.
1133d097410SRafael Espindola     for (Type *Ty : SpeculativeTypes)
1143d097410SRafael Espindola       MappedTypes.erase(Ty);
115a96f235cSRafael Espindola 
116a96f235cSRafael Espindola     SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
117a96f235cSRafael Espindola                                    SpeculativeDstOpaqueTypes.size());
118a96f235cSRafael Espindola     for (StructType *Ty : SpeculativeDstOpaqueTypes)
119a96f235cSRafael Espindola       DstResolvedOpaqueTypes.erase(Ty);
12004a74af7SRafael Espindola   } else {
12104a74af7SRafael Espindola     for (Type *Ty : SpeculativeTypes)
12204a74af7SRafael Espindola       if (auto *STy = dyn_cast<StructType>(Ty))
12304a74af7SRafael Espindola         if (STy->hasName())
12404a74af7SRafael Espindola           STy->setName("");
125d48b7783SBill Wendling   }
126b1ed91f3SChris Lattner   SpeculativeTypes.clear();
127a96f235cSRafael Espindola   SpeculativeDstOpaqueTypes.clear();
128b1ed91f3SChris Lattner }
129b1ed91f3SChris Lattner 
13018c89411SRafael Espindola /// Recursively walk this pair of types, returning true if they are isomorphic,
13118c89411SRafael Espindola /// false if they are not.
132b1ed91f3SChris Lattner bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
133b1ed91f3SChris Lattner   // Two types with differing kinds are clearly not isomorphic.
134290e2cc5SRafael Espindola   if (DstTy->getTypeID() != SrcTy->getTypeID())
135290e2cc5SRafael Espindola     return false;
136b1ed91f3SChris Lattner 
137b1ed91f3SChris Lattner   // If we have an entry in the MappedTypes table, then we have our answer.
138b1ed91f3SChris Lattner   Type *&Entry = MappedTypes[SrcTy];
139b1ed91f3SChris Lattner   if (Entry)
140b1ed91f3SChris Lattner     return Entry == DstTy;
141b1ed91f3SChris Lattner 
142b1ed91f3SChris Lattner   // Two identical types are clearly isomorphic.  Remember this
143b1ed91f3SChris Lattner   // non-speculatively.
144b1ed91f3SChris Lattner   if (DstTy == SrcTy) {
145b1ed91f3SChris Lattner     Entry = DstTy;
146361e513dSReid Spencer     return true;
147361e513dSReid Spencer   }
148361e513dSReid Spencer 
149b1ed91f3SChris Lattner   // Okay, we have two types with identical kinds that we haven't seen before.
150361e513dSReid Spencer 
151b1ed91f3SChris Lattner   // If this is an opaque struct type, special case it.
152b1ed91f3SChris Lattner   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
153b1ed91f3SChris Lattner     // Mapping an opaque type to any struct, just keep the dest struct.
154b1ed91f3SChris Lattner     if (SSTy->isOpaque()) {
155b1ed91f3SChris Lattner       Entry = DstTy;
156b1ed91f3SChris Lattner       SpeculativeTypes.push_back(SrcTy);
157b1ed91f3SChris Lattner       return true;
158361e513dSReid Spencer     }
159b1ed91f3SChris Lattner 
1605e3bd972SChris Lattner     // Mapping a non-opaque source type to an opaque dest.  If this is the first
1615e3bd972SChris Lattner     // type that we're mapping onto this destination type then we succeed.  Keep
162a96f235cSRafael Espindola     // the dest, but fill it in later. If this is the second (different) type
163a96f235cSRafael Espindola     // that we're trying to map onto the same opaque type then we fail.
164b1ed91f3SChris Lattner     if (cast<StructType>(DstTy)->isOpaque()) {
1655e3bd972SChris Lattner       // We can only map one source type onto the opaque destination type.
16670573dcdSDavid Blaikie       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
1675e3bd972SChris Lattner         return false;
1685e3bd972SChris Lattner       SrcDefinitionsToResolve.push_back(SSTy);
169a96f235cSRafael Espindola       SpeculativeTypes.push_back(SrcTy);
170a96f235cSRafael Espindola       SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
171b1ed91f3SChris Lattner       Entry = DstTy;
172b1ed91f3SChris Lattner       return true;
173b1ed91f3SChris Lattner     }
174b1ed91f3SChris Lattner   }
175b1ed91f3SChris Lattner 
176b1ed91f3SChris Lattner   // If the number of subtypes disagree between the two types, then we fail.
177b1ed91f3SChris Lattner   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
178b1ed91f3SChris Lattner     return false;
179b1ed91f3SChris Lattner 
180b1ed91f3SChris Lattner   // Fail if any of the extra properties (e.g. array size) of the type disagree.
181b1ed91f3SChris Lattner   if (isa<IntegerType>(DstTy))
182b1ed91f3SChris Lattner     return false;  // bitwidth disagrees.
183b1ed91f3SChris Lattner   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
184b1ed91f3SChris Lattner     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
185b1ed91f3SChris Lattner       return false;
186eaf9b762SChris Lattner 
187b1ed91f3SChris Lattner   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
188b1ed91f3SChris Lattner     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
189b1ed91f3SChris Lattner       return false;
190b1ed91f3SChris Lattner   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
191b1ed91f3SChris Lattner     StructType *SSTy = cast<StructType>(SrcTy);
19244f7ab45SChris Lattner     if (DSTy->isLiteral() != SSTy->isLiteral() ||
193b1ed91f3SChris Lattner         DSTy->isPacked() != SSTy->isPacked())
194b1ed91f3SChris Lattner       return false;
195b1ed91f3SChris Lattner   } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
196b1ed91f3SChris Lattner     if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
197b1ed91f3SChris Lattner       return false;
198b1ed91f3SChris Lattner   } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
1995fad3e9aSJoey Gouly     if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
200361e513dSReid Spencer       return false;
201361e513dSReid Spencer   }
202361e513dSReid Spencer 
203b1ed91f3SChris Lattner   // Otherwise, we speculate that these two types will line up and recursively
204b1ed91f3SChris Lattner   // check the subelements.
205b1ed91f3SChris Lattner   Entry = DstTy;
206b1ed91f3SChris Lattner   SpeculativeTypes.push_back(SrcTy);
207eee6f995SChris Lattner 
208290e2cc5SRafael Espindola   for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
209290e2cc5SRafael Espindola     if (!areTypesIsomorphic(DstTy->getContainedType(I),
210290e2cc5SRafael Espindola                             SrcTy->getContainedType(I)))
211b1ed91f3SChris Lattner       return false;
212eee6f995SChris Lattner 
213b1ed91f3SChris Lattner   // If everything seems to have lined up, then everything is great.
214eee6f995SChris Lattner   return true;
215eee6f995SChris Lattner }
216eee6f995SChris Lattner 
217b1ed91f3SChris Lattner void TypeMapTy::linkDefinedTypeBodies() {
218b1ed91f3SChris Lattner   SmallVector<Type*, 16> Elements;
219c81c3f55SRafael Espindola   for (StructType *SrcSTy : SrcDefinitionsToResolve) {
220b1ed91f3SChris Lattner     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
221c81c3f55SRafael Espindola     assert(DstSTy->isOpaque());
222b1ed91f3SChris Lattner 
223b1ed91f3SChris Lattner     // Map the body of the source type over to a new body for the dest type.
224b1ed91f3SChris Lattner     Elements.resize(SrcSTy->getNumElements());
225290e2cc5SRafael Espindola     for (unsigned I = 0, E = Elements.size(); I != E; ++I)
226c81c3f55SRafael Espindola       Elements[I] = get(SrcSTy->getElementType(I));
227b1ed91f3SChris Lattner 
228b1ed91f3SChris Lattner     DstSTy->setBody(Elements, SrcSTy->isPacked());
229a5b9e1cfSRafael Espindola     DstStructTypesSet.switchToNonOpaque(DstSTy);
230b1ed91f3SChris Lattner   }
231c81c3f55SRafael Espindola   SrcDefinitionsToResolve.clear();
2325e3bd972SChris Lattner   DstResolvedOpaqueTypes.clear();
233eee6f995SChris Lattner }
234eee6f995SChris Lattner 
23531ad468dSRafael Espindola void TypeMapTy::finishType(StructType *DTy, StructType *STy,
23631ad468dSRafael Espindola                            ArrayRef<Type *> ETypes) {
23731ad468dSRafael Espindola   DTy->setBody(ETypes, STy->isPacked());
238a4e85e3dSRafael Espindola 
23931ad468dSRafael Espindola   // Steal STy's name.
24031ad468dSRafael Espindola   if (STy->hasName()) {
24131ad468dSRafael Espindola     SmallString<16> TmpName = STy->getName();
24231ad468dSRafael Espindola     STy->setName("");
24331ad468dSRafael Espindola     DTy->setName(TmpName);
24431ad468dSRafael Espindola   }
24531ad468dSRafael Espindola 
24631ad468dSRafael Espindola   DstStructTypesSet.addNonOpaque(DTy);
24731ad468dSRafael Espindola }
24831ad468dSRafael Espindola 
24931ad468dSRafael Espindola Type *TypeMapTy::get(Type *Ty) {
25031ad468dSRafael Espindola   SmallPtrSet<StructType *, 8> Visited;
25131ad468dSRafael Espindola   return get(Ty, Visited);
25231ad468dSRafael Espindola }
25331ad468dSRafael Espindola 
25431ad468dSRafael Espindola Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
255b1ed91f3SChris Lattner   // If we already have an entry for this type, return it.
256b1ed91f3SChris Lattner   Type **Entry = &MappedTypes[Ty];
257290e2cc5SRafael Espindola   if (*Entry)
258290e2cc5SRafael Espindola     return *Entry;
259b1ed91f3SChris Lattner 
26031ad468dSRafael Espindola   // These are types that LLVM itself will unique.
26131ad468dSRafael Espindola   bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
26231ad468dSRafael Espindola 
26331ad468dSRafael Espindola #ifndef NDEBUG
26431ad468dSRafael Espindola   if (!IsUniqued) {
26531ad468dSRafael Espindola     for (auto &Pair : MappedTypes) {
26631ad468dSRafael Espindola       assert(!(Pair.first != Ty && Pair.second == Ty) &&
26731ad468dSRafael Espindola              "mapping to a source type");
26831ad468dSRafael Espindola     }
26931ad468dSRafael Espindola   }
27031ad468dSRafael Espindola #endif
27131ad468dSRafael Espindola 
27231ad468dSRafael Espindola   if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
27331ad468dSRafael Espindola     StructType *DTy = StructType::create(Ty->getContext());
27431ad468dSRafael Espindola     return *Entry = DTy;
27531ad468dSRafael Espindola   }
27631ad468dSRafael Espindola 
27731ad468dSRafael Espindola   // If this is not a recursive type, then just map all of the elements and
278b1ed91f3SChris Lattner   // then rebuild the type from inside out.
27931ad468dSRafael Espindola   SmallVector<Type *, 4> ElementTypes;
28031ad468dSRafael Espindola 
281b1ed91f3SChris Lattner   // If there are no element types to map, then the type is itself.  This is
282b1ed91f3SChris Lattner   // true for the anonymous {} struct, things like 'float', integers, etc.
28331ad468dSRafael Espindola   if (Ty->getNumContainedTypes() == 0 && IsUniqued)
284b1ed91f3SChris Lattner     return *Entry = Ty;
285b1ed91f3SChris Lattner 
286b1ed91f3SChris Lattner   // Remap all of the elements, keeping track of whether any of them change.
287b1ed91f3SChris Lattner   bool AnyChange = false;
288b1ed91f3SChris Lattner   ElementTypes.resize(Ty->getNumContainedTypes());
289290e2cc5SRafael Espindola   for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
29031ad468dSRafael Espindola     ElementTypes[I] = get(Ty->getContainedType(I), Visited);
291290e2cc5SRafael Espindola     AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
292eee6f995SChris Lattner   }
293b1ed91f3SChris Lattner 
294b1ed91f3SChris Lattner   // If we found our type while recursively processing stuff, just use it.
295b1ed91f3SChris Lattner   Entry = &MappedTypes[Ty];
29631ad468dSRafael Espindola   if (*Entry) {
29731ad468dSRafael Espindola     if (auto *DTy = dyn_cast<StructType>(*Entry)) {
29831ad468dSRafael Espindola       if (DTy->isOpaque()) {
29931ad468dSRafael Espindola         auto *STy = cast<StructType>(Ty);
30031ad468dSRafael Espindola         finishType(DTy, STy, ElementTypes);
30131ad468dSRafael Espindola       }
30231ad468dSRafael Espindola     }
303290e2cc5SRafael Espindola     return *Entry;
30431ad468dSRafael Espindola   }
305b1ed91f3SChris Lattner 
30631ad468dSRafael Espindola   // If all of the element types mapped directly over and the type is not
30731ad468dSRafael Espindola   // a nomed struct, then the type is usable as-is.
30831ad468dSRafael Espindola   if (!AnyChange && IsUniqued)
309b1ed91f3SChris Lattner     return *Entry = Ty;
310b1ed91f3SChris Lattner 
311b1ed91f3SChris Lattner   // Otherwise, rebuild a modified type.
312b1ed91f3SChris Lattner   switch (Ty->getTypeID()) {
313290e2cc5SRafael Espindola   default:
314290e2cc5SRafael Espindola     llvm_unreachable("unknown derived type to remap");
315b1ed91f3SChris Lattner   case Type::ArrayTyID:
316b1ed91f3SChris Lattner     return *Entry = ArrayType::get(ElementTypes[0],
317b1ed91f3SChris Lattner                                    cast<ArrayType>(Ty)->getNumElements());
318b1ed91f3SChris Lattner   case Type::VectorTyID:
319b1ed91f3SChris Lattner     return *Entry = VectorType::get(ElementTypes[0],
320b1ed91f3SChris Lattner                                     cast<VectorType>(Ty)->getNumElements());
321b1ed91f3SChris Lattner   case Type::PointerTyID:
32231ad468dSRafael Espindola     return *Entry = PointerType::get(ElementTypes[0],
32331ad468dSRafael Espindola                                      cast<PointerType>(Ty)->getAddressSpace());
324b1ed91f3SChris Lattner   case Type::FunctionTyID:
325b1ed91f3SChris Lattner     return *Entry = FunctionType::get(ElementTypes[0],
326717d7eddSFrits van Bommel                                       makeArrayRef(ElementTypes).slice(1),
327b1ed91f3SChris Lattner                                       cast<FunctionType>(Ty)->isVarArg());
32831ad468dSRafael Espindola   case Type::StructTyID: {
32931ad468dSRafael Espindola     auto *STy = cast<StructType>(Ty);
33031ad468dSRafael Espindola     bool IsPacked = STy->isPacked();
33131ad468dSRafael Espindola     if (IsUniqued)
33231ad468dSRafael Espindola       return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
333b1ed91f3SChris Lattner 
334b1ed91f3SChris Lattner     // If the type is opaque, we can just use it directly.
335aa9918aaSRafael Espindola     if (STy->isOpaque()) {
33631ad468dSRafael Espindola       DstStructTypesSet.addOpaque(STy);
33731ad468dSRafael Espindola       return *Entry = Ty;
338aa9918aaSRafael Espindola     }
339b1ed91f3SChris Lattner 
34031ad468dSRafael Espindola     if (StructType *OldT =
34131ad468dSRafael Espindola             DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
342c81c3f55SRafael Espindola       STy->setName("");
34331ad468dSRafael Espindola       return *Entry = OldT;
344c81c3f55SRafael Espindola     }
345c81c3f55SRafael Espindola 
34631ad468dSRafael Espindola     if (!AnyChange) {
34731ad468dSRafael Espindola       DstStructTypesSet.addNonOpaque(STy);
34831ad468dSRafael Espindola       return *Entry = Ty;
34931ad468dSRafael Espindola     }
35031ad468dSRafael Espindola 
35131ad468dSRafael Espindola     StructType *DTy = StructType::create(Ty->getContext());
35231ad468dSRafael Espindola     finishType(DTy, STy, ElementTypes);
35331ad468dSRafael Espindola     return *Entry = DTy;
35431ad468dSRafael Espindola   }
35531ad468dSRafael Espindola   }
356b1ed91f3SChris Lattner }
357b1ed91f3SChris Lattner 
358b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
359b1ed91f3SChris Lattner // ModuleLinker implementation.
360b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
361b1ed91f3SChris Lattner 
362b1ed91f3SChris Lattner namespace {
363f6f121e2SJames Molloy class ModuleLinker;
364f6f121e2SJames Molloy 
36518c89411SRafael Espindola /// Creates prototypes for functions that are lazily linked on the fly. This
36618c89411SRafael Espindola /// speeds up linking for modules with many/ lazily linked functions of which
36718c89411SRafael Espindola /// few get used.
368*437aafdaSDavid Blaikie class ValueMaterializerTy final : public ValueMaterializer {
369f6f121e2SJames Molloy   TypeMapTy &TypeMap;
370f6f121e2SJames Molloy   Module *DstM;
371ef23711eSRafael Espindola   std::vector<GlobalValue *> &LazilyLinkGlobalValues;
372c84f608bSRafael Espindola 
373f6f121e2SJames Molloy public:
374f6f121e2SJames Molloy   ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
375ef23711eSRafael Espindola                       std::vector<GlobalValue *> &LazilyLinkGlobalValues)
376c84f608bSRafael Espindola       : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
377ef23711eSRafael Espindola         LazilyLinkGlobalValues(LazilyLinkGlobalValues) {}
378f6f121e2SJames Molloy 
3798548299aSCraig Topper   Value *materializeValueFor(Value *V) override;
380f6f121e2SJames Molloy };
381f6f121e2SJames Molloy 
382d12b4a33SRafael Espindola class LinkDiagnosticInfo : public DiagnosticInfo {
383d12b4a33SRafael Espindola   const Twine &Msg;
384d12b4a33SRafael Espindola 
385d12b4a33SRafael Espindola public:
386d12b4a33SRafael Espindola   LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
387d12b4a33SRafael Espindola   void print(DiagnosticPrinter &DP) const override;
388d12b4a33SRafael Espindola };
389d12b4a33SRafael Espindola LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
390d12b4a33SRafael Espindola                                        const Twine &Msg)
391d12b4a33SRafael Espindola     : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
392d12b4a33SRafael Espindola void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
393d12b4a33SRafael Espindola 
39418c89411SRafael Espindola /// This is an implementation class for the LinkModules function, which is the
39518c89411SRafael Espindola /// entrypoint for this file.
396b1ed91f3SChris Lattner class ModuleLinker {
397b1ed91f3SChris Lattner   Module *DstM, *SrcM;
398b1ed91f3SChris Lattner 
399b1ed91f3SChris Lattner   TypeMapTy TypeMap;
400f6f121e2SJames Molloy   ValueMaterializerTy ValMaterializer;
401b1ed91f3SChris Lattner 
40218c89411SRafael Espindola   /// Mapping of values from what they used to be in Src, to what they are now
40318c89411SRafael Espindola   /// in DstM.  ValueToValueMapTy is a ValueMap, which involves some overhead
40418c89411SRafael Espindola   /// due to the use of Value handles which the Linker doesn't actually need,
40518c89411SRafael Espindola   /// but this allows us to reuse the ValueMapper code.
406b1ed91f3SChris Lattner   ValueToValueMapTy ValueMap;
407b1ed91f3SChris Lattner 
408b1ed91f3SChris Lattner   struct AppendingVarInfo {
409b1ed91f3SChris Lattner     GlobalVariable *NewGV;   // New aggregate global in dest module.
4103e8bc6a8SRafael Espindola     const Constant *DstInit; // Old initializer from dest module.
4113e8bc6a8SRafael Espindola     const Constant *SrcInit; // Old initializer from src module.
412b1ed91f3SChris Lattner   };
413b1ed91f3SChris Lattner 
414b1ed91f3SChris Lattner   std::vector<AppendingVarInfo> AppendingVars;
415b1ed91f3SChris Lattner 
416cbb91408STanya Lattner   // Set of items not to link in from source.
417cbb91408STanya Lattner   SmallPtrSet<const Value *, 16> DoNotLinkFromSource;
418cbb91408STanya Lattner 
419ef23711eSRafael Espindola   // Vector of GlobalValues to lazily link in.
420ef23711eSRafael Espindola   std::vector<GlobalValue *> LazilyLinkGlobalValues;
4210a48b877STanya Lattner 
422fda0cee7SDuncan P. N. Exon Smith   /// Functions that have replaced other functions.
423fda0cee7SDuncan P. N. Exon Smith   SmallPtrSet<const Function *, 16> OverridingFunctions;
424fda0cee7SDuncan P. N. Exon Smith 
425d0b23befSRafael Espindola   DiagnosticHandlerFunction DiagnosticHandler;
4264160f5d3SRafael Espindola 
427e868123dSDuncan P. N. Exon Smith   /// For symbol clashes, prefer those from Src.
428020d4fb1SArtem Belevich   unsigned Flags;
429e868123dSDuncan P. N. Exon Smith 
430b1ed91f3SChris Lattner public:
43131ad468dSRafael Espindola   ModuleLinker(Module *dstM, Linker::IdentifiedStructTypeSet &Set, Module *srcM,
432020d4fb1SArtem Belevich                DiagnosticHandlerFunction DiagnosticHandler, unsigned Flags)
433a4e85e3dSRafael Espindola       : DstM(dstM), SrcM(srcM), TypeMap(Set),
434ef23711eSRafael Espindola         ValMaterializer(TypeMap, DstM, LazilyLinkGlobalValues),
435020d4fb1SArtem Belevich         DiagnosticHandler(DiagnosticHandler), Flags(Flags) {}
436b1ed91f3SChris Lattner 
437b1ed91f3SChris Lattner   bool run();
438b1ed91f3SChris Lattner 
439020d4fb1SArtem Belevich   bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
440020d4fb1SArtem Belevich   bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
441020d4fb1SArtem Belevich   bool shouldInternalizeLinkedSymbols() {
442020d4fb1SArtem Belevich     return Flags & Linker::InternalizeLinkedSymbols;
443020d4fb1SArtem Belevich   }
444020d4fb1SArtem Belevich 
445b1ed91f3SChris Lattner private:
446d12b4a33SRafael Espindola   bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
447d12b4a33SRafael Espindola                             const GlobalValue &Src);
448dbb0bd1aSRafael Espindola 
449d12b4a33SRafael Espindola   /// Helper method for setting a message and returning an error code.
450b1ed91f3SChris Lattner   bool emitError(const Twine &Message) {
4514160f5d3SRafael Espindola     DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
452b1ed91f3SChris Lattner     return true;
453b1ed91f3SChris Lattner   }
454b1ed91f3SChris Lattner 
455d12b4a33SRafael Espindola   void emitWarning(const Twine &Message) {
4564160f5d3SRafael Espindola     DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
457d12b4a33SRafael Espindola   }
458d12b4a33SRafael Espindola 
459dad0a645SDavid Majnemer   bool getComdatLeader(Module *M, StringRef ComdatName,
460dad0a645SDavid Majnemer                        const GlobalVariable *&GVar);
461dad0a645SDavid Majnemer   bool computeResultingSelectionKind(StringRef ComdatName,
462dad0a645SDavid Majnemer                                      Comdat::SelectionKind Src,
463dad0a645SDavid Majnemer                                      Comdat::SelectionKind Dst,
464dad0a645SDavid Majnemer                                      Comdat::SelectionKind &Result,
465dad0a645SDavid Majnemer                                      bool &LinkFromSrc);
466dad0a645SDavid Majnemer   std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
467dad0a645SDavid Majnemer       ComdatsChosen;
468dad0a645SDavid Majnemer   bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
469dad0a645SDavid Majnemer                        bool &LinkFromSrc);
470dad0a645SDavid Majnemer 
47118c89411SRafael Espindola   /// Given a global in the source module, return the global in the
47218c89411SRafael Espindola   /// destination module that is being linked to, if any.
4733e8bc6a8SRafael Espindola   GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
474b1ed91f3SChris Lattner     // If the source has no name it can't link.  If it has local linkage,
475b1ed91f3SChris Lattner     // there is no name match-up going on.
476b1ed91f3SChris Lattner     if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
4772617dcceSCraig Topper       return nullptr;
478b1ed91f3SChris Lattner 
479b1ed91f3SChris Lattner     // Otherwise see if we have a match in the destination module's symtab.
480b1ed91f3SChris Lattner     GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
481c84f608bSRafael Espindola     if (!DGV)
482c84f608bSRafael Espindola       return nullptr;
483b1ed91f3SChris Lattner 
484b1ed91f3SChris Lattner     // If we found a global with the same name in the dest module, but it has
485b1ed91f3SChris Lattner     // internal linkage, we are really not doing any linkage here.
486b1ed91f3SChris Lattner     if (DGV->hasLocalLinkage())
4872617dcceSCraig Topper       return nullptr;
488b1ed91f3SChris Lattner 
489b1ed91f3SChris Lattner     // Otherwise, we do in fact link to the destination global.
490b1ed91f3SChris Lattner     return DGV;
491b1ed91f3SChris Lattner   }
492b1ed91f3SChris Lattner 
493b1ed91f3SChris Lattner   void computeTypeMapping();
494b1ed91f3SChris Lattner 
49509d84addSDuncan P. N. Exon Smith   void upgradeMismatchedGlobalArray(StringRef Name);
49609d84addSDuncan P. N. Exon Smith   void upgradeMismatchedGlobals();
49709d84addSDuncan P. N. Exon Smith 
4983e8bc6a8SRafael Espindola   bool linkAppendingVarProto(GlobalVariable *DstGV,
4993e8bc6a8SRafael Espindola                              const GlobalVariable *SrcGV);
500778fcc77SRafael Espindola 
501778fcc77SRafael Espindola   bool linkGlobalValueProto(GlobalValue *GV);
50266f02413SBill Wendling   bool linkModuleFlagsMetadata();
503b1ed91f3SChris Lattner 
504b1ed91f3SChris Lattner   void linkAppendingVarInit(const AppendingVarInfo &AVI);
505ef23711eSRafael Espindola 
506ef23711eSRafael Espindola   void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
507ef23711eSRafael Espindola   bool linkFunctionBody(Function &Dst, Function &Src);
508ef23711eSRafael Espindola   void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
509ef23711eSRafael Espindola   bool linkGlobalValueBody(GlobalValue &Src);
510ef23711eSRafael Espindola 
511b1ed91f3SChris Lattner   void linkNamedMDNodes();
512fda0cee7SDuncan P. N. Exon Smith   void stripReplacedSubprograms();
513eee6f995SChris Lattner };
514f00654e3SAlexander Kornienko }
515d48b7783SBill Wendling 
51618c89411SRafael Espindola /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
51718c89411SRafael Espindola /// table. This is good for all clients except for us. Go through the trouble
51818c89411SRafael Espindola /// to force this back.
519b1ed91f3SChris Lattner static void forceRenaming(GlobalValue *GV, StringRef Name) {
520b1ed91f3SChris Lattner   // If the global doesn't force its name or if it already has the right name,
521b1ed91f3SChris Lattner   // there is nothing for us to do.
522b1ed91f3SChris Lattner   if (GV->hasLocalLinkage() || GV->getName() == Name)
523b1ed91f3SChris Lattner     return;
524b1ed91f3SChris Lattner 
525b1ed91f3SChris Lattner   Module *M = GV->getParent();
526361e513dSReid Spencer 
527361e513dSReid Spencer   // If there is a conflict, rename the conflict.
528b1ed91f3SChris Lattner   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
5292a8d2e0eSChris Lattner     GV->takeName(ConflictGV);
530361e513dSReid Spencer     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
531b1ed91f3SChris Lattner     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
5322a8d2e0eSChris Lattner   } else {
5332a8d2e0eSChris Lattner     GV->setName(Name);              // Force the name back
5343aaaa0b2SReid Spencer   }
5353aaaa0b2SReid Spencer }
5363aaaa0b2SReid Spencer 
53718c89411SRafael Espindola /// copy additional attributes (those not needed to construct a GlobalValue)
53818c89411SRafael Espindola /// from the SrcGV to the DestGV.
539b6af2f36SBill Wendling static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
540dd7daee8SDuncan Sands   DestGV->copyAttributesFrom(SrcGV);
541b1ed91f3SChris Lattner   forceRenaming(DestGV, SrcGV->getName());
542361e513dSReid Spencer }
543361e513dSReid Spencer 
54423f8d64bSRafael Espindola static bool isLessConstraining(GlobalValue::VisibilityTypes a,
54523f8d64bSRafael Espindola                                GlobalValue::VisibilityTypes b) {
54623f8d64bSRafael Espindola   if (a == GlobalValue::HiddenVisibility)
54723f8d64bSRafael Espindola     return false;
54823f8d64bSRafael Espindola   if (b == GlobalValue::HiddenVisibility)
54923f8d64bSRafael Espindola     return true;
55023f8d64bSRafael Espindola   if (a == GlobalValue::ProtectedVisibility)
55123f8d64bSRafael Espindola     return false;
55223f8d64bSRafael Espindola   if (b == GlobalValue::ProtectedVisibility)
55323f8d64bSRafael Espindola     return true;
55423f8d64bSRafael Espindola   return false;
55523f8d64bSRafael Espindola }
55623f8d64bSRafael Espindola 
557ef23711eSRafael Espindola /// Loop through the global variables in the src module and merge them into the
558ef23711eSRafael Espindola /// dest module.
559ef23711eSRafael Espindola static GlobalVariable *copyGlobalVariableProto(TypeMapTy &TypeMap, Module &DstM,
560ef23711eSRafael Espindola                                                const GlobalVariable *SGVar) {
561ef23711eSRafael Espindola   // No linking to be performed or linking from the source: simply create an
562ef23711eSRafael Espindola   // identical version of the symbol over in the dest module... the
563ef23711eSRafael Espindola   // initializer will be filled in later by LinkGlobalInits.
564ef23711eSRafael Espindola   GlobalVariable *NewDGV = new GlobalVariable(
565ef23711eSRafael Espindola       DstM, TypeMap.get(SGVar->getType()->getElementType()),
566ef23711eSRafael Espindola       SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr,
567ef23711eSRafael Espindola       SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
568ef23711eSRafael Espindola       SGVar->getType()->getAddressSpace());
569f6f121e2SJames Molloy 
570ef23711eSRafael Espindola   return NewDGV;
5713931c28bSRafael Espindola }
5723931c28bSRafael Espindola 
573ef23711eSRafael Espindola /// Link the function in the source module into the destination module if
574ef23711eSRafael Espindola /// needed, setting up mapping information.
575ef23711eSRafael Espindola static Function *copyFunctionProto(TypeMapTy &TypeMap, Module &DstM,
576ef23711eSRafael Espindola                                    const Function *SF) {
577ef23711eSRafael Espindola   // If there is no linkage to be performed or we are linking from the source,
578ef23711eSRafael Espindola   // bring SF over.
579ef23711eSRafael Espindola   return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(),
580ef23711eSRafael Espindola                           SF->getName(), &DstM);
581ef23711eSRafael Espindola }
582ef23711eSRafael Espindola 
583ef23711eSRafael Espindola /// Set up prototypes for any aliases that come over from the source module.
584ef23711eSRafael Espindola static GlobalAlias *copyGlobalAliasProto(TypeMapTy &TypeMap, Module &DstM,
585ef23711eSRafael Espindola                                          const GlobalAlias *SGA) {
586ef23711eSRafael Espindola   // If there is no linkage to be performed or we're linking from the source,
587ef23711eSRafael Espindola   // bring over SGA.
5886614d8d2SDavid Blaikie   auto *Ty = TypeMap.get(SGA->getValueType());
5896614d8d2SDavid Blaikie   return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
59016a2f3e3SDavid Blaikie                              SGA->getLinkage(), SGA->getName(), &DstM);
591ef23711eSRafael Espindola }
592ef23711eSRafael Espindola 
593ef23711eSRafael Espindola static GlobalValue *copyGlobalValueProto(TypeMapTy &TypeMap, Module &DstM,
594ef23711eSRafael Espindola                                          const GlobalValue *SGV) {
595ef23711eSRafael Espindola   GlobalValue *NewGV;
596ef23711eSRafael Espindola   if (auto *SGVar = dyn_cast<GlobalVariable>(SGV))
597ef23711eSRafael Espindola     NewGV = copyGlobalVariableProto(TypeMap, DstM, SGVar);
598ef23711eSRafael Espindola   else if (auto *SF = dyn_cast<Function>(SGV))
599ef23711eSRafael Espindola     NewGV = copyFunctionProto(TypeMap, DstM, SF);
600ef23711eSRafael Espindola   else
601ef23711eSRafael Espindola     NewGV = copyGlobalAliasProto(TypeMap, DstM, cast<GlobalAlias>(SGV));
602ef23711eSRafael Espindola   copyGVAttributes(NewGV, SGV);
603ef23711eSRafael Espindola   return NewGV;
604ef23711eSRafael Espindola }
605ef23711eSRafael Espindola 
606ef23711eSRafael Espindola Value *ValueMaterializerTy::materializeValueFor(Value *V) {
607ef23711eSRafael Espindola   auto *SGV = dyn_cast<GlobalValue>(V);
608ef23711eSRafael Espindola   if (!SGV)
609ef23711eSRafael Espindola     return nullptr;
610ef23711eSRafael Espindola 
611ef23711eSRafael Espindola   GlobalValue *DGV = copyGlobalValueProto(TypeMap, *DstM, SGV);
612ef23711eSRafael Espindola 
613ef23711eSRafael Espindola   if (Comdat *SC = SGV->getComdat()) {
614ef23711eSRafael Espindola     if (auto *DGO = dyn_cast<GlobalObject>(DGV)) {
615ef23711eSRafael Espindola       Comdat *DC = DstM->getOrInsertComdat(SC->getName());
616ef23711eSRafael Espindola       DGO->setComdat(DC);
617ef23711eSRafael Espindola     }
618ef23711eSRafael Espindola   }
619ef23711eSRafael Espindola 
620ef23711eSRafael Espindola   LazilyLinkGlobalValues.push_back(SGV);
621ef23711eSRafael Espindola   return DGV;
622f6f121e2SJames Molloy }
623f6f121e2SJames Molloy 
624dad0a645SDavid Majnemer bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
625dad0a645SDavid Majnemer                                    const GlobalVariable *&GVar) {
626dad0a645SDavid Majnemer   const GlobalValue *GVal = M->getNamedValue(ComdatName);
627dad0a645SDavid Majnemer   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
628dad0a645SDavid Majnemer     GVal = GA->getBaseObject();
629dad0a645SDavid Majnemer     if (!GVal)
630dad0a645SDavid Majnemer       // We cannot resolve the size of the aliasee yet.
631dad0a645SDavid Majnemer       return emitError("Linking COMDATs named '" + ComdatName +
632dad0a645SDavid Majnemer                        "': COMDAT key involves incomputable alias size.");
633dad0a645SDavid Majnemer   }
634dad0a645SDavid Majnemer 
635dad0a645SDavid Majnemer   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
636dad0a645SDavid Majnemer   if (!GVar)
637dad0a645SDavid Majnemer     return emitError(
638dad0a645SDavid Majnemer         "Linking COMDATs named '" + ComdatName +
639dad0a645SDavid Majnemer         "': GlobalVariable required for data dependent selection!");
640dad0a645SDavid Majnemer 
641dad0a645SDavid Majnemer   return false;
642dad0a645SDavid Majnemer }
643dad0a645SDavid Majnemer 
644dad0a645SDavid Majnemer bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
645dad0a645SDavid Majnemer                                                  Comdat::SelectionKind Src,
646dad0a645SDavid Majnemer                                                  Comdat::SelectionKind Dst,
647dad0a645SDavid Majnemer                                                  Comdat::SelectionKind &Result,
648dad0a645SDavid Majnemer                                                  bool &LinkFromSrc) {
649dad0a645SDavid Majnemer   // The ability to mix Comdat::SelectionKind::Any with
650dad0a645SDavid Majnemer   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
651dad0a645SDavid Majnemer   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
652dad0a645SDavid Majnemer                          Dst == Comdat::SelectionKind::Largest;
653dad0a645SDavid Majnemer   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
654dad0a645SDavid Majnemer                          Src == Comdat::SelectionKind::Largest;
655dad0a645SDavid Majnemer   if (DstAnyOrLargest && SrcAnyOrLargest) {
656dad0a645SDavid Majnemer     if (Dst == Comdat::SelectionKind::Largest ||
657dad0a645SDavid Majnemer         Src == Comdat::SelectionKind::Largest)
658dad0a645SDavid Majnemer       Result = Comdat::SelectionKind::Largest;
659dad0a645SDavid Majnemer     else
660dad0a645SDavid Majnemer       Result = Comdat::SelectionKind::Any;
661dad0a645SDavid Majnemer   } else if (Src == Dst) {
662dad0a645SDavid Majnemer     Result = Dst;
663dad0a645SDavid Majnemer   } else {
664dad0a645SDavid Majnemer     return emitError("Linking COMDATs named '" + ComdatName +
665dad0a645SDavid Majnemer                      "': invalid selection kinds!");
666dad0a645SDavid Majnemer   }
667dad0a645SDavid Majnemer 
668dad0a645SDavid Majnemer   switch (Result) {
669dad0a645SDavid Majnemer   case Comdat::SelectionKind::Any:
670dad0a645SDavid Majnemer     // Go with Dst.
671dad0a645SDavid Majnemer     LinkFromSrc = false;
672dad0a645SDavid Majnemer     break;
673dad0a645SDavid Majnemer   case Comdat::SelectionKind::NoDuplicates:
674dad0a645SDavid Majnemer     return emitError("Linking COMDATs named '" + ComdatName +
675dad0a645SDavid Majnemer                      "': noduplicates has been violated!");
676dad0a645SDavid Majnemer   case Comdat::SelectionKind::ExactMatch:
677dad0a645SDavid Majnemer   case Comdat::SelectionKind::Largest:
678dad0a645SDavid Majnemer   case Comdat::SelectionKind::SameSize: {
679dad0a645SDavid Majnemer     const GlobalVariable *DstGV;
680dad0a645SDavid Majnemer     const GlobalVariable *SrcGV;
681dad0a645SDavid Majnemer     if (getComdatLeader(DstM, ComdatName, DstGV) ||
682dad0a645SDavid Majnemer         getComdatLeader(SrcM, ComdatName, SrcGV))
683dad0a645SDavid Majnemer       return true;
684dad0a645SDavid Majnemer 
68546a43556SMehdi Amini     const DataLayout &DstDL = DstM->getDataLayout();
68646a43556SMehdi Amini     const DataLayout &SrcDL = SrcM->getDataLayout();
687dad0a645SDavid Majnemer     uint64_t DstSize =
68846a43556SMehdi Amini         DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
689dad0a645SDavid Majnemer     uint64_t SrcSize =
69046a43556SMehdi Amini         SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
691dad0a645SDavid Majnemer     if (Result == Comdat::SelectionKind::ExactMatch) {
692dad0a645SDavid Majnemer       if (SrcGV->getInitializer() != DstGV->getInitializer())
693dad0a645SDavid Majnemer         return emitError("Linking COMDATs named '" + ComdatName +
694dad0a645SDavid Majnemer                          "': ExactMatch violated!");
695dad0a645SDavid Majnemer       LinkFromSrc = false;
696dad0a645SDavid Majnemer     } else if (Result == Comdat::SelectionKind::Largest) {
697dad0a645SDavid Majnemer       LinkFromSrc = SrcSize > DstSize;
698dad0a645SDavid Majnemer     } else if (Result == Comdat::SelectionKind::SameSize) {
699dad0a645SDavid Majnemer       if (SrcSize != DstSize)
700dad0a645SDavid Majnemer         return emitError("Linking COMDATs named '" + ComdatName +
701dad0a645SDavid Majnemer                          "': SameSize violated!");
702dad0a645SDavid Majnemer       LinkFromSrc = false;
703dad0a645SDavid Majnemer     } else {
704dad0a645SDavid Majnemer       llvm_unreachable("unknown selection kind");
705dad0a645SDavid Majnemer     }
706dad0a645SDavid Majnemer     break;
707dad0a645SDavid Majnemer   }
708dad0a645SDavid Majnemer   }
709dad0a645SDavid Majnemer 
710dad0a645SDavid Majnemer   return false;
711dad0a645SDavid Majnemer }
712dad0a645SDavid Majnemer 
713dad0a645SDavid Majnemer bool ModuleLinker::getComdatResult(const Comdat *SrcC,
714dad0a645SDavid Majnemer                                    Comdat::SelectionKind &Result,
715dad0a645SDavid Majnemer                                    bool &LinkFromSrc) {
716b16196a3SRafael Espindola   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
717dad0a645SDavid Majnemer   StringRef ComdatName = SrcC->getName();
718dad0a645SDavid Majnemer   Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
719dad0a645SDavid Majnemer   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
7202ef3f299SRafael Espindola 
721b16196a3SRafael Espindola   if (DstCI == ComdatSymTab.end()) {
722b16196a3SRafael Espindola     // Use the comdat if it is only available in one of the modules.
723b16196a3SRafael Espindola     LinkFromSrc = true;
724b16196a3SRafael Espindola     Result = SSK;
7252ef3f299SRafael Espindola     return false;
726b16196a3SRafael Espindola   }
7272ef3f299SRafael Espindola 
728dad0a645SDavid Majnemer   const Comdat *DstC = &DstCI->second;
729dad0a645SDavid Majnemer   Comdat::SelectionKind DSK = DstC->getSelectionKind();
7302ef3f299SRafael Espindola   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
7312ef3f299SRafael Espindola                                        LinkFromSrc);
732dad0a645SDavid Majnemer }
733f6f121e2SJames Molloy 
734d12b4a33SRafael Espindola bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
735d12b4a33SRafael Espindola                                         const GlobalValue &Dest,
736dbb0bd1aSRafael Espindola                                         const GlobalValue &Src) {
737e868123dSDuncan P. N. Exon Smith   // Should we unconditionally use the Src?
738020d4fb1SArtem Belevich   if (shouldOverrideFromSrc()) {
739e868123dSDuncan P. N. Exon Smith     LinkFromSrc = true;
740e868123dSDuncan P. N. Exon Smith     return false;
741e868123dSDuncan P. N. Exon Smith   }
742e868123dSDuncan P. N. Exon Smith 
743778fcc77SRafael Espindola   // We always have to add Src if it has appending linkage.
744778fcc77SRafael Espindola   if (Src.hasAppendingLinkage()) {
745778fcc77SRafael Espindola     LinkFromSrc = true;
746778fcc77SRafael Espindola     return false;
747778fcc77SRafael Espindola   }
748778fcc77SRafael Espindola 
749d4bcefc7SRafael Espindola   bool SrcIsDeclaration = Src.isDeclarationForLinker();
750d4bcefc7SRafael Espindola   bool DestIsDeclaration = Dest.isDeclarationForLinker();
751dbb0bd1aSRafael Espindola 
752dbb0bd1aSRafael Espindola   if (SrcIsDeclaration) {
753dbb0bd1aSRafael Espindola     // If Src is external or if both Src & Dest are external..  Just link the
754dbb0bd1aSRafael Espindola     // external globals, we aren't adding anything.
755d12b4a33SRafael Espindola     if (Src.hasDLLImportStorageClass()) {
756dbb0bd1aSRafael Espindola       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
757d12b4a33SRafael Espindola       LinkFromSrc = DestIsDeclaration;
758d12b4a33SRafael Espindola       return false;
759d12b4a33SRafael Espindola     }
760dbb0bd1aSRafael Espindola     // If the Dest is weak, use the source linkage.
761d12b4a33SRafael Espindola     LinkFromSrc = Dest.hasExternalWeakLinkage();
762d12b4a33SRafael Espindola     return false;
763dbb0bd1aSRafael Espindola   }
764dbb0bd1aSRafael Espindola 
765d12b4a33SRafael Espindola   if (DestIsDeclaration) {
766dbb0bd1aSRafael Espindola     // If Dest is external but Src is not:
767d12b4a33SRafael Espindola     LinkFromSrc = true;
768d12b4a33SRafael Espindola     return false;
769d12b4a33SRafael Espindola   }
770dbb0bd1aSRafael Espindola 
7710910605aSRafael Espindola   if (Src.hasCommonLinkage()) {
772d12b4a33SRafael Espindola     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
773d12b4a33SRafael Espindola       LinkFromSrc = true;
7740910605aSRafael Espindola       return false;
775d12b4a33SRafael Espindola     }
776d12b4a33SRafael Espindola 
777d12b4a33SRafael Espindola     if (!Dest.hasCommonLinkage()) {
778d12b4a33SRafael Espindola       LinkFromSrc = false;
779d12b4a33SRafael Espindola       return false;
780d12b4a33SRafael Espindola     }
7810910605aSRafael Espindola 
782a28d91d8SMehdi Amini     const DataLayout &DL = Dest.getParent()->getDataLayout();
7830910605aSRafael Espindola     uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
7840910605aSRafael Espindola     uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
785d12b4a33SRafael Espindola     LinkFromSrc = SrcSize > DestSize;
786d12b4a33SRafael Espindola     return false;
7870910605aSRafael Espindola   }
7880910605aSRafael Espindola 
789dbb0bd1aSRafael Espindola   if (Src.isWeakForLinker()) {
790dbb0bd1aSRafael Espindola     assert(!Dest.hasExternalWeakLinkage());
791dbb0bd1aSRafael Espindola     assert(!Dest.hasAvailableExternallyLinkage());
7920910605aSRafael Espindola 
793d12b4a33SRafael Espindola     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
794d12b4a33SRafael Espindola       LinkFromSrc = true;
795d12b4a33SRafael Espindola       return false;
796d12b4a33SRafael Espindola     }
797dbb0bd1aSRafael Espindola 
798d12b4a33SRafael Espindola     LinkFromSrc = false;
7990910605aSRafael Espindola     return false;
800dbb0bd1aSRafael Espindola   }
801dbb0bd1aSRafael Espindola 
802dbb0bd1aSRafael Espindola   if (Dest.isWeakForLinker()) {
803dbb0bd1aSRafael Espindola     assert(Src.hasExternalLinkage());
804d12b4a33SRafael Espindola     LinkFromSrc = true;
805d12b4a33SRafael Espindola     return false;
806dbb0bd1aSRafael Espindola   }
807dbb0bd1aSRafael Espindola 
808dbb0bd1aSRafael Espindola   assert(!Src.hasExternalWeakLinkage());
809dbb0bd1aSRafael Espindola   assert(!Dest.hasExternalWeakLinkage());
810dbb0bd1aSRafael Espindola   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
811dbb0bd1aSRafael Espindola          "Unexpected linkage type!");
812dbb0bd1aSRafael Espindola   return emitError("Linking globals named '" + Src.getName() +
813dbb0bd1aSRafael Espindola                    "': symbol multiply defined!");
814dbb0bd1aSRafael Espindola }
815dbb0bd1aSRafael Espindola 
81618c89411SRafael Espindola /// Loop over all of the linked values to compute type mappings.  For example,
81718c89411SRafael Espindola /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
81818c89411SRafael Espindola /// types 'Foo' but one got renamed when the module was loaded into the same
81918c89411SRafael Espindola /// LLVMContext.
820b1ed91f3SChris Lattner void ModuleLinker::computeTypeMapping() {
821c8a476eeSRafael Espindola   for (GlobalValue &SGV : SrcM->globals()) {
822c8a476eeSRafael Espindola     GlobalValue *DGV = getLinkedToGlobal(&SGV);
823c8a476eeSRafael Espindola     if (!DGV)
824c8a476eeSRafael Espindola       continue;
825b1ed91f3SChris Lattner 
826c8a476eeSRafael Espindola     if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
827c8a476eeSRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
828b1ed91f3SChris Lattner       continue;
8295c310be0SDevang Patel     }
8305c310be0SDevang Patel 
831b1ed91f3SChris Lattner     // Unify the element type of appending arrays.
832b1ed91f3SChris Lattner     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
833c8a476eeSRafael Espindola     ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
834b1ed91f3SChris Lattner     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
835b1ed91f3SChris Lattner   }
83634fc5a0eSChris Lattner 
837c8a476eeSRafael Espindola   for (GlobalValue &SGV : *SrcM) {
838c8a476eeSRafael Espindola     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
839c8a476eeSRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
840b1ed91f3SChris Lattner   }
841e79f4c77SAnton Korobeynikov 
842e96d7eb8SRafael Espindola   for (GlobalValue &SGV : SrcM->aliases()) {
843e96d7eb8SRafael Espindola     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
844e96d7eb8SRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
845e96d7eb8SRafael Espindola   }
846e96d7eb8SRafael Espindola 
847d48b7783SBill Wendling   // Incorporate types by name, scanning all the types in the source module.
848d48b7783SBill Wendling   // At this point, the destination module may have a type "%foo = { i32 }" for
8492b3f61afSBill Wendling   // example.  When the source module got loaded into the same LLVMContext, if
8502b3f61afSBill Wendling   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
8512fa1e43aSRafael Espindola   std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
8522fa1e43aSRafael Espindola   for (StructType *ST : Types) {
8534d4c9387SRafael Espindola     if (!ST->hasName())
8544d4c9387SRafael Espindola       continue;
8552b3f61afSBill Wendling 
8562b3f61afSBill Wendling     // Check to see if there is a dot in the name followed by a digit.
857d48b7783SBill Wendling     size_t DotPos = ST->getName().rfind('.');
858d48b7783SBill Wendling     if (DotPos == 0 || DotPos == StringRef::npos ||
85983c74e9fSGuy Benyei         ST->getName().back() == '.' ||
86083c74e9fSGuy Benyei         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
861d48b7783SBill Wendling       continue;
8622b3f61afSBill Wendling 
8632b3f61afSBill Wendling     // Check to see if the destination module has a struct with the prefix name.
864973b3612SRafael Espindola     StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos));
865973b3612SRafael Espindola     if (!DST)
866973b3612SRafael Espindola       continue;
867973b3612SRafael Espindola 
8682b3f61afSBill Wendling     // Don't use it if this actually came from the source module. They're in
8698737480dSBill Wendling     // the same LLVMContext after all. Also don't use it unless the type is
8708737480dSBill Wendling     // actually used in the destination module. This can happen in situations
8718737480dSBill Wendling     // like this:
8728737480dSBill Wendling     //
8738737480dSBill Wendling     //      Module A                         Module B
8748737480dSBill Wendling     //      --------                         --------
8758737480dSBill Wendling     //   %Z = type { %A }                %B = type { %C.1 }
8768737480dSBill Wendling     //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
8778737480dSBill Wendling     //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
8788737480dSBill Wendling     //   %C = type { i8* }               %B.3 = type { %C.1 }
8798737480dSBill Wendling     //
8808737480dSBill Wendling     // When we link Module B with Module A, the '%B' in Module B is
8818737480dSBill Wendling     // used. However, that would then use '%C.1'. But when we process '%C.1',
8828737480dSBill Wendling     // we prefer to take the '%C' version. So we are then left with both
8838737480dSBill Wendling     // '%C.1' and '%C' being used for the same types. This leads to some
8848737480dSBill Wendling     // variables using one type and some using the other.
88531ad468dSRafael Espindola     if (TypeMap.DstStructTypesSet.hasType(DST))
8862b3f61afSBill Wendling       TypeMap.addTypeMapping(DST, ST);
8872b3f61afSBill Wendling   }
8882b3f61afSBill Wendling 
889b1ed91f3SChris Lattner   // Now that we have discovered all of the type equivalences, get a body for
890b1ed91f3SChris Lattner   // any 'opaque' types in the dest module that are now resolved.
891b1ed91f3SChris Lattner   TypeMap.linkDefinedTypeBodies();
892b1ed91f3SChris Lattner }
893c08e7a00SChris Lattner 
89409d84addSDuncan P. N. Exon Smith static void upgradeGlobalArray(GlobalVariable *GV) {
89509d84addSDuncan P. N. Exon Smith   ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
89609d84addSDuncan P. N. Exon Smith   StructType *OldTy = cast<StructType>(ATy->getElementType());
89709d84addSDuncan P. N. Exon Smith   assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
89809d84addSDuncan P. N. Exon Smith 
89909d84addSDuncan P. N. Exon Smith   // Get the upgraded 3 element type.
90009d84addSDuncan P. N. Exon Smith   PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
90109d84addSDuncan P. N. Exon Smith   Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
90209d84addSDuncan P. N. Exon Smith                   VoidPtrTy};
90309d84addSDuncan P. N. Exon Smith   StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
90409d84addSDuncan P. N. Exon Smith 
90509d84addSDuncan P. N. Exon Smith   // Build new constants with a null third field filled in.
90609d84addSDuncan P. N. Exon Smith   Constant *OldInitC = GV->getInitializer();
90709d84addSDuncan P. N. Exon Smith   ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
90809d84addSDuncan P. N. Exon Smith   if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
90909d84addSDuncan P. N. Exon Smith     // Invalid initializer; give up.
91009d84addSDuncan P. N. Exon Smith     return;
91109d84addSDuncan P. N. Exon Smith   std::vector<Constant *> Initializers;
91209d84addSDuncan P. N. Exon Smith   if (OldInit && OldInit->getNumOperands()) {
91309d84addSDuncan P. N. Exon Smith     Value *Null = Constant::getNullValue(VoidPtrTy);
91409d84addSDuncan P. N. Exon Smith     for (Use &U : OldInit->operands()) {
91509d84addSDuncan P. N. Exon Smith       ConstantStruct *Init = cast<ConstantStruct>(U.get());
91609d84addSDuncan P. N. Exon Smith       Initializers.push_back(ConstantStruct::get(
91709d84addSDuncan P. N. Exon Smith           NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
91809d84addSDuncan P. N. Exon Smith     }
91909d84addSDuncan P. N. Exon Smith   }
92009d84addSDuncan P. N. Exon Smith   assert(Initializers.size() == ATy->getNumElements() &&
92109d84addSDuncan P. N. Exon Smith          "Failed to copy all array elements");
92209d84addSDuncan P. N. Exon Smith 
92309d84addSDuncan P. N. Exon Smith   // Replace the old GV with a new one.
92409d84addSDuncan P. N. Exon Smith   ATy = ArrayType::get(NewTy, Initializers.size());
92509d84addSDuncan P. N. Exon Smith   Constant *NewInit = ConstantArray::get(ATy, Initializers);
92609d84addSDuncan P. N. Exon Smith   GlobalVariable *NewGV = new GlobalVariable(
92709d84addSDuncan P. N. Exon Smith       *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
92809d84addSDuncan P. N. Exon Smith       GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
92909d84addSDuncan P. N. Exon Smith       GV->isExternallyInitialized());
93009d84addSDuncan P. N. Exon Smith   NewGV->copyAttributesFrom(GV);
93109d84addSDuncan P. N. Exon Smith   NewGV->takeName(GV);
93209d84addSDuncan P. N. Exon Smith   assert(GV->use_empty() && "program cannot use initializer list");
93309d84addSDuncan P. N. Exon Smith   GV->eraseFromParent();
93409d84addSDuncan P. N. Exon Smith }
93509d84addSDuncan P. N. Exon Smith 
93609d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
93709d84addSDuncan P. N. Exon Smith   // Look for the global arrays.
93809d84addSDuncan P. N. Exon Smith   auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
93909d84addSDuncan P. N. Exon Smith   if (!DstGV)
94009d84addSDuncan P. N. Exon Smith     return;
94109d84addSDuncan P. N. Exon Smith   auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
94209d84addSDuncan P. N. Exon Smith   if (!SrcGV)
94309d84addSDuncan P. N. Exon Smith     return;
94409d84addSDuncan P. N. Exon Smith 
94509d84addSDuncan P. N. Exon Smith   // Check if the types already match.
94609d84addSDuncan P. N. Exon Smith   auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
94709d84addSDuncan P. N. Exon Smith   auto *SrcTy =
94809d84addSDuncan P. N. Exon Smith       cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
94909d84addSDuncan P. N. Exon Smith   if (DstTy == SrcTy)
95009d84addSDuncan P. N. Exon Smith     return;
95109d84addSDuncan P. N. Exon Smith 
95209d84addSDuncan P. N. Exon Smith   // Grab the element types.  We can only upgrade an array of a two-field
95309d84addSDuncan P. N. Exon Smith   // struct.  Only bother if the other one has three-fields.
95409d84addSDuncan P. N. Exon Smith   auto *DstEltTy = cast<StructType>(DstTy->getElementType());
95509d84addSDuncan P. N. Exon Smith   auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
95609d84addSDuncan P. N. Exon Smith   if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
95709d84addSDuncan P. N. Exon Smith     upgradeGlobalArray(DstGV);
95809d84addSDuncan P. N. Exon Smith     return;
95909d84addSDuncan P. N. Exon Smith   }
96009d84addSDuncan P. N. Exon Smith   if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
96109d84addSDuncan P. N. Exon Smith     upgradeGlobalArray(SrcGV);
96209d84addSDuncan P. N. Exon Smith 
96309d84addSDuncan P. N. Exon Smith   // We can't upgrade any other differences.
96409d84addSDuncan P. N. Exon Smith }
96509d84addSDuncan P. N. Exon Smith 
96609d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobals() {
96709d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobalArray("llvm.global_ctors");
96809d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobalArray("llvm.global_dtors");
96909d84addSDuncan P. N. Exon Smith }
97009d84addSDuncan P. N. Exon Smith 
97118c89411SRafael Espindola /// If there were any appending global variables, link them together now.
97218c89411SRafael Espindola /// Return true on error.
973b1ed91f3SChris Lattner bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
9743e8bc6a8SRafael Espindola                                          const GlobalVariable *SrcGV) {
975d48b7783SBill Wendling 
976b1ed91f3SChris Lattner   if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
977b1ed91f3SChris Lattner     return emitError("Linking globals named '" + SrcGV->getName() +
978b1ed91f3SChris Lattner            "': can only link appending global with another appending global!");
979361e513dSReid Spencer 
980b1ed91f3SChris Lattner   ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
981b1ed91f3SChris Lattner   ArrayType *SrcTy =
982b1ed91f3SChris Lattner     cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
983b1ed91f3SChris Lattner   Type *EltTy = DstTy->getElementType();
984b1ed91f3SChris Lattner 
985b1ed91f3SChris Lattner   // Check to see that they two arrays agree on type.
986b1ed91f3SChris Lattner   if (EltTy != SrcTy->getElementType())
987b1ed91f3SChris Lattner     return emitError("Appending variables with different element types!");
988b1ed91f3SChris Lattner   if (DstGV->isConstant() != SrcGV->isConstant())
989b1ed91f3SChris Lattner     return emitError("Appending variables linked with different const'ness!");
990b1ed91f3SChris Lattner 
991b1ed91f3SChris Lattner   if (DstGV->getAlignment() != SrcGV->getAlignment())
992b1ed91f3SChris Lattner     return emitError(
993b1ed91f3SChris Lattner              "Appending variables with different alignment need to be linked!");
994b1ed91f3SChris Lattner 
995b1ed91f3SChris Lattner   if (DstGV->getVisibility() != SrcGV->getVisibility())
996b1ed91f3SChris Lattner     return emitError(
997b1ed91f3SChris Lattner             "Appending variables with different visibility need to be linked!");
998b1ed91f3SChris Lattner 
999fac3a018SRafael Espindola   if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
1000fac3a018SRafael Espindola     return emitError(
1001fac3a018SRafael Espindola         "Appending variables with different unnamed_addr need to be linked!");
1002fac3a018SRafael Espindola 
100364c1e180SRafael Espindola   if (StringRef(DstGV->getSection()) != SrcGV->getSection())
1004b1ed91f3SChris Lattner     return emitError(
1005b1ed91f3SChris Lattner           "Appending variables with different section name need to be linked!");
1006b1ed91f3SChris Lattner 
1007b1ed91f3SChris Lattner   uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
1008b1ed91f3SChris Lattner   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
1009b1ed91f3SChris Lattner 
1010b1ed91f3SChris Lattner   // Create the new global variable.
1011b1ed91f3SChris Lattner   GlobalVariable *NG =
1012b1ed91f3SChris Lattner     new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
10132617dcceSCraig Topper                        DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
1014cbe34b4cSHans Wennborg                        DstGV->getThreadLocalMode(),
1015b1ed91f3SChris Lattner                        DstGV->getType()->getAddressSpace());
1016b1ed91f3SChris Lattner 
1017b1ed91f3SChris Lattner   // Propagate alignment, visibility and section info.
1018b6af2f36SBill Wendling   copyGVAttributes(NG, DstGV);
1019b1ed91f3SChris Lattner 
1020b1ed91f3SChris Lattner   AppendingVarInfo AVI;
1021b1ed91f3SChris Lattner   AVI.NewGV = NG;
1022b1ed91f3SChris Lattner   AVI.DstInit = DstGV->getInitializer();
1023b1ed91f3SChris Lattner   AVI.SrcInit = SrcGV->getInitializer();
1024b1ed91f3SChris Lattner   AppendingVars.push_back(AVI);
1025b1ed91f3SChris Lattner 
1026b1ed91f3SChris Lattner   // Replace any uses of the two global variables with uses of the new
1027b1ed91f3SChris Lattner   // global.
1028b1ed91f3SChris Lattner   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
1029b1ed91f3SChris Lattner 
1030b1ed91f3SChris Lattner   DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
1031b1ed91f3SChris Lattner   DstGV->eraseFromParent();
1032b1ed91f3SChris Lattner 
1033cbb91408STanya Lattner   // Track the source variable so we don't try to link it.
1034cbb91408STanya Lattner   DoNotLinkFromSource.insert(SrcGV);
1035cbb91408STanya Lattner 
1036b1ed91f3SChris Lattner   return false;
1037b1ed91f3SChris Lattner }
1038b1ed91f3SChris Lattner 
1039778fcc77SRafael Espindola bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
1040b1ed91f3SChris Lattner   GlobalValue *DGV = getLinkedToGlobal(SGV);
1041b1ed91f3SChris Lattner 
1042778fcc77SRafael Espindola   // Handle the ultra special appending linkage case first.
1043778fcc77SRafael Espindola   if (DGV && DGV->hasAppendingLinkage())
1044778fcc77SRafael Espindola     return linkAppendingVarProto(cast<GlobalVariable>(DGV),
1045778fcc77SRafael Espindola                                  cast<GlobalVariable>(SGV));
1046778fcc77SRafael Espindola 
1047778fcc77SRafael Espindola   bool LinkFromSrc = true;
1048778fcc77SRafael Espindola   Comdat *C = nullptr;
1049778fcc77SRafael Espindola   GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
1050778fcc77SRafael Espindola   bool HasUnnamedAddr = SGV->hasUnnamedAddr();
1051778fcc77SRafael Espindola 
1052dad0a645SDavid Majnemer   if (const Comdat *SC = SGV->getComdat()) {
1053dad0a645SDavid Majnemer     Comdat::SelectionKind SK;
1054dad0a645SDavid Majnemer     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1055778fcc77SRafael Espindola     C = DstM->getOrInsertComdat(SC->getName());
1056778fcc77SRafael Espindola     C->setSelectionKind(SK);
1057778fcc77SRafael Espindola   } else if (DGV) {
1058778fcc77SRafael Espindola     if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1059fc61de39SChris Lattner       return true;
1060dad0a645SDavid Majnemer   }
106134fc5a0eSChris Lattner 
1062dad0a645SDavid Majnemer   if (!LinkFromSrc) {
1063cbb91408STanya Lattner     // Track the source global so that we don't attempt to copy it over when
1064cbb91408STanya Lattner     // processing global initializers.
1065cbb91408STanya Lattner     DoNotLinkFromSource.insert(SGV);
1066cbb91408STanya Lattner 
1067778fcc77SRafael Espindola     if (DGV)
1068778fcc77SRafael Espindola       // Make sure to remember this mapping.
1069778fcc77SRafael Espindola       ValueMap[SGV] =
1070778fcc77SRafael Espindola           ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
1071778fcc77SRafael Espindola   }
1072778fcc77SRafael Espindola 
1073778fcc77SRafael Espindola   if (DGV) {
1074778fcc77SRafael Espindola     Visibility = isLessConstraining(Visibility, DGV->getVisibility())
1075778fcc77SRafael Espindola                      ? DGV->getVisibility()
1076778fcc77SRafael Espindola                      : Visibility;
1077778fcc77SRafael Espindola     HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1078778fcc77SRafael Espindola   }
1079778fcc77SRafael Espindola 
1080778fcc77SRafael Espindola   if (!LinkFromSrc && !DGV)
1081dad0a645SDavid Majnemer     return false;
1082778fcc77SRafael Espindola 
1083778fcc77SRafael Espindola   GlobalValue *NewGV;
108426c29511SRafael Espindola   if (!LinkFromSrc) {
108526c29511SRafael Espindola     NewGV = DGV;
108626c29511SRafael Espindola   } else {
1087ef23711eSRafael Espindola     // If the GV is to be lazily linked, don't create it just yet.
1088ef23711eSRafael Espindola     // The ValueMaterializerTy will deal with creating it if it's used.
1089020d4fb1SArtem Belevich     if (!DGV && !shouldOverrideFromSrc() &&
1090e868123dSDuncan P. N. Exon Smith         (SGV->hasLocalLinkage() || SGV->hasLinkOnceLinkage() ||
1091ef23711eSRafael Espindola          SGV->hasAvailableExternallyLinkage())) {
1092ef23711eSRafael Espindola       DoNotLinkFromSource.insert(SGV);
1093ef23711eSRafael Espindola       return false;
109426c29511SRafael Espindola     }
1095778fcc77SRafael Espindola 
1096020d4fb1SArtem Belevich     // When we only want to link in unresolved dependencies, blacklist
1097020d4fb1SArtem Belevich     // the symbol unless unless DestM has a matching declaration (DGV).
1098020d4fb1SArtem Belevich     if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration())) {
1099020d4fb1SArtem Belevich       DoNotLinkFromSource.insert(SGV);
1100020d4fb1SArtem Belevich       return false;
1101020d4fb1SArtem Belevich     }
1102020d4fb1SArtem Belevich 
1103ef23711eSRafael Espindola     NewGV = copyGlobalValueProto(TypeMap, *DstM, SGV);
1104fda0cee7SDuncan P. N. Exon Smith 
1105fda0cee7SDuncan P. N. Exon Smith     if (DGV && isa<Function>(DGV))
1106fda0cee7SDuncan P. N. Exon Smith       if (auto *NewF = dyn_cast<Function>(NewGV))
1107fda0cee7SDuncan P. N. Exon Smith         OverridingFunctions.insert(NewF);
1108ef23711eSRafael Espindola   }
1109778fcc77SRafael Espindola 
1110778fcc77SRafael Espindola   NewGV->setUnnamedAddr(HasUnnamedAddr);
1111778fcc77SRafael Espindola   NewGV->setVisibility(Visibility);
1112778fcc77SRafael Espindola 
1113778fcc77SRafael Espindola   if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1114778fcc77SRafael Espindola     if (C)
1115778fcc77SRafael Espindola       NewGO->setComdat(C);
1116439835a6SRafael Espindola 
1117439835a6SRafael Espindola     if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1118439835a6SRafael Espindola       NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
1119778fcc77SRafael Espindola   }
1120778fcc77SRafael Espindola 
1121879aeb77SRafael Espindola   if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) {
1122879aeb77SRafael Espindola     auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV);
1123879aeb77SRafael Espindola     auto *SGVar = dyn_cast<GlobalVariable>(SGV);
1124879aeb77SRafael Espindola     if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() &&
1125879aeb77SRafael Espindola         (!DGVar->isConstant() || !SGVar->isConstant()))
1126879aeb77SRafael Espindola       NewGVar->setConstant(false);
1127879aeb77SRafael Espindola   }
1128879aeb77SRafael Espindola 
1129778fcc77SRafael Espindola   // Make sure to remember this mapping.
1130778fcc77SRafael Espindola   if (NewGV != DGV) {
1131778fcc77SRafael Espindola     if (DGV) {
1132ad9d0ca8SRafael Espindola       DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
1133778fcc77SRafael Espindola       DGV->eraseFromParent();
1134778fcc77SRafael Espindola     }
1135778fcc77SRafael Espindola     ValueMap[SGV] = NewGV;
1136dad0a645SDavid Majnemer   }
11374e27567aSRafael Espindola 
1138fd38af2dSChandler Carruth   return false;
11394e27567aSRafael Espindola }
11404e27567aSRafael Espindola 
11413e8bc6a8SRafael Espindola static void getArrayElements(const Constant *C,
11423e8bc6a8SRafael Espindola                              SmallVectorImpl<Constant *> &Dest) {
11436705883aSChris Lattner   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
114400245f42SChris Lattner 
11456705883aSChris Lattner   for (unsigned i = 0; i != NumElements; ++i)
11466705883aSChris Lattner     Dest.push_back(C->getAggregateElement(i));
114700245f42SChris Lattner }
114800245f42SChris Lattner 
1149b1ed91f3SChris Lattner void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1150b1ed91f3SChris Lattner   // Merge the initializer.
1151d31dc048SRafael Espindola   SmallVector<Constant *, 16> DstElements;
1152d31dc048SRafael Espindola   getArrayElements(AVI.DstInit, DstElements);
1153b1ed91f3SChris Lattner 
1154d31dc048SRafael Espindola   SmallVector<Constant *, 16> SrcElements;
1155d31dc048SRafael Espindola   getArrayElements(AVI.SrcInit, SrcElements);
115600245f42SChris Lattner 
1157b1ed91f3SChris Lattner   ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1158d31dc048SRafael Espindola 
1159d31dc048SRafael Espindola   StringRef Name = AVI.NewGV->getName();
1160d31dc048SRafael Espindola   bool IsNewStructor =
1161d31dc048SRafael Espindola       (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1162d31dc048SRafael Espindola       cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1163d31dc048SRafael Espindola 
1164d31dc048SRafael Espindola   for (auto *V : SrcElements) {
1165d31dc048SRafael Espindola     if (IsNewStructor) {
1166d31dc048SRafael Espindola       Constant *Key = V->getAggregateElement(2);
1167d31dc048SRafael Espindola       if (DoNotLinkFromSource.count(Key))
1168d31dc048SRafael Espindola         continue;
1169d31dc048SRafael Espindola     }
1170d31dc048SRafael Espindola     DstElements.push_back(
11714fb46cb8SDuncan P. N. Exon Smith         MapValue(V, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1172d31dc048SRafael Espindola   }
1173d31dc048SRafael Espindola   if (IsNewStructor) {
1174d31dc048SRafael Espindola     NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1175d31dc048SRafael Espindola     AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1176d31dc048SRafael Espindola   }
1177d31dc048SRafael Espindola 
1178d31dc048SRafael Espindola   AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1179b1ed91f3SChris Lattner }
1180b1ed91f3SChris Lattner 
118118c89411SRafael Espindola /// Update the initializers in the Dest module now that all globals that may be
118218c89411SRafael Espindola /// referenced are in Dest.
1183ef23711eSRafael Espindola void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
1184b1ed91f3SChris Lattner   // Figure out what the initializer looks like in the dest module.
11854fb46cb8SDuncan P. N. Exon Smith   Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap,
11864fb46cb8SDuncan P. N. Exon Smith                               RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1187b1ed91f3SChris Lattner }
1188b1ed91f3SChris Lattner 
118918c89411SRafael Espindola /// Copy the source function over into the dest function and fix up references
119018c89411SRafael Espindola /// to values. At this point we know that Dest is an external function, and
119118c89411SRafael Espindola /// that Src is not.
1192ef23711eSRafael Espindola bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) {
1193ef23711eSRafael Espindola   assert(Dst.isDeclaration() && !Src.isDeclaration());
1194361e513dSReid Spencer 
119540d7ebedSRafael Espindola   // Materialize if needed.
11963519da82SRafael Espindola   if (std::error_code EC = Src.materialize())
119740d7ebedSRafael Espindola     return emitError(EC.message());
119840d7ebedSRafael Espindola 
1199869d1ce8SRafael Espindola   // Link in the prefix data.
12003519da82SRafael Espindola   if (Src.hasPrefixData())
12014fb46cb8SDuncan P. N. Exon Smith     Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap,
12024fb46cb8SDuncan P. N. Exon Smith                                RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1203869d1ce8SRafael Espindola 
1204869d1ce8SRafael Espindola   // Link in the prologue data.
12053519da82SRafael Espindola   if (Src.hasPrologueData())
12064fb46cb8SDuncan P. N. Exon Smith     Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap,
12074fb46cb8SDuncan P. N. Exon Smith                                  RF_MoveDistinctMDs, &TypeMap,
12084fb46cb8SDuncan P. N. Exon Smith                                  &ValMaterializer));
1209869d1ce8SRafael Espindola 
12107fddeccbSDavid Majnemer   // Link in the personality function.
12117fddeccbSDavid Majnemer   if (Src.hasPersonalityFn())
12124fb46cb8SDuncan P. N. Exon Smith     Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap,
12134fb46cb8SDuncan P. N. Exon Smith                                   RF_MoveDistinctMDs, &TypeMap,
12144fb46cb8SDuncan P. N. Exon Smith                                   &ValMaterializer));
12157fddeccbSDavid Majnemer 
12167391dde1SChris Lattner   // Go through and convert function arguments over, remembering the mapping.
1217ef23711eSRafael Espindola   Function::arg_iterator DI = Dst.arg_begin();
12183519da82SRafael Espindola   for (Argument &Arg : Src.args()) {
1219a314d1acSRafael Espindola     DI->setName(Arg.getName());  // Copy the name over.
1220361e513dSReid Spencer 
1221b1ed91f3SChris Lattner     // Add a mapping to our mapping.
1222a314d1acSRafael Espindola     ValueMap[&Arg] = DI;
1223a314d1acSRafael Espindola     ++DI;
1224361e513dSReid Spencer   }
1225361e513dSReid Spencer 
1226c8d987b1SDuncan P. N. Exon Smith   // Copy over the metadata attachments.
1227c8d987b1SDuncan P. N. Exon Smith   SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1228c8d987b1SDuncan P. N. Exon Smith   Src.getAllMetadata(MDs);
1229c8d987b1SDuncan P. N. Exon Smith   for (const auto &I : MDs)
12304fb46cb8SDuncan P. N. Exon Smith     Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, RF_MoveDistinctMDs,
12314fb46cb8SDuncan P. N. Exon Smith                                          &TypeMap, &ValMaterializer));
1232c8d987b1SDuncan P. N. Exon Smith 
12332f0557d0SChris Lattner   // Splice the body of the source function into the dest function.
1234ef23711eSRafael Espindola   Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
1235361e513dSReid Spencer 
1236361e513dSReid Spencer   // At this point, all of the instructions and values of the function are now
1237361e513dSReid Spencer   // copied over.  The only problem is that they are still referencing values in
1238361e513dSReid Spencer   // the Source function as operands.  Loop through all of the operands of the
123943f8d164SChris Lattner   // functions and patch them up to point to the local versions.
1240ef23711eSRafael Espindola   for (BasicBlock &BB : Dst)
1241a314d1acSRafael Espindola     for (Instruction &I : BB)
12424fb46cb8SDuncan P. N. Exon Smith       RemapInstruction(&I, ValueMap,
12434fb46cb8SDuncan P. N. Exon Smith                        RF_IgnoreMissingEntries | RF_MoveDistinctMDs, &TypeMap,
12449f8eff31SRafael Espindola                        &ValMaterializer);
1245cbb91408STanya Lattner 
12467391dde1SChris Lattner   // There is no need to map the arguments anymore.
12473519da82SRafael Espindola   for (Argument &Arg : Src.args())
1248a314d1acSRafael Espindola     ValueMap.erase(&Arg);
1249cbb91408STanya Lattner 
125097cb5657SEric Christopher   Src.dematerialize();
125140d7ebedSRafael Espindola   return false;
1252361e513dSReid Spencer }
1253361e513dSReid Spencer 
1254ef23711eSRafael Espindola void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1255ef23711eSRafael Espindola   Constant *Aliasee = Src.getAliasee();
12564fb46cb8SDuncan P. N. Exon Smith   Constant *Val = MapValue(Aliasee, ValueMap, RF_MoveDistinctMDs, &TypeMap,
12574fb46cb8SDuncan P. N. Exon Smith                            &ValMaterializer);
1258ef23711eSRafael Espindola   Dst.setAliasee(Val);
12592c4a34aeSDavid Chisnall }
1260ef23711eSRafael Espindola 
1261ef23711eSRafael Espindola bool ModuleLinker::linkGlobalValueBody(GlobalValue &Src) {
1262ef23711eSRafael Espindola   Value *Dst = ValueMap[&Src];
1263ef23711eSRafael Espindola   assert(Dst);
1264020d4fb1SArtem Belevich   if (shouldInternalizeLinkedSymbols())
1265020d4fb1SArtem Belevich     if (auto *DGV = dyn_cast<GlobalValue>(Dst))
1266020d4fb1SArtem Belevich       DGV->setLinkage(GlobalValue::InternalLinkage);
1267ef23711eSRafael Espindola   if (auto *F = dyn_cast<Function>(&Src))
1268ef23711eSRafael Espindola     return linkFunctionBody(cast<Function>(*Dst), *F);
1269ef23711eSRafael Espindola   if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1270ef23711eSRafael Espindola     linkGlobalInit(cast<GlobalVariable>(*Dst), *GVar);
1271ef23711eSRafael Espindola     return false;
1272b1ed91f3SChris Lattner   }
1273ef23711eSRafael Espindola   linkAliasBody(cast<GlobalAlias>(*Dst), cast<GlobalAlias>(Src));
1274ef23711eSRafael Espindola   return false;
1275cbb91408STanya Lattner }
1276b1ed91f3SChris Lattner 
127718c89411SRafael Espindola /// Insert all of the named MDNodes in Src into the Dest module.
1278b1ed91f3SChris Lattner void ModuleLinker::linkNamedMDNodes() {
127966f02413SBill Wendling   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
12803bf3f1f5SYaron Keren   for (const NamedMDNode &NMD : SrcM->named_metadata()) {
128166f02413SBill Wendling     // Don't link module flags here. Do them separately.
12823bf3f1f5SYaron Keren     if (&NMD == SrcModFlags)
12833bf3f1f5SYaron Keren       continue;
12843bf3f1f5SYaron Keren     NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(NMD.getName());
1285b1ed91f3SChris Lattner     // Add Src elements into Dest node.
12863bf3f1f5SYaron Keren     for (const MDNode *op : NMD.operands())
12874fb46cb8SDuncan P. N. Exon Smith       DestNMD->addOperand(MapMetadata(op, ValueMap, RF_MoveDistinctMDs,
12884fb46cb8SDuncan P. N. Exon Smith                                       &TypeMap, &ValMaterializer));
1289b1ed91f3SChris Lattner   }
1290b1ed91f3SChris Lattner }
1291b1ed91f3SChris Lattner 
1292fda0cee7SDuncan P. N. Exon Smith /// Drop DISubprograms that have been superseded.
1293fda0cee7SDuncan P. N. Exon Smith ///
1294c947892dSDuncan P. N. Exon Smith /// FIXME: this creates an asymmetric result: we strip functions from losing
1295c947892dSDuncan P. N. Exon Smith /// subprograms in DstM, but leave losing subprograms in SrcM.
1296c947892dSDuncan P. N. Exon Smith /// TODO: Remove this logic once the backend can correctly determine canonical
1297c947892dSDuncan P. N. Exon Smith /// subprograms.
1298fda0cee7SDuncan P. N. Exon Smith void ModuleLinker::stripReplacedSubprograms() {
1299fda0cee7SDuncan P. N. Exon Smith   // Avoid quadratic runtime by returning early when there's nothing to do.
1300fda0cee7SDuncan P. N. Exon Smith   if (OverridingFunctions.empty())
1301fda0cee7SDuncan P. N. Exon Smith     return;
1302fda0cee7SDuncan P. N. Exon Smith 
1303fda0cee7SDuncan P. N. Exon Smith   // Move the functions now, so the set gets cleared even on early returns.
1304fda0cee7SDuncan P. N. Exon Smith   auto Functions = std::move(OverridingFunctions);
1305fda0cee7SDuncan P. N. Exon Smith   OverridingFunctions.clear();
1306fda0cee7SDuncan P. N. Exon Smith 
1307c947892dSDuncan P. N. Exon Smith   // Drop functions from subprograms if they've been overridden by the new
1308c947892dSDuncan P. N. Exon Smith   // compile unit.
1309fda0cee7SDuncan P. N. Exon Smith   NamedMDNode *CompileUnits = DstM->getNamedMetadata("llvm.dbg.cu");
1310fda0cee7SDuncan P. N. Exon Smith   if (!CompileUnits)
1311fda0cee7SDuncan P. N. Exon Smith     return;
1312fda0cee7SDuncan P. N. Exon Smith   for (unsigned I = 0, E = CompileUnits->getNumOperands(); I != E; ++I) {
1313a9308c49SDuncan P. N. Exon Smith     auto *CU = cast<DICompileUnit>(CompileUnits->getOperand(I));
1314fda0cee7SDuncan P. N. Exon Smith     assert(CU && "Expected valid compile unit");
1315fda0cee7SDuncan P. N. Exon Smith 
1316a9308c49SDuncan P. N. Exon Smith     for (DISubprogram *SP : CU->getSubprograms()) {
1317537b4a81SDuncan P. N. Exon Smith       if (!SP || !SP->getFunction() || !Functions.count(SP->getFunction()))
1318fda0cee7SDuncan P. N. Exon Smith         continue;
1319fda0cee7SDuncan P. N. Exon Smith 
1320c947892dSDuncan P. N. Exon Smith       // Prevent DebugInfoFinder from tagging this as the canonical subprogram,
1321c947892dSDuncan P. N. Exon Smith       // since the canonical one is in the incoming module.
1322c947892dSDuncan P. N. Exon Smith       SP->replaceFunction(nullptr);
1323fda0cee7SDuncan P. N. Exon Smith     }
1324fda0cee7SDuncan P. N. Exon Smith   }
1325fda0cee7SDuncan P. N. Exon Smith }
1326fda0cee7SDuncan P. N. Exon Smith 
132718c89411SRafael Espindola /// Merge the linker flags in Src into the Dest module.
132866f02413SBill Wendling bool ModuleLinker::linkModuleFlagsMetadata() {
13290ec72bbcSDaniel Dunbar   // If the source module has no module flags, we are done.
133066f02413SBill Wendling   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
133166f02413SBill Wendling   if (!SrcModFlags) return false;
133266f02413SBill Wendling 
133366f02413SBill Wendling   // If the destination module doesn't have module flags yet, then just copy
133466f02413SBill Wendling   // over the source module's flags.
13350ec72bbcSDaniel Dunbar   NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
133666f02413SBill Wendling   if (DstModFlags->getNumOperands() == 0) {
133766f02413SBill Wendling     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
133866f02413SBill Wendling       DstModFlags->addOperand(SrcModFlags->getOperand(I));
133966f02413SBill Wendling 
134066f02413SBill Wendling     return false;
134166f02413SBill Wendling   }
134266f02413SBill Wendling 
13430ec72bbcSDaniel Dunbar   // First build a map of the existing module flags and requirements.
1344df55d8baSDuncan P. N. Exon Smith   DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
13450ec72bbcSDaniel Dunbar   SmallSetVector<MDNode*, 16> Requirements;
13460ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1347de36e804SDuncan P. N. Exon Smith     MDNode *Op = DstModFlags->getOperand(I);
13485bf8fef5SDuncan P. N. Exon Smith     ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
13490ec72bbcSDaniel Dunbar     MDString *ID = cast<MDString>(Op->getOperand(1));
13500ec72bbcSDaniel Dunbar 
13510ec72bbcSDaniel Dunbar     if (Behavior->getZExtValue() == Module::Require) {
13520ec72bbcSDaniel Dunbar       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
13530ec72bbcSDaniel Dunbar     } else {
1354df55d8baSDuncan P. N. Exon Smith       Flags[ID] = std::make_pair(Op, I);
13550ec72bbcSDaniel Dunbar     }
13560ec72bbcSDaniel Dunbar   }
13570ec72bbcSDaniel Dunbar 
13580ec72bbcSDaniel Dunbar   // Merge in the flags from the source module, and also collect its set of
13590ec72bbcSDaniel Dunbar   // requirements.
136066f02413SBill Wendling   bool HasErr = false;
13610ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1362de36e804SDuncan P. N. Exon Smith     MDNode *SrcOp = SrcModFlags->getOperand(I);
13635bf8fef5SDuncan P. N. Exon Smith     ConstantInt *SrcBehavior =
13645bf8fef5SDuncan P. N. Exon Smith         mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
13650ec72bbcSDaniel Dunbar     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1366df55d8baSDuncan P. N. Exon Smith     MDNode *DstOp;
1367df55d8baSDuncan P. N. Exon Smith     unsigned DstIndex;
1368df55d8baSDuncan P. N. Exon Smith     std::tie(DstOp, DstIndex) = Flags.lookup(ID);
13690ec72bbcSDaniel Dunbar     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
137066f02413SBill Wendling 
13710ec72bbcSDaniel Dunbar     // If this is a requirement, add it and continue.
13720ec72bbcSDaniel Dunbar     if (SrcBehaviorValue == Module::Require) {
13730ec72bbcSDaniel Dunbar       // If the destination module does not already have this requirement, add
13740ec72bbcSDaniel Dunbar       // it.
13750ec72bbcSDaniel Dunbar       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
13760ec72bbcSDaniel Dunbar         DstModFlags->addOperand(SrcOp);
13770ec72bbcSDaniel Dunbar       }
13780ec72bbcSDaniel Dunbar       continue;
13790ec72bbcSDaniel Dunbar     }
138066f02413SBill Wendling 
13810ec72bbcSDaniel Dunbar     // If there is no existing flag with this ID, just add it.
13820ec72bbcSDaniel Dunbar     if (!DstOp) {
1383df55d8baSDuncan P. N. Exon Smith       Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
13840ec72bbcSDaniel Dunbar       DstModFlags->addOperand(SrcOp);
13850ec72bbcSDaniel Dunbar       continue;
13860ec72bbcSDaniel Dunbar     }
138766f02413SBill Wendling 
13880ec72bbcSDaniel Dunbar     // Otherwise, perform a merge.
13895bf8fef5SDuncan P. N. Exon Smith     ConstantInt *DstBehavior =
13905bf8fef5SDuncan P. N. Exon Smith         mdconst::extract<ConstantInt>(DstOp->getOperand(0));
13910ec72bbcSDaniel Dunbar     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
13920ec72bbcSDaniel Dunbar 
13930ec72bbcSDaniel Dunbar     // If either flag has override behavior, handle it first.
13940ec72bbcSDaniel Dunbar     if (DstBehaviorValue == Module::Override) {
13950ec72bbcSDaniel Dunbar       // Diagnose inconsistent flags which both have override behavior.
13960ec72bbcSDaniel Dunbar       if (SrcBehaviorValue == Module::Override &&
13970ec72bbcSDaniel Dunbar           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
13980ec72bbcSDaniel Dunbar         HasErr |= emitError("linking module flags '" + ID->getString() +
13990ec72bbcSDaniel Dunbar                             "': IDs have conflicting override values");
14000ec72bbcSDaniel Dunbar       }
14010ec72bbcSDaniel Dunbar       continue;
14020ec72bbcSDaniel Dunbar     } else if (SrcBehaviorValue == Module::Override) {
14030ec72bbcSDaniel Dunbar       // Update the destination flag to that of the source.
1404df55d8baSDuncan P. N. Exon Smith       DstModFlags->setOperand(DstIndex, SrcOp);
1405df55d8baSDuncan P. N. Exon Smith       Flags[ID].first = SrcOp;
14060ec72bbcSDaniel Dunbar       continue;
14070ec72bbcSDaniel Dunbar     }
14080ec72bbcSDaniel Dunbar 
14090ec72bbcSDaniel Dunbar     // Diagnose inconsistent merge behavior types.
14100ec72bbcSDaniel Dunbar     if (SrcBehaviorValue != DstBehaviorValue) {
14110ec72bbcSDaniel Dunbar       HasErr |= emitError("linking module flags '" + ID->getString() +
141266f02413SBill Wendling                           "': IDs have conflicting behaviors");
14130ec72bbcSDaniel Dunbar       continue;
141466f02413SBill Wendling     }
141566f02413SBill Wendling 
1416df55d8baSDuncan P. N. Exon Smith     auto replaceDstValue = [&](MDNode *New) {
1417df55d8baSDuncan P. N. Exon Smith       Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1418df55d8baSDuncan P. N. Exon Smith       MDNode *Flag = MDNode::get(DstM->getContext(), FlagOps);
1419df55d8baSDuncan P. N. Exon Smith       DstModFlags->setOperand(DstIndex, Flag);
1420df55d8baSDuncan P. N. Exon Smith       Flags[ID].first = Flag;
1421df55d8baSDuncan P. N. Exon Smith     };
1422df55d8baSDuncan P. N. Exon Smith 
14230ec72bbcSDaniel Dunbar     // Perform the merge for standard behavior types.
14240ec72bbcSDaniel Dunbar     switch (SrcBehaviorValue) {
14250ec72bbcSDaniel Dunbar     case Module::Require:
14262a30d788SCraig Topper     case Module::Override: llvm_unreachable("not possible");
14270ec72bbcSDaniel Dunbar     case Module::Error: {
14280ec72bbcSDaniel Dunbar       // Emit an error if the values differ.
14290ec72bbcSDaniel Dunbar       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
14300ec72bbcSDaniel Dunbar         HasErr |= emitError("linking module flags '" + ID->getString() +
14310ec72bbcSDaniel Dunbar                             "': IDs have conflicting values");
143266f02413SBill Wendling       }
14330ec72bbcSDaniel Dunbar       continue;
143466f02413SBill Wendling     }
14350ec72bbcSDaniel Dunbar     case Module::Warning: {
14360ec72bbcSDaniel Dunbar       // Emit a warning if the values differ.
14370ec72bbcSDaniel Dunbar       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1438d12b4a33SRafael Espindola         emitWarning("linking module flags '" + ID->getString() +
1439d12b4a33SRafael Espindola                     "': IDs have conflicting values");
1440e17f3708SEli Bendersky       }
14410ec72bbcSDaniel Dunbar       continue;
14420ec72bbcSDaniel Dunbar     }
1443d77d9fb0SDaniel Dunbar     case Module::Append: {
1444d77d9fb0SDaniel Dunbar       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1445d77d9fb0SDaniel Dunbar       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
14465bf8fef5SDuncan P. N. Exon Smith       SmallVector<Metadata *, 8> MDs;
14475bf8fef5SDuncan P. N. Exon Smith       MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
14486cd780ffSBenjamin Kramer       MDs.append(DstValue->op_begin(), DstValue->op_end());
14496cd780ffSBenjamin Kramer       MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1450df55d8baSDuncan P. N. Exon Smith 
1451df55d8baSDuncan P. N. Exon Smith       replaceDstValue(MDNode::get(DstM->getContext(), MDs));
1452d77d9fb0SDaniel Dunbar       break;
1453d77d9fb0SDaniel Dunbar     }
1454d77d9fb0SDaniel Dunbar     case Module::AppendUnique: {
14555bf8fef5SDuncan P. N. Exon Smith       SmallSetVector<Metadata *, 16> Elts;
1456d77d9fb0SDaniel Dunbar       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1457d77d9fb0SDaniel Dunbar       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
14586cd780ffSBenjamin Kramer       Elts.insert(DstValue->op_begin(), DstValue->op_end());
14596cd780ffSBenjamin Kramer       Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1460df55d8baSDuncan P. N. Exon Smith 
1461df55d8baSDuncan P. N. Exon Smith       replaceDstValue(MDNode::get(DstM->getContext(),
14625bf8fef5SDuncan P. N. Exon Smith                                   makeArrayRef(Elts.begin(), Elts.end())));
1463d77d9fb0SDaniel Dunbar       break;
1464d77d9fb0SDaniel Dunbar     }
146566f02413SBill Wendling     }
146666f02413SBill Wendling   }
146766f02413SBill Wendling 
14680ec72bbcSDaniel Dunbar   // Check all of the requirements.
14690ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
14700ec72bbcSDaniel Dunbar     MDNode *Requirement = Requirements[I];
14710ec72bbcSDaniel Dunbar     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
14725bf8fef5SDuncan P. N. Exon Smith     Metadata *ReqValue = Requirement->getOperand(1);
14730ec72bbcSDaniel Dunbar 
1474df55d8baSDuncan P. N. Exon Smith     MDNode *Op = Flags[Flag].first;
14750ec72bbcSDaniel Dunbar     if (!Op || Op->getOperand(2) != ReqValue) {
14760ec72bbcSDaniel Dunbar       HasErr |= emitError("linking module flags '" + Flag->getString() +
14779273b539SBill Wendling                           "': does not have the required value");
14780ec72bbcSDaniel Dunbar       continue;
147966f02413SBill Wendling     }
148066f02413SBill Wendling   }
148166f02413SBill Wendling 
148266f02413SBill Wendling   return HasErr;
148366f02413SBill Wendling }
148466f02413SBill Wendling 
1485c43df518SAkira Hatanaka // This function returns true if the triples match.
1486c43df518SAkira Hatanaka static bool triplesMatch(const Triple &T0, const Triple &T1) {
1487c43df518SAkira Hatanaka   // If vendor is apple, ignore the version number.
1488c43df518SAkira Hatanaka   if (T0.getVendor() == Triple::Apple)
1489c43df518SAkira Hatanaka     return T0.getArch() == T1.getArch() &&
1490c43df518SAkira Hatanaka            T0.getSubArch() == T1.getSubArch() &&
1491c43df518SAkira Hatanaka            T0.getVendor() == T1.getVendor() &&
1492c43df518SAkira Hatanaka            T0.getOS() == T1.getOS();
1493c43df518SAkira Hatanaka 
1494c43df518SAkira Hatanaka   return T0 == T1;
1495c43df518SAkira Hatanaka }
1496c43df518SAkira Hatanaka 
1497c43df518SAkira Hatanaka // This function returns the merged triple.
1498c43df518SAkira Hatanaka static std::string mergeTriples(const Triple &SrcTriple, const Triple &DstTriple) {
1499c43df518SAkira Hatanaka   // If vendor is apple, pick the triple with the larger version number.
1500c43df518SAkira Hatanaka   if (SrcTriple.getVendor() == Triple::Apple)
1501c43df518SAkira Hatanaka     if (DstTriple.isOSVersionLT(SrcTriple))
1502c43df518SAkira Hatanaka       return SrcTriple.str();
1503c43df518SAkira Hatanaka 
1504c43df518SAkira Hatanaka   return DstTriple.str();
1505c43df518SAkira Hatanaka }
1506c43df518SAkira Hatanaka 
1507b1ed91f3SChris Lattner bool ModuleLinker::run() {
150866f02413SBill Wendling   assert(DstM && "Null destination module");
150966f02413SBill Wendling   assert(SrcM && "Null source module");
1510b1ed91f3SChris Lattner 
1511b1ed91f3SChris Lattner   // Inherit the target data from the source module if the destination module
1512b1ed91f3SChris Lattner   // doesn't have one already.
151346a43556SMehdi Amini   if (DstM->getDataLayout().isDefault())
1514b1ed91f3SChris Lattner     DstM->setDataLayout(SrcM->getDataLayout());
1515b1ed91f3SChris Lattner 
151646a43556SMehdi Amini   if (SrcM->getDataLayout() != DstM->getDataLayout()) {
1517d12b4a33SRafael Espindola     emitWarning("Linking two modules of different data layouts: '" +
1518d12b4a33SRafael Espindola                 SrcM->getModuleIdentifier() + "' is '" +
1519d12b4a33SRafael Espindola                 SrcM->getDataLayoutStr() + "' whereas '" +
1520d12b4a33SRafael Espindola                 DstM->getModuleIdentifier() + "' is '" +
1521d12b4a33SRafael Espindola                 DstM->getDataLayoutStr() + "'\n");
1522e17f3708SEli Bendersky   }
1523c43df518SAkira Hatanaka 
1524c43df518SAkira Hatanaka   // Copy the target triple from the source to dest if the dest's is empty.
1525c43df518SAkira Hatanaka   if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1526c43df518SAkira Hatanaka     DstM->setTargetTriple(SrcM->getTargetTriple());
1527c43df518SAkira Hatanaka 
1528c43df518SAkira Hatanaka   Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM->getTargetTriple());
1529c43df518SAkira Hatanaka 
1530c43df518SAkira Hatanaka   if (!SrcM->getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
1531d12b4a33SRafael Espindola     emitWarning("Linking two modules of different target triples: " +
1532d12b4a33SRafael Espindola                 SrcM->getModuleIdentifier() + "' is '" +
1533d12b4a33SRafael Espindola                 SrcM->getTargetTriple() + "' whereas '" +
1534d12b4a33SRafael Espindola                 DstM->getModuleIdentifier() + "' is '" +
1535d12b4a33SRafael Espindola                 DstM->getTargetTriple() + "'\n");
1536c43df518SAkira Hatanaka 
1537c43df518SAkira Hatanaka   DstM->setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1538b1ed91f3SChris Lattner 
1539b1ed91f3SChris Lattner   // Append the module inline asm string.
1540b1ed91f3SChris Lattner   if (!SrcM->getModuleInlineAsm().empty()) {
1541b1ed91f3SChris Lattner     if (DstM->getModuleInlineAsm().empty())
1542b1ed91f3SChris Lattner       DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1543b1ed91f3SChris Lattner     else
1544b1ed91f3SChris Lattner       DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1545b1ed91f3SChris Lattner                                SrcM->getModuleInlineAsm());
1546b1ed91f3SChris Lattner   }
1547b1ed91f3SChris Lattner 
1548b1ed91f3SChris Lattner   // Loop over all of the linked values to compute type mappings.
1549b1ed91f3SChris Lattner   computeTypeMapping();
1550b1ed91f3SChris Lattner 
1551dad0a645SDavid Majnemer   ComdatsChosen.clear();
15525106ce78SDavid Blaikie   for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
1553dad0a645SDavid Majnemer     const Comdat &C = SMEC.getValue();
1554dad0a645SDavid Majnemer     if (ComdatsChosen.count(&C))
1555dad0a645SDavid Majnemer       continue;
1556dad0a645SDavid Majnemer     Comdat::SelectionKind SK;
1557dad0a645SDavid Majnemer     bool LinkFromSrc;
1558dad0a645SDavid Majnemer     if (getComdatResult(&C, SK, LinkFromSrc))
1559dad0a645SDavid Majnemer       return true;
1560dad0a645SDavid Majnemer     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1561dad0a645SDavid Majnemer   }
1562dad0a645SDavid Majnemer 
156309d84addSDuncan P. N. Exon Smith   // Upgrade mismatched global arrays.
156409d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobals();
156509d84addSDuncan P. N. Exon Smith 
1566b1ed91f3SChris Lattner   // Insert all of the globals in src into the DstM module... without linking
1567b1ed91f3SChris Lattner   // initializers (which could refer to functions not yet mapped over).
15683bf3f1f5SYaron Keren   for (GlobalVariable &GV : SrcM->globals())
15693bf3f1f5SYaron Keren     if (linkGlobalValueProto(&GV))
1570b1ed91f3SChris Lattner       return true;
1571b1ed91f3SChris Lattner 
1572b1ed91f3SChris Lattner   // Link the functions together between the two modules, without doing function
1573b1ed91f3SChris Lattner   // bodies... this just adds external function prototypes to the DstM
1574b1ed91f3SChris Lattner   // function...  We do this so that when we begin processing function bodies,
1575b1ed91f3SChris Lattner   // all of the global values that may be referenced are available in our
1576b1ed91f3SChris Lattner   // ValueMap.
15773bf3f1f5SYaron Keren   for (Function &F :*SrcM)
15783bf3f1f5SYaron Keren     if (linkGlobalValueProto(&F))
1579b1ed91f3SChris Lattner       return true;
1580b1ed91f3SChris Lattner 
1581b1ed91f3SChris Lattner   // If there were any aliases, link them now.
15823bf3f1f5SYaron Keren   for (GlobalAlias &GA : SrcM->aliases())
15833bf3f1f5SYaron Keren     if (linkGlobalValueProto(&GA))
1584b1ed91f3SChris Lattner       return true;
1585b1ed91f3SChris Lattner 
15863bf3f1f5SYaron Keren   for (const AppendingVarInfo &AppendingVar : AppendingVars)
15873bf3f1f5SYaron Keren     linkAppendingVarInit(AppendingVar);
1588b1ed91f3SChris Lattner 
1589beadd56aSRafael Espindola   for (const auto &Entry : DstM->getComdatSymbolTable()) {
1590beadd56aSRafael Espindola     const Comdat &C = Entry.getValue();
1591beadd56aSRafael Espindola     if (C.getSelectionKind() == Comdat::Any)
1592beadd56aSRafael Espindola       continue;
1593beadd56aSRafael Espindola     const GlobalValue *GV = SrcM->getNamedValue(C.getName());
1594ea45d834SPeter Collingbourne     if (GV)
15954fb46cb8SDuncan P. N. Exon Smith       MapValue(GV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1596beadd56aSRafael Espindola   }
1597beadd56aSRafael Espindola 
1598c947892dSDuncan P. N. Exon Smith   // Strip replaced subprograms before mapping any metadata -- so that we're
1599c947892dSDuncan P. N. Exon Smith   // not changing metadata from the source module (note that
1600c947892dSDuncan P. N. Exon Smith   // linkGlobalValueBody() eventually calls RemapInstruction() and therefore
1601c947892dSDuncan P. N. Exon Smith   // MapMetadata()) -- but after linking global value protocols -- so that
1602c947892dSDuncan P. N. Exon Smith   // OverridingFunctions has been built.
1603c947892dSDuncan P. N. Exon Smith   stripReplacedSubprograms();
1604c947892dSDuncan P. N. Exon Smith 
1605b1ed91f3SChris Lattner   // Link in the function bodies that are defined in the source module into
1606b1ed91f3SChris Lattner   // DstM.
1607f97d0cbeSRafael Espindola   for (Function &SF : *SrcM) {
1608d4bcefc7SRafael Espindola     // Skip if no body (function is external).
1609f97d0cbeSRafael Espindola     if (SF.isDeclaration())
1610d4bcefc7SRafael Espindola       continue;
1611d4bcefc7SRafael Espindola 
1612f97d0cbeSRafael Espindola     // Skip if not linking from source.
1613f97d0cbeSRafael Espindola     if (DoNotLinkFromSource.count(&SF))
1614f97d0cbeSRafael Espindola       continue;
1615f97d0cbeSRafael Espindola 
1616ef23711eSRafael Espindola     if (linkGlobalValueBody(SF))
161740d7ebedSRafael Espindola       return true;
1618b1ed91f3SChris Lattner   }
1619b1ed91f3SChris Lattner 
1620b1ed91f3SChris Lattner   // Resolve all uses of aliases with aliasees.
1621ef23711eSRafael Espindola   for (GlobalAlias &Src : SrcM->aliases()) {
1622ef23711eSRafael Espindola     if (DoNotLinkFromSource.count(&Src))
1623ef23711eSRafael Espindola       continue;
1624ef23711eSRafael Espindola     linkGlobalValueBody(Src);
1625ef23711eSRafael Espindola   }
1626b1ed91f3SChris Lattner 
162766f02413SBill Wendling   // Remap all of the named MDNodes in Src into the DstM module. We do this
16286ddbb2e2SDevang Patel   // after linking GlobalValues so that MDNodes that reference GlobalValues
16296ddbb2e2SDevang Patel   // are properly remapped.
16306ddbb2e2SDevang Patel   linkNamedMDNodes();
16316ddbb2e2SDevang Patel 
163266f02413SBill Wendling   // Merge the module flags into the DstM module.
163366f02413SBill Wendling   if (linkModuleFlagsMetadata())
163466f02413SBill Wendling     return true;
163566f02413SBill Wendling 
163691686d6dSBill Wendling   // Update the initializers in the DstM module now that all globals that may
163791686d6dSBill Wendling   // be referenced are in DstM.
1638ef23711eSRafael Espindola   for (GlobalVariable &Src : SrcM->globals()) {
1639ef23711eSRafael Espindola     // Only process initialized GV's or ones not already in dest.
1640ef23711eSRafael Espindola     if (!Src.hasInitializer() || DoNotLinkFromSource.count(&Src))
1641ef23711eSRafael Espindola       continue;
1642ef23711eSRafael Espindola     linkGlobalValueBody(Src);
1643ef23711eSRafael Espindola   }
164491686d6dSBill Wendling 
16450a48b877STanya Lattner   // Process vector of lazily linked in functions.
1646ef23711eSRafael Espindola   while (!LazilyLinkGlobalValues.empty()) {
1647ef23711eSRafael Espindola     GlobalValue *SGV = LazilyLinkGlobalValues.back();
1648ef23711eSRafael Espindola     LazilyLinkGlobalValues.pop_back();
16490a48b877STanya Lattner 
1650020d4fb1SArtem Belevich     // Skip declarations that ValueMaterializer may have created in
1651020d4fb1SArtem Belevich     // case we link in only some of SrcM.
1652020d4fb1SArtem Belevich     if (shouldLinkOnlyNeeded() && SGV->isDeclaration())
1653020d4fb1SArtem Belevich       continue;
1654020d4fb1SArtem Belevich 
16559573a9cfSRafael Espindola     assert(!SGV->isDeclaration() && "users should not pass down decls");
1656ef23711eSRafael Espindola     if (linkGlobalValueBody(*SGV))
165740d7ebedSRafael Espindola       return true;
16580a48b877STanya Lattner   }
16590a48b877STanya Lattner 
16602609888fSAnton Korobeynikov   return false;
16612609888fSAnton Korobeynikov }
1662361e513dSReid Spencer 
166331ad468dSRafael Espindola Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
166431ad468dSRafael Espindola     : ETypes(E), IsPacked(P) {}
166531ad468dSRafael Espindola 
166631ad468dSRafael Espindola Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
166731ad468dSRafael Espindola     : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
166831ad468dSRafael Espindola 
166931ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
167031ad468dSRafael Espindola   if (IsPacked != That.IsPacked)
167131ad468dSRafael Espindola     return false;
167231ad468dSRafael Espindola   if (ETypes != That.ETypes)
167331ad468dSRafael Espindola     return false;
167431ad468dSRafael Espindola   return true;
167531ad468dSRafael Espindola }
167631ad468dSRafael Espindola 
167731ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
167831ad468dSRafael Espindola   return !this->operator==(That);
167931ad468dSRafael Espindola }
168031ad468dSRafael Espindola 
168131ad468dSRafael Espindola StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
168231ad468dSRafael Espindola   return DenseMapInfo<StructType *>::getEmptyKey();
168331ad468dSRafael Espindola }
168431ad468dSRafael Espindola 
168531ad468dSRafael Espindola StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
168631ad468dSRafael Espindola   return DenseMapInfo<StructType *>::getTombstoneKey();
168731ad468dSRafael Espindola }
168831ad468dSRafael Espindola 
168931ad468dSRafael Espindola unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
169031ad468dSRafael Espindola   return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
169131ad468dSRafael Espindola                       Key.IsPacked);
169231ad468dSRafael Espindola }
169331ad468dSRafael Espindola 
169431ad468dSRafael Espindola unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
169531ad468dSRafael Espindola   return getHashValue(KeyTy(ST));
169631ad468dSRafael Espindola }
169731ad468dSRafael Espindola 
169831ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
169931ad468dSRafael Espindola                                         const StructType *RHS) {
170031ad468dSRafael Espindola   if (RHS == getEmptyKey() || RHS == getTombstoneKey())
170131ad468dSRafael Espindola     return false;
170231ad468dSRafael Espindola   return LHS == KeyTy(RHS);
170331ad468dSRafael Espindola }
170431ad468dSRafael Espindola 
170531ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
170631ad468dSRafael Espindola                                         const StructType *RHS) {
170731ad468dSRafael Espindola   if (RHS == getEmptyKey())
170831ad468dSRafael Espindola     return LHS == getEmptyKey();
170931ad468dSRafael Espindola 
171031ad468dSRafael Espindola   if (RHS == getTombstoneKey())
171131ad468dSRafael Espindola     return LHS == getTombstoneKey();
171231ad468dSRafael Espindola 
171331ad468dSRafael Espindola   return KeyTy(LHS) == KeyTy(RHS);
171431ad468dSRafael Espindola }
171531ad468dSRafael Espindola 
171631ad468dSRafael Espindola void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
171731ad468dSRafael Espindola   assert(!Ty->isOpaque());
17183280a5d9SBenjamin Kramer   NonOpaqueStructTypes.insert(Ty);
171931ad468dSRafael Espindola }
172031ad468dSRafael Espindola 
1721a5b9e1cfSRafael Espindola void Linker::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1722a5b9e1cfSRafael Espindola   assert(!Ty->isOpaque());
1723a5b9e1cfSRafael Espindola   NonOpaqueStructTypes.insert(Ty);
1724a5b9e1cfSRafael Espindola   bool Removed = OpaqueStructTypes.erase(Ty);
1725a5b9e1cfSRafael Espindola   (void)Removed;
1726a5b9e1cfSRafael Espindola   assert(Removed);
1727a5b9e1cfSRafael Espindola }
1728a5b9e1cfSRafael Espindola 
172931ad468dSRafael Espindola void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
173031ad468dSRafael Espindola   assert(Ty->isOpaque());
173131ad468dSRafael Espindola   OpaqueStructTypes.insert(Ty);
173231ad468dSRafael Espindola }
173331ad468dSRafael Espindola 
173431ad468dSRafael Espindola StructType *
173531ad468dSRafael Espindola Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
173631ad468dSRafael Espindola                                                bool IsPacked) {
173731ad468dSRafael Espindola   Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
173831ad468dSRafael Espindola   auto I = NonOpaqueStructTypes.find_as(Key);
173931ad468dSRafael Espindola   if (I == NonOpaqueStructTypes.end())
174031ad468dSRafael Espindola     return nullptr;
17413280a5d9SBenjamin Kramer   return *I;
174231ad468dSRafael Espindola }
174331ad468dSRafael Espindola 
174431ad468dSRafael Espindola bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
174531ad468dSRafael Espindola   if (Ty->isOpaque())
174631ad468dSRafael Espindola     return OpaqueStructTypes.count(Ty);
174731ad468dSRafael Espindola   auto I = NonOpaqueStructTypes.find(Ty);
174831ad468dSRafael Espindola   if (I == NonOpaqueStructTypes.end())
174931ad468dSRafael Espindola     return false;
17503280a5d9SBenjamin Kramer   return *I == Ty;
175131ad468dSRafael Espindola }
175231ad468dSRafael Espindola 
17535cb9c82aSRafael Espindola void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
17545cb9c82aSRafael Espindola   this->Composite = M;
17555cb9c82aSRafael Espindola   this->DiagnosticHandler = DiagnosticHandler;
1756a4e85e3dSRafael Espindola 
1757a4e85e3dSRafael Espindola   TypeFinder StructTypes;
1758a4e85e3dSRafael Espindola   StructTypes.run(*M, true);
175931ad468dSRafael Espindola   for (StructType *Ty : StructTypes) {
176031ad468dSRafael Espindola     if (Ty->isOpaque())
176131ad468dSRafael Espindola       IdentifiedStructTypes.addOpaque(Ty);
176231ad468dSRafael Espindola     else
176331ad468dSRafael Espindola       IdentifiedStructTypes.addNonOpaque(Ty);
176431ad468dSRafael Espindola   }
1765aa9918aaSRafael Espindola }
17663df61b7bSRafael Espindola 
17675cb9c82aSRafael Espindola Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
17685cb9c82aSRafael Espindola   init(M, DiagnosticHandler);
17695cb9c82aSRafael Espindola }
17705cb9c82aSRafael Espindola 
17715cb9c82aSRafael Espindola Linker::Linker(Module *M) {
17725cb9c82aSRafael Espindola   init(M, [this](const DiagnosticInfo &DI) {
17735cb9c82aSRafael Espindola     Composite->getContext().diagnose(DI);
17745cb9c82aSRafael Espindola   });
17755cb9c82aSRafael Espindola }
17765cb9c82aSRafael Espindola 
177791e6f6e1SBill Wendling void Linker::deleteModule() {
177891e6f6e1SBill Wendling   delete Composite;
17792617dcceSCraig Topper   Composite = nullptr;
178091e6f6e1SBill Wendling }
178191e6f6e1SBill Wendling 
1782020d4fb1SArtem Belevich bool Linker::linkInModule(Module *Src, unsigned Flags) {
1783a4e85e3dSRafael Espindola   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
1784020d4fb1SArtem Belevich                          DiagnosticHandler, Flags);
1785dab999d5SManman Ren   bool RetCode = TheLinker.run();
1786dab999d5SManman Ren   Composite->dropTriviallyDeadConstantArrays();
1787dab999d5SManman Ren   return RetCode;
17883df61b7bSRafael Espindola }
17893df61b7bSRafael Espindola 
17906487ce95SManman Ren void Linker::setModule(Module *Dst) {
17916487ce95SManman Ren   init(Dst, DiagnosticHandler);
17926487ce95SManman Ren }
17936487ce95SManman Ren 
1794b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
1795b1ed91f3SChris Lattner // LinkModules entrypoint.
1796b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
1797b1ed91f3SChris Lattner 
179818c89411SRafael Espindola /// This function links two modules together, with the resulting Dest module
179918c89411SRafael Espindola /// modified to be the composite of the two input modules. If an error occurs,
180018c89411SRafael Espindola /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
180118c89411SRafael Espindola /// Upon failure, the Dest module could be in a modified state, and shouldn't be
180218c89411SRafael Espindola /// relied on to be consistent.
18039f8eff31SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src,
1804020d4fb1SArtem Belevich                          DiagnosticHandlerFunction DiagnosticHandler,
1805020d4fb1SArtem Belevich                          unsigned Flags) {
18064160f5d3SRafael Espindola   Linker L(Dest, DiagnosticHandler);
1807020d4fb1SArtem Belevich   return L.linkInModule(Src, Flags);
18084160f5d3SRafael Espindola }
18094160f5d3SRafael Espindola 
1810020d4fb1SArtem Belevich bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Flags) {
1811287f18b4SRafael Espindola   Linker L(Dest);
1812020d4fb1SArtem Belevich   return L.linkInModule(Src, Flags);
1813361e513dSReid Spencer }
1814a3aeb980SBill Wendling 
1815a3aeb980SBill Wendling //===----------------------------------------------------------------------===//
1816a3aeb980SBill Wendling // C API.
1817a3aeb980SBill Wendling //===----------------------------------------------------------------------===//
1818a3aeb980SBill Wendling 
1819a3aeb980SBill Wendling LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1820a57d588cSJuergen Ributzka                          LLVMLinkerMode Unused, char **OutMessages) {
182198ab63ceSRafael Espindola   Module *D = unwrap(Dest);
182298ab63ceSRafael Espindola   std::string Message;
18234160f5d3SRafael Espindola   raw_string_ostream Stream(Message);
18244160f5d3SRafael Espindola   DiagnosticPrinterRawOStream DP(Stream);
18254160f5d3SRafael Espindola 
18264160f5d3SRafael Espindola   LLVMBool Result = Linker::LinkModules(
18279f8eff31SRafael Espindola       D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
182898ab63ceSRafael Espindola 
1829ff715e2dSEli Bendersky   if (OutMessages && Result) {
1830ff715e2dSEli Bendersky     Stream.flush();
183198ab63ceSRafael Espindola     *OutMessages = strdup(Message.c_str());
1832ff715e2dSEli Bendersky   }
1833a3aeb980SBill Wendling   return Result;
1834a3aeb980SBill Wendling }
1835