159a5afa9SMikhail Glushenkov //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
2361e513dSReid Spencer //
3361e513dSReid Spencer //                     The LLVM Compiler Infrastructure
4361e513dSReid Spencer //
5f3ebc3f3SChris Lattner // This file is distributed under the University of Illinois Open Source
6f3ebc3f3SChris Lattner // License. See LICENSE.TXT for details.
7361e513dSReid Spencer //
8361e513dSReid Spencer //===----------------------------------------------------------------------===//
9361e513dSReid Spencer //
10361e513dSReid Spencer // This file implements the LLVM module linker.
11361e513dSReid Spencer //
12361e513dSReid Spencer //===----------------------------------------------------------------------===//
13361e513dSReid Spencer 
146cc07df4SChandler Carruth #include "llvm/Linker/Linker.h"
15ed0881b2SChandler Carruth #include "llvm-c/Linker.h"
1631ad468dSRafael Espindola #include "llvm/ADT/Hashing.h"
1723f8d64bSRafael Espindola #include "llvm/ADT/Optional.h"
1866f02413SBill Wendling #include "llvm/ADT/SetVector.h"
190f7fd36fSEli Bendersky #include "llvm/ADT/SmallString.h"
2031ad468dSRafael Espindola #include "llvm/ADT/Statistic.h"
21c43df518SAkira Hatanaka #include "llvm/ADT/Triple.h"
229fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
23fda0cee7SDuncan P. N. Exon Smith #include "llvm/IR/DebugInfo.h"
24d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticInfo.h"
25d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticPrinter.h"
26d12b4a33SRafael Espindola #include "llvm/IR/LLVMContext.h"
279fb823bbSChandler Carruth #include "llvm/IR/Module.h"
28dcb603feSChandler Carruth #include "llvm/IR/TypeFinder.h"
29e17f3708SEli Bendersky #include "llvm/Support/CommandLine.h"
30b6af2f36SBill Wendling #include "llvm/Support/Debug.h"
31b6af2f36SBill Wendling #include "llvm/Support/raw_ostream.h"
32cbb91408STanya Lattner #include "llvm/Transforms/Utils/Cloning.h"
33981af002SWill Dietz #include <cctype>
3482d6ff6bSDavid Majnemer #include <tuple>
35361e513dSReid Spencer using namespace llvm;
36361e513dSReid Spencer 
37b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
38b1ed91f3SChris Lattner // TypeMap implementation.
39b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
40b1ed91f3SChris Lattner 
41b1ed91f3SChris Lattner namespace {
42b1ed91f3SChris Lattner class TypeMapTy : public ValueMapTypeRemapper {
4318c89411SRafael Espindola   /// This is a mapping from a source type to a destination type to use.
44b1ed91f3SChris Lattner   DenseMap<Type *, Type *> MappedTypes;
45b1ed91f3SChris Lattner 
4618c89411SRafael Espindola   /// When checking to see if two subgraphs are isomorphic, we speculatively
4718c89411SRafael Espindola   /// add types to MappedTypes, but keep track of them here in case we need to
4818c89411SRafael Espindola   /// roll back.
49b1ed91f3SChris Lattner   SmallVector<Type *, 16> SpeculativeTypes;
50b1ed91f3SChris Lattner 
51a96f235cSRafael Espindola   SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
52a96f235cSRafael Espindola 
5318c89411SRafael Espindola   /// This is a list of non-opaque structs in the source module that are mapped
5418c89411SRafael Espindola   /// to an opaque struct in the destination module.
555e3bd972SChris Lattner   SmallVector<StructType *, 16> SrcDefinitionsToResolve;
565e3bd972SChris Lattner 
5718c89411SRafael Espindola   /// This is the set of opaque types in the destination modules who are
5818c89411SRafael Espindola   /// getting a body from the source module.
595e3bd972SChris Lattner   SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
60d48b7783SBill Wendling 
618c2cc416SBill Wendling public:
6231ad468dSRafael Espindola   TypeMapTy(Linker::IdentifiedStructTypeSet &DstStructTypesSet)
6331ad468dSRafael Espindola       : DstStructTypesSet(DstStructTypesSet) {}
64aa9918aaSRafael Espindola 
6531ad468dSRafael Espindola   Linker::IdentifiedStructTypeSet &DstStructTypesSet;
6618c89411SRafael Espindola   /// Indicate that the specified type in the destination module is conceptually
6718c89411SRafael Espindola   /// equivalent to the specified type in the source module.
68b1ed91f3SChris Lattner   void addTypeMapping(Type *DstTy, Type *SrcTy);
69b1ed91f3SChris Lattner 
70d2a13a2eSRafael Espindola   /// Produce a body for an opaque type in the dest module from a type
71d2a13a2eSRafael Espindola   /// definition in the source module.
72b1ed91f3SChris Lattner   void linkDefinedTypeBodies();
73b1ed91f3SChris Lattner 
7418c89411SRafael Espindola   /// Return the mapped type to use for the specified input type from the
75b1ed91f3SChris Lattner   /// source module.
76b1ed91f3SChris Lattner   Type *get(Type *SrcTy);
7731ad468dSRafael Espindola   Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
7831ad468dSRafael Espindola 
7931ad468dSRafael Espindola   void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
80b1ed91f3SChris Lattner 
81290e2cc5SRafael Espindola   FunctionType *get(FunctionType *T) {
82290e2cc5SRafael Espindola     return cast<FunctionType>(get((Type *)T));
83290e2cc5SRafael Espindola   }
84b1ed91f3SChris Lattner 
8518c89411SRafael Espindola   /// Dump out the type map for debugging purposes.
86b6af2f36SBill Wendling   void dump() const {
878f14471eSRafael Espindola     for (auto &Pair : MappedTypes) {
88b6af2f36SBill Wendling       dbgs() << "TypeMap: ";
898f14471eSRafael Espindola       Pair.first->print(dbgs());
90b6af2f36SBill Wendling       dbgs() << " => ";
918f14471eSRafael Espindola       Pair.second->print(dbgs());
92b6af2f36SBill Wendling       dbgs() << '\n';
93b6af2f36SBill Wendling     }
94b6af2f36SBill Wendling   }
95b6af2f36SBill Wendling 
96b1ed91f3SChris Lattner private:
97290e2cc5SRafael Espindola   Type *remapType(Type *SrcTy) override { return get(SrcTy); }
98b1ed91f3SChris Lattner 
99b1ed91f3SChris Lattner   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
100b1ed91f3SChris Lattner };
101f00654e3SAlexander Kornienko }
102b1ed91f3SChris Lattner 
103b1ed91f3SChris Lattner void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
1043d097410SRafael Espindola   assert(SpeculativeTypes.empty());
105a96f235cSRafael Espindola   assert(SpeculativeDstOpaqueTypes.empty());
1063d097410SRafael Espindola 
107b1ed91f3SChris Lattner   // Check to see if these types are recursively isomorphic and establish a
108b1ed91f3SChris Lattner   // mapping between them if so.
109c586eaa1SDuncan P. N. Exon Smith   if (!areTypesIsomorphic(DstTy, SrcTy)) {
110b1ed91f3SChris Lattner     // Oops, they aren't isomorphic.  Just discard this request by rolling out
111b1ed91f3SChris Lattner     // any speculative mappings we've established.
1123d097410SRafael Espindola     for (Type *Ty : SpeculativeTypes)
1133d097410SRafael Espindola       MappedTypes.erase(Ty);
114a96f235cSRafael Espindola 
115a96f235cSRafael Espindola     SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
116a96f235cSRafael Espindola                                    SpeculativeDstOpaqueTypes.size());
117a96f235cSRafael Espindola     for (StructType *Ty : SpeculativeDstOpaqueTypes)
118a96f235cSRafael Espindola       DstResolvedOpaqueTypes.erase(Ty);
11904a74af7SRafael Espindola   } else {
12004a74af7SRafael Espindola     for (Type *Ty : SpeculativeTypes)
12104a74af7SRafael Espindola       if (auto *STy = dyn_cast<StructType>(Ty))
12204a74af7SRafael Espindola         if (STy->hasName())
12304a74af7SRafael Espindola           STy->setName("");
124d48b7783SBill Wendling   }
125b1ed91f3SChris Lattner   SpeculativeTypes.clear();
126a96f235cSRafael Espindola   SpeculativeDstOpaqueTypes.clear();
127b1ed91f3SChris Lattner }
128b1ed91f3SChris Lattner 
12918c89411SRafael Espindola /// Recursively walk this pair of types, returning true if they are isomorphic,
13018c89411SRafael Espindola /// false if they are not.
131b1ed91f3SChris Lattner bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
132b1ed91f3SChris Lattner   // Two types with differing kinds are clearly not isomorphic.
133290e2cc5SRafael Espindola   if (DstTy->getTypeID() != SrcTy->getTypeID())
134290e2cc5SRafael Espindola     return false;
135b1ed91f3SChris Lattner 
136b1ed91f3SChris Lattner   // If we have an entry in the MappedTypes table, then we have our answer.
137b1ed91f3SChris Lattner   Type *&Entry = MappedTypes[SrcTy];
138b1ed91f3SChris Lattner   if (Entry)
139b1ed91f3SChris Lattner     return Entry == DstTy;
140b1ed91f3SChris Lattner 
141b1ed91f3SChris Lattner   // Two identical types are clearly isomorphic.  Remember this
142b1ed91f3SChris Lattner   // non-speculatively.
143b1ed91f3SChris Lattner   if (DstTy == SrcTy) {
144b1ed91f3SChris Lattner     Entry = DstTy;
145361e513dSReid Spencer     return true;
146361e513dSReid Spencer   }
147361e513dSReid Spencer 
148b1ed91f3SChris Lattner   // Okay, we have two types with identical kinds that we haven't seen before.
149361e513dSReid Spencer 
150b1ed91f3SChris Lattner   // If this is an opaque struct type, special case it.
151b1ed91f3SChris Lattner   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
152b1ed91f3SChris Lattner     // Mapping an opaque type to any struct, just keep the dest struct.
153b1ed91f3SChris Lattner     if (SSTy->isOpaque()) {
154b1ed91f3SChris Lattner       Entry = DstTy;
155b1ed91f3SChris Lattner       SpeculativeTypes.push_back(SrcTy);
156b1ed91f3SChris Lattner       return true;
157361e513dSReid Spencer     }
158b1ed91f3SChris Lattner 
1595e3bd972SChris Lattner     // Mapping a non-opaque source type to an opaque dest.  If this is the first
1605e3bd972SChris Lattner     // type that we're mapping onto this destination type then we succeed.  Keep
161a96f235cSRafael Espindola     // the dest, but fill it in later. If this is the second (different) type
162a96f235cSRafael Espindola     // that we're trying to map onto the same opaque type then we fail.
163b1ed91f3SChris Lattner     if (cast<StructType>(DstTy)->isOpaque()) {
1645e3bd972SChris Lattner       // We can only map one source type onto the opaque destination type.
16570573dcdSDavid Blaikie       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
1665e3bd972SChris Lattner         return false;
1675e3bd972SChris Lattner       SrcDefinitionsToResolve.push_back(SSTy);
168a96f235cSRafael Espindola       SpeculativeTypes.push_back(SrcTy);
169a96f235cSRafael Espindola       SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
170b1ed91f3SChris Lattner       Entry = DstTy;
171b1ed91f3SChris Lattner       return true;
172b1ed91f3SChris Lattner     }
173b1ed91f3SChris Lattner   }
174b1ed91f3SChris Lattner 
175b1ed91f3SChris Lattner   // If the number of subtypes disagree between the two types, then we fail.
176b1ed91f3SChris Lattner   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
177b1ed91f3SChris Lattner     return false;
178b1ed91f3SChris Lattner 
179b1ed91f3SChris Lattner   // Fail if any of the extra properties (e.g. array size) of the type disagree.
180b1ed91f3SChris Lattner   if (isa<IntegerType>(DstTy))
181b1ed91f3SChris Lattner     return false; // bitwidth disagrees.
182b1ed91f3SChris Lattner   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
183b1ed91f3SChris Lattner     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
184b1ed91f3SChris Lattner       return false;
185eaf9b762SChris Lattner 
186b1ed91f3SChris Lattner   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
187b1ed91f3SChris Lattner     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
188b1ed91f3SChris Lattner       return false;
189b1ed91f3SChris Lattner   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
190b1ed91f3SChris Lattner     StructType *SSTy = cast<StructType>(SrcTy);
19144f7ab45SChris Lattner     if (DSTy->isLiteral() != SSTy->isLiteral() ||
192b1ed91f3SChris Lattner         DSTy->isPacked() != SSTy->isPacked())
193b1ed91f3SChris Lattner       return false;
194b1ed91f3SChris Lattner   } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
195b1ed91f3SChris Lattner     if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
196b1ed91f3SChris Lattner       return false;
197b1ed91f3SChris Lattner   } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
1985fad3e9aSJoey Gouly     if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
199361e513dSReid Spencer       return false;
200361e513dSReid Spencer   }
201361e513dSReid Spencer 
202b1ed91f3SChris Lattner   // Otherwise, we speculate that these two types will line up and recursively
203b1ed91f3SChris Lattner   // check the subelements.
204b1ed91f3SChris Lattner   Entry = DstTy;
205b1ed91f3SChris Lattner   SpeculativeTypes.push_back(SrcTy);
206eee6f995SChris Lattner 
207290e2cc5SRafael Espindola   for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
208290e2cc5SRafael Espindola     if (!areTypesIsomorphic(DstTy->getContainedType(I),
209290e2cc5SRafael Espindola                             SrcTy->getContainedType(I)))
210b1ed91f3SChris Lattner       return false;
211eee6f995SChris Lattner 
212b1ed91f3SChris Lattner   // If everything seems to have lined up, then everything is great.
213eee6f995SChris Lattner   return true;
214eee6f995SChris Lattner }
215eee6f995SChris Lattner 
216b1ed91f3SChris Lattner void TypeMapTy::linkDefinedTypeBodies() {
217b1ed91f3SChris Lattner   SmallVector<Type *, 16> Elements;
218c81c3f55SRafael Espindola   for (StructType *SrcSTy : SrcDefinitionsToResolve) {
219b1ed91f3SChris Lattner     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
220c81c3f55SRafael Espindola     assert(DstSTy->isOpaque());
221b1ed91f3SChris Lattner 
222b1ed91f3SChris Lattner     // Map the body of the source type over to a new body for the dest type.
223b1ed91f3SChris Lattner     Elements.resize(SrcSTy->getNumElements());
224290e2cc5SRafael Espindola     for (unsigned I = 0, E = Elements.size(); I != E; ++I)
225c81c3f55SRafael Espindola       Elements[I] = get(SrcSTy->getElementType(I));
226b1ed91f3SChris Lattner 
227b1ed91f3SChris Lattner     DstSTy->setBody(Elements, SrcSTy->isPacked());
228a5b9e1cfSRafael Espindola     DstStructTypesSet.switchToNonOpaque(DstSTy);
229b1ed91f3SChris Lattner   }
230c81c3f55SRafael Espindola   SrcDefinitionsToResolve.clear();
2315e3bd972SChris Lattner   DstResolvedOpaqueTypes.clear();
232eee6f995SChris Lattner }
233eee6f995SChris Lattner 
23431ad468dSRafael Espindola void TypeMapTy::finishType(StructType *DTy, StructType *STy,
23531ad468dSRafael Espindola                            ArrayRef<Type *> ETypes) {
23631ad468dSRafael Espindola   DTy->setBody(ETypes, STy->isPacked());
237a4e85e3dSRafael Espindola 
23831ad468dSRafael Espindola   // Steal STy's name.
23931ad468dSRafael Espindola   if (STy->hasName()) {
24031ad468dSRafael Espindola     SmallString<16> TmpName = STy->getName();
24131ad468dSRafael Espindola     STy->setName("");
24231ad468dSRafael Espindola     DTy->setName(TmpName);
24331ad468dSRafael Espindola   }
24431ad468dSRafael Espindola 
24531ad468dSRafael Espindola   DstStructTypesSet.addNonOpaque(DTy);
24631ad468dSRafael Espindola }
24731ad468dSRafael Espindola 
24831ad468dSRafael Espindola Type *TypeMapTy::get(Type *Ty) {
24931ad468dSRafael Espindola   SmallPtrSet<StructType *, 8> Visited;
25031ad468dSRafael Espindola   return get(Ty, Visited);
25131ad468dSRafael Espindola }
25231ad468dSRafael Espindola 
25331ad468dSRafael Espindola Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
254b1ed91f3SChris Lattner   // If we already have an entry for this type, return it.
255b1ed91f3SChris Lattner   Type **Entry = &MappedTypes[Ty];
256290e2cc5SRafael Espindola   if (*Entry)
257290e2cc5SRafael Espindola     return *Entry;
258b1ed91f3SChris Lattner 
25931ad468dSRafael Espindola   // These are types that LLVM itself will unique.
26031ad468dSRafael Espindola   bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
26131ad468dSRafael Espindola 
26231ad468dSRafael Espindola #ifndef NDEBUG
26331ad468dSRafael Espindola   if (!IsUniqued) {
26431ad468dSRafael Espindola     for (auto &Pair : MappedTypes) {
26531ad468dSRafael Espindola       assert(!(Pair.first != Ty && Pair.second == Ty) &&
26631ad468dSRafael Espindola              "mapping to a source type");
26731ad468dSRafael Espindola     }
26831ad468dSRafael Espindola   }
26931ad468dSRafael Espindola #endif
27031ad468dSRafael Espindola 
27131ad468dSRafael Espindola   if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
27231ad468dSRafael Espindola     StructType *DTy = StructType::create(Ty->getContext());
27331ad468dSRafael Espindola     return *Entry = DTy;
27431ad468dSRafael Espindola   }
27531ad468dSRafael Espindola 
27631ad468dSRafael Espindola   // If this is not a recursive type, then just map all of the elements and
277b1ed91f3SChris Lattner   // then rebuild the type from inside out.
27831ad468dSRafael Espindola   SmallVector<Type *, 4> ElementTypes;
27931ad468dSRafael Espindola 
280b1ed91f3SChris Lattner   // If there are no element types to map, then the type is itself.  This is
281b1ed91f3SChris Lattner   // true for the anonymous {} struct, things like 'float', integers, etc.
28231ad468dSRafael Espindola   if (Ty->getNumContainedTypes() == 0 && IsUniqued)
283b1ed91f3SChris Lattner     return *Entry = Ty;
284b1ed91f3SChris Lattner 
285b1ed91f3SChris Lattner   // Remap all of the elements, keeping track of whether any of them change.
286b1ed91f3SChris Lattner   bool AnyChange = false;
287b1ed91f3SChris Lattner   ElementTypes.resize(Ty->getNumContainedTypes());
288290e2cc5SRafael Espindola   for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
28931ad468dSRafael Espindola     ElementTypes[I] = get(Ty->getContainedType(I), Visited);
290290e2cc5SRafael Espindola     AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
291eee6f995SChris Lattner   }
292b1ed91f3SChris Lattner 
293b1ed91f3SChris Lattner   // If we found our type while recursively processing stuff, just use it.
294b1ed91f3SChris Lattner   Entry = &MappedTypes[Ty];
29531ad468dSRafael Espindola   if (*Entry) {
29631ad468dSRafael Espindola     if (auto *DTy = dyn_cast<StructType>(*Entry)) {
29731ad468dSRafael Espindola       if (DTy->isOpaque()) {
29831ad468dSRafael Espindola         auto *STy = cast<StructType>(Ty);
29931ad468dSRafael Espindola         finishType(DTy, STy, ElementTypes);
30031ad468dSRafael Espindola       }
30131ad468dSRafael Espindola     }
302290e2cc5SRafael Espindola     return *Entry;
30331ad468dSRafael Espindola   }
304b1ed91f3SChris Lattner 
30531ad468dSRafael Espindola   // If all of the element types mapped directly over and the type is not
30631ad468dSRafael Espindola   // a nomed struct, then the type is usable as-is.
30731ad468dSRafael Espindola   if (!AnyChange && IsUniqued)
308b1ed91f3SChris Lattner     return *Entry = Ty;
309b1ed91f3SChris Lattner 
310b1ed91f3SChris Lattner   // Otherwise, rebuild a modified type.
311b1ed91f3SChris Lattner   switch (Ty->getTypeID()) {
312290e2cc5SRafael Espindola   default:
313290e2cc5SRafael Espindola     llvm_unreachable("unknown derived type to remap");
314b1ed91f3SChris Lattner   case Type::ArrayTyID:
315b1ed91f3SChris Lattner     return *Entry = ArrayType::get(ElementTypes[0],
316b1ed91f3SChris Lattner                                    cast<ArrayType>(Ty)->getNumElements());
317b1ed91f3SChris Lattner   case Type::VectorTyID:
318b1ed91f3SChris Lattner     return *Entry = VectorType::get(ElementTypes[0],
319b1ed91f3SChris Lattner                                     cast<VectorType>(Ty)->getNumElements());
320b1ed91f3SChris Lattner   case Type::PointerTyID:
32131ad468dSRafael Espindola     return *Entry = PointerType::get(ElementTypes[0],
32231ad468dSRafael Espindola                                      cast<PointerType>(Ty)->getAddressSpace());
323b1ed91f3SChris Lattner   case Type::FunctionTyID:
324b1ed91f3SChris Lattner     return *Entry = FunctionType::get(ElementTypes[0],
325717d7eddSFrits van Bommel                                       makeArrayRef(ElementTypes).slice(1),
326b1ed91f3SChris Lattner                                       cast<FunctionType>(Ty)->isVarArg());
32731ad468dSRafael Espindola   case Type::StructTyID: {
32831ad468dSRafael Espindola     auto *STy = cast<StructType>(Ty);
32931ad468dSRafael Espindola     bool IsPacked = STy->isPacked();
33031ad468dSRafael Espindola     if (IsUniqued)
33131ad468dSRafael Espindola       return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
332b1ed91f3SChris Lattner 
333b1ed91f3SChris Lattner     // If the type is opaque, we can just use it directly.
334aa9918aaSRafael Espindola     if (STy->isOpaque()) {
33531ad468dSRafael Espindola       DstStructTypesSet.addOpaque(STy);
33631ad468dSRafael Espindola       return *Entry = Ty;
337aa9918aaSRafael Espindola     }
338b1ed91f3SChris Lattner 
33931ad468dSRafael Espindola     if (StructType *OldT =
34031ad468dSRafael Espindola             DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
341c81c3f55SRafael Espindola       STy->setName("");
34231ad468dSRafael Espindola       return *Entry = OldT;
343c81c3f55SRafael Espindola     }
344c81c3f55SRafael Espindola 
34531ad468dSRafael Espindola     if (!AnyChange) {
34631ad468dSRafael Espindola       DstStructTypesSet.addNonOpaque(STy);
34731ad468dSRafael Espindola       return *Entry = Ty;
34831ad468dSRafael Espindola     }
34931ad468dSRafael Espindola 
35031ad468dSRafael Espindola     StructType *DTy = StructType::create(Ty->getContext());
35131ad468dSRafael Espindola     finishType(DTy, STy, ElementTypes);
35231ad468dSRafael Espindola     return *Entry = DTy;
35331ad468dSRafael Espindola   }
35431ad468dSRafael Espindola   }
355b1ed91f3SChris Lattner }
356b1ed91f3SChris Lattner 
357b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
358b1ed91f3SChris Lattner // ModuleLinker implementation.
359b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
360b1ed91f3SChris Lattner 
361b1ed91f3SChris Lattner namespace {
362f6f121e2SJames Molloy class ModuleLinker;
363f6f121e2SJames Molloy 
36418c89411SRafael Espindola /// Creates prototypes for functions that are lazily linked on the fly. This
36518c89411SRafael Espindola /// speeds up linking for modules with many/ lazily linked functions of which
36618c89411SRafael Espindola /// few get used.
367437aafdaSDavid Blaikie class ValueMaterializerTy final : public ValueMaterializer {
368c7ed52f2STeresa Johnson   ModuleLinker *ModLinker;
369c84f608bSRafael Espindola 
370f6f121e2SJames Molloy public:
37119b52383SRafael Espindola   ValueMaterializerTy(ModuleLinker *ModLinker) : ModLinker(ModLinker) {}
372f6f121e2SJames Molloy 
37319b52383SRafael Espindola   Value *materializeDeclFor(Value *V) override;
37419b52383SRafael Espindola   void materializeInitFor(GlobalValue *New, GlobalValue *Old) override;
375f6f121e2SJames Molloy };
376f6f121e2SJames Molloy 
377d12b4a33SRafael Espindola class LinkDiagnosticInfo : public DiagnosticInfo {
378d12b4a33SRafael Espindola   const Twine &Msg;
379d12b4a33SRafael Espindola 
380d12b4a33SRafael Espindola public:
381d12b4a33SRafael Espindola   LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
382d12b4a33SRafael Espindola   void print(DiagnosticPrinter &DP) const override;
383d12b4a33SRafael Espindola };
384d12b4a33SRafael Espindola LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
385d12b4a33SRafael Espindola                                        const Twine &Msg)
386d12b4a33SRafael Espindola     : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
387d12b4a33SRafael Espindola void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
388d12b4a33SRafael Espindola 
38918c89411SRafael Espindola /// This is an implementation class for the LinkModules function, which is the
39018c89411SRafael Espindola /// entrypoint for this file.
391b1ed91f3SChris Lattner class ModuleLinker {
3920e309fe8SRafael Espindola   Module &DstM;
3930e309fe8SRafael Espindola   Module &SrcM;
394b1ed91f3SChris Lattner 
395b1ed91f3SChris Lattner   TypeMapTy TypeMap;
396f6f121e2SJames Molloy   ValueMaterializerTy ValMaterializer;
397b1ed91f3SChris Lattner 
39818c89411SRafael Espindola   /// Mapping of values from what they used to be in Src, to what they are now
39918c89411SRafael Espindola   /// in DstM.  ValueToValueMapTy is a ValueMap, which involves some overhead
40018c89411SRafael Espindola   /// due to the use of Value handles which the Linker doesn't actually need,
40118c89411SRafael Espindola   /// but this allows us to reuse the ValueMapper code.
402b1ed91f3SChris Lattner   ValueToValueMapTy ValueMap;
403b1ed91f3SChris Lattner 
404cbb91408STanya Lattner   // Set of items not to link in from source.
405c98b20b0SRafael Espindola   SmallPtrSet<const GlobalValue *, 16> DoNotLinkFromSource;
406cbb91408STanya Lattner 
407d0b23befSRafael Espindola   DiagnosticHandlerFunction DiagnosticHandler;
4084160f5d3SRafael Espindola 
409e868123dSDuncan P. N. Exon Smith   /// For symbol clashes, prefer those from Src.
410020d4fb1SArtem Belevich   unsigned Flags;
411e868123dSDuncan P. N. Exon Smith 
412c7ed52f2STeresa Johnson   /// Function index passed into ModuleLinker for using in function
413c7ed52f2STeresa Johnson   /// importing/exporting handling.
4148220e8a8SMehdi Amini   const FunctionInfoIndex *ImportIndex;
415c7ed52f2STeresa Johnson 
416c7ed52f2STeresa Johnson   /// Function to import from source module, all other functions are
417c7ed52f2STeresa Johnson   /// imported as declarations instead of definitions.
418c7ed52f2STeresa Johnson   Function *ImportFunction;
419c7ed52f2STeresa Johnson 
420c7ed52f2STeresa Johnson   /// Set to true if the given FunctionInfoIndex contains any functions
421c7ed52f2STeresa Johnson   /// from this source module, in which case we must conservatively assume
422c7ed52f2STeresa Johnson   /// that any of its functions may be imported into another module
423c7ed52f2STeresa Johnson   /// as part of a different backend compilation process.
424c7ed52f2STeresa Johnson   bool HasExportedFunctions;
425c7ed52f2STeresa Johnson 
4261063293aSTeresa Johnson   /// Set to true when all global value body linking is complete (including
4271063293aSTeresa Johnson   /// lazy linking). Used to prevent metadata linking from creating new
4281063293aSTeresa Johnson   /// references.
4291063293aSTeresa Johnson   bool DoneLinkingBodies;
4301063293aSTeresa Johnson 
431baa3bf8fSRafael Espindola   bool HasError = false;
432baa3bf8fSRafael Espindola 
433b1ed91f3SChris Lattner public:
4340e309fe8SRafael Espindola   ModuleLinker(Module &DstM, Linker::IdentifiedStructTypeSet &Set, Module &SrcM,
435c7ed52f2STeresa Johnson                DiagnosticHandlerFunction DiagnosticHandler, unsigned Flags,
4368220e8a8SMehdi Amini                const FunctionInfoIndex *Index = nullptr,
437c7ed52f2STeresa Johnson                Function *FuncToImport = nullptr)
4380e309fe8SRafael Espindola       : DstM(DstM), SrcM(SrcM), TypeMap(Set), ValMaterializer(this),
439c7ed52f2STeresa Johnson         DiagnosticHandler(DiagnosticHandler), Flags(Flags), ImportIndex(Index),
4401063293aSTeresa Johnson         ImportFunction(FuncToImport), HasExportedFunctions(false),
4411063293aSTeresa Johnson         DoneLinkingBodies(false) {
442c7ed52f2STeresa Johnson     assert((ImportIndex || !ImportFunction) &&
443c7ed52f2STeresa Johnson            "Expect a FunctionInfoIndex when importing");
444c7ed52f2STeresa Johnson     // If we have a FunctionInfoIndex but no function to import,
445c7ed52f2STeresa Johnson     // then this is the primary module being compiled in a ThinLTO
446c7ed52f2STeresa Johnson     // backend compilation, and we need to see if it has functions that
447c7ed52f2STeresa Johnson     // may be exported to another backend compilation.
448c7ed52f2STeresa Johnson     if (ImportIndex && !ImportFunction)
4490e309fe8SRafael Espindola       HasExportedFunctions = ImportIndex->hasExportedFunctions(&SrcM);
450c7ed52f2STeresa Johnson   }
451b1ed91f3SChris Lattner 
452b1ed91f3SChris Lattner   bool run();
45319b52383SRafael Espindola   Value *materializeDeclFor(Value *V);
45419b52383SRafael Espindola   void materializeInitFor(GlobalValue *New, GlobalValue *Old);
455b1ed91f3SChris Lattner 
45619b52383SRafael Espindola private:
457020d4fb1SArtem Belevich   bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
458020d4fb1SArtem Belevich   bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
459020d4fb1SArtem Belevich   bool shouldInternalizeLinkedSymbols() {
460020d4fb1SArtem Belevich     return Flags & Linker::InternalizeLinkedSymbols;
461020d4fb1SArtem Belevich   }
462020d4fb1SArtem Belevich 
463c7ed52f2STeresa Johnson   /// Handles cloning of a global values from the source module into
464c7ed52f2STeresa Johnson   /// the destination module, including setting the attributes and visibility.
465c7ed52f2STeresa Johnson   GlobalValue *copyGlobalValueProto(TypeMapTy &TypeMap, const GlobalValue *SGV,
466c7ed52f2STeresa Johnson                                     const GlobalValue *DGV = nullptr);
467c7ed52f2STeresa Johnson 
468c7ed52f2STeresa Johnson   /// Check if we should promote the given local value to global scope.
469c7ed52f2STeresa Johnson   bool doPromoteLocalToGlobal(const GlobalValue *SGV);
470c7ed52f2STeresa Johnson 
4711063293aSTeresa Johnson   /// Check if all global value body linking is complete.
4721063293aSTeresa Johnson   bool doneLinkingBodies() { return DoneLinkingBodies; }
4731063293aSTeresa Johnson 
474d12b4a33SRafael Espindola   bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
475d12b4a33SRafael Espindola                             const GlobalValue &Src);
476dbb0bd1aSRafael Espindola 
477d12b4a33SRafael Espindola   /// Helper method for setting a message and returning an error code.
478b1ed91f3SChris Lattner   bool emitError(const Twine &Message) {
4794160f5d3SRafael Espindola     DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
480baa3bf8fSRafael Espindola     HasError = true;
481b1ed91f3SChris Lattner     return true;
482b1ed91f3SChris Lattner   }
483b1ed91f3SChris Lattner 
484d12b4a33SRafael Espindola   void emitWarning(const Twine &Message) {
4854160f5d3SRafael Espindola     DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
486d12b4a33SRafael Espindola   }
487d12b4a33SRafael Espindola 
4880e309fe8SRafael Espindola   bool getComdatLeader(Module &M, StringRef ComdatName,
489dad0a645SDavid Majnemer                        const GlobalVariable *&GVar);
490dad0a645SDavid Majnemer   bool computeResultingSelectionKind(StringRef ComdatName,
491dad0a645SDavid Majnemer                                      Comdat::SelectionKind Src,
492dad0a645SDavid Majnemer                                      Comdat::SelectionKind Dst,
493dad0a645SDavid Majnemer                                      Comdat::SelectionKind &Result,
494dad0a645SDavid Majnemer                                      bool &LinkFromSrc);
495dad0a645SDavid Majnemer   std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
496dad0a645SDavid Majnemer       ComdatsChosen;
497dad0a645SDavid Majnemer   bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
498dad0a645SDavid Majnemer                        bool &LinkFromSrc);
4992d5fb8caSTeresa Johnson   // Keep track of the global value members of each comdat in source.
5002d5fb8caSTeresa Johnson   DenseMap<const Comdat *, std::vector<GlobalValue *>> ComdatMembers;
501dad0a645SDavid Majnemer 
50218c89411SRafael Espindola   /// Given a global in the source module, return the global in the
50318c89411SRafael Espindola   /// destination module that is being linked to, if any.
5043e8bc6a8SRafael Espindola   GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
505b1ed91f3SChris Lattner     // If the source has no name it can't link.  If it has local linkage,
506b1ed91f3SChris Lattner     // there is no name match-up going on.
507b098f0c1STeresa Johnson     if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(getLinkage(SrcGV)))
5082617dcceSCraig Topper       return nullptr;
509b1ed91f3SChris Lattner 
510b1ed91f3SChris Lattner     // Otherwise see if we have a match in the destination module's symtab.
5110e309fe8SRafael Espindola     GlobalValue *DGV = DstM.getNamedValue(getName(SrcGV));
512c84f608bSRafael Espindola     if (!DGV)
513c84f608bSRafael Espindola       return nullptr;
514b1ed91f3SChris Lattner 
515b1ed91f3SChris Lattner     // If we found a global with the same name in the dest module, but it has
516b1ed91f3SChris Lattner     // internal linkage, we are really not doing any linkage here.
517b1ed91f3SChris Lattner     if (DGV->hasLocalLinkage())
5182617dcceSCraig Topper       return nullptr;
519b1ed91f3SChris Lattner 
520b1ed91f3SChris Lattner     // Otherwise, we do in fact link to the destination global.
521b1ed91f3SChris Lattner     return DGV;
522b1ed91f3SChris Lattner   }
523b1ed91f3SChris Lattner 
524b1ed91f3SChris Lattner   void computeTypeMapping();
525b1ed91f3SChris Lattner 
52609d84addSDuncan P. N. Exon Smith   void upgradeMismatchedGlobalArray(StringRef Name);
52709d84addSDuncan P. N. Exon Smith   void upgradeMismatchedGlobals();
52809d84addSDuncan P. N. Exon Smith 
529baa3bf8fSRafael Espindola   bool linkIfNeeded(GlobalValue &GV);
5303e8bc6a8SRafael Espindola   bool linkAppendingVarProto(GlobalVariable *DstGV,
5313e8bc6a8SRafael Espindola                              const GlobalVariable *SrcGV);
532778fcc77SRafael Espindola 
533778fcc77SRafael Espindola   bool linkGlobalValueProto(GlobalValue *GV);
53466f02413SBill Wendling   bool linkModuleFlagsMetadata();
535b1ed91f3SChris Lattner 
536ef23711eSRafael Espindola   void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
537ef23711eSRafael Espindola   bool linkFunctionBody(Function &Dst, Function &Src);
538ef23711eSRafael Espindola   void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
539ef23711eSRafael Espindola   bool linkGlobalValueBody(GlobalValue &Src);
540ef23711eSRafael Espindola 
541c7ed52f2STeresa Johnson   /// Functions that take care of cloning a specific global value type
542c7ed52f2STeresa Johnson   /// into the destination module.
543c7ed52f2STeresa Johnson   GlobalVariable *copyGlobalVariableProto(TypeMapTy &TypeMap,
544c7ed52f2STeresa Johnson                                           const GlobalVariable *SGVar);
545c7ed52f2STeresa Johnson   Function *copyFunctionProto(TypeMapTy &TypeMap, const Function *SF);
546c7ed52f2STeresa Johnson   GlobalValue *copyGlobalAliasProto(TypeMapTy &TypeMap, const GlobalAlias *SGA);
547c7ed52f2STeresa Johnson 
548c7ed52f2STeresa Johnson   /// Helper methods to check if we are importing from or potentially
549c7ed52f2STeresa Johnson   /// exporting from the current source module.
550c7ed52f2STeresa Johnson   bool isPerformingImport() { return ImportFunction != nullptr; }
551c7ed52f2STeresa Johnson   bool isModuleExporting() { return HasExportedFunctions; }
552c7ed52f2STeresa Johnson 
553c7ed52f2STeresa Johnson   /// If we are importing from the source module, checks if we should
554c7ed52f2STeresa Johnson   /// import SGV as a definition, otherwise import as a declaration.
555c7ed52f2STeresa Johnson   bool doImportAsDefinition(const GlobalValue *SGV);
556c7ed52f2STeresa Johnson 
557c7ed52f2STeresa Johnson   /// Get the name for SGV that should be used in the linked destination
558c7ed52f2STeresa Johnson   /// module. Specifically, this handles the case where we need to rename
559c7ed52f2STeresa Johnson   /// a local that is being promoted to global scope.
560c7ed52f2STeresa Johnson   std::string getName(const GlobalValue *SGV);
561c7ed52f2STeresa Johnson 
562c7ed52f2STeresa Johnson   /// Get the new linkage for SGV that should be used in the linked destination
563c7ed52f2STeresa Johnson   /// module. Specifically, for ThinLTO importing or exporting it may need
564c7ed52f2STeresa Johnson   /// to be adjusted.
565c7ed52f2STeresa Johnson   GlobalValue::LinkageTypes getLinkage(const GlobalValue *SGV);
566c7ed52f2STeresa Johnson 
567c7ed52f2STeresa Johnson   /// Copies the necessary global value attributes and name from the source
568c7ed52f2STeresa Johnson   /// to the newly cloned global value.
569c7ed52f2STeresa Johnson   void copyGVAttributes(GlobalValue *NewGV, const GlobalValue *SrcGV);
570c7ed52f2STeresa Johnson 
571c7ed52f2STeresa Johnson   /// Updates the visibility for the new global cloned from the source
572c7ed52f2STeresa Johnson   /// and, if applicable, linked with an existing destination global.
573c7ed52f2STeresa Johnson   /// Handles visibility change required for promoted locals.
574c7ed52f2STeresa Johnson   void setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
575c7ed52f2STeresa Johnson                      const GlobalValue *DGV = nullptr);
576c7ed52f2STeresa Johnson 
577b1ed91f3SChris Lattner   void linkNamedMDNodes();
578eee6f995SChris Lattner };
579f00654e3SAlexander Kornienko }
580d48b7783SBill Wendling 
58118c89411SRafael Espindola /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
58218c89411SRafael Espindola /// table. This is good for all clients except for us. Go through the trouble
58318c89411SRafael Espindola /// to force this back.
584b1ed91f3SChris Lattner static void forceRenaming(GlobalValue *GV, StringRef Name) {
585b1ed91f3SChris Lattner   // If the global doesn't force its name or if it already has the right name,
586b1ed91f3SChris Lattner   // there is nothing for us to do.
587c7ed52f2STeresa Johnson   // Note that any required local to global promotion should already be done,
588c7ed52f2STeresa Johnson   // so promoted locals will not skip this handling as their linkage is no
589c7ed52f2STeresa Johnson   // longer local.
590b1ed91f3SChris Lattner   if (GV->hasLocalLinkage() || GV->getName() == Name)
591b1ed91f3SChris Lattner     return;
592b1ed91f3SChris Lattner 
593b1ed91f3SChris Lattner   Module *M = GV->getParent();
594361e513dSReid Spencer 
595361e513dSReid Spencer   // If there is a conflict, rename the conflict.
596b1ed91f3SChris Lattner   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
5972a8d2e0eSChris Lattner     GV->takeName(ConflictGV);
598361e513dSReid Spencer     ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
599b1ed91f3SChris Lattner     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
6002a8d2e0eSChris Lattner   } else {
6012a8d2e0eSChris Lattner     GV->setName(Name); // Force the name back
6023aaaa0b2SReid Spencer   }
6033aaaa0b2SReid Spencer }
6043aaaa0b2SReid Spencer 
60518c89411SRafael Espindola /// copy additional attributes (those not needed to construct a GlobalValue)
60618c89411SRafael Espindola /// from the SrcGV to the DestGV.
607c7ed52f2STeresa Johnson void ModuleLinker::copyGVAttributes(GlobalValue *NewGV,
608c7ed52f2STeresa Johnson                                     const GlobalValue *SrcGV) {
609c7ed52f2STeresa Johnson   auto *GA = dyn_cast<GlobalAlias>(SrcGV);
610c7ed52f2STeresa Johnson   // Check for the special case of converting an alias (definition) to a
611c7ed52f2STeresa Johnson   // non-alias (declaration). This can happen when we are importing and
612c7ed52f2STeresa Johnson   // encounter a weak_any alias (weak_any defs may not be imported, see
613c7ed52f2STeresa Johnson   // comments in ModuleLinker::getLinkage) or an alias whose base object is
614c7ed52f2STeresa Johnson   // being imported as a declaration. In that case copy the attributes from the
615c7ed52f2STeresa Johnson   // base object.
616c7ed52f2STeresa Johnson   if (GA && !dyn_cast<GlobalAlias>(NewGV)) {
6173cd8161cSTeresa Johnson     assert(isPerformingImport() && !doImportAsDefinition(GA));
618c7ed52f2STeresa Johnson     NewGV->copyAttributesFrom(GA->getBaseObject());
619c7ed52f2STeresa Johnson   } else
620c7ed52f2STeresa Johnson     NewGV->copyAttributesFrom(SrcGV);
621c7ed52f2STeresa Johnson   forceRenaming(NewGV, getName(SrcGV));
622361e513dSReid Spencer }
623361e513dSReid Spencer 
624c7ed52f2STeresa Johnson bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
625c7ed52f2STeresa Johnson   if (!isPerformingImport())
626c7ed52f2STeresa Johnson     return false;
6273cd8161cSTeresa Johnson   auto *GA = dyn_cast<GlobalAlias>(SGV);
6283cd8161cSTeresa Johnson   if (GA) {
6293cd8161cSTeresa Johnson     if (GA->hasWeakAnyLinkage())
6303cd8161cSTeresa Johnson       return false;
63189345771SRafael Espindola     const GlobalObject *GO = GA->getBaseObject();
63289345771SRafael Espindola     if (!GO->hasLinkOnceODRLinkage())
63389345771SRafael Espindola       return false;
63489345771SRafael Espindola     return doImportAsDefinition(GO);
6353cd8161cSTeresa Johnson   }
636dfbebc37STeresa Johnson   // Always import GlobalVariable definitions, except for the special
637dfbebc37STeresa Johnson   // case of WeakAny which are imported as ExternalWeak declarations
638dfbebc37STeresa Johnson   // (see comments in ModuleLinker::getLinkage). The linkage changes
639c7ed52f2STeresa Johnson   // described in ModuleLinker::getLinkage ensure the correct behavior (e.g.
640c7ed52f2STeresa Johnson   // global variables with external linkage are transformed to
6413cd8161cSTeresa Johnson   // available_externally definitions, which are ultimately turned into
6423cd8161cSTeresa Johnson   // declarations after the EliminateAvailableExternally pass).
64366059c9fSCraig Topper   if (isa<GlobalVariable>(SGV) && !SGV->isDeclaration() &&
6443cd8161cSTeresa Johnson       !SGV->hasWeakAnyLinkage())
645c7ed52f2STeresa Johnson     return true;
646c7ed52f2STeresa Johnson   // Only import the function requested for importing.
647c7ed52f2STeresa Johnson   auto *SF = dyn_cast<Function>(SGV);
648c7ed52f2STeresa Johnson   if (SF && SF == ImportFunction)
649c7ed52f2STeresa Johnson     return true;
650c7ed52f2STeresa Johnson   // Otherwise no.
651c7ed52f2STeresa Johnson   return false;
652c7ed52f2STeresa Johnson }
653c7ed52f2STeresa Johnson 
654c7ed52f2STeresa Johnson bool ModuleLinker::doPromoteLocalToGlobal(const GlobalValue *SGV) {
655c7ed52f2STeresa Johnson   assert(SGV->hasLocalLinkage());
656c7ed52f2STeresa Johnson   // Both the imported references and the original local variable must
657c7ed52f2STeresa Johnson   // be promoted.
658c7ed52f2STeresa Johnson   if (!isPerformingImport() && !isModuleExporting())
659c7ed52f2STeresa Johnson     return false;
660c7ed52f2STeresa Johnson 
661c7ed52f2STeresa Johnson   // Local const variables never need to be promoted unless they are address
662c7ed52f2STeresa Johnson   // taken. The imported uses can simply use the clone created in this module.
663c7ed52f2STeresa Johnson   // For now we are conservative in determining which variables are not
664c7ed52f2STeresa Johnson   // address taken by checking the unnamed addr flag. To be more aggressive,
665c7ed52f2STeresa Johnson   // the address taken information must be checked earlier during parsing
666c7ed52f2STeresa Johnson   // of the module and recorded in the function index for use when importing
667c7ed52f2STeresa Johnson   // from that module.
668c7ed52f2STeresa Johnson   auto *GVar = dyn_cast<GlobalVariable>(SGV);
669c7ed52f2STeresa Johnson   if (GVar && GVar->isConstant() && GVar->hasUnnamedAddr())
670c7ed52f2STeresa Johnson     return false;
671c7ed52f2STeresa Johnson 
672c7ed52f2STeresa Johnson   // Eventually we only need to promote functions in the exporting module that
673c7ed52f2STeresa Johnson   // are referenced by a potentially exported function (i.e. one that is in the
674c7ed52f2STeresa Johnson   // function index).
675c7ed52f2STeresa Johnson   return true;
676c7ed52f2STeresa Johnson }
677c7ed52f2STeresa Johnson 
678c7ed52f2STeresa Johnson std::string ModuleLinker::getName(const GlobalValue *SGV) {
679c7ed52f2STeresa Johnson   // For locals that must be promoted to global scope, ensure that
680c7ed52f2STeresa Johnson   // the promoted name uniquely identifies the copy in the original module,
681c7ed52f2STeresa Johnson   // using the ID assigned during combined index creation. When importing,
682c7ed52f2STeresa Johnson   // we rename all locals (not just those that are promoted) in order to
683c7ed52f2STeresa Johnson   // avoid naming conflicts between locals imported from different modules.
684c7ed52f2STeresa Johnson   if (SGV->hasLocalLinkage() &&
685c7ed52f2STeresa Johnson       (doPromoteLocalToGlobal(SGV) || isPerformingImport()))
686c7ed52f2STeresa Johnson     return FunctionInfoIndex::getGlobalNameForLocal(
687c7ed52f2STeresa Johnson         SGV->getName(),
688c7ed52f2STeresa Johnson         ImportIndex->getModuleId(SGV->getParent()->getModuleIdentifier()));
689c7ed52f2STeresa Johnson   return SGV->getName();
690c7ed52f2STeresa Johnson }
691c7ed52f2STeresa Johnson 
692c7ed52f2STeresa Johnson GlobalValue::LinkageTypes ModuleLinker::getLinkage(const GlobalValue *SGV) {
693c7ed52f2STeresa Johnson   // Any local variable that is referenced by an exported function needs
694c7ed52f2STeresa Johnson   // to be promoted to global scope. Since we don't currently know which
695c7ed52f2STeresa Johnson   // functions reference which local variables/functions, we must treat
696c7ed52f2STeresa Johnson   // all as potentially exported if this module is exporting anything.
697c7ed52f2STeresa Johnson   if (isModuleExporting()) {
698c7ed52f2STeresa Johnson     if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
699c7ed52f2STeresa Johnson       return GlobalValue::ExternalLinkage;
700c7ed52f2STeresa Johnson     return SGV->getLinkage();
701c7ed52f2STeresa Johnson   }
702c7ed52f2STeresa Johnson 
703c7ed52f2STeresa Johnson   // Otherwise, if we aren't importing, no linkage change is needed.
704c7ed52f2STeresa Johnson   if (!isPerformingImport())
705c7ed52f2STeresa Johnson     return SGV->getLinkage();
706c7ed52f2STeresa Johnson 
707c7ed52f2STeresa Johnson   switch (SGV->getLinkage()) {
708c7ed52f2STeresa Johnson   case GlobalValue::ExternalLinkage:
709c7ed52f2STeresa Johnson     // External defnitions are converted to available_externally
710c7ed52f2STeresa Johnson     // definitions upon import, so that they are available for inlining
711c7ed52f2STeresa Johnson     // and/or optimization, but are turned into declarations later
712c7ed52f2STeresa Johnson     // during the EliminateAvailableExternally pass.
7133cd8161cSTeresa Johnson     if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
714c7ed52f2STeresa Johnson       return GlobalValue::AvailableExternallyLinkage;
715c7ed52f2STeresa Johnson     // An imported external declaration stays external.
716c7ed52f2STeresa Johnson     return SGV->getLinkage();
717c7ed52f2STeresa Johnson 
718c7ed52f2STeresa Johnson   case GlobalValue::AvailableExternallyLinkage:
719c7ed52f2STeresa Johnson     // An imported available_externally definition converts
720c7ed52f2STeresa Johnson     // to external if imported as a declaration.
721c7ed52f2STeresa Johnson     if (!doImportAsDefinition(SGV))
722c7ed52f2STeresa Johnson       return GlobalValue::ExternalLinkage;
723c7ed52f2STeresa Johnson     // An imported available_externally declaration stays that way.
724c7ed52f2STeresa Johnson     return SGV->getLinkage();
725c7ed52f2STeresa Johnson 
726c7ed52f2STeresa Johnson   case GlobalValue::LinkOnceAnyLinkage:
727c7ed52f2STeresa Johnson   case GlobalValue::LinkOnceODRLinkage:
728c7ed52f2STeresa Johnson     // These both stay the same when importing the definition.
729c7ed52f2STeresa Johnson     // The ThinLTO pass will eventually force-import their definitions.
730c7ed52f2STeresa Johnson     return SGV->getLinkage();
731c7ed52f2STeresa Johnson 
732c7ed52f2STeresa Johnson   case GlobalValue::WeakAnyLinkage:
733c7ed52f2STeresa Johnson     // Can't import weak_any definitions correctly, or we might change the
734c7ed52f2STeresa Johnson     // program semantics, since the linker will pick the first weak_any
735c7ed52f2STeresa Johnson     // definition and importing would change the order they are seen by the
736c7ed52f2STeresa Johnson     // linker. The module linking caller needs to enforce this.
737c7ed52f2STeresa Johnson     assert(!doImportAsDefinition(SGV));
738c7ed52f2STeresa Johnson     // If imported as a declaration, it becomes external_weak.
739c7ed52f2STeresa Johnson     return GlobalValue::ExternalWeakLinkage;
740c7ed52f2STeresa Johnson 
741c7ed52f2STeresa Johnson   case GlobalValue::WeakODRLinkage:
742c7ed52f2STeresa Johnson     // For weak_odr linkage, there is a guarantee that all copies will be
743c7ed52f2STeresa Johnson     // equivalent, so the issue described above for weak_any does not exist,
744c7ed52f2STeresa Johnson     // and the definition can be imported. It can be treated similarly
745c7ed52f2STeresa Johnson     // to an imported externally visible global value.
7463cd8161cSTeresa Johnson     if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
747c7ed52f2STeresa Johnson       return GlobalValue::AvailableExternallyLinkage;
748c7ed52f2STeresa Johnson     else
749c7ed52f2STeresa Johnson       return GlobalValue::ExternalLinkage;
750c7ed52f2STeresa Johnson 
751c7ed52f2STeresa Johnson   case GlobalValue::AppendingLinkage:
752c7ed52f2STeresa Johnson     // It would be incorrect to import an appending linkage variable,
753c7ed52f2STeresa Johnson     // since it would cause global constructors/destructors to be
754c7ed52f2STeresa Johnson     // executed multiple times. This should have already been handled
755c7ed52f2STeresa Johnson     // by linkGlobalValueProto.
756f3d2329dSDavide Italiano     llvm_unreachable("Cannot import appending linkage variable");
757c7ed52f2STeresa Johnson 
758c7ed52f2STeresa Johnson   case GlobalValue::InternalLinkage:
759c7ed52f2STeresa Johnson   case GlobalValue::PrivateLinkage:
760c7ed52f2STeresa Johnson     // If we are promoting the local to global scope, it is handled
761c7ed52f2STeresa Johnson     // similarly to a normal externally visible global.
762c7ed52f2STeresa Johnson     if (doPromoteLocalToGlobal(SGV)) {
7633cd8161cSTeresa Johnson       if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
764c7ed52f2STeresa Johnson         return GlobalValue::AvailableExternallyLinkage;
765c7ed52f2STeresa Johnson       else
766c7ed52f2STeresa Johnson         return GlobalValue::ExternalLinkage;
767c7ed52f2STeresa Johnson     }
768c7ed52f2STeresa Johnson     // A non-promoted imported local definition stays local.
769c7ed52f2STeresa Johnson     // The ThinLTO pass will eventually force-import their definitions.
770c7ed52f2STeresa Johnson     return SGV->getLinkage();
771c7ed52f2STeresa Johnson 
772c7ed52f2STeresa Johnson   case GlobalValue::ExternalWeakLinkage:
773c7ed52f2STeresa Johnson     // External weak doesn't apply to definitions, must be a declaration.
774c7ed52f2STeresa Johnson     assert(!doImportAsDefinition(SGV));
775c7ed52f2STeresa Johnson     // Linkage stays external_weak.
776c7ed52f2STeresa Johnson     return SGV->getLinkage();
777c7ed52f2STeresa Johnson 
778c7ed52f2STeresa Johnson   case GlobalValue::CommonLinkage:
779c7ed52f2STeresa Johnson     // Linkage stays common on definitions.
780c7ed52f2STeresa Johnson     // The ThinLTO pass will eventually force-import their definitions.
781c7ed52f2STeresa Johnson     return SGV->getLinkage();
782c7ed52f2STeresa Johnson   }
783c7ed52f2STeresa Johnson 
784c7ed52f2STeresa Johnson   llvm_unreachable("unknown linkage type");
785c7ed52f2STeresa Johnson }
786c7ed52f2STeresa Johnson 
787ef23711eSRafael Espindola /// Loop through the global variables in the src module and merge them into the
788ef23711eSRafael Espindola /// dest module.
789c7ed52f2STeresa Johnson GlobalVariable *
790c7ed52f2STeresa Johnson ModuleLinker::copyGlobalVariableProto(TypeMapTy &TypeMap,
791ef23711eSRafael Espindola                                       const GlobalVariable *SGVar) {
792ef23711eSRafael Espindola   // No linking to be performed or linking from the source: simply create an
793ef23711eSRafael Espindola   // identical version of the symbol over in the dest module... the
794ef23711eSRafael Espindola   // initializer will be filled in later by LinkGlobalInits.
795ef23711eSRafael Espindola   GlobalVariable *NewDGV = new GlobalVariable(
7960e309fe8SRafael Espindola       DstM, TypeMap.get(SGVar->getType()->getElementType()),
797c7ed52f2STeresa Johnson       SGVar->isConstant(), getLinkage(SGVar), /*init*/ nullptr, getName(SGVar),
798c7ed52f2STeresa Johnson       /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
799ef23711eSRafael Espindola       SGVar->getType()->getAddressSpace());
800f6f121e2SJames Molloy 
801ef23711eSRafael Espindola   return NewDGV;
8023931c28bSRafael Espindola }
8033931c28bSRafael Espindola 
804ef23711eSRafael Espindola /// Link the function in the source module into the destination module if
805ef23711eSRafael Espindola /// needed, setting up mapping information.
806c7ed52f2STeresa Johnson Function *ModuleLinker::copyFunctionProto(TypeMapTy &TypeMap,
807ef23711eSRafael Espindola                                           const Function *SF) {
808ef23711eSRafael Espindola   // If there is no linkage to be performed or we are linking from the source,
809ef23711eSRafael Espindola   // bring SF over.
810c7ed52f2STeresa Johnson   return Function::Create(TypeMap.get(SF->getFunctionType()), getLinkage(SF),
8110e309fe8SRafael Espindola                           getName(SF), &DstM);
812ef23711eSRafael Espindola }
813ef23711eSRafael Espindola 
814ef23711eSRafael Espindola /// Set up prototypes for any aliases that come over from the source module.
815c7ed52f2STeresa Johnson GlobalValue *ModuleLinker::copyGlobalAliasProto(TypeMapTy &TypeMap,
816ef23711eSRafael Espindola                                                 const GlobalAlias *SGA) {
817c7ed52f2STeresa Johnson   // If we are importing and encounter a weak_any alias, or an alias to
818c7ed52f2STeresa Johnson   // an object being imported as a declaration, we must import the alias
819c7ed52f2STeresa Johnson   // as a declaration as well, which involves converting it to a non-alias.
820c7ed52f2STeresa Johnson   // See comments in ModuleLinker::getLinkage for why we cannot import
821c7ed52f2STeresa Johnson   // weak_any defintions.
8223cd8161cSTeresa Johnson   if (isPerformingImport() && !doImportAsDefinition(SGA)) {
823c7ed52f2STeresa Johnson     // Need to convert to declaration. All aliases must be definitions.
824c7ed52f2STeresa Johnson     const GlobalValue *GVal = SGA->getBaseObject();
825c7ed52f2STeresa Johnson     GlobalValue *NewGV;
826c7ed52f2STeresa Johnson     if (auto *GVar = dyn_cast<GlobalVariable>(GVal))
827c7ed52f2STeresa Johnson       NewGV = copyGlobalVariableProto(TypeMap, GVar);
828c7ed52f2STeresa Johnson     else {
829c7ed52f2STeresa Johnson       auto *F = dyn_cast<Function>(GVal);
830c7ed52f2STeresa Johnson       assert(F);
831c7ed52f2STeresa Johnson       NewGV = copyFunctionProto(TypeMap, F);
832c7ed52f2STeresa Johnson     }
833f1b0a6e3STeresa Johnson     // Set the linkage to External or ExternalWeak (see comments in
834f1b0a6e3STeresa Johnson     // ModuleLinker::getLinkage for why WeakAny is converted to ExternalWeak).
835c7ed52f2STeresa Johnson     if (SGA->hasWeakAnyLinkage())
836c7ed52f2STeresa Johnson       NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
837f1b0a6e3STeresa Johnson     else
838f1b0a6e3STeresa Johnson       NewGV->setLinkage(GlobalValue::ExternalLinkage);
839c7ed52f2STeresa Johnson     return NewGV;
840c7ed52f2STeresa Johnson   }
841ef23711eSRafael Espindola   // If there is no linkage to be performed or we're linking from the source,
842ef23711eSRafael Espindola   // bring over SGA.
8436614d8d2SDavid Blaikie   auto *Ty = TypeMap.get(SGA->getValueType());
8446614d8d2SDavid Blaikie   return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
8450e309fe8SRafael Espindola                              getLinkage(SGA), getName(SGA), &DstM);
846ef23711eSRafael Espindola }
847ef23711eSRafael Espindola 
848eb5e0a77SRafael Espindola static GlobalValue::VisibilityTypes
849eb5e0a77SRafael Espindola getMinVisibility(GlobalValue::VisibilityTypes A,
850eb5e0a77SRafael Espindola                  GlobalValue::VisibilityTypes B) {
851eb5e0a77SRafael Espindola   if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
852eb5e0a77SRafael Espindola     return GlobalValue::HiddenVisibility;
853eb5e0a77SRafael Espindola   if (A == GlobalValue::ProtectedVisibility ||
854eb5e0a77SRafael Espindola       B == GlobalValue::ProtectedVisibility)
855eb5e0a77SRafael Espindola     return GlobalValue::ProtectedVisibility;
856eb5e0a77SRafael Espindola   return GlobalValue::DefaultVisibility;
857eb5e0a77SRafael Espindola }
858eb5e0a77SRafael Espindola 
859c7ed52f2STeresa Johnson void ModuleLinker::setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
860c7ed52f2STeresa Johnson                                  const GlobalValue *DGV) {
861c7ed52f2STeresa Johnson   GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
862c7ed52f2STeresa Johnson   if (DGV)
863eb5e0a77SRafael Espindola     Visibility = getMinVisibility(DGV->getVisibility(), Visibility);
864c7ed52f2STeresa Johnson   // For promoted locals, mark them hidden so that they can later be
865c7ed52f2STeresa Johnson   // stripped from the symbol table to reduce bloat.
866c7ed52f2STeresa Johnson   if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
867c7ed52f2STeresa Johnson     Visibility = GlobalValue::HiddenVisibility;
868c7ed52f2STeresa Johnson   NewGV->setVisibility(Visibility);
869c7ed52f2STeresa Johnson }
870c7ed52f2STeresa Johnson 
871c7ed52f2STeresa Johnson GlobalValue *ModuleLinker::copyGlobalValueProto(TypeMapTy &TypeMap,
872c7ed52f2STeresa Johnson                                                 const GlobalValue *SGV,
873c7ed52f2STeresa Johnson                                                 const GlobalValue *DGV) {
874ef23711eSRafael Espindola   GlobalValue *NewGV;
875ef23711eSRafael Espindola   if (auto *SGVar = dyn_cast<GlobalVariable>(SGV))
876c7ed52f2STeresa Johnson     NewGV = copyGlobalVariableProto(TypeMap, SGVar);
877ef23711eSRafael Espindola   else if (auto *SF = dyn_cast<Function>(SGV))
878c7ed52f2STeresa Johnson     NewGV = copyFunctionProto(TypeMap, SF);
879ef23711eSRafael Espindola   else
880c7ed52f2STeresa Johnson     NewGV = copyGlobalAliasProto(TypeMap, cast<GlobalAlias>(SGV));
881ef23711eSRafael Espindola   copyGVAttributes(NewGV, SGV);
882c7ed52f2STeresa Johnson   setVisibility(NewGV, SGV, DGV);
883ef23711eSRafael Espindola   return NewGV;
884ef23711eSRafael Espindola }
885ef23711eSRafael Espindola 
88619b52383SRafael Espindola Value *ValueMaterializerTy::materializeDeclFor(Value *V) {
88719b52383SRafael Espindola   return ModLinker->materializeDeclFor(V);
88819b52383SRafael Espindola }
88919b52383SRafael Espindola 
89019b52383SRafael Espindola Value *ModuleLinker::materializeDeclFor(Value *V) {
891ef23711eSRafael Espindola   auto *SGV = dyn_cast<GlobalValue>(V);
892ef23711eSRafael Espindola   if (!SGV)
893ef23711eSRafael Espindola     return nullptr;
894ef23711eSRafael Espindola 
8951063293aSTeresa Johnson   // If we are done linking global value bodies (i.e. we are performing
8961063293aSTeresa Johnson   // metadata linking), don't link in the global value due to this
8971063293aSTeresa Johnson   // reference, simply map it to null.
89819b52383SRafael Espindola   if (doneLinkingBodies())
8991063293aSTeresa Johnson     return nullptr;
9001063293aSTeresa Johnson 
901baa3bf8fSRafael Espindola   linkGlobalValueProto(SGV);
902baa3bf8fSRafael Espindola   if (HasError)
903baa3bf8fSRafael Espindola     return nullptr;
904baa3bf8fSRafael Espindola   Value *Ret = ValueMap[SGV];
905baa3bf8fSRafael Espindola   assert(Ret);
906baa3bf8fSRafael Espindola   return Ret;
907f6f121e2SJames Molloy }
908f6f121e2SJames Molloy 
90919b52383SRafael Espindola void ValueMaterializerTy::materializeInitFor(GlobalValue *New,
91019b52383SRafael Espindola                                              GlobalValue *Old) {
91119b52383SRafael Espindola   return ModLinker->materializeInitFor(New, Old);
91219b52383SRafael Espindola }
91319b52383SRafael Espindola 
91419b52383SRafael Espindola void ModuleLinker::materializeInitFor(GlobalValue *New, GlobalValue *Old) {
915baa3bf8fSRafael Espindola   if (auto *F = dyn_cast<Function>(New)) {
916baa3bf8fSRafael Espindola     if (!F->isDeclaration())
917baa3bf8fSRafael Espindola       return;
918baa3bf8fSRafael Espindola   } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
919baa3bf8fSRafael Espindola     if (V->hasInitializer())
920baa3bf8fSRafael Espindola       return;
921baa3bf8fSRafael Espindola   } else {
922baa3bf8fSRafael Espindola     auto *A = cast<GlobalAlias>(New);
923baa3bf8fSRafael Espindola     if (A->getAliasee())
924baa3bf8fSRafael Espindola       return;
925baa3bf8fSRafael Espindola   }
926baa3bf8fSRafael Espindola 
927baa3bf8fSRafael Espindola   if (Old->isDeclaration())
928baa3bf8fSRafael Espindola     return;
929baa3bf8fSRafael Espindola 
93019b52383SRafael Espindola   if (isPerformingImport() && !doImportAsDefinition(Old))
93119b52383SRafael Espindola     return;
93219b52383SRafael Espindola 
933baa3bf8fSRafael Espindola   if (!New->hasLocalLinkage() && DoNotLinkFromSource.count(Old))
93419b52383SRafael Espindola     return;
93519b52383SRafael Espindola 
93619b52383SRafael Espindola   linkGlobalValueBody(*Old);
93719b52383SRafael Espindola }
93819b52383SRafael Espindola 
9390e309fe8SRafael Espindola bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
940dad0a645SDavid Majnemer                                    const GlobalVariable *&GVar) {
9410e309fe8SRafael Espindola   const GlobalValue *GVal = M.getNamedValue(ComdatName);
942dad0a645SDavid Majnemer   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
943dad0a645SDavid Majnemer     GVal = GA->getBaseObject();
944dad0a645SDavid Majnemer     if (!GVal)
945dad0a645SDavid Majnemer       // We cannot resolve the size of the aliasee yet.
946dad0a645SDavid Majnemer       return emitError("Linking COMDATs named '" + ComdatName +
947dad0a645SDavid Majnemer                        "': COMDAT key involves incomputable alias size.");
948dad0a645SDavid Majnemer   }
949dad0a645SDavid Majnemer 
950dad0a645SDavid Majnemer   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
951dad0a645SDavid Majnemer   if (!GVar)
952dad0a645SDavid Majnemer     return emitError(
953dad0a645SDavid Majnemer         "Linking COMDATs named '" + ComdatName +
954dad0a645SDavid Majnemer         "': GlobalVariable required for data dependent selection!");
955dad0a645SDavid Majnemer 
956dad0a645SDavid Majnemer   return false;
957dad0a645SDavid Majnemer }
958dad0a645SDavid Majnemer 
959dad0a645SDavid Majnemer bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
960dad0a645SDavid Majnemer                                                  Comdat::SelectionKind Src,
961dad0a645SDavid Majnemer                                                  Comdat::SelectionKind Dst,
962dad0a645SDavid Majnemer                                                  Comdat::SelectionKind &Result,
963dad0a645SDavid Majnemer                                                  bool &LinkFromSrc) {
964dad0a645SDavid Majnemer   // The ability to mix Comdat::SelectionKind::Any with
965dad0a645SDavid Majnemer   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
966dad0a645SDavid Majnemer   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
967dad0a645SDavid Majnemer                          Dst == Comdat::SelectionKind::Largest;
968dad0a645SDavid Majnemer   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
969dad0a645SDavid Majnemer                          Src == Comdat::SelectionKind::Largest;
970dad0a645SDavid Majnemer   if (DstAnyOrLargest && SrcAnyOrLargest) {
971dad0a645SDavid Majnemer     if (Dst == Comdat::SelectionKind::Largest ||
972dad0a645SDavid Majnemer         Src == Comdat::SelectionKind::Largest)
973dad0a645SDavid Majnemer       Result = Comdat::SelectionKind::Largest;
974dad0a645SDavid Majnemer     else
975dad0a645SDavid Majnemer       Result = Comdat::SelectionKind::Any;
976dad0a645SDavid Majnemer   } else if (Src == Dst) {
977dad0a645SDavid Majnemer     Result = Dst;
978dad0a645SDavid Majnemer   } else {
979dad0a645SDavid Majnemer     return emitError("Linking COMDATs named '" + ComdatName +
980dad0a645SDavid Majnemer                      "': invalid selection kinds!");
981dad0a645SDavid Majnemer   }
982dad0a645SDavid Majnemer 
983dad0a645SDavid Majnemer   switch (Result) {
984dad0a645SDavid Majnemer   case Comdat::SelectionKind::Any:
985dad0a645SDavid Majnemer     // Go with Dst.
986dad0a645SDavid Majnemer     LinkFromSrc = false;
987dad0a645SDavid Majnemer     break;
988dad0a645SDavid Majnemer   case Comdat::SelectionKind::NoDuplicates:
989dad0a645SDavid Majnemer     return emitError("Linking COMDATs named '" + ComdatName +
990dad0a645SDavid Majnemer                      "': noduplicates has been violated!");
991dad0a645SDavid Majnemer   case Comdat::SelectionKind::ExactMatch:
992dad0a645SDavid Majnemer   case Comdat::SelectionKind::Largest:
993dad0a645SDavid Majnemer   case Comdat::SelectionKind::SameSize: {
994dad0a645SDavid Majnemer     const GlobalVariable *DstGV;
995dad0a645SDavid Majnemer     const GlobalVariable *SrcGV;
996dad0a645SDavid Majnemer     if (getComdatLeader(DstM, ComdatName, DstGV) ||
997dad0a645SDavid Majnemer         getComdatLeader(SrcM, ComdatName, SrcGV))
998dad0a645SDavid Majnemer       return true;
999dad0a645SDavid Majnemer 
10000e309fe8SRafael Espindola     const DataLayout &DstDL = DstM.getDataLayout();
10010e309fe8SRafael Espindola     const DataLayout &SrcDL = SrcM.getDataLayout();
1002dad0a645SDavid Majnemer     uint64_t DstSize =
100346a43556SMehdi Amini         DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
1004dad0a645SDavid Majnemer     uint64_t SrcSize =
100546a43556SMehdi Amini         SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
1006dad0a645SDavid Majnemer     if (Result == Comdat::SelectionKind::ExactMatch) {
1007dad0a645SDavid Majnemer       if (SrcGV->getInitializer() != DstGV->getInitializer())
1008dad0a645SDavid Majnemer         return emitError("Linking COMDATs named '" + ComdatName +
1009dad0a645SDavid Majnemer                          "': ExactMatch violated!");
1010dad0a645SDavid Majnemer       LinkFromSrc = false;
1011dad0a645SDavid Majnemer     } else if (Result == Comdat::SelectionKind::Largest) {
1012dad0a645SDavid Majnemer       LinkFromSrc = SrcSize > DstSize;
1013dad0a645SDavid Majnemer     } else if (Result == Comdat::SelectionKind::SameSize) {
1014dad0a645SDavid Majnemer       if (SrcSize != DstSize)
1015dad0a645SDavid Majnemer         return emitError("Linking COMDATs named '" + ComdatName +
1016dad0a645SDavid Majnemer                          "': SameSize violated!");
1017dad0a645SDavid Majnemer       LinkFromSrc = false;
1018dad0a645SDavid Majnemer     } else {
1019dad0a645SDavid Majnemer       llvm_unreachable("unknown selection kind");
1020dad0a645SDavid Majnemer     }
1021dad0a645SDavid Majnemer     break;
1022dad0a645SDavid Majnemer   }
1023dad0a645SDavid Majnemer   }
1024dad0a645SDavid Majnemer 
1025dad0a645SDavid Majnemer   return false;
1026dad0a645SDavid Majnemer }
1027dad0a645SDavid Majnemer 
1028dad0a645SDavid Majnemer bool ModuleLinker::getComdatResult(const Comdat *SrcC,
1029dad0a645SDavid Majnemer                                    Comdat::SelectionKind &Result,
1030dad0a645SDavid Majnemer                                    bool &LinkFromSrc) {
1031b16196a3SRafael Espindola   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
1032dad0a645SDavid Majnemer   StringRef ComdatName = SrcC->getName();
10330e309fe8SRafael Espindola   Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
1034dad0a645SDavid Majnemer   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
10352ef3f299SRafael Espindola 
1036b16196a3SRafael Espindola   if (DstCI == ComdatSymTab.end()) {
1037b16196a3SRafael Espindola     // Use the comdat if it is only available in one of the modules.
1038b16196a3SRafael Espindola     LinkFromSrc = true;
1039b16196a3SRafael Espindola     Result = SSK;
10402ef3f299SRafael Espindola     return false;
1041b16196a3SRafael Espindola   }
10422ef3f299SRafael Espindola 
1043dad0a645SDavid Majnemer   const Comdat *DstC = &DstCI->second;
1044dad0a645SDavid Majnemer   Comdat::SelectionKind DSK = DstC->getSelectionKind();
10452ef3f299SRafael Espindola   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
10462ef3f299SRafael Espindola                                        LinkFromSrc);
1047dad0a645SDavid Majnemer }
1048f6f121e2SJames Molloy 
1049d12b4a33SRafael Espindola bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
1050d12b4a33SRafael Espindola                                         const GlobalValue &Dest,
1051dbb0bd1aSRafael Espindola                                         const GlobalValue &Src) {
1052e868123dSDuncan P. N. Exon Smith   // Should we unconditionally use the Src?
1053020d4fb1SArtem Belevich   if (shouldOverrideFromSrc()) {
1054e868123dSDuncan P. N. Exon Smith     LinkFromSrc = true;
1055e868123dSDuncan P. N. Exon Smith     return false;
1056e868123dSDuncan P. N. Exon Smith   }
1057e868123dSDuncan P. N. Exon Smith 
1058778fcc77SRafael Espindola   // We always have to add Src if it has appending linkage.
1059778fcc77SRafael Espindola   if (Src.hasAppendingLinkage()) {
1060c7ed52f2STeresa Johnson     // Caller should have already determined that we can't link from source
1061c7ed52f2STeresa Johnson     // when importing (see comments in linkGlobalValueProto).
1062c7ed52f2STeresa Johnson     assert(!isPerformingImport());
1063778fcc77SRafael Espindola     LinkFromSrc = true;
1064778fcc77SRafael Espindola     return false;
1065778fcc77SRafael Espindola   }
1066778fcc77SRafael Espindola 
1067d4bcefc7SRafael Espindola   bool SrcIsDeclaration = Src.isDeclarationForLinker();
1068d4bcefc7SRafael Espindola   bool DestIsDeclaration = Dest.isDeclarationForLinker();
1069dbb0bd1aSRafael Espindola 
1070c7ed52f2STeresa Johnson   if (isPerformingImport()) {
1071c7ed52f2STeresa Johnson     if (isa<Function>(&Src)) {
1072c7ed52f2STeresa Johnson       // For functions, LinkFromSrc iff this is the function requested
1073c7ed52f2STeresa Johnson       // for importing. For variables, decide below normally.
1074c7ed52f2STeresa Johnson       LinkFromSrc = (&Src == ImportFunction);
1075c7ed52f2STeresa Johnson       return false;
1076c7ed52f2STeresa Johnson     }
1077c7ed52f2STeresa Johnson 
1078c7ed52f2STeresa Johnson     // Check if this is an alias with an already existing definition
1079c7ed52f2STeresa Johnson     // in Dest, which must have come from a prior importing pass from
1080c7ed52f2STeresa Johnson     // the same Src module. Unlike imported function and variable
1081c7ed52f2STeresa Johnson     // definitions, which are imported as available_externally and are
1082c7ed52f2STeresa Johnson     // not definitions for the linker, that is not a valid linkage for
1083c7ed52f2STeresa Johnson     // imported aliases which must be definitions. Simply use the existing
1084c7ed52f2STeresa Johnson     // Dest copy.
1085c7ed52f2STeresa Johnson     if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
1086c7ed52f2STeresa Johnson       assert(isa<GlobalAlias>(&Dest));
1087c7ed52f2STeresa Johnson       LinkFromSrc = false;
1088c7ed52f2STeresa Johnson       return false;
1089c7ed52f2STeresa Johnson     }
1090c7ed52f2STeresa Johnson   }
1091c7ed52f2STeresa Johnson 
1092dbb0bd1aSRafael Espindola   if (SrcIsDeclaration) {
1093dbb0bd1aSRafael Espindola     // If Src is external or if both Src & Dest are external..  Just link the
1094dbb0bd1aSRafael Espindola     // external globals, we aren't adding anything.
1095d12b4a33SRafael Espindola     if (Src.hasDLLImportStorageClass()) {
1096dbb0bd1aSRafael Espindola       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
1097d12b4a33SRafael Espindola       LinkFromSrc = DestIsDeclaration;
1098d12b4a33SRafael Espindola       return false;
1099d12b4a33SRafael Espindola     }
1100dbb0bd1aSRafael Espindola     // If the Dest is weak, use the source linkage.
1101d12b4a33SRafael Espindola     LinkFromSrc = Dest.hasExternalWeakLinkage();
1102d12b4a33SRafael Espindola     return false;
1103dbb0bd1aSRafael Espindola   }
1104dbb0bd1aSRafael Espindola 
1105d12b4a33SRafael Espindola   if (DestIsDeclaration) {
1106dbb0bd1aSRafael Espindola     // If Dest is external but Src is not:
1107d12b4a33SRafael Espindola     LinkFromSrc = true;
1108d12b4a33SRafael Espindola     return false;
1109d12b4a33SRafael Espindola   }
1110dbb0bd1aSRafael Espindola 
11110910605aSRafael Espindola   if (Src.hasCommonLinkage()) {
1112d12b4a33SRafael Espindola     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
1113d12b4a33SRafael Espindola       LinkFromSrc = true;
11140910605aSRafael Espindola       return false;
1115d12b4a33SRafael Espindola     }
1116d12b4a33SRafael Espindola 
1117d12b4a33SRafael Espindola     if (!Dest.hasCommonLinkage()) {
1118d12b4a33SRafael Espindola       LinkFromSrc = false;
1119d12b4a33SRafael Espindola       return false;
1120d12b4a33SRafael Espindola     }
11210910605aSRafael Espindola 
1122a28d91d8SMehdi Amini     const DataLayout &DL = Dest.getParent()->getDataLayout();
11230910605aSRafael Espindola     uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
11240910605aSRafael Espindola     uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
1125d12b4a33SRafael Espindola     LinkFromSrc = SrcSize > DestSize;
1126d12b4a33SRafael Espindola     return false;
11270910605aSRafael Espindola   }
11280910605aSRafael Espindola 
1129dbb0bd1aSRafael Espindola   if (Src.isWeakForLinker()) {
1130dbb0bd1aSRafael Espindola     assert(!Dest.hasExternalWeakLinkage());
1131dbb0bd1aSRafael Espindola     assert(!Dest.hasAvailableExternallyLinkage());
11320910605aSRafael Espindola 
1133d12b4a33SRafael Espindola     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
1134d12b4a33SRafael Espindola       LinkFromSrc = true;
1135d12b4a33SRafael Espindola       return false;
1136d12b4a33SRafael Espindola     }
1137dbb0bd1aSRafael Espindola 
1138d12b4a33SRafael Espindola     LinkFromSrc = false;
11390910605aSRafael Espindola     return false;
1140dbb0bd1aSRafael Espindola   }
1141dbb0bd1aSRafael Espindola 
1142dbb0bd1aSRafael Espindola   if (Dest.isWeakForLinker()) {
1143dbb0bd1aSRafael Espindola     assert(Src.hasExternalLinkage());
1144d12b4a33SRafael Espindola     LinkFromSrc = true;
1145d12b4a33SRafael Espindola     return false;
1146dbb0bd1aSRafael Espindola   }
1147dbb0bd1aSRafael Espindola 
1148dbb0bd1aSRafael Espindola   assert(!Src.hasExternalWeakLinkage());
1149dbb0bd1aSRafael Espindola   assert(!Dest.hasExternalWeakLinkage());
1150dbb0bd1aSRafael Espindola   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
1151dbb0bd1aSRafael Espindola          "Unexpected linkage type!");
1152dbb0bd1aSRafael Espindola   return emitError("Linking globals named '" + Src.getName() +
1153dbb0bd1aSRafael Espindola                    "': symbol multiply defined!");
1154dbb0bd1aSRafael Espindola }
1155dbb0bd1aSRafael Espindola 
115618c89411SRafael Espindola /// Loop over all of the linked values to compute type mappings.  For example,
115718c89411SRafael Espindola /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
115818c89411SRafael Espindola /// types 'Foo' but one got renamed when the module was loaded into the same
115918c89411SRafael Espindola /// LLVMContext.
1160b1ed91f3SChris Lattner void ModuleLinker::computeTypeMapping() {
11610e309fe8SRafael Espindola   for (GlobalValue &SGV : SrcM.globals()) {
1162c8a476eeSRafael Espindola     GlobalValue *DGV = getLinkedToGlobal(&SGV);
1163c8a476eeSRafael Espindola     if (!DGV)
1164c8a476eeSRafael Espindola       continue;
1165b1ed91f3SChris Lattner 
1166c8a476eeSRafael Espindola     if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
1167c8a476eeSRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1168b1ed91f3SChris Lattner       continue;
11695c310be0SDevang Patel     }
11705c310be0SDevang Patel 
1171b1ed91f3SChris Lattner     // Unify the element type of appending arrays.
1172b1ed91f3SChris Lattner     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
1173c8a476eeSRafael Espindola     ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
1174b1ed91f3SChris Lattner     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
1175b1ed91f3SChris Lattner   }
117634fc5a0eSChris Lattner 
11770e309fe8SRafael Espindola   for (GlobalValue &SGV : SrcM) {
1178c8a476eeSRafael Espindola     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1179c8a476eeSRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1180b1ed91f3SChris Lattner   }
1181e79f4c77SAnton Korobeynikov 
11820e309fe8SRafael Espindola   for (GlobalValue &SGV : SrcM.aliases()) {
1183e96d7eb8SRafael Espindola     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1184e96d7eb8SRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1185e96d7eb8SRafael Espindola   }
1186e96d7eb8SRafael Espindola 
1187d48b7783SBill Wendling   // Incorporate types by name, scanning all the types in the source module.
1188d48b7783SBill Wendling   // At this point, the destination module may have a type "%foo = { i32 }" for
11892b3f61afSBill Wendling   // example.  When the source module got loaded into the same LLVMContext, if
11902b3f61afSBill Wendling   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
11910e309fe8SRafael Espindola   std::vector<StructType *> Types = SrcM.getIdentifiedStructTypes();
11922fa1e43aSRafael Espindola   for (StructType *ST : Types) {
11934d4c9387SRafael Espindola     if (!ST->hasName())
11944d4c9387SRafael Espindola       continue;
11952b3f61afSBill Wendling 
11962b3f61afSBill Wendling     // Check to see if there is a dot in the name followed by a digit.
1197d48b7783SBill Wendling     size_t DotPos = ST->getName().rfind('.');
1198d48b7783SBill Wendling     if (DotPos == 0 || DotPos == StringRef::npos ||
119983c74e9fSGuy Benyei         ST->getName().back() == '.' ||
120083c74e9fSGuy Benyei         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
1201d48b7783SBill Wendling       continue;
12022b3f61afSBill Wendling 
12032b3f61afSBill Wendling     // Check to see if the destination module has a struct with the prefix name.
12040e309fe8SRafael Espindola     StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
1205973b3612SRafael Espindola     if (!DST)
1206973b3612SRafael Espindola       continue;
1207973b3612SRafael Espindola 
12082b3f61afSBill Wendling     // Don't use it if this actually came from the source module. They're in
12098737480dSBill Wendling     // the same LLVMContext after all. Also don't use it unless the type is
12108737480dSBill Wendling     // actually used in the destination module. This can happen in situations
12118737480dSBill Wendling     // like this:
12128737480dSBill Wendling     //
12138737480dSBill Wendling     //      Module A                         Module B
12148737480dSBill Wendling     //      --------                         --------
12158737480dSBill Wendling     //   %Z = type { %A }                %B = type { %C.1 }
12168737480dSBill Wendling     //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
12178737480dSBill Wendling     //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
12188737480dSBill Wendling     //   %C = type { i8* }               %B.3 = type { %C.1 }
12198737480dSBill Wendling     //
12208737480dSBill Wendling     // When we link Module B with Module A, the '%B' in Module B is
12218737480dSBill Wendling     // used. However, that would then use '%C.1'. But when we process '%C.1',
12228737480dSBill Wendling     // we prefer to take the '%C' version. So we are then left with both
12238737480dSBill Wendling     // '%C.1' and '%C' being used for the same types. This leads to some
12248737480dSBill Wendling     // variables using one type and some using the other.
122531ad468dSRafael Espindola     if (TypeMap.DstStructTypesSet.hasType(DST))
12262b3f61afSBill Wendling       TypeMap.addTypeMapping(DST, ST);
12272b3f61afSBill Wendling   }
12282b3f61afSBill Wendling 
1229b1ed91f3SChris Lattner   // Now that we have discovered all of the type equivalences, get a body for
1230b1ed91f3SChris Lattner   // any 'opaque' types in the dest module that are now resolved.
1231b1ed91f3SChris Lattner   TypeMap.linkDefinedTypeBodies();
1232b1ed91f3SChris Lattner }
1233c08e7a00SChris Lattner 
123409d84addSDuncan P. N. Exon Smith static void upgradeGlobalArray(GlobalVariable *GV) {
123509d84addSDuncan P. N. Exon Smith   ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
123609d84addSDuncan P. N. Exon Smith   StructType *OldTy = cast<StructType>(ATy->getElementType());
123709d84addSDuncan P. N. Exon Smith   assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
123809d84addSDuncan P. N. Exon Smith 
123909d84addSDuncan P. N. Exon Smith   // Get the upgraded 3 element type.
124009d84addSDuncan P. N. Exon Smith   PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
124109d84addSDuncan P. N. Exon Smith   Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
124209d84addSDuncan P. N. Exon Smith                   VoidPtrTy};
124309d84addSDuncan P. N. Exon Smith   StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
124409d84addSDuncan P. N. Exon Smith 
124509d84addSDuncan P. N. Exon Smith   // Build new constants with a null third field filled in.
124609d84addSDuncan P. N. Exon Smith   Constant *OldInitC = GV->getInitializer();
124709d84addSDuncan P. N. Exon Smith   ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
124809d84addSDuncan P. N. Exon Smith   if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
124909d84addSDuncan P. N. Exon Smith     // Invalid initializer; give up.
125009d84addSDuncan P. N. Exon Smith     return;
125109d84addSDuncan P. N. Exon Smith   std::vector<Constant *> Initializers;
125209d84addSDuncan P. N. Exon Smith   if (OldInit && OldInit->getNumOperands()) {
125309d84addSDuncan P. N. Exon Smith     Value *Null = Constant::getNullValue(VoidPtrTy);
125409d84addSDuncan P. N. Exon Smith     for (Use &U : OldInit->operands()) {
125509d84addSDuncan P. N. Exon Smith       ConstantStruct *Init = cast<ConstantStruct>(U.get());
125609d84addSDuncan P. N. Exon Smith       Initializers.push_back(ConstantStruct::get(
125709d84addSDuncan P. N. Exon Smith           NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
125809d84addSDuncan P. N. Exon Smith     }
125909d84addSDuncan P. N. Exon Smith   }
126009d84addSDuncan P. N. Exon Smith   assert(Initializers.size() == ATy->getNumElements() &&
126109d84addSDuncan P. N. Exon Smith          "Failed to copy all array elements");
126209d84addSDuncan P. N. Exon Smith 
126309d84addSDuncan P. N. Exon Smith   // Replace the old GV with a new one.
126409d84addSDuncan P. N. Exon Smith   ATy = ArrayType::get(NewTy, Initializers.size());
126509d84addSDuncan P. N. Exon Smith   Constant *NewInit = ConstantArray::get(ATy, Initializers);
126609d84addSDuncan P. N. Exon Smith   GlobalVariable *NewGV = new GlobalVariable(
126709d84addSDuncan P. N. Exon Smith       *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
126809d84addSDuncan P. N. Exon Smith       GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
126909d84addSDuncan P. N. Exon Smith       GV->isExternallyInitialized());
127009d84addSDuncan P. N. Exon Smith   NewGV->copyAttributesFrom(GV);
127109d84addSDuncan P. N. Exon Smith   NewGV->takeName(GV);
127209d84addSDuncan P. N. Exon Smith   assert(GV->use_empty() && "program cannot use initializer list");
127309d84addSDuncan P. N. Exon Smith   GV->eraseFromParent();
127409d84addSDuncan P. N. Exon Smith }
127509d84addSDuncan P. N. Exon Smith 
127609d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
127709d84addSDuncan P. N. Exon Smith   // Look for the global arrays.
12780e309fe8SRafael Espindola   auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM.getNamedValue(Name));
127909d84addSDuncan P. N. Exon Smith   if (!DstGV)
128009d84addSDuncan P. N. Exon Smith     return;
12810e309fe8SRafael Espindola   auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM.getNamedValue(Name));
128209d84addSDuncan P. N. Exon Smith   if (!SrcGV)
128309d84addSDuncan P. N. Exon Smith     return;
128409d84addSDuncan P. N. Exon Smith 
128509d84addSDuncan P. N. Exon Smith   // Check if the types already match.
128609d84addSDuncan P. N. Exon Smith   auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
128709d84addSDuncan P. N. Exon Smith   auto *SrcTy =
128809d84addSDuncan P. N. Exon Smith       cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
128909d84addSDuncan P. N. Exon Smith   if (DstTy == SrcTy)
129009d84addSDuncan P. N. Exon Smith     return;
129109d84addSDuncan P. N. Exon Smith 
129209d84addSDuncan P. N. Exon Smith   // Grab the element types.  We can only upgrade an array of a two-field
129309d84addSDuncan P. N. Exon Smith   // struct.  Only bother if the other one has three-fields.
129409d84addSDuncan P. N. Exon Smith   auto *DstEltTy = cast<StructType>(DstTy->getElementType());
129509d84addSDuncan P. N. Exon Smith   auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
129609d84addSDuncan P. N. Exon Smith   if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
129709d84addSDuncan P. N. Exon Smith     upgradeGlobalArray(DstGV);
129809d84addSDuncan P. N. Exon Smith     return;
129909d84addSDuncan P. N. Exon Smith   }
130009d84addSDuncan P. N. Exon Smith   if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
130109d84addSDuncan P. N. Exon Smith     upgradeGlobalArray(SrcGV);
130209d84addSDuncan P. N. Exon Smith 
130309d84addSDuncan P. N. Exon Smith   // We can't upgrade any other differences.
130409d84addSDuncan P. N. Exon Smith }
130509d84addSDuncan P. N. Exon Smith 
130609d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobals() {
130709d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobalArray("llvm.global_ctors");
130809d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobalArray("llvm.global_dtors");
130909d84addSDuncan P. N. Exon Smith }
131009d84addSDuncan P. N. Exon Smith 
13116e8ab928SRafael Espindola static void getArrayElements(const Constant *C,
13126e8ab928SRafael Espindola                              SmallVectorImpl<Constant *> &Dest) {
13136e8ab928SRafael Espindola   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
13146e8ab928SRafael Espindola 
13156e8ab928SRafael Espindola   for (unsigned i = 0; i != NumElements; ++i)
13166e8ab928SRafael Espindola     Dest.push_back(C->getAggregateElement(i));
13176e8ab928SRafael Espindola }
13186e8ab928SRafael Espindola 
131918c89411SRafael Espindola /// If there were any appending global variables, link them together now.
132018c89411SRafael Espindola /// Return true on error.
1321b1ed91f3SChris Lattner bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
13223e8bc6a8SRafael Espindola                                          const GlobalVariable *SrcGV) {
1323b1ed91f3SChris Lattner   ArrayType *SrcTy =
1324b1ed91f3SChris Lattner       cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
1325c945c8d2SRafael Espindola   Type *EltTy = SrcTy->getElementType();
1326c945c8d2SRafael Espindola 
1327c945c8d2SRafael Espindola   if (DstGV) {
1328c945c8d2SRafael Espindola     ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
1329c945c8d2SRafael Espindola 
1330c945c8d2SRafael Espindola     if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
1331c945c8d2SRafael Espindola       return emitError(
1332c945c8d2SRafael Espindola           "Linking globals named '" + SrcGV->getName() +
1333c945c8d2SRafael Espindola           "': can only link appending global with another appending global!");
1334b1ed91f3SChris Lattner 
1335b1ed91f3SChris Lattner     // Check to see that they two arrays agree on type.
1336c945c8d2SRafael Espindola     if (EltTy != DstTy->getElementType())
1337b1ed91f3SChris Lattner       return emitError("Appending variables with different element types!");
1338b1ed91f3SChris Lattner     if (DstGV->isConstant() != SrcGV->isConstant())
1339b1ed91f3SChris Lattner       return emitError("Appending variables linked with different const'ness!");
1340b1ed91f3SChris Lattner 
1341b1ed91f3SChris Lattner     if (DstGV->getAlignment() != SrcGV->getAlignment())
1342b1ed91f3SChris Lattner       return emitError(
1343b1ed91f3SChris Lattner           "Appending variables with different alignment need to be linked!");
1344b1ed91f3SChris Lattner 
1345b1ed91f3SChris Lattner     if (DstGV->getVisibility() != SrcGV->getVisibility())
1346b1ed91f3SChris Lattner       return emitError(
1347b1ed91f3SChris Lattner           "Appending variables with different visibility need to be linked!");
1348b1ed91f3SChris Lattner 
1349fac3a018SRafael Espindola     if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
1350fac3a018SRafael Espindola       return emitError(
1351fac3a018SRafael Espindola           "Appending variables with different unnamed_addr need to be linked!");
1352fac3a018SRafael Espindola 
135364c1e180SRafael Espindola     if (StringRef(DstGV->getSection()) != SrcGV->getSection())
1354b1ed91f3SChris Lattner       return emitError(
1355b1ed91f3SChris Lattner           "Appending variables with different section name need to be linked!");
1356c945c8d2SRafael Espindola   }
1357b1ed91f3SChris Lattner 
13586e8ab928SRafael Espindola   SmallVector<Constant *, 16> DstElements;
13596e8ab928SRafael Espindola   if (DstGV)
13606e8ab928SRafael Espindola     getArrayElements(DstGV->getInitializer(), DstElements);
13616e8ab928SRafael Espindola 
13626e8ab928SRafael Espindola   SmallVector<Constant *, 16> SrcElements;
13636e8ab928SRafael Espindola   getArrayElements(SrcGV->getInitializer(), SrcElements);
13646e8ab928SRafael Espindola 
13656e8ab928SRafael Espindola   StringRef Name = SrcGV->getName();
13666e8ab928SRafael Espindola   bool IsNewStructor =
13676e8ab928SRafael Espindola       (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
13686e8ab928SRafael Espindola       cast<StructType>(EltTy)->getNumElements() == 3;
13696e8ab928SRafael Espindola   if (IsNewStructor)
13706e8ab928SRafael Espindola     SrcElements.erase(
13716e8ab928SRafael Espindola         std::remove_if(SrcElements.begin(), SrcElements.end(),
13726e8ab928SRafael Espindola                        [this](Constant *E) {
13736e8ab928SRafael Espindola                          auto *Key = dyn_cast<GlobalValue>(
13746e8ab928SRafael Espindola                              E->getAggregateElement(2)->stripPointerCasts());
13756e8ab928SRafael Espindola                          return DoNotLinkFromSource.count(Key);
13766e8ab928SRafael Espindola                        }),
13776e8ab928SRafael Espindola         SrcElements.end());
13786e8ab928SRafael Espindola   uint64_t NewSize = DstElements.size() + SrcElements.size();
1379b1ed91f3SChris Lattner   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
1380b1ed91f3SChris Lattner 
1381b1ed91f3SChris Lattner   // Create the new global variable.
1382c945c8d2SRafael Espindola   GlobalVariable *NG = new GlobalVariable(
13830e309fe8SRafael Espindola       DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
1384c945c8d2SRafael Espindola       /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
1385c945c8d2SRafael Espindola       SrcGV->getType()->getAddressSpace());
1386b1ed91f3SChris Lattner 
1387b1ed91f3SChris Lattner   // Propagate alignment, visibility and section info.
1388c945c8d2SRafael Espindola   copyGVAttributes(NG, SrcGV);
1389b1ed91f3SChris Lattner 
1390b1ed91f3SChris Lattner   // Replace any uses of the two global variables with uses of the new
1391b1ed91f3SChris Lattner   // global.
1392b1ed91f3SChris Lattner   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
1393b1ed91f3SChris Lattner 
13946e8ab928SRafael Espindola   for (auto *V : SrcElements) {
13956e8ab928SRafael Espindola     DstElements.push_back(
13966e8ab928SRafael Espindola         MapValue(V, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
13976e8ab928SRafael Espindola   }
13986e8ab928SRafael Espindola 
13996e8ab928SRafael Espindola   NG->setInitializer(ConstantArray::get(NewType, DstElements));
14006e8ab928SRafael Espindola 
1401c945c8d2SRafael Espindola   if (DstGV) {
1402b1ed91f3SChris Lattner     DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
1403b1ed91f3SChris Lattner     DstGV->eraseFromParent();
1404c945c8d2SRafael Espindola   }
1405b1ed91f3SChris Lattner 
1406b1ed91f3SChris Lattner   return false;
1407b1ed91f3SChris Lattner }
1408b1ed91f3SChris Lattner 
1409778fcc77SRafael Espindola bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
1410b1ed91f3SChris Lattner   GlobalValue *DGV = getLinkedToGlobal(SGV);
1411b1ed91f3SChris Lattner 
1412778fcc77SRafael Espindola   // Handle the ultra special appending linkage case first.
1413c7ed52f2STeresa Johnson   assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
1414c7ed52f2STeresa Johnson   if (SGV->hasAppendingLinkage() && isPerformingImport()) {
1415c7ed52f2STeresa Johnson     // Don't want to append to global_ctors list, for example, when we
1416c7ed52f2STeresa Johnson     // are importing for ThinLTO, otherwise the global ctors and dtors
1417c7ed52f2STeresa Johnson     // get executed multiple times for local variables (the latter causing
1418c7ed52f2STeresa Johnson     // double frees).
1419c7ed52f2STeresa Johnson     DoNotLinkFromSource.insert(SGV);
1420c7ed52f2STeresa Johnson     return false;
1421c7ed52f2STeresa Johnson   }
1422c945c8d2SRafael Espindola   if (SGV->hasAppendingLinkage())
1423c945c8d2SRafael Espindola     return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
1424778fcc77SRafael Espindola                                  cast<GlobalVariable>(SGV));
1425778fcc77SRafael Espindola 
1426778fcc77SRafael Espindola   bool LinkFromSrc = true;
1427778fcc77SRafael Espindola   Comdat *C = nullptr;
1428778fcc77SRafael Espindola   bool HasUnnamedAddr = SGV->hasUnnamedAddr();
1429778fcc77SRafael Espindola 
1430dad0a645SDavid Majnemer   if (const Comdat *SC = SGV->getComdat()) {
1431dad0a645SDavid Majnemer     Comdat::SelectionKind SK;
1432dad0a645SDavid Majnemer     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
14330e309fe8SRafael Espindola     C = DstM.getOrInsertComdat(SC->getName());
1434778fcc77SRafael Espindola     C->setSelectionKind(SK);
1435baa3bf8fSRafael Espindola     if (SGV->hasInternalLinkage())
1436baa3bf8fSRafael Espindola       LinkFromSrc = true;
1437778fcc77SRafael Espindola   } else if (DGV) {
1438778fcc77SRafael Espindola     if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1439fc61de39SChris Lattner       return true;
1440dad0a645SDavid Majnemer   }
144134fc5a0eSChris Lattner 
1442dad0a645SDavid Majnemer   if (!LinkFromSrc) {
1443cbb91408STanya Lattner     // Track the source global so that we don't attempt to copy it over when
1444cbb91408STanya Lattner     // processing global initializers.
1445cbb91408STanya Lattner     DoNotLinkFromSource.insert(SGV);
1446cbb91408STanya Lattner 
1447778fcc77SRafael Espindola     if (DGV)
1448778fcc77SRafael Espindola       // Make sure to remember this mapping.
1449778fcc77SRafael Espindola       ValueMap[SGV] =
1450778fcc77SRafael Espindola           ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
1451778fcc77SRafael Espindola   }
1452778fcc77SRafael Espindola 
1453c7ed52f2STeresa Johnson   if (DGV)
1454778fcc77SRafael Espindola     HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1455778fcc77SRafael Espindola 
1456778fcc77SRafael Espindola   GlobalValue *NewGV;
1457baa3bf8fSRafael Espindola   if (!LinkFromSrc && DGV) {
145826c29511SRafael Espindola     NewGV = DGV;
1459c7ed52f2STeresa Johnson     // When linking from source we setVisibility from copyGlobalValueProto.
1460c7ed52f2STeresa Johnson     setVisibility(NewGV, SGV, DGV);
146126c29511SRafael Espindola   } else {
1462c7ed52f2STeresa Johnson     NewGV = copyGlobalValueProto(TypeMap, SGV, DGV);
14633cd8161cSTeresa Johnson 
14643cd8161cSTeresa Johnson     if (isPerformingImport() && !doImportAsDefinition(SGV))
14653cd8161cSTeresa Johnson       DoNotLinkFromSource.insert(SGV);
1466ef23711eSRafael Espindola   }
1467778fcc77SRafael Espindola 
1468778fcc77SRafael Espindola   NewGV->setUnnamedAddr(HasUnnamedAddr);
1469778fcc77SRafael Espindola 
1470778fcc77SRafael Espindola   if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1471baa3bf8fSRafael Espindola     if (C && LinkFromSrc)
1472778fcc77SRafael Espindola       NewGO->setComdat(C);
1473439835a6SRafael Espindola 
1474439835a6SRafael Espindola     if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1475439835a6SRafael Espindola       NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
1476778fcc77SRafael Espindola   }
1477778fcc77SRafael Espindola 
1478879aeb77SRafael Espindola   if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) {
1479879aeb77SRafael Espindola     auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV);
1480879aeb77SRafael Espindola     auto *SGVar = dyn_cast<GlobalVariable>(SGV);
1481879aeb77SRafael Espindola     if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() &&
1482879aeb77SRafael Espindola         (!DGVar->isConstant() || !SGVar->isConstant()))
1483879aeb77SRafael Espindola       NewGVar->setConstant(false);
1484879aeb77SRafael Espindola   }
1485879aeb77SRafael Espindola 
1486778fcc77SRafael Espindola   // Make sure to remember this mapping.
1487778fcc77SRafael Espindola   if (NewGV != DGV) {
1488778fcc77SRafael Espindola     if (DGV) {
1489ad9d0ca8SRafael Espindola       DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
1490778fcc77SRafael Espindola       DGV->eraseFromParent();
1491778fcc77SRafael Espindola     }
1492778fcc77SRafael Espindola     ValueMap[SGV] = NewGV;
1493dad0a645SDavid Majnemer   }
14944e27567aSRafael Espindola 
1495fd38af2dSChandler Carruth   return false;
14964e27567aSRafael Espindola }
14974e27567aSRafael Espindola 
149818c89411SRafael Espindola /// Update the initializers in the Dest module now that all globals that may be
149918c89411SRafael Espindola /// referenced are in Dest.
1500ef23711eSRafael Espindola void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
1501b1ed91f3SChris Lattner   // Figure out what the initializer looks like in the dest module.
15024fb46cb8SDuncan P. N. Exon Smith   Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap,
15034fb46cb8SDuncan P. N. Exon Smith                               RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1504b1ed91f3SChris Lattner }
1505b1ed91f3SChris Lattner 
150618c89411SRafael Espindola /// Copy the source function over into the dest function and fix up references
150718c89411SRafael Espindola /// to values. At this point we know that Dest is an external function, and
150818c89411SRafael Espindola /// that Src is not.
1509ef23711eSRafael Espindola bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) {
1510ef23711eSRafael Espindola   assert(Dst.isDeclaration() && !Src.isDeclaration());
1511361e513dSReid Spencer 
151240d7ebedSRafael Espindola   // Materialize if needed.
15133519da82SRafael Espindola   if (std::error_code EC = Src.materialize())
151440d7ebedSRafael Espindola     return emitError(EC.message());
151540d7ebedSRafael Espindola 
1516869d1ce8SRafael Espindola   // Link in the prefix data.
15173519da82SRafael Espindola   if (Src.hasPrefixData())
15184fb46cb8SDuncan P. N. Exon Smith     Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap,
15194fb46cb8SDuncan P. N. Exon Smith                                RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1520869d1ce8SRafael Espindola 
1521869d1ce8SRafael Espindola   // Link in the prologue data.
15223519da82SRafael Espindola   if (Src.hasPrologueData())
15234fb46cb8SDuncan P. N. Exon Smith     Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap,
15244fb46cb8SDuncan P. N. Exon Smith                                  RF_MoveDistinctMDs, &TypeMap,
15254fb46cb8SDuncan P. N. Exon Smith                                  &ValMaterializer));
1526869d1ce8SRafael Espindola 
15277fddeccbSDavid Majnemer   // Link in the personality function.
15287fddeccbSDavid Majnemer   if (Src.hasPersonalityFn())
15294fb46cb8SDuncan P. N. Exon Smith     Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap,
15304fb46cb8SDuncan P. N. Exon Smith                                   RF_MoveDistinctMDs, &TypeMap,
15314fb46cb8SDuncan P. N. Exon Smith                                   &ValMaterializer));
15327fddeccbSDavid Majnemer 
15337391dde1SChris Lattner   // Go through and convert function arguments over, remembering the mapping.
1534ef23711eSRafael Espindola   Function::arg_iterator DI = Dst.arg_begin();
15353519da82SRafael Espindola   for (Argument &Arg : Src.args()) {
1536a314d1acSRafael Espindola     DI->setName(Arg.getName()); // Copy the name over.
1537361e513dSReid Spencer 
1538b1ed91f3SChris Lattner     // Add a mapping to our mapping.
15399934b26bSDuncan P. N. Exon Smith     ValueMap[&Arg] = &*DI;
1540a314d1acSRafael Espindola     ++DI;
1541361e513dSReid Spencer   }
1542361e513dSReid Spencer 
1543c8d987b1SDuncan P. N. Exon Smith   // Copy over the metadata attachments.
1544c8d987b1SDuncan P. N. Exon Smith   SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1545c8d987b1SDuncan P. N. Exon Smith   Src.getAllMetadata(MDs);
1546c8d987b1SDuncan P. N. Exon Smith   for (const auto &I : MDs)
15474fb46cb8SDuncan P. N. Exon Smith     Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, RF_MoveDistinctMDs,
15484fb46cb8SDuncan P. N. Exon Smith                                          &TypeMap, &ValMaterializer));
1549c8d987b1SDuncan P. N. Exon Smith 
15502f0557d0SChris Lattner   // Splice the body of the source function into the dest function.
1551ef23711eSRafael Espindola   Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
1552361e513dSReid Spencer 
1553361e513dSReid Spencer   // At this point, all of the instructions and values of the function are now
1554361e513dSReid Spencer   // copied over.  The only problem is that they are still referencing values in
1555361e513dSReid Spencer   // the Source function as operands.  Loop through all of the operands of the
155643f8d164SChris Lattner   // functions and patch them up to point to the local versions.
1557ef23711eSRafael Espindola   for (BasicBlock &BB : Dst)
1558a314d1acSRafael Espindola     for (Instruction &I : BB)
15594fb46cb8SDuncan P. N. Exon Smith       RemapInstruction(&I, ValueMap,
15604fb46cb8SDuncan P. N. Exon Smith                        RF_IgnoreMissingEntries | RF_MoveDistinctMDs, &TypeMap,
15619f8eff31SRafael Espindola                        &ValMaterializer);
1562cbb91408STanya Lattner 
15637391dde1SChris Lattner   // There is no need to map the arguments anymore.
15643519da82SRafael Espindola   for (Argument &Arg : Src.args())
1565a314d1acSRafael Espindola     ValueMap.erase(&Arg);
1566cbb91408STanya Lattner 
156797cb5657SEric Christopher   Src.dematerialize();
156840d7ebedSRafael Espindola   return false;
1569361e513dSReid Spencer }
1570361e513dSReid Spencer 
1571ef23711eSRafael Espindola void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1572ef23711eSRafael Espindola   Constant *Aliasee = Src.getAliasee();
15734fb46cb8SDuncan P. N. Exon Smith   Constant *Val = MapValue(Aliasee, ValueMap, RF_MoveDistinctMDs, &TypeMap,
15744fb46cb8SDuncan P. N. Exon Smith                            &ValMaterializer);
1575ef23711eSRafael Espindola   Dst.setAliasee(Val);
15762c4a34aeSDavid Chisnall }
1577ef23711eSRafael Espindola 
1578ef23711eSRafael Espindola bool ModuleLinker::linkGlobalValueBody(GlobalValue &Src) {
1579ef23711eSRafael Espindola   Value *Dst = ValueMap[&Src];
1580ef23711eSRafael Espindola   assert(Dst);
15812d5fb8caSTeresa Johnson   if (const Comdat *SC = Src.getComdat()) {
15822d5fb8caSTeresa Johnson     // To ensure that we don't generate an incomplete comdat group,
15832d5fb8caSTeresa Johnson     // we must materialize and map in any other members that are not
15842d5fb8caSTeresa Johnson     // yet materialized in Dst, which also ensures their definitions
15852d5fb8caSTeresa Johnson     // are linked in. Otherwise, linkonce and other lazy linked GVs will
15862d5fb8caSTeresa Johnson     // not be materialized if they aren't referenced.
15872d5fb8caSTeresa Johnson     for (auto *SGV : ComdatMembers[SC]) {
158819b52383SRafael Espindola       auto *DGV = cast_or_null<GlobalValue>(ValueMap[SGV]);
158919b52383SRafael Espindola       if (DGV && !DGV->isDeclaration())
15902d5fb8caSTeresa Johnson         continue;
159119b52383SRafael Espindola       MapValue(SGV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
15922d5fb8caSTeresa Johnson     }
15932d5fb8caSTeresa Johnson   }
1594020d4fb1SArtem Belevich   if (shouldInternalizeLinkedSymbols())
1595020d4fb1SArtem Belevich     if (auto *DGV = dyn_cast<GlobalValue>(Dst))
1596020d4fb1SArtem Belevich       DGV->setLinkage(GlobalValue::InternalLinkage);
1597ef23711eSRafael Espindola   if (auto *F = dyn_cast<Function>(&Src))
1598ef23711eSRafael Espindola     return linkFunctionBody(cast<Function>(*Dst), *F);
1599ef23711eSRafael Espindola   if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1600ef23711eSRafael Espindola     linkGlobalInit(cast<GlobalVariable>(*Dst), *GVar);
1601ef23711eSRafael Espindola     return false;
1602b1ed91f3SChris Lattner   }
1603ef23711eSRafael Espindola   linkAliasBody(cast<GlobalAlias>(*Dst), cast<GlobalAlias>(Src));
1604ef23711eSRafael Espindola   return false;
1605cbb91408STanya Lattner }
1606b1ed91f3SChris Lattner 
160718c89411SRafael Espindola /// Insert all of the named MDNodes in Src into the Dest module.
1608b1ed91f3SChris Lattner void ModuleLinker::linkNamedMDNodes() {
16090e309fe8SRafael Espindola   const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
16100e309fe8SRafael Espindola   for (const NamedMDNode &NMD : SrcM.named_metadata()) {
161166f02413SBill Wendling     // Don't link module flags here. Do them separately.
16123bf3f1f5SYaron Keren     if (&NMD == SrcModFlags)
16133bf3f1f5SYaron Keren       continue;
16140e309fe8SRafael Espindola     NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1615b1ed91f3SChris Lattner     // Add Src elements into Dest node.
16163bf3f1f5SYaron Keren     for (const MDNode *op : NMD.operands())
161783d03ddbSTeresa Johnson       DestNMD->addOperand(MapMetadata(
161883d03ddbSTeresa Johnson           op, ValueMap, RF_MoveDistinctMDs | RF_NullMapMissingGlobalValues,
16194fb46cb8SDuncan P. N. Exon Smith           &TypeMap, &ValMaterializer));
1620b1ed91f3SChris Lattner   }
1621b1ed91f3SChris Lattner }
1622b1ed91f3SChris Lattner 
162318c89411SRafael Espindola /// Merge the linker flags in Src into the Dest module.
162466f02413SBill Wendling bool ModuleLinker::linkModuleFlagsMetadata() {
16250ec72bbcSDaniel Dunbar   // If the source module has no module flags, we are done.
16260e309fe8SRafael Espindola   const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1627*e3a933afSRafael Espindola   if (!SrcModFlags)
1628*e3a933afSRafael Espindola     return false;
162966f02413SBill Wendling 
163066f02413SBill Wendling   // If the destination module doesn't have module flags yet, then just copy
163166f02413SBill Wendling   // over the source module's flags.
16320e309fe8SRafael Espindola   NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
163366f02413SBill Wendling   if (DstModFlags->getNumOperands() == 0) {
163466f02413SBill Wendling     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
163566f02413SBill Wendling       DstModFlags->addOperand(SrcModFlags->getOperand(I));
163666f02413SBill Wendling 
163766f02413SBill Wendling     return false;
163866f02413SBill Wendling   }
163966f02413SBill Wendling 
16400ec72bbcSDaniel Dunbar   // First build a map of the existing module flags and requirements.
1641df55d8baSDuncan P. N. Exon Smith   DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
16420ec72bbcSDaniel Dunbar   SmallSetVector<MDNode *, 16> Requirements;
16430ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1644de36e804SDuncan P. N. Exon Smith     MDNode *Op = DstModFlags->getOperand(I);
16455bf8fef5SDuncan P. N. Exon Smith     ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
16460ec72bbcSDaniel Dunbar     MDString *ID = cast<MDString>(Op->getOperand(1));
16470ec72bbcSDaniel Dunbar 
16480ec72bbcSDaniel Dunbar     if (Behavior->getZExtValue() == Module::Require) {
16490ec72bbcSDaniel Dunbar       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
16500ec72bbcSDaniel Dunbar     } else {
1651df55d8baSDuncan P. N. Exon Smith       Flags[ID] = std::make_pair(Op, I);
16520ec72bbcSDaniel Dunbar     }
16530ec72bbcSDaniel Dunbar   }
16540ec72bbcSDaniel Dunbar 
16550ec72bbcSDaniel Dunbar   // Merge in the flags from the source module, and also collect its set of
16560ec72bbcSDaniel Dunbar   // requirements.
165766f02413SBill Wendling   bool HasErr = false;
16580ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1659de36e804SDuncan P. N. Exon Smith     MDNode *SrcOp = SrcModFlags->getOperand(I);
16605bf8fef5SDuncan P. N. Exon Smith     ConstantInt *SrcBehavior =
16615bf8fef5SDuncan P. N. Exon Smith         mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
16620ec72bbcSDaniel Dunbar     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1663df55d8baSDuncan P. N. Exon Smith     MDNode *DstOp;
1664df55d8baSDuncan P. N. Exon Smith     unsigned DstIndex;
1665df55d8baSDuncan P. N. Exon Smith     std::tie(DstOp, DstIndex) = Flags.lookup(ID);
16660ec72bbcSDaniel Dunbar     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
166766f02413SBill Wendling 
16680ec72bbcSDaniel Dunbar     // If this is a requirement, add it and continue.
16690ec72bbcSDaniel Dunbar     if (SrcBehaviorValue == Module::Require) {
16700ec72bbcSDaniel Dunbar       // If the destination module does not already have this requirement, add
16710ec72bbcSDaniel Dunbar       // it.
16720ec72bbcSDaniel Dunbar       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
16730ec72bbcSDaniel Dunbar         DstModFlags->addOperand(SrcOp);
16740ec72bbcSDaniel Dunbar       }
16750ec72bbcSDaniel Dunbar       continue;
16760ec72bbcSDaniel Dunbar     }
167766f02413SBill Wendling 
16780ec72bbcSDaniel Dunbar     // If there is no existing flag with this ID, just add it.
16790ec72bbcSDaniel Dunbar     if (!DstOp) {
1680df55d8baSDuncan P. N. Exon Smith       Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
16810ec72bbcSDaniel Dunbar       DstModFlags->addOperand(SrcOp);
16820ec72bbcSDaniel Dunbar       continue;
16830ec72bbcSDaniel Dunbar     }
168466f02413SBill Wendling 
16850ec72bbcSDaniel Dunbar     // Otherwise, perform a merge.
16865bf8fef5SDuncan P. N. Exon Smith     ConstantInt *DstBehavior =
16875bf8fef5SDuncan P. N. Exon Smith         mdconst::extract<ConstantInt>(DstOp->getOperand(0));
16880ec72bbcSDaniel Dunbar     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
16890ec72bbcSDaniel Dunbar 
16900ec72bbcSDaniel Dunbar     // If either flag has override behavior, handle it first.
16910ec72bbcSDaniel Dunbar     if (DstBehaviorValue == Module::Override) {
16920ec72bbcSDaniel Dunbar       // Diagnose inconsistent flags which both have override behavior.
16930ec72bbcSDaniel Dunbar       if (SrcBehaviorValue == Module::Override &&
16940ec72bbcSDaniel Dunbar           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
16950ec72bbcSDaniel Dunbar         HasErr |= emitError("linking module flags '" + ID->getString() +
16960ec72bbcSDaniel Dunbar                             "': IDs have conflicting override values");
16970ec72bbcSDaniel Dunbar       }
16980ec72bbcSDaniel Dunbar       continue;
16990ec72bbcSDaniel Dunbar     } else if (SrcBehaviorValue == Module::Override) {
17000ec72bbcSDaniel Dunbar       // Update the destination flag to that of the source.
1701df55d8baSDuncan P. N. Exon Smith       DstModFlags->setOperand(DstIndex, SrcOp);
1702df55d8baSDuncan P. N. Exon Smith       Flags[ID].first = SrcOp;
17030ec72bbcSDaniel Dunbar       continue;
17040ec72bbcSDaniel Dunbar     }
17050ec72bbcSDaniel Dunbar 
17060ec72bbcSDaniel Dunbar     // Diagnose inconsistent merge behavior types.
17070ec72bbcSDaniel Dunbar     if (SrcBehaviorValue != DstBehaviorValue) {
17080ec72bbcSDaniel Dunbar       HasErr |= emitError("linking module flags '" + ID->getString() +
170966f02413SBill Wendling                           "': IDs have conflicting behaviors");
17100ec72bbcSDaniel Dunbar       continue;
171166f02413SBill Wendling     }
171266f02413SBill Wendling 
1713df55d8baSDuncan P. N. Exon Smith     auto replaceDstValue = [&](MDNode *New) {
1714df55d8baSDuncan P. N. Exon Smith       Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
17150e309fe8SRafael Espindola       MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1716df55d8baSDuncan P. N. Exon Smith       DstModFlags->setOperand(DstIndex, Flag);
1717df55d8baSDuncan P. N. Exon Smith       Flags[ID].first = Flag;
1718df55d8baSDuncan P. N. Exon Smith     };
1719df55d8baSDuncan P. N. Exon Smith 
17200ec72bbcSDaniel Dunbar     // Perform the merge for standard behavior types.
17210ec72bbcSDaniel Dunbar     switch (SrcBehaviorValue) {
17220ec72bbcSDaniel Dunbar     case Module::Require:
1723*e3a933afSRafael Espindola     case Module::Override:
1724*e3a933afSRafael Espindola       llvm_unreachable("not possible");
17250ec72bbcSDaniel Dunbar     case Module::Error: {
17260ec72bbcSDaniel Dunbar       // Emit an error if the values differ.
17270ec72bbcSDaniel Dunbar       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
17280ec72bbcSDaniel Dunbar         HasErr |= emitError("linking module flags '" + ID->getString() +
17290ec72bbcSDaniel Dunbar                             "': IDs have conflicting values");
173066f02413SBill Wendling       }
17310ec72bbcSDaniel Dunbar       continue;
173266f02413SBill Wendling     }
17330ec72bbcSDaniel Dunbar     case Module::Warning: {
17340ec72bbcSDaniel Dunbar       // Emit a warning if the values differ.
17350ec72bbcSDaniel Dunbar       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1736d12b4a33SRafael Espindola         emitWarning("linking module flags '" + ID->getString() +
1737d12b4a33SRafael Espindola                     "': IDs have conflicting values");
1738e17f3708SEli Bendersky       }
17390ec72bbcSDaniel Dunbar       continue;
17400ec72bbcSDaniel Dunbar     }
1741d77d9fb0SDaniel Dunbar     case Module::Append: {
1742d77d9fb0SDaniel Dunbar       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1743d77d9fb0SDaniel Dunbar       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
17445bf8fef5SDuncan P. N. Exon Smith       SmallVector<Metadata *, 8> MDs;
17455bf8fef5SDuncan P. N. Exon Smith       MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
17466cd780ffSBenjamin Kramer       MDs.append(DstValue->op_begin(), DstValue->op_end());
17476cd780ffSBenjamin Kramer       MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1748df55d8baSDuncan P. N. Exon Smith 
17490e309fe8SRafael Espindola       replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1750d77d9fb0SDaniel Dunbar       break;
1751d77d9fb0SDaniel Dunbar     }
1752d77d9fb0SDaniel Dunbar     case Module::AppendUnique: {
17535bf8fef5SDuncan P. N. Exon Smith       SmallSetVector<Metadata *, 16> Elts;
1754d77d9fb0SDaniel Dunbar       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1755d77d9fb0SDaniel Dunbar       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
17566cd780ffSBenjamin Kramer       Elts.insert(DstValue->op_begin(), DstValue->op_end());
17576cd780ffSBenjamin Kramer       Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1758df55d8baSDuncan P. N. Exon Smith 
17590e309fe8SRafael Espindola       replaceDstValue(MDNode::get(DstM.getContext(),
17605bf8fef5SDuncan P. N. Exon Smith                                   makeArrayRef(Elts.begin(), Elts.end())));
1761d77d9fb0SDaniel Dunbar       break;
1762d77d9fb0SDaniel Dunbar     }
176366f02413SBill Wendling     }
176466f02413SBill Wendling   }
176566f02413SBill Wendling 
17660ec72bbcSDaniel Dunbar   // Check all of the requirements.
17670ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
17680ec72bbcSDaniel Dunbar     MDNode *Requirement = Requirements[I];
17690ec72bbcSDaniel Dunbar     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
17705bf8fef5SDuncan P. N. Exon Smith     Metadata *ReqValue = Requirement->getOperand(1);
17710ec72bbcSDaniel Dunbar 
1772df55d8baSDuncan P. N. Exon Smith     MDNode *Op = Flags[Flag].first;
17730ec72bbcSDaniel Dunbar     if (!Op || Op->getOperand(2) != ReqValue) {
17740ec72bbcSDaniel Dunbar       HasErr |= emitError("linking module flags '" + Flag->getString() +
17759273b539SBill Wendling                           "': does not have the required value");
17760ec72bbcSDaniel Dunbar       continue;
177766f02413SBill Wendling     }
177866f02413SBill Wendling   }
177966f02413SBill Wendling 
178066f02413SBill Wendling   return HasErr;
178166f02413SBill Wendling }
178266f02413SBill Wendling 
1783c43df518SAkira Hatanaka // This function returns true if the triples match.
1784c43df518SAkira Hatanaka static bool triplesMatch(const Triple &T0, const Triple &T1) {
1785c43df518SAkira Hatanaka   // If vendor is apple, ignore the version number.
1786c43df518SAkira Hatanaka   if (T0.getVendor() == Triple::Apple)
1787*e3a933afSRafael Espindola     return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1788*e3a933afSRafael Espindola            T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1789c43df518SAkira Hatanaka 
1790c43df518SAkira Hatanaka   return T0 == T1;
1791c43df518SAkira Hatanaka }
1792c43df518SAkira Hatanaka 
1793c43df518SAkira Hatanaka // This function returns the merged triple.
1794*e3a933afSRafael Espindola static std::string mergeTriples(const Triple &SrcTriple,
1795*e3a933afSRafael Espindola                                 const Triple &DstTriple) {
1796c43df518SAkira Hatanaka   // If vendor is apple, pick the triple with the larger version number.
1797c43df518SAkira Hatanaka   if (SrcTriple.getVendor() == Triple::Apple)
1798c43df518SAkira Hatanaka     if (DstTriple.isOSVersionLT(SrcTriple))
1799c43df518SAkira Hatanaka       return SrcTriple.str();
1800c43df518SAkira Hatanaka 
1801c43df518SAkira Hatanaka   return DstTriple.str();
1802c43df518SAkira Hatanaka }
1803c43df518SAkira Hatanaka 
1804baa3bf8fSRafael Espindola bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
1805baa3bf8fSRafael Espindola   GlobalValue *DGV = getLinkedToGlobal(&GV);
1806baa3bf8fSRafael Espindola 
1807baa3bf8fSRafael Espindola   if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
1808baa3bf8fSRafael Espindola     return false;
1809baa3bf8fSRafael Espindola 
1810baa3bf8fSRafael Espindola   if (DGV && !GV.hasLocalLinkage()) {
1811baa3bf8fSRafael Espindola     GlobalValue::VisibilityTypes Visibility =
1812baa3bf8fSRafael Espindola         getMinVisibility(DGV->getVisibility(), GV.getVisibility());
1813baa3bf8fSRafael Espindola     DGV->setVisibility(Visibility);
1814baa3bf8fSRafael Espindola     GV.setVisibility(Visibility);
1815baa3bf8fSRafael Espindola   }
1816baa3bf8fSRafael Espindola 
1817baa3bf8fSRafael Espindola   if (const Comdat *SC = GV.getComdat()) {
1818baa3bf8fSRafael Espindola     bool LinkFromSrc;
1819baa3bf8fSRafael Espindola     Comdat::SelectionKind SK;
1820baa3bf8fSRafael Espindola     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1821baa3bf8fSRafael Espindola     if (!LinkFromSrc) {
1822baa3bf8fSRafael Espindola       DoNotLinkFromSource.insert(&GV);
1823baa3bf8fSRafael Espindola       return false;
1824baa3bf8fSRafael Espindola     }
1825baa3bf8fSRafael Espindola   }
1826baa3bf8fSRafael Espindola 
1827baa3bf8fSRafael Espindola   if (!DGV && !shouldOverrideFromSrc() &&
1828baa3bf8fSRafael Espindola       (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
1829baa3bf8fSRafael Espindola        GV.hasAvailableExternallyLinkage())) {
1830baa3bf8fSRafael Espindola     return false;
1831baa3bf8fSRafael Espindola   }
1832baa3bf8fSRafael Espindola   MapValue(&GV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1833baa3bf8fSRafael Espindola   return HasError;
1834baa3bf8fSRafael Espindola }
1835baa3bf8fSRafael Espindola 
1836b1ed91f3SChris Lattner bool ModuleLinker::run() {
1837b1ed91f3SChris Lattner   // Inherit the target data from the source module if the destination module
1838b1ed91f3SChris Lattner   // doesn't have one already.
18390e309fe8SRafael Espindola   if (DstM.getDataLayout().isDefault())
18400e309fe8SRafael Espindola     DstM.setDataLayout(SrcM.getDataLayout());
1841b1ed91f3SChris Lattner 
18420e309fe8SRafael Espindola   if (SrcM.getDataLayout() != DstM.getDataLayout()) {
1843d12b4a33SRafael Espindola     emitWarning("Linking two modules of different data layouts: '" +
18440e309fe8SRafael Espindola                 SrcM.getModuleIdentifier() + "' is '" +
18450e309fe8SRafael Espindola                 SrcM.getDataLayoutStr() + "' whereas '" +
18460e309fe8SRafael Espindola                 DstM.getModuleIdentifier() + "' is '" +
18470e309fe8SRafael Espindola                 DstM.getDataLayoutStr() + "'\n");
1848e17f3708SEli Bendersky   }
1849c43df518SAkira Hatanaka 
1850c43df518SAkira Hatanaka   // Copy the target triple from the source to dest if the dest's is empty.
18510e309fe8SRafael Espindola   if (DstM.getTargetTriple().empty() && !SrcM.getTargetTriple().empty())
18520e309fe8SRafael Espindola     DstM.setTargetTriple(SrcM.getTargetTriple());
1853c43df518SAkira Hatanaka 
18540e309fe8SRafael Espindola   Triple SrcTriple(SrcM.getTargetTriple()), DstTriple(DstM.getTargetTriple());
1855c43df518SAkira Hatanaka 
18560e309fe8SRafael Espindola   if (!SrcM.getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
1857d12b4a33SRafael Espindola     emitWarning("Linking two modules of different target triples: " +
18580e309fe8SRafael Espindola                 SrcM.getModuleIdentifier() + "' is '" + SrcM.getTargetTriple() +
18590e309fe8SRafael Espindola                 "' whereas '" + DstM.getModuleIdentifier() + "' is '" +
18600e309fe8SRafael Espindola                 DstM.getTargetTriple() + "'\n");
1861c43df518SAkira Hatanaka 
18620e309fe8SRafael Espindola   DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1863b1ed91f3SChris Lattner 
1864b1ed91f3SChris Lattner   // Append the module inline asm string.
18650e309fe8SRafael Espindola   if (!SrcM.getModuleInlineAsm().empty()) {
18660e309fe8SRafael Espindola     if (DstM.getModuleInlineAsm().empty())
18670e309fe8SRafael Espindola       DstM.setModuleInlineAsm(SrcM.getModuleInlineAsm());
1868b1ed91f3SChris Lattner     else
18690e309fe8SRafael Espindola       DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
18700e309fe8SRafael Espindola                               SrcM.getModuleInlineAsm());
1871b1ed91f3SChris Lattner   }
1872b1ed91f3SChris Lattner 
1873b1ed91f3SChris Lattner   // Loop over all of the linked values to compute type mappings.
1874b1ed91f3SChris Lattner   computeTypeMapping();
1875b1ed91f3SChris Lattner 
1876dad0a645SDavid Majnemer   ComdatsChosen.clear();
18770e309fe8SRafael Espindola   for (const auto &SMEC : SrcM.getComdatSymbolTable()) {
1878dad0a645SDavid Majnemer     const Comdat &C = SMEC.getValue();
1879dad0a645SDavid Majnemer     if (ComdatsChosen.count(&C))
1880dad0a645SDavid Majnemer       continue;
1881dad0a645SDavid Majnemer     Comdat::SelectionKind SK;
1882dad0a645SDavid Majnemer     bool LinkFromSrc;
1883dad0a645SDavid Majnemer     if (getComdatResult(&C, SK, LinkFromSrc))
1884dad0a645SDavid Majnemer       return true;
1885dad0a645SDavid Majnemer     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1886dad0a645SDavid Majnemer   }
1887dad0a645SDavid Majnemer 
188809d84addSDuncan P. N. Exon Smith   // Upgrade mismatched global arrays.
188909d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobals();
189009d84addSDuncan P. N. Exon Smith 
18910e309fe8SRafael Espindola   for (GlobalVariable &GV : SrcM.globals())
1892baa3bf8fSRafael Espindola     if (const Comdat *SC = GV.getComdat())
1893baa3bf8fSRafael Espindola       ComdatMembers[SC].push_back(&GV);
1894baa3bf8fSRafael Espindola 
18950e309fe8SRafael Espindola   for (Function &SF : SrcM)
1896baa3bf8fSRafael Espindola     if (const Comdat *SC = SF.getComdat())
1897baa3bf8fSRafael Espindola       ComdatMembers[SC].push_back(&SF);
1898baa3bf8fSRafael Espindola 
18990e309fe8SRafael Espindola   for (GlobalAlias &GA : SrcM.aliases())
1900baa3bf8fSRafael Espindola     if (const Comdat *SC = GA.getComdat())
1901baa3bf8fSRafael Espindola       ComdatMembers[SC].push_back(&GA);
1902baa3bf8fSRafael Espindola 
1903b1ed91f3SChris Lattner   // Insert all of the globals in src into the DstM module... without linking
1904b1ed91f3SChris Lattner   // initializers (which could refer to functions not yet mapped over).
19050e309fe8SRafael Espindola   for (GlobalVariable &GV : SrcM.globals())
1906baa3bf8fSRafael Espindola     if (linkIfNeeded(GV))
1907b1ed91f3SChris Lattner       return true;
1908b1ed91f3SChris Lattner 
19090e309fe8SRafael Espindola   for (Function &SF : SrcM)
1910baa3bf8fSRafael Espindola     if (linkIfNeeded(SF))
1911b1ed91f3SChris Lattner       return true;
1912b1ed91f3SChris Lattner 
19130e309fe8SRafael Espindola   for (GlobalAlias &GA : SrcM.aliases())
1914baa3bf8fSRafael Espindola     if (linkIfNeeded(GA))
1915b1ed91f3SChris Lattner       return true;
1916b1ed91f3SChris Lattner 
19170e309fe8SRafael Espindola   for (const auto &Entry : DstM.getComdatSymbolTable()) {
1918beadd56aSRafael Espindola     const Comdat &C = Entry.getValue();
1919beadd56aSRafael Espindola     if (C.getSelectionKind() == Comdat::Any)
1920beadd56aSRafael Espindola       continue;
19210e309fe8SRafael Espindola     const GlobalValue *GV = SrcM.getNamedValue(C.getName());
1922ea45d834SPeter Collingbourne     if (GV)
19234fb46cb8SDuncan P. N. Exon Smith       MapValue(GV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1924beadd56aSRafael Espindola   }
1925beadd56aSRafael Espindola 
19261063293aSTeresa Johnson   // Note that we are done linking global value bodies. This prevents
19271063293aSTeresa Johnson   // metadata linking from creating new references.
19281063293aSTeresa Johnson   DoneLinkingBodies = true;
19291063293aSTeresa Johnson 
1930189b2526STeresa Johnson   // Remap all of the named MDNodes in Src into the DstM module. We do this
1931189b2526STeresa Johnson   // after linking GlobalValues so that MDNodes that reference GlobalValues
1932189b2526STeresa Johnson   // are properly remapped.
1933189b2526STeresa Johnson   linkNamedMDNodes();
1934189b2526STeresa Johnson 
1935189b2526STeresa Johnson   // Merge the module flags into the DstM module.
1936189b2526STeresa Johnson   if (linkModuleFlagsMetadata())
1937189b2526STeresa Johnson     return true;
1938189b2526STeresa Johnson 
19392609888fSAnton Korobeynikov   return false;
19402609888fSAnton Korobeynikov }
1941361e513dSReid Spencer 
194231ad468dSRafael Espindola Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
194331ad468dSRafael Espindola     : ETypes(E), IsPacked(P) {}
194431ad468dSRafael Espindola 
194531ad468dSRafael Espindola Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
194631ad468dSRafael Espindola     : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
194731ad468dSRafael Espindola 
194831ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
194931ad468dSRafael Espindola   if (IsPacked != That.IsPacked)
195031ad468dSRafael Espindola     return false;
195131ad468dSRafael Espindola   if (ETypes != That.ETypes)
195231ad468dSRafael Espindola     return false;
195331ad468dSRafael Espindola   return true;
195431ad468dSRafael Espindola }
195531ad468dSRafael Espindola 
195631ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
195731ad468dSRafael Espindola   return !this->operator==(That);
195831ad468dSRafael Espindola }
195931ad468dSRafael Espindola 
196031ad468dSRafael Espindola StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
196131ad468dSRafael Espindola   return DenseMapInfo<StructType *>::getEmptyKey();
196231ad468dSRafael Espindola }
196331ad468dSRafael Espindola 
196431ad468dSRafael Espindola StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
196531ad468dSRafael Espindola   return DenseMapInfo<StructType *>::getTombstoneKey();
196631ad468dSRafael Espindola }
196731ad468dSRafael Espindola 
196831ad468dSRafael Espindola unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
196931ad468dSRafael Espindola   return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
197031ad468dSRafael Espindola                       Key.IsPacked);
197131ad468dSRafael Espindola }
197231ad468dSRafael Espindola 
197331ad468dSRafael Espindola unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
197431ad468dSRafael Espindola   return getHashValue(KeyTy(ST));
197531ad468dSRafael Espindola }
197631ad468dSRafael Espindola 
197731ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
197831ad468dSRafael Espindola                                         const StructType *RHS) {
197931ad468dSRafael Espindola   if (RHS == getEmptyKey() || RHS == getTombstoneKey())
198031ad468dSRafael Espindola     return false;
198131ad468dSRafael Espindola   return LHS == KeyTy(RHS);
198231ad468dSRafael Espindola }
198331ad468dSRafael Espindola 
198431ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
198531ad468dSRafael Espindola                                         const StructType *RHS) {
198631ad468dSRafael Espindola   if (RHS == getEmptyKey())
198731ad468dSRafael Espindola     return LHS == getEmptyKey();
198831ad468dSRafael Espindola 
198931ad468dSRafael Espindola   if (RHS == getTombstoneKey())
199031ad468dSRafael Espindola     return LHS == getTombstoneKey();
199131ad468dSRafael Espindola 
199231ad468dSRafael Espindola   return KeyTy(LHS) == KeyTy(RHS);
199331ad468dSRafael Espindola }
199431ad468dSRafael Espindola 
199531ad468dSRafael Espindola void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
199631ad468dSRafael Espindola   assert(!Ty->isOpaque());
19973280a5d9SBenjamin Kramer   NonOpaqueStructTypes.insert(Ty);
199831ad468dSRafael Espindola }
199931ad468dSRafael Espindola 
2000a5b9e1cfSRafael Espindola void Linker::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
2001a5b9e1cfSRafael Espindola   assert(!Ty->isOpaque());
2002a5b9e1cfSRafael Espindola   NonOpaqueStructTypes.insert(Ty);
2003a5b9e1cfSRafael Espindola   bool Removed = OpaqueStructTypes.erase(Ty);
2004a5b9e1cfSRafael Espindola   (void)Removed;
2005a5b9e1cfSRafael Espindola   assert(Removed);
2006a5b9e1cfSRafael Espindola }
2007a5b9e1cfSRafael Espindola 
200831ad468dSRafael Espindola void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
200931ad468dSRafael Espindola   assert(Ty->isOpaque());
201031ad468dSRafael Espindola   OpaqueStructTypes.insert(Ty);
201131ad468dSRafael Espindola }
201231ad468dSRafael Espindola 
201331ad468dSRafael Espindola StructType *
201431ad468dSRafael Espindola Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
201531ad468dSRafael Espindola                                                bool IsPacked) {
201631ad468dSRafael Espindola   Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
201731ad468dSRafael Espindola   auto I = NonOpaqueStructTypes.find_as(Key);
201831ad468dSRafael Espindola   if (I == NonOpaqueStructTypes.end())
201931ad468dSRafael Espindola     return nullptr;
20203280a5d9SBenjamin Kramer   return *I;
202131ad468dSRafael Espindola }
202231ad468dSRafael Espindola 
202331ad468dSRafael Espindola bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
202431ad468dSRafael Espindola   if (Ty->isOpaque())
202531ad468dSRafael Espindola     return OpaqueStructTypes.count(Ty);
202631ad468dSRafael Espindola   auto I = NonOpaqueStructTypes.find(Ty);
202731ad468dSRafael Espindola   if (I == NonOpaqueStructTypes.end())
202831ad468dSRafael Espindola     return false;
20293280a5d9SBenjamin Kramer   return *I == Ty;
203031ad468dSRafael Espindola }
203131ad468dSRafael Espindola 
20320e309fe8SRafael Espindola Linker::Linker(Module &M, DiagnosticHandlerFunction DiagnosticHandler)
20330e309fe8SRafael Espindola     : Composite(M), DiagnosticHandler(DiagnosticHandler) {
2034a4e85e3dSRafael Espindola   TypeFinder StructTypes;
20350e309fe8SRafael Espindola   StructTypes.run(M, true);
203631ad468dSRafael Espindola   for (StructType *Ty : StructTypes) {
203731ad468dSRafael Espindola     if (Ty->isOpaque())
203831ad468dSRafael Espindola       IdentifiedStructTypes.addOpaque(Ty);
203931ad468dSRafael Espindola     else
204031ad468dSRafael Espindola       IdentifiedStructTypes.addNonOpaque(Ty);
204131ad468dSRafael Espindola   }
2042aa9918aaSRafael Espindola }
20433df61b7bSRafael Espindola 
20440e309fe8SRafael Espindola Linker::Linker(Module &M)
20454dbdceb6SRafael Espindola     : Linker(M, [this](const DiagnosticInfo &DI) {
20460e309fe8SRafael Espindola         Composite.getContext().diagnose(DI);
20474dbdceb6SRafael Espindola       }) {}
20485cb9c82aSRafael Espindola 
20490e309fe8SRafael Espindola bool Linker::linkInModule(Module &Src, unsigned Flags,
20508220e8a8SMehdi Amini                           const FunctionInfoIndex *Index,
2051c7ed52f2STeresa Johnson                           Function *FuncToImport) {
2052a4e85e3dSRafael Espindola   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
2053c7ed52f2STeresa Johnson                          DiagnosticHandler, Flags, Index, FuncToImport);
2054dab999d5SManman Ren   bool RetCode = TheLinker.run();
20550e309fe8SRafael Espindola   Composite.dropTriviallyDeadConstantArrays();
2056dab999d5SManman Ren   return RetCode;
20573df61b7bSRafael Espindola }
20583df61b7bSRafael Espindola 
2059b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
2060b1ed91f3SChris Lattner // LinkModules entrypoint.
2061b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
2062b1ed91f3SChris Lattner 
206318c89411SRafael Espindola /// This function links two modules together, with the resulting Dest module
206418c89411SRafael Espindola /// modified to be the composite of the two input modules. If an error occurs,
206518c89411SRafael Espindola /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
206618c89411SRafael Espindola /// Upon failure, the Dest module could be in a modified state, and shouldn't be
206718c89411SRafael Espindola /// relied on to be consistent.
20680e309fe8SRafael Espindola bool Linker::linkModules(Module &Dest, Module &Src,
2069020d4fb1SArtem Belevich                          DiagnosticHandlerFunction DiagnosticHandler,
2070020d4fb1SArtem Belevich                          unsigned Flags) {
20714160f5d3SRafael Espindola   Linker L(Dest, DiagnosticHandler);
2072020d4fb1SArtem Belevich   return L.linkInModule(Src, Flags);
20734160f5d3SRafael Espindola }
20744160f5d3SRafael Espindola 
20750e309fe8SRafael Espindola bool Linker::linkModules(Module &Dest, Module &Src, unsigned Flags) {
2076287f18b4SRafael Espindola   Linker L(Dest);
2077020d4fb1SArtem Belevich   return L.linkInModule(Src, Flags);
2078361e513dSReid Spencer }
2079a3aeb980SBill Wendling 
2080a3aeb980SBill Wendling //===----------------------------------------------------------------------===//
2081a3aeb980SBill Wendling // C API.
2082a3aeb980SBill Wendling //===----------------------------------------------------------------------===//
2083a3aeb980SBill Wendling 
2084a3aeb980SBill Wendling LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
2085a57d588cSJuergen Ributzka                          LLVMLinkerMode Unused, char **OutMessages) {
208698ab63ceSRafael Espindola   Module *D = unwrap(Dest);
208798ab63ceSRafael Espindola   std::string Message;
20884160f5d3SRafael Espindola   raw_string_ostream Stream(Message);
20894160f5d3SRafael Espindola   DiagnosticPrinterRawOStream DP(Stream);
20904160f5d3SRafael Espindola 
20910e309fe8SRafael Espindola   LLVMBool Result = Linker::linkModules(
20920e309fe8SRafael Espindola       *D, *unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
209398ab63ceSRafael Espindola 
2094ff715e2dSEli Bendersky   if (OutMessages && Result) {
2095ff715e2dSEli Bendersky     Stream.flush();
209698ab63ceSRafael Espindola     *OutMessages = strdup(Message.c_str());
2097ff715e2dSEli Bendersky   }
2098a3aeb980SBill Wendling   return Result;
2099a3aeb980SBill Wendling }
2100