159a5afa9SMikhail Glushenkov //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
2361e513dSReid Spencer //
3361e513dSReid Spencer //                     The LLVM Compiler Infrastructure
4361e513dSReid Spencer //
5f3ebc3f3SChris Lattner // This file is distributed under the University of Illinois Open Source
6f3ebc3f3SChris Lattner // License. See LICENSE.TXT for details.
7361e513dSReid Spencer //
8361e513dSReid Spencer //===----------------------------------------------------------------------===//
9361e513dSReid Spencer //
10361e513dSReid Spencer // This file implements the LLVM module linker.
11361e513dSReid Spencer //
12361e513dSReid Spencer //===----------------------------------------------------------------------===//
13361e513dSReid Spencer 
146cc07df4SChandler Carruth #include "llvm/Linker/Linker.h"
15ed0881b2SChandler Carruth #include "llvm-c/Linker.h"
1623f8d64bSRafael Espindola #include "llvm/ADT/Optional.h"
1766f02413SBill Wendling #include "llvm/ADT/SetVector.h"
180f7fd36fSEli Bendersky #include "llvm/ADT/SmallString.h"
199fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
20d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticInfo.h"
21d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticPrinter.h"
22d12b4a33SRafael Espindola #include "llvm/IR/LLVMContext.h"
239fb823bbSChandler Carruth #include "llvm/IR/Module.h"
24dcb603feSChandler Carruth #include "llvm/IR/TypeFinder.h"
25e17f3708SEli Bendersky #include "llvm/Support/CommandLine.h"
26b6af2f36SBill Wendling #include "llvm/Support/Debug.h"
27b6af2f36SBill Wendling #include "llvm/Support/raw_ostream.h"
28cbb91408STanya Lattner #include "llvm/Transforms/Utils/Cloning.h"
29981af002SWill Dietz #include <cctype>
3082d6ff6bSDavid Majnemer #include <tuple>
31361e513dSReid Spencer using namespace llvm;
32361e513dSReid Spencer 
33e17f3708SEli Bendersky 
34b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
35b1ed91f3SChris Lattner // TypeMap implementation.
36b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
37b1ed91f3SChris Lattner 
38b1ed91f3SChris Lattner namespace {
39aa9918aaSRafael Espindola typedef SmallPtrSet<StructType *, 32> TypeSet;
40aa9918aaSRafael Espindola 
41b1ed91f3SChris Lattner class TypeMapTy : public ValueMapTypeRemapper {
4218c89411SRafael Espindola   /// This is a mapping from a source type to a destination type to use.
43b1ed91f3SChris Lattner   DenseMap<Type*, Type*> MappedTypes;
44b1ed91f3SChris Lattner 
4518c89411SRafael Espindola   /// When checking to see if two subgraphs are isomorphic, we speculatively
4618c89411SRafael Espindola   /// add types to MappedTypes, but keep track of them here in case we need to
4718c89411SRafael Espindola   /// roll back.
48b1ed91f3SChris Lattner   SmallVector<Type*, 16> SpeculativeTypes;
49b1ed91f3SChris Lattner 
5018c89411SRafael Espindola   /// This is a list of non-opaque structs in the source module that are mapped
5118c89411SRafael Espindola   /// to an opaque struct in the destination module.
525e3bd972SChris Lattner   SmallVector<StructType*, 16> SrcDefinitionsToResolve;
535e3bd972SChris Lattner 
5418c89411SRafael Espindola   /// This is the set of opaque types in the destination modules who are
5518c89411SRafael Espindola   /// getting a body from the source module.
565e3bd972SChris Lattner   SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
57d48b7783SBill Wendling 
588c2cc416SBill Wendling public:
59aa9918aaSRafael Espindola   TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {}
60aa9918aaSRafael Espindola 
61aa9918aaSRafael Espindola   TypeSet &DstStructTypesSet;
6218c89411SRafael Espindola   /// Indicate that the specified type in the destination module is conceptually
6318c89411SRafael Espindola   /// equivalent to the specified type in the source module.
64b1ed91f3SChris Lattner   void addTypeMapping(Type *DstTy, Type *SrcTy);
65b1ed91f3SChris Lattner 
66d2a13a2eSRafael Espindola   /// Produce a body for an opaque type in the dest module from a type
67d2a13a2eSRafael Espindola   /// definition in the source module.
68b1ed91f3SChris Lattner   void linkDefinedTypeBodies();
69b1ed91f3SChris Lattner 
7018c89411SRafael Espindola   /// Return the mapped type to use for the specified input type from the
71b1ed91f3SChris Lattner   /// source module.
72b1ed91f3SChris Lattner   Type *get(Type *SrcTy);
73b1ed91f3SChris Lattner 
74b1ed91f3SChris Lattner   FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
75b1ed91f3SChris Lattner 
7618c89411SRafael Espindola   /// Dump out the type map for debugging purposes.
77b6af2f36SBill Wendling   void dump() const {
78b6af2f36SBill Wendling     for (DenseMap<Type*, Type*>::const_iterator
79b6af2f36SBill Wendling            I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
80b6af2f36SBill Wendling       dbgs() << "TypeMap: ";
81c0087f36SJustin Bogner       I->first->print(dbgs());
82b6af2f36SBill Wendling       dbgs() << " => ";
83c0087f36SJustin Bogner       I->second->print(dbgs());
84b6af2f36SBill Wendling       dbgs() << '\n';
85b6af2f36SBill Wendling     }
86b6af2f36SBill Wendling   }
87b6af2f36SBill Wendling 
88b1ed91f3SChris Lattner private:
89b1ed91f3SChris Lattner   Type *getImpl(Type *T);
9018c89411SRafael Espindola   /// Implement the ValueMapTypeRemapper interface.
918548299aSCraig Topper   Type *remapType(Type *SrcTy) override {
92b1ed91f3SChris Lattner     return get(SrcTy);
93b1ed91f3SChris Lattner   }
94b1ed91f3SChris Lattner 
95b1ed91f3SChris Lattner   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
96b1ed91f3SChris Lattner };
97b1ed91f3SChris Lattner }
98b1ed91f3SChris Lattner 
99b1ed91f3SChris Lattner void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
100b1ed91f3SChris Lattner   Type *&Entry = MappedTypes[SrcTy];
101b1ed91f3SChris Lattner   if (Entry) return;
102b1ed91f3SChris Lattner 
103b1ed91f3SChris Lattner   if (DstTy == SrcTy) {
104b1ed91f3SChris Lattner     Entry = DstTy;
105b1ed91f3SChris Lattner     return;
106b1ed91f3SChris Lattner   }
107b1ed91f3SChris Lattner 
108b1ed91f3SChris Lattner   // Check to see if these types are recursively isomorphic and establish a
109b1ed91f3SChris Lattner   // mapping between them if so.
11086911440SRafael Espindola   if (areTypesIsomorphic(DstTy, SrcTy)) {
11186911440SRafael Espindola     SpeculativeTypes.clear();
11286911440SRafael Espindola     return;
11386911440SRafael Espindola   }
11486911440SRafael Espindola 
115b1ed91f3SChris Lattner   // Oops, they aren't isomorphic. Just discard this request by rolling out
116b1ed91f3SChris Lattner   // any speculative mappings we've established.
11786911440SRafael Espindola   unsigned Removed = 0;
11886911440SRafael Espindola   for (unsigned I = 0, E = SpeculativeTypes.size(); I != E; ++I) {
11986911440SRafael Espindola     Type *SrcTy = SpeculativeTypes[I];
12086911440SRafael Espindola     auto Iter = MappedTypes.find(SrcTy);
12186911440SRafael Espindola     auto *DstTy = dyn_cast<StructType>(Iter->second);
12286911440SRafael Espindola     if (DstTy && DstResolvedOpaqueTypes.erase(DstTy))
12386911440SRafael Espindola       Removed++;
12486911440SRafael Espindola     MappedTypes.erase(Iter);
125d48b7783SBill Wendling   }
12686911440SRafael Espindola   SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() - Removed);
127b1ed91f3SChris Lattner   SpeculativeTypes.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.
134b1ed91f3SChris Lattner   if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
135b1ed91f3SChris Lattner 
136b1ed91f3SChris Lattner   // If we have an entry in the MappedTypes table, then we have our answer.
137b1ed91f3SChris Lattner   Type *&Entry = MappedTypes[SrcTy];
138b1ed91f3SChris Lattner   if (Entry)
139b1ed91f3SChris Lattner     return Entry == DstTy;
140b1ed91f3SChris Lattner 
141b1ed91f3SChris Lattner   // Two identical types are clearly isomorphic.  Remember this
142b1ed91f3SChris Lattner   // non-speculatively.
143b1ed91f3SChris Lattner   if (DstTy == SrcTy) {
144b1ed91f3SChris Lattner     Entry = DstTy;
145361e513dSReid Spencer     return true;
146361e513dSReid Spencer   }
147361e513dSReid Spencer 
148b1ed91f3SChris Lattner   // Okay, we have two types with identical kinds that we haven't seen before.
149361e513dSReid Spencer 
150b1ed91f3SChris Lattner   // If this is an opaque struct type, special case it.
151b1ed91f3SChris Lattner   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
152b1ed91f3SChris Lattner     // Mapping an opaque type to any struct, just keep the dest struct.
153b1ed91f3SChris Lattner     if (SSTy->isOpaque()) {
154b1ed91f3SChris Lattner       Entry = DstTy;
155b1ed91f3SChris Lattner       SpeculativeTypes.push_back(SrcTy);
156b1ed91f3SChris Lattner       return true;
157361e513dSReid Spencer     }
158b1ed91f3SChris Lattner 
1595e3bd972SChris Lattner     // Mapping a non-opaque source type to an opaque dest.  If this is the first
1605e3bd972SChris Lattner     // type that we're mapping onto this destination type then we succeed.  Keep
16186911440SRafael Espindola     // the dest, but fill it in later. If this is the second (different) type
16286911440SRafael Espindola     // that we're trying to map onto the same opaque type then we fail.
163b1ed91f3SChris Lattner     if (cast<StructType>(DstTy)->isOpaque()) {
1645e3bd972SChris Lattner       // We can only map one source type onto the opaque destination type.
16570573dcdSDavid Blaikie       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
1665e3bd972SChris Lattner         return false;
1675e3bd972SChris Lattner       SrcDefinitionsToResolve.push_back(SSTy);
16886911440SRafael Espindola       SpeculativeTypes.push_back(SrcTy);
169b1ed91f3SChris Lattner       Entry = DstTy;
170b1ed91f3SChris Lattner       return true;
171b1ed91f3SChris Lattner     }
172b1ed91f3SChris Lattner   }
173b1ed91f3SChris Lattner 
174b1ed91f3SChris Lattner   // If the number of subtypes disagree between the two types, then we fail.
175b1ed91f3SChris Lattner   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
176b1ed91f3SChris Lattner     return false;
177b1ed91f3SChris Lattner 
178b1ed91f3SChris Lattner   // Fail if any of the extra properties (e.g. array size) of the type disagree.
179b1ed91f3SChris Lattner   if (isa<IntegerType>(DstTy))
180b1ed91f3SChris Lattner     return false;  // bitwidth disagrees.
181b1ed91f3SChris Lattner   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
182b1ed91f3SChris Lattner     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
183b1ed91f3SChris Lattner       return false;
184eaf9b762SChris Lattner 
185b1ed91f3SChris Lattner   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
186b1ed91f3SChris Lattner     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
187b1ed91f3SChris Lattner       return false;
188b1ed91f3SChris Lattner   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
189b1ed91f3SChris Lattner     StructType *SSTy = cast<StructType>(SrcTy);
19044f7ab45SChris Lattner     if (DSTy->isLiteral() != SSTy->isLiteral() ||
191b1ed91f3SChris Lattner         DSTy->isPacked() != SSTy->isPacked())
192b1ed91f3SChris Lattner       return false;
193b1ed91f3SChris Lattner   } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
194b1ed91f3SChris Lattner     if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
195b1ed91f3SChris Lattner       return false;
196b1ed91f3SChris Lattner   } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
1975fad3e9aSJoey Gouly     if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
198361e513dSReid Spencer       return false;
199361e513dSReid Spencer   }
200361e513dSReid Spencer 
201b1ed91f3SChris Lattner   // Otherwise, we speculate that these two types will line up and recursively
202b1ed91f3SChris Lattner   // check the subelements.
203b1ed91f3SChris Lattner   Entry = DstTy;
204b1ed91f3SChris Lattner   SpeculativeTypes.push_back(SrcTy);
205eee6f995SChris Lattner 
206d48b7783SBill Wendling   for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
207d48b7783SBill Wendling     if (!areTypesIsomorphic(DstTy->getContainedType(i),
208d48b7783SBill Wendling                             SrcTy->getContainedType(i)))
209b1ed91f3SChris Lattner       return false;
210eee6f995SChris Lattner 
211b1ed91f3SChris Lattner   // If everything seems to have lined up, then everything is great.
212eee6f995SChris Lattner   return true;
213eee6f995SChris Lattner }
214eee6f995SChris Lattner 
215b1ed91f3SChris Lattner void TypeMapTy::linkDefinedTypeBodies() {
216b1ed91f3SChris Lattner   SmallVector<Type*, 16> Elements;
217b1ed91f3SChris Lattner   SmallString<16> TmpName;
218eee6f995SChris Lattner 
219b1ed91f3SChris Lattner   // Note that processing entries in this loop (calling 'get') can add new
2205e3bd972SChris Lattner   // entries to the SrcDefinitionsToResolve vector.
2215e3bd972SChris Lattner   while (!SrcDefinitionsToResolve.empty()) {
2225e3bd972SChris Lattner     StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
223b1ed91f3SChris Lattner     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
224eee6f995SChris Lattner 
225b1ed91f3SChris Lattner     // TypeMap is a many-to-one mapping, if there were multiple types that
226b1ed91f3SChris Lattner     // provide a body for DstSTy then previous iterations of this loop may have
227b1ed91f3SChris Lattner     // already handled it.  Just ignore this case.
228b1ed91f3SChris Lattner     if (!DstSTy->isOpaque()) continue;
229b1ed91f3SChris Lattner     assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
230b1ed91f3SChris Lattner 
231b1ed91f3SChris Lattner     // Map the body of the source type over to a new body for the dest type.
232b1ed91f3SChris Lattner     Elements.resize(SrcSTy->getNumElements());
233b1ed91f3SChris Lattner     for (unsigned i = 0, e = Elements.size(); i != e; ++i)
234b1ed91f3SChris Lattner       Elements[i] = getImpl(SrcSTy->getElementType(i));
235b1ed91f3SChris Lattner 
236b1ed91f3SChris Lattner     DstSTy->setBody(Elements, SrcSTy->isPacked());
237b1ed91f3SChris Lattner 
238b1ed91f3SChris Lattner     // If DstSTy has no name or has a longer name than STy, then viciously steal
239b1ed91f3SChris Lattner     // STy's name.
240b1ed91f3SChris Lattner     if (!SrcSTy->hasName()) continue;
241b1ed91f3SChris Lattner     StringRef SrcName = SrcSTy->getName();
242b1ed91f3SChris Lattner 
243b1ed91f3SChris Lattner     if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
244b1ed91f3SChris Lattner       TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
245b1ed91f3SChris Lattner       SrcSTy->setName("");
246b1ed91f3SChris Lattner       DstSTy->setName(TmpName.str());
247b1ed91f3SChris Lattner       TmpName.clear();
248b1ed91f3SChris Lattner     }
249b1ed91f3SChris Lattner   }
2505e3bd972SChris Lattner 
2515e3bd972SChris Lattner   DstResolvedOpaqueTypes.clear();
252eee6f995SChris Lattner }
253eee6f995SChris Lattner 
254b1ed91f3SChris Lattner Type *TypeMapTy::get(Type *Ty) {
255b1ed91f3SChris Lattner   Type *Result = getImpl(Ty);
256b1ed91f3SChris Lattner 
257b1ed91f3SChris Lattner   // If this caused a reference to any struct type, resolve it before returning.
2585e3bd972SChris Lattner   if (!SrcDefinitionsToResolve.empty())
259b1ed91f3SChris Lattner     linkDefinedTypeBodies();
260b1ed91f3SChris Lattner   return Result;
261eee6f995SChris Lattner }
262eee6f995SChris Lattner 
26318c89411SRafael Espindola /// This is the recursive version of get().
264b1ed91f3SChris Lattner Type *TypeMapTy::getImpl(Type *Ty) {
265b1ed91f3SChris Lattner   // If we already have an entry for this type, return it.
266b1ed91f3SChris Lattner   Type **Entry = &MappedTypes[Ty];
267b1ed91f3SChris Lattner   if (*Entry) return *Entry;
268b1ed91f3SChris Lattner 
269b1ed91f3SChris Lattner   // If this is not a named struct type, then just map all of the elements and
270b1ed91f3SChris Lattner   // then rebuild the type from inside out.
27144f7ab45SChris Lattner   if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
272b1ed91f3SChris Lattner     // If there are no element types to map, then the type is itself.  This is
273b1ed91f3SChris Lattner     // true for the anonymous {} struct, things like 'float', integers, etc.
274b1ed91f3SChris Lattner     if (Ty->getNumContainedTypes() == 0)
275b1ed91f3SChris Lattner       return *Entry = Ty;
276b1ed91f3SChris Lattner 
277b1ed91f3SChris Lattner     // Remap all of the elements, keeping track of whether any of them change.
278b1ed91f3SChris Lattner     bool AnyChange = false;
279b1ed91f3SChris Lattner     SmallVector<Type*, 4> ElementTypes;
280b1ed91f3SChris Lattner     ElementTypes.resize(Ty->getNumContainedTypes());
281b1ed91f3SChris Lattner     for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
282b1ed91f3SChris Lattner       ElementTypes[i] = getImpl(Ty->getContainedType(i));
283b1ed91f3SChris Lattner       AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
284eee6f995SChris Lattner     }
285b1ed91f3SChris Lattner 
286b1ed91f3SChris Lattner     // If we found our type while recursively processing stuff, just use it.
287b1ed91f3SChris Lattner     Entry = &MappedTypes[Ty];
288b1ed91f3SChris Lattner     if (*Entry) return *Entry;
289b1ed91f3SChris Lattner 
290b1ed91f3SChris Lattner     // If all of the element types mapped directly over, then the type is usable
291b1ed91f3SChris Lattner     // as-is.
292b1ed91f3SChris Lattner     if (!AnyChange)
293b1ed91f3SChris Lattner       return *Entry = Ty;
294b1ed91f3SChris Lattner 
295b1ed91f3SChris Lattner     // Otherwise, rebuild a modified type.
296b1ed91f3SChris Lattner     switch (Ty->getTypeID()) {
297a2886c21SCraig Topper     default: llvm_unreachable("unknown derived type to remap");
298b1ed91f3SChris Lattner     case Type::ArrayTyID:
299b1ed91f3SChris Lattner       return *Entry = ArrayType::get(ElementTypes[0],
300b1ed91f3SChris Lattner                                      cast<ArrayType>(Ty)->getNumElements());
301b1ed91f3SChris Lattner     case Type::VectorTyID:
302b1ed91f3SChris Lattner       return *Entry = VectorType::get(ElementTypes[0],
303b1ed91f3SChris Lattner                                       cast<VectorType>(Ty)->getNumElements());
304b1ed91f3SChris Lattner     case Type::PointerTyID:
305b1ed91f3SChris Lattner       return *Entry = PointerType::get(ElementTypes[0],
306b1ed91f3SChris Lattner                                       cast<PointerType>(Ty)->getAddressSpace());
307b1ed91f3SChris Lattner     case Type::FunctionTyID:
308b1ed91f3SChris Lattner       return *Entry = FunctionType::get(ElementTypes[0],
309717d7eddSFrits van Bommel                                         makeArrayRef(ElementTypes).slice(1),
310b1ed91f3SChris Lattner                                         cast<FunctionType>(Ty)->isVarArg());
311b1ed91f3SChris Lattner     case Type::StructTyID:
312b1ed91f3SChris Lattner       // Note that this is only reached for anonymous structs.
313b1ed91f3SChris Lattner       return *Entry = StructType::get(Ty->getContext(), ElementTypes,
314b1ed91f3SChris Lattner                                       cast<StructType>(Ty)->isPacked());
315b1ed91f3SChris Lattner     }
316b1ed91f3SChris Lattner   }
317b1ed91f3SChris Lattner 
318b1ed91f3SChris Lattner   // Otherwise, this is an unmapped named struct.  If the struct can be directly
319b1ed91f3SChris Lattner   // mapped over, just use it as-is.  This happens in a case when the linked-in
320b1ed91f3SChris Lattner   // module has something like:
321b1ed91f3SChris Lattner   //   %T = type {%T*, i32}
322b1ed91f3SChris Lattner   //   @GV = global %T* null
323b1ed91f3SChris Lattner   // where T does not exist at all in the destination module.
324b1ed91f3SChris Lattner   //
325b1ed91f3SChris Lattner   // The other case we watch for is when the type is not in the destination
326b1ed91f3SChris Lattner   // module, but that it has to be rebuilt because it refers to something that
327b1ed91f3SChris Lattner   // is already mapped.  For example, if the destination module has:
328b1ed91f3SChris Lattner   //  %A = type { i32 }
329b1ed91f3SChris Lattner   // and the source module has something like
330b1ed91f3SChris Lattner   //  %A' = type { i32 }
331b1ed91f3SChris Lattner   //  %B = type { %A'* }
332b1ed91f3SChris Lattner   //  @GV = global %B* null
333b1ed91f3SChris Lattner   // then we want to create a new type: "%B = type { %A*}" and have it take the
334b1ed91f3SChris Lattner   // pristine "%B" name from the source module.
335b1ed91f3SChris Lattner   //
336b1ed91f3SChris Lattner   // To determine which case this is, we have to recursively walk the type graph
337b1ed91f3SChris Lattner   // speculating that we'll be able to reuse it unmodified.  Only if this is
338b1ed91f3SChris Lattner   // safe would we map the entire thing over.  Because this is an optimization,
339b1ed91f3SChris Lattner   // and is not required for the prettiness of the linked module, we just skip
340b1ed91f3SChris Lattner   // it and always rebuild a type here.
341b1ed91f3SChris Lattner   StructType *STy = cast<StructType>(Ty);
342b1ed91f3SChris Lattner 
343b1ed91f3SChris Lattner   // If the type is opaque, we can just use it directly.
344aa9918aaSRafael Espindola   if (STy->isOpaque()) {
345aa9918aaSRafael Espindola     // A named structure type from src module is used. Add it to the Set of
346aa9918aaSRafael Espindola     // identified structs in the destination module.
347aa9918aaSRafael Espindola     DstStructTypesSet.insert(STy);
348b1ed91f3SChris Lattner     return *Entry = STy;
349aa9918aaSRafael Espindola   }
350b1ed91f3SChris Lattner 
351b1ed91f3SChris Lattner   // Otherwise we create a new type and resolve its body later.  This will be
352b1ed91f3SChris Lattner   // resolved by the top level of get().
3535e3bd972SChris Lattner   SrcDefinitionsToResolve.push_back(STy);
3545e3bd972SChris Lattner   StructType *DTy = StructType::create(STy->getContext());
355aa9918aaSRafael Espindola   // A new identified structure type was created. Add it to the set of
356aa9918aaSRafael Espindola   // identified structs in the destination module.
357aa9918aaSRafael Espindola   DstStructTypesSet.insert(DTy);
3585e3bd972SChris Lattner   DstResolvedOpaqueTypes.insert(DTy);
3595e3bd972SChris Lattner   return *Entry = DTy;
360b1ed91f3SChris Lattner }
361b1ed91f3SChris Lattner 
362b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
363b1ed91f3SChris Lattner // ModuleLinker implementation.
364b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
365b1ed91f3SChris Lattner 
366b1ed91f3SChris Lattner namespace {
367f6f121e2SJames Molloy class ModuleLinker;
368f6f121e2SJames Molloy 
36918c89411SRafael Espindola /// Creates prototypes for functions that are lazily linked on the fly. This
37018c89411SRafael Espindola /// speeds up linking for modules with many/ lazily linked functions of which
37118c89411SRafael Espindola /// few get used.
372f6f121e2SJames Molloy class ValueMaterializerTy : public ValueMaterializer {
373f6f121e2SJames Molloy   TypeMapTy &TypeMap;
374f6f121e2SJames Molloy   Module *DstM;
375f6f121e2SJames Molloy   std::vector<Function *> &LazilyLinkFunctions;
376*c84f608bSRafael Espindola 
377f6f121e2SJames Molloy public:
378f6f121e2SJames Molloy   ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
379*c84f608bSRafael Espindola                       std::vector<Function *> &LazilyLinkFunctions)
380*c84f608bSRafael Espindola       : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
381*c84f608bSRafael Espindola         LazilyLinkFunctions(LazilyLinkFunctions) {}
382f6f121e2SJames Molloy 
3838548299aSCraig Topper   Value *materializeValueFor(Value *V) override;
384f6f121e2SJames Molloy };
385f6f121e2SJames Molloy 
386d12b4a33SRafael Espindola class LinkDiagnosticInfo : public DiagnosticInfo {
387d12b4a33SRafael Espindola   const Twine &Msg;
388d12b4a33SRafael Espindola 
389d12b4a33SRafael Espindola public:
390d12b4a33SRafael Espindola   LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
391d12b4a33SRafael Espindola   void print(DiagnosticPrinter &DP) const override;
392d12b4a33SRafael Espindola };
393d12b4a33SRafael Espindola LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
394d12b4a33SRafael Espindola                                        const Twine &Msg)
395d12b4a33SRafael Espindola     : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
396d12b4a33SRafael Espindola void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
397d12b4a33SRafael Espindola 
39818c89411SRafael Espindola /// This is an implementation class for the LinkModules function, which is the
39918c89411SRafael Espindola /// entrypoint for this file.
400b1ed91f3SChris Lattner class ModuleLinker {
401b1ed91f3SChris Lattner   Module *DstM, *SrcM;
402b1ed91f3SChris Lattner 
403b1ed91f3SChris Lattner   TypeMapTy TypeMap;
404f6f121e2SJames Molloy   ValueMaterializerTy ValMaterializer;
405b1ed91f3SChris Lattner 
40618c89411SRafael Espindola   /// Mapping of values from what they used to be in Src, to what they are now
40718c89411SRafael Espindola   /// in DstM.  ValueToValueMapTy is a ValueMap, which involves some overhead
40818c89411SRafael Espindola   /// due to the use of Value handles which the Linker doesn't actually need,
40918c89411SRafael Espindola   /// but this allows us to reuse the ValueMapper code.
410b1ed91f3SChris Lattner   ValueToValueMapTy ValueMap;
411b1ed91f3SChris Lattner 
412b1ed91f3SChris Lattner   struct AppendingVarInfo {
413b1ed91f3SChris Lattner     GlobalVariable *NewGV;   // New aggregate global in dest module.
4143e8bc6a8SRafael Espindola     const Constant *DstInit; // Old initializer from dest module.
4153e8bc6a8SRafael Espindola     const Constant *SrcInit; // Old initializer from src module.
416b1ed91f3SChris Lattner   };
417b1ed91f3SChris Lattner 
418b1ed91f3SChris Lattner   std::vector<AppendingVarInfo> AppendingVars;
419b1ed91f3SChris Lattner 
420cbb91408STanya Lattner   // Set of items not to link in from source.
421cbb91408STanya Lattner   SmallPtrSet<const Value *, 16> DoNotLinkFromSource;
422cbb91408STanya Lattner 
4230a48b877STanya Lattner   // Vector of functions to lazily link in.
424fa228782SBill Wendling   std::vector<Function *> LazilyLinkFunctions;
4250a48b877STanya Lattner 
4264160f5d3SRafael Espindola   Linker::DiagnosticHandlerFunction DiagnosticHandler;
4274160f5d3SRafael Espindola 
428b1ed91f3SChris Lattner public:
4299f8eff31SRafael Espindola   ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM,
4304160f5d3SRafael Espindola                Linker::DiagnosticHandlerFunction DiagnosticHandler)
431f6f121e2SJames Molloy       : DstM(dstM), SrcM(srcM), TypeMap(Set),
4329f8eff31SRafael Espindola         ValMaterializer(TypeMap, DstM, LazilyLinkFunctions),
4334160f5d3SRafael Espindola         DiagnosticHandler(DiagnosticHandler) {}
434b1ed91f3SChris Lattner 
435b1ed91f3SChris Lattner   bool run();
436b1ed91f3SChris Lattner 
437b1ed91f3SChris Lattner private:
438d12b4a33SRafael Espindola   bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
439d12b4a33SRafael Espindola                             const GlobalValue &Src);
440dbb0bd1aSRafael Espindola 
441d12b4a33SRafael Espindola   /// Helper method for setting a message and returning an error code.
442b1ed91f3SChris Lattner   bool emitError(const Twine &Message) {
4434160f5d3SRafael Espindola     DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
444b1ed91f3SChris Lattner     return true;
445b1ed91f3SChris Lattner   }
446b1ed91f3SChris Lattner 
447d12b4a33SRafael Espindola   void emitWarning(const Twine &Message) {
4484160f5d3SRafael Espindola     DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
449d12b4a33SRafael Espindola   }
450d12b4a33SRafael Espindola 
451dad0a645SDavid Majnemer   bool getComdatLeader(Module *M, StringRef ComdatName,
452dad0a645SDavid Majnemer                        const GlobalVariable *&GVar);
453dad0a645SDavid Majnemer   bool computeResultingSelectionKind(StringRef ComdatName,
454dad0a645SDavid Majnemer                                      Comdat::SelectionKind Src,
455dad0a645SDavid Majnemer                                      Comdat::SelectionKind Dst,
456dad0a645SDavid Majnemer                                      Comdat::SelectionKind &Result,
457dad0a645SDavid Majnemer                                      bool &LinkFromSrc);
458dad0a645SDavid Majnemer   std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
459dad0a645SDavid Majnemer       ComdatsChosen;
460dad0a645SDavid Majnemer   bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
461dad0a645SDavid Majnemer                        bool &LinkFromSrc);
462dad0a645SDavid Majnemer 
46318c89411SRafael Espindola   /// Given a global in the source module, return the global in the
46418c89411SRafael Espindola   /// destination module that is being linked to, if any.
4653e8bc6a8SRafael Espindola   GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
466b1ed91f3SChris Lattner     // If the source has no name it can't link.  If it has local linkage,
467b1ed91f3SChris Lattner     // there is no name match-up going on.
468b1ed91f3SChris Lattner     if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
4692617dcceSCraig Topper       return nullptr;
470b1ed91f3SChris Lattner 
471b1ed91f3SChris Lattner     // Otherwise see if we have a match in the destination module's symtab.
472b1ed91f3SChris Lattner     GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
473*c84f608bSRafael Espindola     if (!DGV)
474*c84f608bSRafael Espindola       return nullptr;
475b1ed91f3SChris Lattner 
476b1ed91f3SChris Lattner     // If we found a global with the same name in the dest module, but it has
477b1ed91f3SChris Lattner     // internal linkage, we are really not doing any linkage here.
478b1ed91f3SChris Lattner     if (DGV->hasLocalLinkage())
4792617dcceSCraig Topper       return nullptr;
480b1ed91f3SChris Lattner 
481b1ed91f3SChris Lattner     // Otherwise, we do in fact link to the destination global.
482b1ed91f3SChris Lattner     return DGV;
483b1ed91f3SChris Lattner   }
484b1ed91f3SChris Lattner 
485b1ed91f3SChris Lattner   void computeTypeMapping();
486b1ed91f3SChris Lattner 
48709d84addSDuncan P. N. Exon Smith   void upgradeMismatchedGlobalArray(StringRef Name);
48809d84addSDuncan P. N. Exon Smith   void upgradeMismatchedGlobals();
48909d84addSDuncan P. N. Exon Smith 
4903e8bc6a8SRafael Espindola   bool linkAppendingVarProto(GlobalVariable *DstGV,
4913e8bc6a8SRafael Espindola                              const GlobalVariable *SrcGV);
492778fcc77SRafael Espindola 
493778fcc77SRafael Espindola   bool linkGlobalValueProto(GlobalValue *GV);
494778fcc77SRafael Espindola   GlobalValue *linkGlobalVariableProto(const GlobalVariable *SGVar,
495778fcc77SRafael Espindola                                        GlobalValue *DGV, bool LinkFromSrc);
496778fcc77SRafael Espindola   GlobalValue *linkFunctionProto(const Function *SF, GlobalValue *DGV,
497778fcc77SRafael Espindola                                  bool LinkFromSrc);
498778fcc77SRafael Espindola   GlobalValue *linkGlobalAliasProto(const GlobalAlias *SGA, GlobalValue *DGV,
499778fcc77SRafael Espindola                                     bool LinkFromSrc);
500778fcc77SRafael Espindola 
50166f02413SBill Wendling   bool linkModuleFlagsMetadata();
502b1ed91f3SChris Lattner 
503b1ed91f3SChris Lattner   void linkAppendingVarInit(const AppendingVarInfo &AVI);
504b1ed91f3SChris Lattner   void linkGlobalInits();
505b1ed91f3SChris Lattner   void linkFunctionBody(Function *Dst, Function *Src);
506b1ed91f3SChris Lattner   void linkAliasBodies();
507b1ed91f3SChris Lattner   void linkNamedMDNodes();
508eee6f995SChris Lattner };
509d48b7783SBill Wendling }
510d48b7783SBill Wendling 
51118c89411SRafael Espindola /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
51218c89411SRafael Espindola /// table. This is good for all clients except for us. Go through the trouble
51318c89411SRafael Espindola /// to force this back.
514b1ed91f3SChris Lattner static void forceRenaming(GlobalValue *GV, StringRef Name) {
515b1ed91f3SChris Lattner   // If the global doesn't force its name or if it already has the right name,
516b1ed91f3SChris Lattner   // there is nothing for us to do.
517b1ed91f3SChris Lattner   if (GV->hasLocalLinkage() || GV->getName() == Name)
518b1ed91f3SChris Lattner     return;
519b1ed91f3SChris Lattner 
520b1ed91f3SChris Lattner   Module *M = GV->getParent();
521361e513dSReid Spencer 
522361e513dSReid Spencer   // If there is a conflict, rename the conflict.
523b1ed91f3SChris Lattner   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
5242a8d2e0eSChris Lattner     GV->takeName(ConflictGV);
525361e513dSReid Spencer     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
526b1ed91f3SChris Lattner     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
5272a8d2e0eSChris Lattner   } else {
5282a8d2e0eSChris Lattner     GV->setName(Name);              // Force the name back
5293aaaa0b2SReid Spencer   }
5303aaaa0b2SReid Spencer }
5313aaaa0b2SReid Spencer 
53218c89411SRafael Espindola /// copy additional attributes (those not needed to construct a GlobalValue)
53318c89411SRafael Espindola /// from the SrcGV to the DestGV.
534b6af2f36SBill Wendling static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
535dd7daee8SDuncan Sands   // Use the maximum alignment, rather than just copying the alignment of SrcGV.
53699e05cf1SRafael Espindola   auto *DestGO = dyn_cast<GlobalObject>(DestGV);
537a7d9c69cSRafael Espindola   unsigned Alignment;
53899e05cf1SRafael Espindola   if (DestGO)
53999e05cf1SRafael Espindola     Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
540a7d9c69cSRafael Espindola 
541dd7daee8SDuncan Sands   DestGV->copyAttributesFrom(SrcGV);
542a7d9c69cSRafael Espindola 
54399e05cf1SRafael Espindola   if (DestGO)
54499e05cf1SRafael Espindola     DestGO->setAlignment(Alignment);
545b1ed91f3SChris Lattner 
546b1ed91f3SChris Lattner   forceRenaming(DestGV, SrcGV->getName());
547361e513dSReid Spencer }
548361e513dSReid Spencer 
54923f8d64bSRafael Espindola static bool isLessConstraining(GlobalValue::VisibilityTypes a,
55023f8d64bSRafael Espindola                                GlobalValue::VisibilityTypes b) {
55123f8d64bSRafael Espindola   if (a == GlobalValue::HiddenVisibility)
55223f8d64bSRafael Espindola     return false;
55323f8d64bSRafael Espindola   if (b == GlobalValue::HiddenVisibility)
55423f8d64bSRafael Espindola     return true;
55523f8d64bSRafael Espindola   if (a == GlobalValue::ProtectedVisibility)
55623f8d64bSRafael Espindola     return false;
55723f8d64bSRafael Espindola   if (b == GlobalValue::ProtectedVisibility)
55823f8d64bSRafael Espindola     return true;
55923f8d64bSRafael Espindola   return false;
56023f8d64bSRafael Espindola }
56123f8d64bSRafael Espindola 
562f6f121e2SJames Molloy Value *ValueMaterializerTy::materializeValueFor(Value *V) {
563f6f121e2SJames Molloy   Function *SF = dyn_cast<Function>(V);
564f6f121e2SJames Molloy   if (!SF)
5652617dcceSCraig Topper     return nullptr;
566f6f121e2SJames Molloy 
567f6f121e2SJames Molloy   Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
568f6f121e2SJames Molloy                                   SF->getLinkage(), SF->getName(), DstM);
569f6f121e2SJames Molloy   copyGVAttributes(DF, SF);
570f6f121e2SJames Molloy 
5713931c28bSRafael Espindola   if (Comdat *SC = SF->getComdat()) {
5723931c28bSRafael Espindola     Comdat *DC = DstM->getOrInsertComdat(SC->getName());
5733931c28bSRafael Espindola     DF->setComdat(DC);
5743931c28bSRafael Espindola   }
5753931c28bSRafael Espindola 
576f6f121e2SJames Molloy   LazilyLinkFunctions.push_back(SF);
577f6f121e2SJames Molloy   return DF;
578f6f121e2SJames Molloy }
579f6f121e2SJames Molloy 
580dad0a645SDavid Majnemer bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
581dad0a645SDavid Majnemer                                    const GlobalVariable *&GVar) {
582dad0a645SDavid Majnemer   const GlobalValue *GVal = M->getNamedValue(ComdatName);
583dad0a645SDavid Majnemer   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
584dad0a645SDavid Majnemer     GVal = GA->getBaseObject();
585dad0a645SDavid Majnemer     if (!GVal)
586dad0a645SDavid Majnemer       // We cannot resolve the size of the aliasee yet.
587dad0a645SDavid Majnemer       return emitError("Linking COMDATs named '" + ComdatName +
588dad0a645SDavid Majnemer                        "': COMDAT key involves incomputable alias size.");
589dad0a645SDavid Majnemer   }
590dad0a645SDavid Majnemer 
591dad0a645SDavid Majnemer   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
592dad0a645SDavid Majnemer   if (!GVar)
593dad0a645SDavid Majnemer     return emitError(
594dad0a645SDavid Majnemer         "Linking COMDATs named '" + ComdatName +
595dad0a645SDavid Majnemer         "': GlobalVariable required for data dependent selection!");
596dad0a645SDavid Majnemer 
597dad0a645SDavid Majnemer   return false;
598dad0a645SDavid Majnemer }
599dad0a645SDavid Majnemer 
600dad0a645SDavid Majnemer bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
601dad0a645SDavid Majnemer                                                  Comdat::SelectionKind Src,
602dad0a645SDavid Majnemer                                                  Comdat::SelectionKind Dst,
603dad0a645SDavid Majnemer                                                  Comdat::SelectionKind &Result,
604dad0a645SDavid Majnemer                                                  bool &LinkFromSrc) {
605dad0a645SDavid Majnemer   // The ability to mix Comdat::SelectionKind::Any with
606dad0a645SDavid Majnemer   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
607dad0a645SDavid Majnemer   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
608dad0a645SDavid Majnemer                          Dst == Comdat::SelectionKind::Largest;
609dad0a645SDavid Majnemer   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
610dad0a645SDavid Majnemer                          Src == Comdat::SelectionKind::Largest;
611dad0a645SDavid Majnemer   if (DstAnyOrLargest && SrcAnyOrLargest) {
612dad0a645SDavid Majnemer     if (Dst == Comdat::SelectionKind::Largest ||
613dad0a645SDavid Majnemer         Src == Comdat::SelectionKind::Largest)
614dad0a645SDavid Majnemer       Result = Comdat::SelectionKind::Largest;
615dad0a645SDavid Majnemer     else
616dad0a645SDavid Majnemer       Result = Comdat::SelectionKind::Any;
617dad0a645SDavid Majnemer   } else if (Src == Dst) {
618dad0a645SDavid Majnemer     Result = Dst;
619dad0a645SDavid Majnemer   } else {
620dad0a645SDavid Majnemer     return emitError("Linking COMDATs named '" + ComdatName +
621dad0a645SDavid Majnemer                      "': invalid selection kinds!");
622dad0a645SDavid Majnemer   }
623dad0a645SDavid Majnemer 
624dad0a645SDavid Majnemer   switch (Result) {
625dad0a645SDavid Majnemer   case Comdat::SelectionKind::Any:
626dad0a645SDavid Majnemer     // Go with Dst.
627dad0a645SDavid Majnemer     LinkFromSrc = false;
628dad0a645SDavid Majnemer     break;
629dad0a645SDavid Majnemer   case Comdat::SelectionKind::NoDuplicates:
630dad0a645SDavid Majnemer     return emitError("Linking COMDATs named '" + ComdatName +
631dad0a645SDavid Majnemer                      "': noduplicates has been violated!");
632dad0a645SDavid Majnemer   case Comdat::SelectionKind::ExactMatch:
633dad0a645SDavid Majnemer   case Comdat::SelectionKind::Largest:
634dad0a645SDavid Majnemer   case Comdat::SelectionKind::SameSize: {
635dad0a645SDavid Majnemer     const GlobalVariable *DstGV;
636dad0a645SDavid Majnemer     const GlobalVariable *SrcGV;
637dad0a645SDavid Majnemer     if (getComdatLeader(DstM, ComdatName, DstGV) ||
638dad0a645SDavid Majnemer         getComdatLeader(SrcM, ComdatName, SrcGV))
639dad0a645SDavid Majnemer       return true;
640dad0a645SDavid Majnemer 
641dad0a645SDavid Majnemer     const DataLayout *DstDL = DstM->getDataLayout();
642dad0a645SDavid Majnemer     const DataLayout *SrcDL = SrcM->getDataLayout();
643dad0a645SDavid Majnemer     if (!DstDL || !SrcDL) {
644dad0a645SDavid Majnemer       return emitError(
645dad0a645SDavid Majnemer           "Linking COMDATs named '" + ComdatName +
646dad0a645SDavid Majnemer           "': can't do size dependent selection without DataLayout!");
647dad0a645SDavid Majnemer     }
648dad0a645SDavid Majnemer     uint64_t DstSize =
649dad0a645SDavid Majnemer         DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
650dad0a645SDavid Majnemer     uint64_t SrcSize =
651dad0a645SDavid Majnemer         SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
652dad0a645SDavid Majnemer     if (Result == Comdat::SelectionKind::ExactMatch) {
653dad0a645SDavid Majnemer       if (SrcGV->getInitializer() != DstGV->getInitializer())
654dad0a645SDavid Majnemer         return emitError("Linking COMDATs named '" + ComdatName +
655dad0a645SDavid Majnemer                          "': ExactMatch violated!");
656dad0a645SDavid Majnemer       LinkFromSrc = false;
657dad0a645SDavid Majnemer     } else if (Result == Comdat::SelectionKind::Largest) {
658dad0a645SDavid Majnemer       LinkFromSrc = SrcSize > DstSize;
659dad0a645SDavid Majnemer     } else if (Result == Comdat::SelectionKind::SameSize) {
660dad0a645SDavid Majnemer       if (SrcSize != DstSize)
661dad0a645SDavid Majnemer         return emitError("Linking COMDATs named '" + ComdatName +
662dad0a645SDavid Majnemer                          "': SameSize violated!");
663dad0a645SDavid Majnemer       LinkFromSrc = false;
664dad0a645SDavid Majnemer     } else {
665dad0a645SDavid Majnemer       llvm_unreachable("unknown selection kind");
666dad0a645SDavid Majnemer     }
667dad0a645SDavid Majnemer     break;
668dad0a645SDavid Majnemer   }
669dad0a645SDavid Majnemer   }
670dad0a645SDavid Majnemer 
671dad0a645SDavid Majnemer   return false;
672dad0a645SDavid Majnemer }
673dad0a645SDavid Majnemer 
674dad0a645SDavid Majnemer bool ModuleLinker::getComdatResult(const Comdat *SrcC,
675dad0a645SDavid Majnemer                                    Comdat::SelectionKind &Result,
676dad0a645SDavid Majnemer                                    bool &LinkFromSrc) {
677b16196a3SRafael Espindola   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
678dad0a645SDavid Majnemer   StringRef ComdatName = SrcC->getName();
679dad0a645SDavid Majnemer   Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
680dad0a645SDavid Majnemer   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
6812ef3f299SRafael Espindola 
682b16196a3SRafael Espindola   if (DstCI == ComdatSymTab.end()) {
683b16196a3SRafael Espindola     // Use the comdat if it is only available in one of the modules.
684b16196a3SRafael Espindola     LinkFromSrc = true;
685b16196a3SRafael Espindola     Result = SSK;
6862ef3f299SRafael Espindola     return false;
687b16196a3SRafael Espindola   }
6882ef3f299SRafael Espindola 
689dad0a645SDavid Majnemer   const Comdat *DstC = &DstCI->second;
690dad0a645SDavid Majnemer   Comdat::SelectionKind DSK = DstC->getSelectionKind();
6912ef3f299SRafael Espindola   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
6922ef3f299SRafael Espindola                                        LinkFromSrc);
693dad0a645SDavid Majnemer }
694f6f121e2SJames Molloy 
695d12b4a33SRafael Espindola bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
696d12b4a33SRafael Espindola                                         const GlobalValue &Dest,
697dbb0bd1aSRafael Espindola                                         const GlobalValue &Src) {
698778fcc77SRafael Espindola   // We always have to add Src if it has appending linkage.
699778fcc77SRafael Espindola   if (Src.hasAppendingLinkage()) {
700778fcc77SRafael Espindola     LinkFromSrc = true;
701778fcc77SRafael Espindola     return false;
702778fcc77SRafael Espindola   }
703778fcc77SRafael Espindola 
704d4bcefc7SRafael Espindola   bool SrcIsDeclaration = Src.isDeclarationForLinker();
705d4bcefc7SRafael Espindola   bool DestIsDeclaration = Dest.isDeclarationForLinker();
706dbb0bd1aSRafael Espindola 
707dbb0bd1aSRafael Espindola   if (SrcIsDeclaration) {
708dbb0bd1aSRafael Espindola     // If Src is external or if both Src & Dest are external..  Just link the
709dbb0bd1aSRafael Espindola     // external globals, we aren't adding anything.
710d12b4a33SRafael Espindola     if (Src.hasDLLImportStorageClass()) {
711dbb0bd1aSRafael Espindola       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
712d12b4a33SRafael Espindola       LinkFromSrc = DestIsDeclaration;
713d12b4a33SRafael Espindola       return false;
714d12b4a33SRafael Espindola     }
715dbb0bd1aSRafael Espindola     // If the Dest is weak, use the source linkage.
716d12b4a33SRafael Espindola     LinkFromSrc = Dest.hasExternalWeakLinkage();
717d12b4a33SRafael Espindola     return false;
718dbb0bd1aSRafael Espindola   }
719dbb0bd1aSRafael Espindola 
720d12b4a33SRafael Espindola   if (DestIsDeclaration) {
721dbb0bd1aSRafael Espindola     // If Dest is external but Src is not:
722d12b4a33SRafael Espindola     LinkFromSrc = true;
723d12b4a33SRafael Espindola     return false;
724d12b4a33SRafael Espindola   }
725dbb0bd1aSRafael Espindola 
7260910605aSRafael Espindola   if (Src.hasCommonLinkage()) {
727d12b4a33SRafael Espindola     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
728d12b4a33SRafael Espindola       LinkFromSrc = true;
7290910605aSRafael Espindola       return false;
730d12b4a33SRafael Espindola     }
731d12b4a33SRafael Espindola 
732d12b4a33SRafael Espindola     if (!Dest.hasCommonLinkage()) {
733d12b4a33SRafael Espindola       LinkFromSrc = false;
734d12b4a33SRafael Espindola       return false;
735d12b4a33SRafael Espindola     }
7360910605aSRafael Espindola 
7370ae225b6SRafael Espindola     // FIXME: Make datalayout mandatory and just use getDataLayout().
7380ae225b6SRafael Espindola     DataLayout DL(Dest.getParent());
7390ae225b6SRafael Espindola 
7400910605aSRafael Espindola     uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
7410910605aSRafael Espindola     uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
742d12b4a33SRafael Espindola     LinkFromSrc = SrcSize > DestSize;
743d12b4a33SRafael Espindola     return false;
7440910605aSRafael Espindola   }
7450910605aSRafael Espindola 
746dbb0bd1aSRafael Espindola   if (Src.isWeakForLinker()) {
747dbb0bd1aSRafael Espindola     assert(!Dest.hasExternalWeakLinkage());
748dbb0bd1aSRafael Espindola     assert(!Dest.hasAvailableExternallyLinkage());
7490910605aSRafael Espindola 
750d12b4a33SRafael Espindola     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
751d12b4a33SRafael Espindola       LinkFromSrc = true;
752d12b4a33SRafael Espindola       return false;
753d12b4a33SRafael Espindola     }
754dbb0bd1aSRafael Espindola 
755d12b4a33SRafael Espindola     LinkFromSrc = false;
7560910605aSRafael Espindola     return false;
757dbb0bd1aSRafael Espindola   }
758dbb0bd1aSRafael Espindola 
759dbb0bd1aSRafael Espindola   if (Dest.isWeakForLinker()) {
760dbb0bd1aSRafael Espindola     assert(Src.hasExternalLinkage());
761d12b4a33SRafael Espindola     LinkFromSrc = true;
762d12b4a33SRafael Espindola     return false;
763dbb0bd1aSRafael Espindola   }
764dbb0bd1aSRafael Espindola 
765dbb0bd1aSRafael Espindola   assert(!Src.hasExternalWeakLinkage());
766dbb0bd1aSRafael Espindola   assert(!Dest.hasExternalWeakLinkage());
767dbb0bd1aSRafael Espindola   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
768dbb0bd1aSRafael Espindola          "Unexpected linkage type!");
769dbb0bd1aSRafael Espindola   return emitError("Linking globals named '" + Src.getName() +
770dbb0bd1aSRafael Espindola                    "': symbol multiply defined!");
771dbb0bd1aSRafael Espindola }
772dbb0bd1aSRafael Espindola 
77318c89411SRafael Espindola /// Loop over all of the linked values to compute type mappings.  For example,
77418c89411SRafael Espindola /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
77518c89411SRafael Espindola /// types 'Foo' but one got renamed when the module was loaded into the same
77618c89411SRafael Espindola /// LLVMContext.
777b1ed91f3SChris Lattner void ModuleLinker::computeTypeMapping() {
778c8a476eeSRafael Espindola   for (GlobalValue &SGV : SrcM->globals()) {
779c8a476eeSRafael Espindola     GlobalValue *DGV = getLinkedToGlobal(&SGV);
780c8a476eeSRafael Espindola     if (!DGV)
781c8a476eeSRafael Espindola       continue;
782b1ed91f3SChris Lattner 
783c8a476eeSRafael Espindola     if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
784c8a476eeSRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
785b1ed91f3SChris Lattner       continue;
7865c310be0SDevang Patel     }
7875c310be0SDevang Patel 
788b1ed91f3SChris Lattner     // Unify the element type of appending arrays.
789b1ed91f3SChris Lattner     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
790c8a476eeSRafael Espindola     ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
791b1ed91f3SChris Lattner     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
792b1ed91f3SChris Lattner   }
79334fc5a0eSChris Lattner 
794c8a476eeSRafael Espindola   for (GlobalValue &SGV : *SrcM) {
795c8a476eeSRafael Espindola     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
796c8a476eeSRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
797b1ed91f3SChris Lattner   }
798e79f4c77SAnton Korobeynikov 
799e96d7eb8SRafael Espindola   for (GlobalValue &SGV : SrcM->aliases()) {
800e96d7eb8SRafael Espindola     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
801e96d7eb8SRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
802e96d7eb8SRafael Espindola   }
803e96d7eb8SRafael Espindola 
804d48b7783SBill Wendling   // Incorporate types by name, scanning all the types in the source module.
805d48b7783SBill Wendling   // At this point, the destination module may have a type "%foo = { i32 }" for
8062b3f61afSBill Wendling   // example.  When the source module got loaded into the same LLVMContext, if
8072b3f61afSBill Wendling   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
8088555a37cSBill Wendling   TypeFinder SrcStructTypes;
8098555a37cSBill Wendling   SrcStructTypes.run(*SrcM, true);
8102b3f61afSBill Wendling   SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
8112b3f61afSBill Wendling                                                  SrcStructTypes.end());
8122b3f61afSBill Wendling 
8132b3f61afSBill Wendling   for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
8142b3f61afSBill Wendling     StructType *ST = SrcStructTypes[i];
8152b3f61afSBill Wendling     if (!ST->hasName()) continue;
8162b3f61afSBill Wendling 
8172b3f61afSBill Wendling     // Check to see if there is a dot in the name followed by a digit.
818d48b7783SBill Wendling     size_t DotPos = ST->getName().rfind('.');
819d48b7783SBill Wendling     if (DotPos == 0 || DotPos == StringRef::npos ||
82083c74e9fSGuy Benyei         ST->getName().back() == '.' ||
82183c74e9fSGuy Benyei         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
822d48b7783SBill Wendling       continue;
8232b3f61afSBill Wendling 
8242b3f61afSBill Wendling     // Check to see if the destination module has a struct with the prefix name.
825d48b7783SBill Wendling     if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
8262b3f61afSBill Wendling       // Don't use it if this actually came from the source module. They're in
8278737480dSBill Wendling       // the same LLVMContext after all. Also don't use it unless the type is
8288737480dSBill Wendling       // actually used in the destination module. This can happen in situations
8298737480dSBill Wendling       // like this:
8308737480dSBill Wendling       //
8318737480dSBill Wendling       //      Module A                         Module B
8328737480dSBill Wendling       //      --------                         --------
8338737480dSBill Wendling       //   %Z = type { %A }                %B = type { %C.1 }
8348737480dSBill Wendling       //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
8358737480dSBill Wendling       //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
8368737480dSBill Wendling       //   %C = type { i8* }               %B.3 = type { %C.1 }
8378737480dSBill Wendling       //
8388737480dSBill Wendling       // When we link Module B with Module A, the '%B' in Module B is
8398737480dSBill Wendling       // used. However, that would then use '%C.1'. But when we process '%C.1',
8408737480dSBill Wendling       // we prefer to take the '%C' version. So we are then left with both
8418737480dSBill Wendling       // '%C.1' and '%C' being used for the same types. This leads to some
8428737480dSBill Wendling       // variables using one type and some using the other.
843aa9918aaSRafael Espindola       if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
8442b3f61afSBill Wendling         TypeMap.addTypeMapping(DST, ST);
8452b3f61afSBill Wendling   }
8462b3f61afSBill Wendling 
847b1ed91f3SChris Lattner   // Now that we have discovered all of the type equivalences, get a body for
848b1ed91f3SChris Lattner   // any 'opaque' types in the dest module that are now resolved.
849b1ed91f3SChris Lattner   TypeMap.linkDefinedTypeBodies();
850b1ed91f3SChris Lattner }
851c08e7a00SChris Lattner 
85209d84addSDuncan P. N. Exon Smith static void upgradeGlobalArray(GlobalVariable *GV) {
85309d84addSDuncan P. N. Exon Smith   ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
85409d84addSDuncan P. N. Exon Smith   StructType *OldTy = cast<StructType>(ATy->getElementType());
85509d84addSDuncan P. N. Exon Smith   assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
85609d84addSDuncan P. N. Exon Smith 
85709d84addSDuncan P. N. Exon Smith   // Get the upgraded 3 element type.
85809d84addSDuncan P. N. Exon Smith   PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
85909d84addSDuncan P. N. Exon Smith   Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
86009d84addSDuncan P. N. Exon Smith                   VoidPtrTy};
86109d84addSDuncan P. N. Exon Smith   StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
86209d84addSDuncan P. N. Exon Smith 
86309d84addSDuncan P. N. Exon Smith   // Build new constants with a null third field filled in.
86409d84addSDuncan P. N. Exon Smith   Constant *OldInitC = GV->getInitializer();
86509d84addSDuncan P. N. Exon Smith   ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
86609d84addSDuncan P. N. Exon Smith   if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
86709d84addSDuncan P. N. Exon Smith     // Invalid initializer; give up.
86809d84addSDuncan P. N. Exon Smith     return;
86909d84addSDuncan P. N. Exon Smith   std::vector<Constant *> Initializers;
87009d84addSDuncan P. N. Exon Smith   if (OldInit && OldInit->getNumOperands()) {
87109d84addSDuncan P. N. Exon Smith     Value *Null = Constant::getNullValue(VoidPtrTy);
87209d84addSDuncan P. N. Exon Smith     for (Use &U : OldInit->operands()) {
87309d84addSDuncan P. N. Exon Smith       ConstantStruct *Init = cast<ConstantStruct>(U.get());
87409d84addSDuncan P. N. Exon Smith       Initializers.push_back(ConstantStruct::get(
87509d84addSDuncan P. N. Exon Smith           NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
87609d84addSDuncan P. N. Exon Smith     }
87709d84addSDuncan P. N. Exon Smith   }
87809d84addSDuncan P. N. Exon Smith   assert(Initializers.size() == ATy->getNumElements() &&
87909d84addSDuncan P. N. Exon Smith          "Failed to copy all array elements");
88009d84addSDuncan P. N. Exon Smith 
88109d84addSDuncan P. N. Exon Smith   // Replace the old GV with a new one.
88209d84addSDuncan P. N. Exon Smith   ATy = ArrayType::get(NewTy, Initializers.size());
88309d84addSDuncan P. N. Exon Smith   Constant *NewInit = ConstantArray::get(ATy, Initializers);
88409d84addSDuncan P. N. Exon Smith   GlobalVariable *NewGV = new GlobalVariable(
88509d84addSDuncan P. N. Exon Smith       *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
88609d84addSDuncan P. N. Exon Smith       GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
88709d84addSDuncan P. N. Exon Smith       GV->isExternallyInitialized());
88809d84addSDuncan P. N. Exon Smith   NewGV->copyAttributesFrom(GV);
88909d84addSDuncan P. N. Exon Smith   NewGV->takeName(GV);
89009d84addSDuncan P. N. Exon Smith   assert(GV->use_empty() && "program cannot use initializer list");
89109d84addSDuncan P. N. Exon Smith   GV->eraseFromParent();
89209d84addSDuncan P. N. Exon Smith }
89309d84addSDuncan P. N. Exon Smith 
89409d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
89509d84addSDuncan P. N. Exon Smith   // Look for the global arrays.
89609d84addSDuncan P. N. Exon Smith   auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
89709d84addSDuncan P. N. Exon Smith   if (!DstGV)
89809d84addSDuncan P. N. Exon Smith     return;
89909d84addSDuncan P. N. Exon Smith   auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
90009d84addSDuncan P. N. Exon Smith   if (!SrcGV)
90109d84addSDuncan P. N. Exon Smith     return;
90209d84addSDuncan P. N. Exon Smith 
90309d84addSDuncan P. N. Exon Smith   // Check if the types already match.
90409d84addSDuncan P. N. Exon Smith   auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
90509d84addSDuncan P. N. Exon Smith   auto *SrcTy =
90609d84addSDuncan P. N. Exon Smith       cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
90709d84addSDuncan P. N. Exon Smith   if (DstTy == SrcTy)
90809d84addSDuncan P. N. Exon Smith     return;
90909d84addSDuncan P. N. Exon Smith 
91009d84addSDuncan P. N. Exon Smith   // Grab the element types.  We can only upgrade an array of a two-field
91109d84addSDuncan P. N. Exon Smith   // struct.  Only bother if the other one has three-fields.
91209d84addSDuncan P. N. Exon Smith   auto *DstEltTy = cast<StructType>(DstTy->getElementType());
91309d84addSDuncan P. N. Exon Smith   auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
91409d84addSDuncan P. N. Exon Smith   if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
91509d84addSDuncan P. N. Exon Smith     upgradeGlobalArray(DstGV);
91609d84addSDuncan P. N. Exon Smith     return;
91709d84addSDuncan P. N. Exon Smith   }
91809d84addSDuncan P. N. Exon Smith   if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
91909d84addSDuncan P. N. Exon Smith     upgradeGlobalArray(SrcGV);
92009d84addSDuncan P. N. Exon Smith 
92109d84addSDuncan P. N. Exon Smith   // We can't upgrade any other differences.
92209d84addSDuncan P. N. Exon Smith }
92309d84addSDuncan P. N. Exon Smith 
92409d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobals() {
92509d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobalArray("llvm.global_ctors");
92609d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobalArray("llvm.global_dtors");
92709d84addSDuncan P. N. Exon Smith }
92809d84addSDuncan P. N. Exon Smith 
92918c89411SRafael Espindola /// If there were any appending global variables, link them together now.
93018c89411SRafael Espindola /// Return true on error.
931b1ed91f3SChris Lattner bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
9323e8bc6a8SRafael Espindola                                          const GlobalVariable *SrcGV) {
933d48b7783SBill Wendling 
934b1ed91f3SChris Lattner   if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
935b1ed91f3SChris Lattner     return emitError("Linking globals named '" + SrcGV->getName() +
936b1ed91f3SChris Lattner            "': can only link appending global with another appending global!");
937361e513dSReid Spencer 
938b1ed91f3SChris Lattner   ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
939b1ed91f3SChris Lattner   ArrayType *SrcTy =
940b1ed91f3SChris Lattner     cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
941b1ed91f3SChris Lattner   Type *EltTy = DstTy->getElementType();
942b1ed91f3SChris Lattner 
943b1ed91f3SChris Lattner   // Check to see that they two arrays agree on type.
944b1ed91f3SChris Lattner   if (EltTy != SrcTy->getElementType())
945b1ed91f3SChris Lattner     return emitError("Appending variables with different element types!");
946b1ed91f3SChris Lattner   if (DstGV->isConstant() != SrcGV->isConstant())
947b1ed91f3SChris Lattner     return emitError("Appending variables linked with different const'ness!");
948b1ed91f3SChris Lattner 
949b1ed91f3SChris Lattner   if (DstGV->getAlignment() != SrcGV->getAlignment())
950b1ed91f3SChris Lattner     return emitError(
951b1ed91f3SChris Lattner              "Appending variables with different alignment need to be linked!");
952b1ed91f3SChris Lattner 
953b1ed91f3SChris Lattner   if (DstGV->getVisibility() != SrcGV->getVisibility())
954b1ed91f3SChris Lattner     return emitError(
955b1ed91f3SChris Lattner             "Appending variables with different visibility need to be linked!");
956b1ed91f3SChris Lattner 
957fac3a018SRafael Espindola   if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
958fac3a018SRafael Espindola     return emitError(
959fac3a018SRafael Espindola         "Appending variables with different unnamed_addr need to be linked!");
960fac3a018SRafael Espindola 
96164c1e180SRafael Espindola   if (StringRef(DstGV->getSection()) != SrcGV->getSection())
962b1ed91f3SChris Lattner     return emitError(
963b1ed91f3SChris Lattner           "Appending variables with different section name need to be linked!");
964b1ed91f3SChris Lattner 
965b1ed91f3SChris Lattner   uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
966b1ed91f3SChris Lattner   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
967b1ed91f3SChris Lattner 
968b1ed91f3SChris Lattner   // Create the new global variable.
969b1ed91f3SChris Lattner   GlobalVariable *NG =
970b1ed91f3SChris Lattner     new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
9712617dcceSCraig Topper                        DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
972cbe34b4cSHans Wennborg                        DstGV->getThreadLocalMode(),
973b1ed91f3SChris Lattner                        DstGV->getType()->getAddressSpace());
974b1ed91f3SChris Lattner 
975b1ed91f3SChris Lattner   // Propagate alignment, visibility and section info.
976b6af2f36SBill Wendling   copyGVAttributes(NG, DstGV);
977b1ed91f3SChris Lattner 
978b1ed91f3SChris Lattner   AppendingVarInfo AVI;
979b1ed91f3SChris Lattner   AVI.NewGV = NG;
980b1ed91f3SChris Lattner   AVI.DstInit = DstGV->getInitializer();
981b1ed91f3SChris Lattner   AVI.SrcInit = SrcGV->getInitializer();
982b1ed91f3SChris Lattner   AppendingVars.push_back(AVI);
983b1ed91f3SChris Lattner 
984b1ed91f3SChris Lattner   // Replace any uses of the two global variables with uses of the new
985b1ed91f3SChris Lattner   // global.
986b1ed91f3SChris Lattner   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
987b1ed91f3SChris Lattner 
988b1ed91f3SChris Lattner   DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
989b1ed91f3SChris Lattner   DstGV->eraseFromParent();
990b1ed91f3SChris Lattner 
991cbb91408STanya Lattner   // Track the source variable so we don't try to link it.
992cbb91408STanya Lattner   DoNotLinkFromSource.insert(SrcGV);
993cbb91408STanya Lattner 
994b1ed91f3SChris Lattner   return false;
995b1ed91f3SChris Lattner }
996b1ed91f3SChris Lattner 
997778fcc77SRafael Espindola bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
998b1ed91f3SChris Lattner   GlobalValue *DGV = getLinkedToGlobal(SGV);
999b1ed91f3SChris Lattner 
1000778fcc77SRafael Espindola   // Handle the ultra special appending linkage case first.
1001778fcc77SRafael Espindola   if (DGV && DGV->hasAppendingLinkage())
1002778fcc77SRafael Espindola     return linkAppendingVarProto(cast<GlobalVariable>(DGV),
1003778fcc77SRafael Espindola                                  cast<GlobalVariable>(SGV));
1004778fcc77SRafael Espindola 
1005778fcc77SRafael Espindola   bool LinkFromSrc = true;
1006778fcc77SRafael Espindola   Comdat *C = nullptr;
1007778fcc77SRafael Espindola   GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
1008778fcc77SRafael Espindola   bool HasUnnamedAddr = SGV->hasUnnamedAddr();
1009778fcc77SRafael Espindola 
1010dad0a645SDavid Majnemer   if (const Comdat *SC = SGV->getComdat()) {
1011dad0a645SDavid Majnemer     Comdat::SelectionKind SK;
1012dad0a645SDavid Majnemer     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1013778fcc77SRafael Espindola     C = DstM->getOrInsertComdat(SC->getName());
1014778fcc77SRafael Espindola     C->setSelectionKind(SK);
1015778fcc77SRafael Espindola   } else if (DGV) {
1016778fcc77SRafael Espindola     if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1017fc61de39SChris Lattner       return true;
1018dad0a645SDavid Majnemer   }
101934fc5a0eSChris Lattner 
1020dad0a645SDavid Majnemer   if (!LinkFromSrc) {
1021cbb91408STanya Lattner     // Track the source global so that we don't attempt to copy it over when
1022cbb91408STanya Lattner     // processing global initializers.
1023cbb91408STanya Lattner     DoNotLinkFromSource.insert(SGV);
1024cbb91408STanya Lattner 
1025778fcc77SRafael Espindola     if (DGV)
1026778fcc77SRafael Espindola       // Make sure to remember this mapping.
1027778fcc77SRafael Espindola       ValueMap[SGV] =
1028778fcc77SRafael Espindola           ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
1029778fcc77SRafael Espindola   }
1030778fcc77SRafael Espindola 
1031778fcc77SRafael Espindola   if (DGV) {
1032778fcc77SRafael Espindola     Visibility = isLessConstraining(Visibility, DGV->getVisibility())
1033778fcc77SRafael Espindola                      ? DGV->getVisibility()
1034778fcc77SRafael Espindola                      : Visibility;
1035778fcc77SRafael Espindola     HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1036778fcc77SRafael Espindola   }
1037778fcc77SRafael Espindola 
1038778fcc77SRafael Espindola   if (!LinkFromSrc && !DGV)
1039dad0a645SDavid Majnemer     return false;
1040778fcc77SRafael Espindola 
1041778fcc77SRafael Espindola   GlobalValue *NewGV;
1042778fcc77SRafael Espindola   if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
1043778fcc77SRafael Espindola     NewGV = linkGlobalVariableProto(SGVar, DGV, LinkFromSrc);
1044778fcc77SRafael Espindola     if (!NewGV)
1045778fcc77SRafael Espindola       return true;
1046778fcc77SRafael Espindola   } else if (auto *SF = dyn_cast<Function>(SGV)) {
1047778fcc77SRafael Espindola     NewGV = linkFunctionProto(SF, DGV, LinkFromSrc);
1048778fcc77SRafael Espindola   } else {
1049778fcc77SRafael Espindola     NewGV = linkGlobalAliasProto(cast<GlobalAlias>(SGV), DGV, LinkFromSrc);
1050778fcc77SRafael Espindola   }
1051778fcc77SRafael Espindola 
1052778fcc77SRafael Espindola   if (NewGV) {
1053778fcc77SRafael Espindola     if (NewGV != DGV)
1054778fcc77SRafael Espindola       copyGVAttributes(NewGV, SGV);
1055778fcc77SRafael Espindola 
1056778fcc77SRafael Espindola     NewGV->setUnnamedAddr(HasUnnamedAddr);
1057778fcc77SRafael Espindola     NewGV->setVisibility(Visibility);
1058778fcc77SRafael Espindola 
1059778fcc77SRafael Espindola     if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1060778fcc77SRafael Espindola       if (C)
1061778fcc77SRafael Espindola         NewGO->setComdat(C);
1062778fcc77SRafael Espindola     }
1063778fcc77SRafael Espindola 
1064778fcc77SRafael Espindola     // Make sure to remember this mapping.
1065778fcc77SRafael Espindola     if (NewGV != DGV) {
1066778fcc77SRafael Espindola       if (DGV) {
1067778fcc77SRafael Espindola         DGV->replaceAllUsesWith(
1068778fcc77SRafael Espindola             ConstantExpr::getBitCast(NewGV, DGV->getType()));
1069778fcc77SRafael Espindola         DGV->eraseFromParent();
1070778fcc77SRafael Espindola       }
1071778fcc77SRafael Espindola       ValueMap[SGV] = NewGV;
1072dad0a645SDavid Majnemer     }
10734e27567aSRafael Espindola   }
10744e27567aSRafael Espindola 
1075fd38af2dSChandler Carruth   return false;
10764e27567aSRafael Espindola }
10774e27567aSRafael Espindola 
1078778fcc77SRafael Espindola /// Loop through the global variables in the src module and merge them into the
1079778fcc77SRafael Espindola /// dest module.
1080778fcc77SRafael Espindola GlobalValue *ModuleLinker::linkGlobalVariableProto(const GlobalVariable *SGVar,
1081778fcc77SRafael Espindola                                                    GlobalValue *DGV,
1082778fcc77SRafael Espindola                                                    bool LinkFromSrc) {
1083778fcc77SRafael Espindola   unsigned Alignment = 0;
1084778fcc77SRafael Espindola   bool ClearConstant = false;
1085778fcc77SRafael Espindola 
1086778fcc77SRafael Espindola   if (DGV) {
1087778fcc77SRafael Espindola     if (DGV->hasCommonLinkage() && SGVar->hasCommonLinkage())
1088778fcc77SRafael Espindola       Alignment = std::max(SGVar->getAlignment(), DGV->getAlignment());
1089778fcc77SRafael Espindola 
1090778fcc77SRafael Espindola     auto *DGVar = dyn_cast<GlobalVariable>(DGV);
1091778fcc77SRafael Espindola     if (!SGVar->isConstant() || (DGVar && !DGVar->isConstant()))
1092778fcc77SRafael Espindola       ClearConstant = true;
1093778fcc77SRafael Espindola   }
1094778fcc77SRafael Espindola 
1095778fcc77SRafael Espindola   if (!LinkFromSrc) {
1096778fcc77SRafael Espindola     if (auto *NewGVar = dyn_cast<GlobalVariable>(DGV)) {
1097778fcc77SRafael Espindola       if (Alignment)
1098778fcc77SRafael Espindola         NewGVar->setAlignment(Alignment);
1099778fcc77SRafael Espindola       if (NewGVar->isDeclaration() && ClearConstant)
1100778fcc77SRafael Espindola         NewGVar->setConstant(false);
1101778fcc77SRafael Espindola     }
1102778fcc77SRafael Espindola     return DGV;
1103778fcc77SRafael Espindola   }
1104778fcc77SRafael Espindola 
1105b1ed91f3SChris Lattner   // No linking to be performed or linking from the source: simply create an
1106b1ed91f3SChris Lattner   // identical version of the symbol over in the dest module... the
1107b1ed91f3SChris Lattner   // initializer will be filled in later by LinkGlobalInits.
1108778fcc77SRafael Espindola   GlobalVariable *NewDGV = new GlobalVariable(
1109778fcc77SRafael Espindola       *DstM, TypeMap.get(SGVar->getType()->getElementType()),
1110778fcc77SRafael Espindola       SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr,
1111778fcc77SRafael Espindola       SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
1112778fcc77SRafael Espindola       SGVar->getType()->getAddressSpace());
1113778fcc77SRafael Espindola 
1114778fcc77SRafael Espindola   if (Alignment)
1115fe3842cdSRafael Espindola     NewDGV->setAlignment(Alignment);
1116b1ed91f3SChris Lattner 
1117778fcc77SRafael Espindola   return NewDGV;
1118361e513dSReid Spencer }
1119361e513dSReid Spencer 
112018c89411SRafael Espindola /// Link the function in the source module into the destination module if
112118c89411SRafael Espindola /// needed, setting up mapping information.
1122778fcc77SRafael Espindola GlobalValue *ModuleLinker::linkFunctionProto(const Function *SF,
1123778fcc77SRafael Espindola                                              GlobalValue *DGV,
1124778fcc77SRafael Espindola                                              bool LinkFromSrc) {
1125778fcc77SRafael Espindola   if (!LinkFromSrc)
1126778fcc77SRafael Espindola     return DGV;
1127b1ed91f3SChris Lattner 
1128f6f121e2SJames Molloy   // If the function is to be lazily linked, don't create it just yet.
1129f6f121e2SJames Molloy   // The ValueMaterializerTy will deal with creating it if it's used.
1130f6f121e2SJames Molloy   if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1131f6f121e2SJames Molloy                SF->hasAvailableExternallyLinkage())) {
1132f6f121e2SJames Molloy     DoNotLinkFromSource.insert(SF);
1133778fcc77SRafael Espindola     return nullptr;
1134dad0a645SDavid Majnemer   }
1135dad0a645SDavid Majnemer 
1136b1ed91f3SChris Lattner   // If there is no linkage to be performed or we are linking from the source,
1137b1ed91f3SChris Lattner   // bring SF over.
1138778fcc77SRafael Espindola   return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(),
1139778fcc77SRafael Espindola                           SF->getName(), DstM);
1140361e513dSReid Spencer }
1141361e513dSReid Spencer 
114218c89411SRafael Espindola /// Set up prototypes for any aliases that come over from the source module.
1143778fcc77SRafael Espindola GlobalValue *ModuleLinker::linkGlobalAliasProto(const GlobalAlias *SGA,
1144778fcc77SRafael Espindola                                                 GlobalValue *DGV,
1145778fcc77SRafael Espindola                                                 bool LinkFromSrc) {
1146778fcc77SRafael Espindola   if (!LinkFromSrc)
1147778fcc77SRafael Espindola     return DGV;
1148dad0a645SDavid Majnemer 
1149b1ed91f3SChris Lattner   // If there is no linkage to be performed or we're linking from the source,
1150b1ed91f3SChris Lattner   // bring over SGA.
11514fe0094fSRafael Espindola   auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
1152778fcc77SRafael Espindola   return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
115383705658SRafael Espindola                              SGA->getLinkage(), SGA->getName(), DstM);
1154b1ed91f3SChris Lattner }
1155b1ed91f3SChris Lattner 
11563e8bc6a8SRafael Espindola static void getArrayElements(const Constant *C,
11573e8bc6a8SRafael Espindola                              SmallVectorImpl<Constant *> &Dest) {
11586705883aSChris Lattner   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
115900245f42SChris Lattner 
11606705883aSChris Lattner   for (unsigned i = 0; i != NumElements; ++i)
11616705883aSChris Lattner     Dest.push_back(C->getAggregateElement(i));
116200245f42SChris Lattner }
116300245f42SChris Lattner 
1164b1ed91f3SChris Lattner void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1165b1ed91f3SChris Lattner   // Merge the initializer.
1166d31dc048SRafael Espindola   SmallVector<Constant *, 16> DstElements;
1167d31dc048SRafael Espindola   getArrayElements(AVI.DstInit, DstElements);
1168b1ed91f3SChris Lattner 
1169d31dc048SRafael Espindola   SmallVector<Constant *, 16> SrcElements;
1170d31dc048SRafael Espindola   getArrayElements(AVI.SrcInit, SrcElements);
117100245f42SChris Lattner 
1172b1ed91f3SChris Lattner   ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1173d31dc048SRafael Espindola 
1174d31dc048SRafael Espindola   StringRef Name = AVI.NewGV->getName();
1175d31dc048SRafael Espindola   bool IsNewStructor =
1176d31dc048SRafael Espindola       (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1177d31dc048SRafael Espindola       cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1178d31dc048SRafael Espindola 
1179d31dc048SRafael Espindola   for (auto *V : SrcElements) {
1180d31dc048SRafael Espindola     if (IsNewStructor) {
1181d31dc048SRafael Espindola       Constant *Key = V->getAggregateElement(2);
1182d31dc048SRafael Espindola       if (DoNotLinkFromSource.count(Key))
1183d31dc048SRafael Espindola         continue;
1184d31dc048SRafael Espindola     }
1185d31dc048SRafael Espindola     DstElements.push_back(
1186d31dc048SRafael Espindola         MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1187d31dc048SRafael Espindola   }
1188d31dc048SRafael Espindola   if (IsNewStructor) {
1189d31dc048SRafael Espindola     NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1190d31dc048SRafael Espindola     AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1191d31dc048SRafael Espindola   }
1192d31dc048SRafael Espindola 
1193d31dc048SRafael Espindola   AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1194b1ed91f3SChris Lattner }
1195b1ed91f3SChris Lattner 
119618c89411SRafael Espindola /// Update the initializers in the Dest module now that all globals that may be
119718c89411SRafael Espindola /// referenced are in Dest.
1198b1ed91f3SChris Lattner void ModuleLinker::linkGlobalInits() {
1199b1ed91f3SChris Lattner   // Loop over all of the globals in the src module, mapping them over as we go
1200b1ed91f3SChris Lattner   for (Module::const_global_iterator I = SrcM->global_begin(),
1201b1ed91f3SChris Lattner        E = SrcM->global_end(); I != E; ++I) {
1202cbb91408STanya Lattner 
1203cbb91408STanya Lattner     // Only process initialized GV's or ones not already in dest.
1204cbb91408STanya Lattner     if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1205b1ed91f3SChris Lattner 
1206b1ed91f3SChris Lattner     // Grab destination global variable.
1207b1ed91f3SChris Lattner     GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1208b1ed91f3SChris Lattner     // Figure out what the initializer looks like in the dest module.
1209b1ed91f3SChris Lattner     DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
1210f6f121e2SJames Molloy                                  RF_None, &TypeMap, &ValMaterializer));
1211b1ed91f3SChris Lattner   }
1212b1ed91f3SChris Lattner }
1213b1ed91f3SChris Lattner 
121418c89411SRafael Espindola /// Copy the source function over into the dest function and fix up references
121518c89411SRafael Espindola /// to values. At this point we know that Dest is an external function, and
121618c89411SRafael Espindola /// that Src is not.
1217b1ed91f3SChris Lattner void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1218b1ed91f3SChris Lattner   assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
1219361e513dSReid Spencer 
12207391dde1SChris Lattner   // Go through and convert function arguments over, remembering the mapping.
1221b1ed91f3SChris Lattner   Function::arg_iterator DI = Dst->arg_begin();
1222531f9e92SChris Lattner   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1223361e513dSReid Spencer        I != E; ++I, ++DI) {
1224b1ed91f3SChris Lattner     DI->setName(I->getName());  // Copy the name over.
1225361e513dSReid Spencer 
1226b1ed91f3SChris Lattner     // Add a mapping to our mapping.
122766a6271cSAnton Korobeynikov     ValueMap[I] = DI;
1228361e513dSReid Spencer   }
1229361e513dSReid Spencer 
12302f0557d0SChris Lattner   // Splice the body of the source function into the dest function.
1231b1ed91f3SChris Lattner   Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
1232361e513dSReid Spencer 
1233361e513dSReid Spencer   // At this point, all of the instructions and values of the function are now
1234361e513dSReid Spencer   // copied over.  The only problem is that they are still referencing values in
1235361e513dSReid Spencer   // the Source function as operands.  Loop through all of the operands of the
123643f8d164SChris Lattner   // functions and patch them up to point to the local versions.
1237b1ed91f3SChris Lattner   for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
123843f8d164SChris Lattner     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
12399f8eff31SRafael Espindola       RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap,
12409f8eff31SRafael Espindola                        &ValMaterializer);
1241cbb91408STanya Lattner 
12427391dde1SChris Lattner   // There is no need to map the arguments anymore.
124344ab8aefSChris Lattner   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
124444ab8aefSChris Lattner        I != E; ++I)
12453aaaa0b2SReid Spencer     ValueMap.erase(I);
1246cbb91408STanya Lattner 
1247361e513dSReid Spencer }
1248361e513dSReid Spencer 
124918c89411SRafael Espindola /// Insert all of the aliases in Src into the Dest module.
1250b1ed91f3SChris Lattner void ModuleLinker::linkAliasBodies() {
1251b1ed91f3SChris Lattner   for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
1252cbb91408STanya Lattner        I != E; ++I) {
1253cbb91408STanya Lattner     if (DoNotLinkFromSource.count(I))
1254cbb91408STanya Lattner       continue;
1255b1ed91f3SChris Lattner     if (Constant *Aliasee = I->getAliasee()) {
1256b1ed91f3SChris Lattner       GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
12576b238633SRafael Espindola       Constant *Val =
12586b238633SRafael Espindola           MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
125964c1e180SRafael Espindola       DA->setAliasee(Val);
12602c4a34aeSDavid Chisnall     }
1261b1ed91f3SChris Lattner   }
1262cbb91408STanya Lattner }
1263b1ed91f3SChris Lattner 
126418c89411SRafael Espindola /// Insert all of the named MDNodes in Src into the Dest module.
1265b1ed91f3SChris Lattner void ModuleLinker::linkNamedMDNodes() {
126666f02413SBill Wendling   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1267b1ed91f3SChris Lattner   for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1268b1ed91f3SChris Lattner        E = SrcM->named_metadata_end(); I != E; ++I) {
126966f02413SBill Wendling     // Don't link module flags here. Do them separately.
127066f02413SBill Wendling     if (&*I == SrcModFlags) continue;
1271b1ed91f3SChris Lattner     NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1272b1ed91f3SChris Lattner     // Add Src elements into Dest node.
1273b1ed91f3SChris Lattner     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1274b1ed91f3SChris Lattner       DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
1275f6f121e2SJames Molloy                                    RF_None, &TypeMap, &ValMaterializer));
1276b1ed91f3SChris Lattner   }
1277b1ed91f3SChris Lattner }
1278b1ed91f3SChris Lattner 
127918c89411SRafael Espindola /// Merge the linker flags in Src into the Dest module.
128066f02413SBill Wendling bool ModuleLinker::linkModuleFlagsMetadata() {
12810ec72bbcSDaniel Dunbar   // If the source module has no module flags, we are done.
128266f02413SBill Wendling   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
128366f02413SBill Wendling   if (!SrcModFlags) return false;
128466f02413SBill Wendling 
128566f02413SBill Wendling   // If the destination module doesn't have module flags yet, then just copy
128666f02413SBill Wendling   // over the source module's flags.
12870ec72bbcSDaniel Dunbar   NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
128866f02413SBill Wendling   if (DstModFlags->getNumOperands() == 0) {
128966f02413SBill Wendling     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
129066f02413SBill Wendling       DstModFlags->addOperand(SrcModFlags->getOperand(I));
129166f02413SBill Wendling 
129266f02413SBill Wendling     return false;
129366f02413SBill Wendling   }
129466f02413SBill Wendling 
12950ec72bbcSDaniel Dunbar   // First build a map of the existing module flags and requirements.
12960ec72bbcSDaniel Dunbar   DenseMap<MDString*, MDNode*> Flags;
12970ec72bbcSDaniel Dunbar   SmallSetVector<MDNode*, 16> Requirements;
12980ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1299de36e804SDuncan P. N. Exon Smith     MDNode *Op = DstModFlags->getOperand(I);
13000ec72bbcSDaniel Dunbar     ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
13010ec72bbcSDaniel Dunbar     MDString *ID = cast<MDString>(Op->getOperand(1));
13020ec72bbcSDaniel Dunbar 
13030ec72bbcSDaniel Dunbar     if (Behavior->getZExtValue() == Module::Require) {
13040ec72bbcSDaniel Dunbar       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
13050ec72bbcSDaniel Dunbar     } else {
13060ec72bbcSDaniel Dunbar       Flags[ID] = Op;
13070ec72bbcSDaniel Dunbar     }
13080ec72bbcSDaniel Dunbar   }
13090ec72bbcSDaniel Dunbar 
13100ec72bbcSDaniel Dunbar   // Merge in the flags from the source module, and also collect its set of
13110ec72bbcSDaniel Dunbar   // requirements.
131266f02413SBill Wendling   bool HasErr = false;
13130ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1314de36e804SDuncan P. N. Exon Smith     MDNode *SrcOp = SrcModFlags->getOperand(I);
13150ec72bbcSDaniel Dunbar     ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
13160ec72bbcSDaniel Dunbar     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
13170ec72bbcSDaniel Dunbar     MDNode *DstOp = Flags.lookup(ID);
13180ec72bbcSDaniel Dunbar     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
131966f02413SBill Wendling 
13200ec72bbcSDaniel Dunbar     // If this is a requirement, add it and continue.
13210ec72bbcSDaniel Dunbar     if (SrcBehaviorValue == Module::Require) {
13220ec72bbcSDaniel Dunbar       // If the destination module does not already have this requirement, add
13230ec72bbcSDaniel Dunbar       // it.
13240ec72bbcSDaniel Dunbar       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
13250ec72bbcSDaniel Dunbar         DstModFlags->addOperand(SrcOp);
13260ec72bbcSDaniel Dunbar       }
13270ec72bbcSDaniel Dunbar       continue;
13280ec72bbcSDaniel Dunbar     }
132966f02413SBill Wendling 
13300ec72bbcSDaniel Dunbar     // If there is no existing flag with this ID, just add it.
13310ec72bbcSDaniel Dunbar     if (!DstOp) {
13320ec72bbcSDaniel Dunbar       Flags[ID] = SrcOp;
13330ec72bbcSDaniel Dunbar       DstModFlags->addOperand(SrcOp);
13340ec72bbcSDaniel Dunbar       continue;
13350ec72bbcSDaniel Dunbar     }
133666f02413SBill Wendling 
13370ec72bbcSDaniel Dunbar     // Otherwise, perform a merge.
13380ec72bbcSDaniel Dunbar     ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
13390ec72bbcSDaniel Dunbar     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
13400ec72bbcSDaniel Dunbar 
13410ec72bbcSDaniel Dunbar     // If either flag has override behavior, handle it first.
13420ec72bbcSDaniel Dunbar     if (DstBehaviorValue == Module::Override) {
13430ec72bbcSDaniel Dunbar       // Diagnose inconsistent flags which both have override behavior.
13440ec72bbcSDaniel Dunbar       if (SrcBehaviorValue == Module::Override &&
13450ec72bbcSDaniel Dunbar           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
13460ec72bbcSDaniel Dunbar         HasErr |= emitError("linking module flags '" + ID->getString() +
13470ec72bbcSDaniel Dunbar                             "': IDs have conflicting override values");
13480ec72bbcSDaniel Dunbar       }
13490ec72bbcSDaniel Dunbar       continue;
13500ec72bbcSDaniel Dunbar     } else if (SrcBehaviorValue == Module::Override) {
13510ec72bbcSDaniel Dunbar       // Update the destination flag to that of the source.
13520ec72bbcSDaniel Dunbar       DstOp->replaceOperandWith(0, SrcBehavior);
13530ec72bbcSDaniel Dunbar       DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
13540ec72bbcSDaniel Dunbar       continue;
13550ec72bbcSDaniel Dunbar     }
13560ec72bbcSDaniel Dunbar 
13570ec72bbcSDaniel Dunbar     // Diagnose inconsistent merge behavior types.
13580ec72bbcSDaniel Dunbar     if (SrcBehaviorValue != DstBehaviorValue) {
13590ec72bbcSDaniel Dunbar       HasErr |= emitError("linking module flags '" + ID->getString() +
136066f02413SBill Wendling                           "': IDs have conflicting behaviors");
13610ec72bbcSDaniel Dunbar       continue;
136266f02413SBill Wendling     }
136366f02413SBill Wendling 
13640ec72bbcSDaniel Dunbar     // Perform the merge for standard behavior types.
13650ec72bbcSDaniel Dunbar     switch (SrcBehaviorValue) {
13660ec72bbcSDaniel Dunbar     case Module::Require:
13672a30d788SCraig Topper     case Module::Override: llvm_unreachable("not possible");
13680ec72bbcSDaniel Dunbar     case Module::Error: {
13690ec72bbcSDaniel Dunbar       // Emit an error if the values differ.
13700ec72bbcSDaniel Dunbar       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
13710ec72bbcSDaniel Dunbar         HasErr |= emitError("linking module flags '" + ID->getString() +
13720ec72bbcSDaniel Dunbar                             "': IDs have conflicting values");
137366f02413SBill Wendling       }
13740ec72bbcSDaniel Dunbar       continue;
137566f02413SBill Wendling     }
13760ec72bbcSDaniel Dunbar     case Module::Warning: {
13770ec72bbcSDaniel Dunbar       // Emit a warning if the values differ.
13780ec72bbcSDaniel Dunbar       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1379d12b4a33SRafael Espindola         emitWarning("linking module flags '" + ID->getString() +
1380d12b4a33SRafael Espindola                     "': IDs have conflicting values");
1381e17f3708SEli Bendersky       }
13820ec72bbcSDaniel Dunbar       continue;
13830ec72bbcSDaniel Dunbar     }
1384d77d9fb0SDaniel Dunbar     case Module::Append: {
1385d77d9fb0SDaniel Dunbar       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1386d77d9fb0SDaniel Dunbar       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1387d77d9fb0SDaniel Dunbar       unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1388d77d9fb0SDaniel Dunbar       Value **VP, **Values = VP = new Value*[NumOps];
1389d77d9fb0SDaniel Dunbar       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1390d77d9fb0SDaniel Dunbar         *VP = DstValue->getOperand(i);
1391d77d9fb0SDaniel Dunbar       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1392d77d9fb0SDaniel Dunbar         *VP = SrcValue->getOperand(i);
1393d77d9fb0SDaniel Dunbar       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1394d77d9fb0SDaniel Dunbar                                                ArrayRef<Value*>(Values,
1395d77d9fb0SDaniel Dunbar                                                                 NumOps)));
1396d77d9fb0SDaniel Dunbar       delete[] Values;
1397d77d9fb0SDaniel Dunbar       break;
1398d77d9fb0SDaniel Dunbar     }
1399d77d9fb0SDaniel Dunbar     case Module::AppendUnique: {
1400d77d9fb0SDaniel Dunbar       SmallSetVector<Value*, 16> Elts;
1401d77d9fb0SDaniel Dunbar       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1402d77d9fb0SDaniel Dunbar       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1403d77d9fb0SDaniel Dunbar       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1404d77d9fb0SDaniel Dunbar         Elts.insert(DstValue->getOperand(i));
1405d77d9fb0SDaniel Dunbar       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1406d77d9fb0SDaniel Dunbar         Elts.insert(SrcValue->getOperand(i));
1407d77d9fb0SDaniel Dunbar       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1408d77d9fb0SDaniel Dunbar                                                ArrayRef<Value*>(Elts.begin(),
1409d77d9fb0SDaniel Dunbar                                                                 Elts.end())));
1410d77d9fb0SDaniel Dunbar       break;
1411d77d9fb0SDaniel Dunbar     }
141266f02413SBill Wendling     }
141366f02413SBill Wendling   }
141466f02413SBill Wendling 
14150ec72bbcSDaniel Dunbar   // Check all of the requirements.
14160ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
14170ec72bbcSDaniel Dunbar     MDNode *Requirement = Requirements[I];
14180ec72bbcSDaniel Dunbar     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
14190ec72bbcSDaniel Dunbar     Value *ReqValue = Requirement->getOperand(1);
14200ec72bbcSDaniel Dunbar 
14210ec72bbcSDaniel Dunbar     MDNode *Op = Flags[Flag];
14220ec72bbcSDaniel Dunbar     if (!Op || Op->getOperand(2) != ReqValue) {
14230ec72bbcSDaniel Dunbar       HasErr |= emitError("linking module flags '" + Flag->getString() +
14249273b539SBill Wendling                           "': does not have the required value");
14250ec72bbcSDaniel Dunbar       continue;
142666f02413SBill Wendling     }
142766f02413SBill Wendling   }
142866f02413SBill Wendling 
142966f02413SBill Wendling   return HasErr;
143066f02413SBill Wendling }
143166f02413SBill Wendling 
1432b1ed91f3SChris Lattner bool ModuleLinker::run() {
143366f02413SBill Wendling   assert(DstM && "Null destination module");
143466f02413SBill Wendling   assert(SrcM && "Null source module");
1435b1ed91f3SChris Lattner 
1436b1ed91f3SChris Lattner   // Inherit the target data from the source module if the destination module
1437b1ed91f3SChris Lattner   // doesn't have one already.
1438f863ee29SRafael Espindola   if (!DstM->getDataLayout() && SrcM->getDataLayout())
1439b1ed91f3SChris Lattner     DstM->setDataLayout(SrcM->getDataLayout());
1440b1ed91f3SChris Lattner 
1441b1ed91f3SChris Lattner   // Copy the target triple from the source to dest if the dest's is empty.
1442b1ed91f3SChris Lattner   if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1443b1ed91f3SChris Lattner     DstM->setTargetTriple(SrcM->getTargetTriple());
1444b1ed91f3SChris Lattner 
1445f863ee29SRafael Espindola   if (SrcM->getDataLayout() && DstM->getDataLayout() &&
1446ae593f15SRafael Espindola       *SrcM->getDataLayout() != *DstM->getDataLayout()) {
1447d12b4a33SRafael Espindola     emitWarning("Linking two modules of different data layouts: '" +
1448d12b4a33SRafael Espindola                 SrcM->getModuleIdentifier() + "' is '" +
1449d12b4a33SRafael Espindola                 SrcM->getDataLayoutStr() + "' whereas '" +
1450d12b4a33SRafael Espindola                 DstM->getModuleIdentifier() + "' is '" +
1451d12b4a33SRafael Espindola                 DstM->getDataLayoutStr() + "'\n");
1452e17f3708SEli Bendersky   }
1453b1ed91f3SChris Lattner   if (!SrcM->getTargetTriple().empty() &&
1454b1ed91f3SChris Lattner       DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1455d12b4a33SRafael Espindola     emitWarning("Linking two modules of different target triples: " +
1456d12b4a33SRafael Espindola                 SrcM->getModuleIdentifier() + "' is '" +
1457d12b4a33SRafael Espindola                 SrcM->getTargetTriple() + "' whereas '" +
1458d12b4a33SRafael Espindola                 DstM->getModuleIdentifier() + "' is '" +
1459d12b4a33SRafael Espindola                 DstM->getTargetTriple() + "'\n");
1460e17f3708SEli Bendersky   }
1461b1ed91f3SChris Lattner 
1462b1ed91f3SChris Lattner   // Append the module inline asm string.
1463b1ed91f3SChris Lattner   if (!SrcM->getModuleInlineAsm().empty()) {
1464b1ed91f3SChris Lattner     if (DstM->getModuleInlineAsm().empty())
1465b1ed91f3SChris Lattner       DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1466b1ed91f3SChris Lattner     else
1467b1ed91f3SChris Lattner       DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1468b1ed91f3SChris Lattner                                SrcM->getModuleInlineAsm());
1469b1ed91f3SChris Lattner   }
1470b1ed91f3SChris Lattner 
1471b1ed91f3SChris Lattner   // Loop over all of the linked values to compute type mappings.
1472b1ed91f3SChris Lattner   computeTypeMapping();
1473b1ed91f3SChris Lattner 
1474dad0a645SDavid Majnemer   ComdatsChosen.clear();
14755106ce78SDavid Blaikie   for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
1476dad0a645SDavid Majnemer     const Comdat &C = SMEC.getValue();
1477dad0a645SDavid Majnemer     if (ComdatsChosen.count(&C))
1478dad0a645SDavid Majnemer       continue;
1479dad0a645SDavid Majnemer     Comdat::SelectionKind SK;
1480dad0a645SDavid Majnemer     bool LinkFromSrc;
1481dad0a645SDavid Majnemer     if (getComdatResult(&C, SK, LinkFromSrc))
1482dad0a645SDavid Majnemer       return true;
1483dad0a645SDavid Majnemer     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1484dad0a645SDavid Majnemer   }
1485dad0a645SDavid Majnemer 
148609d84addSDuncan P. N. Exon Smith   // Upgrade mismatched global arrays.
148709d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobals();
148809d84addSDuncan P. N. Exon Smith 
1489b1ed91f3SChris Lattner   // Insert all of the globals in src into the DstM module... without linking
1490b1ed91f3SChris Lattner   // initializers (which could refer to functions not yet mapped over).
1491b1ed91f3SChris Lattner   for (Module::global_iterator I = SrcM->global_begin(),
1492b1ed91f3SChris Lattner        E = SrcM->global_end(); I != E; ++I)
1493778fcc77SRafael Espindola     if (linkGlobalValueProto(I))
1494b1ed91f3SChris Lattner       return true;
1495b1ed91f3SChris Lattner 
1496b1ed91f3SChris Lattner   // Link the functions together between the two modules, without doing function
1497b1ed91f3SChris Lattner   // bodies... this just adds external function prototypes to the DstM
1498b1ed91f3SChris Lattner   // function...  We do this so that when we begin processing function bodies,
1499b1ed91f3SChris Lattner   // all of the global values that may be referenced are available in our
1500b1ed91f3SChris Lattner   // ValueMap.
1501b1ed91f3SChris Lattner   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1502778fcc77SRafael Espindola     if (linkGlobalValueProto(I))
1503b1ed91f3SChris Lattner       return true;
1504b1ed91f3SChris Lattner 
1505b1ed91f3SChris Lattner   // If there were any aliases, link them now.
1506b1ed91f3SChris Lattner   for (Module::alias_iterator I = SrcM->alias_begin(),
1507b1ed91f3SChris Lattner        E = SrcM->alias_end(); I != E; ++I)
1508778fcc77SRafael Espindola     if (linkGlobalValueProto(I))
1509b1ed91f3SChris Lattner       return true;
1510b1ed91f3SChris Lattner 
1511b1ed91f3SChris Lattner   for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1512b1ed91f3SChris Lattner     linkAppendingVarInit(AppendingVars[i]);
1513b1ed91f3SChris Lattner 
1514b1ed91f3SChris Lattner   // Link in the function bodies that are defined in the source module into
1515b1ed91f3SChris Lattner   // DstM.
1516b1ed91f3SChris Lattner   for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1517ea166d44STanya Lattner     // Skip if not linking from source.
1518ea166d44STanya Lattner     if (DoNotLinkFromSource.count(SF)) continue;
1519ea166d44STanya Lattner 
15203fa50f9bSPeter Collingbourne     Function *DF = cast<Function>(ValueMap[SF]);
15213fa50f9bSPeter Collingbourne     if (SF->hasPrefixData()) {
15223fa50f9bSPeter Collingbourne       // Link in the prefix data.
15233fa50f9bSPeter Collingbourne       DF->setPrefixData(MapValue(
15243fa50f9bSPeter Collingbourne           SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
15253fa50f9bSPeter Collingbourne     }
15263fa50f9bSPeter Collingbourne 
1527d4bcefc7SRafael Espindola     // Materialize if needed.
1528d12b4a33SRafael Espindola     if (std::error_code EC = SF->materialize())
1529d12b4a33SRafael Espindola       return emitError(EC.message());
1530b1ed91f3SChris Lattner 
1531d4bcefc7SRafael Espindola     // Skip if no body (function is external).
1532d4bcefc7SRafael Espindola     if (SF->isDeclaration())
1533d4bcefc7SRafael Espindola       continue;
1534d4bcefc7SRafael Espindola 
15353fa50f9bSPeter Collingbourne     linkFunctionBody(DF, SF);
153600623787SBill Wendling     SF->Dematerialize();
1537b1ed91f3SChris Lattner   }
1538b1ed91f3SChris Lattner 
1539b1ed91f3SChris Lattner   // Resolve all uses of aliases with aliasees.
1540b1ed91f3SChris Lattner   linkAliasBodies();
1541b1ed91f3SChris Lattner 
154266f02413SBill Wendling   // Remap all of the named MDNodes in Src into the DstM module. We do this
15436ddbb2e2SDevang Patel   // after linking GlobalValues so that MDNodes that reference GlobalValues
15446ddbb2e2SDevang Patel   // are properly remapped.
15456ddbb2e2SDevang Patel   linkNamedMDNodes();
15466ddbb2e2SDevang Patel 
154766f02413SBill Wendling   // Merge the module flags into the DstM module.
154866f02413SBill Wendling   if (linkModuleFlagsMetadata())
154966f02413SBill Wendling     return true;
155066f02413SBill Wendling 
155191686d6dSBill Wendling   // Update the initializers in the DstM module now that all globals that may
155291686d6dSBill Wendling   // be referenced are in DstM.
155391686d6dSBill Wendling   linkGlobalInits();
155491686d6dSBill Wendling 
15550a48b877STanya Lattner   // Process vector of lazily linked in functions.
15560a48b877STanya Lattner   bool LinkedInAnyFunctions;
15570a48b877STanya Lattner   do {
15580a48b877STanya Lattner     LinkedInAnyFunctions = false;
15590a48b877STanya Lattner 
1560fa228782SBill Wendling     for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
15610a48b877STanya Lattner         E = LazilyLinkFunctions.end(); I != E; ++I) {
1562f6f121e2SJames Molloy       Function *SF = *I;
1563f6f121e2SJames Molloy       if (!SF)
15640a48b877STanya Lattner         continue;
15650a48b877STanya Lattner 
1566fa228782SBill Wendling       Function *DF = cast<Function>(ValueMap[SF]);
15673fa50f9bSPeter Collingbourne       if (SF->hasPrefixData()) {
15683fa50f9bSPeter Collingbourne         // Link in the prefix data.
15693fa50f9bSPeter Collingbourne         DF->setPrefixData(MapValue(SF->getPrefixData(),
15703fa50f9bSPeter Collingbourne                                    ValueMap,
15713fa50f9bSPeter Collingbourne                                    RF_None,
15723fa50f9bSPeter Collingbourne                                    &TypeMap,
15733fa50f9bSPeter Collingbourne                                    &ValMaterializer));
15743fa50f9bSPeter Collingbourne       }
15750a48b877STanya Lattner 
1576d4bcefc7SRafael Espindola       // Materialize if needed.
1577d12b4a33SRafael Espindola       if (std::error_code EC = SF->materialize())
1578d12b4a33SRafael Espindola         return emitError(EC.message());
15790a48b877STanya Lattner 
1580d4bcefc7SRafael Espindola       // Skip if no body (function is external).
1581d4bcefc7SRafael Espindola       if (SF->isDeclaration())
1582d4bcefc7SRafael Espindola         continue;
1583d4bcefc7SRafael Espindola 
1584f6f121e2SJames Molloy       // Erase from vector *before* the function body is linked - linkFunctionBody could
1585f6f121e2SJames Molloy       // invalidate I.
1586f6f121e2SJames Molloy       LazilyLinkFunctions.erase(I);
1587f6f121e2SJames Molloy 
15880a48b877STanya Lattner       // Link in function body.
15890a48b877STanya Lattner       linkFunctionBody(DF, SF);
159000623787SBill Wendling       SF->Dematerialize();
15910a48b877STanya Lattner 
15920a48b877STanya Lattner       // Set flag to indicate we may have more functions to lazily link in
15930a48b877STanya Lattner       // since we linked in a function.
15940a48b877STanya Lattner       LinkedInAnyFunctions = true;
1595f6f121e2SJames Molloy       break;
15960a48b877STanya Lattner     }
15970a48b877STanya Lattner   } while (LinkedInAnyFunctions);
15980a48b877STanya Lattner 
1599b1ed91f3SChris Lattner   // Now that all of the types from the source are used, resolve any structs
1600b1ed91f3SChris Lattner   // copied over to the dest that didn't exist there.
1601b1ed91f3SChris Lattner   TypeMap.linkDefinedTypeBodies();
16022609888fSAnton Korobeynikov 
16032609888fSAnton Korobeynikov   return false;
16042609888fSAnton Korobeynikov }
1605361e513dSReid Spencer 
16065cb9c82aSRafael Espindola void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
16075cb9c82aSRafael Espindola   this->Composite = M;
16085cb9c82aSRafael Espindola   this->DiagnosticHandler = DiagnosticHandler;
16094160f5d3SRafael Espindola 
1610aa9918aaSRafael Espindola   TypeFinder StructTypes;
1611aa9918aaSRafael Espindola   StructTypes.run(*M, true);
1612aa9918aaSRafael Espindola   IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1613aa9918aaSRafael Espindola }
16143df61b7bSRafael Espindola 
16155cb9c82aSRafael Espindola Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
16165cb9c82aSRafael Espindola   init(M, DiagnosticHandler);
16175cb9c82aSRafael Espindola }
16185cb9c82aSRafael Espindola 
16195cb9c82aSRafael Espindola Linker::Linker(Module *M) {
16205cb9c82aSRafael Espindola   init(M, [this](const DiagnosticInfo &DI) {
16215cb9c82aSRafael Espindola     Composite->getContext().diagnose(DI);
16225cb9c82aSRafael Espindola   });
16235cb9c82aSRafael Espindola }
16245cb9c82aSRafael Espindola 
16253df61b7bSRafael Espindola Linker::~Linker() {
16263df61b7bSRafael Espindola }
16273df61b7bSRafael Espindola 
162891e6f6e1SBill Wendling void Linker::deleteModule() {
162991e6f6e1SBill Wendling   delete Composite;
16302617dcceSCraig Topper   Composite = nullptr;
163191e6f6e1SBill Wendling }
163291e6f6e1SBill Wendling 
16339f8eff31SRafael Espindola bool Linker::linkInModule(Module *Src) {
16349f8eff31SRafael Espindola   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
16359f8eff31SRafael Espindola                          DiagnosticHandler);
1636d12b4a33SRafael Espindola   return TheLinker.run();
16373df61b7bSRafael Espindola }
16383df61b7bSRafael Espindola 
1639b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
1640b1ed91f3SChris Lattner // LinkModules entrypoint.
1641b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
1642b1ed91f3SChris Lattner 
164318c89411SRafael Espindola /// This function links two modules together, with the resulting Dest module
164418c89411SRafael Espindola /// modified to be the composite of the two input modules. If an error occurs,
164518c89411SRafael Espindola /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
164618c89411SRafael Espindola /// Upon failure, the Dest module could be in a modified state, and shouldn't be
164718c89411SRafael Espindola /// relied on to be consistent.
16489f8eff31SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src,
16494160f5d3SRafael Espindola                          DiagnosticHandlerFunction DiagnosticHandler) {
16504160f5d3SRafael Espindola   Linker L(Dest, DiagnosticHandler);
16519f8eff31SRafael Espindola   return L.linkInModule(Src);
16524160f5d3SRafael Espindola }
16534160f5d3SRafael Espindola 
16549f8eff31SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src) {
1655287f18b4SRafael Espindola   Linker L(Dest);
16569f8eff31SRafael Espindola   return L.linkInModule(Src);
1657361e513dSReid Spencer }
1658a3aeb980SBill Wendling 
1659a3aeb980SBill Wendling //===----------------------------------------------------------------------===//
1660a3aeb980SBill Wendling // C API.
1661a3aeb980SBill Wendling //===----------------------------------------------------------------------===//
1662a3aeb980SBill Wendling 
1663a3aeb980SBill Wendling LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1664a3aeb980SBill Wendling                          LLVMLinkerMode Mode, char **OutMessages) {
166598ab63ceSRafael Espindola   Module *D = unwrap(Dest);
166698ab63ceSRafael Espindola   std::string Message;
16674160f5d3SRafael Espindola   raw_string_ostream Stream(Message);
16684160f5d3SRafael Espindola   DiagnosticPrinterRawOStream DP(Stream);
16694160f5d3SRafael Espindola 
16704160f5d3SRafael Espindola   LLVMBool Result = Linker::LinkModules(
16719f8eff31SRafael Espindola       D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
167298ab63ceSRafael Espindola 
167398ab63ceSRafael Espindola   if (OutMessages && Result)
167498ab63ceSRafael Espindola     *OutMessages = strdup(Message.c_str());
1675a3aeb980SBill Wendling   return Result;
1676a3aeb980SBill Wendling }
1677