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"
209fb823bbSChandler Carruth #include "llvm/IR/Module.h"
21dcb603feSChandler Carruth #include "llvm/IR/TypeFinder.h"
22e17f3708SEli Bendersky #include "llvm/Support/CommandLine.h"
23b6af2f36SBill Wendling #include "llvm/Support/Debug.h"
24b6af2f36SBill Wendling #include "llvm/Support/raw_ostream.h"
25cbb91408STanya Lattner #include "llvm/Transforms/Utils/Cloning.h"
26981af002SWill Dietz #include <cctype>
2782d6ff6bSDavid Majnemer #include <tuple>
28361e513dSReid Spencer using namespace llvm;
29361e513dSReid Spencer 
30e17f3708SEli Bendersky 
31b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
32b1ed91f3SChris Lattner // TypeMap implementation.
33b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
34b1ed91f3SChris Lattner 
35b1ed91f3SChris Lattner namespace {
36aa9918aaSRafael Espindola   typedef SmallPtrSet<StructType*, 32> TypeSet;
37aa9918aaSRafael Espindola 
38b1ed91f3SChris Lattner class TypeMapTy : public ValueMapTypeRemapper {
39b1ed91f3SChris Lattner   /// MappedTypes - This is a mapping from a source type to a destination type
40b1ed91f3SChris Lattner   /// to use.
41b1ed91f3SChris Lattner   DenseMap<Type*, Type*> MappedTypes;
42b1ed91f3SChris Lattner 
43b1ed91f3SChris Lattner   /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
44b1ed91f3SChris Lattner   /// we speculatively add types to MappedTypes, but keep track of them here in
45b1ed91f3SChris Lattner   /// case we need to roll back.
46b1ed91f3SChris Lattner   SmallVector<Type*, 16> SpeculativeTypes;
47b1ed91f3SChris Lattner 
485e3bd972SChris Lattner   /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
495e3bd972SChris Lattner   /// source module that are mapped to an opaque struct in the destination
505e3bd972SChris Lattner   /// module.
515e3bd972SChris Lattner   SmallVector<StructType*, 16> SrcDefinitionsToResolve;
525e3bd972SChris Lattner 
535e3bd972SChris Lattner   /// DstResolvedOpaqueTypes - This is the set of opaque types in the
545e3bd972SChris Lattner   /// destination modules who are getting a body from the source module.
555e3bd972SChris Lattner   SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
56d48b7783SBill Wendling 
578c2cc416SBill Wendling public:
58aa9918aaSRafael Espindola   TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {}
59aa9918aaSRafael Espindola 
60aa9918aaSRafael Espindola   TypeSet &DstStructTypesSet;
61b1ed91f3SChris Lattner   /// addTypeMapping - Indicate that the specified type in the destination
62b1ed91f3SChris Lattner   /// module is conceptually equivalent to the specified type in the source
63b1ed91f3SChris Lattner   /// module.
64b1ed91f3SChris Lattner   void addTypeMapping(Type *DstTy, Type *SrcTy);
65b1ed91f3SChris Lattner 
66b1ed91f3SChris Lattner   /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
67b1ed91f3SChris Lattner   /// module from a type definition in the source module.
68b1ed91f3SChris Lattner   void linkDefinedTypeBodies();
69b1ed91f3SChris Lattner 
70b1ed91f3SChris Lattner   /// get - 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 
76b6af2f36SBill Wendling   /// dump - 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);
90b1ed91f3SChris Lattner   /// remapType - Implement the ValueMapTypeRemapper interface.
918548299aSCraig Topper   Type *remapType(Type *SrcTy) override {
92b1ed91f3SChris Lattner     return get(SrcTy);
93b1ed91f3SChris Lattner   }
94b1ed91f3SChris Lattner 
95b1ed91f3SChris Lattner   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
96b1ed91f3SChris Lattner };
97b1ed91f3SChris Lattner }
98b1ed91f3SChris Lattner 
99b1ed91f3SChris Lattner void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
100b1ed91f3SChris Lattner   Type *&Entry = MappedTypes[SrcTy];
101b1ed91f3SChris Lattner   if (Entry) return;
102b1ed91f3SChris Lattner 
103b1ed91f3SChris Lattner   if (DstTy == SrcTy) {
104b1ed91f3SChris Lattner     Entry = DstTy;
105b1ed91f3SChris Lattner     return;
106b1ed91f3SChris Lattner   }
107b1ed91f3SChris Lattner 
108b1ed91f3SChris Lattner   // Check to see if these types are recursively isomorphic and establish a
109b1ed91f3SChris Lattner   // mapping between them if so.
110d48b7783SBill Wendling   if (!areTypesIsomorphic(DstTy, SrcTy)) {
111b1ed91f3SChris Lattner     // Oops, they aren't isomorphic.  Just discard this request by rolling out
112b1ed91f3SChris Lattner     // any speculative mappings we've established.
113b1ed91f3SChris Lattner     for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
114b1ed91f3SChris Lattner       MappedTypes.erase(SpeculativeTypes[i]);
115d48b7783SBill Wendling   }
116b1ed91f3SChris Lattner   SpeculativeTypes.clear();
117b1ed91f3SChris Lattner }
118b1ed91f3SChris Lattner 
119b1ed91f3SChris Lattner /// areTypesIsomorphic - Recursively walk this pair of types, returning true
120b1ed91f3SChris Lattner /// if they are isomorphic, false if they are not.
121b1ed91f3SChris Lattner bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
122b1ed91f3SChris Lattner   // Two types with differing kinds are clearly not isomorphic.
123b1ed91f3SChris Lattner   if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
124b1ed91f3SChris Lattner 
125b1ed91f3SChris Lattner   // If we have an entry in the MappedTypes table, then we have our answer.
126b1ed91f3SChris Lattner   Type *&Entry = MappedTypes[SrcTy];
127b1ed91f3SChris Lattner   if (Entry)
128b1ed91f3SChris Lattner     return Entry == DstTy;
129b1ed91f3SChris Lattner 
130b1ed91f3SChris Lattner   // Two identical types are clearly isomorphic.  Remember this
131b1ed91f3SChris Lattner   // non-speculatively.
132b1ed91f3SChris Lattner   if (DstTy == SrcTy) {
133b1ed91f3SChris Lattner     Entry = DstTy;
134361e513dSReid Spencer     return true;
135361e513dSReid Spencer   }
136361e513dSReid Spencer 
137b1ed91f3SChris Lattner   // Okay, we have two types with identical kinds that we haven't seen before.
138361e513dSReid Spencer 
139b1ed91f3SChris Lattner   // If this is an opaque struct type, special case it.
140b1ed91f3SChris Lattner   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
141b1ed91f3SChris Lattner     // Mapping an opaque type to any struct, just keep the dest struct.
142b1ed91f3SChris Lattner     if (SSTy->isOpaque()) {
143b1ed91f3SChris Lattner       Entry = DstTy;
144b1ed91f3SChris Lattner       SpeculativeTypes.push_back(SrcTy);
145b1ed91f3SChris Lattner       return true;
146361e513dSReid Spencer     }
147b1ed91f3SChris Lattner 
1485e3bd972SChris Lattner     // Mapping a non-opaque source type to an opaque dest.  If this is the first
1495e3bd972SChris Lattner     // type that we're mapping onto this destination type then we succeed.  Keep
1505e3bd972SChris Lattner     // the dest, but fill it in later.  This doesn't need to be speculative.  If
1515e3bd972SChris Lattner     // this is the second (different) type that we're trying to map onto the
1525e3bd972SChris Lattner     // same opaque type then we fail.
153b1ed91f3SChris Lattner     if (cast<StructType>(DstTy)->isOpaque()) {
1545e3bd972SChris Lattner       // We can only map one source type onto the opaque destination type.
1555e3bd972SChris Lattner       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
1565e3bd972SChris Lattner         return false;
1575e3bd972SChris Lattner       SrcDefinitionsToResolve.push_back(SSTy);
158b1ed91f3SChris Lattner       Entry = DstTy;
159b1ed91f3SChris Lattner       return true;
160b1ed91f3SChris Lattner     }
161b1ed91f3SChris Lattner   }
162b1ed91f3SChris Lattner 
163b1ed91f3SChris Lattner   // If the number of subtypes disagree between the two types, then we fail.
164b1ed91f3SChris Lattner   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
165b1ed91f3SChris Lattner     return false;
166b1ed91f3SChris Lattner 
167b1ed91f3SChris Lattner   // Fail if any of the extra properties (e.g. array size) of the type disagree.
168b1ed91f3SChris Lattner   if (isa<IntegerType>(DstTy))
169b1ed91f3SChris Lattner     return false;  // bitwidth disagrees.
170b1ed91f3SChris Lattner   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
171b1ed91f3SChris Lattner     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
172b1ed91f3SChris Lattner       return false;
173eaf9b762SChris Lattner 
174b1ed91f3SChris Lattner   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
175b1ed91f3SChris Lattner     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
176b1ed91f3SChris Lattner       return false;
177b1ed91f3SChris Lattner   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
178b1ed91f3SChris Lattner     StructType *SSTy = cast<StructType>(SrcTy);
17944f7ab45SChris Lattner     if (DSTy->isLiteral() != SSTy->isLiteral() ||
180b1ed91f3SChris Lattner         DSTy->isPacked() != SSTy->isPacked())
181b1ed91f3SChris Lattner       return false;
182b1ed91f3SChris Lattner   } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
183b1ed91f3SChris Lattner     if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
184b1ed91f3SChris Lattner       return false;
185b1ed91f3SChris Lattner   } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
1865fad3e9aSJoey Gouly     if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
187361e513dSReid Spencer       return false;
188361e513dSReid Spencer   }
189361e513dSReid Spencer 
190b1ed91f3SChris Lattner   // Otherwise, we speculate that these two types will line up and recursively
191b1ed91f3SChris Lattner   // check the subelements.
192b1ed91f3SChris Lattner   Entry = DstTy;
193b1ed91f3SChris Lattner   SpeculativeTypes.push_back(SrcTy);
194eee6f995SChris Lattner 
195d48b7783SBill Wendling   for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
196d48b7783SBill Wendling     if (!areTypesIsomorphic(DstTy->getContainedType(i),
197d48b7783SBill Wendling                             SrcTy->getContainedType(i)))
198b1ed91f3SChris Lattner       return false;
199eee6f995SChris Lattner 
200b1ed91f3SChris Lattner   // If everything seems to have lined up, then everything is great.
201eee6f995SChris Lattner   return true;
202eee6f995SChris Lattner }
203eee6f995SChris Lattner 
204b1ed91f3SChris Lattner /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
205b1ed91f3SChris Lattner /// module from a type definition in the source module.
206b1ed91f3SChris Lattner void TypeMapTy::linkDefinedTypeBodies() {
207b1ed91f3SChris Lattner   SmallVector<Type*, 16> Elements;
208b1ed91f3SChris Lattner   SmallString<16> TmpName;
209eee6f995SChris Lattner 
210b1ed91f3SChris Lattner   // Note that processing entries in this loop (calling 'get') can add new
2115e3bd972SChris Lattner   // entries to the SrcDefinitionsToResolve vector.
2125e3bd972SChris Lattner   while (!SrcDefinitionsToResolve.empty()) {
2135e3bd972SChris Lattner     StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
214b1ed91f3SChris Lattner     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
215eee6f995SChris Lattner 
216b1ed91f3SChris Lattner     // TypeMap is a many-to-one mapping, if there were multiple types that
217b1ed91f3SChris Lattner     // provide a body for DstSTy then previous iterations of this loop may have
218b1ed91f3SChris Lattner     // already handled it.  Just ignore this case.
219b1ed91f3SChris Lattner     if (!DstSTy->isOpaque()) continue;
220b1ed91f3SChris Lattner     assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
221b1ed91f3SChris Lattner 
222b1ed91f3SChris Lattner     // Map the body of the source type over to a new body for the dest type.
223b1ed91f3SChris Lattner     Elements.resize(SrcSTy->getNumElements());
224b1ed91f3SChris Lattner     for (unsigned i = 0, e = Elements.size(); i != e; ++i)
225b1ed91f3SChris Lattner       Elements[i] = getImpl(SrcSTy->getElementType(i));
226b1ed91f3SChris Lattner 
227b1ed91f3SChris Lattner     DstSTy->setBody(Elements, SrcSTy->isPacked());
228b1ed91f3SChris Lattner 
229b1ed91f3SChris Lattner     // If DstSTy has no name or has a longer name than STy, then viciously steal
230b1ed91f3SChris Lattner     // STy's name.
231b1ed91f3SChris Lattner     if (!SrcSTy->hasName()) continue;
232b1ed91f3SChris Lattner     StringRef SrcName = SrcSTy->getName();
233b1ed91f3SChris Lattner 
234b1ed91f3SChris Lattner     if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
235b1ed91f3SChris Lattner       TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
236b1ed91f3SChris Lattner       SrcSTy->setName("");
237b1ed91f3SChris Lattner       DstSTy->setName(TmpName.str());
238b1ed91f3SChris Lattner       TmpName.clear();
239b1ed91f3SChris Lattner     }
240b1ed91f3SChris Lattner   }
2415e3bd972SChris Lattner 
2425e3bd972SChris Lattner   DstResolvedOpaqueTypes.clear();
243eee6f995SChris Lattner }
244eee6f995SChris Lattner 
245b1ed91f3SChris Lattner /// get - Return the mapped type to use for the specified input type from the
246b1ed91f3SChris Lattner /// source module.
247b1ed91f3SChris Lattner Type *TypeMapTy::get(Type *Ty) {
248b1ed91f3SChris Lattner   Type *Result = getImpl(Ty);
249b1ed91f3SChris Lattner 
250b1ed91f3SChris Lattner   // If this caused a reference to any struct type, resolve it before returning.
2515e3bd972SChris Lattner   if (!SrcDefinitionsToResolve.empty())
252b1ed91f3SChris Lattner     linkDefinedTypeBodies();
253b1ed91f3SChris Lattner   return Result;
254eee6f995SChris Lattner }
255eee6f995SChris Lattner 
256b1ed91f3SChris Lattner /// getImpl - This is the recursive version of get().
257b1ed91f3SChris Lattner Type *TypeMapTy::getImpl(Type *Ty) {
258b1ed91f3SChris Lattner   // If we already have an entry for this type, return it.
259b1ed91f3SChris Lattner   Type **Entry = &MappedTypes[Ty];
260b1ed91f3SChris Lattner   if (*Entry) return *Entry;
261b1ed91f3SChris Lattner 
262b1ed91f3SChris Lattner   // If this is not a named struct type, then just map all of the elements and
263b1ed91f3SChris Lattner   // then rebuild the type from inside out.
26444f7ab45SChris Lattner   if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
265b1ed91f3SChris Lattner     // If there are no element types to map, then the type is itself.  This is
266b1ed91f3SChris Lattner     // true for the anonymous {} struct, things like 'float', integers, etc.
267b1ed91f3SChris Lattner     if (Ty->getNumContainedTypes() == 0)
268b1ed91f3SChris Lattner       return *Entry = Ty;
269b1ed91f3SChris Lattner 
270b1ed91f3SChris Lattner     // Remap all of the elements, keeping track of whether any of them change.
271b1ed91f3SChris Lattner     bool AnyChange = false;
272b1ed91f3SChris Lattner     SmallVector<Type*, 4> ElementTypes;
273b1ed91f3SChris Lattner     ElementTypes.resize(Ty->getNumContainedTypes());
274b1ed91f3SChris Lattner     for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
275b1ed91f3SChris Lattner       ElementTypes[i] = getImpl(Ty->getContainedType(i));
276b1ed91f3SChris Lattner       AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
277eee6f995SChris Lattner     }
278b1ed91f3SChris Lattner 
279b1ed91f3SChris Lattner     // If we found our type while recursively processing stuff, just use it.
280b1ed91f3SChris Lattner     Entry = &MappedTypes[Ty];
281b1ed91f3SChris Lattner     if (*Entry) return *Entry;
282b1ed91f3SChris Lattner 
283b1ed91f3SChris Lattner     // If all of the element types mapped directly over, then the type is usable
284b1ed91f3SChris Lattner     // as-is.
285b1ed91f3SChris Lattner     if (!AnyChange)
286b1ed91f3SChris Lattner       return *Entry = Ty;
287b1ed91f3SChris Lattner 
288b1ed91f3SChris Lattner     // Otherwise, rebuild a modified type.
289b1ed91f3SChris Lattner     switch (Ty->getTypeID()) {
290a2886c21SCraig Topper     default: llvm_unreachable("unknown derived type to remap");
291b1ed91f3SChris Lattner     case Type::ArrayTyID:
292b1ed91f3SChris Lattner       return *Entry = ArrayType::get(ElementTypes[0],
293b1ed91f3SChris Lattner                                      cast<ArrayType>(Ty)->getNumElements());
294b1ed91f3SChris Lattner     case Type::VectorTyID:
295b1ed91f3SChris Lattner       return *Entry = VectorType::get(ElementTypes[0],
296b1ed91f3SChris Lattner                                       cast<VectorType>(Ty)->getNumElements());
297b1ed91f3SChris Lattner     case Type::PointerTyID:
298b1ed91f3SChris Lattner       return *Entry = PointerType::get(ElementTypes[0],
299b1ed91f3SChris Lattner                                       cast<PointerType>(Ty)->getAddressSpace());
300b1ed91f3SChris Lattner     case Type::FunctionTyID:
301b1ed91f3SChris Lattner       return *Entry = FunctionType::get(ElementTypes[0],
302717d7eddSFrits van Bommel                                         makeArrayRef(ElementTypes).slice(1),
303b1ed91f3SChris Lattner                                         cast<FunctionType>(Ty)->isVarArg());
304b1ed91f3SChris Lattner     case Type::StructTyID:
305b1ed91f3SChris Lattner       // Note that this is only reached for anonymous structs.
306b1ed91f3SChris Lattner       return *Entry = StructType::get(Ty->getContext(), ElementTypes,
307b1ed91f3SChris Lattner                                       cast<StructType>(Ty)->isPacked());
308b1ed91f3SChris Lattner     }
309b1ed91f3SChris Lattner   }
310b1ed91f3SChris Lattner 
311b1ed91f3SChris Lattner   // Otherwise, this is an unmapped named struct.  If the struct can be directly
312b1ed91f3SChris Lattner   // mapped over, just use it as-is.  This happens in a case when the linked-in
313b1ed91f3SChris Lattner   // module has something like:
314b1ed91f3SChris Lattner   //   %T = type {%T*, i32}
315b1ed91f3SChris Lattner   //   @GV = global %T* null
316b1ed91f3SChris Lattner   // where T does not exist at all in the destination module.
317b1ed91f3SChris Lattner   //
318b1ed91f3SChris Lattner   // The other case we watch for is when the type is not in the destination
319b1ed91f3SChris Lattner   // module, but that it has to be rebuilt because it refers to something that
320b1ed91f3SChris Lattner   // is already mapped.  For example, if the destination module has:
321b1ed91f3SChris Lattner   //  %A = type { i32 }
322b1ed91f3SChris Lattner   // and the source module has something like
323b1ed91f3SChris Lattner   //  %A' = type { i32 }
324b1ed91f3SChris Lattner   //  %B = type { %A'* }
325b1ed91f3SChris Lattner   //  @GV = global %B* null
326b1ed91f3SChris Lattner   // then we want to create a new type: "%B = type { %A*}" and have it take the
327b1ed91f3SChris Lattner   // pristine "%B" name from the source module.
328b1ed91f3SChris Lattner   //
329b1ed91f3SChris Lattner   // To determine which case this is, we have to recursively walk the type graph
330b1ed91f3SChris Lattner   // speculating that we'll be able to reuse it unmodified.  Only if this is
331b1ed91f3SChris Lattner   // safe would we map the entire thing over.  Because this is an optimization,
332b1ed91f3SChris Lattner   // and is not required for the prettiness of the linked module, we just skip
333b1ed91f3SChris Lattner   // it and always rebuild a type here.
334b1ed91f3SChris Lattner   StructType *STy = cast<StructType>(Ty);
335b1ed91f3SChris Lattner 
336b1ed91f3SChris Lattner   // If the type is opaque, we can just use it directly.
337aa9918aaSRafael Espindola   if (STy->isOpaque()) {
338aa9918aaSRafael Espindola     // A named structure type from src module is used. Add it to the Set of
339aa9918aaSRafael Espindola     // identified structs in the destination module.
340aa9918aaSRafael Espindola     DstStructTypesSet.insert(STy);
341b1ed91f3SChris Lattner     return *Entry = STy;
342aa9918aaSRafael Espindola   }
343b1ed91f3SChris Lattner 
344b1ed91f3SChris Lattner   // Otherwise we create a new type and resolve its body later.  This will be
345b1ed91f3SChris Lattner   // resolved by the top level of get().
3465e3bd972SChris Lattner   SrcDefinitionsToResolve.push_back(STy);
3475e3bd972SChris Lattner   StructType *DTy = StructType::create(STy->getContext());
348aa9918aaSRafael Espindola   // A new identified structure type was created. Add it to the set of
349aa9918aaSRafael Espindola   // identified structs in the destination module.
350aa9918aaSRafael Espindola   DstStructTypesSet.insert(DTy);
3515e3bd972SChris Lattner   DstResolvedOpaqueTypes.insert(DTy);
3525e3bd972SChris Lattner   return *Entry = DTy;
353b1ed91f3SChris Lattner }
354b1ed91f3SChris Lattner 
355b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
356b1ed91f3SChris Lattner // ModuleLinker implementation.
357b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
358b1ed91f3SChris Lattner 
359b1ed91f3SChris Lattner namespace {
360f6f121e2SJames Molloy   class ModuleLinker;
361f6f121e2SJames Molloy 
362f6f121e2SJames Molloy   /// ValueMaterializerTy - Creates prototypes for functions that are lazily
363f6f121e2SJames Molloy   /// linked on the fly. This speeds up linking for modules with many
364f6f121e2SJames Molloy   /// lazily linked functions of which few get used.
365f6f121e2SJames Molloy   class ValueMaterializerTy : public ValueMaterializer {
366f6f121e2SJames Molloy     TypeMapTy &TypeMap;
367f6f121e2SJames Molloy     Module *DstM;
368f6f121e2SJames Molloy     std::vector<Function*> &LazilyLinkFunctions;
369f6f121e2SJames Molloy   public:
370f6f121e2SJames Molloy     ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
371f6f121e2SJames Molloy                         std::vector<Function*> &LazilyLinkFunctions) :
372f6f121e2SJames Molloy       ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
373f6f121e2SJames Molloy       LazilyLinkFunctions(LazilyLinkFunctions) {
374f6f121e2SJames Molloy     }
375f6f121e2SJames Molloy 
3768548299aSCraig Topper     Value *materializeValueFor(Value *V) override;
377f6f121e2SJames Molloy   };
378f6f121e2SJames Molloy 
379b1ed91f3SChris Lattner   /// ModuleLinker - This is an implementation class for the LinkModules
380b1ed91f3SChris Lattner   /// function, which is the entrypoint for this file.
381b1ed91f3SChris Lattner   class ModuleLinker {
382b1ed91f3SChris Lattner     Module *DstM, *SrcM;
383b1ed91f3SChris Lattner 
384b1ed91f3SChris Lattner     TypeMapTy TypeMap;
385f6f121e2SJames Molloy     ValueMaterializerTy ValMaterializer;
386b1ed91f3SChris Lattner 
387b1ed91f3SChris Lattner     /// ValueMap - Mapping of values from what they used to be in Src, to what
388b1ed91f3SChris Lattner     /// they are now in DstM.  ValueToValueMapTy is a ValueMap, which involves
389b1ed91f3SChris Lattner     /// some overhead due to the use of Value handles which the Linker doesn't
390b1ed91f3SChris Lattner     /// actually need, but this allows us to reuse the ValueMapper code.
391b1ed91f3SChris Lattner     ValueToValueMapTy ValueMap;
392b1ed91f3SChris Lattner 
393b1ed91f3SChris Lattner     struct AppendingVarInfo {
394b1ed91f3SChris Lattner       GlobalVariable *NewGV;  // New aggregate global in dest module.
395b1ed91f3SChris Lattner       Constant *DstInit;      // Old initializer from dest module.
396b1ed91f3SChris Lattner       Constant *SrcInit;      // Old initializer from src module.
397b1ed91f3SChris Lattner     };
398b1ed91f3SChris Lattner 
399b1ed91f3SChris Lattner     std::vector<AppendingVarInfo> AppendingVars;
400b1ed91f3SChris Lattner 
401cbb91408STanya Lattner     unsigned Mode; // Mode to treat source module.
402cbb91408STanya Lattner 
403cbb91408STanya Lattner     // Set of items not to link in from source.
404cbb91408STanya Lattner     SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
405cbb91408STanya Lattner 
4060a48b877STanya Lattner     // Vector of functions to lazily link in.
407fa228782SBill Wendling     std::vector<Function*> LazilyLinkFunctions;
4080a48b877STanya Lattner 
4097da92ed8SEli Bendersky     bool SuppressWarnings;
4107da92ed8SEli Bendersky 
411b1ed91f3SChris Lattner   public:
412b1ed91f3SChris Lattner     std::string ErrorMsg;
413b1ed91f3SChris Lattner 
4147da92ed8SEli Bendersky     ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, unsigned mode,
4157da92ed8SEli Bendersky                  bool SuppressWarnings=false)
416f6f121e2SJames Molloy         : DstM(dstM), SrcM(srcM), TypeMap(Set),
4177da92ed8SEli Bendersky           ValMaterializer(TypeMap, DstM, LazilyLinkFunctions), Mode(mode),
4187da92ed8SEli Bendersky           SuppressWarnings(SuppressWarnings) {}
419b1ed91f3SChris Lattner 
420b1ed91f3SChris Lattner     bool run();
421b1ed91f3SChris Lattner 
422b1ed91f3SChris Lattner   private:
423dbb0bd1aSRafael Espindola     bool shouldLinkFromSource(const GlobalValue &Dest, const GlobalValue &Src);
424dbb0bd1aSRafael Espindola 
425b1ed91f3SChris Lattner     /// emitError - Helper method for setting a message and returning an error
426b1ed91f3SChris Lattner     /// code.
427b1ed91f3SChris Lattner     bool emitError(const Twine &Message) {
428b1ed91f3SChris Lattner       ErrorMsg = Message.str();
429b1ed91f3SChris Lattner       return true;
430b1ed91f3SChris Lattner     }
431b1ed91f3SChris Lattner 
432dad0a645SDavid Majnemer     bool getComdatLeader(Module *M, StringRef ComdatName,
433dad0a645SDavid Majnemer                          const GlobalVariable *&GVar);
434dad0a645SDavid Majnemer     bool computeResultingSelectionKind(StringRef ComdatName,
435dad0a645SDavid Majnemer                                        Comdat::SelectionKind Src,
436dad0a645SDavid Majnemer                                        Comdat::SelectionKind Dst,
437dad0a645SDavid Majnemer                                        Comdat::SelectionKind &Result,
438dad0a645SDavid Majnemer                                        bool &LinkFromSrc);
439dad0a645SDavid Majnemer     std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
440dad0a645SDavid Majnemer         ComdatsChosen;
441dad0a645SDavid Majnemer     bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
442dad0a645SDavid Majnemer                          bool &LinkFromSrc);
443dad0a645SDavid Majnemer 
444b1ed91f3SChris Lattner     /// getLinkageResult - This analyzes the two global values and determines
445b1ed91f3SChris Lattner     /// what the result will look like in the destination module.
446b1ed91f3SChris Lattner     bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
44723f8d64bSRafael Espindola                           GlobalValue::LinkageTypes &LT,
44823f8d64bSRafael Espindola                           GlobalValue::VisibilityTypes &Vis,
44923f8d64bSRafael Espindola                           bool &LinkFromSrc);
450b1ed91f3SChris Lattner 
451b1ed91f3SChris Lattner     /// getLinkedToGlobal - Given a global in the source module, return the
452b1ed91f3SChris Lattner     /// global in the destination module that is being linked to, if any.
453b1ed91f3SChris Lattner     GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
454b1ed91f3SChris Lattner       // If the source has no name it can't link.  If it has local linkage,
455b1ed91f3SChris Lattner       // there is no name match-up going on.
456b1ed91f3SChris Lattner       if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
4572617dcceSCraig Topper         return nullptr;
458b1ed91f3SChris Lattner 
459b1ed91f3SChris Lattner       // Otherwise see if we have a match in the destination module's symtab.
460b1ed91f3SChris Lattner       GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
4612617dcceSCraig Topper       if (!DGV) return nullptr;
462b1ed91f3SChris Lattner 
463b1ed91f3SChris Lattner       // If we found a global with the same name in the dest module, but it has
464b1ed91f3SChris Lattner       // internal linkage, we are really not doing any linkage here.
465b1ed91f3SChris Lattner       if (DGV->hasLocalLinkage())
4662617dcceSCraig Topper         return nullptr;
467b1ed91f3SChris Lattner 
468b1ed91f3SChris Lattner       // Otherwise, we do in fact link to the destination global.
469b1ed91f3SChris Lattner       return DGV;
470b1ed91f3SChris Lattner     }
471b1ed91f3SChris Lattner 
472b1ed91f3SChris Lattner     void computeTypeMapping();
473b1ed91f3SChris Lattner 
47409d84addSDuncan P. N. Exon Smith     void upgradeMismatchedGlobalArray(StringRef Name);
47509d84addSDuncan P. N. Exon Smith     void upgradeMismatchedGlobals();
47609d84addSDuncan P. N. Exon Smith 
477b1ed91f3SChris Lattner     bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
478b1ed91f3SChris Lattner     bool linkGlobalProto(GlobalVariable *SrcGV);
479b1ed91f3SChris Lattner     bool linkFunctionProto(Function *SrcF);
480b1ed91f3SChris Lattner     bool linkAliasProto(GlobalAlias *SrcA);
48166f02413SBill Wendling     bool linkModuleFlagsMetadata();
482b1ed91f3SChris Lattner 
483b1ed91f3SChris Lattner     void linkAppendingVarInit(const AppendingVarInfo &AVI);
484b1ed91f3SChris Lattner     void linkGlobalInits();
485b1ed91f3SChris Lattner     void linkFunctionBody(Function *Dst, Function *Src);
486b1ed91f3SChris Lattner     void linkAliasBodies();
487b1ed91f3SChris Lattner     void linkNamedMDNodes();
488eee6f995SChris Lattner   };
489d48b7783SBill Wendling }
490d48b7783SBill Wendling 
491b1ed91f3SChris Lattner /// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
49290246aa7SReid Spencer /// in the symbol table.  This is good for all clients except for us.  Go
49390246aa7SReid Spencer /// through the trouble to force this back.
494b1ed91f3SChris Lattner static void forceRenaming(GlobalValue *GV, StringRef Name) {
495b1ed91f3SChris Lattner   // If the global doesn't force its name or if it already has the right name,
496b1ed91f3SChris Lattner   // there is nothing for us to do.
497b1ed91f3SChris Lattner   if (GV->hasLocalLinkage() || GV->getName() == Name)
498b1ed91f3SChris Lattner     return;
499b1ed91f3SChris Lattner 
500b1ed91f3SChris Lattner   Module *M = GV->getParent();
501361e513dSReid Spencer 
502361e513dSReid Spencer   // If there is a conflict, rename the conflict.
503b1ed91f3SChris Lattner   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
5042a8d2e0eSChris Lattner     GV->takeName(ConflictGV);
505361e513dSReid Spencer     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
506b1ed91f3SChris Lattner     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
5072a8d2e0eSChris Lattner   } else {
5082a8d2e0eSChris Lattner     GV->setName(Name);              // Force the name back
5093aaaa0b2SReid Spencer   }
5103aaaa0b2SReid Spencer }
5113aaaa0b2SReid Spencer 
512b6af2f36SBill Wendling /// copyGVAttributes - copy additional attributes (those not needed to construct
5133aaaa0b2SReid Spencer /// a GlobalValue) from the SrcGV to the DestGV.
514b6af2f36SBill Wendling static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
515dd7daee8SDuncan Sands   // Use the maximum alignment, rather than just copying the alignment of SrcGV.
51699e05cf1SRafael Espindola   auto *DestGO = dyn_cast<GlobalObject>(DestGV);
517a7d9c69cSRafael Espindola   unsigned Alignment;
51899e05cf1SRafael Espindola   if (DestGO)
51999e05cf1SRafael Espindola     Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
520a7d9c69cSRafael Espindola 
521dd7daee8SDuncan Sands   DestGV->copyAttributesFrom(SrcGV);
522a7d9c69cSRafael Espindola 
52399e05cf1SRafael Espindola   if (DestGO)
52499e05cf1SRafael Espindola     DestGO->setAlignment(Alignment);
525b1ed91f3SChris Lattner 
526b1ed91f3SChris Lattner   forceRenaming(DestGV, SrcGV->getName());
527361e513dSReid Spencer }
528361e513dSReid Spencer 
52923f8d64bSRafael Espindola static bool isLessConstraining(GlobalValue::VisibilityTypes a,
53023f8d64bSRafael Espindola                                GlobalValue::VisibilityTypes b) {
53123f8d64bSRafael Espindola   if (a == GlobalValue::HiddenVisibility)
53223f8d64bSRafael Espindola     return false;
53323f8d64bSRafael Espindola   if (b == GlobalValue::HiddenVisibility)
53423f8d64bSRafael Espindola     return true;
53523f8d64bSRafael Espindola   if (a == GlobalValue::ProtectedVisibility)
53623f8d64bSRafael Espindola     return false;
53723f8d64bSRafael Espindola   if (b == GlobalValue::ProtectedVisibility)
53823f8d64bSRafael Espindola     return true;
53923f8d64bSRafael Espindola   return false;
54023f8d64bSRafael Espindola }
54123f8d64bSRafael Espindola 
542f6f121e2SJames Molloy Value *ValueMaterializerTy::materializeValueFor(Value *V) {
543f6f121e2SJames Molloy   Function *SF = dyn_cast<Function>(V);
544f6f121e2SJames Molloy   if (!SF)
5452617dcceSCraig Topper     return nullptr;
546f6f121e2SJames Molloy 
547f6f121e2SJames Molloy   Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
548f6f121e2SJames Molloy                                   SF->getLinkage(), SF->getName(), DstM);
549f6f121e2SJames Molloy   copyGVAttributes(DF, SF);
550f6f121e2SJames Molloy 
5513931c28bSRafael Espindola   if (Comdat *SC = SF->getComdat()) {
5523931c28bSRafael Espindola     Comdat *DC = DstM->getOrInsertComdat(SC->getName());
5533931c28bSRafael Espindola     DF->setComdat(DC);
5543931c28bSRafael Espindola   }
5553931c28bSRafael Espindola 
556f6f121e2SJames Molloy   LazilyLinkFunctions.push_back(SF);
557f6f121e2SJames Molloy   return DF;
558f6f121e2SJames Molloy }
559f6f121e2SJames Molloy 
560dad0a645SDavid Majnemer bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
561dad0a645SDavid Majnemer                                    const GlobalVariable *&GVar) {
562dad0a645SDavid Majnemer   const GlobalValue *GVal = M->getNamedValue(ComdatName);
563dad0a645SDavid Majnemer   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
564dad0a645SDavid Majnemer     GVal = GA->getBaseObject();
565dad0a645SDavid Majnemer     if (!GVal)
566dad0a645SDavid Majnemer       // We cannot resolve the size of the aliasee yet.
567dad0a645SDavid Majnemer       return emitError("Linking COMDATs named '" + ComdatName +
568dad0a645SDavid Majnemer                        "': COMDAT key involves incomputable alias size.");
569dad0a645SDavid Majnemer   }
570dad0a645SDavid Majnemer 
571dad0a645SDavid Majnemer   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
572dad0a645SDavid Majnemer   if (!GVar)
573dad0a645SDavid Majnemer     return emitError(
574dad0a645SDavid Majnemer         "Linking COMDATs named '" + ComdatName +
575dad0a645SDavid Majnemer         "': GlobalVariable required for data dependent selection!");
576dad0a645SDavid Majnemer 
577dad0a645SDavid Majnemer   return false;
578dad0a645SDavid Majnemer }
579dad0a645SDavid Majnemer 
580dad0a645SDavid Majnemer bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
581dad0a645SDavid Majnemer                                                  Comdat::SelectionKind Src,
582dad0a645SDavid Majnemer                                                  Comdat::SelectionKind Dst,
583dad0a645SDavid Majnemer                                                  Comdat::SelectionKind &Result,
584dad0a645SDavid Majnemer                                                  bool &LinkFromSrc) {
585dad0a645SDavid Majnemer   // The ability to mix Comdat::SelectionKind::Any with
586dad0a645SDavid Majnemer   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
587dad0a645SDavid Majnemer   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
588dad0a645SDavid Majnemer                          Dst == Comdat::SelectionKind::Largest;
589dad0a645SDavid Majnemer   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
590dad0a645SDavid Majnemer                          Src == Comdat::SelectionKind::Largest;
591dad0a645SDavid Majnemer   if (DstAnyOrLargest && SrcAnyOrLargest) {
592dad0a645SDavid Majnemer     if (Dst == Comdat::SelectionKind::Largest ||
593dad0a645SDavid Majnemer         Src == Comdat::SelectionKind::Largest)
594dad0a645SDavid Majnemer       Result = Comdat::SelectionKind::Largest;
595dad0a645SDavid Majnemer     else
596dad0a645SDavid Majnemer       Result = Comdat::SelectionKind::Any;
597dad0a645SDavid Majnemer   } else if (Src == Dst) {
598dad0a645SDavid Majnemer     Result = Dst;
599dad0a645SDavid Majnemer   } else {
600dad0a645SDavid Majnemer     return emitError("Linking COMDATs named '" + ComdatName +
601dad0a645SDavid Majnemer                      "': invalid selection kinds!");
602dad0a645SDavid Majnemer   }
603dad0a645SDavid Majnemer 
604dad0a645SDavid Majnemer   switch (Result) {
605dad0a645SDavid Majnemer   case Comdat::SelectionKind::Any:
606dad0a645SDavid Majnemer     // Go with Dst.
607dad0a645SDavid Majnemer     LinkFromSrc = false;
608dad0a645SDavid Majnemer     break;
609dad0a645SDavid Majnemer   case Comdat::SelectionKind::NoDuplicates:
610dad0a645SDavid Majnemer     return emitError("Linking COMDATs named '" + ComdatName +
611dad0a645SDavid Majnemer                      "': noduplicates has been violated!");
612dad0a645SDavid Majnemer   case Comdat::SelectionKind::ExactMatch:
613dad0a645SDavid Majnemer   case Comdat::SelectionKind::Largest:
614dad0a645SDavid Majnemer   case Comdat::SelectionKind::SameSize: {
615dad0a645SDavid Majnemer     const GlobalVariable *DstGV;
616dad0a645SDavid Majnemer     const GlobalVariable *SrcGV;
617dad0a645SDavid Majnemer     if (getComdatLeader(DstM, ComdatName, DstGV) ||
618dad0a645SDavid Majnemer         getComdatLeader(SrcM, ComdatName, SrcGV))
619dad0a645SDavid Majnemer       return true;
620dad0a645SDavid Majnemer 
621dad0a645SDavid Majnemer     const DataLayout *DstDL = DstM->getDataLayout();
622dad0a645SDavid Majnemer     const DataLayout *SrcDL = SrcM->getDataLayout();
623dad0a645SDavid Majnemer     if (!DstDL || !SrcDL) {
624dad0a645SDavid Majnemer       return emitError(
625dad0a645SDavid Majnemer           "Linking COMDATs named '" + ComdatName +
626dad0a645SDavid Majnemer           "': can't do size dependent selection without DataLayout!");
627dad0a645SDavid Majnemer     }
628dad0a645SDavid Majnemer     uint64_t DstSize =
629dad0a645SDavid Majnemer         DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
630dad0a645SDavid Majnemer     uint64_t SrcSize =
631dad0a645SDavid Majnemer         SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
632dad0a645SDavid Majnemer     if (Result == Comdat::SelectionKind::ExactMatch) {
633dad0a645SDavid Majnemer       if (SrcGV->getInitializer() != DstGV->getInitializer())
634dad0a645SDavid Majnemer         return emitError("Linking COMDATs named '" + ComdatName +
635dad0a645SDavid Majnemer                          "': ExactMatch violated!");
636dad0a645SDavid Majnemer       LinkFromSrc = false;
637dad0a645SDavid Majnemer     } else if (Result == Comdat::SelectionKind::Largest) {
638dad0a645SDavid Majnemer       LinkFromSrc = SrcSize > DstSize;
639dad0a645SDavid Majnemer     } else if (Result == Comdat::SelectionKind::SameSize) {
640dad0a645SDavid Majnemer       if (SrcSize != DstSize)
641dad0a645SDavid Majnemer         return emitError("Linking COMDATs named '" + ComdatName +
642dad0a645SDavid Majnemer                          "': SameSize violated!");
643dad0a645SDavid Majnemer       LinkFromSrc = false;
644dad0a645SDavid Majnemer     } else {
645dad0a645SDavid Majnemer       llvm_unreachable("unknown selection kind");
646dad0a645SDavid Majnemer     }
647dad0a645SDavid Majnemer     break;
648dad0a645SDavid Majnemer   }
649dad0a645SDavid Majnemer   }
650dad0a645SDavid Majnemer 
651dad0a645SDavid Majnemer   return false;
652dad0a645SDavid Majnemer }
653dad0a645SDavid Majnemer 
654dad0a645SDavid Majnemer bool ModuleLinker::getComdatResult(const Comdat *SrcC,
655dad0a645SDavid Majnemer                                    Comdat::SelectionKind &Result,
656dad0a645SDavid Majnemer                                    bool &LinkFromSrc) {
657b16196a3SRafael Espindola   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
658dad0a645SDavid Majnemer   StringRef ComdatName = SrcC->getName();
659dad0a645SDavid Majnemer   Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
660dad0a645SDavid Majnemer   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
6612ef3f299SRafael Espindola 
662b16196a3SRafael Espindola   if (DstCI == ComdatSymTab.end()) {
663b16196a3SRafael Espindola     // Use the comdat if it is only available in one of the modules.
664b16196a3SRafael Espindola     LinkFromSrc = true;
665b16196a3SRafael Espindola     Result = SSK;
6662ef3f299SRafael Espindola     return false;
667b16196a3SRafael Espindola   }
6682ef3f299SRafael Espindola 
669dad0a645SDavid Majnemer   const Comdat *DstC = &DstCI->second;
670dad0a645SDavid Majnemer   Comdat::SelectionKind DSK = DstC->getSelectionKind();
6712ef3f299SRafael Espindola   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
6722ef3f299SRafael Espindola                                        LinkFromSrc);
673dad0a645SDavid Majnemer }
674f6f121e2SJames Molloy 
675dbb0bd1aSRafael Espindola bool ModuleLinker::shouldLinkFromSource(const GlobalValue &Dest,
676dbb0bd1aSRafael Espindola                                         const GlobalValue &Src) {
677*d4bcefc7SRafael Espindola   bool SrcIsDeclaration = Src.isDeclarationForLinker();
678*d4bcefc7SRafael Espindola   bool DestIsDeclaration = Dest.isDeclarationForLinker();
679dbb0bd1aSRafael Espindola 
6800910605aSRafael Espindola   // FIXME: Make datalayout mandatory and just use getDataLayout().
6810910605aSRafael Espindola   DataLayout DL(Dest.getParent());
6820910605aSRafael Espindola 
683dbb0bd1aSRafael Espindola   if (SrcIsDeclaration) {
684dbb0bd1aSRafael Espindola     // If Src is external or if both Src & Dest are external..  Just link the
685dbb0bd1aSRafael Espindola     // external globals, we aren't adding anything.
686dbb0bd1aSRafael Espindola     if (Src.hasDLLImportStorageClass())
687dbb0bd1aSRafael Espindola       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
688dbb0bd1aSRafael Espindola       return DestIsDeclaration;
689dbb0bd1aSRafael Espindola     // If the Dest is weak, use the source linkage.
690dbb0bd1aSRafael Espindola     return Dest.hasExternalWeakLinkage();
691dbb0bd1aSRafael Espindola   }
692dbb0bd1aSRafael Espindola 
693dbb0bd1aSRafael Espindola   if (DestIsDeclaration)
694dbb0bd1aSRafael Espindola     // If Dest is external but Src is not:
695dbb0bd1aSRafael Espindola     return true;
696dbb0bd1aSRafael Espindola 
6970910605aSRafael Espindola   if (Src.hasCommonLinkage()) {
6980910605aSRafael Espindola     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage())
6990910605aSRafael Espindola       return true;
7000910605aSRafael Espindola 
7010910605aSRafael Espindola     if (!Dest.hasCommonLinkage())
7020910605aSRafael Espindola       return false;
7030910605aSRafael Espindola 
7040910605aSRafael Espindola     uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
7050910605aSRafael Espindola     uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
7060910605aSRafael Espindola     return SrcSize > DestSize;
7070910605aSRafael Espindola   }
7080910605aSRafael Espindola 
709dbb0bd1aSRafael Espindola   if (Src.isWeakForLinker()) {
710dbb0bd1aSRafael Espindola     assert(!Dest.hasExternalWeakLinkage());
711dbb0bd1aSRafael Espindola     assert(!Dest.hasAvailableExternallyLinkage());
7120910605aSRafael Espindola 
713dbb0bd1aSRafael Espindola     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage())
714dbb0bd1aSRafael Espindola       return true;
715dbb0bd1aSRafael Espindola 
7160910605aSRafael Espindola     return false;
717dbb0bd1aSRafael Espindola   }
718dbb0bd1aSRafael Espindola 
719dbb0bd1aSRafael Espindola   if (Dest.isWeakForLinker()) {
720dbb0bd1aSRafael Espindola     assert(Src.hasExternalLinkage());
721dbb0bd1aSRafael Espindola     return true;
722dbb0bd1aSRafael Espindola   }
723dbb0bd1aSRafael Espindola 
724dbb0bd1aSRafael Espindola   assert(!Src.hasExternalWeakLinkage());
725dbb0bd1aSRafael Espindola   assert(!Dest.hasExternalWeakLinkage());
726dbb0bd1aSRafael Espindola   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
727dbb0bd1aSRafael Espindola          "Unexpected linkage type!");
728dbb0bd1aSRafael Espindola   return emitError("Linking globals named '" + Src.getName() +
729dbb0bd1aSRafael Espindola                    "': symbol multiply defined!");
730dbb0bd1aSRafael Espindola }
731dbb0bd1aSRafael Espindola 
73283a7ddbcSRafael Espindola /// This analyzes the two global values and determines what the result will look
73383a7ddbcSRafael Espindola /// like in the destination module. In particular, it computes the resultant
73483a7ddbcSRafael Espindola /// linkage type and visibility, computes whether the global in the source
73583a7ddbcSRafael Espindola /// should be copied over to the destination (replacing the existing one), and
73683a7ddbcSRafael Espindola /// computes whether this linkage is an error or not.
737b1ed91f3SChris Lattner bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
738b1ed91f3SChris Lattner                                     GlobalValue::LinkageTypes &LT,
73923f8d64bSRafael Espindola                                     GlobalValue::VisibilityTypes &Vis,
740b1ed91f3SChris Lattner                                     bool &LinkFromSrc) {
741b1ed91f3SChris Lattner   assert(Dest && "Must have two globals being queried");
742b1ed91f3SChris Lattner   assert(!Src->hasLocalLinkage() &&
743fc61de39SChris Lattner          "If Src has internal linkage, Dest shouldn't be set!");
744b1ed91f3SChris Lattner 
745dbb0bd1aSRafael Espindola   assert(ErrorMsg.empty());
746dbb0bd1aSRafael Espindola   LinkFromSrc = shouldLinkFromSource(*Dest, *Src);
747dbb0bd1aSRafael Espindola   if (!ErrorMsg.empty())
748dbb0bd1aSRafael Espindola     return true;
749b1ed91f3SChris Lattner 
750dbb0bd1aSRafael Espindola   if (LinkFromSrc)
751d61d39ecSAnton Korobeynikov     LT = Src->getLinkage();
752dbb0bd1aSRafael Espindola   else
753c83c8d4eSRafael Espindola     LT = Dest->getLinkage();
75431fc4f95SAnton Korobeynikov 
75523f8d64bSRafael Espindola   // Compute the visibility. We follow the rules in the System V Application
75623f8d64bSRafael Espindola   // Binary Interface.
757b2becfdbSDuncan P. N. Exon Smith   assert(!GlobalValue::isLocalLinkage(LT) &&
758b2becfdbSDuncan P. N. Exon Smith          "Symbols with local linkage should not be merged");
75923f8d64bSRafael Espindola   Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
76023f8d64bSRafael Espindola     Dest->getVisibility() : Src->getVisibility();
761fc61de39SChris Lattner   return false;
762fc61de39SChris Lattner }
763361e513dSReid Spencer 
764b1ed91f3SChris Lattner /// computeTypeMapping - Loop over all of the linked values to compute type
765b1ed91f3SChris Lattner /// mappings.  For example, if we link "extern Foo *x" and "Foo *x = NULL", then
766b1ed91f3SChris Lattner /// we have two struct types 'Foo' but one got renamed when the module was
767b1ed91f3SChris Lattner /// loaded into the same LLVMContext.
768b1ed91f3SChris Lattner void ModuleLinker::computeTypeMapping() {
769b1ed91f3SChris Lattner   // Incorporate globals.
770b1ed91f3SChris Lattner   for (Module::global_iterator I = SrcM->global_begin(),
771b1ed91f3SChris Lattner        E = SrcM->global_end(); I != E; ++I) {
772b1ed91f3SChris Lattner     GlobalValue *DGV = getLinkedToGlobal(I);
7732617dcceSCraig Topper     if (!DGV) continue;
774b1ed91f3SChris Lattner 
775b1ed91f3SChris Lattner     if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
776b1ed91f3SChris Lattner       TypeMap.addTypeMapping(DGV->getType(), I->getType());
777b1ed91f3SChris Lattner       continue;
7785c310be0SDevang Patel     }
7795c310be0SDevang Patel 
780b1ed91f3SChris Lattner     // Unify the element type of appending arrays.
781b1ed91f3SChris Lattner     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
782b1ed91f3SChris Lattner     ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
783b1ed91f3SChris Lattner     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
784b1ed91f3SChris Lattner   }
78534fc5a0eSChris Lattner 
786b1ed91f3SChris Lattner   // Incorporate functions.
787b1ed91f3SChris Lattner   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
788b1ed91f3SChris Lattner     if (GlobalValue *DGV = getLinkedToGlobal(I))
789b1ed91f3SChris Lattner       TypeMap.addTypeMapping(DGV->getType(), I->getType());
790b1ed91f3SChris Lattner   }
791e79f4c77SAnton Korobeynikov 
792d48b7783SBill Wendling   // Incorporate types by name, scanning all the types in the source module.
793d48b7783SBill Wendling   // At this point, the destination module may have a type "%foo = { i32 }" for
7942b3f61afSBill Wendling   // example.  When the source module got loaded into the same LLVMContext, if
7952b3f61afSBill Wendling   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
7968555a37cSBill Wendling   TypeFinder SrcStructTypes;
7978555a37cSBill Wendling   SrcStructTypes.run(*SrcM, true);
7982b3f61afSBill Wendling   SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
7992b3f61afSBill Wendling                                                  SrcStructTypes.end());
8002b3f61afSBill Wendling 
8012b3f61afSBill Wendling   for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
8022b3f61afSBill Wendling     StructType *ST = SrcStructTypes[i];
8032b3f61afSBill Wendling     if (!ST->hasName()) continue;
8042b3f61afSBill Wendling 
8052b3f61afSBill Wendling     // Check to see if there is a dot in the name followed by a digit.
806d48b7783SBill Wendling     size_t DotPos = ST->getName().rfind('.');
807d48b7783SBill Wendling     if (DotPos == 0 || DotPos == StringRef::npos ||
80883c74e9fSGuy Benyei         ST->getName().back() == '.' ||
80983c74e9fSGuy Benyei         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
810d48b7783SBill Wendling       continue;
8112b3f61afSBill Wendling 
8122b3f61afSBill Wendling     // Check to see if the destination module has a struct with the prefix name.
813d48b7783SBill Wendling     if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
8142b3f61afSBill Wendling       // Don't use it if this actually came from the source module. They're in
8158737480dSBill Wendling       // the same LLVMContext after all. Also don't use it unless the type is
8168737480dSBill Wendling       // actually used in the destination module. This can happen in situations
8178737480dSBill Wendling       // like this:
8188737480dSBill Wendling       //
8198737480dSBill Wendling       //      Module A                         Module B
8208737480dSBill Wendling       //      --------                         --------
8218737480dSBill Wendling       //   %Z = type { %A }                %B = type { %C.1 }
8228737480dSBill Wendling       //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
8238737480dSBill Wendling       //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
8248737480dSBill Wendling       //   %C = type { i8* }               %B.3 = type { %C.1 }
8258737480dSBill Wendling       //
8268737480dSBill Wendling       // When we link Module B with Module A, the '%B' in Module B is
8278737480dSBill Wendling       // used. However, that would then use '%C.1'. But when we process '%C.1',
8288737480dSBill Wendling       // we prefer to take the '%C' version. So we are then left with both
8298737480dSBill Wendling       // '%C.1' and '%C' being used for the same types. This leads to some
8308737480dSBill Wendling       // variables using one type and some using the other.
831aa9918aaSRafael Espindola       if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
8322b3f61afSBill Wendling         TypeMap.addTypeMapping(DST, ST);
8332b3f61afSBill Wendling   }
8342b3f61afSBill Wendling 
835b1ed91f3SChris Lattner   // Don't bother incorporating aliases, they aren't generally typed well.
836361e513dSReid Spencer 
837b1ed91f3SChris Lattner   // Now that we have discovered all of the type equivalences, get a body for
838b1ed91f3SChris Lattner   // any 'opaque' types in the dest module that are now resolved.
839b1ed91f3SChris Lattner   TypeMap.linkDefinedTypeBodies();
840b1ed91f3SChris Lattner }
841c08e7a00SChris Lattner 
84209d84addSDuncan P. N. Exon Smith static void upgradeGlobalArray(GlobalVariable *GV) {
84309d84addSDuncan P. N. Exon Smith   ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
84409d84addSDuncan P. N. Exon Smith   StructType *OldTy = cast<StructType>(ATy->getElementType());
84509d84addSDuncan P. N. Exon Smith   assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
84609d84addSDuncan P. N. Exon Smith 
84709d84addSDuncan P. N. Exon Smith   // Get the upgraded 3 element type.
84809d84addSDuncan P. N. Exon Smith   PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
84909d84addSDuncan P. N. Exon Smith   Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
85009d84addSDuncan P. N. Exon Smith                   VoidPtrTy};
85109d84addSDuncan P. N. Exon Smith   StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
85209d84addSDuncan P. N. Exon Smith 
85309d84addSDuncan P. N. Exon Smith   // Build new constants with a null third field filled in.
85409d84addSDuncan P. N. Exon Smith   Constant *OldInitC = GV->getInitializer();
85509d84addSDuncan P. N. Exon Smith   ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
85609d84addSDuncan P. N. Exon Smith   if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
85709d84addSDuncan P. N. Exon Smith     // Invalid initializer; give up.
85809d84addSDuncan P. N. Exon Smith     return;
85909d84addSDuncan P. N. Exon Smith   std::vector<Constant *> Initializers;
86009d84addSDuncan P. N. Exon Smith   if (OldInit && OldInit->getNumOperands()) {
86109d84addSDuncan P. N. Exon Smith     Value *Null = Constant::getNullValue(VoidPtrTy);
86209d84addSDuncan P. N. Exon Smith     for (Use &U : OldInit->operands()) {
86309d84addSDuncan P. N. Exon Smith       ConstantStruct *Init = cast<ConstantStruct>(U.get());
86409d84addSDuncan P. N. Exon Smith       Initializers.push_back(ConstantStruct::get(
86509d84addSDuncan P. N. Exon Smith           NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
86609d84addSDuncan P. N. Exon Smith     }
86709d84addSDuncan P. N. Exon Smith   }
86809d84addSDuncan P. N. Exon Smith   assert(Initializers.size() == ATy->getNumElements() &&
86909d84addSDuncan P. N. Exon Smith          "Failed to copy all array elements");
87009d84addSDuncan P. N. Exon Smith 
87109d84addSDuncan P. N. Exon Smith   // Replace the old GV with a new one.
87209d84addSDuncan P. N. Exon Smith   ATy = ArrayType::get(NewTy, Initializers.size());
87309d84addSDuncan P. N. Exon Smith   Constant *NewInit = ConstantArray::get(ATy, Initializers);
87409d84addSDuncan P. N. Exon Smith   GlobalVariable *NewGV = new GlobalVariable(
87509d84addSDuncan P. N. Exon Smith       *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
87609d84addSDuncan P. N. Exon Smith       GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
87709d84addSDuncan P. N. Exon Smith       GV->isExternallyInitialized());
87809d84addSDuncan P. N. Exon Smith   NewGV->copyAttributesFrom(GV);
87909d84addSDuncan P. N. Exon Smith   NewGV->takeName(GV);
88009d84addSDuncan P. N. Exon Smith   assert(GV->use_empty() && "program cannot use initializer list");
88109d84addSDuncan P. N. Exon Smith   GV->eraseFromParent();
88209d84addSDuncan P. N. Exon Smith }
88309d84addSDuncan P. N. Exon Smith 
88409d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
88509d84addSDuncan P. N. Exon Smith   // Look for the global arrays.
88609d84addSDuncan P. N. Exon Smith   auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
88709d84addSDuncan P. N. Exon Smith   if (!DstGV)
88809d84addSDuncan P. N. Exon Smith     return;
88909d84addSDuncan P. N. Exon Smith   auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
89009d84addSDuncan P. N. Exon Smith   if (!SrcGV)
89109d84addSDuncan P. N. Exon Smith     return;
89209d84addSDuncan P. N. Exon Smith 
89309d84addSDuncan P. N. Exon Smith   // Check if the types already match.
89409d84addSDuncan P. N. Exon Smith   auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
89509d84addSDuncan P. N. Exon Smith   auto *SrcTy =
89609d84addSDuncan P. N. Exon Smith       cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
89709d84addSDuncan P. N. Exon Smith   if (DstTy == SrcTy)
89809d84addSDuncan P. N. Exon Smith     return;
89909d84addSDuncan P. N. Exon Smith 
90009d84addSDuncan P. N. Exon Smith   // Grab the element types.  We can only upgrade an array of a two-field
90109d84addSDuncan P. N. Exon Smith   // struct.  Only bother if the other one has three-fields.
90209d84addSDuncan P. N. Exon Smith   auto *DstEltTy = cast<StructType>(DstTy->getElementType());
90309d84addSDuncan P. N. Exon Smith   auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
90409d84addSDuncan P. N. Exon Smith   if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
90509d84addSDuncan P. N. Exon Smith     upgradeGlobalArray(DstGV);
90609d84addSDuncan P. N. Exon Smith     return;
90709d84addSDuncan P. N. Exon Smith   }
90809d84addSDuncan P. N. Exon Smith   if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
90909d84addSDuncan P. N. Exon Smith     upgradeGlobalArray(SrcGV);
91009d84addSDuncan P. N. Exon Smith 
91109d84addSDuncan P. N. Exon Smith   // We can't upgrade any other differences.
91209d84addSDuncan P. N. Exon Smith }
91309d84addSDuncan P. N. Exon Smith 
91409d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobals() {
91509d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobalArray("llvm.global_ctors");
91609d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobalArray("llvm.global_dtors");
91709d84addSDuncan P. N. Exon Smith }
91809d84addSDuncan P. N. Exon Smith 
919b1ed91f3SChris Lattner /// linkAppendingVarProto - If there were any appending global variables, link
920b1ed91f3SChris Lattner /// them together now.  Return true on error.
921b1ed91f3SChris Lattner bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
922b1ed91f3SChris Lattner                                          GlobalVariable *SrcGV) {
923d48b7783SBill Wendling 
924b1ed91f3SChris Lattner   if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
925b1ed91f3SChris Lattner     return emitError("Linking globals named '" + SrcGV->getName() +
926b1ed91f3SChris Lattner            "': can only link appending global with another appending global!");
927361e513dSReid Spencer 
928b1ed91f3SChris Lattner   ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
929b1ed91f3SChris Lattner   ArrayType *SrcTy =
930b1ed91f3SChris Lattner     cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
931b1ed91f3SChris Lattner   Type *EltTy = DstTy->getElementType();
932b1ed91f3SChris Lattner 
933b1ed91f3SChris Lattner   // Check to see that they two arrays agree on type.
934b1ed91f3SChris Lattner   if (EltTy != SrcTy->getElementType())
935b1ed91f3SChris Lattner     return emitError("Appending variables with different element types!");
936b1ed91f3SChris Lattner   if (DstGV->isConstant() != SrcGV->isConstant())
937b1ed91f3SChris Lattner     return emitError("Appending variables linked with different const'ness!");
938b1ed91f3SChris Lattner 
939b1ed91f3SChris Lattner   if (DstGV->getAlignment() != SrcGV->getAlignment())
940b1ed91f3SChris Lattner     return emitError(
941b1ed91f3SChris Lattner              "Appending variables with different alignment need to be linked!");
942b1ed91f3SChris Lattner 
943b1ed91f3SChris Lattner   if (DstGV->getVisibility() != SrcGV->getVisibility())
944b1ed91f3SChris Lattner     return emitError(
945b1ed91f3SChris Lattner             "Appending variables with different visibility need to be linked!");
946b1ed91f3SChris Lattner 
947fac3a018SRafael Espindola   if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
948fac3a018SRafael Espindola     return emitError(
949fac3a018SRafael Espindola         "Appending variables with different unnamed_addr need to be linked!");
950fac3a018SRafael Espindola 
95164c1e180SRafael Espindola   if (StringRef(DstGV->getSection()) != SrcGV->getSection())
952b1ed91f3SChris Lattner     return emitError(
953b1ed91f3SChris Lattner           "Appending variables with different section name need to be linked!");
954b1ed91f3SChris Lattner 
955b1ed91f3SChris Lattner   uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
956b1ed91f3SChris Lattner   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
957b1ed91f3SChris Lattner 
958b1ed91f3SChris Lattner   // Create the new global variable.
959b1ed91f3SChris Lattner   GlobalVariable *NG =
960b1ed91f3SChris Lattner     new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
9612617dcceSCraig Topper                        DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
962cbe34b4cSHans Wennborg                        DstGV->getThreadLocalMode(),
963b1ed91f3SChris Lattner                        DstGV->getType()->getAddressSpace());
964b1ed91f3SChris Lattner 
965b1ed91f3SChris Lattner   // Propagate alignment, visibility and section info.
966b6af2f36SBill Wendling   copyGVAttributes(NG, DstGV);
967b1ed91f3SChris Lattner 
968b1ed91f3SChris Lattner   AppendingVarInfo AVI;
969b1ed91f3SChris Lattner   AVI.NewGV = NG;
970b1ed91f3SChris Lattner   AVI.DstInit = DstGV->getInitializer();
971b1ed91f3SChris Lattner   AVI.SrcInit = SrcGV->getInitializer();
972b1ed91f3SChris Lattner   AppendingVars.push_back(AVI);
973b1ed91f3SChris Lattner 
974b1ed91f3SChris Lattner   // Replace any uses of the two global variables with uses of the new
975b1ed91f3SChris Lattner   // global.
976b1ed91f3SChris Lattner   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
977b1ed91f3SChris Lattner 
978b1ed91f3SChris Lattner   DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
979b1ed91f3SChris Lattner   DstGV->eraseFromParent();
980b1ed91f3SChris Lattner 
981cbb91408STanya Lattner   // Track the source variable so we don't try to link it.
982cbb91408STanya Lattner   DoNotLinkFromSource.insert(SrcGV);
983cbb91408STanya Lattner 
984b1ed91f3SChris Lattner   return false;
985b1ed91f3SChris Lattner }
986b1ed91f3SChris Lattner 
987b1ed91f3SChris Lattner /// linkGlobalProto - Loop through the global variables in the src module and
988b1ed91f3SChris Lattner /// merge them into the dest module.
989b1ed91f3SChris Lattner bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
990b1ed91f3SChris Lattner   GlobalValue *DGV = getLinkedToGlobal(SGV);
99123f8d64bSRafael Espindola   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
992d4885daeSRafael Espindola   bool HasUnnamedAddr = SGV->hasUnnamedAddr();
993fe3842cdSRafael Espindola   unsigned Alignment = SGV->getAlignment();
994b1ed91f3SChris Lattner 
995dad0a645SDavid Majnemer   bool LinkFromSrc = false;
996dad0a645SDavid Majnemer   Comdat *DC = nullptr;
997dad0a645SDavid Majnemer   if (const Comdat *SC = SGV->getComdat()) {
998dad0a645SDavid Majnemer     Comdat::SelectionKind SK;
999dad0a645SDavid Majnemer     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1000dad0a645SDavid Majnemer     DC = DstM->getOrInsertComdat(SC->getName());
1001dad0a645SDavid Majnemer     DC->setSelectionKind(SK);
1002dad0a645SDavid Majnemer   }
1003dad0a645SDavid Majnemer 
1004b1ed91f3SChris Lattner   if (DGV) {
1005dad0a645SDavid Majnemer     if (!DC) {
1006b1ed91f3SChris Lattner       // Concatenation of appending linkage variables is magic and handled later.
1007b1ed91f3SChris Lattner       if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
1008b1ed91f3SChris Lattner         return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
1009b1ed91f3SChris Lattner 
1010b1ed91f3SChris Lattner       // Determine whether linkage of these two globals follows the source
1011b1ed91f3SChris Lattner       // module's definition or the destination module's definition.
10121b9633d7SChris Lattner       GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
101323f8d64bSRafael Espindola       GlobalValue::VisibilityTypes NV;
101423f8d64bSRafael Espindola       if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
1015fc61de39SChris Lattner         return true;
101623f8d64bSRafael Espindola       NewVisibility = NV;
1017fd9a9415SRafael Espindola       HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1018fe3842cdSRafael Espindola       if (DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1019fe3842cdSRafael Espindola         Alignment = std::max(Alignment, DGV->getAlignment());
1020fe3842cdSRafael Espindola       else if (!LinkFromSrc)
1021fe3842cdSRafael Espindola         Alignment = DGV->getAlignment();
1022361e513dSReid Spencer 
1023b1ed91f3SChris Lattner       // If we're not linking from the source, then keep the definition that we
1024b1ed91f3SChris Lattner       // have.
1025b1ed91f3SChris Lattner       if (!LinkFromSrc) {
102634fc5a0eSChris Lattner         // Special case for const propagation.
1027fe3842cdSRafael Espindola         if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
1028fe3842cdSRafael Espindola           DGVar->setAlignment(Alignment);
1029fe3842cdSRafael Espindola 
1030dad0a645SDavid Majnemer           if (DGVar->isDeclaration() && SGV->isConstant() &&
1031dad0a645SDavid Majnemer               !DGVar->isConstant())
103234fc5a0eSChris Lattner             DGVar->setConstant(true);
1033fe3842cdSRafael Espindola         }
103434fc5a0eSChris Lattner 
1035d4885daeSRafael Espindola         // Set calculated linkage, visibility and unnamed_addr.
103634fc5a0eSChris Lattner         DGV->setLinkage(NewLinkage);
103723f8d64bSRafael Espindola         DGV->setVisibility(*NewVisibility);
1038d4885daeSRafael Espindola         DGV->setUnnamedAddr(HasUnnamedAddr);
1039dad0a645SDavid Majnemer       }
1040dad0a645SDavid Majnemer     }
104134fc5a0eSChris Lattner 
1042dad0a645SDavid Majnemer     if (!LinkFromSrc) {
1043b1ed91f3SChris Lattner       // Make sure to remember this mapping.
1044b1ed91f3SChris Lattner       ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
1045b1ed91f3SChris Lattner 
1046cbb91408STanya Lattner       // Track the source global so that we don't attempt to copy it over when
1047cbb91408STanya Lattner       // processing global initializers.
1048cbb91408STanya Lattner       DoNotLinkFromSource.insert(SGV);
1049cbb91408STanya Lattner 
1050b1ed91f3SChris Lattner       return false;
1051361e513dSReid Spencer     }
1052b1ed91f3SChris Lattner   }
1053b1ed91f3SChris Lattner 
1054dad0a645SDavid Majnemer   // If the Comdat this variable was inside of wasn't selected, skip it.
1055dad0a645SDavid Majnemer   if (DC && !DGV && !LinkFromSrc) {
1056dad0a645SDavid Majnemer     DoNotLinkFromSource.insert(SGV);
1057dad0a645SDavid Majnemer     return false;
1058dad0a645SDavid Majnemer   }
1059dad0a645SDavid Majnemer 
1060b1ed91f3SChris Lattner   // No linking to be performed or linking from the source: simply create an
1061b1ed91f3SChris Lattner   // identical version of the symbol over in the dest module... the
1062b1ed91f3SChris Lattner   // initializer will be filled in later by LinkGlobalInits.
1063b1ed91f3SChris Lattner   GlobalVariable *NewDGV =
1064b1ed91f3SChris Lattner     new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
10652617dcceSCraig Topper                        SGV->isConstant(), SGV->getLinkage(), /*init*/nullptr,
10662617dcceSCraig Topper                        SGV->getName(), /*insertbefore*/nullptr,
1067cbe34b4cSHans Wennborg                        SGV->getThreadLocalMode(),
1068b1ed91f3SChris Lattner                        SGV->getType()->getAddressSpace());
1069b1ed91f3SChris Lattner   // Propagate alignment, visibility and section info.
1070b6af2f36SBill Wendling   copyGVAttributes(NewDGV, SGV);
1071fe3842cdSRafael Espindola   NewDGV->setAlignment(Alignment);
107223f8d64bSRafael Espindola   if (NewVisibility)
107323f8d64bSRafael Espindola     NewDGV->setVisibility(*NewVisibility);
1074d4885daeSRafael Espindola   NewDGV->setUnnamedAddr(HasUnnamedAddr);
1075b1ed91f3SChris Lattner 
1076dad0a645SDavid Majnemer   if (DC)
1077dad0a645SDavid Majnemer     NewDGV->setComdat(DC);
1078dad0a645SDavid Majnemer 
1079b1ed91f3SChris Lattner   if (DGV) {
1080b1ed91f3SChris Lattner     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
1081b1ed91f3SChris Lattner     DGV->eraseFromParent();
1082b1ed91f3SChris Lattner   }
1083b1ed91f3SChris Lattner 
1084b1ed91f3SChris Lattner   // Make sure to remember this mapping.
1085b1ed91f3SChris Lattner   ValueMap[SGV] = NewDGV;
1086361e513dSReid Spencer   return false;
1087361e513dSReid Spencer }
1088361e513dSReid Spencer 
1089b1ed91f3SChris Lattner /// linkFunctionProto - Link the function in the source module into the
1090b1ed91f3SChris Lattner /// destination module if needed, setting up mapping information.
1091b1ed91f3SChris Lattner bool ModuleLinker::linkFunctionProto(Function *SF) {
1092b1ed91f3SChris Lattner   GlobalValue *DGV = getLinkedToGlobal(SF);
109323f8d64bSRafael Espindola   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
1094fd9a9415SRafael Espindola   bool HasUnnamedAddr = SF->hasUnnamedAddr();
1095dac5fa94SAnton Korobeynikov 
10960ead7a50SChris Lattner   bool LinkFromSrc = false;
1097dad0a645SDavid Majnemer   Comdat *DC = nullptr;
1098dad0a645SDavid Majnemer   if (const Comdat *SC = SF->getComdat()) {
1099dad0a645SDavid Majnemer     Comdat::SelectionKind SK;
1100dad0a645SDavid Majnemer     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1101dad0a645SDavid Majnemer     DC = DstM->getOrInsertComdat(SC->getName());
1102dad0a645SDavid Majnemer     DC->setSelectionKind(SK);
1103dad0a645SDavid Majnemer   }
1104dad0a645SDavid Majnemer 
1105dad0a645SDavid Majnemer   if (DGV) {
1106dad0a645SDavid Majnemer     if (!DC) {
1107dad0a645SDavid Majnemer       GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
110823f8d64bSRafael Espindola       GlobalValue::VisibilityTypes NV;
110923f8d64bSRafael Espindola       if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
11100ead7a50SChris Lattner         return true;
111123f8d64bSRafael Espindola       NewVisibility = NV;
1112fd9a9415SRafael Espindola       HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
11130ead7a50SChris Lattner 
1114b1ed91f3SChris Lattner       if (!LinkFromSrc) {
11150ead7a50SChris Lattner         // Set calculated linkage
11160ead7a50SChris Lattner         DGV->setLinkage(NewLinkage);
111723f8d64bSRafael Espindola         DGV->setVisibility(*NewVisibility);
1118fd9a9415SRafael Espindola         DGV->setUnnamedAddr(HasUnnamedAddr);
1119dad0a645SDavid Majnemer       }
1120dad0a645SDavid Majnemer     }
112177e8ac4dSChris Lattner 
1122dad0a645SDavid Majnemer     if (!LinkFromSrc) {
11230ead7a50SChris Lattner       // Make sure to remember this mapping.
1124b1ed91f3SChris Lattner       ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
1125b1ed91f3SChris Lattner 
1126cbb91408STanya Lattner       // Track the function from the source module so we don't attempt to remap
1127cbb91408STanya Lattner       // it.
1128cbb91408STanya Lattner       DoNotLinkFromSource.insert(SF);
1129cbb91408STanya Lattner 
1130b1ed91f3SChris Lattner       return false;
1131361e513dSReid Spencer     }
1132b1ed91f3SChris Lattner   }
1133b1ed91f3SChris Lattner 
1134f6f121e2SJames Molloy   // If the function is to be lazily linked, don't create it just yet.
1135f6f121e2SJames Molloy   // The ValueMaterializerTy will deal with creating it if it's used.
1136f6f121e2SJames Molloy   if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1137f6f121e2SJames Molloy                SF->hasAvailableExternallyLinkage())) {
1138f6f121e2SJames Molloy     DoNotLinkFromSource.insert(SF);
1139f6f121e2SJames Molloy     return false;
1140f6f121e2SJames Molloy   }
1141f6f121e2SJames Molloy 
1142dad0a645SDavid Majnemer   // If the Comdat this function was inside of wasn't selected, skip it.
1143dad0a645SDavid Majnemer   if (DC && !DGV && !LinkFromSrc) {
1144dad0a645SDavid Majnemer     DoNotLinkFromSource.insert(SF);
1145dad0a645SDavid Majnemer     return false;
1146dad0a645SDavid Majnemer   }
1147dad0a645SDavid Majnemer 
1148b1ed91f3SChris Lattner   // If there is no linkage to be performed or we are linking from the source,
1149b1ed91f3SChris Lattner   // bring SF over.
1150b1ed91f3SChris Lattner   Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
1151b1ed91f3SChris Lattner                                      SF->getLinkage(), SF->getName(), DstM);
1152b6af2f36SBill Wendling   copyGVAttributes(NewDF, SF);
115323f8d64bSRafael Espindola   if (NewVisibility)
115423f8d64bSRafael Espindola     NewDF->setVisibility(*NewVisibility);
1155fd9a9415SRafael Espindola   NewDF->setUnnamedAddr(HasUnnamedAddr);
1156b1ed91f3SChris Lattner 
1157dad0a645SDavid Majnemer   if (DC)
1158dad0a645SDavid Majnemer     NewDF->setComdat(DC);
1159dad0a645SDavid Majnemer 
1160b1ed91f3SChris Lattner   if (DGV) {
1161b1ed91f3SChris Lattner     // Any uses of DF need to change to NewDF, with cast.
1162b1ed91f3SChris Lattner     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
1163b1ed91f3SChris Lattner     DGV->eraseFromParent();
1164b1ed91f3SChris Lattner   }
1165b1ed91f3SChris Lattner 
1166b1ed91f3SChris Lattner   ValueMap[SF] = NewDF;
1167361e513dSReid Spencer   return false;
1168361e513dSReid Spencer }
1169361e513dSReid Spencer 
1170b1ed91f3SChris Lattner /// LinkAliasProto - Set up prototypes for any aliases that come over from the
1171b1ed91f3SChris Lattner /// source module.
1172b1ed91f3SChris Lattner bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
1173b1ed91f3SChris Lattner   GlobalValue *DGV = getLinkedToGlobal(SGA);
117423f8d64bSRafael Espindola   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
117542a4c9f9SRafael Espindola   bool HasUnnamedAddr = SGA->hasUnnamedAddr();
1176b1ed91f3SChris Lattner 
1177dad0a645SDavid Majnemer   bool LinkFromSrc = false;
1178dad0a645SDavid Majnemer   Comdat *DC = nullptr;
1179dad0a645SDavid Majnemer   if (const Comdat *SC = SGA->getComdat()) {
1180dad0a645SDavid Majnemer     Comdat::SelectionKind SK;
1181dad0a645SDavid Majnemer     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1182dad0a645SDavid Majnemer     DC = DstM->getOrInsertComdat(SC->getName());
1183dad0a645SDavid Majnemer     DC->setSelectionKind(SK);
1184dad0a645SDavid Majnemer   }
1185dad0a645SDavid Majnemer 
1186b1ed91f3SChris Lattner   if (DGV) {
1187dad0a645SDavid Majnemer     if (!DC) {
1188b1ed91f3SChris Lattner       GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
118923f8d64bSRafael Espindola       GlobalValue::VisibilityTypes NV;
119023f8d64bSRafael Espindola       if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
1191b1ed91f3SChris Lattner         return true;
119223f8d64bSRafael Espindola       NewVisibility = NV;
119342a4c9f9SRafael Espindola       HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1194b1ed91f3SChris Lattner 
1195b1ed91f3SChris Lattner       if (!LinkFromSrc) {
1196b1ed91f3SChris Lattner         // Set calculated linkage.
1197b1ed91f3SChris Lattner         DGV->setLinkage(NewLinkage);
119823f8d64bSRafael Espindola         DGV->setVisibility(*NewVisibility);
119942a4c9f9SRafael Espindola         DGV->setUnnamedAddr(HasUnnamedAddr);
1200dad0a645SDavid Majnemer       }
1201dad0a645SDavid Majnemer     }
1202b1ed91f3SChris Lattner 
1203dad0a645SDavid Majnemer     if (!LinkFromSrc) {
1204b1ed91f3SChris Lattner       // Make sure to remember this mapping.
1205b1ed91f3SChris Lattner       ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
1206b1ed91f3SChris Lattner 
1207cbb91408STanya Lattner       // Track the alias from the source module so we don't attempt to remap it.
1208cbb91408STanya Lattner       DoNotLinkFromSource.insert(SGA);
1209cbb91408STanya Lattner 
1210b1ed91f3SChris Lattner       return false;
1211b1ed91f3SChris Lattner     }
1212b1ed91f3SChris Lattner   }
1213b1ed91f3SChris Lattner 
1214dad0a645SDavid Majnemer   // If the Comdat this alias was inside of wasn't selected, skip it.
1215dad0a645SDavid Majnemer   if (DC && !DGV && !LinkFromSrc) {
1216dad0a645SDavid Majnemer     DoNotLinkFromSource.insert(SGA);
1217dad0a645SDavid Majnemer     return false;
1218dad0a645SDavid Majnemer   }
1219dad0a645SDavid Majnemer 
1220b1ed91f3SChris Lattner   // If there is no linkage to be performed or we're linking from the source,
1221b1ed91f3SChris Lattner   // bring over SGA.
12224fe0094fSRafael Espindola   auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
1223f1bedd37SRafael Espindola   auto *NewDA =
1224f1bedd37SRafael Espindola       GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
122583705658SRafael Espindola                           SGA->getLinkage(), SGA->getName(), DstM);
1226b6af2f36SBill Wendling   copyGVAttributes(NewDA, SGA);
122723f8d64bSRafael Espindola   if (NewVisibility)
122823f8d64bSRafael Espindola     NewDA->setVisibility(*NewVisibility);
122942a4c9f9SRafael Espindola   NewDA->setUnnamedAddr(HasUnnamedAddr);
1230b1ed91f3SChris Lattner 
123164c1e180SRafael Espindola   if (DGV) {
123264c1e180SRafael Espindola     // Any uses of DGV need to change to NewDA, with cast.
123364c1e180SRafael Espindola     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
123464c1e180SRafael Espindola     DGV->eraseFromParent();
123564c1e180SRafael Espindola   }
1236b1ed91f3SChris Lattner 
1237b1ed91f3SChris Lattner   ValueMap[SGA] = NewDA;
1238b1ed91f3SChris Lattner   return false;
1239b1ed91f3SChris Lattner }
1240b1ed91f3SChris Lattner 
124100245f42SChris Lattner static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
12426705883aSChris Lattner   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
124300245f42SChris Lattner 
12446705883aSChris Lattner   for (unsigned i = 0; i != NumElements; ++i)
12456705883aSChris Lattner     Dest.push_back(C->getAggregateElement(i));
124600245f42SChris Lattner }
124700245f42SChris Lattner 
1248b1ed91f3SChris Lattner void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1249b1ed91f3SChris Lattner   // Merge the initializer.
1250d31dc048SRafael Espindola   SmallVector<Constant *, 16> DstElements;
1251d31dc048SRafael Espindola   getArrayElements(AVI.DstInit, DstElements);
1252b1ed91f3SChris Lattner 
1253d31dc048SRafael Espindola   SmallVector<Constant *, 16> SrcElements;
1254d31dc048SRafael Espindola   getArrayElements(AVI.SrcInit, SrcElements);
125500245f42SChris Lattner 
1256b1ed91f3SChris Lattner   ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1257d31dc048SRafael Espindola 
1258d31dc048SRafael Espindola   StringRef Name = AVI.NewGV->getName();
1259d31dc048SRafael Espindola   bool IsNewStructor =
1260d31dc048SRafael Espindola       (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1261d31dc048SRafael Espindola       cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1262d31dc048SRafael Espindola 
1263d31dc048SRafael Espindola   for (auto *V : SrcElements) {
1264d31dc048SRafael Espindola     if (IsNewStructor) {
1265d31dc048SRafael Espindola       Constant *Key = V->getAggregateElement(2);
1266d31dc048SRafael Espindola       if (DoNotLinkFromSource.count(Key))
1267d31dc048SRafael Espindola         continue;
1268d31dc048SRafael Espindola     }
1269d31dc048SRafael Espindola     DstElements.push_back(
1270d31dc048SRafael Espindola         MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1271d31dc048SRafael Espindola   }
1272d31dc048SRafael Espindola   if (IsNewStructor) {
1273d31dc048SRafael Espindola     NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1274d31dc048SRafael Espindola     AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1275d31dc048SRafael Espindola   }
1276d31dc048SRafael Espindola 
1277d31dc048SRafael Espindola   AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1278b1ed91f3SChris Lattner }
1279b1ed91f3SChris Lattner 
1280b6af2f36SBill Wendling /// linkGlobalInits - Update the initializers in the Dest module now that all
1281b6af2f36SBill Wendling /// globals that may be referenced are in Dest.
1282b1ed91f3SChris Lattner void ModuleLinker::linkGlobalInits() {
1283b1ed91f3SChris Lattner   // Loop over all of the globals in the src module, mapping them over as we go
1284b1ed91f3SChris Lattner   for (Module::const_global_iterator I = SrcM->global_begin(),
1285b1ed91f3SChris Lattner        E = SrcM->global_end(); I != E; ++I) {
1286cbb91408STanya Lattner 
1287cbb91408STanya Lattner     // Only process initialized GV's or ones not already in dest.
1288cbb91408STanya Lattner     if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1289b1ed91f3SChris Lattner 
1290b1ed91f3SChris Lattner     // Grab destination global variable.
1291b1ed91f3SChris Lattner     GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1292b1ed91f3SChris Lattner     // Figure out what the initializer looks like in the dest module.
1293b1ed91f3SChris Lattner     DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
1294f6f121e2SJames Molloy                                  RF_None, &TypeMap, &ValMaterializer));
1295b1ed91f3SChris Lattner   }
1296b1ed91f3SChris Lattner }
1297b1ed91f3SChris Lattner 
1298b6af2f36SBill Wendling /// linkFunctionBody - Copy the source function over into the dest function and
1299b6af2f36SBill Wendling /// fix up references to values.  At this point we know that Dest is an external
1300b6af2f36SBill Wendling /// function, and that Src is not.
1301b1ed91f3SChris Lattner void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1302b1ed91f3SChris Lattner   assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
1303361e513dSReid Spencer 
13047391dde1SChris Lattner   // Go through and convert function arguments over, remembering the mapping.
1305b1ed91f3SChris Lattner   Function::arg_iterator DI = Dst->arg_begin();
1306531f9e92SChris Lattner   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1307361e513dSReid Spencer        I != E; ++I, ++DI) {
1308b1ed91f3SChris Lattner     DI->setName(I->getName());  // Copy the name over.
1309361e513dSReid Spencer 
1310b1ed91f3SChris Lattner     // Add a mapping to our mapping.
131166a6271cSAnton Korobeynikov     ValueMap[I] = DI;
1312361e513dSReid Spencer   }
1313361e513dSReid Spencer 
1314cbb91408STanya Lattner   if (Mode == Linker::DestroySource) {
13152f0557d0SChris Lattner     // Splice the body of the source function into the dest function.
1316b1ed91f3SChris Lattner     Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
1317361e513dSReid Spencer 
1318361e513dSReid Spencer     // At this point, all of the instructions and values of the function are now
1319361e513dSReid Spencer     // copied over.  The only problem is that they are still referencing values in
1320361e513dSReid Spencer     // the Source function as operands.  Loop through all of the operands of the
132143f8d164SChris Lattner     // functions and patch them up to point to the local versions.
1322b1ed91f3SChris Lattner     for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
132343f8d164SChris Lattner       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1324f6f121e2SJames Molloy         RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries,
1325f6f121e2SJames Molloy                          &TypeMap, &ValMaterializer);
13267391dde1SChris Lattner 
1327cbb91408STanya Lattner   } else {
1328cbb91408STanya Lattner     // Clone the body of the function into the dest function.
1329cbb91408STanya Lattner     SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
13302617dcceSCraig Topper     CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", nullptr,
1331f6f121e2SJames Molloy                       &TypeMap, &ValMaterializer);
1332cbb91408STanya Lattner   }
1333cbb91408STanya Lattner 
13347391dde1SChris Lattner   // There is no need to map the arguments anymore.
133544ab8aefSChris Lattner   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
133644ab8aefSChris Lattner        I != E; ++I)
13373aaaa0b2SReid Spencer     ValueMap.erase(I);
1338cbb91408STanya Lattner 
1339361e513dSReid Spencer }
1340361e513dSReid Spencer 
1341b6af2f36SBill Wendling /// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
1342b1ed91f3SChris Lattner void ModuleLinker::linkAliasBodies() {
1343b1ed91f3SChris Lattner   for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
1344cbb91408STanya Lattner        I != E; ++I) {
1345cbb91408STanya Lattner     if (DoNotLinkFromSource.count(I))
1346cbb91408STanya Lattner       continue;
1347b1ed91f3SChris Lattner     if (Constant *Aliasee = I->getAliasee()) {
1348b1ed91f3SChris Lattner       GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
13496b238633SRafael Espindola       Constant *Val =
13506b238633SRafael Espindola           MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
135164c1e180SRafael Espindola       DA->setAliasee(Val);
13522c4a34aeSDavid Chisnall     }
1353b1ed91f3SChris Lattner   }
1354cbb91408STanya Lattner }
1355b1ed91f3SChris Lattner 
1356b6af2f36SBill Wendling /// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
1357b1ed91f3SChris Lattner /// module.
1358b1ed91f3SChris Lattner void ModuleLinker::linkNamedMDNodes() {
135966f02413SBill Wendling   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1360b1ed91f3SChris Lattner   for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1361b1ed91f3SChris Lattner        E = SrcM->named_metadata_end(); I != E; ++I) {
136266f02413SBill Wendling     // Don't link module flags here. Do them separately.
136366f02413SBill Wendling     if (&*I == SrcModFlags) continue;
1364b1ed91f3SChris Lattner     NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1365b1ed91f3SChris Lattner     // Add Src elements into Dest node.
1366b1ed91f3SChris Lattner     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1367b1ed91f3SChris Lattner       DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
1368f6f121e2SJames Molloy                                    RF_None, &TypeMap, &ValMaterializer));
1369b1ed91f3SChris Lattner   }
1370b1ed91f3SChris Lattner }
1371b1ed91f3SChris Lattner 
137266f02413SBill Wendling /// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
137366f02413SBill Wendling /// module.
137466f02413SBill Wendling bool ModuleLinker::linkModuleFlagsMetadata() {
13750ec72bbcSDaniel Dunbar   // If the source module has no module flags, we are done.
137666f02413SBill Wendling   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
137766f02413SBill Wendling   if (!SrcModFlags) return false;
137866f02413SBill Wendling 
137966f02413SBill Wendling   // If the destination module doesn't have module flags yet, then just copy
138066f02413SBill Wendling   // over the source module's flags.
13810ec72bbcSDaniel Dunbar   NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
138266f02413SBill Wendling   if (DstModFlags->getNumOperands() == 0) {
138366f02413SBill Wendling     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
138466f02413SBill Wendling       DstModFlags->addOperand(SrcModFlags->getOperand(I));
138566f02413SBill Wendling 
138666f02413SBill Wendling     return false;
138766f02413SBill Wendling   }
138866f02413SBill Wendling 
13890ec72bbcSDaniel Dunbar   // First build a map of the existing module flags and requirements.
13900ec72bbcSDaniel Dunbar   DenseMap<MDString*, MDNode*> Flags;
13910ec72bbcSDaniel Dunbar   SmallSetVector<MDNode*, 16> Requirements;
13920ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
13930ec72bbcSDaniel Dunbar     MDNode *Op = DstModFlags->getOperand(I);
13940ec72bbcSDaniel Dunbar     ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
13950ec72bbcSDaniel Dunbar     MDString *ID = cast<MDString>(Op->getOperand(1));
13960ec72bbcSDaniel Dunbar 
13970ec72bbcSDaniel Dunbar     if (Behavior->getZExtValue() == Module::Require) {
13980ec72bbcSDaniel Dunbar       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
13990ec72bbcSDaniel Dunbar     } else {
14000ec72bbcSDaniel Dunbar       Flags[ID] = Op;
14010ec72bbcSDaniel Dunbar     }
14020ec72bbcSDaniel Dunbar   }
14030ec72bbcSDaniel Dunbar 
14040ec72bbcSDaniel Dunbar   // Merge in the flags from the source module, and also collect its set of
14050ec72bbcSDaniel Dunbar   // requirements.
140666f02413SBill Wendling   bool HasErr = false;
14070ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
14080ec72bbcSDaniel Dunbar     MDNode *SrcOp = SrcModFlags->getOperand(I);
14090ec72bbcSDaniel Dunbar     ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
14100ec72bbcSDaniel Dunbar     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
14110ec72bbcSDaniel Dunbar     MDNode *DstOp = Flags.lookup(ID);
14120ec72bbcSDaniel Dunbar     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
141366f02413SBill Wendling 
14140ec72bbcSDaniel Dunbar     // If this is a requirement, add it and continue.
14150ec72bbcSDaniel Dunbar     if (SrcBehaviorValue == Module::Require) {
14160ec72bbcSDaniel Dunbar       // If the destination module does not already have this requirement, add
14170ec72bbcSDaniel Dunbar       // it.
14180ec72bbcSDaniel Dunbar       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
14190ec72bbcSDaniel Dunbar         DstModFlags->addOperand(SrcOp);
14200ec72bbcSDaniel Dunbar       }
14210ec72bbcSDaniel Dunbar       continue;
14220ec72bbcSDaniel Dunbar     }
142366f02413SBill Wendling 
14240ec72bbcSDaniel Dunbar     // If there is no existing flag with this ID, just add it.
14250ec72bbcSDaniel Dunbar     if (!DstOp) {
14260ec72bbcSDaniel Dunbar       Flags[ID] = SrcOp;
14270ec72bbcSDaniel Dunbar       DstModFlags->addOperand(SrcOp);
14280ec72bbcSDaniel Dunbar       continue;
14290ec72bbcSDaniel Dunbar     }
143066f02413SBill Wendling 
14310ec72bbcSDaniel Dunbar     // Otherwise, perform a merge.
14320ec72bbcSDaniel Dunbar     ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
14330ec72bbcSDaniel Dunbar     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
14340ec72bbcSDaniel Dunbar 
14350ec72bbcSDaniel Dunbar     // If either flag has override behavior, handle it first.
14360ec72bbcSDaniel Dunbar     if (DstBehaviorValue == Module::Override) {
14370ec72bbcSDaniel Dunbar       // Diagnose inconsistent flags which both have override behavior.
14380ec72bbcSDaniel Dunbar       if (SrcBehaviorValue == Module::Override &&
14390ec72bbcSDaniel Dunbar           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
14400ec72bbcSDaniel Dunbar         HasErr |= emitError("linking module flags '" + ID->getString() +
14410ec72bbcSDaniel Dunbar                             "': IDs have conflicting override values");
14420ec72bbcSDaniel Dunbar       }
14430ec72bbcSDaniel Dunbar       continue;
14440ec72bbcSDaniel Dunbar     } else if (SrcBehaviorValue == Module::Override) {
14450ec72bbcSDaniel Dunbar       // Update the destination flag to that of the source.
14460ec72bbcSDaniel Dunbar       DstOp->replaceOperandWith(0, SrcBehavior);
14470ec72bbcSDaniel Dunbar       DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
14480ec72bbcSDaniel Dunbar       continue;
14490ec72bbcSDaniel Dunbar     }
14500ec72bbcSDaniel Dunbar 
14510ec72bbcSDaniel Dunbar     // Diagnose inconsistent merge behavior types.
14520ec72bbcSDaniel Dunbar     if (SrcBehaviorValue != DstBehaviorValue) {
14530ec72bbcSDaniel Dunbar       HasErr |= emitError("linking module flags '" + ID->getString() +
145466f02413SBill Wendling                           "': IDs have conflicting behaviors");
14550ec72bbcSDaniel Dunbar       continue;
145666f02413SBill Wendling     }
145766f02413SBill Wendling 
14580ec72bbcSDaniel Dunbar     // Perform the merge for standard behavior types.
14590ec72bbcSDaniel Dunbar     switch (SrcBehaviorValue) {
14600ec72bbcSDaniel Dunbar     case Module::Require:
14612a30d788SCraig Topper     case Module::Override: llvm_unreachable("not possible");
14620ec72bbcSDaniel Dunbar     case Module::Error: {
14630ec72bbcSDaniel Dunbar       // Emit an error if the values differ.
14640ec72bbcSDaniel Dunbar       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
14650ec72bbcSDaniel Dunbar         HasErr |= emitError("linking module flags '" + ID->getString() +
14660ec72bbcSDaniel Dunbar                             "': IDs have conflicting values");
146766f02413SBill Wendling       }
14680ec72bbcSDaniel Dunbar       continue;
146966f02413SBill Wendling     }
14700ec72bbcSDaniel Dunbar     case Module::Warning: {
14710ec72bbcSDaniel Dunbar       // Emit a warning if the values differ.
14720ec72bbcSDaniel Dunbar       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1473e17f3708SEli Bendersky         if (!SuppressWarnings) {
14740ec72bbcSDaniel Dunbar           errs() << "WARNING: linking module flags '" << ID->getString()
14750ec72bbcSDaniel Dunbar                  << "': IDs have conflicting values";
14760ec72bbcSDaniel Dunbar         }
1477e17f3708SEli Bendersky       }
14780ec72bbcSDaniel Dunbar       continue;
14790ec72bbcSDaniel Dunbar     }
1480d77d9fb0SDaniel Dunbar     case Module::Append: {
1481d77d9fb0SDaniel Dunbar       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1482d77d9fb0SDaniel Dunbar       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1483d77d9fb0SDaniel Dunbar       unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1484d77d9fb0SDaniel Dunbar       Value **VP, **Values = VP = new Value*[NumOps];
1485d77d9fb0SDaniel Dunbar       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1486d77d9fb0SDaniel Dunbar         *VP = DstValue->getOperand(i);
1487d77d9fb0SDaniel Dunbar       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1488d77d9fb0SDaniel Dunbar         *VP = SrcValue->getOperand(i);
1489d77d9fb0SDaniel Dunbar       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1490d77d9fb0SDaniel Dunbar                                                ArrayRef<Value*>(Values,
1491d77d9fb0SDaniel Dunbar                                                                 NumOps)));
1492d77d9fb0SDaniel Dunbar       delete[] Values;
1493d77d9fb0SDaniel Dunbar       break;
1494d77d9fb0SDaniel Dunbar     }
1495d77d9fb0SDaniel Dunbar     case Module::AppendUnique: {
1496d77d9fb0SDaniel Dunbar       SmallSetVector<Value*, 16> Elts;
1497d77d9fb0SDaniel Dunbar       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1498d77d9fb0SDaniel Dunbar       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1499d77d9fb0SDaniel Dunbar       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1500d77d9fb0SDaniel Dunbar         Elts.insert(DstValue->getOperand(i));
1501d77d9fb0SDaniel Dunbar       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1502d77d9fb0SDaniel Dunbar         Elts.insert(SrcValue->getOperand(i));
1503d77d9fb0SDaniel Dunbar       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1504d77d9fb0SDaniel Dunbar                                                ArrayRef<Value*>(Elts.begin(),
1505d77d9fb0SDaniel Dunbar                                                                 Elts.end())));
1506d77d9fb0SDaniel Dunbar       break;
1507d77d9fb0SDaniel Dunbar     }
150866f02413SBill Wendling     }
150966f02413SBill Wendling   }
151066f02413SBill Wendling 
15110ec72bbcSDaniel Dunbar   // Check all of the requirements.
15120ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
15130ec72bbcSDaniel Dunbar     MDNode *Requirement = Requirements[I];
15140ec72bbcSDaniel Dunbar     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
15150ec72bbcSDaniel Dunbar     Value *ReqValue = Requirement->getOperand(1);
15160ec72bbcSDaniel Dunbar 
15170ec72bbcSDaniel Dunbar     MDNode *Op = Flags[Flag];
15180ec72bbcSDaniel Dunbar     if (!Op || Op->getOperand(2) != ReqValue) {
15190ec72bbcSDaniel Dunbar       HasErr |= emitError("linking module flags '" + Flag->getString() +
15209273b539SBill Wendling                           "': does not have the required value");
15210ec72bbcSDaniel Dunbar       continue;
152266f02413SBill Wendling     }
152366f02413SBill Wendling   }
152466f02413SBill Wendling 
152566f02413SBill Wendling   return HasErr;
152666f02413SBill Wendling }
152766f02413SBill Wendling 
1528b1ed91f3SChris Lattner bool ModuleLinker::run() {
152966f02413SBill Wendling   assert(DstM && "Null destination module");
153066f02413SBill Wendling   assert(SrcM && "Null source module");
1531b1ed91f3SChris Lattner 
1532b1ed91f3SChris Lattner   // Inherit the target data from the source module if the destination module
1533b1ed91f3SChris Lattner   // doesn't have one already.
1534f863ee29SRafael Espindola   if (!DstM->getDataLayout() && SrcM->getDataLayout())
1535b1ed91f3SChris Lattner     DstM->setDataLayout(SrcM->getDataLayout());
1536b1ed91f3SChris Lattner 
1537b1ed91f3SChris Lattner   // Copy the target triple from the source to dest if the dest's is empty.
1538b1ed91f3SChris Lattner   if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1539b1ed91f3SChris Lattner     DstM->setTargetTriple(SrcM->getTargetTriple());
1540b1ed91f3SChris Lattner 
1541f863ee29SRafael Espindola   if (SrcM->getDataLayout() && DstM->getDataLayout() &&
1542ae593f15SRafael Espindola       *SrcM->getDataLayout() != *DstM->getDataLayout()) {
1543e17f3708SEli Bendersky     if (!SuppressWarnings) {
1544026fc5f6SJF Bastien       errs() << "WARNING: Linking two modules of different data layouts: '"
1545026fc5f6SJF Bastien              << SrcM->getModuleIdentifier() << "' is '"
1546026fc5f6SJF Bastien              << SrcM->getDataLayoutStr() << "' whereas '"
1547026fc5f6SJF Bastien              << DstM->getModuleIdentifier() << "' is '"
1548026fc5f6SJF Bastien              << DstM->getDataLayoutStr() << "'\n";
1549e17f3708SEli Bendersky     }
1550e17f3708SEli Bendersky   }
1551b1ed91f3SChris Lattner   if (!SrcM->getTargetTriple().empty() &&
1552b1ed91f3SChris Lattner       DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1553e17f3708SEli Bendersky     if (!SuppressWarnings) {
1554026fc5f6SJF Bastien       errs() << "WARNING: Linking two modules of different target triples: "
1555026fc5f6SJF Bastien              << SrcM->getModuleIdentifier() << "' is '"
1556026fc5f6SJF Bastien              << SrcM->getTargetTriple() << "' whereas '"
1557026fc5f6SJF Bastien              << DstM->getModuleIdentifier() << "' is '"
1558b1ed91f3SChris Lattner              << DstM->getTargetTriple() << "'\n";
1559b1ed91f3SChris Lattner     }
1560e17f3708SEli Bendersky   }
1561b1ed91f3SChris Lattner 
1562b1ed91f3SChris Lattner   // Append the module inline asm string.
1563b1ed91f3SChris Lattner   if (!SrcM->getModuleInlineAsm().empty()) {
1564b1ed91f3SChris Lattner     if (DstM->getModuleInlineAsm().empty())
1565b1ed91f3SChris Lattner       DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1566b1ed91f3SChris Lattner     else
1567b1ed91f3SChris Lattner       DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1568b1ed91f3SChris Lattner                                SrcM->getModuleInlineAsm());
1569b1ed91f3SChris Lattner   }
1570b1ed91f3SChris Lattner 
1571b1ed91f3SChris Lattner   // Loop over all of the linked values to compute type mappings.
1572b1ed91f3SChris Lattner   computeTypeMapping();
1573b1ed91f3SChris Lattner 
1574dad0a645SDavid Majnemer   ComdatsChosen.clear();
1575dad0a645SDavid Majnemer   for (const StringMapEntry<llvm::Comdat> &SMEC : SrcM->getComdatSymbolTable()) {
1576dad0a645SDavid Majnemer     const Comdat &C = SMEC.getValue();
1577dad0a645SDavid Majnemer     if (ComdatsChosen.count(&C))
1578dad0a645SDavid Majnemer       continue;
1579dad0a645SDavid Majnemer     Comdat::SelectionKind SK;
1580dad0a645SDavid Majnemer     bool LinkFromSrc;
1581dad0a645SDavid Majnemer     if (getComdatResult(&C, SK, LinkFromSrc))
1582dad0a645SDavid Majnemer       return true;
1583dad0a645SDavid Majnemer     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1584dad0a645SDavid Majnemer   }
1585dad0a645SDavid Majnemer 
158609d84addSDuncan P. N. Exon Smith   // Upgrade mismatched global arrays.
158709d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobals();
158809d84addSDuncan P. N. Exon Smith 
1589b1ed91f3SChris Lattner   // Insert all of the globals in src into the DstM module... without linking
1590b1ed91f3SChris Lattner   // initializers (which could refer to functions not yet mapped over).
1591b1ed91f3SChris Lattner   for (Module::global_iterator I = SrcM->global_begin(),
1592b1ed91f3SChris Lattner        E = SrcM->global_end(); I != E; ++I)
1593b1ed91f3SChris Lattner     if (linkGlobalProto(I))
1594b1ed91f3SChris Lattner       return true;
1595b1ed91f3SChris Lattner 
1596b1ed91f3SChris Lattner   // Link the functions together between the two modules, without doing function
1597b1ed91f3SChris Lattner   // bodies... this just adds external function prototypes to the DstM
1598b1ed91f3SChris Lattner   // function...  We do this so that when we begin processing function bodies,
1599b1ed91f3SChris Lattner   // all of the global values that may be referenced are available in our
1600b1ed91f3SChris Lattner   // ValueMap.
1601b1ed91f3SChris Lattner   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1602b1ed91f3SChris Lattner     if (linkFunctionProto(I))
1603b1ed91f3SChris Lattner       return true;
1604b1ed91f3SChris Lattner 
1605b1ed91f3SChris Lattner   // If there were any aliases, link them now.
1606b1ed91f3SChris Lattner   for (Module::alias_iterator I = SrcM->alias_begin(),
1607b1ed91f3SChris Lattner        E = SrcM->alias_end(); I != E; ++I)
1608b1ed91f3SChris Lattner     if (linkAliasProto(I))
1609b1ed91f3SChris Lattner       return true;
1610b1ed91f3SChris Lattner 
1611b1ed91f3SChris Lattner   for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1612b1ed91f3SChris Lattner     linkAppendingVarInit(AppendingVars[i]);
1613b1ed91f3SChris Lattner 
1614b1ed91f3SChris Lattner   // Link in the function bodies that are defined in the source module into
1615b1ed91f3SChris Lattner   // DstM.
1616b1ed91f3SChris Lattner   for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1617ea166d44STanya Lattner     // Skip if not linking from source.
1618ea166d44STanya Lattner     if (DoNotLinkFromSource.count(SF)) continue;
1619ea166d44STanya Lattner 
16203fa50f9bSPeter Collingbourne     Function *DF = cast<Function>(ValueMap[SF]);
16213fa50f9bSPeter Collingbourne     if (SF->hasPrefixData()) {
16223fa50f9bSPeter Collingbourne       // Link in the prefix data.
16233fa50f9bSPeter Collingbourne       DF->setPrefixData(MapValue(
16243fa50f9bSPeter Collingbourne           SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
16253fa50f9bSPeter Collingbourne     }
16263fa50f9bSPeter Collingbourne 
1627*d4bcefc7SRafael Espindola     // Materialize if needed.
1628*d4bcefc7SRafael Espindola     if (SF->isMaterializable()) {
1629ea166d44STanya Lattner       if (SF->Materialize(&ErrorMsg))
1630ea166d44STanya Lattner         return true;
1631ea166d44STanya Lattner     }
1632b1ed91f3SChris Lattner 
1633*d4bcefc7SRafael Espindola     // Skip if no body (function is external).
1634*d4bcefc7SRafael Espindola     if (SF->isDeclaration())
1635*d4bcefc7SRafael Espindola       continue;
1636*d4bcefc7SRafael Espindola 
16373fa50f9bSPeter Collingbourne     linkFunctionBody(DF, SF);
163800623787SBill Wendling     SF->Dematerialize();
1639b1ed91f3SChris Lattner   }
1640b1ed91f3SChris Lattner 
1641b1ed91f3SChris Lattner   // Resolve all uses of aliases with aliasees.
1642b1ed91f3SChris Lattner   linkAliasBodies();
1643b1ed91f3SChris Lattner 
164466f02413SBill Wendling   // Remap all of the named MDNodes in Src into the DstM module. We do this
16456ddbb2e2SDevang Patel   // after linking GlobalValues so that MDNodes that reference GlobalValues
16466ddbb2e2SDevang Patel   // are properly remapped.
16476ddbb2e2SDevang Patel   linkNamedMDNodes();
16486ddbb2e2SDevang Patel 
164966f02413SBill Wendling   // Merge the module flags into the DstM module.
165066f02413SBill Wendling   if (linkModuleFlagsMetadata())
165166f02413SBill Wendling     return true;
165266f02413SBill Wendling 
165391686d6dSBill Wendling   // Update the initializers in the DstM module now that all globals that may
165491686d6dSBill Wendling   // be referenced are in DstM.
165591686d6dSBill Wendling   linkGlobalInits();
165691686d6dSBill Wendling 
16570a48b877STanya Lattner   // Process vector of lazily linked in functions.
16580a48b877STanya Lattner   bool LinkedInAnyFunctions;
16590a48b877STanya Lattner   do {
16600a48b877STanya Lattner     LinkedInAnyFunctions = false;
16610a48b877STanya Lattner 
1662fa228782SBill Wendling     for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
16630a48b877STanya Lattner         E = LazilyLinkFunctions.end(); I != E; ++I) {
1664f6f121e2SJames Molloy       Function *SF = *I;
1665f6f121e2SJames Molloy       if (!SF)
16660a48b877STanya Lattner         continue;
16670a48b877STanya Lattner 
1668fa228782SBill Wendling       Function *DF = cast<Function>(ValueMap[SF]);
16693fa50f9bSPeter Collingbourne       if (SF->hasPrefixData()) {
16703fa50f9bSPeter Collingbourne         // Link in the prefix data.
16713fa50f9bSPeter Collingbourne         DF->setPrefixData(MapValue(SF->getPrefixData(),
16723fa50f9bSPeter Collingbourne                                    ValueMap,
16733fa50f9bSPeter Collingbourne                                    RF_None,
16743fa50f9bSPeter Collingbourne                                    &TypeMap,
16753fa50f9bSPeter Collingbourne                                    &ValMaterializer));
16763fa50f9bSPeter Collingbourne       }
16770a48b877STanya Lattner 
1678*d4bcefc7SRafael Espindola       // Materialize if needed.
1679*d4bcefc7SRafael Espindola       if (SF->isMaterializable()) {
16800a48b877STanya Lattner         if (SF->Materialize(&ErrorMsg))
16810a48b877STanya Lattner           return true;
16820a48b877STanya Lattner       }
16830a48b877STanya Lattner 
1684*d4bcefc7SRafael Espindola       // Skip if no body (function is external).
1685*d4bcefc7SRafael Espindola       if (SF->isDeclaration())
1686*d4bcefc7SRafael Espindola         continue;
1687*d4bcefc7SRafael Espindola 
1688f6f121e2SJames Molloy       // Erase from vector *before* the function body is linked - linkFunctionBody could
1689f6f121e2SJames Molloy       // invalidate I.
1690f6f121e2SJames Molloy       LazilyLinkFunctions.erase(I);
1691f6f121e2SJames Molloy 
16920a48b877STanya Lattner       // Link in function body.
16930a48b877STanya Lattner       linkFunctionBody(DF, SF);
169400623787SBill Wendling       SF->Dematerialize();
16950a48b877STanya Lattner 
16960a48b877STanya Lattner       // Set flag to indicate we may have more functions to lazily link in
16970a48b877STanya Lattner       // since we linked in a function.
16980a48b877STanya Lattner       LinkedInAnyFunctions = true;
1699f6f121e2SJames Molloy       break;
17000a48b877STanya Lattner     }
17010a48b877STanya Lattner   } while (LinkedInAnyFunctions);
17020a48b877STanya Lattner 
1703b1ed91f3SChris Lattner   // Now that all of the types from the source are used, resolve any structs
1704b1ed91f3SChris Lattner   // copied over to the dest that didn't exist there.
1705b1ed91f3SChris Lattner   TypeMap.linkDefinedTypeBodies();
17062609888fSAnton Korobeynikov 
17072609888fSAnton Korobeynikov   return false;
17082609888fSAnton Korobeynikov }
1709361e513dSReid Spencer 
17107da92ed8SEli Bendersky Linker::Linker(Module *M, bool SuppressWarnings)
17117da92ed8SEli Bendersky     : Composite(M), SuppressWarnings(SuppressWarnings) {
1712aa9918aaSRafael Espindola   TypeFinder StructTypes;
1713aa9918aaSRafael Espindola   StructTypes.run(*M, true);
1714aa9918aaSRafael Espindola   IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1715aa9918aaSRafael Espindola }
17163df61b7bSRafael Espindola 
17173df61b7bSRafael Espindola Linker::~Linker() {
17183df61b7bSRafael Espindola }
17193df61b7bSRafael Espindola 
172091e6f6e1SBill Wendling void Linker::deleteModule() {
172191e6f6e1SBill Wendling   delete Composite;
17222617dcceSCraig Topper   Composite = nullptr;
172391e6f6e1SBill Wendling }
172491e6f6e1SBill Wendling 
17253df61b7bSRafael Espindola bool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) {
17267da92ed8SEli Bendersky   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode,
17277da92ed8SEli Bendersky                          SuppressWarnings);
1728287f18b4SRafael Espindola   if (TheLinker.run()) {
1729287f18b4SRafael Espindola     if (ErrorMsg)
1730287f18b4SRafael Espindola       *ErrorMsg = TheLinker.ErrorMsg;
1731287f18b4SRafael Espindola     return true;
1732287f18b4SRafael Espindola   }
1733287f18b4SRafael Espindola   return false;
17343df61b7bSRafael Espindola }
17353df61b7bSRafael Espindola 
1736b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
1737b1ed91f3SChris Lattner // LinkModules entrypoint.
1738b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
1739b1ed91f3SChris Lattner 
1740b6af2f36SBill Wendling /// LinkModules - This function links two modules together, with the resulting
1741970cc634SEli Bendersky /// Dest module modified to be the composite of the two input modules.  If an
1742b6af2f36SBill Wendling /// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1743b6af2f36SBill Wendling /// the problem.  Upon failure, the Dest module could be in a modified state,
1744b6af2f36SBill Wendling /// and shouldn't be relied on to be consistent.
1745cbb91408STanya Lattner bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1746cbb91408STanya Lattner                          std::string *ErrorMsg) {
1747287f18b4SRafael Espindola   Linker L(Dest);
1748287f18b4SRafael Espindola   return L.linkInModule(Src, Mode, ErrorMsg);
1749361e513dSReid Spencer }
1750a3aeb980SBill Wendling 
1751a3aeb980SBill Wendling //===----------------------------------------------------------------------===//
1752a3aeb980SBill Wendling // C API.
1753a3aeb980SBill Wendling //===----------------------------------------------------------------------===//
1754a3aeb980SBill Wendling 
1755a3aeb980SBill Wendling LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1756a3aeb980SBill Wendling                          LLVMLinkerMode Mode, char **OutMessages) {
1757a3aeb980SBill Wendling   std::string Messages;
1758a3aeb980SBill Wendling   LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
17592617dcceSCraig Topper                                         Mode, OutMessages? &Messages : nullptr);
1760a3aeb980SBill Wendling   if (OutMessages)
1761a3aeb980SBill Wendling     *OutMessages = strdup(Messages.c_str());
1762a3aeb980SBill Wendling   return Result;
1763a3aeb980SBill Wendling }
1764