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"
16*31ad468dSRafael Espindola #include "llvm/ADT/Hashing.h"
1723f8d64bSRafael Espindola #include "llvm/ADT/Optional.h"
1866f02413SBill Wendling #include "llvm/ADT/SetVector.h"
190f7fd36fSEli Bendersky #include "llvm/ADT/SmallString.h"
20*31ad468dSRafael Espindola #include "llvm/ADT/Statistic.h"
219fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
22d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticInfo.h"
23d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticPrinter.h"
24d12b4a33SRafael Espindola #include "llvm/IR/LLVMContext.h"
259fb823bbSChandler Carruth #include "llvm/IR/Module.h"
26dcb603feSChandler Carruth #include "llvm/IR/TypeFinder.h"
27e17f3708SEli Bendersky #include "llvm/Support/CommandLine.h"
28b6af2f36SBill Wendling #include "llvm/Support/Debug.h"
29b6af2f36SBill Wendling #include "llvm/Support/raw_ostream.h"
30cbb91408STanya Lattner #include "llvm/Transforms/Utils/Cloning.h"
31981af002SWill Dietz #include <cctype>
3282d6ff6bSDavid Majnemer #include <tuple>
33361e513dSReid Spencer using namespace llvm;
34361e513dSReid Spencer 
35e17f3708SEli Bendersky 
36b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
37b1ed91f3SChris Lattner // TypeMap implementation.
38b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
39b1ed91f3SChris Lattner 
40b1ed91f3SChris Lattner namespace {
41b1ed91f3SChris Lattner class TypeMapTy : public ValueMapTypeRemapper {
4218c89411SRafael Espindola   /// This is a mapping from a source type to a destination type to use.
43b1ed91f3SChris Lattner   DenseMap<Type*, Type*> MappedTypes;
44b1ed91f3SChris Lattner 
4518c89411SRafael Espindola   /// When checking to see if two subgraphs are isomorphic, we speculatively
4618c89411SRafael Espindola   /// add types to MappedTypes, but keep track of them here in case we need to
4718c89411SRafael Espindola   /// roll back.
48b1ed91f3SChris Lattner   SmallVector<Type*, 16> SpeculativeTypes;
49b1ed91f3SChris Lattner 
50a96f235cSRafael Espindola   SmallVector<StructType*, 16> SpeculativeDstOpaqueTypes;
51a96f235cSRafael Espindola 
5218c89411SRafael Espindola   /// This is a list of non-opaque structs in the source module that are mapped
5318c89411SRafael Espindola   /// to an opaque struct in the destination module.
545e3bd972SChris Lattner   SmallVector<StructType*, 16> SrcDefinitionsToResolve;
555e3bd972SChris Lattner 
5618c89411SRafael Espindola   /// This is the set of opaque types in the destination modules who are
5718c89411SRafael Espindola   /// getting a body from the source module.
585e3bd972SChris Lattner   SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
59d48b7783SBill Wendling 
608c2cc416SBill Wendling public:
61*31ad468dSRafael Espindola   TypeMapTy(Linker::IdentifiedStructTypeSet &DstStructTypesSet)
62*31ad468dSRafael Espindola       : DstStructTypesSet(DstStructTypesSet) {}
63aa9918aaSRafael Espindola 
64*31ad468dSRafael Espindola   Linker::IdentifiedStructTypeSet &DstStructTypesSet;
6518c89411SRafael Espindola   /// Indicate that the specified type in the destination module is conceptually
6618c89411SRafael Espindola   /// equivalent to the specified type in the source module.
67b1ed91f3SChris Lattner   void addTypeMapping(Type *DstTy, Type *SrcTy);
68b1ed91f3SChris Lattner 
69d2a13a2eSRafael Espindola   /// Produce a body for an opaque type in the dest module from a type
70d2a13a2eSRafael Espindola   /// definition in the source module.
71b1ed91f3SChris Lattner   void linkDefinedTypeBodies();
72b1ed91f3SChris Lattner 
7318c89411SRafael Espindola   /// Return the mapped type to use for the specified input type from the
74b1ed91f3SChris Lattner   /// source module.
75b1ed91f3SChris Lattner   Type *get(Type *SrcTy);
76*31ad468dSRafael Espindola   Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
77*31ad468dSRafael Espindola 
78*31ad468dSRafael Espindola   void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
79b1ed91f3SChris Lattner 
80290e2cc5SRafael Espindola   FunctionType *get(FunctionType *T) {
81290e2cc5SRafael Espindola     return cast<FunctionType>(get((Type *)T));
82290e2cc5SRafael Espindola   }
83b1ed91f3SChris Lattner 
8418c89411SRafael Espindola   /// Dump out the type map for debugging purposes.
85b6af2f36SBill Wendling   void dump() const {
868f14471eSRafael Espindola     for (auto &Pair : MappedTypes) {
87b6af2f36SBill Wendling       dbgs() << "TypeMap: ";
888f14471eSRafael Espindola       Pair.first->print(dbgs());
89b6af2f36SBill Wendling       dbgs() << " => ";
908f14471eSRafael Espindola       Pair.second->print(dbgs());
91b6af2f36SBill Wendling       dbgs() << '\n';
92b6af2f36SBill Wendling     }
93b6af2f36SBill Wendling   }
94b6af2f36SBill Wendling 
95b1ed91f3SChris Lattner private:
96290e2cc5SRafael Espindola   Type *remapType(Type *SrcTy) override { return get(SrcTy); }
97b1ed91f3SChris Lattner 
98b1ed91f3SChris Lattner   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
99b1ed91f3SChris Lattner };
100b1ed91f3SChris Lattner }
101b1ed91f3SChris Lattner 
102b1ed91f3SChris Lattner void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
1033d097410SRafael Espindola   assert(SpeculativeTypes.empty());
104a96f235cSRafael Espindola   assert(SpeculativeDstOpaqueTypes.empty());
1053d097410SRafael Espindola 
106b1ed91f3SChris Lattner   // Check to see if these types are recursively isomorphic and establish a
107b1ed91f3SChris Lattner   // mapping between them if so.
108c586eaa1SDuncan P. N. Exon Smith   if (!areTypesIsomorphic(DstTy, SrcTy)) {
109b1ed91f3SChris Lattner     // Oops, they aren't isomorphic.  Just discard this request by rolling out
110b1ed91f3SChris Lattner     // any speculative mappings we've established.
1113d097410SRafael Espindola     for (Type *Ty : SpeculativeTypes)
1123d097410SRafael Espindola       MappedTypes.erase(Ty);
113a96f235cSRafael Espindola 
114a96f235cSRafael Espindola     SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
115a96f235cSRafael Espindola                                    SpeculativeDstOpaqueTypes.size());
116a96f235cSRafael Espindola     for (StructType *Ty : SpeculativeDstOpaqueTypes)
117a96f235cSRafael Espindola       DstResolvedOpaqueTypes.erase(Ty);
11804a74af7SRafael Espindola   } else {
11904a74af7SRafael Espindola     for (Type *Ty : SpeculativeTypes)
12004a74af7SRafael Espindola       if (auto *STy = dyn_cast<StructType>(Ty))
12104a74af7SRafael Espindola         if (STy->hasName())
12204a74af7SRafael Espindola           STy->setName("");
123d48b7783SBill Wendling   }
124b1ed91f3SChris Lattner   SpeculativeTypes.clear();
125a96f235cSRafael Espindola   SpeculativeDstOpaqueTypes.clear();
126b1ed91f3SChris Lattner }
127b1ed91f3SChris Lattner 
12818c89411SRafael Espindola /// Recursively walk this pair of types, returning true if they are isomorphic,
12918c89411SRafael Espindola /// false if they are not.
130b1ed91f3SChris Lattner bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
131b1ed91f3SChris Lattner   // Two types with differing kinds are clearly not isomorphic.
132290e2cc5SRafael Espindola   if (DstTy->getTypeID() != SrcTy->getTypeID())
133290e2cc5SRafael Espindola     return false;
134b1ed91f3SChris Lattner 
135b1ed91f3SChris Lattner   // If we have an entry in the MappedTypes table, then we have our answer.
136b1ed91f3SChris Lattner   Type *&Entry = MappedTypes[SrcTy];
137b1ed91f3SChris Lattner   if (Entry)
138b1ed91f3SChris Lattner     return Entry == DstTy;
139b1ed91f3SChris Lattner 
140b1ed91f3SChris Lattner   // Two identical types are clearly isomorphic.  Remember this
141b1ed91f3SChris Lattner   // non-speculatively.
142b1ed91f3SChris Lattner   if (DstTy == SrcTy) {
143b1ed91f3SChris Lattner     Entry = DstTy;
144361e513dSReid Spencer     return true;
145361e513dSReid Spencer   }
146361e513dSReid Spencer 
147b1ed91f3SChris Lattner   // Okay, we have two types with identical kinds that we haven't seen before.
148361e513dSReid Spencer 
149b1ed91f3SChris Lattner   // If this is an opaque struct type, special case it.
150b1ed91f3SChris Lattner   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
151b1ed91f3SChris Lattner     // Mapping an opaque type to any struct, just keep the dest struct.
152b1ed91f3SChris Lattner     if (SSTy->isOpaque()) {
153b1ed91f3SChris Lattner       Entry = DstTy;
154b1ed91f3SChris Lattner       SpeculativeTypes.push_back(SrcTy);
155b1ed91f3SChris Lattner       return true;
156361e513dSReid Spencer     }
157b1ed91f3SChris Lattner 
1585e3bd972SChris Lattner     // Mapping a non-opaque source type to an opaque dest.  If this is the first
1595e3bd972SChris Lattner     // type that we're mapping onto this destination type then we succeed.  Keep
160a96f235cSRafael Espindola     // the dest, but fill it in later. If this is the second (different) type
161a96f235cSRafael Espindola     // that we're trying to map onto the same opaque type then we fail.
162b1ed91f3SChris Lattner     if (cast<StructType>(DstTy)->isOpaque()) {
1635e3bd972SChris Lattner       // We can only map one source type onto the opaque destination type.
16470573dcdSDavid Blaikie       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
1655e3bd972SChris Lattner         return false;
1665e3bd972SChris Lattner       SrcDefinitionsToResolve.push_back(SSTy);
167a96f235cSRafael Espindola       SpeculativeTypes.push_back(SrcTy);
168a96f235cSRafael Espindola       SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
169b1ed91f3SChris Lattner       Entry = DstTy;
170b1ed91f3SChris Lattner       return true;
171b1ed91f3SChris Lattner     }
172b1ed91f3SChris Lattner   }
173b1ed91f3SChris Lattner 
174b1ed91f3SChris Lattner   // If the number of subtypes disagree between the two types, then we fail.
175b1ed91f3SChris Lattner   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
176b1ed91f3SChris Lattner     return false;
177b1ed91f3SChris Lattner 
178b1ed91f3SChris Lattner   // Fail if any of the extra properties (e.g. array size) of the type disagree.
179b1ed91f3SChris Lattner   if (isa<IntegerType>(DstTy))
180b1ed91f3SChris Lattner     return false;  // bitwidth disagrees.
181b1ed91f3SChris Lattner   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
182b1ed91f3SChris Lattner     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
183b1ed91f3SChris Lattner       return false;
184eaf9b762SChris Lattner 
185b1ed91f3SChris Lattner   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
186b1ed91f3SChris Lattner     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
187b1ed91f3SChris Lattner       return false;
188b1ed91f3SChris Lattner   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
189b1ed91f3SChris Lattner     StructType *SSTy = cast<StructType>(SrcTy);
19044f7ab45SChris Lattner     if (DSTy->isLiteral() != SSTy->isLiteral() ||
191b1ed91f3SChris Lattner         DSTy->isPacked() != SSTy->isPacked())
192b1ed91f3SChris Lattner       return false;
193b1ed91f3SChris Lattner   } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
194b1ed91f3SChris Lattner     if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
195b1ed91f3SChris Lattner       return false;
196b1ed91f3SChris Lattner   } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
1975fad3e9aSJoey Gouly     if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
198361e513dSReid Spencer       return false;
199361e513dSReid Spencer   }
200361e513dSReid Spencer 
201b1ed91f3SChris Lattner   // Otherwise, we speculate that these two types will line up and recursively
202b1ed91f3SChris Lattner   // check the subelements.
203b1ed91f3SChris Lattner   Entry = DstTy;
204b1ed91f3SChris Lattner   SpeculativeTypes.push_back(SrcTy);
205eee6f995SChris Lattner 
206290e2cc5SRafael Espindola   for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
207290e2cc5SRafael Espindola     if (!areTypesIsomorphic(DstTy->getContainedType(I),
208290e2cc5SRafael Espindola                             SrcTy->getContainedType(I)))
209b1ed91f3SChris Lattner       return false;
210eee6f995SChris Lattner 
211b1ed91f3SChris Lattner   // If everything seems to have lined up, then everything is great.
212eee6f995SChris Lattner   return true;
213eee6f995SChris Lattner }
214eee6f995SChris Lattner 
215b1ed91f3SChris Lattner void TypeMapTy::linkDefinedTypeBodies() {
216b1ed91f3SChris Lattner   SmallVector<Type*, 16> Elements;
217c81c3f55SRafael Espindola   for (StructType *SrcSTy : SrcDefinitionsToResolve) {
218b1ed91f3SChris Lattner     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
219c81c3f55SRafael Espindola     assert(DstSTy->isOpaque());
220b1ed91f3SChris Lattner 
221b1ed91f3SChris Lattner     // Map the body of the source type over to a new body for the dest type.
222b1ed91f3SChris Lattner     Elements.resize(SrcSTy->getNumElements());
223290e2cc5SRafael Espindola     for (unsigned I = 0, E = Elements.size(); I != E; ++I)
224c81c3f55SRafael Espindola       Elements[I] = get(SrcSTy->getElementType(I));
225b1ed91f3SChris Lattner 
226b1ed91f3SChris Lattner     DstSTy->setBody(Elements, SrcSTy->isPacked());
227b1ed91f3SChris Lattner   }
228c81c3f55SRafael Espindola   SrcDefinitionsToResolve.clear();
2295e3bd972SChris Lattner   DstResolvedOpaqueTypes.clear();
230eee6f995SChris Lattner }
231eee6f995SChris Lattner 
232*31ad468dSRafael Espindola void TypeMapTy::finishType(StructType *DTy, StructType *STy,
233*31ad468dSRafael Espindola                            ArrayRef<Type *> ETypes) {
234*31ad468dSRafael Espindola   DTy->setBody(ETypes, STy->isPacked());
235a4e85e3dSRafael Espindola 
236*31ad468dSRafael Espindola   // Steal STy's name.
237*31ad468dSRafael Espindola   if (STy->hasName()) {
238*31ad468dSRafael Espindola     SmallString<16> TmpName = STy->getName();
239*31ad468dSRafael Espindola     STy->setName("");
240*31ad468dSRafael Espindola     DTy->setName(TmpName);
241*31ad468dSRafael Espindola   }
242*31ad468dSRafael Espindola 
243*31ad468dSRafael Espindola   DstStructTypesSet.addNonOpaque(DTy);
244*31ad468dSRafael Espindola }
245*31ad468dSRafael Espindola 
246*31ad468dSRafael Espindola Type *TypeMapTy::get(Type *Ty) {
247*31ad468dSRafael Espindola   SmallPtrSet<StructType *, 8> Visited;
248*31ad468dSRafael Espindola   return get(Ty, Visited);
249*31ad468dSRafael Espindola }
250*31ad468dSRafael Espindola 
251*31ad468dSRafael Espindola Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
252b1ed91f3SChris Lattner   // If we already have an entry for this type, return it.
253b1ed91f3SChris Lattner   Type **Entry = &MappedTypes[Ty];
254290e2cc5SRafael Espindola   if (*Entry)
255290e2cc5SRafael Espindola     return *Entry;
256b1ed91f3SChris Lattner 
257*31ad468dSRafael Espindola   // These are types that LLVM itself will unique.
258*31ad468dSRafael Espindola   bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
259*31ad468dSRafael Espindola 
260*31ad468dSRafael Espindola #ifndef NDEBUG
261*31ad468dSRafael Espindola   if (!IsUniqued) {
262*31ad468dSRafael Espindola     for (auto &Pair : MappedTypes) {
263*31ad468dSRafael Espindola       assert(!(Pair.first != Ty && Pair.second == Ty) &&
264*31ad468dSRafael Espindola              "mapping to a source type");
265*31ad468dSRafael Espindola     }
266*31ad468dSRafael Espindola   }
267*31ad468dSRafael Espindola #endif
268*31ad468dSRafael Espindola 
269*31ad468dSRafael Espindola   if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
270*31ad468dSRafael Espindola     StructType *DTy = StructType::create(Ty->getContext());
271*31ad468dSRafael Espindola     return *Entry = DTy;
272*31ad468dSRafael Espindola   }
273*31ad468dSRafael Espindola 
274*31ad468dSRafael Espindola   // If this is not a recursive type, then just map all of the elements and
275b1ed91f3SChris Lattner   // then rebuild the type from inside out.
276*31ad468dSRafael Espindola   SmallVector<Type *, 4> ElementTypes;
277*31ad468dSRafael Espindola 
278b1ed91f3SChris Lattner   // If there are no element types to map, then the type is itself.  This is
279b1ed91f3SChris Lattner   // true for the anonymous {} struct, things like 'float', integers, etc.
280*31ad468dSRafael Espindola   if (Ty->getNumContainedTypes() == 0 && IsUniqued)
281b1ed91f3SChris Lattner     return *Entry = Ty;
282b1ed91f3SChris Lattner 
283b1ed91f3SChris Lattner   // Remap all of the elements, keeping track of whether any of them change.
284b1ed91f3SChris Lattner   bool AnyChange = false;
285b1ed91f3SChris Lattner   ElementTypes.resize(Ty->getNumContainedTypes());
286290e2cc5SRafael Espindola   for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
287*31ad468dSRafael Espindola     ElementTypes[I] = get(Ty->getContainedType(I), Visited);
288290e2cc5SRafael Espindola     AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
289eee6f995SChris Lattner   }
290b1ed91f3SChris Lattner 
291b1ed91f3SChris Lattner   // If we found our type while recursively processing stuff, just use it.
292b1ed91f3SChris Lattner   Entry = &MappedTypes[Ty];
293*31ad468dSRafael Espindola   if (*Entry) {
294*31ad468dSRafael Espindola     if (auto *DTy = dyn_cast<StructType>(*Entry)) {
295*31ad468dSRafael Espindola       if (DTy->isOpaque()) {
296*31ad468dSRafael Espindola         auto *STy = cast<StructType>(Ty);
297*31ad468dSRafael Espindola         finishType(DTy, STy, ElementTypes);
298*31ad468dSRafael Espindola       }
299*31ad468dSRafael Espindola     }
300290e2cc5SRafael Espindola     return *Entry;
301*31ad468dSRafael Espindola   }
302b1ed91f3SChris Lattner 
303*31ad468dSRafael Espindola   // If all of the element types mapped directly over and the type is not
304*31ad468dSRafael Espindola   // a nomed struct, then the type is usable as-is.
305*31ad468dSRafael Espindola   if (!AnyChange && IsUniqued)
306b1ed91f3SChris Lattner     return *Entry = Ty;
307b1ed91f3SChris Lattner 
308b1ed91f3SChris Lattner   // Otherwise, rebuild a modified type.
309b1ed91f3SChris Lattner   switch (Ty->getTypeID()) {
310290e2cc5SRafael Espindola   default:
311290e2cc5SRafael Espindola     llvm_unreachable("unknown derived type to remap");
312b1ed91f3SChris Lattner   case Type::ArrayTyID:
313b1ed91f3SChris Lattner     return *Entry = ArrayType::get(ElementTypes[0],
314b1ed91f3SChris Lattner                                    cast<ArrayType>(Ty)->getNumElements());
315b1ed91f3SChris Lattner   case Type::VectorTyID:
316b1ed91f3SChris Lattner     return *Entry = VectorType::get(ElementTypes[0],
317b1ed91f3SChris Lattner                                     cast<VectorType>(Ty)->getNumElements());
318b1ed91f3SChris Lattner   case Type::PointerTyID:
319*31ad468dSRafael Espindola     return *Entry = PointerType::get(ElementTypes[0],
320*31ad468dSRafael Espindola                                      cast<PointerType>(Ty)->getAddressSpace());
321b1ed91f3SChris Lattner   case Type::FunctionTyID:
322b1ed91f3SChris Lattner     return *Entry = FunctionType::get(ElementTypes[0],
323717d7eddSFrits van Bommel                                       makeArrayRef(ElementTypes).slice(1),
324b1ed91f3SChris Lattner                                       cast<FunctionType>(Ty)->isVarArg());
325*31ad468dSRafael Espindola   case Type::StructTyID: {
326*31ad468dSRafael Espindola     auto *STy = cast<StructType>(Ty);
327*31ad468dSRafael Espindola     bool IsPacked = STy->isPacked();
328*31ad468dSRafael Espindola     if (IsUniqued)
329*31ad468dSRafael Espindola       return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
330b1ed91f3SChris Lattner 
331b1ed91f3SChris Lattner     // If the type is opaque, we can just use it directly.
332aa9918aaSRafael Espindola     if (STy->isOpaque()) {
333*31ad468dSRafael Espindola       DstStructTypesSet.addOpaque(STy);
334*31ad468dSRafael Espindola       return *Entry = Ty;
335aa9918aaSRafael Espindola     }
336b1ed91f3SChris Lattner 
337*31ad468dSRafael Espindola     if (StructType *OldT =
338*31ad468dSRafael Espindola             DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
339c81c3f55SRafael Espindola       STy->setName("");
340*31ad468dSRafael Espindola       return *Entry = OldT;
341c81c3f55SRafael Espindola     }
342c81c3f55SRafael Espindola 
343*31ad468dSRafael Espindola     if (!AnyChange) {
344*31ad468dSRafael Espindola       DstStructTypesSet.addNonOpaque(STy);
345*31ad468dSRafael Espindola       return *Entry = Ty;
346*31ad468dSRafael Espindola     }
347*31ad468dSRafael Espindola 
348*31ad468dSRafael Espindola     StructType *DTy = StructType::create(Ty->getContext());
349*31ad468dSRafael Espindola     finishType(DTy, STy, ElementTypes);
350*31ad468dSRafael Espindola     return *Entry = DTy;
351*31ad468dSRafael Espindola   }
352*31ad468dSRafael Espindola   }
353b1ed91f3SChris Lattner }
354b1ed91f3SChris Lattner 
355b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
356b1ed91f3SChris Lattner // ModuleLinker implementation.
357b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
358b1ed91f3SChris Lattner 
359b1ed91f3SChris Lattner namespace {
360f6f121e2SJames Molloy class ModuleLinker;
361f6f121e2SJames Molloy 
36218c89411SRafael Espindola /// Creates prototypes for functions that are lazily linked on the fly. This
36318c89411SRafael Espindola /// speeds up linking for modules with many/ lazily linked functions of which
36418c89411SRafael Espindola /// few get used.
365f6f121e2SJames Molloy class ValueMaterializerTy : public ValueMaterializer {
366f6f121e2SJames Molloy   TypeMapTy &TypeMap;
367f6f121e2SJames Molloy   Module *DstM;
368f6f121e2SJames Molloy   std::vector<Function *> &LazilyLinkFunctions;
369c84f608bSRafael Espindola 
370f6f121e2SJames Molloy public:
371f6f121e2SJames Molloy   ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
372c84f608bSRafael Espindola                       std::vector<Function *> &LazilyLinkFunctions)
373c84f608bSRafael Espindola       : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
374c84f608bSRafael Espindola         LazilyLinkFunctions(LazilyLinkFunctions) {}
375f6f121e2SJames Molloy 
3768548299aSCraig Topper   Value *materializeValueFor(Value *V) override;
377f6f121e2SJames Molloy };
378f6f121e2SJames Molloy 
379d12b4a33SRafael Espindola class LinkDiagnosticInfo : public DiagnosticInfo {
380d12b4a33SRafael Espindola   const Twine &Msg;
381d12b4a33SRafael Espindola 
382d12b4a33SRafael Espindola public:
383d12b4a33SRafael Espindola   LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
384d12b4a33SRafael Espindola   void print(DiagnosticPrinter &DP) const override;
385d12b4a33SRafael Espindola };
386d12b4a33SRafael Espindola LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
387d12b4a33SRafael Espindola                                        const Twine &Msg)
388d12b4a33SRafael Espindola     : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
389d12b4a33SRafael Espindola void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
390d12b4a33SRafael Espindola 
39118c89411SRafael Espindola /// This is an implementation class for the LinkModules function, which is the
39218c89411SRafael Espindola /// entrypoint for this file.
393b1ed91f3SChris Lattner class ModuleLinker {
394b1ed91f3SChris Lattner   Module *DstM, *SrcM;
395b1ed91f3SChris Lattner 
396b1ed91f3SChris Lattner   TypeMapTy TypeMap;
397f6f121e2SJames Molloy   ValueMaterializerTy ValMaterializer;
398b1ed91f3SChris Lattner 
39918c89411SRafael Espindola   /// Mapping of values from what they used to be in Src, to what they are now
40018c89411SRafael Espindola   /// in DstM.  ValueToValueMapTy is a ValueMap, which involves some overhead
40118c89411SRafael Espindola   /// due to the use of Value handles which the Linker doesn't actually need,
40218c89411SRafael Espindola   /// but this allows us to reuse the ValueMapper code.
403b1ed91f3SChris Lattner   ValueToValueMapTy ValueMap;
404b1ed91f3SChris Lattner 
405b1ed91f3SChris Lattner   struct AppendingVarInfo {
406b1ed91f3SChris Lattner     GlobalVariable *NewGV;   // New aggregate global in dest module.
4073e8bc6a8SRafael Espindola     const Constant *DstInit; // Old initializer from dest module.
4083e8bc6a8SRafael Espindola     const Constant *SrcInit; // Old initializer from src module.
409b1ed91f3SChris Lattner   };
410b1ed91f3SChris Lattner 
411b1ed91f3SChris Lattner   std::vector<AppendingVarInfo> AppendingVars;
412b1ed91f3SChris Lattner 
413cbb91408STanya Lattner   // Set of items not to link in from source.
414cbb91408STanya Lattner   SmallPtrSet<const Value *, 16> DoNotLinkFromSource;
415cbb91408STanya Lattner 
4160a48b877STanya Lattner   // Vector of functions to lazily link in.
417fa228782SBill Wendling   std::vector<Function *> LazilyLinkFunctions;
4180a48b877STanya Lattner 
4194160f5d3SRafael Espindola   Linker::DiagnosticHandlerFunction DiagnosticHandler;
4204160f5d3SRafael Espindola 
421b1ed91f3SChris Lattner public:
422*31ad468dSRafael Espindola   ModuleLinker(Module *dstM, Linker::IdentifiedStructTypeSet &Set, Module *srcM,
4234160f5d3SRafael Espindola                Linker::DiagnosticHandlerFunction DiagnosticHandler)
424a4e85e3dSRafael Espindola       : DstM(dstM), SrcM(srcM), TypeMap(Set),
4259f8eff31SRafael Espindola         ValMaterializer(TypeMap, DstM, LazilyLinkFunctions),
4264160f5d3SRafael Espindola         DiagnosticHandler(DiagnosticHandler) {}
427b1ed91f3SChris Lattner 
428b1ed91f3SChris Lattner   bool run();
429b1ed91f3SChris Lattner 
430b1ed91f3SChris Lattner private:
431d12b4a33SRafael Espindola   bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
432d12b4a33SRafael Espindola                             const GlobalValue &Src);
433dbb0bd1aSRafael Espindola 
434d12b4a33SRafael Espindola   /// Helper method for setting a message and returning an error code.
435b1ed91f3SChris Lattner   bool emitError(const Twine &Message) {
4364160f5d3SRafael Espindola     DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
437b1ed91f3SChris Lattner     return true;
438b1ed91f3SChris Lattner   }
439b1ed91f3SChris Lattner 
440d12b4a33SRafael Espindola   void emitWarning(const Twine &Message) {
4414160f5d3SRafael Espindola     DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
442d12b4a33SRafael Espindola   }
443d12b4a33SRafael Espindola 
444dad0a645SDavid Majnemer   bool getComdatLeader(Module *M, StringRef ComdatName,
445dad0a645SDavid Majnemer                        const GlobalVariable *&GVar);
446dad0a645SDavid Majnemer   bool computeResultingSelectionKind(StringRef ComdatName,
447dad0a645SDavid Majnemer                                      Comdat::SelectionKind Src,
448dad0a645SDavid Majnemer                                      Comdat::SelectionKind Dst,
449dad0a645SDavid Majnemer                                      Comdat::SelectionKind &Result,
450dad0a645SDavid Majnemer                                      bool &LinkFromSrc);
451dad0a645SDavid Majnemer   std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
452dad0a645SDavid Majnemer       ComdatsChosen;
453dad0a645SDavid Majnemer   bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
454dad0a645SDavid Majnemer                        bool &LinkFromSrc);
455dad0a645SDavid Majnemer 
45618c89411SRafael Espindola   /// Given a global in the source module, return the global in the
45718c89411SRafael Espindola   /// destination module that is being linked to, if any.
4583e8bc6a8SRafael Espindola   GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
459b1ed91f3SChris Lattner     // If the source has no name it can't link.  If it has local linkage,
460b1ed91f3SChris Lattner     // there is no name match-up going on.
461b1ed91f3SChris Lattner     if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
4622617dcceSCraig Topper       return nullptr;
463b1ed91f3SChris Lattner 
464b1ed91f3SChris Lattner     // Otherwise see if we have a match in the destination module's symtab.
465b1ed91f3SChris Lattner     GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
466c84f608bSRafael Espindola     if (!DGV)
467c84f608bSRafael Espindola       return nullptr;
468b1ed91f3SChris Lattner 
469b1ed91f3SChris Lattner     // If we found a global with the same name in the dest module, but it has
470b1ed91f3SChris Lattner     // internal linkage, we are really not doing any linkage here.
471b1ed91f3SChris Lattner     if (DGV->hasLocalLinkage())
4722617dcceSCraig Topper       return nullptr;
473b1ed91f3SChris Lattner 
474b1ed91f3SChris Lattner     // Otherwise, we do in fact link to the destination global.
475b1ed91f3SChris Lattner     return DGV;
476b1ed91f3SChris Lattner   }
477b1ed91f3SChris Lattner 
478b1ed91f3SChris Lattner   void computeTypeMapping();
479b1ed91f3SChris Lattner 
48009d84addSDuncan P. N. Exon Smith   void upgradeMismatchedGlobalArray(StringRef Name);
48109d84addSDuncan P. N. Exon Smith   void upgradeMismatchedGlobals();
48209d84addSDuncan P. N. Exon Smith 
4833e8bc6a8SRafael Espindola   bool linkAppendingVarProto(GlobalVariable *DstGV,
4843e8bc6a8SRafael Espindola                              const GlobalVariable *SrcGV);
485778fcc77SRafael Espindola 
486778fcc77SRafael Espindola   bool linkGlobalValueProto(GlobalValue *GV);
487778fcc77SRafael Espindola   GlobalValue *linkGlobalVariableProto(const GlobalVariable *SGVar,
488778fcc77SRafael Espindola                                        GlobalValue *DGV, bool LinkFromSrc);
489778fcc77SRafael Espindola   GlobalValue *linkFunctionProto(const Function *SF, GlobalValue *DGV,
490778fcc77SRafael Espindola                                  bool LinkFromSrc);
491778fcc77SRafael Espindola   GlobalValue *linkGlobalAliasProto(const GlobalAlias *SGA, GlobalValue *DGV,
492778fcc77SRafael Espindola                                     bool LinkFromSrc);
493778fcc77SRafael Espindola 
49466f02413SBill Wendling   bool linkModuleFlagsMetadata();
495b1ed91f3SChris Lattner 
496b1ed91f3SChris Lattner   void linkAppendingVarInit(const AppendingVarInfo &AVI);
497b1ed91f3SChris Lattner   void linkGlobalInits();
498b1ed91f3SChris Lattner   void linkFunctionBody(Function *Dst, Function *Src);
499b1ed91f3SChris Lattner   void linkAliasBodies();
500b1ed91f3SChris Lattner   void linkNamedMDNodes();
501eee6f995SChris Lattner };
502d48b7783SBill Wendling }
503d48b7783SBill Wendling 
50418c89411SRafael Espindola /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
50518c89411SRafael Espindola /// table. This is good for all clients except for us. Go through the trouble
50618c89411SRafael Espindola /// to force this back.
507b1ed91f3SChris Lattner static void forceRenaming(GlobalValue *GV, StringRef Name) {
508b1ed91f3SChris Lattner   // If the global doesn't force its name or if it already has the right name,
509b1ed91f3SChris Lattner   // there is nothing for us to do.
510b1ed91f3SChris Lattner   if (GV->hasLocalLinkage() || GV->getName() == Name)
511b1ed91f3SChris Lattner     return;
512b1ed91f3SChris Lattner 
513b1ed91f3SChris Lattner   Module *M = GV->getParent();
514361e513dSReid Spencer 
515361e513dSReid Spencer   // If there is a conflict, rename the conflict.
516b1ed91f3SChris Lattner   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
5172a8d2e0eSChris Lattner     GV->takeName(ConflictGV);
518361e513dSReid Spencer     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
519b1ed91f3SChris Lattner     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
5202a8d2e0eSChris Lattner   } else {
5212a8d2e0eSChris Lattner     GV->setName(Name);              // Force the name back
5223aaaa0b2SReid Spencer   }
5233aaaa0b2SReid Spencer }
5243aaaa0b2SReid Spencer 
52518c89411SRafael Espindola /// copy additional attributes (those not needed to construct a GlobalValue)
52618c89411SRafael Espindola /// from the SrcGV to the DestGV.
527b6af2f36SBill Wendling static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
528dd7daee8SDuncan Sands   // Use the maximum alignment, rather than just copying the alignment of SrcGV.
52999e05cf1SRafael Espindola   auto *DestGO = dyn_cast<GlobalObject>(DestGV);
530a7d9c69cSRafael Espindola   unsigned Alignment;
53199e05cf1SRafael Espindola   if (DestGO)
53299e05cf1SRafael Espindola     Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
533a7d9c69cSRafael Espindola 
534dd7daee8SDuncan Sands   DestGV->copyAttributesFrom(SrcGV);
535a7d9c69cSRafael Espindola 
53699e05cf1SRafael Espindola   if (DestGO)
53799e05cf1SRafael Espindola     DestGO->setAlignment(Alignment);
538b1ed91f3SChris Lattner 
539b1ed91f3SChris Lattner   forceRenaming(DestGV, SrcGV->getName());
540361e513dSReid Spencer }
541361e513dSReid Spencer 
54223f8d64bSRafael Espindola static bool isLessConstraining(GlobalValue::VisibilityTypes a,
54323f8d64bSRafael Espindola                                GlobalValue::VisibilityTypes b) {
54423f8d64bSRafael Espindola   if (a == GlobalValue::HiddenVisibility)
54523f8d64bSRafael Espindola     return false;
54623f8d64bSRafael Espindola   if (b == GlobalValue::HiddenVisibility)
54723f8d64bSRafael Espindola     return true;
54823f8d64bSRafael Espindola   if (a == GlobalValue::ProtectedVisibility)
54923f8d64bSRafael Espindola     return false;
55023f8d64bSRafael Espindola   if (b == GlobalValue::ProtectedVisibility)
55123f8d64bSRafael Espindola     return true;
55223f8d64bSRafael Espindola   return false;
55323f8d64bSRafael Espindola }
55423f8d64bSRafael Espindola 
555f6f121e2SJames Molloy Value *ValueMaterializerTy::materializeValueFor(Value *V) {
556f6f121e2SJames Molloy   Function *SF = dyn_cast<Function>(V);
557f6f121e2SJames Molloy   if (!SF)
5582617dcceSCraig Topper     return nullptr;
559f6f121e2SJames Molloy 
560f6f121e2SJames Molloy   Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
561f6f121e2SJames Molloy                                   SF->getLinkage(), SF->getName(), DstM);
562f6f121e2SJames Molloy   copyGVAttributes(DF, SF);
563f6f121e2SJames Molloy 
5643931c28bSRafael Espindola   if (Comdat *SC = SF->getComdat()) {
5653931c28bSRafael Espindola     Comdat *DC = DstM->getOrInsertComdat(SC->getName());
5663931c28bSRafael Espindola     DF->setComdat(DC);
5673931c28bSRafael Espindola   }
5683931c28bSRafael Espindola 
569f6f121e2SJames Molloy   LazilyLinkFunctions.push_back(SF);
570f6f121e2SJames Molloy   return DF;
571f6f121e2SJames Molloy }
572f6f121e2SJames Molloy 
573dad0a645SDavid Majnemer bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
574dad0a645SDavid Majnemer                                    const GlobalVariable *&GVar) {
575dad0a645SDavid Majnemer   const GlobalValue *GVal = M->getNamedValue(ComdatName);
576dad0a645SDavid Majnemer   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
577dad0a645SDavid Majnemer     GVal = GA->getBaseObject();
578dad0a645SDavid Majnemer     if (!GVal)
579dad0a645SDavid Majnemer       // We cannot resolve the size of the aliasee yet.
580dad0a645SDavid Majnemer       return emitError("Linking COMDATs named '" + ComdatName +
581dad0a645SDavid Majnemer                        "': COMDAT key involves incomputable alias size.");
582dad0a645SDavid Majnemer   }
583dad0a645SDavid Majnemer 
584dad0a645SDavid Majnemer   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
585dad0a645SDavid Majnemer   if (!GVar)
586dad0a645SDavid Majnemer     return emitError(
587dad0a645SDavid Majnemer         "Linking COMDATs named '" + ComdatName +
588dad0a645SDavid Majnemer         "': GlobalVariable required for data dependent selection!");
589dad0a645SDavid Majnemer 
590dad0a645SDavid Majnemer   return false;
591dad0a645SDavid Majnemer }
592dad0a645SDavid Majnemer 
593dad0a645SDavid Majnemer bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
594dad0a645SDavid Majnemer                                                  Comdat::SelectionKind Src,
595dad0a645SDavid Majnemer                                                  Comdat::SelectionKind Dst,
596dad0a645SDavid Majnemer                                                  Comdat::SelectionKind &Result,
597dad0a645SDavid Majnemer                                                  bool &LinkFromSrc) {
598dad0a645SDavid Majnemer   // The ability to mix Comdat::SelectionKind::Any with
599dad0a645SDavid Majnemer   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
600dad0a645SDavid Majnemer   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
601dad0a645SDavid Majnemer                          Dst == Comdat::SelectionKind::Largest;
602dad0a645SDavid Majnemer   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
603dad0a645SDavid Majnemer                          Src == Comdat::SelectionKind::Largest;
604dad0a645SDavid Majnemer   if (DstAnyOrLargest && SrcAnyOrLargest) {
605dad0a645SDavid Majnemer     if (Dst == Comdat::SelectionKind::Largest ||
606dad0a645SDavid Majnemer         Src == Comdat::SelectionKind::Largest)
607dad0a645SDavid Majnemer       Result = Comdat::SelectionKind::Largest;
608dad0a645SDavid Majnemer     else
609dad0a645SDavid Majnemer       Result = Comdat::SelectionKind::Any;
610dad0a645SDavid Majnemer   } else if (Src == Dst) {
611dad0a645SDavid Majnemer     Result = Dst;
612dad0a645SDavid Majnemer   } else {
613dad0a645SDavid Majnemer     return emitError("Linking COMDATs named '" + ComdatName +
614dad0a645SDavid Majnemer                      "': invalid selection kinds!");
615dad0a645SDavid Majnemer   }
616dad0a645SDavid Majnemer 
617dad0a645SDavid Majnemer   switch (Result) {
618dad0a645SDavid Majnemer   case Comdat::SelectionKind::Any:
619dad0a645SDavid Majnemer     // Go with Dst.
620dad0a645SDavid Majnemer     LinkFromSrc = false;
621dad0a645SDavid Majnemer     break;
622dad0a645SDavid Majnemer   case Comdat::SelectionKind::NoDuplicates:
623dad0a645SDavid Majnemer     return emitError("Linking COMDATs named '" + ComdatName +
624dad0a645SDavid Majnemer                      "': noduplicates has been violated!");
625dad0a645SDavid Majnemer   case Comdat::SelectionKind::ExactMatch:
626dad0a645SDavid Majnemer   case Comdat::SelectionKind::Largest:
627dad0a645SDavid Majnemer   case Comdat::SelectionKind::SameSize: {
628dad0a645SDavid Majnemer     const GlobalVariable *DstGV;
629dad0a645SDavid Majnemer     const GlobalVariable *SrcGV;
630dad0a645SDavid Majnemer     if (getComdatLeader(DstM, ComdatName, DstGV) ||
631dad0a645SDavid Majnemer         getComdatLeader(SrcM, ComdatName, SrcGV))
632dad0a645SDavid Majnemer       return true;
633dad0a645SDavid Majnemer 
634dad0a645SDavid Majnemer     const DataLayout *DstDL = DstM->getDataLayout();
635dad0a645SDavid Majnemer     const DataLayout *SrcDL = SrcM->getDataLayout();
636dad0a645SDavid Majnemer     if (!DstDL || !SrcDL) {
637dad0a645SDavid Majnemer       return emitError(
638dad0a645SDavid Majnemer           "Linking COMDATs named '" + ComdatName +
639dad0a645SDavid Majnemer           "': can't do size dependent selection without DataLayout!");
640dad0a645SDavid Majnemer     }
641dad0a645SDavid Majnemer     uint64_t DstSize =
642dad0a645SDavid Majnemer         DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
643dad0a645SDavid Majnemer     uint64_t SrcSize =
644dad0a645SDavid Majnemer         SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
645dad0a645SDavid Majnemer     if (Result == Comdat::SelectionKind::ExactMatch) {
646dad0a645SDavid Majnemer       if (SrcGV->getInitializer() != DstGV->getInitializer())
647dad0a645SDavid Majnemer         return emitError("Linking COMDATs named '" + ComdatName +
648dad0a645SDavid Majnemer                          "': ExactMatch violated!");
649dad0a645SDavid Majnemer       LinkFromSrc = false;
650dad0a645SDavid Majnemer     } else if (Result == Comdat::SelectionKind::Largest) {
651dad0a645SDavid Majnemer       LinkFromSrc = SrcSize > DstSize;
652dad0a645SDavid Majnemer     } else if (Result == Comdat::SelectionKind::SameSize) {
653dad0a645SDavid Majnemer       if (SrcSize != DstSize)
654dad0a645SDavid Majnemer         return emitError("Linking COMDATs named '" + ComdatName +
655dad0a645SDavid Majnemer                          "': SameSize violated!");
656dad0a645SDavid Majnemer       LinkFromSrc = false;
657dad0a645SDavid Majnemer     } else {
658dad0a645SDavid Majnemer       llvm_unreachable("unknown selection kind");
659dad0a645SDavid Majnemer     }
660dad0a645SDavid Majnemer     break;
661dad0a645SDavid Majnemer   }
662dad0a645SDavid Majnemer   }
663dad0a645SDavid Majnemer 
664dad0a645SDavid Majnemer   return false;
665dad0a645SDavid Majnemer }
666dad0a645SDavid Majnemer 
667dad0a645SDavid Majnemer bool ModuleLinker::getComdatResult(const Comdat *SrcC,
668dad0a645SDavid Majnemer                                    Comdat::SelectionKind &Result,
669dad0a645SDavid Majnemer                                    bool &LinkFromSrc) {
670b16196a3SRafael Espindola   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
671dad0a645SDavid Majnemer   StringRef ComdatName = SrcC->getName();
672dad0a645SDavid Majnemer   Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
673dad0a645SDavid Majnemer   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
6742ef3f299SRafael Espindola 
675b16196a3SRafael Espindola   if (DstCI == ComdatSymTab.end()) {
676b16196a3SRafael Espindola     // Use the comdat if it is only available in one of the modules.
677b16196a3SRafael Espindola     LinkFromSrc = true;
678b16196a3SRafael Espindola     Result = SSK;
6792ef3f299SRafael Espindola     return false;
680b16196a3SRafael Espindola   }
6812ef3f299SRafael Espindola 
682dad0a645SDavid Majnemer   const Comdat *DstC = &DstCI->second;
683dad0a645SDavid Majnemer   Comdat::SelectionKind DSK = DstC->getSelectionKind();
6842ef3f299SRafael Espindola   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
6852ef3f299SRafael Espindola                                        LinkFromSrc);
686dad0a645SDavid Majnemer }
687f6f121e2SJames Molloy 
688d12b4a33SRafael Espindola bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
689d12b4a33SRafael Espindola                                         const GlobalValue &Dest,
690dbb0bd1aSRafael Espindola                                         const GlobalValue &Src) {
691778fcc77SRafael Espindola   // We always have to add Src if it has appending linkage.
692778fcc77SRafael Espindola   if (Src.hasAppendingLinkage()) {
693778fcc77SRafael Espindola     LinkFromSrc = true;
694778fcc77SRafael Espindola     return false;
695778fcc77SRafael Espindola   }
696778fcc77SRafael Espindola 
697d4bcefc7SRafael Espindola   bool SrcIsDeclaration = Src.isDeclarationForLinker();
698d4bcefc7SRafael Espindola   bool DestIsDeclaration = Dest.isDeclarationForLinker();
699dbb0bd1aSRafael Espindola 
700dbb0bd1aSRafael Espindola   if (SrcIsDeclaration) {
701dbb0bd1aSRafael Espindola     // If Src is external or if both Src & Dest are external..  Just link the
702dbb0bd1aSRafael Espindola     // external globals, we aren't adding anything.
703d12b4a33SRafael Espindola     if (Src.hasDLLImportStorageClass()) {
704dbb0bd1aSRafael Espindola       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
705d12b4a33SRafael Espindola       LinkFromSrc = DestIsDeclaration;
706d12b4a33SRafael Espindola       return false;
707d12b4a33SRafael Espindola     }
708dbb0bd1aSRafael Espindola     // If the Dest is weak, use the source linkage.
709d12b4a33SRafael Espindola     LinkFromSrc = Dest.hasExternalWeakLinkage();
710d12b4a33SRafael Espindola     return false;
711dbb0bd1aSRafael Espindola   }
712dbb0bd1aSRafael Espindola 
713d12b4a33SRafael Espindola   if (DestIsDeclaration) {
714dbb0bd1aSRafael Espindola     // If Dest is external but Src is not:
715d12b4a33SRafael Espindola     LinkFromSrc = true;
716d12b4a33SRafael Espindola     return false;
717d12b4a33SRafael Espindola   }
718dbb0bd1aSRafael Espindola 
7190910605aSRafael Espindola   if (Src.hasCommonLinkage()) {
720d12b4a33SRafael Espindola     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
721d12b4a33SRafael Espindola       LinkFromSrc = true;
7220910605aSRafael Espindola       return false;
723d12b4a33SRafael Espindola     }
724d12b4a33SRafael Espindola 
725d12b4a33SRafael Espindola     if (!Dest.hasCommonLinkage()) {
726d12b4a33SRafael Espindola       LinkFromSrc = false;
727d12b4a33SRafael Espindola       return false;
728d12b4a33SRafael Espindola     }
7290910605aSRafael Espindola 
7300ae225b6SRafael Espindola     // FIXME: Make datalayout mandatory and just use getDataLayout().
7310ae225b6SRafael Espindola     DataLayout DL(Dest.getParent());
7320ae225b6SRafael Espindola 
7330910605aSRafael Espindola     uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
7340910605aSRafael Espindola     uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
735d12b4a33SRafael Espindola     LinkFromSrc = SrcSize > DestSize;
736d12b4a33SRafael Espindola     return false;
7370910605aSRafael Espindola   }
7380910605aSRafael Espindola 
739dbb0bd1aSRafael Espindola   if (Src.isWeakForLinker()) {
740dbb0bd1aSRafael Espindola     assert(!Dest.hasExternalWeakLinkage());
741dbb0bd1aSRafael Espindola     assert(!Dest.hasAvailableExternallyLinkage());
7420910605aSRafael Espindola 
743d12b4a33SRafael Espindola     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
744d12b4a33SRafael Espindola       LinkFromSrc = true;
745d12b4a33SRafael Espindola       return false;
746d12b4a33SRafael Espindola     }
747dbb0bd1aSRafael Espindola 
748d12b4a33SRafael Espindola     LinkFromSrc = false;
7490910605aSRafael Espindola     return false;
750dbb0bd1aSRafael Espindola   }
751dbb0bd1aSRafael Espindola 
752dbb0bd1aSRafael Espindola   if (Dest.isWeakForLinker()) {
753dbb0bd1aSRafael Espindola     assert(Src.hasExternalLinkage());
754d12b4a33SRafael Espindola     LinkFromSrc = true;
755d12b4a33SRafael Espindola     return false;
756dbb0bd1aSRafael Espindola   }
757dbb0bd1aSRafael Espindola 
758dbb0bd1aSRafael Espindola   assert(!Src.hasExternalWeakLinkage());
759dbb0bd1aSRafael Espindola   assert(!Dest.hasExternalWeakLinkage());
760dbb0bd1aSRafael Espindola   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
761dbb0bd1aSRafael Espindola          "Unexpected linkage type!");
762dbb0bd1aSRafael Espindola   return emitError("Linking globals named '" + Src.getName() +
763dbb0bd1aSRafael Espindola                    "': symbol multiply defined!");
764dbb0bd1aSRafael Espindola }
765dbb0bd1aSRafael Espindola 
76618c89411SRafael Espindola /// Loop over all of the linked values to compute type mappings.  For example,
76718c89411SRafael Espindola /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
76818c89411SRafael Espindola /// types 'Foo' but one got renamed when the module was loaded into the same
76918c89411SRafael Espindola /// LLVMContext.
770b1ed91f3SChris Lattner void ModuleLinker::computeTypeMapping() {
771c8a476eeSRafael Espindola   for (GlobalValue &SGV : SrcM->globals()) {
772c8a476eeSRafael Espindola     GlobalValue *DGV = getLinkedToGlobal(&SGV);
773c8a476eeSRafael Espindola     if (!DGV)
774c8a476eeSRafael Espindola       continue;
775b1ed91f3SChris Lattner 
776c8a476eeSRafael Espindola     if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
777c8a476eeSRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
778b1ed91f3SChris Lattner       continue;
7795c310be0SDevang Patel     }
7805c310be0SDevang Patel 
781b1ed91f3SChris Lattner     // Unify the element type of appending arrays.
782b1ed91f3SChris Lattner     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
783c8a476eeSRafael Espindola     ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
784b1ed91f3SChris Lattner     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
785b1ed91f3SChris Lattner   }
78634fc5a0eSChris Lattner 
787c8a476eeSRafael Espindola   for (GlobalValue &SGV : *SrcM) {
788c8a476eeSRafael Espindola     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
789c8a476eeSRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
790b1ed91f3SChris Lattner   }
791e79f4c77SAnton Korobeynikov 
792e96d7eb8SRafael Espindola   for (GlobalValue &SGV : SrcM->aliases()) {
793e96d7eb8SRafael Espindola     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
794e96d7eb8SRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
795e96d7eb8SRafael Espindola   }
796e96d7eb8SRafael Espindola 
797d48b7783SBill Wendling   // Incorporate types by name, scanning all the types in the source module.
798d48b7783SBill Wendling   // At this point, the destination module may have a type "%foo = { i32 }" for
7992b3f61afSBill Wendling   // example.  When the source module got loaded into the same LLVMContext, if
8002b3f61afSBill Wendling   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
8012fa1e43aSRafael Espindola   std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
8022fa1e43aSRafael Espindola   for (StructType *ST : Types) {
8034d4c9387SRafael Espindola     if (!ST->hasName())
8044d4c9387SRafael Espindola       continue;
8052b3f61afSBill Wendling 
8062b3f61afSBill Wendling     // Check to see if there is a dot in the name followed by a digit.
807d48b7783SBill Wendling     size_t DotPos = ST->getName().rfind('.');
808d48b7783SBill Wendling     if (DotPos == 0 || DotPos == StringRef::npos ||
80983c74e9fSGuy Benyei         ST->getName().back() == '.' ||
81083c74e9fSGuy Benyei         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
811d48b7783SBill Wendling       continue;
8122b3f61afSBill Wendling 
8132b3f61afSBill Wendling     // Check to see if the destination module has a struct with the prefix name.
814973b3612SRafael Espindola     StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos));
815973b3612SRafael Espindola     if (!DST)
816973b3612SRafael Espindola       continue;
817973b3612SRafael Espindola 
8182b3f61afSBill Wendling     // Don't use it if this actually came from the source module. They're in
8198737480dSBill Wendling     // the same LLVMContext after all. Also don't use it unless the type is
8208737480dSBill Wendling     // actually used in the destination module. This can happen in situations
8218737480dSBill Wendling     // like this:
8228737480dSBill Wendling     //
8238737480dSBill Wendling     //      Module A                         Module B
8248737480dSBill Wendling     //      --------                         --------
8258737480dSBill Wendling     //   %Z = type { %A }                %B = type { %C.1 }
8268737480dSBill Wendling     //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
8278737480dSBill Wendling     //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
8288737480dSBill Wendling     //   %C = type { i8* }               %B.3 = type { %C.1 }
8298737480dSBill Wendling     //
8308737480dSBill Wendling     // When we link Module B with Module A, the '%B' in Module B is
8318737480dSBill Wendling     // used. However, that would then use '%C.1'. But when we process '%C.1',
8328737480dSBill Wendling     // we prefer to take the '%C' version. So we are then left with both
8338737480dSBill Wendling     // '%C.1' and '%C' being used for the same types. This leads to some
8348737480dSBill Wendling     // variables using one type and some using the other.
835*31ad468dSRafael Espindola     if (TypeMap.DstStructTypesSet.hasType(DST))
8362b3f61afSBill Wendling       TypeMap.addTypeMapping(DST, ST);
8372b3f61afSBill Wendling   }
8382b3f61afSBill Wendling 
839b1ed91f3SChris Lattner   // Now that we have discovered all of the type equivalences, get a body for
840b1ed91f3SChris Lattner   // any 'opaque' types in the dest module that are now resolved.
841b1ed91f3SChris Lattner   TypeMap.linkDefinedTypeBodies();
842b1ed91f3SChris Lattner }
843c08e7a00SChris Lattner 
84409d84addSDuncan P. N. Exon Smith static void upgradeGlobalArray(GlobalVariable *GV) {
84509d84addSDuncan P. N. Exon Smith   ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
84609d84addSDuncan P. N. Exon Smith   StructType *OldTy = cast<StructType>(ATy->getElementType());
84709d84addSDuncan P. N. Exon Smith   assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
84809d84addSDuncan P. N. Exon Smith 
84909d84addSDuncan P. N. Exon Smith   // Get the upgraded 3 element type.
85009d84addSDuncan P. N. Exon Smith   PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
85109d84addSDuncan P. N. Exon Smith   Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
85209d84addSDuncan P. N. Exon Smith                   VoidPtrTy};
85309d84addSDuncan P. N. Exon Smith   StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
85409d84addSDuncan P. N. Exon Smith 
85509d84addSDuncan P. N. Exon Smith   // Build new constants with a null third field filled in.
85609d84addSDuncan P. N. Exon Smith   Constant *OldInitC = GV->getInitializer();
85709d84addSDuncan P. N. Exon Smith   ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
85809d84addSDuncan P. N. Exon Smith   if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
85909d84addSDuncan P. N. Exon Smith     // Invalid initializer; give up.
86009d84addSDuncan P. N. Exon Smith     return;
86109d84addSDuncan P. N. Exon Smith   std::vector<Constant *> Initializers;
86209d84addSDuncan P. N. Exon Smith   if (OldInit && OldInit->getNumOperands()) {
86309d84addSDuncan P. N. Exon Smith     Value *Null = Constant::getNullValue(VoidPtrTy);
86409d84addSDuncan P. N. Exon Smith     for (Use &U : OldInit->operands()) {
86509d84addSDuncan P. N. Exon Smith       ConstantStruct *Init = cast<ConstantStruct>(U.get());
86609d84addSDuncan P. N. Exon Smith       Initializers.push_back(ConstantStruct::get(
86709d84addSDuncan P. N. Exon Smith           NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
86809d84addSDuncan P. N. Exon Smith     }
86909d84addSDuncan P. N. Exon Smith   }
87009d84addSDuncan P. N. Exon Smith   assert(Initializers.size() == ATy->getNumElements() &&
87109d84addSDuncan P. N. Exon Smith          "Failed to copy all array elements");
87209d84addSDuncan P. N. Exon Smith 
87309d84addSDuncan P. N. Exon Smith   // Replace the old GV with a new one.
87409d84addSDuncan P. N. Exon Smith   ATy = ArrayType::get(NewTy, Initializers.size());
87509d84addSDuncan P. N. Exon Smith   Constant *NewInit = ConstantArray::get(ATy, Initializers);
87609d84addSDuncan P. N. Exon Smith   GlobalVariable *NewGV = new GlobalVariable(
87709d84addSDuncan P. N. Exon Smith       *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
87809d84addSDuncan P. N. Exon Smith       GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
87909d84addSDuncan P. N. Exon Smith       GV->isExternallyInitialized());
88009d84addSDuncan P. N. Exon Smith   NewGV->copyAttributesFrom(GV);
88109d84addSDuncan P. N. Exon Smith   NewGV->takeName(GV);
88209d84addSDuncan P. N. Exon Smith   assert(GV->use_empty() && "program cannot use initializer list");
88309d84addSDuncan P. N. Exon Smith   GV->eraseFromParent();
88409d84addSDuncan P. N. Exon Smith }
88509d84addSDuncan P. N. Exon Smith 
88609d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
88709d84addSDuncan P. N. Exon Smith   // Look for the global arrays.
88809d84addSDuncan P. N. Exon Smith   auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
88909d84addSDuncan P. N. Exon Smith   if (!DstGV)
89009d84addSDuncan P. N. Exon Smith     return;
89109d84addSDuncan P. N. Exon Smith   auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
89209d84addSDuncan P. N. Exon Smith   if (!SrcGV)
89309d84addSDuncan P. N. Exon Smith     return;
89409d84addSDuncan P. N. Exon Smith 
89509d84addSDuncan P. N. Exon Smith   // Check if the types already match.
89609d84addSDuncan P. N. Exon Smith   auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
89709d84addSDuncan P. N. Exon Smith   auto *SrcTy =
89809d84addSDuncan P. N. Exon Smith       cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
89909d84addSDuncan P. N. Exon Smith   if (DstTy == SrcTy)
90009d84addSDuncan P. N. Exon Smith     return;
90109d84addSDuncan P. N. Exon Smith 
90209d84addSDuncan P. N. Exon Smith   // Grab the element types.  We can only upgrade an array of a two-field
90309d84addSDuncan P. N. Exon Smith   // struct.  Only bother if the other one has three-fields.
90409d84addSDuncan P. N. Exon Smith   auto *DstEltTy = cast<StructType>(DstTy->getElementType());
90509d84addSDuncan P. N. Exon Smith   auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
90609d84addSDuncan P. N. Exon Smith   if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
90709d84addSDuncan P. N. Exon Smith     upgradeGlobalArray(DstGV);
90809d84addSDuncan P. N. Exon Smith     return;
90909d84addSDuncan P. N. Exon Smith   }
91009d84addSDuncan P. N. Exon Smith   if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
91109d84addSDuncan P. N. Exon Smith     upgradeGlobalArray(SrcGV);
91209d84addSDuncan P. N. Exon Smith 
91309d84addSDuncan P. N. Exon Smith   // We can't upgrade any other differences.
91409d84addSDuncan P. N. Exon Smith }
91509d84addSDuncan P. N. Exon Smith 
91609d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobals() {
91709d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobalArray("llvm.global_ctors");
91809d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobalArray("llvm.global_dtors");
91909d84addSDuncan P. N. Exon Smith }
92009d84addSDuncan P. N. Exon Smith 
92118c89411SRafael Espindola /// If there were any appending global variables, link them together now.
92218c89411SRafael Espindola /// Return true on error.
923b1ed91f3SChris Lattner bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
9243e8bc6a8SRafael Espindola                                          const GlobalVariable *SrcGV) {
925d48b7783SBill Wendling 
926b1ed91f3SChris Lattner   if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
927b1ed91f3SChris Lattner     return emitError("Linking globals named '" + SrcGV->getName() +
928b1ed91f3SChris Lattner            "': can only link appending global with another appending global!");
929361e513dSReid Spencer 
930b1ed91f3SChris Lattner   ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
931b1ed91f3SChris Lattner   ArrayType *SrcTy =
932b1ed91f3SChris Lattner     cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
933b1ed91f3SChris Lattner   Type *EltTy = DstTy->getElementType();
934b1ed91f3SChris Lattner 
935b1ed91f3SChris Lattner   // Check to see that they two arrays agree on type.
936b1ed91f3SChris Lattner   if (EltTy != SrcTy->getElementType())
937b1ed91f3SChris Lattner     return emitError("Appending variables with different element types!");
938b1ed91f3SChris Lattner   if (DstGV->isConstant() != SrcGV->isConstant())
939b1ed91f3SChris Lattner     return emitError("Appending variables linked with different const'ness!");
940b1ed91f3SChris Lattner 
941b1ed91f3SChris Lattner   if (DstGV->getAlignment() != SrcGV->getAlignment())
942b1ed91f3SChris Lattner     return emitError(
943b1ed91f3SChris Lattner              "Appending variables with different alignment need to be linked!");
944b1ed91f3SChris Lattner 
945b1ed91f3SChris Lattner   if (DstGV->getVisibility() != SrcGV->getVisibility())
946b1ed91f3SChris Lattner     return emitError(
947b1ed91f3SChris Lattner             "Appending variables with different visibility need to be linked!");
948b1ed91f3SChris Lattner 
949fac3a018SRafael Espindola   if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
950fac3a018SRafael Espindola     return emitError(
951fac3a018SRafael Espindola         "Appending variables with different unnamed_addr need to be linked!");
952fac3a018SRafael Espindola 
95364c1e180SRafael Espindola   if (StringRef(DstGV->getSection()) != SrcGV->getSection())
954b1ed91f3SChris Lattner     return emitError(
955b1ed91f3SChris Lattner           "Appending variables with different section name need to be linked!");
956b1ed91f3SChris Lattner 
957b1ed91f3SChris Lattner   uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
958b1ed91f3SChris Lattner   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
959b1ed91f3SChris Lattner 
960b1ed91f3SChris Lattner   // Create the new global variable.
961b1ed91f3SChris Lattner   GlobalVariable *NG =
962b1ed91f3SChris Lattner     new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
9632617dcceSCraig Topper                        DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
964cbe34b4cSHans Wennborg                        DstGV->getThreadLocalMode(),
965b1ed91f3SChris Lattner                        DstGV->getType()->getAddressSpace());
966b1ed91f3SChris Lattner 
967b1ed91f3SChris Lattner   // Propagate alignment, visibility and section info.
968b6af2f36SBill Wendling   copyGVAttributes(NG, DstGV);
969b1ed91f3SChris Lattner 
970b1ed91f3SChris Lattner   AppendingVarInfo AVI;
971b1ed91f3SChris Lattner   AVI.NewGV = NG;
972b1ed91f3SChris Lattner   AVI.DstInit = DstGV->getInitializer();
973b1ed91f3SChris Lattner   AVI.SrcInit = SrcGV->getInitializer();
974b1ed91f3SChris Lattner   AppendingVars.push_back(AVI);
975b1ed91f3SChris Lattner 
976b1ed91f3SChris Lattner   // Replace any uses of the two global variables with uses of the new
977b1ed91f3SChris Lattner   // global.
978b1ed91f3SChris Lattner   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
979b1ed91f3SChris Lattner 
980b1ed91f3SChris Lattner   DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
981b1ed91f3SChris Lattner   DstGV->eraseFromParent();
982b1ed91f3SChris Lattner 
983cbb91408STanya Lattner   // Track the source variable so we don't try to link it.
984cbb91408STanya Lattner   DoNotLinkFromSource.insert(SrcGV);
985cbb91408STanya Lattner 
986b1ed91f3SChris Lattner   return false;
987b1ed91f3SChris Lattner }
988b1ed91f3SChris Lattner 
989778fcc77SRafael Espindola bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
990b1ed91f3SChris Lattner   GlobalValue *DGV = getLinkedToGlobal(SGV);
991b1ed91f3SChris Lattner 
992778fcc77SRafael Espindola   // Handle the ultra special appending linkage case first.
993778fcc77SRafael Espindola   if (DGV && DGV->hasAppendingLinkage())
994778fcc77SRafael Espindola     return linkAppendingVarProto(cast<GlobalVariable>(DGV),
995778fcc77SRafael Espindola                                  cast<GlobalVariable>(SGV));
996778fcc77SRafael Espindola 
997778fcc77SRafael Espindola   bool LinkFromSrc = true;
998778fcc77SRafael Espindola   Comdat *C = nullptr;
999778fcc77SRafael Espindola   GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
1000778fcc77SRafael Espindola   bool HasUnnamedAddr = SGV->hasUnnamedAddr();
1001778fcc77SRafael Espindola 
1002dad0a645SDavid Majnemer   if (const Comdat *SC = SGV->getComdat()) {
1003dad0a645SDavid Majnemer     Comdat::SelectionKind SK;
1004dad0a645SDavid Majnemer     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1005778fcc77SRafael Espindola     C = DstM->getOrInsertComdat(SC->getName());
1006778fcc77SRafael Espindola     C->setSelectionKind(SK);
1007778fcc77SRafael Espindola   } else if (DGV) {
1008778fcc77SRafael Espindola     if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1009fc61de39SChris Lattner       return true;
1010dad0a645SDavid Majnemer   }
101134fc5a0eSChris Lattner 
1012dad0a645SDavid Majnemer   if (!LinkFromSrc) {
1013cbb91408STanya Lattner     // Track the source global so that we don't attempt to copy it over when
1014cbb91408STanya Lattner     // processing global initializers.
1015cbb91408STanya Lattner     DoNotLinkFromSource.insert(SGV);
1016cbb91408STanya Lattner 
1017778fcc77SRafael Espindola     if (DGV)
1018778fcc77SRafael Espindola       // Make sure to remember this mapping.
1019778fcc77SRafael Espindola       ValueMap[SGV] =
1020778fcc77SRafael Espindola           ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
1021778fcc77SRafael Espindola   }
1022778fcc77SRafael Espindola 
1023778fcc77SRafael Espindola   if (DGV) {
1024778fcc77SRafael Espindola     Visibility = isLessConstraining(Visibility, DGV->getVisibility())
1025778fcc77SRafael Espindola                      ? DGV->getVisibility()
1026778fcc77SRafael Espindola                      : Visibility;
1027778fcc77SRafael Espindola     HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1028778fcc77SRafael Espindola   }
1029778fcc77SRafael Espindola 
1030778fcc77SRafael Espindola   if (!LinkFromSrc && !DGV)
1031dad0a645SDavid Majnemer     return false;
1032778fcc77SRafael Espindola 
1033778fcc77SRafael Espindola   GlobalValue *NewGV;
1034778fcc77SRafael Espindola   if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
1035778fcc77SRafael Espindola     NewGV = linkGlobalVariableProto(SGVar, DGV, LinkFromSrc);
1036778fcc77SRafael Espindola     if (!NewGV)
1037778fcc77SRafael Espindola       return true;
1038778fcc77SRafael Espindola   } else if (auto *SF = dyn_cast<Function>(SGV)) {
1039778fcc77SRafael Espindola     NewGV = linkFunctionProto(SF, DGV, LinkFromSrc);
1040778fcc77SRafael Espindola   } else {
1041778fcc77SRafael Espindola     NewGV = linkGlobalAliasProto(cast<GlobalAlias>(SGV), DGV, LinkFromSrc);
1042778fcc77SRafael Espindola   }
1043778fcc77SRafael Espindola 
1044778fcc77SRafael Espindola   if (NewGV) {
1045778fcc77SRafael Espindola     if (NewGV != DGV)
1046778fcc77SRafael Espindola       copyGVAttributes(NewGV, SGV);
1047778fcc77SRafael Espindola 
1048778fcc77SRafael Espindola     NewGV->setUnnamedAddr(HasUnnamedAddr);
1049778fcc77SRafael Espindola     NewGV->setVisibility(Visibility);
1050778fcc77SRafael Espindola 
1051778fcc77SRafael Espindola     if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1052778fcc77SRafael Espindola       if (C)
1053778fcc77SRafael Espindola         NewGO->setComdat(C);
1054778fcc77SRafael Espindola     }
1055778fcc77SRafael Espindola 
1056778fcc77SRafael Espindola     // Make sure to remember this mapping.
1057778fcc77SRafael Espindola     if (NewGV != DGV) {
1058778fcc77SRafael Espindola       if (DGV) {
1059778fcc77SRafael Espindola         DGV->replaceAllUsesWith(
1060778fcc77SRafael Espindola             ConstantExpr::getBitCast(NewGV, DGV->getType()));
1061778fcc77SRafael Espindola         DGV->eraseFromParent();
1062778fcc77SRafael Espindola       }
1063778fcc77SRafael Espindola       ValueMap[SGV] = NewGV;
1064dad0a645SDavid Majnemer     }
10654e27567aSRafael Espindola   }
10664e27567aSRafael Espindola 
1067fd38af2dSChandler Carruth   return false;
10684e27567aSRafael Espindola }
10694e27567aSRafael Espindola 
1070778fcc77SRafael Espindola /// Loop through the global variables in the src module and merge them into the
1071778fcc77SRafael Espindola /// dest module.
1072778fcc77SRafael Espindola GlobalValue *ModuleLinker::linkGlobalVariableProto(const GlobalVariable *SGVar,
1073778fcc77SRafael Espindola                                                    GlobalValue *DGV,
1074778fcc77SRafael Espindola                                                    bool LinkFromSrc) {
1075778fcc77SRafael Espindola   unsigned Alignment = 0;
1076778fcc77SRafael Espindola   bool ClearConstant = false;
1077778fcc77SRafael Espindola 
1078778fcc77SRafael Espindola   if (DGV) {
1079778fcc77SRafael Espindola     if (DGV->hasCommonLinkage() && SGVar->hasCommonLinkage())
1080778fcc77SRafael Espindola       Alignment = std::max(SGVar->getAlignment(), DGV->getAlignment());
1081778fcc77SRafael Espindola 
1082778fcc77SRafael Espindola     auto *DGVar = dyn_cast<GlobalVariable>(DGV);
1083778fcc77SRafael Espindola     if (!SGVar->isConstant() || (DGVar && !DGVar->isConstant()))
1084778fcc77SRafael Espindola       ClearConstant = true;
1085778fcc77SRafael Espindola   }
1086778fcc77SRafael Espindola 
1087778fcc77SRafael Espindola   if (!LinkFromSrc) {
1088778fcc77SRafael Espindola     if (auto *NewGVar = dyn_cast<GlobalVariable>(DGV)) {
1089778fcc77SRafael Espindola       if (Alignment)
1090778fcc77SRafael Espindola         NewGVar->setAlignment(Alignment);
1091778fcc77SRafael Espindola       if (NewGVar->isDeclaration() && ClearConstant)
1092778fcc77SRafael Espindola         NewGVar->setConstant(false);
1093778fcc77SRafael Espindola     }
1094778fcc77SRafael Espindola     return DGV;
1095778fcc77SRafael Espindola   }
1096778fcc77SRafael Espindola 
1097b1ed91f3SChris Lattner   // No linking to be performed or linking from the source: simply create an
1098b1ed91f3SChris Lattner   // identical version of the symbol over in the dest module... the
1099b1ed91f3SChris Lattner   // initializer will be filled in later by LinkGlobalInits.
1100778fcc77SRafael Espindola   GlobalVariable *NewDGV = new GlobalVariable(
1101778fcc77SRafael Espindola       *DstM, TypeMap.get(SGVar->getType()->getElementType()),
1102778fcc77SRafael Espindola       SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr,
1103778fcc77SRafael Espindola       SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
1104778fcc77SRafael Espindola       SGVar->getType()->getAddressSpace());
1105778fcc77SRafael Espindola 
1106778fcc77SRafael Espindola   if (Alignment)
1107fe3842cdSRafael Espindola     NewDGV->setAlignment(Alignment);
1108b1ed91f3SChris Lattner 
1109778fcc77SRafael Espindola   return NewDGV;
1110361e513dSReid Spencer }
1111361e513dSReid Spencer 
111218c89411SRafael Espindola /// Link the function in the source module into the destination module if
111318c89411SRafael Espindola /// needed, setting up mapping information.
1114778fcc77SRafael Espindola GlobalValue *ModuleLinker::linkFunctionProto(const Function *SF,
1115778fcc77SRafael Espindola                                              GlobalValue *DGV,
1116778fcc77SRafael Espindola                                              bool LinkFromSrc) {
1117778fcc77SRafael Espindola   if (!LinkFromSrc)
1118778fcc77SRafael Espindola     return DGV;
1119b1ed91f3SChris Lattner 
1120f6f121e2SJames Molloy   // If the function is to be lazily linked, don't create it just yet.
1121f6f121e2SJames Molloy   // The ValueMaterializerTy will deal with creating it if it's used.
1122f6f121e2SJames Molloy   if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1123f6f121e2SJames Molloy                SF->hasAvailableExternallyLinkage())) {
1124f6f121e2SJames Molloy     DoNotLinkFromSource.insert(SF);
1125778fcc77SRafael Espindola     return nullptr;
1126dad0a645SDavid Majnemer   }
1127dad0a645SDavid Majnemer 
1128b1ed91f3SChris Lattner   // If there is no linkage to be performed or we are linking from the source,
1129b1ed91f3SChris Lattner   // bring SF over.
1130778fcc77SRafael Espindola   return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(),
1131778fcc77SRafael Espindola                           SF->getName(), DstM);
1132361e513dSReid Spencer }
1133361e513dSReid Spencer 
113418c89411SRafael Espindola /// Set up prototypes for any aliases that come over from the source module.
1135778fcc77SRafael Espindola GlobalValue *ModuleLinker::linkGlobalAliasProto(const GlobalAlias *SGA,
1136778fcc77SRafael Espindola                                                 GlobalValue *DGV,
1137778fcc77SRafael Espindola                                                 bool LinkFromSrc) {
1138778fcc77SRafael Espindola   if (!LinkFromSrc)
1139778fcc77SRafael Espindola     return DGV;
1140dad0a645SDavid Majnemer 
1141b1ed91f3SChris Lattner   // If there is no linkage to be performed or we're linking from the source,
1142b1ed91f3SChris Lattner   // bring over SGA.
11434fe0094fSRafael Espindola   auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
1144778fcc77SRafael Espindola   return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
114583705658SRafael Espindola                              SGA->getLinkage(), SGA->getName(), DstM);
1146b1ed91f3SChris Lattner }
1147b1ed91f3SChris Lattner 
11483e8bc6a8SRafael Espindola static void getArrayElements(const Constant *C,
11493e8bc6a8SRafael Espindola                              SmallVectorImpl<Constant *> &Dest) {
11506705883aSChris Lattner   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
115100245f42SChris Lattner 
11526705883aSChris Lattner   for (unsigned i = 0; i != NumElements; ++i)
11536705883aSChris Lattner     Dest.push_back(C->getAggregateElement(i));
115400245f42SChris Lattner }
115500245f42SChris Lattner 
1156b1ed91f3SChris Lattner void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1157b1ed91f3SChris Lattner   // Merge the initializer.
1158d31dc048SRafael Espindola   SmallVector<Constant *, 16> DstElements;
1159d31dc048SRafael Espindola   getArrayElements(AVI.DstInit, DstElements);
1160b1ed91f3SChris Lattner 
1161d31dc048SRafael Espindola   SmallVector<Constant *, 16> SrcElements;
1162d31dc048SRafael Espindola   getArrayElements(AVI.SrcInit, SrcElements);
116300245f42SChris Lattner 
1164b1ed91f3SChris Lattner   ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1165d31dc048SRafael Espindola 
1166d31dc048SRafael Espindola   StringRef Name = AVI.NewGV->getName();
1167d31dc048SRafael Espindola   bool IsNewStructor =
1168d31dc048SRafael Espindola       (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1169d31dc048SRafael Espindola       cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1170d31dc048SRafael Espindola 
1171d31dc048SRafael Espindola   for (auto *V : SrcElements) {
1172d31dc048SRafael Espindola     if (IsNewStructor) {
1173d31dc048SRafael Espindola       Constant *Key = V->getAggregateElement(2);
1174d31dc048SRafael Espindola       if (DoNotLinkFromSource.count(Key))
1175d31dc048SRafael Espindola         continue;
1176d31dc048SRafael Espindola     }
1177d31dc048SRafael Espindola     DstElements.push_back(
1178d31dc048SRafael Espindola         MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1179d31dc048SRafael Espindola   }
1180d31dc048SRafael Espindola   if (IsNewStructor) {
1181d31dc048SRafael Espindola     NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1182d31dc048SRafael Espindola     AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1183d31dc048SRafael Espindola   }
1184d31dc048SRafael Espindola 
1185d31dc048SRafael Espindola   AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1186b1ed91f3SChris Lattner }
1187b1ed91f3SChris Lattner 
118818c89411SRafael Espindola /// Update the initializers in the Dest module now that all globals that may be
118918c89411SRafael Espindola /// referenced are in Dest.
1190b1ed91f3SChris Lattner void ModuleLinker::linkGlobalInits() {
1191b1ed91f3SChris Lattner   // Loop over all of the globals in the src module, mapping them over as we go
1192b1ed91f3SChris Lattner   for (Module::const_global_iterator I = SrcM->global_begin(),
1193b1ed91f3SChris Lattner        E = SrcM->global_end(); I != E; ++I) {
1194cbb91408STanya Lattner 
1195cbb91408STanya Lattner     // Only process initialized GV's or ones not already in dest.
1196cbb91408STanya Lattner     if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1197b1ed91f3SChris Lattner 
1198b1ed91f3SChris Lattner     // Grab destination global variable.
1199b1ed91f3SChris Lattner     GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1200b1ed91f3SChris Lattner     // Figure out what the initializer looks like in the dest module.
1201b1ed91f3SChris Lattner     DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
1202f6f121e2SJames Molloy                                  RF_None, &TypeMap, &ValMaterializer));
1203b1ed91f3SChris Lattner   }
1204b1ed91f3SChris Lattner }
1205b1ed91f3SChris Lattner 
120618c89411SRafael Espindola /// Copy the source function over into the dest function and fix up references
120718c89411SRafael Espindola /// to values. At this point we know that Dest is an external function, and
120818c89411SRafael Espindola /// that Src is not.
1209b1ed91f3SChris Lattner void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1210b1ed91f3SChris Lattner   assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
1211361e513dSReid Spencer 
12127391dde1SChris Lattner   // Go through and convert function arguments over, remembering the mapping.
1213b1ed91f3SChris Lattner   Function::arg_iterator DI = Dst->arg_begin();
1214531f9e92SChris Lattner   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1215361e513dSReid Spencer        I != E; ++I, ++DI) {
1216b1ed91f3SChris Lattner     DI->setName(I->getName());  // Copy the name over.
1217361e513dSReid Spencer 
1218b1ed91f3SChris Lattner     // Add a mapping to our mapping.
121966a6271cSAnton Korobeynikov     ValueMap[I] = DI;
1220361e513dSReid Spencer   }
1221361e513dSReid Spencer 
12222f0557d0SChris Lattner   // Splice the body of the source function into the dest function.
1223b1ed91f3SChris Lattner   Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
1224361e513dSReid Spencer 
1225361e513dSReid Spencer   // At this point, all of the instructions and values of the function are now
1226361e513dSReid Spencer   // copied over.  The only problem is that they are still referencing values in
1227361e513dSReid Spencer   // the Source function as operands.  Loop through all of the operands of the
122843f8d164SChris Lattner   // functions and patch them up to point to the local versions.
1229b1ed91f3SChris Lattner   for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
123043f8d164SChris Lattner     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
12319f8eff31SRafael Espindola       RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap,
12329f8eff31SRafael Espindola                        &ValMaterializer);
1233cbb91408STanya Lattner 
12347391dde1SChris Lattner   // There is no need to map the arguments anymore.
123544ab8aefSChris Lattner   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
123644ab8aefSChris Lattner        I != E; ++I)
12373aaaa0b2SReid Spencer     ValueMap.erase(I);
1238cbb91408STanya Lattner 
1239361e513dSReid Spencer }
1240361e513dSReid Spencer 
124118c89411SRafael Espindola /// Insert all of the aliases in Src into the Dest module.
1242b1ed91f3SChris Lattner void ModuleLinker::linkAliasBodies() {
1243b1ed91f3SChris Lattner   for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
1244cbb91408STanya Lattner        I != E; ++I) {
1245cbb91408STanya Lattner     if (DoNotLinkFromSource.count(I))
1246cbb91408STanya Lattner       continue;
1247b1ed91f3SChris Lattner     if (Constant *Aliasee = I->getAliasee()) {
1248b1ed91f3SChris Lattner       GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
12496b238633SRafael Espindola       Constant *Val =
12506b238633SRafael Espindola           MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
125164c1e180SRafael Espindola       DA->setAliasee(Val);
12522c4a34aeSDavid Chisnall     }
1253b1ed91f3SChris Lattner   }
1254cbb91408STanya Lattner }
1255b1ed91f3SChris Lattner 
125618c89411SRafael Espindola /// Insert all of the named MDNodes in Src into the Dest module.
1257b1ed91f3SChris Lattner void ModuleLinker::linkNamedMDNodes() {
125866f02413SBill Wendling   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1259b1ed91f3SChris Lattner   for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1260b1ed91f3SChris Lattner        E = SrcM->named_metadata_end(); I != E; ++I) {
126166f02413SBill Wendling     // Don't link module flags here. Do them separately.
126266f02413SBill Wendling     if (&*I == SrcModFlags) continue;
1263b1ed91f3SChris Lattner     NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1264b1ed91f3SChris Lattner     // Add Src elements into Dest node.
1265b1ed91f3SChris Lattner     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1266b1ed91f3SChris Lattner       DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
1267f6f121e2SJames Molloy                                    RF_None, &TypeMap, &ValMaterializer));
1268b1ed91f3SChris Lattner   }
1269b1ed91f3SChris Lattner }
1270b1ed91f3SChris Lattner 
127118c89411SRafael Espindola /// Merge the linker flags in Src into the Dest module.
127266f02413SBill Wendling bool ModuleLinker::linkModuleFlagsMetadata() {
12730ec72bbcSDaniel Dunbar   // If the source module has no module flags, we are done.
127466f02413SBill Wendling   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
127566f02413SBill Wendling   if (!SrcModFlags) return false;
127666f02413SBill Wendling 
127766f02413SBill Wendling   // If the destination module doesn't have module flags yet, then just copy
127866f02413SBill Wendling   // over the source module's flags.
12790ec72bbcSDaniel Dunbar   NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
128066f02413SBill Wendling   if (DstModFlags->getNumOperands() == 0) {
128166f02413SBill Wendling     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
128266f02413SBill Wendling       DstModFlags->addOperand(SrcModFlags->getOperand(I));
128366f02413SBill Wendling 
128466f02413SBill Wendling     return false;
128566f02413SBill Wendling   }
128666f02413SBill Wendling 
12870ec72bbcSDaniel Dunbar   // First build a map of the existing module flags and requirements.
12880ec72bbcSDaniel Dunbar   DenseMap<MDString*, MDNode*> Flags;
12890ec72bbcSDaniel Dunbar   SmallSetVector<MDNode*, 16> Requirements;
12900ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1291de36e804SDuncan P. N. Exon Smith     MDNode *Op = DstModFlags->getOperand(I);
12920ec72bbcSDaniel Dunbar     ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
12930ec72bbcSDaniel Dunbar     MDString *ID = cast<MDString>(Op->getOperand(1));
12940ec72bbcSDaniel Dunbar 
12950ec72bbcSDaniel Dunbar     if (Behavior->getZExtValue() == Module::Require) {
12960ec72bbcSDaniel Dunbar       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
12970ec72bbcSDaniel Dunbar     } else {
12980ec72bbcSDaniel Dunbar       Flags[ID] = Op;
12990ec72bbcSDaniel Dunbar     }
13000ec72bbcSDaniel Dunbar   }
13010ec72bbcSDaniel Dunbar 
13020ec72bbcSDaniel Dunbar   // Merge in the flags from the source module, and also collect its set of
13030ec72bbcSDaniel Dunbar   // requirements.
130466f02413SBill Wendling   bool HasErr = false;
13050ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1306de36e804SDuncan P. N. Exon Smith     MDNode *SrcOp = SrcModFlags->getOperand(I);
13070ec72bbcSDaniel Dunbar     ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
13080ec72bbcSDaniel Dunbar     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
13090ec72bbcSDaniel Dunbar     MDNode *DstOp = Flags.lookup(ID);
13100ec72bbcSDaniel Dunbar     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
131166f02413SBill Wendling 
13120ec72bbcSDaniel Dunbar     // If this is a requirement, add it and continue.
13130ec72bbcSDaniel Dunbar     if (SrcBehaviorValue == Module::Require) {
13140ec72bbcSDaniel Dunbar       // If the destination module does not already have this requirement, add
13150ec72bbcSDaniel Dunbar       // it.
13160ec72bbcSDaniel Dunbar       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
13170ec72bbcSDaniel Dunbar         DstModFlags->addOperand(SrcOp);
13180ec72bbcSDaniel Dunbar       }
13190ec72bbcSDaniel Dunbar       continue;
13200ec72bbcSDaniel Dunbar     }
132166f02413SBill Wendling 
13220ec72bbcSDaniel Dunbar     // If there is no existing flag with this ID, just add it.
13230ec72bbcSDaniel Dunbar     if (!DstOp) {
13240ec72bbcSDaniel Dunbar       Flags[ID] = SrcOp;
13250ec72bbcSDaniel Dunbar       DstModFlags->addOperand(SrcOp);
13260ec72bbcSDaniel Dunbar       continue;
13270ec72bbcSDaniel Dunbar     }
132866f02413SBill Wendling 
13290ec72bbcSDaniel Dunbar     // Otherwise, perform a merge.
13300ec72bbcSDaniel Dunbar     ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
13310ec72bbcSDaniel Dunbar     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
13320ec72bbcSDaniel Dunbar 
13330ec72bbcSDaniel Dunbar     // If either flag has override behavior, handle it first.
13340ec72bbcSDaniel Dunbar     if (DstBehaviorValue == Module::Override) {
13350ec72bbcSDaniel Dunbar       // Diagnose inconsistent flags which both have override behavior.
13360ec72bbcSDaniel Dunbar       if (SrcBehaviorValue == Module::Override &&
13370ec72bbcSDaniel Dunbar           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
13380ec72bbcSDaniel Dunbar         HasErr |= emitError("linking module flags '" + ID->getString() +
13390ec72bbcSDaniel Dunbar                             "': IDs have conflicting override values");
13400ec72bbcSDaniel Dunbar       }
13410ec72bbcSDaniel Dunbar       continue;
13420ec72bbcSDaniel Dunbar     } else if (SrcBehaviorValue == Module::Override) {
13430ec72bbcSDaniel Dunbar       // Update the destination flag to that of the source.
13440ec72bbcSDaniel Dunbar       DstOp->replaceOperandWith(0, SrcBehavior);
13450ec72bbcSDaniel Dunbar       DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
13460ec72bbcSDaniel Dunbar       continue;
13470ec72bbcSDaniel Dunbar     }
13480ec72bbcSDaniel Dunbar 
13490ec72bbcSDaniel Dunbar     // Diagnose inconsistent merge behavior types.
13500ec72bbcSDaniel Dunbar     if (SrcBehaviorValue != DstBehaviorValue) {
13510ec72bbcSDaniel Dunbar       HasErr |= emitError("linking module flags '" + ID->getString() +
135266f02413SBill Wendling                           "': IDs have conflicting behaviors");
13530ec72bbcSDaniel Dunbar       continue;
135466f02413SBill Wendling     }
135566f02413SBill Wendling 
13560ec72bbcSDaniel Dunbar     // Perform the merge for standard behavior types.
13570ec72bbcSDaniel Dunbar     switch (SrcBehaviorValue) {
13580ec72bbcSDaniel Dunbar     case Module::Require:
13592a30d788SCraig Topper     case Module::Override: llvm_unreachable("not possible");
13600ec72bbcSDaniel Dunbar     case Module::Error: {
13610ec72bbcSDaniel Dunbar       // Emit an error if the values differ.
13620ec72bbcSDaniel Dunbar       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
13630ec72bbcSDaniel Dunbar         HasErr |= emitError("linking module flags '" + ID->getString() +
13640ec72bbcSDaniel Dunbar                             "': IDs have conflicting values");
136566f02413SBill Wendling       }
13660ec72bbcSDaniel Dunbar       continue;
136766f02413SBill Wendling     }
13680ec72bbcSDaniel Dunbar     case Module::Warning: {
13690ec72bbcSDaniel Dunbar       // Emit a warning if the values differ.
13700ec72bbcSDaniel Dunbar       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1371d12b4a33SRafael Espindola         emitWarning("linking module flags '" + ID->getString() +
1372d12b4a33SRafael Espindola                     "': IDs have conflicting values");
1373e17f3708SEli Bendersky       }
13740ec72bbcSDaniel Dunbar       continue;
13750ec72bbcSDaniel Dunbar     }
1376d77d9fb0SDaniel Dunbar     case Module::Append: {
1377d77d9fb0SDaniel Dunbar       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1378d77d9fb0SDaniel Dunbar       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1379d77d9fb0SDaniel Dunbar       unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1380d77d9fb0SDaniel Dunbar       Value **VP, **Values = VP = new Value*[NumOps];
1381d77d9fb0SDaniel Dunbar       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1382d77d9fb0SDaniel Dunbar         *VP = DstValue->getOperand(i);
1383d77d9fb0SDaniel Dunbar       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1384d77d9fb0SDaniel Dunbar         *VP = SrcValue->getOperand(i);
1385d77d9fb0SDaniel Dunbar       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1386d77d9fb0SDaniel Dunbar                                                ArrayRef<Value*>(Values,
1387d77d9fb0SDaniel Dunbar                                                                 NumOps)));
1388d77d9fb0SDaniel Dunbar       delete[] Values;
1389d77d9fb0SDaniel Dunbar       break;
1390d77d9fb0SDaniel Dunbar     }
1391d77d9fb0SDaniel Dunbar     case Module::AppendUnique: {
1392d77d9fb0SDaniel Dunbar       SmallSetVector<Value*, 16> Elts;
1393d77d9fb0SDaniel Dunbar       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1394d77d9fb0SDaniel Dunbar       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1395d77d9fb0SDaniel Dunbar       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1396d77d9fb0SDaniel Dunbar         Elts.insert(DstValue->getOperand(i));
1397d77d9fb0SDaniel Dunbar       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1398d77d9fb0SDaniel Dunbar         Elts.insert(SrcValue->getOperand(i));
1399d77d9fb0SDaniel Dunbar       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1400d77d9fb0SDaniel Dunbar                                                ArrayRef<Value*>(Elts.begin(),
1401d77d9fb0SDaniel Dunbar                                                                 Elts.end())));
1402d77d9fb0SDaniel Dunbar       break;
1403d77d9fb0SDaniel Dunbar     }
140466f02413SBill Wendling     }
140566f02413SBill Wendling   }
140666f02413SBill Wendling 
14070ec72bbcSDaniel Dunbar   // Check all of the requirements.
14080ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
14090ec72bbcSDaniel Dunbar     MDNode *Requirement = Requirements[I];
14100ec72bbcSDaniel Dunbar     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
14110ec72bbcSDaniel Dunbar     Value *ReqValue = Requirement->getOperand(1);
14120ec72bbcSDaniel Dunbar 
14130ec72bbcSDaniel Dunbar     MDNode *Op = Flags[Flag];
14140ec72bbcSDaniel Dunbar     if (!Op || Op->getOperand(2) != ReqValue) {
14150ec72bbcSDaniel Dunbar       HasErr |= emitError("linking module flags '" + Flag->getString() +
14169273b539SBill Wendling                           "': does not have the required value");
14170ec72bbcSDaniel Dunbar       continue;
141866f02413SBill Wendling     }
141966f02413SBill Wendling   }
142066f02413SBill Wendling 
142166f02413SBill Wendling   return HasErr;
142266f02413SBill Wendling }
142366f02413SBill Wendling 
1424b1ed91f3SChris Lattner bool ModuleLinker::run() {
142566f02413SBill Wendling   assert(DstM && "Null destination module");
142666f02413SBill Wendling   assert(SrcM && "Null source module");
1427b1ed91f3SChris Lattner 
1428b1ed91f3SChris Lattner   // Inherit the target data from the source module if the destination module
1429b1ed91f3SChris Lattner   // doesn't have one already.
1430f863ee29SRafael Espindola   if (!DstM->getDataLayout() && SrcM->getDataLayout())
1431b1ed91f3SChris Lattner     DstM->setDataLayout(SrcM->getDataLayout());
1432b1ed91f3SChris Lattner 
1433b1ed91f3SChris Lattner   // Copy the target triple from the source to dest if the dest's is empty.
1434b1ed91f3SChris Lattner   if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1435b1ed91f3SChris Lattner     DstM->setTargetTriple(SrcM->getTargetTriple());
1436b1ed91f3SChris Lattner 
1437f863ee29SRafael Espindola   if (SrcM->getDataLayout() && DstM->getDataLayout() &&
1438ae593f15SRafael Espindola       *SrcM->getDataLayout() != *DstM->getDataLayout()) {
1439d12b4a33SRafael Espindola     emitWarning("Linking two modules of different data layouts: '" +
1440d12b4a33SRafael Espindola                 SrcM->getModuleIdentifier() + "' is '" +
1441d12b4a33SRafael Espindola                 SrcM->getDataLayoutStr() + "' whereas '" +
1442d12b4a33SRafael Espindola                 DstM->getModuleIdentifier() + "' is '" +
1443d12b4a33SRafael Espindola                 DstM->getDataLayoutStr() + "'\n");
1444e17f3708SEli Bendersky   }
1445b1ed91f3SChris Lattner   if (!SrcM->getTargetTriple().empty() &&
1446b1ed91f3SChris Lattner       DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1447d12b4a33SRafael Espindola     emitWarning("Linking two modules of different target triples: " +
1448d12b4a33SRafael Espindola                 SrcM->getModuleIdentifier() + "' is '" +
1449d12b4a33SRafael Espindola                 SrcM->getTargetTriple() + "' whereas '" +
1450d12b4a33SRafael Espindola                 DstM->getModuleIdentifier() + "' is '" +
1451d12b4a33SRafael Espindola                 DstM->getTargetTriple() + "'\n");
1452e17f3708SEli Bendersky   }
1453b1ed91f3SChris Lattner 
1454b1ed91f3SChris Lattner   // Append the module inline asm string.
1455b1ed91f3SChris Lattner   if (!SrcM->getModuleInlineAsm().empty()) {
1456b1ed91f3SChris Lattner     if (DstM->getModuleInlineAsm().empty())
1457b1ed91f3SChris Lattner       DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1458b1ed91f3SChris Lattner     else
1459b1ed91f3SChris Lattner       DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1460b1ed91f3SChris Lattner                                SrcM->getModuleInlineAsm());
1461b1ed91f3SChris Lattner   }
1462b1ed91f3SChris Lattner 
1463b1ed91f3SChris Lattner   // Loop over all of the linked values to compute type mappings.
1464b1ed91f3SChris Lattner   computeTypeMapping();
1465b1ed91f3SChris Lattner 
1466dad0a645SDavid Majnemer   ComdatsChosen.clear();
14675106ce78SDavid Blaikie   for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
1468dad0a645SDavid Majnemer     const Comdat &C = SMEC.getValue();
1469dad0a645SDavid Majnemer     if (ComdatsChosen.count(&C))
1470dad0a645SDavid Majnemer       continue;
1471dad0a645SDavid Majnemer     Comdat::SelectionKind SK;
1472dad0a645SDavid Majnemer     bool LinkFromSrc;
1473dad0a645SDavid Majnemer     if (getComdatResult(&C, SK, LinkFromSrc))
1474dad0a645SDavid Majnemer       return true;
1475dad0a645SDavid Majnemer     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1476dad0a645SDavid Majnemer   }
1477dad0a645SDavid Majnemer 
147809d84addSDuncan P. N. Exon Smith   // Upgrade mismatched global arrays.
147909d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobals();
148009d84addSDuncan P. N. Exon Smith 
1481b1ed91f3SChris Lattner   // Insert all of the globals in src into the DstM module... without linking
1482b1ed91f3SChris Lattner   // initializers (which could refer to functions not yet mapped over).
1483b1ed91f3SChris Lattner   for (Module::global_iterator I = SrcM->global_begin(),
1484b1ed91f3SChris Lattner        E = SrcM->global_end(); I != E; ++I)
1485778fcc77SRafael Espindola     if (linkGlobalValueProto(I))
1486b1ed91f3SChris Lattner       return true;
1487b1ed91f3SChris Lattner 
1488b1ed91f3SChris Lattner   // Link the functions together between the two modules, without doing function
1489b1ed91f3SChris Lattner   // bodies... this just adds external function prototypes to the DstM
1490b1ed91f3SChris Lattner   // function...  We do this so that when we begin processing function bodies,
1491b1ed91f3SChris Lattner   // all of the global values that may be referenced are available in our
1492b1ed91f3SChris Lattner   // ValueMap.
1493b1ed91f3SChris Lattner   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1494778fcc77SRafael Espindola     if (linkGlobalValueProto(I))
1495b1ed91f3SChris Lattner       return true;
1496b1ed91f3SChris Lattner 
1497b1ed91f3SChris Lattner   // If there were any aliases, link them now.
1498b1ed91f3SChris Lattner   for (Module::alias_iterator I = SrcM->alias_begin(),
1499b1ed91f3SChris Lattner        E = SrcM->alias_end(); I != E; ++I)
1500778fcc77SRafael Espindola     if (linkGlobalValueProto(I))
1501b1ed91f3SChris Lattner       return true;
1502b1ed91f3SChris Lattner 
1503b1ed91f3SChris Lattner   for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1504b1ed91f3SChris Lattner     linkAppendingVarInit(AppendingVars[i]);
1505b1ed91f3SChris Lattner 
1506b1ed91f3SChris Lattner   // Link in the function bodies that are defined in the source module into
1507b1ed91f3SChris Lattner   // DstM.
1508b1ed91f3SChris Lattner   for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1509ea166d44STanya Lattner     // Skip if not linking from source.
1510ea166d44STanya Lattner     if (DoNotLinkFromSource.count(SF)) continue;
1511ea166d44STanya Lattner 
15123fa50f9bSPeter Collingbourne     Function *DF = cast<Function>(ValueMap[SF]);
151351d2de7bSPeter Collingbourne 
15143fa50f9bSPeter Collingbourne     // Link in the prefix data.
151551d2de7bSPeter Collingbourne     if (SF->hasPrefixData())
15163fa50f9bSPeter Collingbourne       DF->setPrefixData(MapValue(
15173fa50f9bSPeter Collingbourne           SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
151851d2de7bSPeter Collingbourne 
151951d2de7bSPeter Collingbourne     // Link in the prologue data.
152051d2de7bSPeter Collingbourne     if (SF->hasPrologueData())
152151d2de7bSPeter Collingbourne       DF->setPrologueData(MapValue(
152251d2de7bSPeter Collingbourne           SF->getPrologueData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
15233fa50f9bSPeter Collingbourne 
1524d4bcefc7SRafael Espindola     // Materialize if needed.
1525d12b4a33SRafael Espindola     if (std::error_code EC = SF->materialize())
1526d12b4a33SRafael Espindola       return emitError(EC.message());
1527b1ed91f3SChris Lattner 
1528d4bcefc7SRafael Espindola     // Skip if no body (function is external).
1529d4bcefc7SRafael Espindola     if (SF->isDeclaration())
1530d4bcefc7SRafael Espindola       continue;
1531d4bcefc7SRafael Espindola 
15323fa50f9bSPeter Collingbourne     linkFunctionBody(DF, SF);
153300623787SBill Wendling     SF->Dematerialize();
1534b1ed91f3SChris Lattner   }
1535b1ed91f3SChris Lattner 
1536b1ed91f3SChris Lattner   // Resolve all uses of aliases with aliasees.
1537b1ed91f3SChris Lattner   linkAliasBodies();
1538b1ed91f3SChris Lattner 
153966f02413SBill Wendling   // Remap all of the named MDNodes in Src into the DstM module. We do this
15406ddbb2e2SDevang Patel   // after linking GlobalValues so that MDNodes that reference GlobalValues
15416ddbb2e2SDevang Patel   // are properly remapped.
15426ddbb2e2SDevang Patel   linkNamedMDNodes();
15436ddbb2e2SDevang Patel 
154466f02413SBill Wendling   // Merge the module flags into the DstM module.
154566f02413SBill Wendling   if (linkModuleFlagsMetadata())
154666f02413SBill Wendling     return true;
154766f02413SBill Wendling 
154891686d6dSBill Wendling   // Update the initializers in the DstM module now that all globals that may
154991686d6dSBill Wendling   // be referenced are in DstM.
155091686d6dSBill Wendling   linkGlobalInits();
155191686d6dSBill Wendling 
15520a48b877STanya Lattner   // Process vector of lazily linked in functions.
15530a48b877STanya Lattner   bool LinkedInAnyFunctions;
15540a48b877STanya Lattner   do {
15550a48b877STanya Lattner     LinkedInAnyFunctions = false;
15560a48b877STanya Lattner 
1557fa228782SBill Wendling     for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
15580a48b877STanya Lattner         E = LazilyLinkFunctions.end(); I != E; ++I) {
1559f6f121e2SJames Molloy       Function *SF = *I;
1560f6f121e2SJames Molloy       if (!SF)
15610a48b877STanya Lattner         continue;
15620a48b877STanya Lattner 
1563fa228782SBill Wendling       Function *DF = cast<Function>(ValueMap[SF]);
15643fa50f9bSPeter Collingbourne       if (SF->hasPrefixData()) {
15653fa50f9bSPeter Collingbourne         // Link in the prefix data.
15663fa50f9bSPeter Collingbourne         DF->setPrefixData(MapValue(SF->getPrefixData(),
15673fa50f9bSPeter Collingbourne                                    ValueMap,
15683fa50f9bSPeter Collingbourne                                    RF_None,
15693fa50f9bSPeter Collingbourne                                    &TypeMap,
15703fa50f9bSPeter Collingbourne                                    &ValMaterializer));
15713fa50f9bSPeter Collingbourne       }
15720a48b877STanya Lattner 
1573d4bcefc7SRafael Espindola       // Materialize if needed.
1574d12b4a33SRafael Espindola       if (std::error_code EC = SF->materialize())
1575d12b4a33SRafael Espindola         return emitError(EC.message());
15760a48b877STanya Lattner 
1577d4bcefc7SRafael Espindola       // Skip if no body (function is external).
1578d4bcefc7SRafael Espindola       if (SF->isDeclaration())
1579d4bcefc7SRafael Espindola         continue;
1580d4bcefc7SRafael Espindola 
1581f6f121e2SJames Molloy       // Erase from vector *before* the function body is linked - linkFunctionBody could
1582f6f121e2SJames Molloy       // invalidate I.
1583f6f121e2SJames Molloy       LazilyLinkFunctions.erase(I);
1584f6f121e2SJames Molloy 
15850a48b877STanya Lattner       // Link in function body.
15860a48b877STanya Lattner       linkFunctionBody(DF, SF);
158700623787SBill Wendling       SF->Dematerialize();
15880a48b877STanya Lattner 
15890a48b877STanya Lattner       // Set flag to indicate we may have more functions to lazily link in
15900a48b877STanya Lattner       // since we linked in a function.
15910a48b877STanya Lattner       LinkedInAnyFunctions = true;
1592f6f121e2SJames Molloy       break;
15930a48b877STanya Lattner     }
15940a48b877STanya Lattner   } while (LinkedInAnyFunctions);
15950a48b877STanya Lattner 
15962609888fSAnton Korobeynikov   return false;
15972609888fSAnton Korobeynikov }
1598361e513dSReid Spencer 
1599*31ad468dSRafael Espindola Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1600*31ad468dSRafael Espindola     : ETypes(E), IsPacked(P) {}
1601*31ad468dSRafael Espindola 
1602*31ad468dSRafael Espindola Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1603*31ad468dSRafael Espindola     : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1604*31ad468dSRafael Espindola 
1605*31ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1606*31ad468dSRafael Espindola   if (IsPacked != That.IsPacked)
1607*31ad468dSRafael Espindola     return false;
1608*31ad468dSRafael Espindola   if (ETypes != That.ETypes)
1609*31ad468dSRafael Espindola     return false;
1610*31ad468dSRafael Espindola   return true;
1611*31ad468dSRafael Espindola }
1612*31ad468dSRafael Espindola 
1613*31ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1614*31ad468dSRafael Espindola   return !this->operator==(That);
1615*31ad468dSRafael Espindola }
1616*31ad468dSRafael Espindola 
1617*31ad468dSRafael Espindola StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
1618*31ad468dSRafael Espindola   return DenseMapInfo<StructType *>::getEmptyKey();
1619*31ad468dSRafael Espindola }
1620*31ad468dSRafael Espindola 
1621*31ad468dSRafael Espindola StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
1622*31ad468dSRafael Espindola   return DenseMapInfo<StructType *>::getTombstoneKey();
1623*31ad468dSRafael Espindola }
1624*31ad468dSRafael Espindola 
1625*31ad468dSRafael Espindola unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1626*31ad468dSRafael Espindola   return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1627*31ad468dSRafael Espindola                       Key.IsPacked);
1628*31ad468dSRafael Espindola }
1629*31ad468dSRafael Espindola 
1630*31ad468dSRafael Espindola unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1631*31ad468dSRafael Espindola   return getHashValue(KeyTy(ST));
1632*31ad468dSRafael Espindola }
1633*31ad468dSRafael Espindola 
1634*31ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1635*31ad468dSRafael Espindola                                         const StructType *RHS) {
1636*31ad468dSRafael Espindola   if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1637*31ad468dSRafael Espindola     return false;
1638*31ad468dSRafael Espindola   return LHS == KeyTy(RHS);
1639*31ad468dSRafael Espindola }
1640*31ad468dSRafael Espindola 
1641*31ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
1642*31ad468dSRafael Espindola                                         const StructType *RHS) {
1643*31ad468dSRafael Espindola   if (RHS == getEmptyKey())
1644*31ad468dSRafael Espindola     return LHS == getEmptyKey();
1645*31ad468dSRafael Espindola 
1646*31ad468dSRafael Espindola   if (RHS == getTombstoneKey())
1647*31ad468dSRafael Espindola     return LHS == getTombstoneKey();
1648*31ad468dSRafael Espindola 
1649*31ad468dSRafael Espindola   return KeyTy(LHS) == KeyTy(RHS);
1650*31ad468dSRafael Espindola }
1651*31ad468dSRafael Espindola 
1652*31ad468dSRafael Espindola void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1653*31ad468dSRafael Espindola   assert(!Ty->isOpaque());
1654*31ad468dSRafael Espindola   bool &Entry = NonOpaqueStructTypes[Ty];
1655*31ad468dSRafael Espindola   Entry = true;
1656*31ad468dSRafael Espindola }
1657*31ad468dSRafael Espindola 
1658*31ad468dSRafael Espindola void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1659*31ad468dSRafael Espindola   assert(Ty->isOpaque());
1660*31ad468dSRafael Espindola   OpaqueStructTypes.insert(Ty);
1661*31ad468dSRafael Espindola }
1662*31ad468dSRafael Espindola 
1663*31ad468dSRafael Espindola StructType *
1664*31ad468dSRafael Espindola Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1665*31ad468dSRafael Espindola                                                bool IsPacked) {
1666*31ad468dSRafael Espindola   Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1667*31ad468dSRafael Espindola   auto I = NonOpaqueStructTypes.find_as(Key);
1668*31ad468dSRafael Espindola   if (I == NonOpaqueStructTypes.end())
1669*31ad468dSRafael Espindola     return nullptr;
1670*31ad468dSRafael Espindola   return I->first;
1671*31ad468dSRafael Espindola }
1672*31ad468dSRafael Espindola 
1673*31ad468dSRafael Espindola bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1674*31ad468dSRafael Espindola   if (Ty->isOpaque())
1675*31ad468dSRafael Espindola     return OpaqueStructTypes.count(Ty);
1676*31ad468dSRafael Espindola   auto I = NonOpaqueStructTypes.find(Ty);
1677*31ad468dSRafael Espindola   if (I == NonOpaqueStructTypes.end())
1678*31ad468dSRafael Espindola     return false;
1679*31ad468dSRafael Espindola   return I->first == Ty;
1680*31ad468dSRafael Espindola }
1681*31ad468dSRafael Espindola 
16825cb9c82aSRafael Espindola void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
16835cb9c82aSRafael Espindola   this->Composite = M;
16845cb9c82aSRafael Espindola   this->DiagnosticHandler = DiagnosticHandler;
1685a4e85e3dSRafael Espindola 
1686a4e85e3dSRafael Espindola   TypeFinder StructTypes;
1687a4e85e3dSRafael Espindola   StructTypes.run(*M, true);
1688*31ad468dSRafael Espindola   for (StructType *Ty : StructTypes) {
1689*31ad468dSRafael Espindola     if (Ty->isOpaque())
1690*31ad468dSRafael Espindola       IdentifiedStructTypes.addOpaque(Ty);
1691*31ad468dSRafael Espindola     else
1692*31ad468dSRafael Espindola       IdentifiedStructTypes.addNonOpaque(Ty);
1693*31ad468dSRafael Espindola   }
1694aa9918aaSRafael Espindola }
16953df61b7bSRafael Espindola 
16965cb9c82aSRafael Espindola Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
16975cb9c82aSRafael Espindola   init(M, DiagnosticHandler);
16985cb9c82aSRafael Espindola }
16995cb9c82aSRafael Espindola 
17005cb9c82aSRafael Espindola Linker::Linker(Module *M) {
17015cb9c82aSRafael Espindola   init(M, [this](const DiagnosticInfo &DI) {
17025cb9c82aSRafael Espindola     Composite->getContext().diagnose(DI);
17035cb9c82aSRafael Espindola   });
17045cb9c82aSRafael Espindola }
17055cb9c82aSRafael Espindola 
17063df61b7bSRafael Espindola Linker::~Linker() {
17073df61b7bSRafael Espindola }
17083df61b7bSRafael Espindola 
170991e6f6e1SBill Wendling void Linker::deleteModule() {
171091e6f6e1SBill Wendling   delete Composite;
17112617dcceSCraig Topper   Composite = nullptr;
171291e6f6e1SBill Wendling }
171391e6f6e1SBill Wendling 
17149f8eff31SRafael Espindola bool Linker::linkInModule(Module *Src) {
1715a4e85e3dSRafael Espindola   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
1716a4e85e3dSRafael Espindola                          DiagnosticHandler);
1717d12b4a33SRafael Espindola   return TheLinker.run();
17183df61b7bSRafael Espindola }
17193df61b7bSRafael Espindola 
1720b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
1721b1ed91f3SChris Lattner // LinkModules entrypoint.
1722b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
1723b1ed91f3SChris Lattner 
172418c89411SRafael Espindola /// This function links two modules together, with the resulting Dest module
172518c89411SRafael Espindola /// modified to be the composite of the two input modules. If an error occurs,
172618c89411SRafael Espindola /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
172718c89411SRafael Espindola /// Upon failure, the Dest module could be in a modified state, and shouldn't be
172818c89411SRafael Espindola /// relied on to be consistent.
17299f8eff31SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src,
17304160f5d3SRafael Espindola                          DiagnosticHandlerFunction DiagnosticHandler) {
17314160f5d3SRafael Espindola   Linker L(Dest, DiagnosticHandler);
17329f8eff31SRafael Espindola   return L.linkInModule(Src);
17334160f5d3SRafael Espindola }
17344160f5d3SRafael Espindola 
17359f8eff31SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src) {
1736287f18b4SRafael Espindola   Linker L(Dest);
17379f8eff31SRafael Espindola   return L.linkInModule(Src);
1738361e513dSReid Spencer }
1739a3aeb980SBill Wendling 
1740a3aeb980SBill Wendling //===----------------------------------------------------------------------===//
1741a3aeb980SBill Wendling // C API.
1742a3aeb980SBill Wendling //===----------------------------------------------------------------------===//
1743a3aeb980SBill Wendling 
1744a3aeb980SBill Wendling LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1745a3aeb980SBill Wendling                          LLVMLinkerMode Mode, char **OutMessages) {
174698ab63ceSRafael Espindola   Module *D = unwrap(Dest);
174798ab63ceSRafael Espindola   std::string Message;
17484160f5d3SRafael Espindola   raw_string_ostream Stream(Message);
17494160f5d3SRafael Espindola   DiagnosticPrinterRawOStream DP(Stream);
17504160f5d3SRafael Espindola 
17514160f5d3SRafael Espindola   LLVMBool Result = Linker::LinkModules(
17529f8eff31SRafael Espindola       D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
175398ab63ceSRafael Espindola 
175498ab63ceSRafael Espindola   if (OutMessages && Result)
175598ab63ceSRafael Espindola     *OutMessages = strdup(Message.c_str());
1756a3aeb980SBill Wendling   return Result;
1757a3aeb980SBill Wendling }
1758