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"
1666f02413SBill Wendling #include "llvm/ADT/SetVector.h"
170f7fd36fSEli Bendersky #include "llvm/ADT/SmallString.h"
18c43df518SAkira Hatanaka #include "llvm/ADT/Triple.h"
199fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
20d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticInfo.h"
21d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticPrinter.h"
22d12b4a33SRafael Espindola #include "llvm/IR/LLVMContext.h"
239fb823bbSChandler Carruth #include "llvm/IR/Module.h"
24dcb603feSChandler Carruth #include "llvm/IR/TypeFinder.h"
25cbb91408STanya Lattner #include "llvm/Transforms/Utils/Cloning.h"
26361e513dSReid Spencer using namespace llvm;
27361e513dSReid Spencer 
28b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
29b1ed91f3SChris Lattner // TypeMap implementation.
30b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
31b1ed91f3SChris Lattner 
32b1ed91f3SChris Lattner namespace {
33b1ed91f3SChris Lattner class TypeMapTy : public ValueMapTypeRemapper {
3418c89411SRafael Espindola   /// This is a mapping from a source type to a destination type to use.
35b1ed91f3SChris Lattner   DenseMap<Type *, Type *> MappedTypes;
36b1ed91f3SChris Lattner 
3718c89411SRafael Espindola   /// When checking to see if two subgraphs are isomorphic, we speculatively
3818c89411SRafael Espindola   /// add types to MappedTypes, but keep track of them here in case we need to
3918c89411SRafael Espindola   /// roll back.
40b1ed91f3SChris Lattner   SmallVector<Type *, 16> SpeculativeTypes;
41b1ed91f3SChris Lattner 
42a96f235cSRafael Espindola   SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
43a96f235cSRafael Espindola 
4418c89411SRafael Espindola   /// This is a list of non-opaque structs in the source module that are mapped
4518c89411SRafael Espindola   /// to an opaque struct in the destination module.
465e3bd972SChris Lattner   SmallVector<StructType *, 16> SrcDefinitionsToResolve;
475e3bd972SChris Lattner 
4818c89411SRafael Espindola   /// This is the set of opaque types in the destination modules who are
4918c89411SRafael Espindola   /// getting a body from the source module.
505e3bd972SChris Lattner   SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
51d48b7783SBill Wendling 
528c2cc416SBill Wendling public:
5331ad468dSRafael Espindola   TypeMapTy(Linker::IdentifiedStructTypeSet &DstStructTypesSet)
5431ad468dSRafael Espindola       : DstStructTypesSet(DstStructTypesSet) {}
55aa9918aaSRafael Espindola 
5631ad468dSRafael Espindola   Linker::IdentifiedStructTypeSet &DstStructTypesSet;
5718c89411SRafael Espindola   /// Indicate that the specified type in the destination module is conceptually
5818c89411SRafael Espindola   /// equivalent to the specified type in the source module.
59b1ed91f3SChris Lattner   void addTypeMapping(Type *DstTy, Type *SrcTy);
60b1ed91f3SChris Lattner 
61d2a13a2eSRafael Espindola   /// Produce a body for an opaque type in the dest module from a type
62d2a13a2eSRafael Espindola   /// definition in the source module.
63b1ed91f3SChris Lattner   void linkDefinedTypeBodies();
64b1ed91f3SChris Lattner 
6518c89411SRafael Espindola   /// Return the mapped type to use for the specified input type from the
66b1ed91f3SChris Lattner   /// source module.
67b1ed91f3SChris Lattner   Type *get(Type *SrcTy);
6831ad468dSRafael Espindola   Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
6931ad468dSRafael Espindola 
7031ad468dSRafael Espindola   void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
71b1ed91f3SChris Lattner 
72290e2cc5SRafael Espindola   FunctionType *get(FunctionType *T) {
73290e2cc5SRafael Espindola     return cast<FunctionType>(get((Type *)T));
74290e2cc5SRafael Espindola   }
75b1ed91f3SChris Lattner 
7618c89411SRafael Espindola   /// Dump out the type map for debugging purposes.
77b6af2f36SBill Wendling   void dump() const {
788f14471eSRafael Espindola     for (auto &Pair : MappedTypes) {
79b6af2f36SBill Wendling       dbgs() << "TypeMap: ";
808f14471eSRafael Espindola       Pair.first->print(dbgs());
81b6af2f36SBill Wendling       dbgs() << " => ";
828f14471eSRafael Espindola       Pair.second->print(dbgs());
83b6af2f36SBill Wendling       dbgs() << '\n';
84b6af2f36SBill Wendling     }
85b6af2f36SBill Wendling   }
86b6af2f36SBill Wendling 
87b1ed91f3SChris Lattner private:
88290e2cc5SRafael Espindola   Type *remapType(Type *SrcTy) override { return get(SrcTy); }
89b1ed91f3SChris Lattner 
90b1ed91f3SChris Lattner   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
91b1ed91f3SChris Lattner };
92f00654e3SAlexander Kornienko }
93b1ed91f3SChris Lattner 
94b1ed91f3SChris Lattner void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
953d097410SRafael Espindola   assert(SpeculativeTypes.empty());
96a96f235cSRafael Espindola   assert(SpeculativeDstOpaqueTypes.empty());
973d097410SRafael Espindola 
98b1ed91f3SChris Lattner   // Check to see if these types are recursively isomorphic and establish a
99b1ed91f3SChris Lattner   // mapping between them if so.
100c586eaa1SDuncan P. N. Exon Smith   if (!areTypesIsomorphic(DstTy, SrcTy)) {
101b1ed91f3SChris Lattner     // Oops, they aren't isomorphic.  Just discard this request by rolling out
102b1ed91f3SChris Lattner     // any speculative mappings we've established.
1033d097410SRafael Espindola     for (Type *Ty : SpeculativeTypes)
1043d097410SRafael Espindola       MappedTypes.erase(Ty);
105a96f235cSRafael Espindola 
106a96f235cSRafael Espindola     SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
107a96f235cSRafael Espindola                                    SpeculativeDstOpaqueTypes.size());
108a96f235cSRafael Espindola     for (StructType *Ty : SpeculativeDstOpaqueTypes)
109a96f235cSRafael Espindola       DstResolvedOpaqueTypes.erase(Ty);
11004a74af7SRafael Espindola   } else {
11104a74af7SRafael Espindola     for (Type *Ty : SpeculativeTypes)
11204a74af7SRafael Espindola       if (auto *STy = dyn_cast<StructType>(Ty))
11304a74af7SRafael Espindola         if (STy->hasName())
11404a74af7SRafael Espindola           STy->setName("");
115d48b7783SBill Wendling   }
116b1ed91f3SChris Lattner   SpeculativeTypes.clear();
117a96f235cSRafael Espindola   SpeculativeDstOpaqueTypes.clear();
118b1ed91f3SChris Lattner }
119b1ed91f3SChris Lattner 
12018c89411SRafael Espindola /// Recursively walk this pair of types, returning true if they are isomorphic,
12118c89411SRafael Espindola /// false if they are not.
122b1ed91f3SChris Lattner bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
123b1ed91f3SChris Lattner   // Two types with differing kinds are clearly not isomorphic.
124290e2cc5SRafael Espindola   if (DstTy->getTypeID() != SrcTy->getTypeID())
125290e2cc5SRafael Espindola     return false;
126b1ed91f3SChris Lattner 
127b1ed91f3SChris Lattner   // If we have an entry in the MappedTypes table, then we have our answer.
128b1ed91f3SChris Lattner   Type *&Entry = MappedTypes[SrcTy];
129b1ed91f3SChris Lattner   if (Entry)
130b1ed91f3SChris Lattner     return Entry == DstTy;
131b1ed91f3SChris Lattner 
132b1ed91f3SChris Lattner   // Two identical types are clearly isomorphic.  Remember this
133b1ed91f3SChris Lattner   // non-speculatively.
134b1ed91f3SChris Lattner   if (DstTy == SrcTy) {
135b1ed91f3SChris Lattner     Entry = DstTy;
136361e513dSReid Spencer     return true;
137361e513dSReid Spencer   }
138361e513dSReid Spencer 
139b1ed91f3SChris Lattner   // Okay, we have two types with identical kinds that we haven't seen before.
140361e513dSReid Spencer 
141b1ed91f3SChris Lattner   // If this is an opaque struct type, special case it.
142b1ed91f3SChris Lattner   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
143b1ed91f3SChris Lattner     // Mapping an opaque type to any struct, just keep the dest struct.
144b1ed91f3SChris Lattner     if (SSTy->isOpaque()) {
145b1ed91f3SChris Lattner       Entry = DstTy;
146b1ed91f3SChris Lattner       SpeculativeTypes.push_back(SrcTy);
147b1ed91f3SChris Lattner       return true;
148361e513dSReid Spencer     }
149b1ed91f3SChris Lattner 
1505e3bd972SChris Lattner     // Mapping a non-opaque source type to an opaque dest.  If this is the first
1515e3bd972SChris Lattner     // type that we're mapping onto this destination type then we succeed.  Keep
152a96f235cSRafael Espindola     // the dest, but fill it in later. If this is the second (different) type
153a96f235cSRafael Espindola     // that we're trying to map onto the same opaque type then we fail.
154b1ed91f3SChris Lattner     if (cast<StructType>(DstTy)->isOpaque()) {
1555e3bd972SChris Lattner       // We can only map one source type onto the opaque destination type.
15670573dcdSDavid Blaikie       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
1575e3bd972SChris Lattner         return false;
1585e3bd972SChris Lattner       SrcDefinitionsToResolve.push_back(SSTy);
159a96f235cSRafael Espindola       SpeculativeTypes.push_back(SrcTy);
160a96f235cSRafael Espindola       SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
161b1ed91f3SChris Lattner       Entry = DstTy;
162b1ed91f3SChris Lattner       return true;
163b1ed91f3SChris Lattner     }
164b1ed91f3SChris Lattner   }
165b1ed91f3SChris Lattner 
166b1ed91f3SChris Lattner   // If the number of subtypes disagree between the two types, then we fail.
167b1ed91f3SChris Lattner   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
168b1ed91f3SChris Lattner     return false;
169b1ed91f3SChris Lattner 
170b1ed91f3SChris Lattner   // Fail if any of the extra properties (e.g. array size) of the type disagree.
171b1ed91f3SChris Lattner   if (isa<IntegerType>(DstTy))
172b1ed91f3SChris Lattner     return false; // bitwidth disagrees.
173b1ed91f3SChris Lattner   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
174b1ed91f3SChris Lattner     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
175b1ed91f3SChris Lattner       return false;
176eaf9b762SChris Lattner 
177b1ed91f3SChris Lattner   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
178b1ed91f3SChris Lattner     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
179b1ed91f3SChris Lattner       return false;
180b1ed91f3SChris Lattner   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
181b1ed91f3SChris Lattner     StructType *SSTy = cast<StructType>(SrcTy);
18244f7ab45SChris Lattner     if (DSTy->isLiteral() != SSTy->isLiteral() ||
183b1ed91f3SChris Lattner         DSTy->isPacked() != SSTy->isPacked())
184b1ed91f3SChris Lattner       return false;
185b1ed91f3SChris Lattner   } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
186b1ed91f3SChris Lattner     if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
187b1ed91f3SChris Lattner       return false;
188b1ed91f3SChris Lattner   } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
1895fad3e9aSJoey Gouly     if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
190361e513dSReid Spencer       return false;
191361e513dSReid Spencer   }
192361e513dSReid Spencer 
193b1ed91f3SChris Lattner   // Otherwise, we speculate that these two types will line up and recursively
194b1ed91f3SChris Lattner   // check the subelements.
195b1ed91f3SChris Lattner   Entry = DstTy;
196b1ed91f3SChris Lattner   SpeculativeTypes.push_back(SrcTy);
197eee6f995SChris Lattner 
198290e2cc5SRafael Espindola   for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
199290e2cc5SRafael Espindola     if (!areTypesIsomorphic(DstTy->getContainedType(I),
200290e2cc5SRafael Espindola                             SrcTy->getContainedType(I)))
201b1ed91f3SChris Lattner       return false;
202eee6f995SChris Lattner 
203b1ed91f3SChris Lattner   // If everything seems to have lined up, then everything is great.
204eee6f995SChris Lattner   return true;
205eee6f995SChris Lattner }
206eee6f995SChris Lattner 
207b1ed91f3SChris Lattner void TypeMapTy::linkDefinedTypeBodies() {
208b1ed91f3SChris Lattner   SmallVector<Type *, 16> Elements;
209c81c3f55SRafael Espindola   for (StructType *SrcSTy : SrcDefinitionsToResolve) {
210b1ed91f3SChris Lattner     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
211c81c3f55SRafael Espindola     assert(DstSTy->isOpaque());
212b1ed91f3SChris Lattner 
213b1ed91f3SChris Lattner     // Map the body of the source type over to a new body for the dest type.
214b1ed91f3SChris Lattner     Elements.resize(SrcSTy->getNumElements());
215290e2cc5SRafael Espindola     for (unsigned I = 0, E = Elements.size(); I != E; ++I)
216c81c3f55SRafael Espindola       Elements[I] = get(SrcSTy->getElementType(I));
217b1ed91f3SChris Lattner 
218b1ed91f3SChris Lattner     DstSTy->setBody(Elements, SrcSTy->isPacked());
219a5b9e1cfSRafael Espindola     DstStructTypesSet.switchToNonOpaque(DstSTy);
220b1ed91f3SChris Lattner   }
221c81c3f55SRafael Espindola   SrcDefinitionsToResolve.clear();
2225e3bd972SChris Lattner   DstResolvedOpaqueTypes.clear();
223eee6f995SChris Lattner }
224eee6f995SChris Lattner 
22531ad468dSRafael Espindola void TypeMapTy::finishType(StructType *DTy, StructType *STy,
22631ad468dSRafael Espindola                            ArrayRef<Type *> ETypes) {
22731ad468dSRafael Espindola   DTy->setBody(ETypes, STy->isPacked());
228a4e85e3dSRafael Espindola 
22931ad468dSRafael Espindola   // Steal STy's name.
23031ad468dSRafael Espindola   if (STy->hasName()) {
23131ad468dSRafael Espindola     SmallString<16> TmpName = STy->getName();
23231ad468dSRafael Espindola     STy->setName("");
23331ad468dSRafael Espindola     DTy->setName(TmpName);
23431ad468dSRafael Espindola   }
23531ad468dSRafael Espindola 
23631ad468dSRafael Espindola   DstStructTypesSet.addNonOpaque(DTy);
23731ad468dSRafael Espindola }
23831ad468dSRafael Espindola 
23931ad468dSRafael Espindola Type *TypeMapTy::get(Type *Ty) {
24031ad468dSRafael Espindola   SmallPtrSet<StructType *, 8> Visited;
24131ad468dSRafael Espindola   return get(Ty, Visited);
24231ad468dSRafael Espindola }
24331ad468dSRafael Espindola 
24431ad468dSRafael Espindola Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
245b1ed91f3SChris Lattner   // If we already have an entry for this type, return it.
246b1ed91f3SChris Lattner   Type **Entry = &MappedTypes[Ty];
247290e2cc5SRafael Espindola   if (*Entry)
248290e2cc5SRafael Espindola     return *Entry;
249b1ed91f3SChris Lattner 
25031ad468dSRafael Espindola   // These are types that LLVM itself will unique.
25131ad468dSRafael Espindola   bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
25231ad468dSRafael Espindola 
25331ad468dSRafael Espindola #ifndef NDEBUG
25431ad468dSRafael Espindola   if (!IsUniqued) {
25531ad468dSRafael Espindola     for (auto &Pair : MappedTypes) {
25631ad468dSRafael Espindola       assert(!(Pair.first != Ty && Pair.second == Ty) &&
25731ad468dSRafael Espindola              "mapping to a source type");
25831ad468dSRafael Espindola     }
25931ad468dSRafael Espindola   }
26031ad468dSRafael Espindola #endif
26131ad468dSRafael Espindola 
26231ad468dSRafael Espindola   if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
26331ad468dSRafael Espindola     StructType *DTy = StructType::create(Ty->getContext());
26431ad468dSRafael Espindola     return *Entry = DTy;
26531ad468dSRafael Espindola   }
26631ad468dSRafael Espindola 
26731ad468dSRafael Espindola   // If this is not a recursive type, then just map all of the elements and
268b1ed91f3SChris Lattner   // then rebuild the type from inside out.
26931ad468dSRafael Espindola   SmallVector<Type *, 4> ElementTypes;
27031ad468dSRafael Espindola 
271b1ed91f3SChris Lattner   // If there are no element types to map, then the type is itself.  This is
272b1ed91f3SChris Lattner   // true for the anonymous {} struct, things like 'float', integers, etc.
27331ad468dSRafael Espindola   if (Ty->getNumContainedTypes() == 0 && IsUniqued)
274b1ed91f3SChris Lattner     return *Entry = Ty;
275b1ed91f3SChris Lattner 
276b1ed91f3SChris Lattner   // Remap all of the elements, keeping track of whether any of them change.
277b1ed91f3SChris Lattner   bool AnyChange = false;
278b1ed91f3SChris Lattner   ElementTypes.resize(Ty->getNumContainedTypes());
279290e2cc5SRafael Espindola   for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
28031ad468dSRafael Espindola     ElementTypes[I] = get(Ty->getContainedType(I), Visited);
281290e2cc5SRafael Espindola     AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
282eee6f995SChris Lattner   }
283b1ed91f3SChris Lattner 
284b1ed91f3SChris Lattner   // If we found our type while recursively processing stuff, just use it.
285b1ed91f3SChris Lattner   Entry = &MappedTypes[Ty];
28631ad468dSRafael Espindola   if (*Entry) {
28731ad468dSRafael Espindola     if (auto *DTy = dyn_cast<StructType>(*Entry)) {
28831ad468dSRafael Espindola       if (DTy->isOpaque()) {
28931ad468dSRafael Espindola         auto *STy = cast<StructType>(Ty);
29031ad468dSRafael Espindola         finishType(DTy, STy, ElementTypes);
29131ad468dSRafael Espindola       }
29231ad468dSRafael Espindola     }
293290e2cc5SRafael Espindola     return *Entry;
29431ad468dSRafael Espindola   }
295b1ed91f3SChris Lattner 
29631ad468dSRafael Espindola   // If all of the element types mapped directly over and the type is not
29731ad468dSRafael Espindola   // a nomed struct, then the type is usable as-is.
29831ad468dSRafael Espindola   if (!AnyChange && IsUniqued)
299b1ed91f3SChris Lattner     return *Entry = Ty;
300b1ed91f3SChris Lattner 
301b1ed91f3SChris Lattner   // Otherwise, rebuild a modified type.
302b1ed91f3SChris Lattner   switch (Ty->getTypeID()) {
303290e2cc5SRafael Espindola   default:
304290e2cc5SRafael Espindola     llvm_unreachable("unknown derived type to remap");
305b1ed91f3SChris Lattner   case Type::ArrayTyID:
306b1ed91f3SChris Lattner     return *Entry = ArrayType::get(ElementTypes[0],
307b1ed91f3SChris Lattner                                    cast<ArrayType>(Ty)->getNumElements());
308b1ed91f3SChris Lattner   case Type::VectorTyID:
309b1ed91f3SChris Lattner     return *Entry = VectorType::get(ElementTypes[0],
310b1ed91f3SChris Lattner                                     cast<VectorType>(Ty)->getNumElements());
311b1ed91f3SChris Lattner   case Type::PointerTyID:
31231ad468dSRafael Espindola     return *Entry = PointerType::get(ElementTypes[0],
31331ad468dSRafael Espindola                                      cast<PointerType>(Ty)->getAddressSpace());
314b1ed91f3SChris Lattner   case Type::FunctionTyID:
315b1ed91f3SChris Lattner     return *Entry = FunctionType::get(ElementTypes[0],
316717d7eddSFrits van Bommel                                       makeArrayRef(ElementTypes).slice(1),
317b1ed91f3SChris Lattner                                       cast<FunctionType>(Ty)->isVarArg());
31831ad468dSRafael Espindola   case Type::StructTyID: {
31931ad468dSRafael Espindola     auto *STy = cast<StructType>(Ty);
32031ad468dSRafael Espindola     bool IsPacked = STy->isPacked();
32131ad468dSRafael Espindola     if (IsUniqued)
32231ad468dSRafael Espindola       return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
323b1ed91f3SChris Lattner 
324b1ed91f3SChris Lattner     // If the type is opaque, we can just use it directly.
325aa9918aaSRafael Espindola     if (STy->isOpaque()) {
32631ad468dSRafael Espindola       DstStructTypesSet.addOpaque(STy);
32731ad468dSRafael Espindola       return *Entry = Ty;
328aa9918aaSRafael Espindola     }
329b1ed91f3SChris Lattner 
33031ad468dSRafael Espindola     if (StructType *OldT =
33131ad468dSRafael Espindola             DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
332c81c3f55SRafael Espindola       STy->setName("");
33331ad468dSRafael Espindola       return *Entry = OldT;
334c81c3f55SRafael Espindola     }
335c81c3f55SRafael Espindola 
33631ad468dSRafael Espindola     if (!AnyChange) {
33731ad468dSRafael Espindola       DstStructTypesSet.addNonOpaque(STy);
33831ad468dSRafael Espindola       return *Entry = Ty;
33931ad468dSRafael Espindola     }
34031ad468dSRafael Espindola 
34131ad468dSRafael Espindola     StructType *DTy = StructType::create(Ty->getContext());
34231ad468dSRafael Espindola     finishType(DTy, STy, ElementTypes);
34331ad468dSRafael Espindola     return *Entry = DTy;
34431ad468dSRafael Espindola   }
34531ad468dSRafael Espindola   }
346b1ed91f3SChris Lattner }
347b1ed91f3SChris Lattner 
348b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
349b1ed91f3SChris Lattner // ModuleLinker implementation.
350b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
351b1ed91f3SChris Lattner 
352b1ed91f3SChris Lattner namespace {
353f6f121e2SJames Molloy class ModuleLinker;
354f6f121e2SJames Molloy 
35518c89411SRafael Espindola /// Creates prototypes for functions that are lazily linked on the fly. This
35618c89411SRafael Espindola /// speeds up linking for modules with many/ lazily linked functions of which
35718c89411SRafael Espindola /// few get used.
358437aafdaSDavid Blaikie class ValueMaterializerTy final : public ValueMaterializer {
359c7ed52f2STeresa Johnson   ModuleLinker *ModLinker;
360c84f608bSRafael Espindola 
361f6f121e2SJames Molloy public:
36219b52383SRafael Espindola   ValueMaterializerTy(ModuleLinker *ModLinker) : ModLinker(ModLinker) {}
363f6f121e2SJames Molloy 
36419b52383SRafael Espindola   Value *materializeDeclFor(Value *V) override;
36519b52383SRafael Espindola   void materializeInitFor(GlobalValue *New, GlobalValue *Old) override;
366f6f121e2SJames Molloy };
367f6f121e2SJames Molloy 
368d12b4a33SRafael Espindola class LinkDiagnosticInfo : public DiagnosticInfo {
369d12b4a33SRafael Espindola   const Twine &Msg;
370d12b4a33SRafael Espindola 
371d12b4a33SRafael Espindola public:
372d12b4a33SRafael Espindola   LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
373d12b4a33SRafael Espindola   void print(DiagnosticPrinter &DP) const override;
374d12b4a33SRafael Espindola };
375d12b4a33SRafael Espindola LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
376d12b4a33SRafael Espindola                                        const Twine &Msg)
377d12b4a33SRafael Espindola     : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
378d12b4a33SRafael Espindola void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
379d12b4a33SRafael Espindola 
38018c89411SRafael Espindola /// This is an implementation class for the LinkModules function, which is the
38118c89411SRafael Espindola /// entrypoint for this file.
382b1ed91f3SChris Lattner class ModuleLinker {
3830e309fe8SRafael Espindola   Module &DstM;
3840e309fe8SRafael Espindola   Module &SrcM;
385b1ed91f3SChris Lattner 
386b1ed91f3SChris Lattner   TypeMapTy TypeMap;
387f6f121e2SJames Molloy   ValueMaterializerTy ValMaterializer;
388b1ed91f3SChris Lattner 
38918c89411SRafael Espindola   /// Mapping of values from what they used to be in Src, to what they are now
39018c89411SRafael Espindola   /// in DstM.  ValueToValueMapTy is a ValueMap, which involves some overhead
39118c89411SRafael Espindola   /// due to the use of Value handles which the Linker doesn't actually need,
39218c89411SRafael Espindola   /// but this allows us to reuse the ValueMapper code.
393b1ed91f3SChris Lattner   ValueToValueMapTy ValueMap;
394b1ed91f3SChris Lattner 
395cbb91408STanya Lattner   // Set of items not to link in from source.
396c98b20b0SRafael Espindola   SmallPtrSet<const GlobalValue *, 16> DoNotLinkFromSource;
397cbb91408STanya Lattner 
398d0b23befSRafael Espindola   DiagnosticHandlerFunction DiagnosticHandler;
3994160f5d3SRafael Espindola 
400e868123dSDuncan P. N. Exon Smith   /// For symbol clashes, prefer those from Src.
401020d4fb1SArtem Belevich   unsigned Flags;
402e868123dSDuncan P. N. Exon Smith 
403c7ed52f2STeresa Johnson   /// Function index passed into ModuleLinker for using in function
404c7ed52f2STeresa Johnson   /// importing/exporting handling.
4058220e8a8SMehdi Amini   const FunctionInfoIndex *ImportIndex;
406c7ed52f2STeresa Johnson 
407c7ed52f2STeresa Johnson   /// Function to import from source module, all other functions are
408c7ed52f2STeresa Johnson   /// imported as declarations instead of definitions.
409ffe2e4aaSMehdi Amini   DenseSet<const GlobalValue *> *ImportFunction;
410c7ed52f2STeresa Johnson 
411c7ed52f2STeresa Johnson   /// Set to true if the given FunctionInfoIndex contains any functions
412c7ed52f2STeresa Johnson   /// from this source module, in which case we must conservatively assume
413c7ed52f2STeresa Johnson   /// that any of its functions may be imported into another module
414c7ed52f2STeresa Johnson   /// as part of a different backend compilation process.
415af714765SRafael Espindola   bool HasExportedFunctions = false;
416c7ed52f2STeresa Johnson 
4171063293aSTeresa Johnson   /// Set to true when all global value body linking is complete (including
4181063293aSTeresa Johnson   /// lazy linking). Used to prevent metadata linking from creating new
4191063293aSTeresa Johnson   /// references.
420af714765SRafael Espindola   bool DoneLinkingBodies = false;
4211063293aSTeresa Johnson 
422baa3bf8fSRafael Espindola   bool HasError = false;
423baa3bf8fSRafael Espindola 
424b1ed91f3SChris Lattner public:
4250e309fe8SRafael Espindola   ModuleLinker(Module &DstM, Linker::IdentifiedStructTypeSet &Set, Module &SrcM,
426c7ed52f2STeresa Johnson                DiagnosticHandlerFunction DiagnosticHandler, unsigned Flags,
4278220e8a8SMehdi Amini                const FunctionInfoIndex *Index = nullptr,
428ffe2e4aaSMehdi Amini                DenseSet<const GlobalValue *> *FuncToImport = nullptr)
4290e309fe8SRafael Espindola       : DstM(DstM), SrcM(SrcM), TypeMap(Set), ValMaterializer(this),
430c7ed52f2STeresa Johnson         DiagnosticHandler(DiagnosticHandler), Flags(Flags), ImportIndex(Index),
431af714765SRafael Espindola         ImportFunction(FuncToImport) {
432c7ed52f2STeresa Johnson     assert((ImportIndex || !ImportFunction) &&
433c7ed52f2STeresa Johnson            "Expect a FunctionInfoIndex when importing");
434c7ed52f2STeresa Johnson     // If we have a FunctionInfoIndex but no function to import,
435c7ed52f2STeresa Johnson     // then this is the primary module being compiled in a ThinLTO
436c7ed52f2STeresa Johnson     // backend compilation, and we need to see if it has functions that
437c7ed52f2STeresa Johnson     // may be exported to another backend compilation.
438c7ed52f2STeresa Johnson     if (ImportIndex && !ImportFunction)
4390e309fe8SRafael Espindola       HasExportedFunctions = ImportIndex->hasExportedFunctions(&SrcM);
440c7ed52f2STeresa Johnson   }
441b1ed91f3SChris Lattner 
442b1ed91f3SChris Lattner   bool run();
44319b52383SRafael Espindola   Value *materializeDeclFor(Value *V);
44419b52383SRafael Espindola   void materializeInitFor(GlobalValue *New, GlobalValue *Old);
445b1ed91f3SChris Lattner 
44619b52383SRafael Espindola private:
447020d4fb1SArtem Belevich   bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
448020d4fb1SArtem Belevich   bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
449020d4fb1SArtem Belevich   bool shouldInternalizeLinkedSymbols() {
450020d4fb1SArtem Belevich     return Flags & Linker::InternalizeLinkedSymbols;
451020d4fb1SArtem Belevich   }
452020d4fb1SArtem Belevich 
453c7ed52f2STeresa Johnson   /// Handles cloning of a global values from the source module into
454c7ed52f2STeresa Johnson   /// the destination module, including setting the attributes and visibility.
455c7ed52f2STeresa Johnson   GlobalValue *copyGlobalValueProto(TypeMapTy &TypeMap, const GlobalValue *SGV,
456f3518c95SRafael Espindola                                     const GlobalValue *DGV, bool ForDefinition);
457c7ed52f2STeresa Johnson 
458c7ed52f2STeresa Johnson   /// Check if we should promote the given local value to global scope.
459c7ed52f2STeresa Johnson   bool doPromoteLocalToGlobal(const GlobalValue *SGV);
460c7ed52f2STeresa Johnson 
461d12b4a33SRafael Espindola   bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
462d12b4a33SRafael Espindola                             const GlobalValue &Src);
463dbb0bd1aSRafael Espindola 
464d12b4a33SRafael Espindola   /// Helper method for setting a message and returning an error code.
465b1ed91f3SChris Lattner   bool emitError(const Twine &Message) {
4664160f5d3SRafael Espindola     DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
467baa3bf8fSRafael Espindola     HasError = true;
468b1ed91f3SChris Lattner     return true;
469b1ed91f3SChris Lattner   }
470b1ed91f3SChris Lattner 
471d12b4a33SRafael Espindola   void emitWarning(const Twine &Message) {
4724160f5d3SRafael Espindola     DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
473d12b4a33SRafael Espindola   }
474d12b4a33SRafael Espindola 
4750e309fe8SRafael Espindola   bool getComdatLeader(Module &M, StringRef ComdatName,
476dad0a645SDavid Majnemer                        const GlobalVariable *&GVar);
477dad0a645SDavid Majnemer   bool computeResultingSelectionKind(StringRef ComdatName,
478dad0a645SDavid Majnemer                                      Comdat::SelectionKind Src,
479dad0a645SDavid Majnemer                                      Comdat::SelectionKind Dst,
480dad0a645SDavid Majnemer                                      Comdat::SelectionKind &Result,
481dad0a645SDavid Majnemer                                      bool &LinkFromSrc);
482dad0a645SDavid Majnemer   std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
483dad0a645SDavid Majnemer       ComdatsChosen;
484dad0a645SDavid Majnemer   bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
485dad0a645SDavid Majnemer                        bool &LinkFromSrc);
4862d5fb8caSTeresa Johnson   // Keep track of the global value members of each comdat in source.
4872d5fb8caSTeresa Johnson   DenseMap<const Comdat *, std::vector<GlobalValue *>> ComdatMembers;
488dad0a645SDavid Majnemer 
48918c89411SRafael Espindola   /// Given a global in the source module, return the global in the
49018c89411SRafael Espindola   /// destination module that is being linked to, if any.
4913e8bc6a8SRafael Espindola   GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
492b1ed91f3SChris Lattner     // If the source has no name it can't link.  If it has local linkage,
493b1ed91f3SChris Lattner     // there is no name match-up going on.
494b098f0c1STeresa Johnson     if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(getLinkage(SrcGV)))
4952617dcceSCraig Topper       return nullptr;
496b1ed91f3SChris Lattner 
497b1ed91f3SChris Lattner     // Otherwise see if we have a match in the destination module's symtab.
4980e309fe8SRafael Espindola     GlobalValue *DGV = DstM.getNamedValue(getName(SrcGV));
499c84f608bSRafael Espindola     if (!DGV)
500c84f608bSRafael Espindola       return nullptr;
501b1ed91f3SChris Lattner 
502b1ed91f3SChris Lattner     // If we found a global with the same name in the dest module, but it has
503b1ed91f3SChris Lattner     // internal linkage, we are really not doing any linkage here.
504b1ed91f3SChris Lattner     if (DGV->hasLocalLinkage())
5052617dcceSCraig Topper       return nullptr;
506b1ed91f3SChris Lattner 
507b1ed91f3SChris Lattner     // Otherwise, we do in fact link to the destination global.
508b1ed91f3SChris Lattner     return DGV;
509b1ed91f3SChris Lattner   }
510b1ed91f3SChris Lattner 
511b1ed91f3SChris Lattner   void computeTypeMapping();
512b1ed91f3SChris Lattner 
51309d84addSDuncan P. N. Exon Smith   void upgradeMismatchedGlobalArray(StringRef Name);
51409d84addSDuncan P. N. Exon Smith   void upgradeMismatchedGlobals();
51509d84addSDuncan P. N. Exon Smith 
516baa3bf8fSRafael Espindola   bool linkIfNeeded(GlobalValue &GV);
5173e8bc6a8SRafael Espindola   bool linkAppendingVarProto(GlobalVariable *DstGV,
5183e8bc6a8SRafael Espindola                              const GlobalVariable *SrcGV);
519778fcc77SRafael Espindola 
520778fcc77SRafael Espindola   bool linkGlobalValueProto(GlobalValue *GV);
52166f02413SBill Wendling   bool linkModuleFlagsMetadata();
522b1ed91f3SChris Lattner 
523ef23711eSRafael Espindola   void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
524ef23711eSRafael Espindola   bool linkFunctionBody(Function &Dst, Function &Src);
525ef23711eSRafael Espindola   void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
526e39cd5b1SRafael Espindola   bool linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
527ef23711eSRafael Espindola 
528c7ed52f2STeresa Johnson   /// Functions that take care of cloning a specific global value type
529c7ed52f2STeresa Johnson   /// into the destination module.
530c7ed52f2STeresa Johnson   GlobalVariable *copyGlobalVariableProto(TypeMapTy &TypeMap,
531c7ed52f2STeresa Johnson                                           const GlobalVariable *SGVar);
532c7ed52f2STeresa Johnson   Function *copyFunctionProto(TypeMapTy &TypeMap, const Function *SF);
533c7ed52f2STeresa Johnson   GlobalValue *copyGlobalAliasProto(TypeMapTy &TypeMap, const GlobalAlias *SGA);
534c7ed52f2STeresa Johnson 
535c7ed52f2STeresa Johnson   /// Helper methods to check if we are importing from or potentially
536c7ed52f2STeresa Johnson   /// exporting from the current source module.
537c7ed52f2STeresa Johnson   bool isPerformingImport() { return ImportFunction != nullptr; }
538c7ed52f2STeresa Johnson   bool isModuleExporting() { return HasExportedFunctions; }
539c7ed52f2STeresa Johnson 
540c7ed52f2STeresa Johnson   /// If we are importing from the source module, checks if we should
541c7ed52f2STeresa Johnson   /// import SGV as a definition, otherwise import as a declaration.
542c7ed52f2STeresa Johnson   bool doImportAsDefinition(const GlobalValue *SGV);
543c7ed52f2STeresa Johnson 
544c7ed52f2STeresa Johnson   /// Get the name for SGV that should be used in the linked destination
545c7ed52f2STeresa Johnson   /// module. Specifically, this handles the case where we need to rename
546c7ed52f2STeresa Johnson   /// a local that is being promoted to global scope.
547c7ed52f2STeresa Johnson   std::string getName(const GlobalValue *SGV);
548c7ed52f2STeresa Johnson 
549c7ed52f2STeresa Johnson   /// Get the new linkage for SGV that should be used in the linked destination
550c7ed52f2STeresa Johnson   /// module. Specifically, for ThinLTO importing or exporting it may need
551c7ed52f2STeresa Johnson   /// to be adjusted.
552c7ed52f2STeresa Johnson   GlobalValue::LinkageTypes getLinkage(const GlobalValue *SGV);
553c7ed52f2STeresa Johnson 
554c7ed52f2STeresa Johnson   /// Copies the necessary global value attributes and name from the source
555c7ed52f2STeresa Johnson   /// to the newly cloned global value.
556c7ed52f2STeresa Johnson   void copyGVAttributes(GlobalValue *NewGV, const GlobalValue *SrcGV);
557c7ed52f2STeresa Johnson 
558c7ed52f2STeresa Johnson   /// Updates the visibility for the new global cloned from the source
559c7ed52f2STeresa Johnson   /// and, if applicable, linked with an existing destination global.
560c7ed52f2STeresa Johnson   /// Handles visibility change required for promoted locals.
561c7ed52f2STeresa Johnson   void setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
562c7ed52f2STeresa Johnson                      const GlobalValue *DGV = nullptr);
563c7ed52f2STeresa Johnson 
564b1ed91f3SChris Lattner   void linkNamedMDNodes();
565eee6f995SChris Lattner };
566f00654e3SAlexander Kornienko }
567d48b7783SBill Wendling 
56818c89411SRafael Espindola /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
56918c89411SRafael Espindola /// table. This is good for all clients except for us. Go through the trouble
57018c89411SRafael Espindola /// to force this back.
571b1ed91f3SChris Lattner static void forceRenaming(GlobalValue *GV, StringRef Name) {
572b1ed91f3SChris Lattner   // If the global doesn't force its name or if it already has the right name,
573b1ed91f3SChris Lattner   // there is nothing for us to do.
574c7ed52f2STeresa Johnson   // Note that any required local to global promotion should already be done,
575c7ed52f2STeresa Johnson   // so promoted locals will not skip this handling as their linkage is no
576c7ed52f2STeresa Johnson   // longer local.
577b1ed91f3SChris Lattner   if (GV->hasLocalLinkage() || GV->getName() == Name)
578b1ed91f3SChris Lattner     return;
579b1ed91f3SChris Lattner 
580b1ed91f3SChris Lattner   Module *M = GV->getParent();
581361e513dSReid Spencer 
582361e513dSReid Spencer   // If there is a conflict, rename the conflict.
583b1ed91f3SChris Lattner   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
5842a8d2e0eSChris Lattner     GV->takeName(ConflictGV);
585361e513dSReid Spencer     ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
586b1ed91f3SChris Lattner     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
5872a8d2e0eSChris Lattner   } else {
5882a8d2e0eSChris Lattner     GV->setName(Name); // Force the name back
5893aaaa0b2SReid Spencer   }
5903aaaa0b2SReid Spencer }
5913aaaa0b2SReid Spencer 
59218c89411SRafael Espindola /// copy additional attributes (those not needed to construct a GlobalValue)
59318c89411SRafael Espindola /// from the SrcGV to the DestGV.
594c7ed52f2STeresa Johnson void ModuleLinker::copyGVAttributes(GlobalValue *NewGV,
595c7ed52f2STeresa Johnson                                     const GlobalValue *SrcGV) {
596c7ed52f2STeresa Johnson   NewGV->copyAttributesFrom(SrcGV);
597c7ed52f2STeresa Johnson   forceRenaming(NewGV, getName(SrcGV));
598361e513dSReid Spencer }
599361e513dSReid Spencer 
600c7ed52f2STeresa Johnson bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
601c7ed52f2STeresa Johnson   if (!isPerformingImport())
602c7ed52f2STeresa Johnson     return false;
6033cd8161cSTeresa Johnson   auto *GA = dyn_cast<GlobalAlias>(SGV);
6043cd8161cSTeresa Johnson   if (GA) {
6053cd8161cSTeresa Johnson     if (GA->hasWeakAnyLinkage())
6063cd8161cSTeresa Johnson       return false;
60789345771SRafael Espindola     const GlobalObject *GO = GA->getBaseObject();
60889345771SRafael Espindola     if (!GO->hasLinkOnceODRLinkage())
60989345771SRafael Espindola       return false;
61089345771SRafael Espindola     return doImportAsDefinition(GO);
6113cd8161cSTeresa Johnson   }
612dfbebc37STeresa Johnson   // Always import GlobalVariable definitions, except for the special
613dfbebc37STeresa Johnson   // case of WeakAny which are imported as ExternalWeak declarations
614dfbebc37STeresa Johnson   // (see comments in ModuleLinker::getLinkage). The linkage changes
615c7ed52f2STeresa Johnson   // described in ModuleLinker::getLinkage ensure the correct behavior (e.g.
616c7ed52f2STeresa Johnson   // global variables with external linkage are transformed to
6173cd8161cSTeresa Johnson   // available_externally definitions, which are ultimately turned into
6183cd8161cSTeresa Johnson   // declarations after the EliminateAvailableExternally pass).
61966059c9fSCraig Topper   if (isa<GlobalVariable>(SGV) && !SGV->isDeclaration() &&
6203cd8161cSTeresa Johnson       !SGV->hasWeakAnyLinkage())
621c7ed52f2STeresa Johnson     return true;
622c7ed52f2STeresa Johnson   // Only import the function requested for importing.
623c7ed52f2STeresa Johnson   auto *SF = dyn_cast<Function>(SGV);
624ffe2e4aaSMehdi Amini   if (SF && ImportFunction->count(SF))
625c7ed52f2STeresa Johnson     return true;
626c7ed52f2STeresa Johnson   // Otherwise no.
627c7ed52f2STeresa Johnson   return false;
628c7ed52f2STeresa Johnson }
629c7ed52f2STeresa Johnson 
630c7ed52f2STeresa Johnson bool ModuleLinker::doPromoteLocalToGlobal(const GlobalValue *SGV) {
631c7ed52f2STeresa Johnson   assert(SGV->hasLocalLinkage());
632c7ed52f2STeresa Johnson   // Both the imported references and the original local variable must
633c7ed52f2STeresa Johnson   // be promoted.
634c7ed52f2STeresa Johnson   if (!isPerformingImport() && !isModuleExporting())
635c7ed52f2STeresa Johnson     return false;
636c7ed52f2STeresa Johnson 
637c7ed52f2STeresa Johnson   // Local const variables never need to be promoted unless they are address
638c7ed52f2STeresa Johnson   // taken. The imported uses can simply use the clone created in this module.
639c7ed52f2STeresa Johnson   // For now we are conservative in determining which variables are not
640c7ed52f2STeresa Johnson   // address taken by checking the unnamed addr flag. To be more aggressive,
641c7ed52f2STeresa Johnson   // the address taken information must be checked earlier during parsing
642c7ed52f2STeresa Johnson   // of the module and recorded in the function index for use when importing
643c7ed52f2STeresa Johnson   // from that module.
644c7ed52f2STeresa Johnson   auto *GVar = dyn_cast<GlobalVariable>(SGV);
645c7ed52f2STeresa Johnson   if (GVar && GVar->isConstant() && GVar->hasUnnamedAddr())
646c7ed52f2STeresa Johnson     return false;
647c7ed52f2STeresa Johnson 
648c7ed52f2STeresa Johnson   // Eventually we only need to promote functions in the exporting module that
649c7ed52f2STeresa Johnson   // are referenced by a potentially exported function (i.e. one that is in the
650c7ed52f2STeresa Johnson   // function index).
651c7ed52f2STeresa Johnson   return true;
652c7ed52f2STeresa Johnson }
653c7ed52f2STeresa Johnson 
654c7ed52f2STeresa Johnson std::string ModuleLinker::getName(const GlobalValue *SGV) {
655c7ed52f2STeresa Johnson   // For locals that must be promoted to global scope, ensure that
656c7ed52f2STeresa Johnson   // the promoted name uniquely identifies the copy in the original module,
657c7ed52f2STeresa Johnson   // using the ID assigned during combined index creation. When importing,
658c7ed52f2STeresa Johnson   // we rename all locals (not just those that are promoted) in order to
659c7ed52f2STeresa Johnson   // avoid naming conflicts between locals imported from different modules.
660c7ed52f2STeresa Johnson   if (SGV->hasLocalLinkage() &&
661c7ed52f2STeresa Johnson       (doPromoteLocalToGlobal(SGV) || isPerformingImport()))
662c7ed52f2STeresa Johnson     return FunctionInfoIndex::getGlobalNameForLocal(
663c7ed52f2STeresa Johnson         SGV->getName(),
664c7ed52f2STeresa Johnson         ImportIndex->getModuleId(SGV->getParent()->getModuleIdentifier()));
665c7ed52f2STeresa Johnson   return SGV->getName();
666c7ed52f2STeresa Johnson }
667c7ed52f2STeresa Johnson 
668c7ed52f2STeresa Johnson GlobalValue::LinkageTypes ModuleLinker::getLinkage(const GlobalValue *SGV) {
669c7ed52f2STeresa Johnson   // Any local variable that is referenced by an exported function needs
670c7ed52f2STeresa Johnson   // to be promoted to global scope. Since we don't currently know which
671c7ed52f2STeresa Johnson   // functions reference which local variables/functions, we must treat
672c7ed52f2STeresa Johnson   // all as potentially exported if this module is exporting anything.
673c7ed52f2STeresa Johnson   if (isModuleExporting()) {
674c7ed52f2STeresa Johnson     if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
675c7ed52f2STeresa Johnson       return GlobalValue::ExternalLinkage;
676c7ed52f2STeresa Johnson     return SGV->getLinkage();
677c7ed52f2STeresa Johnson   }
678c7ed52f2STeresa Johnson 
679c7ed52f2STeresa Johnson   // Otherwise, if we aren't importing, no linkage change is needed.
680c7ed52f2STeresa Johnson   if (!isPerformingImport())
681c7ed52f2STeresa Johnson     return SGV->getLinkage();
682c7ed52f2STeresa Johnson 
683c7ed52f2STeresa Johnson   switch (SGV->getLinkage()) {
684c7ed52f2STeresa Johnson   case GlobalValue::ExternalLinkage:
685c7ed52f2STeresa Johnson     // External defnitions are converted to available_externally
686c7ed52f2STeresa Johnson     // definitions upon import, so that they are available for inlining
687c7ed52f2STeresa Johnson     // and/or optimization, but are turned into declarations later
688c7ed52f2STeresa Johnson     // during the EliminateAvailableExternally pass.
6893cd8161cSTeresa Johnson     if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
690c7ed52f2STeresa Johnson       return GlobalValue::AvailableExternallyLinkage;
691c7ed52f2STeresa Johnson     // An imported external declaration stays external.
692c7ed52f2STeresa Johnson     return SGV->getLinkage();
693c7ed52f2STeresa Johnson 
694c7ed52f2STeresa Johnson   case GlobalValue::AvailableExternallyLinkage:
695c7ed52f2STeresa Johnson     // An imported available_externally definition converts
696c7ed52f2STeresa Johnson     // to external if imported as a declaration.
697c7ed52f2STeresa Johnson     if (!doImportAsDefinition(SGV))
698c7ed52f2STeresa Johnson       return GlobalValue::ExternalLinkage;
699c7ed52f2STeresa Johnson     // An imported available_externally declaration stays that way.
700c7ed52f2STeresa Johnson     return SGV->getLinkage();
701c7ed52f2STeresa Johnson 
702c7ed52f2STeresa Johnson   case GlobalValue::LinkOnceAnyLinkage:
703c7ed52f2STeresa Johnson   case GlobalValue::LinkOnceODRLinkage:
704c7ed52f2STeresa Johnson     // These both stay the same when importing the definition.
705c7ed52f2STeresa Johnson     // The ThinLTO pass will eventually force-import their definitions.
706c7ed52f2STeresa Johnson     return SGV->getLinkage();
707c7ed52f2STeresa Johnson 
708c7ed52f2STeresa Johnson   case GlobalValue::WeakAnyLinkage:
709c7ed52f2STeresa Johnson     // Can't import weak_any definitions correctly, or we might change the
710c7ed52f2STeresa Johnson     // program semantics, since the linker will pick the first weak_any
711c7ed52f2STeresa Johnson     // definition and importing would change the order they are seen by the
712c7ed52f2STeresa Johnson     // linker. The module linking caller needs to enforce this.
713c7ed52f2STeresa Johnson     assert(!doImportAsDefinition(SGV));
714c7ed52f2STeresa Johnson     // If imported as a declaration, it becomes external_weak.
715c7ed52f2STeresa Johnson     return GlobalValue::ExternalWeakLinkage;
716c7ed52f2STeresa Johnson 
717c7ed52f2STeresa Johnson   case GlobalValue::WeakODRLinkage:
718c7ed52f2STeresa Johnson     // For weak_odr linkage, there is a guarantee that all copies will be
719c7ed52f2STeresa Johnson     // equivalent, so the issue described above for weak_any does not exist,
720c7ed52f2STeresa Johnson     // and the definition can be imported. It can be treated similarly
721c7ed52f2STeresa Johnson     // to an imported externally visible global value.
7223cd8161cSTeresa Johnson     if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
723c7ed52f2STeresa Johnson       return GlobalValue::AvailableExternallyLinkage;
724c7ed52f2STeresa Johnson     else
725c7ed52f2STeresa Johnson       return GlobalValue::ExternalLinkage;
726c7ed52f2STeresa Johnson 
727c7ed52f2STeresa Johnson   case GlobalValue::AppendingLinkage:
728c7ed52f2STeresa Johnson     // It would be incorrect to import an appending linkage variable,
729c7ed52f2STeresa Johnson     // since it would cause global constructors/destructors to be
730c7ed52f2STeresa Johnson     // executed multiple times. This should have already been handled
731c7ed52f2STeresa Johnson     // by linkGlobalValueProto.
732f3d2329dSDavide Italiano     llvm_unreachable("Cannot import appending linkage variable");
733c7ed52f2STeresa Johnson 
734c7ed52f2STeresa Johnson   case GlobalValue::InternalLinkage:
735c7ed52f2STeresa Johnson   case GlobalValue::PrivateLinkage:
736c7ed52f2STeresa Johnson     // If we are promoting the local to global scope, it is handled
737c7ed52f2STeresa Johnson     // similarly to a normal externally visible global.
738c7ed52f2STeresa Johnson     if (doPromoteLocalToGlobal(SGV)) {
7393cd8161cSTeresa Johnson       if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
740c7ed52f2STeresa Johnson         return GlobalValue::AvailableExternallyLinkage;
741c7ed52f2STeresa Johnson       else
742c7ed52f2STeresa Johnson         return GlobalValue::ExternalLinkage;
743c7ed52f2STeresa Johnson     }
744c7ed52f2STeresa Johnson     // A non-promoted imported local definition stays local.
745c7ed52f2STeresa Johnson     // The ThinLTO pass will eventually force-import their definitions.
746c7ed52f2STeresa Johnson     return SGV->getLinkage();
747c7ed52f2STeresa Johnson 
748c7ed52f2STeresa Johnson   case GlobalValue::ExternalWeakLinkage:
749c7ed52f2STeresa Johnson     // External weak doesn't apply to definitions, must be a declaration.
750c7ed52f2STeresa Johnson     assert(!doImportAsDefinition(SGV));
751c7ed52f2STeresa Johnson     // Linkage stays external_weak.
752c7ed52f2STeresa Johnson     return SGV->getLinkage();
753c7ed52f2STeresa Johnson 
754c7ed52f2STeresa Johnson   case GlobalValue::CommonLinkage:
755c7ed52f2STeresa Johnson     // Linkage stays common on definitions.
756c7ed52f2STeresa Johnson     // The ThinLTO pass will eventually force-import their definitions.
757c7ed52f2STeresa Johnson     return SGV->getLinkage();
758c7ed52f2STeresa Johnson   }
759c7ed52f2STeresa Johnson 
760c7ed52f2STeresa Johnson   llvm_unreachable("unknown linkage type");
761c7ed52f2STeresa Johnson }
762c7ed52f2STeresa Johnson 
763ef23711eSRafael Espindola /// Loop through the global variables in the src module and merge them into the
764ef23711eSRafael Espindola /// dest module.
765c7ed52f2STeresa Johnson GlobalVariable *
766c7ed52f2STeresa Johnson ModuleLinker::copyGlobalVariableProto(TypeMapTy &TypeMap,
767ef23711eSRafael Espindola                                       const GlobalVariable *SGVar) {
768ef23711eSRafael Espindola   // No linking to be performed or linking from the source: simply create an
769ef23711eSRafael Espindola   // identical version of the symbol over in the dest module... the
770ef23711eSRafael Espindola   // initializer will be filled in later by LinkGlobalInits.
771f3518c95SRafael Espindola   GlobalVariable *NewDGV =
772f3518c95SRafael Espindola       new GlobalVariable(DstM, TypeMap.get(SGVar->getType()->getElementType()),
773f3518c95SRafael Espindola                          SGVar->isConstant(), GlobalValue::ExternalLinkage,
774f3518c95SRafael Espindola                          /*init*/ nullptr, getName(SGVar),
775c7ed52f2STeresa Johnson                          /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
776ef23711eSRafael Espindola                          SGVar->getType()->getAddressSpace());
777f6f121e2SJames Molloy 
778ef23711eSRafael Espindola   return NewDGV;
7793931c28bSRafael Espindola }
7803931c28bSRafael Espindola 
781ef23711eSRafael Espindola /// Link the function in the source module into the destination module if
782ef23711eSRafael Espindola /// needed, setting up mapping information.
783c7ed52f2STeresa Johnson Function *ModuleLinker::copyFunctionProto(TypeMapTy &TypeMap,
784ef23711eSRafael Espindola                                           const Function *SF) {
785ef23711eSRafael Espindola   // If there is no linkage to be performed or we are linking from the source,
786ef23711eSRafael Espindola   // bring SF over.
787f3518c95SRafael Espindola   return Function::Create(TypeMap.get(SF->getFunctionType()),
788f3518c95SRafael Espindola                           GlobalValue::ExternalLinkage, getName(SF), &DstM);
789ef23711eSRafael Espindola }
790ef23711eSRafael Espindola 
791ef23711eSRafael Espindola /// Set up prototypes for any aliases that come over from the source module.
792c7ed52f2STeresa Johnson GlobalValue *ModuleLinker::copyGlobalAliasProto(TypeMapTy &TypeMap,
793ef23711eSRafael Espindola                                                 const GlobalAlias *SGA) {
794c7ed52f2STeresa Johnson   // If we are importing and encounter a weak_any alias, or an alias to
795c7ed52f2STeresa Johnson   // an object being imported as a declaration, we must import the alias
796c7ed52f2STeresa Johnson   // as a declaration as well, which involves converting it to a non-alias.
797c7ed52f2STeresa Johnson   // See comments in ModuleLinker::getLinkage for why we cannot import
798c7ed52f2STeresa Johnson   // weak_any defintions.
7993cd8161cSTeresa Johnson   if (isPerformingImport() && !doImportAsDefinition(SGA)) {
800c7ed52f2STeresa Johnson     // Need to convert to declaration. All aliases must be definitions.
801c7ed52f2STeresa Johnson     const GlobalValue *GVal = SGA->getBaseObject();
802c7ed52f2STeresa Johnson     GlobalValue *NewGV;
803c7ed52f2STeresa Johnson     if (auto *GVar = dyn_cast<GlobalVariable>(GVal))
804c7ed52f2STeresa Johnson       NewGV = copyGlobalVariableProto(TypeMap, GVar);
805c7ed52f2STeresa Johnson     else {
806c7ed52f2STeresa Johnson       auto *F = dyn_cast<Function>(GVal);
807c7ed52f2STeresa Johnson       assert(F);
808c7ed52f2STeresa Johnson       NewGV = copyFunctionProto(TypeMap, F);
809c7ed52f2STeresa Johnson     }
810f1b0a6e3STeresa Johnson     // Set the linkage to External or ExternalWeak (see comments in
811f1b0a6e3STeresa Johnson     // ModuleLinker::getLinkage for why WeakAny is converted to ExternalWeak).
812c7ed52f2STeresa Johnson     if (SGA->hasWeakAnyLinkage())
813c7ed52f2STeresa Johnson       NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
814f1b0a6e3STeresa Johnson     else
815f1b0a6e3STeresa Johnson       NewGV->setLinkage(GlobalValue::ExternalLinkage);
816c7ed52f2STeresa Johnson     return NewGV;
817c7ed52f2STeresa Johnson   }
818ef23711eSRafael Espindola   // If there is no linkage to be performed or we're linking from the source,
819ef23711eSRafael Espindola   // bring over SGA.
8206614d8d2SDavid Blaikie   auto *Ty = TypeMap.get(SGA->getValueType());
8216614d8d2SDavid Blaikie   return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
822f3518c95SRafael Espindola                              GlobalValue::ExternalLinkage, getName(SGA), &DstM);
823ef23711eSRafael Espindola }
824ef23711eSRafael Espindola 
825eb5e0a77SRafael Espindola static GlobalValue::VisibilityTypes
826eb5e0a77SRafael Espindola getMinVisibility(GlobalValue::VisibilityTypes A,
827eb5e0a77SRafael Espindola                  GlobalValue::VisibilityTypes B) {
828eb5e0a77SRafael Espindola   if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
829eb5e0a77SRafael Espindola     return GlobalValue::HiddenVisibility;
830eb5e0a77SRafael Espindola   if (A == GlobalValue::ProtectedVisibility ||
831eb5e0a77SRafael Espindola       B == GlobalValue::ProtectedVisibility)
832eb5e0a77SRafael Espindola     return GlobalValue::ProtectedVisibility;
833eb5e0a77SRafael Espindola   return GlobalValue::DefaultVisibility;
834eb5e0a77SRafael Espindola }
835eb5e0a77SRafael Espindola 
836c7ed52f2STeresa Johnson void ModuleLinker::setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
837c7ed52f2STeresa Johnson                                  const GlobalValue *DGV) {
838c7ed52f2STeresa Johnson   GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
839c7ed52f2STeresa Johnson   if (DGV)
840eb5e0a77SRafael Espindola     Visibility = getMinVisibility(DGV->getVisibility(), Visibility);
841c7ed52f2STeresa Johnson   // For promoted locals, mark them hidden so that they can later be
842c7ed52f2STeresa Johnson   // stripped from the symbol table to reduce bloat.
843c7ed52f2STeresa Johnson   if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
844c7ed52f2STeresa Johnson     Visibility = GlobalValue::HiddenVisibility;
845c7ed52f2STeresa Johnson   NewGV->setVisibility(Visibility);
846c7ed52f2STeresa Johnson }
847c7ed52f2STeresa Johnson 
848c7ed52f2STeresa Johnson GlobalValue *ModuleLinker::copyGlobalValueProto(TypeMapTy &TypeMap,
849c7ed52f2STeresa Johnson                                                 const GlobalValue *SGV,
850f3518c95SRafael Espindola                                                 const GlobalValue *DGV,
851f3518c95SRafael Espindola                                                 bool ForDefinition) {
852ef23711eSRafael Espindola   GlobalValue *NewGV;
853f3518c95SRafael Espindola   if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
854c7ed52f2STeresa Johnson     NewGV = copyGlobalVariableProto(TypeMap, SGVar);
855f3518c95SRafael Espindola   } else if (auto *SF = dyn_cast<Function>(SGV)) {
856c7ed52f2STeresa Johnson     NewGV = copyFunctionProto(TypeMap, SF);
857f3518c95SRafael Espindola   } else {
858f3518c95SRafael Espindola     if (ForDefinition)
859c7ed52f2STeresa Johnson       NewGV = copyGlobalAliasProto(TypeMap, cast<GlobalAlias>(SGV));
860f3518c95SRafael Espindola     else
861f3518c95SRafael Espindola       NewGV = new GlobalVariable(
862f3518c95SRafael Espindola           DstM, TypeMap.get(SGV->getType()->getElementType()),
863f3518c95SRafael Espindola           /*isConstant*/ false, GlobalValue::ExternalLinkage,
864f3518c95SRafael Espindola           /*init*/ nullptr, getName(SGV),
865f3518c95SRafael Espindola           /*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
866f3518c95SRafael Espindola           SGV->getType()->getAddressSpace());
867f3518c95SRafael Espindola   }
868f3518c95SRafael Espindola 
869f3518c95SRafael Espindola   if (ForDefinition)
870f3518c95SRafael Espindola     NewGV->setLinkage(getLinkage(SGV));
871f3518c95SRafael Espindola   else if (SGV->hasAvailableExternallyLinkage() || SGV->hasWeakLinkage() ||
872f3518c95SRafael Espindola            SGV->hasLinkOnceLinkage())
873f3518c95SRafael Espindola     NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
874f3518c95SRafael Espindola 
875ef23711eSRafael Espindola   copyGVAttributes(NewGV, SGV);
876c7ed52f2STeresa Johnson   setVisibility(NewGV, SGV, DGV);
877ef23711eSRafael Espindola   return NewGV;
878ef23711eSRafael Espindola }
879ef23711eSRafael Espindola 
88019b52383SRafael Espindola Value *ValueMaterializerTy::materializeDeclFor(Value *V) {
88119b52383SRafael Espindola   return ModLinker->materializeDeclFor(V);
88219b52383SRafael Espindola }
88319b52383SRafael Espindola 
88419b52383SRafael Espindola Value *ModuleLinker::materializeDeclFor(Value *V) {
885ef23711eSRafael Espindola   auto *SGV = dyn_cast<GlobalValue>(V);
886ef23711eSRafael Espindola   if (!SGV)
887ef23711eSRafael Espindola     return nullptr;
888ef23711eSRafael Espindola 
8891063293aSTeresa Johnson   // If we are done linking global value bodies (i.e. we are performing
8901063293aSTeresa Johnson   // metadata linking), don't link in the global value due to this
8911063293aSTeresa Johnson   // reference, simply map it to null.
8926d2c313bSRafael Espindola   if (DoneLinkingBodies)
8931063293aSTeresa Johnson     return nullptr;
8941063293aSTeresa Johnson 
895baa3bf8fSRafael Espindola   linkGlobalValueProto(SGV);
896baa3bf8fSRafael Espindola   if (HasError)
897baa3bf8fSRafael Espindola     return nullptr;
898baa3bf8fSRafael Espindola   Value *Ret = ValueMap[SGV];
899baa3bf8fSRafael Espindola   assert(Ret);
900baa3bf8fSRafael Espindola   return Ret;
901f6f121e2SJames Molloy }
902f6f121e2SJames Molloy 
90319b52383SRafael Espindola void ValueMaterializerTy::materializeInitFor(GlobalValue *New,
90419b52383SRafael Espindola                                              GlobalValue *Old) {
90519b52383SRafael Espindola   return ModLinker->materializeInitFor(New, Old);
90619b52383SRafael Espindola }
90719b52383SRafael Espindola 
90819b52383SRafael Espindola void ModuleLinker::materializeInitFor(GlobalValue *New, GlobalValue *Old) {
909baa3bf8fSRafael Espindola   if (auto *F = dyn_cast<Function>(New)) {
910baa3bf8fSRafael Espindola     if (!F->isDeclaration())
911baa3bf8fSRafael Espindola       return;
912baa3bf8fSRafael Espindola   } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
913baa3bf8fSRafael Espindola     if (V->hasInitializer())
914baa3bf8fSRafael Espindola       return;
915baa3bf8fSRafael Espindola   } else {
916baa3bf8fSRafael Espindola     auto *A = cast<GlobalAlias>(New);
917baa3bf8fSRafael Espindola     if (A->getAliasee())
918baa3bf8fSRafael Espindola       return;
919baa3bf8fSRafael Espindola   }
920baa3bf8fSRafael Espindola 
921baa3bf8fSRafael Espindola   if (Old->isDeclaration())
922baa3bf8fSRafael Espindola     return;
923baa3bf8fSRafael Espindola 
92419b52383SRafael Espindola   if (isPerformingImport() && !doImportAsDefinition(Old))
92519b52383SRafael Espindola     return;
92619b52383SRafael Espindola 
927baa3bf8fSRafael Espindola   if (!New->hasLocalLinkage() && DoNotLinkFromSource.count(Old))
92819b52383SRafael Espindola     return;
92919b52383SRafael Espindola 
930e39cd5b1SRafael Espindola   linkGlobalValueBody(*New, *Old);
93119b52383SRafael Espindola }
93219b52383SRafael Espindola 
9330e309fe8SRafael Espindola bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
934dad0a645SDavid Majnemer                                    const GlobalVariable *&GVar) {
9350e309fe8SRafael Espindola   const GlobalValue *GVal = M.getNamedValue(ComdatName);
936dad0a645SDavid Majnemer   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
937dad0a645SDavid Majnemer     GVal = GA->getBaseObject();
938dad0a645SDavid Majnemer     if (!GVal)
939dad0a645SDavid Majnemer       // We cannot resolve the size of the aliasee yet.
940dad0a645SDavid Majnemer       return emitError("Linking COMDATs named '" + ComdatName +
941dad0a645SDavid Majnemer                        "': COMDAT key involves incomputable alias size.");
942dad0a645SDavid Majnemer   }
943dad0a645SDavid Majnemer 
944dad0a645SDavid Majnemer   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
945dad0a645SDavid Majnemer   if (!GVar)
946dad0a645SDavid Majnemer     return emitError(
947dad0a645SDavid Majnemer         "Linking COMDATs named '" + ComdatName +
948dad0a645SDavid Majnemer         "': GlobalVariable required for data dependent selection!");
949dad0a645SDavid Majnemer 
950dad0a645SDavid Majnemer   return false;
951dad0a645SDavid Majnemer }
952dad0a645SDavid Majnemer 
953dad0a645SDavid Majnemer bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
954dad0a645SDavid Majnemer                                                  Comdat::SelectionKind Src,
955dad0a645SDavid Majnemer                                                  Comdat::SelectionKind Dst,
956dad0a645SDavid Majnemer                                                  Comdat::SelectionKind &Result,
957dad0a645SDavid Majnemer                                                  bool &LinkFromSrc) {
958dad0a645SDavid Majnemer   // The ability to mix Comdat::SelectionKind::Any with
959dad0a645SDavid Majnemer   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
960dad0a645SDavid Majnemer   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
961dad0a645SDavid Majnemer                          Dst == Comdat::SelectionKind::Largest;
962dad0a645SDavid Majnemer   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
963dad0a645SDavid Majnemer                          Src == Comdat::SelectionKind::Largest;
964dad0a645SDavid Majnemer   if (DstAnyOrLargest && SrcAnyOrLargest) {
965dad0a645SDavid Majnemer     if (Dst == Comdat::SelectionKind::Largest ||
966dad0a645SDavid Majnemer         Src == Comdat::SelectionKind::Largest)
967dad0a645SDavid Majnemer       Result = Comdat::SelectionKind::Largest;
968dad0a645SDavid Majnemer     else
969dad0a645SDavid Majnemer       Result = Comdat::SelectionKind::Any;
970dad0a645SDavid Majnemer   } else if (Src == Dst) {
971dad0a645SDavid Majnemer     Result = Dst;
972dad0a645SDavid Majnemer   } else {
973dad0a645SDavid Majnemer     return emitError("Linking COMDATs named '" + ComdatName +
974dad0a645SDavid Majnemer                      "': invalid selection kinds!");
975dad0a645SDavid Majnemer   }
976dad0a645SDavid Majnemer 
977dad0a645SDavid Majnemer   switch (Result) {
978dad0a645SDavid Majnemer   case Comdat::SelectionKind::Any:
979dad0a645SDavid Majnemer     // Go with Dst.
980dad0a645SDavid Majnemer     LinkFromSrc = false;
981dad0a645SDavid Majnemer     break;
982dad0a645SDavid Majnemer   case Comdat::SelectionKind::NoDuplicates:
983dad0a645SDavid Majnemer     return emitError("Linking COMDATs named '" + ComdatName +
984dad0a645SDavid Majnemer                      "': noduplicates has been violated!");
985dad0a645SDavid Majnemer   case Comdat::SelectionKind::ExactMatch:
986dad0a645SDavid Majnemer   case Comdat::SelectionKind::Largest:
987dad0a645SDavid Majnemer   case Comdat::SelectionKind::SameSize: {
988dad0a645SDavid Majnemer     const GlobalVariable *DstGV;
989dad0a645SDavid Majnemer     const GlobalVariable *SrcGV;
990dad0a645SDavid Majnemer     if (getComdatLeader(DstM, ComdatName, DstGV) ||
991dad0a645SDavid Majnemer         getComdatLeader(SrcM, ComdatName, SrcGV))
992dad0a645SDavid Majnemer       return true;
993dad0a645SDavid Majnemer 
9940e309fe8SRafael Espindola     const DataLayout &DstDL = DstM.getDataLayout();
9950e309fe8SRafael Espindola     const DataLayout &SrcDL = SrcM.getDataLayout();
996dad0a645SDavid Majnemer     uint64_t DstSize =
99746a43556SMehdi Amini         DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
998dad0a645SDavid Majnemer     uint64_t SrcSize =
99946a43556SMehdi Amini         SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
1000dad0a645SDavid Majnemer     if (Result == Comdat::SelectionKind::ExactMatch) {
1001dad0a645SDavid Majnemer       if (SrcGV->getInitializer() != DstGV->getInitializer())
1002dad0a645SDavid Majnemer         return emitError("Linking COMDATs named '" + ComdatName +
1003dad0a645SDavid Majnemer                          "': ExactMatch violated!");
1004dad0a645SDavid Majnemer       LinkFromSrc = false;
1005dad0a645SDavid Majnemer     } else if (Result == Comdat::SelectionKind::Largest) {
1006dad0a645SDavid Majnemer       LinkFromSrc = SrcSize > DstSize;
1007dad0a645SDavid Majnemer     } else if (Result == Comdat::SelectionKind::SameSize) {
1008dad0a645SDavid Majnemer       if (SrcSize != DstSize)
1009dad0a645SDavid Majnemer         return emitError("Linking COMDATs named '" + ComdatName +
1010dad0a645SDavid Majnemer                          "': SameSize violated!");
1011dad0a645SDavid Majnemer       LinkFromSrc = false;
1012dad0a645SDavid Majnemer     } else {
1013dad0a645SDavid Majnemer       llvm_unreachable("unknown selection kind");
1014dad0a645SDavid Majnemer     }
1015dad0a645SDavid Majnemer     break;
1016dad0a645SDavid Majnemer   }
1017dad0a645SDavid Majnemer   }
1018dad0a645SDavid Majnemer 
1019dad0a645SDavid Majnemer   return false;
1020dad0a645SDavid Majnemer }
1021dad0a645SDavid Majnemer 
1022dad0a645SDavid Majnemer bool ModuleLinker::getComdatResult(const Comdat *SrcC,
1023dad0a645SDavid Majnemer                                    Comdat::SelectionKind &Result,
1024dad0a645SDavid Majnemer                                    bool &LinkFromSrc) {
1025b16196a3SRafael Espindola   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
1026dad0a645SDavid Majnemer   StringRef ComdatName = SrcC->getName();
10270e309fe8SRafael Espindola   Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
1028dad0a645SDavid Majnemer   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
10292ef3f299SRafael Espindola 
1030b16196a3SRafael Espindola   if (DstCI == ComdatSymTab.end()) {
1031b16196a3SRafael Espindola     // Use the comdat if it is only available in one of the modules.
1032b16196a3SRafael Espindola     LinkFromSrc = true;
1033b16196a3SRafael Espindola     Result = SSK;
10342ef3f299SRafael Espindola     return false;
1035b16196a3SRafael Espindola   }
10362ef3f299SRafael Espindola 
1037dad0a645SDavid Majnemer   const Comdat *DstC = &DstCI->second;
1038dad0a645SDavid Majnemer   Comdat::SelectionKind DSK = DstC->getSelectionKind();
10392ef3f299SRafael Espindola   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
10402ef3f299SRafael Espindola                                        LinkFromSrc);
1041dad0a645SDavid Majnemer }
1042f6f121e2SJames Molloy 
1043d12b4a33SRafael Espindola bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
1044d12b4a33SRafael Espindola                                         const GlobalValue &Dest,
1045dbb0bd1aSRafael Espindola                                         const GlobalValue &Src) {
1046e868123dSDuncan P. N. Exon Smith   // Should we unconditionally use the Src?
1047020d4fb1SArtem Belevich   if (shouldOverrideFromSrc()) {
1048e868123dSDuncan P. N. Exon Smith     LinkFromSrc = true;
1049e868123dSDuncan P. N. Exon Smith     return false;
1050e868123dSDuncan P. N. Exon Smith   }
1051e868123dSDuncan P. N. Exon Smith 
1052778fcc77SRafael Espindola   // We always have to add Src if it has appending linkage.
1053778fcc77SRafael Espindola   if (Src.hasAppendingLinkage()) {
1054c7ed52f2STeresa Johnson     // Caller should have already determined that we can't link from source
1055c7ed52f2STeresa Johnson     // when importing (see comments in linkGlobalValueProto).
1056c7ed52f2STeresa Johnson     assert(!isPerformingImport());
1057778fcc77SRafael Espindola     LinkFromSrc = true;
1058778fcc77SRafael Espindola     return false;
1059778fcc77SRafael Espindola   }
1060778fcc77SRafael Espindola 
1061d4bcefc7SRafael Espindola   bool SrcIsDeclaration = Src.isDeclarationForLinker();
1062d4bcefc7SRafael Espindola   bool DestIsDeclaration = Dest.isDeclarationForLinker();
1063dbb0bd1aSRafael Espindola 
1064c7ed52f2STeresa Johnson   if (isPerformingImport()) {
1065c7ed52f2STeresa Johnson     if (isa<Function>(&Src)) {
1066c7ed52f2STeresa Johnson       // For functions, LinkFromSrc iff this is the function requested
1067c7ed52f2STeresa Johnson       // for importing. For variables, decide below normally.
1068ffe2e4aaSMehdi Amini       LinkFromSrc = ImportFunction->count(&Src);
1069c7ed52f2STeresa Johnson       return false;
1070c7ed52f2STeresa Johnson     }
1071c7ed52f2STeresa Johnson 
1072c7ed52f2STeresa Johnson     // Check if this is an alias with an already existing definition
1073c7ed52f2STeresa Johnson     // in Dest, which must have come from a prior importing pass from
1074c7ed52f2STeresa Johnson     // the same Src module. Unlike imported function and variable
1075c7ed52f2STeresa Johnson     // definitions, which are imported as available_externally and are
1076c7ed52f2STeresa Johnson     // not definitions for the linker, that is not a valid linkage for
1077c7ed52f2STeresa Johnson     // imported aliases which must be definitions. Simply use the existing
1078c7ed52f2STeresa Johnson     // Dest copy.
1079c7ed52f2STeresa Johnson     if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
1080c7ed52f2STeresa Johnson       assert(isa<GlobalAlias>(&Dest));
1081c7ed52f2STeresa Johnson       LinkFromSrc = false;
1082c7ed52f2STeresa Johnson       return false;
1083c7ed52f2STeresa Johnson     }
1084c7ed52f2STeresa Johnson   }
1085c7ed52f2STeresa Johnson 
1086dbb0bd1aSRafael Espindola   if (SrcIsDeclaration) {
1087dbb0bd1aSRafael Espindola     // If Src is external or if both Src & Dest are external..  Just link the
1088dbb0bd1aSRafael Espindola     // external globals, we aren't adding anything.
1089d12b4a33SRafael Espindola     if (Src.hasDLLImportStorageClass()) {
1090dbb0bd1aSRafael Espindola       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
1091d12b4a33SRafael Espindola       LinkFromSrc = DestIsDeclaration;
1092d12b4a33SRafael Espindola       return false;
1093d12b4a33SRafael Espindola     }
1094dbb0bd1aSRafael Espindola     // If the Dest is weak, use the source linkage.
1095d12b4a33SRafael Espindola     LinkFromSrc = Dest.hasExternalWeakLinkage();
1096d12b4a33SRafael Espindola     return false;
1097dbb0bd1aSRafael Espindola   }
1098dbb0bd1aSRafael Espindola 
1099d12b4a33SRafael Espindola   if (DestIsDeclaration) {
1100dbb0bd1aSRafael Espindola     // If Dest is external but Src is not:
1101d12b4a33SRafael Espindola     LinkFromSrc = true;
1102d12b4a33SRafael Espindola     return false;
1103d12b4a33SRafael Espindola   }
1104dbb0bd1aSRafael Espindola 
11050910605aSRafael Espindola   if (Src.hasCommonLinkage()) {
1106d12b4a33SRafael Espindola     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
1107d12b4a33SRafael Espindola       LinkFromSrc = true;
11080910605aSRafael Espindola       return false;
1109d12b4a33SRafael Espindola     }
1110d12b4a33SRafael Espindola 
1111d12b4a33SRafael Espindola     if (!Dest.hasCommonLinkage()) {
1112d12b4a33SRafael Espindola       LinkFromSrc = false;
1113d12b4a33SRafael Espindola       return false;
1114d12b4a33SRafael Espindola     }
11150910605aSRafael Espindola 
1116a28d91d8SMehdi Amini     const DataLayout &DL = Dest.getParent()->getDataLayout();
11170910605aSRafael Espindola     uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
11180910605aSRafael Espindola     uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
1119d12b4a33SRafael Espindola     LinkFromSrc = SrcSize > DestSize;
1120d12b4a33SRafael Espindola     return false;
11210910605aSRafael Espindola   }
11220910605aSRafael Espindola 
1123dbb0bd1aSRafael Espindola   if (Src.isWeakForLinker()) {
1124dbb0bd1aSRafael Espindola     assert(!Dest.hasExternalWeakLinkage());
1125dbb0bd1aSRafael Espindola     assert(!Dest.hasAvailableExternallyLinkage());
11260910605aSRafael Espindola 
1127d12b4a33SRafael Espindola     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
1128d12b4a33SRafael Espindola       LinkFromSrc = true;
1129d12b4a33SRafael Espindola       return false;
1130d12b4a33SRafael Espindola     }
1131dbb0bd1aSRafael Espindola 
1132d12b4a33SRafael Espindola     LinkFromSrc = false;
11330910605aSRafael Espindola     return false;
1134dbb0bd1aSRafael Espindola   }
1135dbb0bd1aSRafael Espindola 
1136dbb0bd1aSRafael Espindola   if (Dest.isWeakForLinker()) {
1137dbb0bd1aSRafael Espindola     assert(Src.hasExternalLinkage());
1138d12b4a33SRafael Espindola     LinkFromSrc = true;
1139d12b4a33SRafael Espindola     return false;
1140dbb0bd1aSRafael Espindola   }
1141dbb0bd1aSRafael Espindola 
1142dbb0bd1aSRafael Espindola   assert(!Src.hasExternalWeakLinkage());
1143dbb0bd1aSRafael Espindola   assert(!Dest.hasExternalWeakLinkage());
1144dbb0bd1aSRafael Espindola   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
1145dbb0bd1aSRafael Espindola          "Unexpected linkage type!");
1146dbb0bd1aSRafael Espindola   return emitError("Linking globals named '" + Src.getName() +
1147dbb0bd1aSRafael Espindola                    "': symbol multiply defined!");
1148dbb0bd1aSRafael Espindola }
1149dbb0bd1aSRafael Espindola 
115018c89411SRafael Espindola /// Loop over all of the linked values to compute type mappings.  For example,
115118c89411SRafael Espindola /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
115218c89411SRafael Espindola /// types 'Foo' but one got renamed when the module was loaded into the same
115318c89411SRafael Espindola /// LLVMContext.
1154b1ed91f3SChris Lattner void ModuleLinker::computeTypeMapping() {
11550e309fe8SRafael Espindola   for (GlobalValue &SGV : SrcM.globals()) {
1156c8a476eeSRafael Espindola     GlobalValue *DGV = getLinkedToGlobal(&SGV);
1157c8a476eeSRafael Espindola     if (!DGV)
1158c8a476eeSRafael Espindola       continue;
1159b1ed91f3SChris Lattner 
1160c8a476eeSRafael Espindola     if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
1161c8a476eeSRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1162b1ed91f3SChris Lattner       continue;
11635c310be0SDevang Patel     }
11645c310be0SDevang Patel 
1165b1ed91f3SChris Lattner     // Unify the element type of appending arrays.
1166b1ed91f3SChris Lattner     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
1167c8a476eeSRafael Espindola     ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
1168b1ed91f3SChris Lattner     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
1169b1ed91f3SChris Lattner   }
117034fc5a0eSChris Lattner 
11710e309fe8SRafael Espindola   for (GlobalValue &SGV : SrcM) {
1172c8a476eeSRafael Espindola     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1173c8a476eeSRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1174b1ed91f3SChris Lattner   }
1175e79f4c77SAnton Korobeynikov 
11760e309fe8SRafael Espindola   for (GlobalValue &SGV : SrcM.aliases()) {
1177e96d7eb8SRafael Espindola     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1178e96d7eb8SRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1179e96d7eb8SRafael Espindola   }
1180e96d7eb8SRafael Espindola 
1181d48b7783SBill Wendling   // Incorporate types by name, scanning all the types in the source module.
1182d48b7783SBill Wendling   // At this point, the destination module may have a type "%foo = { i32 }" for
11832b3f61afSBill Wendling   // example.  When the source module got loaded into the same LLVMContext, if
11842b3f61afSBill Wendling   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
11850e309fe8SRafael Espindola   std::vector<StructType *> Types = SrcM.getIdentifiedStructTypes();
11862fa1e43aSRafael Espindola   for (StructType *ST : Types) {
11874d4c9387SRafael Espindola     if (!ST->hasName())
11884d4c9387SRafael Espindola       continue;
11892b3f61afSBill Wendling 
11902b3f61afSBill Wendling     // Check to see if there is a dot in the name followed by a digit.
1191d48b7783SBill Wendling     size_t DotPos = ST->getName().rfind('.');
1192d48b7783SBill Wendling     if (DotPos == 0 || DotPos == StringRef::npos ||
119383c74e9fSGuy Benyei         ST->getName().back() == '.' ||
119483c74e9fSGuy Benyei         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
1195d48b7783SBill Wendling       continue;
11962b3f61afSBill Wendling 
11972b3f61afSBill Wendling     // Check to see if the destination module has a struct with the prefix name.
11980e309fe8SRafael Espindola     StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
1199973b3612SRafael Espindola     if (!DST)
1200973b3612SRafael Espindola       continue;
1201973b3612SRafael Espindola 
12022b3f61afSBill Wendling     // Don't use it if this actually came from the source module. They're in
12038737480dSBill Wendling     // the same LLVMContext after all. Also don't use it unless the type is
12048737480dSBill Wendling     // actually used in the destination module. This can happen in situations
12058737480dSBill Wendling     // like this:
12068737480dSBill Wendling     //
12078737480dSBill Wendling     //      Module A                         Module B
12088737480dSBill Wendling     //      --------                         --------
12098737480dSBill Wendling     //   %Z = type { %A }                %B = type { %C.1 }
12108737480dSBill Wendling     //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
12118737480dSBill Wendling     //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
12128737480dSBill Wendling     //   %C = type { i8* }               %B.3 = type { %C.1 }
12138737480dSBill Wendling     //
12148737480dSBill Wendling     // When we link Module B with Module A, the '%B' in Module B is
12158737480dSBill Wendling     // used. However, that would then use '%C.1'. But when we process '%C.1',
12168737480dSBill Wendling     // we prefer to take the '%C' version. So we are then left with both
12178737480dSBill Wendling     // '%C.1' and '%C' being used for the same types. This leads to some
12188737480dSBill Wendling     // variables using one type and some using the other.
121931ad468dSRafael Espindola     if (TypeMap.DstStructTypesSet.hasType(DST))
12202b3f61afSBill Wendling       TypeMap.addTypeMapping(DST, ST);
12212b3f61afSBill Wendling   }
12222b3f61afSBill Wendling 
1223b1ed91f3SChris Lattner   // Now that we have discovered all of the type equivalences, get a body for
1224b1ed91f3SChris Lattner   // any 'opaque' types in the dest module that are now resolved.
1225b1ed91f3SChris Lattner   TypeMap.linkDefinedTypeBodies();
1226b1ed91f3SChris Lattner }
1227c08e7a00SChris Lattner 
122809d84addSDuncan P. N. Exon Smith static void upgradeGlobalArray(GlobalVariable *GV) {
122909d84addSDuncan P. N. Exon Smith   ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
123009d84addSDuncan P. N. Exon Smith   StructType *OldTy = cast<StructType>(ATy->getElementType());
123109d84addSDuncan P. N. Exon Smith   assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
123209d84addSDuncan P. N. Exon Smith 
123309d84addSDuncan P. N. Exon Smith   // Get the upgraded 3 element type.
123409d84addSDuncan P. N. Exon Smith   PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
123509d84addSDuncan P. N. Exon Smith   Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
123609d84addSDuncan P. N. Exon Smith                   VoidPtrTy};
123709d84addSDuncan P. N. Exon Smith   StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
123809d84addSDuncan P. N. Exon Smith 
123909d84addSDuncan P. N. Exon Smith   // Build new constants with a null third field filled in.
124009d84addSDuncan P. N. Exon Smith   Constant *OldInitC = GV->getInitializer();
124109d84addSDuncan P. N. Exon Smith   ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
124209d84addSDuncan P. N. Exon Smith   if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
124309d84addSDuncan P. N. Exon Smith     // Invalid initializer; give up.
124409d84addSDuncan P. N. Exon Smith     return;
124509d84addSDuncan P. N. Exon Smith   std::vector<Constant *> Initializers;
124609d84addSDuncan P. N. Exon Smith   if (OldInit && OldInit->getNumOperands()) {
124709d84addSDuncan P. N. Exon Smith     Value *Null = Constant::getNullValue(VoidPtrTy);
124809d84addSDuncan P. N. Exon Smith     for (Use &U : OldInit->operands()) {
124909d84addSDuncan P. N. Exon Smith       ConstantStruct *Init = cast<ConstantStruct>(U.get());
125009d84addSDuncan P. N. Exon Smith       Initializers.push_back(ConstantStruct::get(
125109d84addSDuncan P. N. Exon Smith           NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
125209d84addSDuncan P. N. Exon Smith     }
125309d84addSDuncan P. N. Exon Smith   }
125409d84addSDuncan P. N. Exon Smith   assert(Initializers.size() == ATy->getNumElements() &&
125509d84addSDuncan P. N. Exon Smith          "Failed to copy all array elements");
125609d84addSDuncan P. N. Exon Smith 
125709d84addSDuncan P. N. Exon Smith   // Replace the old GV with a new one.
125809d84addSDuncan P. N. Exon Smith   ATy = ArrayType::get(NewTy, Initializers.size());
125909d84addSDuncan P. N. Exon Smith   Constant *NewInit = ConstantArray::get(ATy, Initializers);
126009d84addSDuncan P. N. Exon Smith   GlobalVariable *NewGV = new GlobalVariable(
126109d84addSDuncan P. N. Exon Smith       *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
126209d84addSDuncan P. N. Exon Smith       GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
126309d84addSDuncan P. N. Exon Smith       GV->isExternallyInitialized());
126409d84addSDuncan P. N. Exon Smith   NewGV->copyAttributesFrom(GV);
126509d84addSDuncan P. N. Exon Smith   NewGV->takeName(GV);
126609d84addSDuncan P. N. Exon Smith   assert(GV->use_empty() && "program cannot use initializer list");
126709d84addSDuncan P. N. Exon Smith   GV->eraseFromParent();
126809d84addSDuncan P. N. Exon Smith }
126909d84addSDuncan P. N. Exon Smith 
127009d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
127109d84addSDuncan P. N. Exon Smith   // Look for the global arrays.
12720e309fe8SRafael Espindola   auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM.getNamedValue(Name));
127309d84addSDuncan P. N. Exon Smith   if (!DstGV)
127409d84addSDuncan P. N. Exon Smith     return;
12750e309fe8SRafael Espindola   auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM.getNamedValue(Name));
127609d84addSDuncan P. N. Exon Smith   if (!SrcGV)
127709d84addSDuncan P. N. Exon Smith     return;
127809d84addSDuncan P. N. Exon Smith 
127909d84addSDuncan P. N. Exon Smith   // Check if the types already match.
128009d84addSDuncan P. N. Exon Smith   auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
128109d84addSDuncan P. N. Exon Smith   auto *SrcTy =
128209d84addSDuncan P. N. Exon Smith       cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
128309d84addSDuncan P. N. Exon Smith   if (DstTy == SrcTy)
128409d84addSDuncan P. N. Exon Smith     return;
128509d84addSDuncan P. N. Exon Smith 
128609d84addSDuncan P. N. Exon Smith   // Grab the element types.  We can only upgrade an array of a two-field
128709d84addSDuncan P. N. Exon Smith   // struct.  Only bother if the other one has three-fields.
128809d84addSDuncan P. N. Exon Smith   auto *DstEltTy = cast<StructType>(DstTy->getElementType());
128909d84addSDuncan P. N. Exon Smith   auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
129009d84addSDuncan P. N. Exon Smith   if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
129109d84addSDuncan P. N. Exon Smith     upgradeGlobalArray(DstGV);
129209d84addSDuncan P. N. Exon Smith     return;
129309d84addSDuncan P. N. Exon Smith   }
129409d84addSDuncan P. N. Exon Smith   if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
129509d84addSDuncan P. N. Exon Smith     upgradeGlobalArray(SrcGV);
129609d84addSDuncan P. N. Exon Smith 
129709d84addSDuncan P. N. Exon Smith   // We can't upgrade any other differences.
129809d84addSDuncan P. N. Exon Smith }
129909d84addSDuncan P. N. Exon Smith 
130009d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobals() {
130109d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobalArray("llvm.global_ctors");
130209d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobalArray("llvm.global_dtors");
130309d84addSDuncan P. N. Exon Smith }
130409d84addSDuncan P. N. Exon Smith 
13056e8ab928SRafael Espindola static void getArrayElements(const Constant *C,
13066e8ab928SRafael Espindola                              SmallVectorImpl<Constant *> &Dest) {
13076e8ab928SRafael Espindola   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
13086e8ab928SRafael Espindola 
13096e8ab928SRafael Espindola   for (unsigned i = 0; i != NumElements; ++i)
13106e8ab928SRafael Espindola     Dest.push_back(C->getAggregateElement(i));
13116e8ab928SRafael Espindola }
13126e8ab928SRafael Espindola 
131318c89411SRafael Espindola /// If there were any appending global variables, link them together now.
131418c89411SRafael Espindola /// Return true on error.
1315b1ed91f3SChris Lattner bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
13163e8bc6a8SRafael Espindola                                          const GlobalVariable *SrcGV) {
1317b1ed91f3SChris Lattner   ArrayType *SrcTy =
1318b1ed91f3SChris Lattner       cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
1319c945c8d2SRafael Espindola   Type *EltTy = SrcTy->getElementType();
1320c945c8d2SRafael Espindola 
1321c945c8d2SRafael Espindola   if (DstGV) {
1322c945c8d2SRafael Espindola     ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
1323c945c8d2SRafael Espindola 
1324c945c8d2SRafael Espindola     if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
1325c945c8d2SRafael Espindola       return emitError(
1326c945c8d2SRafael Espindola           "Linking globals named '" + SrcGV->getName() +
1327c945c8d2SRafael Espindola           "': can only link appending global with another appending global!");
1328b1ed91f3SChris Lattner 
1329b1ed91f3SChris Lattner     // Check to see that they two arrays agree on type.
1330c945c8d2SRafael Espindola     if (EltTy != DstTy->getElementType())
1331b1ed91f3SChris Lattner       return emitError("Appending variables with different element types!");
1332b1ed91f3SChris Lattner     if (DstGV->isConstant() != SrcGV->isConstant())
1333b1ed91f3SChris Lattner       return emitError("Appending variables linked with different const'ness!");
1334b1ed91f3SChris Lattner 
1335b1ed91f3SChris Lattner     if (DstGV->getAlignment() != SrcGV->getAlignment())
1336b1ed91f3SChris Lattner       return emitError(
1337b1ed91f3SChris Lattner           "Appending variables with different alignment need to be linked!");
1338b1ed91f3SChris Lattner 
1339b1ed91f3SChris Lattner     if (DstGV->getVisibility() != SrcGV->getVisibility())
1340b1ed91f3SChris Lattner       return emitError(
1341b1ed91f3SChris Lattner           "Appending variables with different visibility need to be linked!");
1342b1ed91f3SChris Lattner 
1343fac3a018SRafael Espindola     if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
1344fac3a018SRafael Espindola       return emitError(
1345fac3a018SRafael Espindola           "Appending variables with different unnamed_addr need to be linked!");
1346fac3a018SRafael Espindola 
134764c1e180SRafael Espindola     if (StringRef(DstGV->getSection()) != SrcGV->getSection())
1348b1ed91f3SChris Lattner       return emitError(
1349b1ed91f3SChris Lattner           "Appending variables with different section name need to be linked!");
1350c945c8d2SRafael Espindola   }
1351b1ed91f3SChris Lattner 
13526e8ab928SRafael Espindola   SmallVector<Constant *, 16> DstElements;
13536e8ab928SRafael Espindola   if (DstGV)
13546e8ab928SRafael Espindola     getArrayElements(DstGV->getInitializer(), DstElements);
13556e8ab928SRafael Espindola 
13566e8ab928SRafael Espindola   SmallVector<Constant *, 16> SrcElements;
13576e8ab928SRafael Espindola   getArrayElements(SrcGV->getInitializer(), SrcElements);
13586e8ab928SRafael Espindola 
13596e8ab928SRafael Espindola   StringRef Name = SrcGV->getName();
13606e8ab928SRafael Espindola   bool IsNewStructor =
13616e8ab928SRafael Espindola       (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
13626e8ab928SRafael Espindola       cast<StructType>(EltTy)->getNumElements() == 3;
13636e8ab928SRafael Espindola   if (IsNewStructor)
13646e8ab928SRafael Espindola     SrcElements.erase(
13656e8ab928SRafael Espindola         std::remove_if(SrcElements.begin(), SrcElements.end(),
13666e8ab928SRafael Espindola                        [this](Constant *E) {
13676e8ab928SRafael Espindola                          auto *Key = dyn_cast<GlobalValue>(
13686e8ab928SRafael Espindola                              E->getAggregateElement(2)->stripPointerCasts());
13696e8ab928SRafael Espindola                          return DoNotLinkFromSource.count(Key);
13706e8ab928SRafael Espindola                        }),
13716e8ab928SRafael Espindola         SrcElements.end());
13726e8ab928SRafael Espindola   uint64_t NewSize = DstElements.size() + SrcElements.size();
1373b1ed91f3SChris Lattner   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
1374b1ed91f3SChris Lattner 
1375b1ed91f3SChris Lattner   // Create the new global variable.
1376c945c8d2SRafael Espindola   GlobalVariable *NG = new GlobalVariable(
13770e309fe8SRafael Espindola       DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
1378c945c8d2SRafael Espindola       /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
1379c945c8d2SRafael Espindola       SrcGV->getType()->getAddressSpace());
1380b1ed91f3SChris Lattner 
1381b1ed91f3SChris Lattner   // Propagate alignment, visibility and section info.
1382c945c8d2SRafael Espindola   copyGVAttributes(NG, SrcGV);
1383b1ed91f3SChris Lattner 
1384b1ed91f3SChris Lattner   // Replace any uses of the two global variables with uses of the new
1385b1ed91f3SChris Lattner   // global.
1386b1ed91f3SChris Lattner   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
1387b1ed91f3SChris Lattner 
13886e8ab928SRafael Espindola   for (auto *V : SrcElements) {
13896e8ab928SRafael Espindola     DstElements.push_back(
13906e8ab928SRafael Espindola         MapValue(V, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
13916e8ab928SRafael Espindola   }
13926e8ab928SRafael Espindola 
13936e8ab928SRafael Espindola   NG->setInitializer(ConstantArray::get(NewType, DstElements));
13946e8ab928SRafael Espindola 
1395c945c8d2SRafael Espindola   if (DstGV) {
1396b1ed91f3SChris Lattner     DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
1397b1ed91f3SChris Lattner     DstGV->eraseFromParent();
1398c945c8d2SRafael Espindola   }
1399b1ed91f3SChris Lattner 
1400b1ed91f3SChris Lattner   return false;
1401b1ed91f3SChris Lattner }
1402b1ed91f3SChris Lattner 
1403778fcc77SRafael Espindola bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
1404b1ed91f3SChris Lattner   GlobalValue *DGV = getLinkedToGlobal(SGV);
1405b1ed91f3SChris Lattner 
1406778fcc77SRafael Espindola   // Handle the ultra special appending linkage case first.
1407c7ed52f2STeresa Johnson   assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
1408c7ed52f2STeresa Johnson   if (SGV->hasAppendingLinkage() && isPerformingImport()) {
1409c7ed52f2STeresa Johnson     // Don't want to append to global_ctors list, for example, when we
1410c7ed52f2STeresa Johnson     // are importing for ThinLTO, otherwise the global ctors and dtors
1411c7ed52f2STeresa Johnson     // get executed multiple times for local variables (the latter causing
1412c7ed52f2STeresa Johnson     // double frees).
1413c7ed52f2STeresa Johnson     DoNotLinkFromSource.insert(SGV);
1414c7ed52f2STeresa Johnson     return false;
1415c7ed52f2STeresa Johnson   }
1416c945c8d2SRafael Espindola   if (SGV->hasAppendingLinkage())
1417c945c8d2SRafael Espindola     return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
1418778fcc77SRafael Espindola                                  cast<GlobalVariable>(SGV));
1419778fcc77SRafael Espindola 
1420778fcc77SRafael Espindola   bool LinkFromSrc = true;
1421778fcc77SRafael Espindola   Comdat *C = nullptr;
1422778fcc77SRafael Espindola   bool HasUnnamedAddr = SGV->hasUnnamedAddr();
1423778fcc77SRafael Espindola 
1424dad0a645SDavid Majnemer   if (const Comdat *SC = SGV->getComdat()) {
1425dad0a645SDavid Majnemer     Comdat::SelectionKind SK;
1426dad0a645SDavid Majnemer     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
14270e309fe8SRafael Espindola     C = DstM.getOrInsertComdat(SC->getName());
1428778fcc77SRafael Espindola     C->setSelectionKind(SK);
1429*0a80da0bSRafael Espindola     if (SGV->hasLocalLinkage())
1430baa3bf8fSRafael Espindola       LinkFromSrc = true;
1431778fcc77SRafael Espindola   } else if (DGV) {
1432778fcc77SRafael Espindola     if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1433fc61de39SChris Lattner       return true;
1434dad0a645SDavid Majnemer   }
143534fc5a0eSChris Lattner 
1436dad0a645SDavid Majnemer   if (!LinkFromSrc) {
1437cbb91408STanya Lattner     // Track the source global so that we don't attempt to copy it over when
1438cbb91408STanya Lattner     // processing global initializers.
1439cbb91408STanya Lattner     DoNotLinkFromSource.insert(SGV);
1440cbb91408STanya Lattner 
1441778fcc77SRafael Espindola     if (DGV)
1442778fcc77SRafael Espindola       // Make sure to remember this mapping.
1443778fcc77SRafael Espindola       ValueMap[SGV] =
1444778fcc77SRafael Espindola           ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
1445778fcc77SRafael Espindola   }
1446778fcc77SRafael Espindola 
1447c7ed52f2STeresa Johnson   if (DGV)
1448778fcc77SRafael Espindola     HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1449778fcc77SRafael Espindola 
1450778fcc77SRafael Espindola   GlobalValue *NewGV;
1451baa3bf8fSRafael Espindola   if (!LinkFromSrc && DGV) {
145226c29511SRafael Espindola     NewGV = DGV;
1453c7ed52f2STeresa Johnson     // When linking from source we setVisibility from copyGlobalValueProto.
1454c7ed52f2STeresa Johnson     setVisibility(NewGV, SGV, DGV);
145526c29511SRafael Espindola   } else {
1456f3518c95SRafael Espindola     NewGV = copyGlobalValueProto(TypeMap, SGV, DGV, LinkFromSrc);
14573cd8161cSTeresa Johnson 
14583cd8161cSTeresa Johnson     if (isPerformingImport() && !doImportAsDefinition(SGV))
14593cd8161cSTeresa Johnson       DoNotLinkFromSource.insert(SGV);
1460ef23711eSRafael Espindola   }
1461778fcc77SRafael Espindola 
1462778fcc77SRafael Espindola   NewGV->setUnnamedAddr(HasUnnamedAddr);
1463778fcc77SRafael Espindola 
1464778fcc77SRafael Espindola   if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1465baa3bf8fSRafael Espindola     if (C && LinkFromSrc)
1466778fcc77SRafael Espindola       NewGO->setComdat(C);
1467439835a6SRafael Espindola 
1468439835a6SRafael Espindola     if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1469439835a6SRafael Espindola       NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
1470778fcc77SRafael Espindola   }
1471778fcc77SRafael Espindola 
1472879aeb77SRafael Espindola   if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) {
1473879aeb77SRafael Espindola     auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV);
1474879aeb77SRafael Espindola     auto *SGVar = dyn_cast<GlobalVariable>(SGV);
1475879aeb77SRafael Espindola     if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() &&
1476879aeb77SRafael Espindola         (!DGVar->isConstant() || !SGVar->isConstant()))
1477879aeb77SRafael Espindola       NewGVar->setConstant(false);
1478879aeb77SRafael Espindola   }
1479879aeb77SRafael Espindola 
1480778fcc77SRafael Espindola   // Make sure to remember this mapping.
1481778fcc77SRafael Espindola   if (NewGV != DGV) {
1482778fcc77SRafael Espindola     if (DGV) {
1483ad9d0ca8SRafael Espindola       DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
1484778fcc77SRafael Espindola       DGV->eraseFromParent();
1485778fcc77SRafael Espindola     }
1486778fcc77SRafael Espindola     ValueMap[SGV] = NewGV;
1487dad0a645SDavid Majnemer   }
14884e27567aSRafael Espindola 
1489fd38af2dSChandler Carruth   return false;
14904e27567aSRafael Espindola }
14914e27567aSRafael Espindola 
149218c89411SRafael Espindola /// Update the initializers in the Dest module now that all globals that may be
149318c89411SRafael Espindola /// referenced are in Dest.
1494ef23711eSRafael Espindola void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
1495b1ed91f3SChris Lattner   // Figure out what the initializer looks like in the dest module.
14964fb46cb8SDuncan P. N. Exon Smith   Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap,
14974fb46cb8SDuncan P. N. Exon Smith                               RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1498b1ed91f3SChris Lattner }
1499b1ed91f3SChris Lattner 
150018c89411SRafael Espindola /// Copy the source function over into the dest function and fix up references
150118c89411SRafael Espindola /// to values. At this point we know that Dest is an external function, and
150218c89411SRafael Espindola /// that Src is not.
1503ef23711eSRafael Espindola bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) {
1504ef23711eSRafael Espindola   assert(Dst.isDeclaration() && !Src.isDeclaration());
1505361e513dSReid Spencer 
150640d7ebedSRafael Espindola   // Materialize if needed.
15073519da82SRafael Espindola   if (std::error_code EC = Src.materialize())
150840d7ebedSRafael Espindola     return emitError(EC.message());
150940d7ebedSRafael Espindola 
1510869d1ce8SRafael Espindola   // Link in the prefix data.
15113519da82SRafael Espindola   if (Src.hasPrefixData())
15124fb46cb8SDuncan P. N. Exon Smith     Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap,
15134fb46cb8SDuncan P. N. Exon Smith                                RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1514869d1ce8SRafael Espindola 
1515869d1ce8SRafael Espindola   // Link in the prologue data.
15163519da82SRafael Espindola   if (Src.hasPrologueData())
15174fb46cb8SDuncan P. N. Exon Smith     Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap,
15184fb46cb8SDuncan P. N. Exon Smith                                  RF_MoveDistinctMDs, &TypeMap,
15194fb46cb8SDuncan P. N. Exon Smith                                  &ValMaterializer));
1520869d1ce8SRafael Espindola 
15217fddeccbSDavid Majnemer   // Link in the personality function.
15227fddeccbSDavid Majnemer   if (Src.hasPersonalityFn())
15234fb46cb8SDuncan P. N. Exon Smith     Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap,
15244fb46cb8SDuncan P. N. Exon Smith                                   RF_MoveDistinctMDs, &TypeMap,
15254fb46cb8SDuncan P. N. Exon Smith                                   &ValMaterializer));
15267fddeccbSDavid Majnemer 
15277391dde1SChris Lattner   // Go through and convert function arguments over, remembering the mapping.
1528ef23711eSRafael Espindola   Function::arg_iterator DI = Dst.arg_begin();
15293519da82SRafael Espindola   for (Argument &Arg : Src.args()) {
1530a314d1acSRafael Espindola     DI->setName(Arg.getName()); // Copy the name over.
1531361e513dSReid Spencer 
1532b1ed91f3SChris Lattner     // Add a mapping to our mapping.
15339934b26bSDuncan P. N. Exon Smith     ValueMap[&Arg] = &*DI;
1534a314d1acSRafael Espindola     ++DI;
1535361e513dSReid Spencer   }
1536361e513dSReid Spencer 
1537c8d987b1SDuncan P. N. Exon Smith   // Copy over the metadata attachments.
1538c8d987b1SDuncan P. N. Exon Smith   SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1539c8d987b1SDuncan P. N. Exon Smith   Src.getAllMetadata(MDs);
1540c8d987b1SDuncan P. N. Exon Smith   for (const auto &I : MDs)
15414fb46cb8SDuncan P. N. Exon Smith     Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, RF_MoveDistinctMDs,
15424fb46cb8SDuncan P. N. Exon Smith                                          &TypeMap, &ValMaterializer));
1543c8d987b1SDuncan P. N. Exon Smith 
15442f0557d0SChris Lattner   // Splice the body of the source function into the dest function.
1545ef23711eSRafael Espindola   Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
1546361e513dSReid Spencer 
1547361e513dSReid Spencer   // At this point, all of the instructions and values of the function are now
1548361e513dSReid Spencer   // copied over.  The only problem is that they are still referencing values in
1549361e513dSReid Spencer   // the Source function as operands.  Loop through all of the operands of the
155043f8d164SChris Lattner   // functions and patch them up to point to the local versions.
1551ef23711eSRafael Espindola   for (BasicBlock &BB : Dst)
1552a314d1acSRafael Espindola     for (Instruction &I : BB)
15534fb46cb8SDuncan P. N. Exon Smith       RemapInstruction(&I, ValueMap,
15544fb46cb8SDuncan P. N. Exon Smith                        RF_IgnoreMissingEntries | RF_MoveDistinctMDs, &TypeMap,
15559f8eff31SRafael Espindola                        &ValMaterializer);
1556cbb91408STanya Lattner 
15577391dde1SChris Lattner   // There is no need to map the arguments anymore.
15583519da82SRafael Espindola   for (Argument &Arg : Src.args())
1559a314d1acSRafael Espindola     ValueMap.erase(&Arg);
1560cbb91408STanya Lattner 
156197cb5657SEric Christopher   Src.dematerialize();
156240d7ebedSRafael Espindola   return false;
1563361e513dSReid Spencer }
1564361e513dSReid Spencer 
1565ef23711eSRafael Espindola void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1566ef23711eSRafael Espindola   Constant *Aliasee = Src.getAliasee();
15674fb46cb8SDuncan P. N. Exon Smith   Constant *Val = MapValue(Aliasee, ValueMap, RF_MoveDistinctMDs, &TypeMap,
15684fb46cb8SDuncan P. N. Exon Smith                            &ValMaterializer);
1569ef23711eSRafael Espindola   Dst.setAliasee(Val);
15702c4a34aeSDavid Chisnall }
1571ef23711eSRafael Espindola 
1572e39cd5b1SRafael Espindola bool ModuleLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
15732d5fb8caSTeresa Johnson   if (const Comdat *SC = Src.getComdat()) {
15742d5fb8caSTeresa Johnson     // To ensure that we don't generate an incomplete comdat group,
15752d5fb8caSTeresa Johnson     // we must materialize and map in any other members that are not
15762d5fb8caSTeresa Johnson     // yet materialized in Dst, which also ensures their definitions
15772d5fb8caSTeresa Johnson     // are linked in. Otherwise, linkonce and other lazy linked GVs will
15782d5fb8caSTeresa Johnson     // not be materialized if they aren't referenced.
15792d5fb8caSTeresa Johnson     for (auto *SGV : ComdatMembers[SC]) {
158019b52383SRafael Espindola       auto *DGV = cast_or_null<GlobalValue>(ValueMap[SGV]);
158119b52383SRafael Espindola       if (DGV && !DGV->isDeclaration())
15822d5fb8caSTeresa Johnson         continue;
158319b52383SRafael Espindola       MapValue(SGV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
15842d5fb8caSTeresa Johnson     }
15852d5fb8caSTeresa Johnson   }
1586020d4fb1SArtem Belevich   if (shouldInternalizeLinkedSymbols())
1587e39cd5b1SRafael Espindola     if (auto *DGV = dyn_cast<GlobalValue>(&Dst))
1588020d4fb1SArtem Belevich       DGV->setLinkage(GlobalValue::InternalLinkage);
1589ef23711eSRafael Espindola   if (auto *F = dyn_cast<Function>(&Src))
1590e39cd5b1SRafael Espindola     return linkFunctionBody(cast<Function>(Dst), *F);
1591ef23711eSRafael Espindola   if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1592e39cd5b1SRafael Espindola     linkGlobalInit(cast<GlobalVariable>(Dst), *GVar);
1593ef23711eSRafael Espindola     return false;
1594b1ed91f3SChris Lattner   }
1595e39cd5b1SRafael Espindola   linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
1596ef23711eSRafael Espindola   return false;
1597cbb91408STanya Lattner }
1598b1ed91f3SChris Lattner 
159918c89411SRafael Espindola /// Insert all of the named MDNodes in Src into the Dest module.
1600b1ed91f3SChris Lattner void ModuleLinker::linkNamedMDNodes() {
16010e309fe8SRafael Espindola   const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
16020e309fe8SRafael Espindola   for (const NamedMDNode &NMD : SrcM.named_metadata()) {
160366f02413SBill Wendling     // Don't link module flags here. Do them separately.
16043bf3f1f5SYaron Keren     if (&NMD == SrcModFlags)
16053bf3f1f5SYaron Keren       continue;
16060e309fe8SRafael Espindola     NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1607b1ed91f3SChris Lattner     // Add Src elements into Dest node.
16083bf3f1f5SYaron Keren     for (const MDNode *op : NMD.operands())
160983d03ddbSTeresa Johnson       DestNMD->addOperand(MapMetadata(
161083d03ddbSTeresa Johnson           op, ValueMap, RF_MoveDistinctMDs | RF_NullMapMissingGlobalValues,
16114fb46cb8SDuncan P. N. Exon Smith           &TypeMap, &ValMaterializer));
1612b1ed91f3SChris Lattner   }
1613b1ed91f3SChris Lattner }
1614b1ed91f3SChris Lattner 
161518c89411SRafael Espindola /// Merge the linker flags in Src into the Dest module.
161666f02413SBill Wendling bool ModuleLinker::linkModuleFlagsMetadata() {
16170ec72bbcSDaniel Dunbar   // If the source module has no module flags, we are done.
16180e309fe8SRafael Espindola   const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1619e3a933afSRafael Espindola   if (!SrcModFlags)
1620e3a933afSRafael Espindola     return false;
162166f02413SBill Wendling 
162266f02413SBill Wendling   // If the destination module doesn't have module flags yet, then just copy
162366f02413SBill Wendling   // over the source module's flags.
16240e309fe8SRafael Espindola   NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
162566f02413SBill Wendling   if (DstModFlags->getNumOperands() == 0) {
162666f02413SBill Wendling     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
162766f02413SBill Wendling       DstModFlags->addOperand(SrcModFlags->getOperand(I));
162866f02413SBill Wendling 
162966f02413SBill Wendling     return false;
163066f02413SBill Wendling   }
163166f02413SBill Wendling 
16320ec72bbcSDaniel Dunbar   // First build a map of the existing module flags and requirements.
1633df55d8baSDuncan P. N. Exon Smith   DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
16340ec72bbcSDaniel Dunbar   SmallSetVector<MDNode *, 16> Requirements;
16350ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1636de36e804SDuncan P. N. Exon Smith     MDNode *Op = DstModFlags->getOperand(I);
16375bf8fef5SDuncan P. N. Exon Smith     ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
16380ec72bbcSDaniel Dunbar     MDString *ID = cast<MDString>(Op->getOperand(1));
16390ec72bbcSDaniel Dunbar 
16400ec72bbcSDaniel Dunbar     if (Behavior->getZExtValue() == Module::Require) {
16410ec72bbcSDaniel Dunbar       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
16420ec72bbcSDaniel Dunbar     } else {
1643df55d8baSDuncan P. N. Exon Smith       Flags[ID] = std::make_pair(Op, I);
16440ec72bbcSDaniel Dunbar     }
16450ec72bbcSDaniel Dunbar   }
16460ec72bbcSDaniel Dunbar 
16470ec72bbcSDaniel Dunbar   // Merge in the flags from the source module, and also collect its set of
16480ec72bbcSDaniel Dunbar   // requirements.
164966f02413SBill Wendling   bool HasErr = false;
16500ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1651de36e804SDuncan P. N. Exon Smith     MDNode *SrcOp = SrcModFlags->getOperand(I);
16525bf8fef5SDuncan P. N. Exon Smith     ConstantInt *SrcBehavior =
16535bf8fef5SDuncan P. N. Exon Smith         mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
16540ec72bbcSDaniel Dunbar     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1655df55d8baSDuncan P. N. Exon Smith     MDNode *DstOp;
1656df55d8baSDuncan P. N. Exon Smith     unsigned DstIndex;
1657df55d8baSDuncan P. N. Exon Smith     std::tie(DstOp, DstIndex) = Flags.lookup(ID);
16580ec72bbcSDaniel Dunbar     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
165966f02413SBill Wendling 
16600ec72bbcSDaniel Dunbar     // If this is a requirement, add it and continue.
16610ec72bbcSDaniel Dunbar     if (SrcBehaviorValue == Module::Require) {
16620ec72bbcSDaniel Dunbar       // If the destination module does not already have this requirement, add
16630ec72bbcSDaniel Dunbar       // it.
16640ec72bbcSDaniel Dunbar       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
16650ec72bbcSDaniel Dunbar         DstModFlags->addOperand(SrcOp);
16660ec72bbcSDaniel Dunbar       }
16670ec72bbcSDaniel Dunbar       continue;
16680ec72bbcSDaniel Dunbar     }
166966f02413SBill Wendling 
16700ec72bbcSDaniel Dunbar     // If there is no existing flag with this ID, just add it.
16710ec72bbcSDaniel Dunbar     if (!DstOp) {
1672df55d8baSDuncan P. N. Exon Smith       Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
16730ec72bbcSDaniel Dunbar       DstModFlags->addOperand(SrcOp);
16740ec72bbcSDaniel Dunbar       continue;
16750ec72bbcSDaniel Dunbar     }
167666f02413SBill Wendling 
16770ec72bbcSDaniel Dunbar     // Otherwise, perform a merge.
16785bf8fef5SDuncan P. N. Exon Smith     ConstantInt *DstBehavior =
16795bf8fef5SDuncan P. N. Exon Smith         mdconst::extract<ConstantInt>(DstOp->getOperand(0));
16800ec72bbcSDaniel Dunbar     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
16810ec72bbcSDaniel Dunbar 
16820ec72bbcSDaniel Dunbar     // If either flag has override behavior, handle it first.
16830ec72bbcSDaniel Dunbar     if (DstBehaviorValue == Module::Override) {
16840ec72bbcSDaniel Dunbar       // Diagnose inconsistent flags which both have override behavior.
16850ec72bbcSDaniel Dunbar       if (SrcBehaviorValue == Module::Override &&
16860ec72bbcSDaniel Dunbar           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
16870ec72bbcSDaniel Dunbar         HasErr |= emitError("linking module flags '" + ID->getString() +
16880ec72bbcSDaniel Dunbar                             "': IDs have conflicting override values");
16890ec72bbcSDaniel Dunbar       }
16900ec72bbcSDaniel Dunbar       continue;
16910ec72bbcSDaniel Dunbar     } else if (SrcBehaviorValue == Module::Override) {
16920ec72bbcSDaniel Dunbar       // Update the destination flag to that of the source.
1693df55d8baSDuncan P. N. Exon Smith       DstModFlags->setOperand(DstIndex, SrcOp);
1694df55d8baSDuncan P. N. Exon Smith       Flags[ID].first = SrcOp;
16950ec72bbcSDaniel Dunbar       continue;
16960ec72bbcSDaniel Dunbar     }
16970ec72bbcSDaniel Dunbar 
16980ec72bbcSDaniel Dunbar     // Diagnose inconsistent merge behavior types.
16990ec72bbcSDaniel Dunbar     if (SrcBehaviorValue != DstBehaviorValue) {
17000ec72bbcSDaniel Dunbar       HasErr |= emitError("linking module flags '" + ID->getString() +
170166f02413SBill Wendling                           "': IDs have conflicting behaviors");
17020ec72bbcSDaniel Dunbar       continue;
170366f02413SBill Wendling     }
170466f02413SBill Wendling 
1705df55d8baSDuncan P. N. Exon Smith     auto replaceDstValue = [&](MDNode *New) {
1706df55d8baSDuncan P. N. Exon Smith       Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
17070e309fe8SRafael Espindola       MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1708df55d8baSDuncan P. N. Exon Smith       DstModFlags->setOperand(DstIndex, Flag);
1709df55d8baSDuncan P. N. Exon Smith       Flags[ID].first = Flag;
1710df55d8baSDuncan P. N. Exon Smith     };
1711df55d8baSDuncan P. N. Exon Smith 
17120ec72bbcSDaniel Dunbar     // Perform the merge for standard behavior types.
17130ec72bbcSDaniel Dunbar     switch (SrcBehaviorValue) {
17140ec72bbcSDaniel Dunbar     case Module::Require:
1715e3a933afSRafael Espindola     case Module::Override:
1716e3a933afSRafael Espindola       llvm_unreachable("not possible");
17170ec72bbcSDaniel Dunbar     case Module::Error: {
17180ec72bbcSDaniel Dunbar       // Emit an error if the values differ.
17190ec72bbcSDaniel Dunbar       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
17200ec72bbcSDaniel Dunbar         HasErr |= emitError("linking module flags '" + ID->getString() +
17210ec72bbcSDaniel Dunbar                             "': IDs have conflicting values");
172266f02413SBill Wendling       }
17230ec72bbcSDaniel Dunbar       continue;
172466f02413SBill Wendling     }
17250ec72bbcSDaniel Dunbar     case Module::Warning: {
17260ec72bbcSDaniel Dunbar       // Emit a warning if the values differ.
17270ec72bbcSDaniel Dunbar       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1728d12b4a33SRafael Espindola         emitWarning("linking module flags '" + ID->getString() +
1729d12b4a33SRafael Espindola                     "': IDs have conflicting values");
1730e17f3708SEli Bendersky       }
17310ec72bbcSDaniel Dunbar       continue;
17320ec72bbcSDaniel Dunbar     }
1733d77d9fb0SDaniel Dunbar     case Module::Append: {
1734d77d9fb0SDaniel Dunbar       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1735d77d9fb0SDaniel Dunbar       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
17365bf8fef5SDuncan P. N. Exon Smith       SmallVector<Metadata *, 8> MDs;
17375bf8fef5SDuncan P. N. Exon Smith       MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
17386cd780ffSBenjamin Kramer       MDs.append(DstValue->op_begin(), DstValue->op_end());
17396cd780ffSBenjamin Kramer       MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1740df55d8baSDuncan P. N. Exon Smith 
17410e309fe8SRafael Espindola       replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1742d77d9fb0SDaniel Dunbar       break;
1743d77d9fb0SDaniel Dunbar     }
1744d77d9fb0SDaniel Dunbar     case Module::AppendUnique: {
17455bf8fef5SDuncan P. N. Exon Smith       SmallSetVector<Metadata *, 16> Elts;
1746d77d9fb0SDaniel Dunbar       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1747d77d9fb0SDaniel Dunbar       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
17486cd780ffSBenjamin Kramer       Elts.insert(DstValue->op_begin(), DstValue->op_end());
17496cd780ffSBenjamin Kramer       Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1750df55d8baSDuncan P. N. Exon Smith 
17510e309fe8SRafael Espindola       replaceDstValue(MDNode::get(DstM.getContext(),
17525bf8fef5SDuncan P. N. Exon Smith                                   makeArrayRef(Elts.begin(), Elts.end())));
1753d77d9fb0SDaniel Dunbar       break;
1754d77d9fb0SDaniel Dunbar     }
175566f02413SBill Wendling     }
175666f02413SBill Wendling   }
175766f02413SBill Wendling 
17580ec72bbcSDaniel Dunbar   // Check all of the requirements.
17590ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
17600ec72bbcSDaniel Dunbar     MDNode *Requirement = Requirements[I];
17610ec72bbcSDaniel Dunbar     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
17625bf8fef5SDuncan P. N. Exon Smith     Metadata *ReqValue = Requirement->getOperand(1);
17630ec72bbcSDaniel Dunbar 
1764df55d8baSDuncan P. N. Exon Smith     MDNode *Op = Flags[Flag].first;
17650ec72bbcSDaniel Dunbar     if (!Op || Op->getOperand(2) != ReqValue) {
17660ec72bbcSDaniel Dunbar       HasErr |= emitError("linking module flags '" + Flag->getString() +
17679273b539SBill Wendling                           "': does not have the required value");
17680ec72bbcSDaniel Dunbar       continue;
176966f02413SBill Wendling     }
177066f02413SBill Wendling   }
177166f02413SBill Wendling 
177266f02413SBill Wendling   return HasErr;
177366f02413SBill Wendling }
177466f02413SBill Wendling 
1775c43df518SAkira Hatanaka // This function returns true if the triples match.
1776c43df518SAkira Hatanaka static bool triplesMatch(const Triple &T0, const Triple &T1) {
1777c43df518SAkira Hatanaka   // If vendor is apple, ignore the version number.
1778c43df518SAkira Hatanaka   if (T0.getVendor() == Triple::Apple)
1779e3a933afSRafael Espindola     return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1780e3a933afSRafael Espindola            T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1781c43df518SAkira Hatanaka 
1782c43df518SAkira Hatanaka   return T0 == T1;
1783c43df518SAkira Hatanaka }
1784c43df518SAkira Hatanaka 
1785c43df518SAkira Hatanaka // This function returns the merged triple.
1786e3a933afSRafael Espindola static std::string mergeTriples(const Triple &SrcTriple,
1787e3a933afSRafael Espindola                                 const Triple &DstTriple) {
1788c43df518SAkira Hatanaka   // If vendor is apple, pick the triple with the larger version number.
1789c43df518SAkira Hatanaka   if (SrcTriple.getVendor() == Triple::Apple)
1790c43df518SAkira Hatanaka     if (DstTriple.isOSVersionLT(SrcTriple))
1791c43df518SAkira Hatanaka       return SrcTriple.str();
1792c43df518SAkira Hatanaka 
1793c43df518SAkira Hatanaka   return DstTriple.str();
1794c43df518SAkira Hatanaka }
1795c43df518SAkira Hatanaka 
1796baa3bf8fSRafael Espindola bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
1797baa3bf8fSRafael Espindola   GlobalValue *DGV = getLinkedToGlobal(&GV);
1798baa3bf8fSRafael Espindola 
1799baa3bf8fSRafael Espindola   if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
1800baa3bf8fSRafael Espindola     return false;
1801baa3bf8fSRafael Espindola 
1802baa3bf8fSRafael Espindola   if (DGV && !GV.hasLocalLinkage()) {
1803baa3bf8fSRafael Espindola     GlobalValue::VisibilityTypes Visibility =
1804baa3bf8fSRafael Espindola         getMinVisibility(DGV->getVisibility(), GV.getVisibility());
1805baa3bf8fSRafael Espindola     DGV->setVisibility(Visibility);
1806baa3bf8fSRafael Espindola     GV.setVisibility(Visibility);
1807baa3bf8fSRafael Espindola   }
1808baa3bf8fSRafael Espindola 
1809baa3bf8fSRafael Espindola   if (const Comdat *SC = GV.getComdat()) {
1810baa3bf8fSRafael Espindola     bool LinkFromSrc;
1811baa3bf8fSRafael Espindola     Comdat::SelectionKind SK;
1812baa3bf8fSRafael Espindola     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1813baa3bf8fSRafael Espindola     if (!LinkFromSrc) {
1814baa3bf8fSRafael Espindola       DoNotLinkFromSource.insert(&GV);
1815baa3bf8fSRafael Espindola       return false;
1816baa3bf8fSRafael Espindola     }
1817baa3bf8fSRafael Espindola   }
1818baa3bf8fSRafael Espindola 
1819baa3bf8fSRafael Espindola   if (!DGV && !shouldOverrideFromSrc() &&
1820baa3bf8fSRafael Espindola       (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
1821baa3bf8fSRafael Espindola        GV.hasAvailableExternallyLinkage())) {
1822baa3bf8fSRafael Espindola     return false;
1823baa3bf8fSRafael Espindola   }
1824baa3bf8fSRafael Espindola   MapValue(&GV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1825baa3bf8fSRafael Espindola   return HasError;
1826baa3bf8fSRafael Espindola }
1827baa3bf8fSRafael Espindola 
1828b1ed91f3SChris Lattner bool ModuleLinker::run() {
1829b1ed91f3SChris Lattner   // Inherit the target data from the source module if the destination module
1830b1ed91f3SChris Lattner   // doesn't have one already.
18310e309fe8SRafael Espindola   if (DstM.getDataLayout().isDefault())
18320e309fe8SRafael Espindola     DstM.setDataLayout(SrcM.getDataLayout());
1833b1ed91f3SChris Lattner 
18340e309fe8SRafael Espindola   if (SrcM.getDataLayout() != DstM.getDataLayout()) {
1835d12b4a33SRafael Espindola     emitWarning("Linking two modules of different data layouts: '" +
18360e309fe8SRafael Espindola                 SrcM.getModuleIdentifier() + "' is '" +
18370e309fe8SRafael Espindola                 SrcM.getDataLayoutStr() + "' whereas '" +
18380e309fe8SRafael Espindola                 DstM.getModuleIdentifier() + "' is '" +
18390e309fe8SRafael Espindola                 DstM.getDataLayoutStr() + "'\n");
1840e17f3708SEli Bendersky   }
1841c43df518SAkira Hatanaka 
1842c43df518SAkira Hatanaka   // Copy the target triple from the source to dest if the dest's is empty.
18430e309fe8SRafael Espindola   if (DstM.getTargetTriple().empty() && !SrcM.getTargetTriple().empty())
18440e309fe8SRafael Espindola     DstM.setTargetTriple(SrcM.getTargetTriple());
1845c43df518SAkira Hatanaka 
18460e309fe8SRafael Espindola   Triple SrcTriple(SrcM.getTargetTriple()), DstTriple(DstM.getTargetTriple());
1847c43df518SAkira Hatanaka 
18480e309fe8SRafael Espindola   if (!SrcM.getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
1849d12b4a33SRafael Espindola     emitWarning("Linking two modules of different target triples: " +
18500e309fe8SRafael Espindola                 SrcM.getModuleIdentifier() + "' is '" + SrcM.getTargetTriple() +
18510e309fe8SRafael Espindola                 "' whereas '" + DstM.getModuleIdentifier() + "' is '" +
18520e309fe8SRafael Espindola                 DstM.getTargetTriple() + "'\n");
1853c43df518SAkira Hatanaka 
18540e309fe8SRafael Espindola   DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1855b1ed91f3SChris Lattner 
1856b1ed91f3SChris Lattner   // Append the module inline asm string.
18570e309fe8SRafael Espindola   if (!SrcM.getModuleInlineAsm().empty()) {
18580e309fe8SRafael Espindola     if (DstM.getModuleInlineAsm().empty())
18590e309fe8SRafael Espindola       DstM.setModuleInlineAsm(SrcM.getModuleInlineAsm());
1860b1ed91f3SChris Lattner     else
18610e309fe8SRafael Espindola       DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
18620e309fe8SRafael Espindola                               SrcM.getModuleInlineAsm());
1863b1ed91f3SChris Lattner   }
1864b1ed91f3SChris Lattner 
1865b1ed91f3SChris Lattner   // Loop over all of the linked values to compute type mappings.
1866b1ed91f3SChris Lattner   computeTypeMapping();
1867b1ed91f3SChris Lattner 
1868dad0a645SDavid Majnemer   ComdatsChosen.clear();
18690e309fe8SRafael Espindola   for (const auto &SMEC : SrcM.getComdatSymbolTable()) {
1870dad0a645SDavid Majnemer     const Comdat &C = SMEC.getValue();
1871dad0a645SDavid Majnemer     if (ComdatsChosen.count(&C))
1872dad0a645SDavid Majnemer       continue;
1873dad0a645SDavid Majnemer     Comdat::SelectionKind SK;
1874dad0a645SDavid Majnemer     bool LinkFromSrc;
1875dad0a645SDavid Majnemer     if (getComdatResult(&C, SK, LinkFromSrc))
1876dad0a645SDavid Majnemer       return true;
1877dad0a645SDavid Majnemer     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1878dad0a645SDavid Majnemer   }
1879dad0a645SDavid Majnemer 
188009d84addSDuncan P. N. Exon Smith   // Upgrade mismatched global arrays.
188109d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobals();
188209d84addSDuncan P. N. Exon Smith 
18830e309fe8SRafael Espindola   for (GlobalVariable &GV : SrcM.globals())
1884baa3bf8fSRafael Espindola     if (const Comdat *SC = GV.getComdat())
1885baa3bf8fSRafael Espindola       ComdatMembers[SC].push_back(&GV);
1886baa3bf8fSRafael Espindola 
18870e309fe8SRafael Espindola   for (Function &SF : SrcM)
1888baa3bf8fSRafael Espindola     if (const Comdat *SC = SF.getComdat())
1889baa3bf8fSRafael Espindola       ComdatMembers[SC].push_back(&SF);
1890baa3bf8fSRafael Espindola 
18910e309fe8SRafael Espindola   for (GlobalAlias &GA : SrcM.aliases())
1892baa3bf8fSRafael Espindola     if (const Comdat *SC = GA.getComdat())
1893baa3bf8fSRafael Espindola       ComdatMembers[SC].push_back(&GA);
1894baa3bf8fSRafael Espindola 
1895b1ed91f3SChris Lattner   // Insert all of the globals in src into the DstM module... without linking
1896b1ed91f3SChris Lattner   // initializers (which could refer to functions not yet mapped over).
18970e309fe8SRafael Espindola   for (GlobalVariable &GV : SrcM.globals())
1898baa3bf8fSRafael Espindola     if (linkIfNeeded(GV))
1899b1ed91f3SChris Lattner       return true;
1900b1ed91f3SChris Lattner 
19010e309fe8SRafael Espindola   for (Function &SF : SrcM)
1902baa3bf8fSRafael Espindola     if (linkIfNeeded(SF))
1903b1ed91f3SChris Lattner       return true;
1904b1ed91f3SChris Lattner 
19050e309fe8SRafael Espindola   for (GlobalAlias &GA : SrcM.aliases())
1906baa3bf8fSRafael Espindola     if (linkIfNeeded(GA))
1907b1ed91f3SChris Lattner       return true;
1908b1ed91f3SChris Lattner 
19090e309fe8SRafael Espindola   for (const auto &Entry : DstM.getComdatSymbolTable()) {
1910beadd56aSRafael Espindola     const Comdat &C = Entry.getValue();
1911beadd56aSRafael Espindola     if (C.getSelectionKind() == Comdat::Any)
1912beadd56aSRafael Espindola       continue;
19130e309fe8SRafael Espindola     const GlobalValue *GV = SrcM.getNamedValue(C.getName());
1914ea45d834SPeter Collingbourne     if (GV)
19154fb46cb8SDuncan P. N. Exon Smith       MapValue(GV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1916beadd56aSRafael Espindola   }
1917beadd56aSRafael Espindola 
19181063293aSTeresa Johnson   // Note that we are done linking global value bodies. This prevents
19191063293aSTeresa Johnson   // metadata linking from creating new references.
19201063293aSTeresa Johnson   DoneLinkingBodies = true;
19211063293aSTeresa Johnson 
1922189b2526STeresa Johnson   // Remap all of the named MDNodes in Src into the DstM module. We do this
1923189b2526STeresa Johnson   // after linking GlobalValues so that MDNodes that reference GlobalValues
1924189b2526STeresa Johnson   // are properly remapped.
1925189b2526STeresa Johnson   linkNamedMDNodes();
1926189b2526STeresa Johnson 
1927189b2526STeresa Johnson   // Merge the module flags into the DstM module.
1928189b2526STeresa Johnson   if (linkModuleFlagsMetadata())
1929189b2526STeresa Johnson     return true;
1930189b2526STeresa Johnson 
19312609888fSAnton Korobeynikov   return false;
19322609888fSAnton Korobeynikov }
1933361e513dSReid Spencer 
193431ad468dSRafael Espindola Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
193531ad468dSRafael Espindola     : ETypes(E), IsPacked(P) {}
193631ad468dSRafael Espindola 
193731ad468dSRafael Espindola Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
193831ad468dSRafael Espindola     : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
193931ad468dSRafael Espindola 
194031ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
194131ad468dSRafael Espindola   if (IsPacked != That.IsPacked)
194231ad468dSRafael Espindola     return false;
194331ad468dSRafael Espindola   if (ETypes != That.ETypes)
194431ad468dSRafael Espindola     return false;
194531ad468dSRafael Espindola   return true;
194631ad468dSRafael Espindola }
194731ad468dSRafael Espindola 
194831ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
194931ad468dSRafael Espindola   return !this->operator==(That);
195031ad468dSRafael Espindola }
195131ad468dSRafael Espindola 
195231ad468dSRafael Espindola StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
195331ad468dSRafael Espindola   return DenseMapInfo<StructType *>::getEmptyKey();
195431ad468dSRafael Espindola }
195531ad468dSRafael Espindola 
195631ad468dSRafael Espindola StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
195731ad468dSRafael Espindola   return DenseMapInfo<StructType *>::getTombstoneKey();
195831ad468dSRafael Espindola }
195931ad468dSRafael Espindola 
196031ad468dSRafael Espindola unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
196131ad468dSRafael Espindola   return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
196231ad468dSRafael Espindola                       Key.IsPacked);
196331ad468dSRafael Espindola }
196431ad468dSRafael Espindola 
196531ad468dSRafael Espindola unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
196631ad468dSRafael Espindola   return getHashValue(KeyTy(ST));
196731ad468dSRafael Espindola }
196831ad468dSRafael Espindola 
196931ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
197031ad468dSRafael Espindola                                         const StructType *RHS) {
197131ad468dSRafael Espindola   if (RHS == getEmptyKey() || RHS == getTombstoneKey())
197231ad468dSRafael Espindola     return false;
197331ad468dSRafael Espindola   return LHS == KeyTy(RHS);
197431ad468dSRafael Espindola }
197531ad468dSRafael Espindola 
197631ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
197731ad468dSRafael Espindola                                         const StructType *RHS) {
197831ad468dSRafael Espindola   if (RHS == getEmptyKey())
197931ad468dSRafael Espindola     return LHS == getEmptyKey();
198031ad468dSRafael Espindola 
198131ad468dSRafael Espindola   if (RHS == getTombstoneKey())
198231ad468dSRafael Espindola     return LHS == getTombstoneKey();
198331ad468dSRafael Espindola 
198431ad468dSRafael Espindola   return KeyTy(LHS) == KeyTy(RHS);
198531ad468dSRafael Espindola }
198631ad468dSRafael Espindola 
198731ad468dSRafael Espindola void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
198831ad468dSRafael Espindola   assert(!Ty->isOpaque());
19893280a5d9SBenjamin Kramer   NonOpaqueStructTypes.insert(Ty);
199031ad468dSRafael Espindola }
199131ad468dSRafael Espindola 
1992a5b9e1cfSRafael Espindola void Linker::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1993a5b9e1cfSRafael Espindola   assert(!Ty->isOpaque());
1994a5b9e1cfSRafael Espindola   NonOpaqueStructTypes.insert(Ty);
1995a5b9e1cfSRafael Espindola   bool Removed = OpaqueStructTypes.erase(Ty);
1996a5b9e1cfSRafael Espindola   (void)Removed;
1997a5b9e1cfSRafael Espindola   assert(Removed);
1998a5b9e1cfSRafael Espindola }
1999a5b9e1cfSRafael Espindola 
200031ad468dSRafael Espindola void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
200131ad468dSRafael Espindola   assert(Ty->isOpaque());
200231ad468dSRafael Espindola   OpaqueStructTypes.insert(Ty);
200331ad468dSRafael Espindola }
200431ad468dSRafael Espindola 
200531ad468dSRafael Espindola StructType *
200631ad468dSRafael Espindola Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
200731ad468dSRafael Espindola                                                bool IsPacked) {
200831ad468dSRafael Espindola   Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
200931ad468dSRafael Espindola   auto I = NonOpaqueStructTypes.find_as(Key);
201031ad468dSRafael Espindola   if (I == NonOpaqueStructTypes.end())
201131ad468dSRafael Espindola     return nullptr;
20123280a5d9SBenjamin Kramer   return *I;
201331ad468dSRafael Espindola }
201431ad468dSRafael Espindola 
201531ad468dSRafael Espindola bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
201631ad468dSRafael Espindola   if (Ty->isOpaque())
201731ad468dSRafael Espindola     return OpaqueStructTypes.count(Ty);
201831ad468dSRafael Espindola   auto I = NonOpaqueStructTypes.find(Ty);
201931ad468dSRafael Espindola   if (I == NonOpaqueStructTypes.end())
202031ad468dSRafael Espindola     return false;
20213280a5d9SBenjamin Kramer   return *I == Ty;
202231ad468dSRafael Espindola }
202331ad468dSRafael Espindola 
20240e309fe8SRafael Espindola Linker::Linker(Module &M, DiagnosticHandlerFunction DiagnosticHandler)
20250e309fe8SRafael Espindola     : Composite(M), DiagnosticHandler(DiagnosticHandler) {
2026a4e85e3dSRafael Espindola   TypeFinder StructTypes;
20270e309fe8SRafael Espindola   StructTypes.run(M, true);
202831ad468dSRafael Espindola   for (StructType *Ty : StructTypes) {
202931ad468dSRafael Espindola     if (Ty->isOpaque())
203031ad468dSRafael Espindola       IdentifiedStructTypes.addOpaque(Ty);
203131ad468dSRafael Espindola     else
203231ad468dSRafael Espindola       IdentifiedStructTypes.addNonOpaque(Ty);
203331ad468dSRafael Espindola   }
2034aa9918aaSRafael Espindola }
20353df61b7bSRafael Espindola 
20360e309fe8SRafael Espindola Linker::Linker(Module &M)
20374dbdceb6SRafael Espindola     : Linker(M, [this](const DiagnosticInfo &DI) {
20380e309fe8SRafael Espindola         Composite.getContext().diagnose(DI);
20394dbdceb6SRafael Espindola       }) {}
20405cb9c82aSRafael Espindola 
20410e309fe8SRafael Espindola bool Linker::linkInModule(Module &Src, unsigned Flags,
20428220e8a8SMehdi Amini                           const FunctionInfoIndex *Index,
2043ffe2e4aaSMehdi Amini                           DenseSet<const GlobalValue *> *FuncToImport) {
2044a4e85e3dSRafael Espindola   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
2045c7ed52f2STeresa Johnson                          DiagnosticHandler, Flags, Index, FuncToImport);
2046dab999d5SManman Ren   bool RetCode = TheLinker.run();
20470e309fe8SRafael Espindola   Composite.dropTriviallyDeadConstantArrays();
2048dab999d5SManman Ren   return RetCode;
20493df61b7bSRafael Espindola }
20503df61b7bSRafael Espindola 
2051b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
2052b1ed91f3SChris Lattner // LinkModules entrypoint.
2053b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
2054b1ed91f3SChris Lattner 
205518c89411SRafael Espindola /// This function links two modules together, with the resulting Dest module
205618c89411SRafael Espindola /// modified to be the composite of the two input modules. If an error occurs,
205718c89411SRafael Espindola /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
205818c89411SRafael Espindola /// Upon failure, the Dest module could be in a modified state, and shouldn't be
205918c89411SRafael Espindola /// relied on to be consistent.
20600e309fe8SRafael Espindola bool Linker::linkModules(Module &Dest, Module &Src,
2061020d4fb1SArtem Belevich                          DiagnosticHandlerFunction DiagnosticHandler,
2062020d4fb1SArtem Belevich                          unsigned Flags) {
20634160f5d3SRafael Espindola   Linker L(Dest, DiagnosticHandler);
2064020d4fb1SArtem Belevich   return L.linkInModule(Src, Flags);
20654160f5d3SRafael Espindola }
20664160f5d3SRafael Espindola 
20670e309fe8SRafael Espindola bool Linker::linkModules(Module &Dest, Module &Src, unsigned Flags) {
2068287f18b4SRafael Espindola   Linker L(Dest);
2069020d4fb1SArtem Belevich   return L.linkInModule(Src, Flags);
2070361e513dSReid Spencer }
2071a3aeb980SBill Wendling 
2072a3aeb980SBill Wendling //===----------------------------------------------------------------------===//
2073a3aeb980SBill Wendling // C API.
2074a3aeb980SBill Wendling //===----------------------------------------------------------------------===//
2075a3aeb980SBill Wendling 
2076a3aeb980SBill Wendling LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
2077a57d588cSJuergen Ributzka                          LLVMLinkerMode Unused, char **OutMessages) {
207898ab63ceSRafael Espindola   Module *D = unwrap(Dest);
207998ab63ceSRafael Espindola   std::string Message;
20804160f5d3SRafael Espindola   raw_string_ostream Stream(Message);
20814160f5d3SRafael Espindola   DiagnosticPrinterRawOStream DP(Stream);
20824160f5d3SRafael Espindola 
20830e309fe8SRafael Espindola   LLVMBool Result = Linker::linkModules(
20840e309fe8SRafael Espindola       *D, *unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
208598ab63ceSRafael Espindola 
2086ff715e2dSEli Bendersky   if (OutMessages && Result) {
2087ff715e2dSEli Bendersky     Stream.flush();
208898ab63ceSRafael Espindola     *OutMessages = strdup(Message.c_str());
2089ff715e2dSEli Bendersky   }
2090a3aeb980SBill Wendling   return Result;
2091a3aeb980SBill Wendling }
2092