Pass down the dst GV to linkGlobalValueBody. NFC.
[oota-llvm.git] / lib / Linker / LinkModules.cpp
1 //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the LLVM module linker.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Linker/Linker.h"
15 #include "llvm-c/Linker.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DiagnosticInfo.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/TypeFinder.h"
25 #include "llvm/Transforms/Utils/Cloning.h"
26 using namespace llvm;
27
28 //===----------------------------------------------------------------------===//
29 // TypeMap implementation.
30 //===----------------------------------------------------------------------===//
31
32 namespace {
33 class TypeMapTy : public ValueMapTypeRemapper {
34   /// This is a mapping from a source type to a destination type to use.
35   DenseMap<Type *, Type *> MappedTypes;
36
37   /// When checking to see if two subgraphs are isomorphic, we speculatively
38   /// add types to MappedTypes, but keep track of them here in case we need to
39   /// roll back.
40   SmallVector<Type *, 16> SpeculativeTypes;
41
42   SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
43
44   /// This is a list of non-opaque structs in the source module that are mapped
45   /// to an opaque struct in the destination module.
46   SmallVector<StructType *, 16> SrcDefinitionsToResolve;
47
48   /// This is the set of opaque types in the destination modules who are
49   /// getting a body from the source module.
50   SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
51
52 public:
53   TypeMapTy(Linker::IdentifiedStructTypeSet &DstStructTypesSet)
54       : DstStructTypesSet(DstStructTypesSet) {}
55
56   Linker::IdentifiedStructTypeSet &DstStructTypesSet;
57   /// Indicate that the specified type in the destination module is conceptually
58   /// equivalent to the specified type in the source module.
59   void addTypeMapping(Type *DstTy, Type *SrcTy);
60
61   /// Produce a body for an opaque type in the dest module from a type
62   /// definition in the source module.
63   void linkDefinedTypeBodies();
64
65   /// Return the mapped type to use for the specified input type from the
66   /// source module.
67   Type *get(Type *SrcTy);
68   Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
69
70   void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
71
72   FunctionType *get(FunctionType *T) {
73     return cast<FunctionType>(get((Type *)T));
74   }
75
76   /// Dump out the type map for debugging purposes.
77   void dump() const {
78     for (auto &Pair : MappedTypes) {
79       dbgs() << "TypeMap: ";
80       Pair.first->print(dbgs());
81       dbgs() << " => ";
82       Pair.second->print(dbgs());
83       dbgs() << '\n';
84     }
85   }
86
87 private:
88   Type *remapType(Type *SrcTy) override { return get(SrcTy); }
89
90   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
91 };
92 }
93
94 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
95   assert(SpeculativeTypes.empty());
96   assert(SpeculativeDstOpaqueTypes.empty());
97
98   // Check to see if these types are recursively isomorphic and establish a
99   // mapping between them if so.
100   if (!areTypesIsomorphic(DstTy, SrcTy)) {
101     // Oops, they aren't isomorphic.  Just discard this request by rolling out
102     // any speculative mappings we've established.
103     for (Type *Ty : SpeculativeTypes)
104       MappedTypes.erase(Ty);
105
106     SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
107                                    SpeculativeDstOpaqueTypes.size());
108     for (StructType *Ty : SpeculativeDstOpaqueTypes)
109       DstResolvedOpaqueTypes.erase(Ty);
110   } else {
111     for (Type *Ty : SpeculativeTypes)
112       if (auto *STy = dyn_cast<StructType>(Ty))
113         if (STy->hasName())
114           STy->setName("");
115   }
116   SpeculativeTypes.clear();
117   SpeculativeDstOpaqueTypes.clear();
118 }
119
120 /// Recursively walk this pair of types, returning true if they are isomorphic,
121 /// false if they are not.
122 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
123   // Two types with differing kinds are clearly not isomorphic.
124   if (DstTy->getTypeID() != SrcTy->getTypeID())
125     return false;
126
127   // If we have an entry in the MappedTypes table, then we have our answer.
128   Type *&Entry = MappedTypes[SrcTy];
129   if (Entry)
130     return Entry == DstTy;
131
132   // Two identical types are clearly isomorphic.  Remember this
133   // non-speculatively.
134   if (DstTy == SrcTy) {
135     Entry = DstTy;
136     return true;
137   }
138
139   // Okay, we have two types with identical kinds that we haven't seen before.
140
141   // If this is an opaque struct type, special case it.
142   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
143     // Mapping an opaque type to any struct, just keep the dest struct.
144     if (SSTy->isOpaque()) {
145       Entry = DstTy;
146       SpeculativeTypes.push_back(SrcTy);
147       return true;
148     }
149
150     // Mapping a non-opaque source type to an opaque dest.  If this is the first
151     // type that we're mapping onto this destination type then we succeed.  Keep
152     // the dest, but fill it in later. If this is the second (different) type
153     // that we're trying to map onto the same opaque type then we fail.
154     if (cast<StructType>(DstTy)->isOpaque()) {
155       // We can only map one source type onto the opaque destination type.
156       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
157         return false;
158       SrcDefinitionsToResolve.push_back(SSTy);
159       SpeculativeTypes.push_back(SrcTy);
160       SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
161       Entry = DstTy;
162       return true;
163     }
164   }
165
166   // If the number of subtypes disagree between the two types, then we fail.
167   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
168     return false;
169
170   // Fail if any of the extra properties (e.g. array size) of the type disagree.
171   if (isa<IntegerType>(DstTy))
172     return false; // bitwidth disagrees.
173   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
174     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
175       return false;
176
177   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
178     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
179       return false;
180   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
181     StructType *SSTy = cast<StructType>(SrcTy);
182     if (DSTy->isLiteral() != SSTy->isLiteral() ||
183         DSTy->isPacked() != SSTy->isPacked())
184       return false;
185   } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
186     if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
187       return false;
188   } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
189     if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
190       return false;
191   }
192
193   // Otherwise, we speculate that these two types will line up and recursively
194   // check the subelements.
195   Entry = DstTy;
196   SpeculativeTypes.push_back(SrcTy);
197
198   for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
199     if (!areTypesIsomorphic(DstTy->getContainedType(I),
200                             SrcTy->getContainedType(I)))
201       return false;
202
203   // If everything seems to have lined up, then everything is great.
204   return true;
205 }
206
207 void TypeMapTy::linkDefinedTypeBodies() {
208   SmallVector<Type *, 16> Elements;
209   for (StructType *SrcSTy : SrcDefinitionsToResolve) {
210     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
211     assert(DstSTy->isOpaque());
212
213     // Map the body of the source type over to a new body for the dest type.
214     Elements.resize(SrcSTy->getNumElements());
215     for (unsigned I = 0, E = Elements.size(); I != E; ++I)
216       Elements[I] = get(SrcSTy->getElementType(I));
217
218     DstSTy->setBody(Elements, SrcSTy->isPacked());
219     DstStructTypesSet.switchToNonOpaque(DstSTy);
220   }
221   SrcDefinitionsToResolve.clear();
222   DstResolvedOpaqueTypes.clear();
223 }
224
225 void TypeMapTy::finishType(StructType *DTy, StructType *STy,
226                            ArrayRef<Type *> ETypes) {
227   DTy->setBody(ETypes, STy->isPacked());
228
229   // Steal STy's name.
230   if (STy->hasName()) {
231     SmallString<16> TmpName = STy->getName();
232     STy->setName("");
233     DTy->setName(TmpName);
234   }
235
236   DstStructTypesSet.addNonOpaque(DTy);
237 }
238
239 Type *TypeMapTy::get(Type *Ty) {
240   SmallPtrSet<StructType *, 8> Visited;
241   return get(Ty, Visited);
242 }
243
244 Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
245   // If we already have an entry for this type, return it.
246   Type **Entry = &MappedTypes[Ty];
247   if (*Entry)
248     return *Entry;
249
250   // These are types that LLVM itself will unique.
251   bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
252
253 #ifndef NDEBUG
254   if (!IsUniqued) {
255     for (auto &Pair : MappedTypes) {
256       assert(!(Pair.first != Ty && Pair.second == Ty) &&
257              "mapping to a source type");
258     }
259   }
260 #endif
261
262   if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
263     StructType *DTy = StructType::create(Ty->getContext());
264     return *Entry = DTy;
265   }
266
267   // If this is not a recursive type, then just map all of the elements and
268   // then rebuild the type from inside out.
269   SmallVector<Type *, 4> ElementTypes;
270
271   // If there are no element types to map, then the type is itself.  This is
272   // true for the anonymous {} struct, things like 'float', integers, etc.
273   if (Ty->getNumContainedTypes() == 0 && IsUniqued)
274     return *Entry = Ty;
275
276   // Remap all of the elements, keeping track of whether any of them change.
277   bool AnyChange = false;
278   ElementTypes.resize(Ty->getNumContainedTypes());
279   for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
280     ElementTypes[I] = get(Ty->getContainedType(I), Visited);
281     AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
282   }
283
284   // If we found our type while recursively processing stuff, just use it.
285   Entry = &MappedTypes[Ty];
286   if (*Entry) {
287     if (auto *DTy = dyn_cast<StructType>(*Entry)) {
288       if (DTy->isOpaque()) {
289         auto *STy = cast<StructType>(Ty);
290         finishType(DTy, STy, ElementTypes);
291       }
292     }
293     return *Entry;
294   }
295
296   // If all of the element types mapped directly over and the type is not
297   // a nomed struct, then the type is usable as-is.
298   if (!AnyChange && IsUniqued)
299     return *Entry = Ty;
300
301   // Otherwise, rebuild a modified type.
302   switch (Ty->getTypeID()) {
303   default:
304     llvm_unreachable("unknown derived type to remap");
305   case Type::ArrayTyID:
306     return *Entry = ArrayType::get(ElementTypes[0],
307                                    cast<ArrayType>(Ty)->getNumElements());
308   case Type::VectorTyID:
309     return *Entry = VectorType::get(ElementTypes[0],
310                                     cast<VectorType>(Ty)->getNumElements());
311   case Type::PointerTyID:
312     return *Entry = PointerType::get(ElementTypes[0],
313                                      cast<PointerType>(Ty)->getAddressSpace());
314   case Type::FunctionTyID:
315     return *Entry = FunctionType::get(ElementTypes[0],
316                                       makeArrayRef(ElementTypes).slice(1),
317                                       cast<FunctionType>(Ty)->isVarArg());
318   case Type::StructTyID: {
319     auto *STy = cast<StructType>(Ty);
320     bool IsPacked = STy->isPacked();
321     if (IsUniqued)
322       return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
323
324     // If the type is opaque, we can just use it directly.
325     if (STy->isOpaque()) {
326       DstStructTypesSet.addOpaque(STy);
327       return *Entry = Ty;
328     }
329
330     if (StructType *OldT =
331             DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
332       STy->setName("");
333       return *Entry = OldT;
334     }
335
336     if (!AnyChange) {
337       DstStructTypesSet.addNonOpaque(STy);
338       return *Entry = Ty;
339     }
340
341     StructType *DTy = StructType::create(Ty->getContext());
342     finishType(DTy, STy, ElementTypes);
343     return *Entry = DTy;
344   }
345   }
346 }
347
348 //===----------------------------------------------------------------------===//
349 // ModuleLinker implementation.
350 //===----------------------------------------------------------------------===//
351
352 namespace {
353 class ModuleLinker;
354
355 /// Creates prototypes for functions that are lazily linked on the fly. This
356 /// speeds up linking for modules with many/ lazily linked functions of which
357 /// few get used.
358 class ValueMaterializerTy final : public ValueMaterializer {
359   ModuleLinker *ModLinker;
360
361 public:
362   ValueMaterializerTy(ModuleLinker *ModLinker) : ModLinker(ModLinker) {}
363
364   Value *materializeDeclFor(Value *V) override;
365   void materializeInitFor(GlobalValue *New, GlobalValue *Old) override;
366 };
367
368 class LinkDiagnosticInfo : public DiagnosticInfo {
369   const Twine &Msg;
370
371 public:
372   LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
373   void print(DiagnosticPrinter &DP) const override;
374 };
375 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
376                                        const Twine &Msg)
377     : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
378 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
379
380 /// This is an implementation class for the LinkModules function, which is the
381 /// entrypoint for this file.
382 class ModuleLinker {
383   Module &DstM;
384   Module &SrcM;
385
386   TypeMapTy TypeMap;
387   ValueMaterializerTy ValMaterializer;
388
389   /// Mapping of values from what they used to be in Src, to what they are now
390   /// in DstM.  ValueToValueMapTy is a ValueMap, which involves some overhead
391   /// due to the use of Value handles which the Linker doesn't actually need,
392   /// but this allows us to reuse the ValueMapper code.
393   ValueToValueMapTy ValueMap;
394
395   // Set of items not to link in from source.
396   SmallPtrSet<const GlobalValue *, 16> DoNotLinkFromSource;
397
398   DiagnosticHandlerFunction DiagnosticHandler;
399
400   /// For symbol clashes, prefer those from Src.
401   unsigned Flags;
402
403   /// Function index passed into ModuleLinker for using in function
404   /// importing/exporting handling.
405   const FunctionInfoIndex *ImportIndex;
406
407   /// Function to import from source module, all other functions are
408   /// imported as declarations instead of definitions.
409   Function *ImportFunction;
410
411   /// Set to true if the given FunctionInfoIndex contains any functions
412   /// from this source module, in which case we must conservatively assume
413   /// that any of its functions may be imported into another module
414   /// as part of a different backend compilation process.
415   bool HasExportedFunctions;
416
417   /// Set to true when all global value body linking is complete (including
418   /// lazy linking). Used to prevent metadata linking from creating new
419   /// references.
420   bool DoneLinkingBodies;
421
422   bool HasError = false;
423
424 public:
425   ModuleLinker(Module &DstM, Linker::IdentifiedStructTypeSet &Set, Module &SrcM,
426                DiagnosticHandlerFunction DiagnosticHandler, unsigned Flags,
427                const FunctionInfoIndex *Index = nullptr,
428                Function *FuncToImport = nullptr)
429       : DstM(DstM), SrcM(SrcM), TypeMap(Set), ValMaterializer(this),
430         DiagnosticHandler(DiagnosticHandler), Flags(Flags), ImportIndex(Index),
431         ImportFunction(FuncToImport), HasExportedFunctions(false),
432         DoneLinkingBodies(false) {
433     assert((ImportIndex || !ImportFunction) &&
434            "Expect a FunctionInfoIndex when importing");
435     // If we have a FunctionInfoIndex but no function to import,
436     // then this is the primary module being compiled in a ThinLTO
437     // backend compilation, and we need to see if it has functions that
438     // may be exported to another backend compilation.
439     if (ImportIndex && !ImportFunction)
440       HasExportedFunctions = ImportIndex->hasExportedFunctions(&SrcM);
441   }
442
443   bool run();
444   Value *materializeDeclFor(Value *V);
445   void materializeInitFor(GlobalValue *New, GlobalValue *Old);
446
447 private:
448   bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
449   bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
450   bool shouldInternalizeLinkedSymbols() {
451     return Flags & Linker::InternalizeLinkedSymbols;
452   }
453
454   /// Handles cloning of a global values from the source module into
455   /// the destination module, including setting the attributes and visibility.
456   GlobalValue *copyGlobalValueProto(TypeMapTy &TypeMap, const GlobalValue *SGV,
457                                     const GlobalValue *DGV = nullptr);
458
459   /// Check if we should promote the given local value to global scope.
460   bool doPromoteLocalToGlobal(const GlobalValue *SGV);
461
462   /// Check if all global value body linking is complete.
463   bool doneLinkingBodies() { return DoneLinkingBodies; }
464
465   bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
466                             const GlobalValue &Src);
467
468   /// Helper method for setting a message and returning an error code.
469   bool emitError(const Twine &Message) {
470     DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
471     HasError = true;
472     return true;
473   }
474
475   void emitWarning(const Twine &Message) {
476     DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
477   }
478
479   bool getComdatLeader(Module &M, StringRef ComdatName,
480                        const GlobalVariable *&GVar);
481   bool computeResultingSelectionKind(StringRef ComdatName,
482                                      Comdat::SelectionKind Src,
483                                      Comdat::SelectionKind Dst,
484                                      Comdat::SelectionKind &Result,
485                                      bool &LinkFromSrc);
486   std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
487       ComdatsChosen;
488   bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
489                        bool &LinkFromSrc);
490   // Keep track of the global value members of each comdat in source.
491   DenseMap<const Comdat *, std::vector<GlobalValue *>> ComdatMembers;
492
493   /// Given a global in the source module, return the global in the
494   /// destination module that is being linked to, if any.
495   GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
496     // If the source has no name it can't link.  If it has local linkage,
497     // there is no name match-up going on.
498     if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(getLinkage(SrcGV)))
499       return nullptr;
500
501     // Otherwise see if we have a match in the destination module's symtab.
502     GlobalValue *DGV = DstM.getNamedValue(getName(SrcGV));
503     if (!DGV)
504       return nullptr;
505
506     // If we found a global with the same name in the dest module, but it has
507     // internal linkage, we are really not doing any linkage here.
508     if (DGV->hasLocalLinkage())
509       return nullptr;
510
511     // Otherwise, we do in fact link to the destination global.
512     return DGV;
513   }
514
515   void computeTypeMapping();
516
517   void upgradeMismatchedGlobalArray(StringRef Name);
518   void upgradeMismatchedGlobals();
519
520   bool linkIfNeeded(GlobalValue &GV);
521   bool linkAppendingVarProto(GlobalVariable *DstGV,
522                              const GlobalVariable *SrcGV);
523
524   bool linkGlobalValueProto(GlobalValue *GV);
525   bool linkModuleFlagsMetadata();
526
527   void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
528   bool linkFunctionBody(Function &Dst, Function &Src);
529   void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
530   bool linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
531
532   /// Functions that take care of cloning a specific global value type
533   /// into the destination module.
534   GlobalVariable *copyGlobalVariableProto(TypeMapTy &TypeMap,
535                                           const GlobalVariable *SGVar);
536   Function *copyFunctionProto(TypeMapTy &TypeMap, const Function *SF);
537   GlobalValue *copyGlobalAliasProto(TypeMapTy &TypeMap, const GlobalAlias *SGA);
538
539   /// Helper methods to check if we are importing from or potentially
540   /// exporting from the current source module.
541   bool isPerformingImport() { return ImportFunction != nullptr; }
542   bool isModuleExporting() { return HasExportedFunctions; }
543
544   /// If we are importing from the source module, checks if we should
545   /// import SGV as a definition, otherwise import as a declaration.
546   bool doImportAsDefinition(const GlobalValue *SGV);
547
548   /// Get the name for SGV that should be used in the linked destination
549   /// module. Specifically, this handles the case where we need to rename
550   /// a local that is being promoted to global scope.
551   std::string getName(const GlobalValue *SGV);
552
553   /// Get the new linkage for SGV that should be used in the linked destination
554   /// module. Specifically, for ThinLTO importing or exporting it may need
555   /// to be adjusted.
556   GlobalValue::LinkageTypes getLinkage(const GlobalValue *SGV);
557
558   /// Copies the necessary global value attributes and name from the source
559   /// to the newly cloned global value.
560   void copyGVAttributes(GlobalValue *NewGV, const GlobalValue *SrcGV);
561
562   /// Updates the visibility for the new global cloned from the source
563   /// and, if applicable, linked with an existing destination global.
564   /// Handles visibility change required for promoted locals.
565   void setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
566                      const GlobalValue *DGV = nullptr);
567
568   void linkNamedMDNodes();
569 };
570 }
571
572 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
573 /// table. This is good for all clients except for us. Go through the trouble
574 /// to force this back.
575 static void forceRenaming(GlobalValue *GV, StringRef Name) {
576   // If the global doesn't force its name or if it already has the right name,
577   // there is nothing for us to do.
578   // Note that any required local to global promotion should already be done,
579   // so promoted locals will not skip this handling as their linkage is no
580   // longer local.
581   if (GV->hasLocalLinkage() || GV->getName() == Name)
582     return;
583
584   Module *M = GV->getParent();
585
586   // If there is a conflict, rename the conflict.
587   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
588     GV->takeName(ConflictGV);
589     ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
590     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
591   } else {
592     GV->setName(Name); // Force the name back
593   }
594 }
595
596 /// copy additional attributes (those not needed to construct a GlobalValue)
597 /// from the SrcGV to the DestGV.
598 void ModuleLinker::copyGVAttributes(GlobalValue *NewGV,
599                                     const GlobalValue *SrcGV) {
600   auto *GA = dyn_cast<GlobalAlias>(SrcGV);
601   // Check for the special case of converting an alias (definition) to a
602   // non-alias (declaration). This can happen when we are importing and
603   // encounter a weak_any alias (weak_any defs may not be imported, see
604   // comments in ModuleLinker::getLinkage) or an alias whose base object is
605   // being imported as a declaration. In that case copy the attributes from the
606   // base object.
607   if (GA && !dyn_cast<GlobalAlias>(NewGV)) {
608     assert(isPerformingImport() && !doImportAsDefinition(GA));
609     NewGV->copyAttributesFrom(GA->getBaseObject());
610   } else
611     NewGV->copyAttributesFrom(SrcGV);
612   forceRenaming(NewGV, getName(SrcGV));
613 }
614
615 bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
616   if (!isPerformingImport())
617     return false;
618   auto *GA = dyn_cast<GlobalAlias>(SGV);
619   if (GA) {
620     if (GA->hasWeakAnyLinkage())
621       return false;
622     const GlobalObject *GO = GA->getBaseObject();
623     if (!GO->hasLinkOnceODRLinkage())
624       return false;
625     return doImportAsDefinition(GO);
626   }
627   // Always import GlobalVariable definitions, except for the special
628   // case of WeakAny which are imported as ExternalWeak declarations
629   // (see comments in ModuleLinker::getLinkage). The linkage changes
630   // described in ModuleLinker::getLinkage ensure the correct behavior (e.g.
631   // global variables with external linkage are transformed to
632   // available_externally definitions, which are ultimately turned into
633   // declarations after the EliminateAvailableExternally pass).
634   if (isa<GlobalVariable>(SGV) && !SGV->isDeclaration() &&
635       !SGV->hasWeakAnyLinkage())
636     return true;
637   // Only import the function requested for importing.
638   auto *SF = dyn_cast<Function>(SGV);
639   if (SF && SF == ImportFunction)
640     return true;
641   // Otherwise no.
642   return false;
643 }
644
645 bool ModuleLinker::doPromoteLocalToGlobal(const GlobalValue *SGV) {
646   assert(SGV->hasLocalLinkage());
647   // Both the imported references and the original local variable must
648   // be promoted.
649   if (!isPerformingImport() && !isModuleExporting())
650     return false;
651
652   // Local const variables never need to be promoted unless they are address
653   // taken. The imported uses can simply use the clone created in this module.
654   // For now we are conservative in determining which variables are not
655   // address taken by checking the unnamed addr flag. To be more aggressive,
656   // the address taken information must be checked earlier during parsing
657   // of the module and recorded in the function index for use when importing
658   // from that module.
659   auto *GVar = dyn_cast<GlobalVariable>(SGV);
660   if (GVar && GVar->isConstant() && GVar->hasUnnamedAddr())
661     return false;
662
663   // Eventually we only need to promote functions in the exporting module that
664   // are referenced by a potentially exported function (i.e. one that is in the
665   // function index).
666   return true;
667 }
668
669 std::string ModuleLinker::getName(const GlobalValue *SGV) {
670   // For locals that must be promoted to global scope, ensure that
671   // the promoted name uniquely identifies the copy in the original module,
672   // using the ID assigned during combined index creation. When importing,
673   // we rename all locals (not just those that are promoted) in order to
674   // avoid naming conflicts between locals imported from different modules.
675   if (SGV->hasLocalLinkage() &&
676       (doPromoteLocalToGlobal(SGV) || isPerformingImport()))
677     return FunctionInfoIndex::getGlobalNameForLocal(
678         SGV->getName(),
679         ImportIndex->getModuleId(SGV->getParent()->getModuleIdentifier()));
680   return SGV->getName();
681 }
682
683 GlobalValue::LinkageTypes ModuleLinker::getLinkage(const GlobalValue *SGV) {
684   // Any local variable that is referenced by an exported function needs
685   // to be promoted to global scope. Since we don't currently know which
686   // functions reference which local variables/functions, we must treat
687   // all as potentially exported if this module is exporting anything.
688   if (isModuleExporting()) {
689     if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
690       return GlobalValue::ExternalLinkage;
691     return SGV->getLinkage();
692   }
693
694   // Otherwise, if we aren't importing, no linkage change is needed.
695   if (!isPerformingImport())
696     return SGV->getLinkage();
697
698   switch (SGV->getLinkage()) {
699   case GlobalValue::ExternalLinkage:
700     // External defnitions are converted to available_externally
701     // definitions upon import, so that they are available for inlining
702     // and/or optimization, but are turned into declarations later
703     // during the EliminateAvailableExternally pass.
704     if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
705       return GlobalValue::AvailableExternallyLinkage;
706     // An imported external declaration stays external.
707     return SGV->getLinkage();
708
709   case GlobalValue::AvailableExternallyLinkage:
710     // An imported available_externally definition converts
711     // to external if imported as a declaration.
712     if (!doImportAsDefinition(SGV))
713       return GlobalValue::ExternalLinkage;
714     // An imported available_externally declaration stays that way.
715     return SGV->getLinkage();
716
717   case GlobalValue::LinkOnceAnyLinkage:
718   case GlobalValue::LinkOnceODRLinkage:
719     // These both stay the same when importing the definition.
720     // The ThinLTO pass will eventually force-import their definitions.
721     return SGV->getLinkage();
722
723   case GlobalValue::WeakAnyLinkage:
724     // Can't import weak_any definitions correctly, or we might change the
725     // program semantics, since the linker will pick the first weak_any
726     // definition and importing would change the order they are seen by the
727     // linker. The module linking caller needs to enforce this.
728     assert(!doImportAsDefinition(SGV));
729     // If imported as a declaration, it becomes external_weak.
730     return GlobalValue::ExternalWeakLinkage;
731
732   case GlobalValue::WeakODRLinkage:
733     // For weak_odr linkage, there is a guarantee that all copies will be
734     // equivalent, so the issue described above for weak_any does not exist,
735     // and the definition can be imported. It can be treated similarly
736     // to an imported externally visible global value.
737     if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
738       return GlobalValue::AvailableExternallyLinkage;
739     else
740       return GlobalValue::ExternalLinkage;
741
742   case GlobalValue::AppendingLinkage:
743     // It would be incorrect to import an appending linkage variable,
744     // since it would cause global constructors/destructors to be
745     // executed multiple times. This should have already been handled
746     // by linkGlobalValueProto.
747     llvm_unreachable("Cannot import appending linkage variable");
748
749   case GlobalValue::InternalLinkage:
750   case GlobalValue::PrivateLinkage:
751     // If we are promoting the local to global scope, it is handled
752     // similarly to a normal externally visible global.
753     if (doPromoteLocalToGlobal(SGV)) {
754       if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
755         return GlobalValue::AvailableExternallyLinkage;
756       else
757         return GlobalValue::ExternalLinkage;
758     }
759     // A non-promoted imported local definition stays local.
760     // The ThinLTO pass will eventually force-import their definitions.
761     return SGV->getLinkage();
762
763   case GlobalValue::ExternalWeakLinkage:
764     // External weak doesn't apply to definitions, must be a declaration.
765     assert(!doImportAsDefinition(SGV));
766     // Linkage stays external_weak.
767     return SGV->getLinkage();
768
769   case GlobalValue::CommonLinkage:
770     // Linkage stays common on definitions.
771     // The ThinLTO pass will eventually force-import their definitions.
772     return SGV->getLinkage();
773   }
774
775   llvm_unreachable("unknown linkage type");
776 }
777
778 /// Loop through the global variables in the src module and merge them into the
779 /// dest module.
780 GlobalVariable *
781 ModuleLinker::copyGlobalVariableProto(TypeMapTy &TypeMap,
782                                       const GlobalVariable *SGVar) {
783   // No linking to be performed or linking from the source: simply create an
784   // identical version of the symbol over in the dest module... the
785   // initializer will be filled in later by LinkGlobalInits.
786   GlobalVariable *NewDGV = new GlobalVariable(
787       DstM, TypeMap.get(SGVar->getType()->getElementType()),
788       SGVar->isConstant(), getLinkage(SGVar), /*init*/ nullptr, getName(SGVar),
789       /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
790       SGVar->getType()->getAddressSpace());
791
792   return NewDGV;
793 }
794
795 /// Link the function in the source module into the destination module if
796 /// needed, setting up mapping information.
797 Function *ModuleLinker::copyFunctionProto(TypeMapTy &TypeMap,
798                                           const Function *SF) {
799   // If there is no linkage to be performed or we are linking from the source,
800   // bring SF over.
801   return Function::Create(TypeMap.get(SF->getFunctionType()), getLinkage(SF),
802                           getName(SF), &DstM);
803 }
804
805 /// Set up prototypes for any aliases that come over from the source module.
806 GlobalValue *ModuleLinker::copyGlobalAliasProto(TypeMapTy &TypeMap,
807                                                 const GlobalAlias *SGA) {
808   // If we are importing and encounter a weak_any alias, or an alias to
809   // an object being imported as a declaration, we must import the alias
810   // as a declaration as well, which involves converting it to a non-alias.
811   // See comments in ModuleLinker::getLinkage for why we cannot import
812   // weak_any defintions.
813   if (isPerformingImport() && !doImportAsDefinition(SGA)) {
814     // Need to convert to declaration. All aliases must be definitions.
815     const GlobalValue *GVal = SGA->getBaseObject();
816     GlobalValue *NewGV;
817     if (auto *GVar = dyn_cast<GlobalVariable>(GVal))
818       NewGV = copyGlobalVariableProto(TypeMap, GVar);
819     else {
820       auto *F = dyn_cast<Function>(GVal);
821       assert(F);
822       NewGV = copyFunctionProto(TypeMap, F);
823     }
824     // Set the linkage to External or ExternalWeak (see comments in
825     // ModuleLinker::getLinkage for why WeakAny is converted to ExternalWeak).
826     if (SGA->hasWeakAnyLinkage())
827       NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
828     else
829       NewGV->setLinkage(GlobalValue::ExternalLinkage);
830     return NewGV;
831   }
832   // If there is no linkage to be performed or we're linking from the source,
833   // bring over SGA.
834   auto *Ty = TypeMap.get(SGA->getValueType());
835   return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
836                              getLinkage(SGA), getName(SGA), &DstM);
837 }
838
839 static GlobalValue::VisibilityTypes
840 getMinVisibility(GlobalValue::VisibilityTypes A,
841                  GlobalValue::VisibilityTypes B) {
842   if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
843     return GlobalValue::HiddenVisibility;
844   if (A == GlobalValue::ProtectedVisibility ||
845       B == GlobalValue::ProtectedVisibility)
846     return GlobalValue::ProtectedVisibility;
847   return GlobalValue::DefaultVisibility;
848 }
849
850 void ModuleLinker::setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
851                                  const GlobalValue *DGV) {
852   GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
853   if (DGV)
854     Visibility = getMinVisibility(DGV->getVisibility(), Visibility);
855   // For promoted locals, mark them hidden so that they can later be
856   // stripped from the symbol table to reduce bloat.
857   if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
858     Visibility = GlobalValue::HiddenVisibility;
859   NewGV->setVisibility(Visibility);
860 }
861
862 GlobalValue *ModuleLinker::copyGlobalValueProto(TypeMapTy &TypeMap,
863                                                 const GlobalValue *SGV,
864                                                 const GlobalValue *DGV) {
865   GlobalValue *NewGV;
866   if (auto *SGVar = dyn_cast<GlobalVariable>(SGV))
867     NewGV = copyGlobalVariableProto(TypeMap, SGVar);
868   else if (auto *SF = dyn_cast<Function>(SGV))
869     NewGV = copyFunctionProto(TypeMap, SF);
870   else
871     NewGV = copyGlobalAliasProto(TypeMap, cast<GlobalAlias>(SGV));
872   copyGVAttributes(NewGV, SGV);
873   setVisibility(NewGV, SGV, DGV);
874   return NewGV;
875 }
876
877 Value *ValueMaterializerTy::materializeDeclFor(Value *V) {
878   return ModLinker->materializeDeclFor(V);
879 }
880
881 Value *ModuleLinker::materializeDeclFor(Value *V) {
882   auto *SGV = dyn_cast<GlobalValue>(V);
883   if (!SGV)
884     return nullptr;
885
886   // If we are done linking global value bodies (i.e. we are performing
887   // metadata linking), don't link in the global value due to this
888   // reference, simply map it to null.
889   if (doneLinkingBodies())
890     return nullptr;
891
892   linkGlobalValueProto(SGV);
893   if (HasError)
894     return nullptr;
895   Value *Ret = ValueMap[SGV];
896   assert(Ret);
897   return Ret;
898 }
899
900 void ValueMaterializerTy::materializeInitFor(GlobalValue *New,
901                                              GlobalValue *Old) {
902   return ModLinker->materializeInitFor(New, Old);
903 }
904
905 void ModuleLinker::materializeInitFor(GlobalValue *New, GlobalValue *Old) {
906   if (auto *F = dyn_cast<Function>(New)) {
907     if (!F->isDeclaration())
908       return;
909   } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
910     if (V->hasInitializer())
911       return;
912   } else {
913     auto *A = cast<GlobalAlias>(New);
914     if (A->getAliasee())
915       return;
916   }
917
918   if (Old->isDeclaration())
919     return;
920
921   if (isPerformingImport() && !doImportAsDefinition(Old))
922     return;
923
924   if (!New->hasLocalLinkage() && DoNotLinkFromSource.count(Old))
925     return;
926
927   linkGlobalValueBody(*New, *Old);
928 }
929
930 bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
931                                    const GlobalVariable *&GVar) {
932   const GlobalValue *GVal = M.getNamedValue(ComdatName);
933   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
934     GVal = GA->getBaseObject();
935     if (!GVal)
936       // We cannot resolve the size of the aliasee yet.
937       return emitError("Linking COMDATs named '" + ComdatName +
938                        "': COMDAT key involves incomputable alias size.");
939   }
940
941   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
942   if (!GVar)
943     return emitError(
944         "Linking COMDATs named '" + ComdatName +
945         "': GlobalVariable required for data dependent selection!");
946
947   return false;
948 }
949
950 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
951                                                  Comdat::SelectionKind Src,
952                                                  Comdat::SelectionKind Dst,
953                                                  Comdat::SelectionKind &Result,
954                                                  bool &LinkFromSrc) {
955   // The ability to mix Comdat::SelectionKind::Any with
956   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
957   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
958                          Dst == Comdat::SelectionKind::Largest;
959   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
960                          Src == Comdat::SelectionKind::Largest;
961   if (DstAnyOrLargest && SrcAnyOrLargest) {
962     if (Dst == Comdat::SelectionKind::Largest ||
963         Src == Comdat::SelectionKind::Largest)
964       Result = Comdat::SelectionKind::Largest;
965     else
966       Result = Comdat::SelectionKind::Any;
967   } else if (Src == Dst) {
968     Result = Dst;
969   } else {
970     return emitError("Linking COMDATs named '" + ComdatName +
971                      "': invalid selection kinds!");
972   }
973
974   switch (Result) {
975   case Comdat::SelectionKind::Any:
976     // Go with Dst.
977     LinkFromSrc = false;
978     break;
979   case Comdat::SelectionKind::NoDuplicates:
980     return emitError("Linking COMDATs named '" + ComdatName +
981                      "': noduplicates has been violated!");
982   case Comdat::SelectionKind::ExactMatch:
983   case Comdat::SelectionKind::Largest:
984   case Comdat::SelectionKind::SameSize: {
985     const GlobalVariable *DstGV;
986     const GlobalVariable *SrcGV;
987     if (getComdatLeader(DstM, ComdatName, DstGV) ||
988         getComdatLeader(SrcM, ComdatName, SrcGV))
989       return true;
990
991     const DataLayout &DstDL = DstM.getDataLayout();
992     const DataLayout &SrcDL = SrcM.getDataLayout();
993     uint64_t DstSize =
994         DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
995     uint64_t SrcSize =
996         SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
997     if (Result == Comdat::SelectionKind::ExactMatch) {
998       if (SrcGV->getInitializer() != DstGV->getInitializer())
999         return emitError("Linking COMDATs named '" + ComdatName +
1000                          "': ExactMatch violated!");
1001       LinkFromSrc = false;
1002     } else if (Result == Comdat::SelectionKind::Largest) {
1003       LinkFromSrc = SrcSize > DstSize;
1004     } else if (Result == Comdat::SelectionKind::SameSize) {
1005       if (SrcSize != DstSize)
1006         return emitError("Linking COMDATs named '" + ComdatName +
1007                          "': SameSize violated!");
1008       LinkFromSrc = false;
1009     } else {
1010       llvm_unreachable("unknown selection kind");
1011     }
1012     break;
1013   }
1014   }
1015
1016   return false;
1017 }
1018
1019 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
1020                                    Comdat::SelectionKind &Result,
1021                                    bool &LinkFromSrc) {
1022   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
1023   StringRef ComdatName = SrcC->getName();
1024   Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
1025   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
1026
1027   if (DstCI == ComdatSymTab.end()) {
1028     // Use the comdat if it is only available in one of the modules.
1029     LinkFromSrc = true;
1030     Result = SSK;
1031     return false;
1032   }
1033
1034   const Comdat *DstC = &DstCI->second;
1035   Comdat::SelectionKind DSK = DstC->getSelectionKind();
1036   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
1037                                        LinkFromSrc);
1038 }
1039
1040 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
1041                                         const GlobalValue &Dest,
1042                                         const GlobalValue &Src) {
1043   // Should we unconditionally use the Src?
1044   if (shouldOverrideFromSrc()) {
1045     LinkFromSrc = true;
1046     return false;
1047   }
1048
1049   // We always have to add Src if it has appending linkage.
1050   if (Src.hasAppendingLinkage()) {
1051     // Caller should have already determined that we can't link from source
1052     // when importing (see comments in linkGlobalValueProto).
1053     assert(!isPerformingImport());
1054     LinkFromSrc = true;
1055     return false;
1056   }
1057
1058   bool SrcIsDeclaration = Src.isDeclarationForLinker();
1059   bool DestIsDeclaration = Dest.isDeclarationForLinker();
1060
1061   if (isPerformingImport()) {
1062     if (isa<Function>(&Src)) {
1063       // For functions, LinkFromSrc iff this is the function requested
1064       // for importing. For variables, decide below normally.
1065       LinkFromSrc = (&Src == ImportFunction);
1066       return false;
1067     }
1068
1069     // Check if this is an alias with an already existing definition
1070     // in Dest, which must have come from a prior importing pass from
1071     // the same Src module. Unlike imported function and variable
1072     // definitions, which are imported as available_externally and are
1073     // not definitions for the linker, that is not a valid linkage for
1074     // imported aliases which must be definitions. Simply use the existing
1075     // Dest copy.
1076     if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
1077       assert(isa<GlobalAlias>(&Dest));
1078       LinkFromSrc = false;
1079       return false;
1080     }
1081   }
1082
1083   if (SrcIsDeclaration) {
1084     // If Src is external or if both Src & Dest are external..  Just link the
1085     // external globals, we aren't adding anything.
1086     if (Src.hasDLLImportStorageClass()) {
1087       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
1088       LinkFromSrc = DestIsDeclaration;
1089       return false;
1090     }
1091     // If the Dest is weak, use the source linkage.
1092     LinkFromSrc = Dest.hasExternalWeakLinkage();
1093     return false;
1094   }
1095
1096   if (DestIsDeclaration) {
1097     // If Dest is external but Src is not:
1098     LinkFromSrc = true;
1099     return false;
1100   }
1101
1102   if (Src.hasCommonLinkage()) {
1103     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
1104       LinkFromSrc = true;
1105       return false;
1106     }
1107
1108     if (!Dest.hasCommonLinkage()) {
1109       LinkFromSrc = false;
1110       return false;
1111     }
1112
1113     const DataLayout &DL = Dest.getParent()->getDataLayout();
1114     uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
1115     uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
1116     LinkFromSrc = SrcSize > DestSize;
1117     return false;
1118   }
1119
1120   if (Src.isWeakForLinker()) {
1121     assert(!Dest.hasExternalWeakLinkage());
1122     assert(!Dest.hasAvailableExternallyLinkage());
1123
1124     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
1125       LinkFromSrc = true;
1126       return false;
1127     }
1128
1129     LinkFromSrc = false;
1130     return false;
1131   }
1132
1133   if (Dest.isWeakForLinker()) {
1134     assert(Src.hasExternalLinkage());
1135     LinkFromSrc = true;
1136     return false;
1137   }
1138
1139   assert(!Src.hasExternalWeakLinkage());
1140   assert(!Dest.hasExternalWeakLinkage());
1141   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
1142          "Unexpected linkage type!");
1143   return emitError("Linking globals named '" + Src.getName() +
1144                    "': symbol multiply defined!");
1145 }
1146
1147 /// Loop over all of the linked values to compute type mappings.  For example,
1148 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
1149 /// types 'Foo' but one got renamed when the module was loaded into the same
1150 /// LLVMContext.
1151 void ModuleLinker::computeTypeMapping() {
1152   for (GlobalValue &SGV : SrcM.globals()) {
1153     GlobalValue *DGV = getLinkedToGlobal(&SGV);
1154     if (!DGV)
1155       continue;
1156
1157     if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
1158       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1159       continue;
1160     }
1161
1162     // Unify the element type of appending arrays.
1163     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
1164     ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
1165     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
1166   }
1167
1168   for (GlobalValue &SGV : SrcM) {
1169     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1170       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1171   }
1172
1173   for (GlobalValue &SGV : SrcM.aliases()) {
1174     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1175       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1176   }
1177
1178   // Incorporate types by name, scanning all the types in the source module.
1179   // At this point, the destination module may have a type "%foo = { i32 }" for
1180   // example.  When the source module got loaded into the same LLVMContext, if
1181   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
1182   std::vector<StructType *> Types = SrcM.getIdentifiedStructTypes();
1183   for (StructType *ST : Types) {
1184     if (!ST->hasName())
1185       continue;
1186
1187     // Check to see if there is a dot in the name followed by a digit.
1188     size_t DotPos = ST->getName().rfind('.');
1189     if (DotPos == 0 || DotPos == StringRef::npos ||
1190         ST->getName().back() == '.' ||
1191         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
1192       continue;
1193
1194     // Check to see if the destination module has a struct with the prefix name.
1195     StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
1196     if (!DST)
1197       continue;
1198
1199     // Don't use it if this actually came from the source module. They're in
1200     // the same LLVMContext after all. Also don't use it unless the type is
1201     // actually used in the destination module. This can happen in situations
1202     // like this:
1203     //
1204     //      Module A                         Module B
1205     //      --------                         --------
1206     //   %Z = type { %A }                %B = type { %C.1 }
1207     //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
1208     //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
1209     //   %C = type { i8* }               %B.3 = type { %C.1 }
1210     //
1211     // When we link Module B with Module A, the '%B' in Module B is
1212     // used. However, that would then use '%C.1'. But when we process '%C.1',
1213     // we prefer to take the '%C' version. So we are then left with both
1214     // '%C.1' and '%C' being used for the same types. This leads to some
1215     // variables using one type and some using the other.
1216     if (TypeMap.DstStructTypesSet.hasType(DST))
1217       TypeMap.addTypeMapping(DST, ST);
1218   }
1219
1220   // Now that we have discovered all of the type equivalences, get a body for
1221   // any 'opaque' types in the dest module that are now resolved.
1222   TypeMap.linkDefinedTypeBodies();
1223 }
1224
1225 static void upgradeGlobalArray(GlobalVariable *GV) {
1226   ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
1227   StructType *OldTy = cast<StructType>(ATy->getElementType());
1228   assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
1229
1230   // Get the upgraded 3 element type.
1231   PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
1232   Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
1233                   VoidPtrTy};
1234   StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
1235
1236   // Build new constants with a null third field filled in.
1237   Constant *OldInitC = GV->getInitializer();
1238   ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
1239   if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
1240     // Invalid initializer; give up.
1241     return;
1242   std::vector<Constant *> Initializers;
1243   if (OldInit && OldInit->getNumOperands()) {
1244     Value *Null = Constant::getNullValue(VoidPtrTy);
1245     for (Use &U : OldInit->operands()) {
1246       ConstantStruct *Init = cast<ConstantStruct>(U.get());
1247       Initializers.push_back(ConstantStruct::get(
1248           NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
1249     }
1250   }
1251   assert(Initializers.size() == ATy->getNumElements() &&
1252          "Failed to copy all array elements");
1253
1254   // Replace the old GV with a new one.
1255   ATy = ArrayType::get(NewTy, Initializers.size());
1256   Constant *NewInit = ConstantArray::get(ATy, Initializers);
1257   GlobalVariable *NewGV = new GlobalVariable(
1258       *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
1259       GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
1260       GV->isExternallyInitialized());
1261   NewGV->copyAttributesFrom(GV);
1262   NewGV->takeName(GV);
1263   assert(GV->use_empty() && "program cannot use initializer list");
1264   GV->eraseFromParent();
1265 }
1266
1267 void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
1268   // Look for the global arrays.
1269   auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM.getNamedValue(Name));
1270   if (!DstGV)
1271     return;
1272   auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM.getNamedValue(Name));
1273   if (!SrcGV)
1274     return;
1275
1276   // Check if the types already match.
1277   auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
1278   auto *SrcTy =
1279       cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
1280   if (DstTy == SrcTy)
1281     return;
1282
1283   // Grab the element types.  We can only upgrade an array of a two-field
1284   // struct.  Only bother if the other one has three-fields.
1285   auto *DstEltTy = cast<StructType>(DstTy->getElementType());
1286   auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
1287   if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
1288     upgradeGlobalArray(DstGV);
1289     return;
1290   }
1291   if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
1292     upgradeGlobalArray(SrcGV);
1293
1294   // We can't upgrade any other differences.
1295 }
1296
1297 void ModuleLinker::upgradeMismatchedGlobals() {
1298   upgradeMismatchedGlobalArray("llvm.global_ctors");
1299   upgradeMismatchedGlobalArray("llvm.global_dtors");
1300 }
1301
1302 static void getArrayElements(const Constant *C,
1303                              SmallVectorImpl<Constant *> &Dest) {
1304   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1305
1306   for (unsigned i = 0; i != NumElements; ++i)
1307     Dest.push_back(C->getAggregateElement(i));
1308 }
1309
1310 /// If there were any appending global variables, link them together now.
1311 /// Return true on error.
1312 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
1313                                          const GlobalVariable *SrcGV) {
1314   ArrayType *SrcTy =
1315       cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
1316   Type *EltTy = SrcTy->getElementType();
1317
1318   if (DstGV) {
1319     ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
1320
1321     if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
1322       return emitError(
1323           "Linking globals named '" + SrcGV->getName() +
1324           "': can only link appending global with another appending global!");
1325
1326     // Check to see that they two arrays agree on type.
1327     if (EltTy != DstTy->getElementType())
1328       return emitError("Appending variables with different element types!");
1329     if (DstGV->isConstant() != SrcGV->isConstant())
1330       return emitError("Appending variables linked with different const'ness!");
1331
1332     if (DstGV->getAlignment() != SrcGV->getAlignment())
1333       return emitError(
1334           "Appending variables with different alignment need to be linked!");
1335
1336     if (DstGV->getVisibility() != SrcGV->getVisibility())
1337       return emitError(
1338           "Appending variables with different visibility need to be linked!");
1339
1340     if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
1341       return emitError(
1342           "Appending variables with different unnamed_addr need to be linked!");
1343
1344     if (StringRef(DstGV->getSection()) != SrcGV->getSection())
1345       return emitError(
1346           "Appending variables with different section name need to be linked!");
1347   }
1348
1349   SmallVector<Constant *, 16> DstElements;
1350   if (DstGV)
1351     getArrayElements(DstGV->getInitializer(), DstElements);
1352
1353   SmallVector<Constant *, 16> SrcElements;
1354   getArrayElements(SrcGV->getInitializer(), SrcElements);
1355
1356   StringRef Name = SrcGV->getName();
1357   bool IsNewStructor =
1358       (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1359       cast<StructType>(EltTy)->getNumElements() == 3;
1360   if (IsNewStructor)
1361     SrcElements.erase(
1362         std::remove_if(SrcElements.begin(), SrcElements.end(),
1363                        [this](Constant *E) {
1364                          auto *Key = dyn_cast<GlobalValue>(
1365                              E->getAggregateElement(2)->stripPointerCasts());
1366                          return DoNotLinkFromSource.count(Key);
1367                        }),
1368         SrcElements.end());
1369   uint64_t NewSize = DstElements.size() + SrcElements.size();
1370   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
1371
1372   // Create the new global variable.
1373   GlobalVariable *NG = new GlobalVariable(
1374       DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
1375       /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
1376       SrcGV->getType()->getAddressSpace());
1377
1378   // Propagate alignment, visibility and section info.
1379   copyGVAttributes(NG, SrcGV);
1380
1381   // Replace any uses of the two global variables with uses of the new
1382   // global.
1383   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
1384
1385   for (auto *V : SrcElements) {
1386     DstElements.push_back(
1387         MapValue(V, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1388   }
1389
1390   NG->setInitializer(ConstantArray::get(NewType, DstElements));
1391
1392   if (DstGV) {
1393     DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
1394     DstGV->eraseFromParent();
1395   }
1396
1397   return false;
1398 }
1399
1400 bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
1401   GlobalValue *DGV = getLinkedToGlobal(SGV);
1402
1403   // Handle the ultra special appending linkage case first.
1404   assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
1405   if (SGV->hasAppendingLinkage() && isPerformingImport()) {
1406     // Don't want to append to global_ctors list, for example, when we
1407     // are importing for ThinLTO, otherwise the global ctors and dtors
1408     // get executed multiple times for local variables (the latter causing
1409     // double frees).
1410     DoNotLinkFromSource.insert(SGV);
1411     return false;
1412   }
1413   if (SGV->hasAppendingLinkage())
1414     return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
1415                                  cast<GlobalVariable>(SGV));
1416
1417   bool LinkFromSrc = true;
1418   Comdat *C = nullptr;
1419   bool HasUnnamedAddr = SGV->hasUnnamedAddr();
1420
1421   if (const Comdat *SC = SGV->getComdat()) {
1422     Comdat::SelectionKind SK;
1423     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1424     C = DstM.getOrInsertComdat(SC->getName());
1425     C->setSelectionKind(SK);
1426     if (SGV->hasInternalLinkage())
1427       LinkFromSrc = true;
1428   } else if (DGV) {
1429     if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1430       return true;
1431   }
1432
1433   if (!LinkFromSrc) {
1434     // Track the source global so that we don't attempt to copy it over when
1435     // processing global initializers.
1436     DoNotLinkFromSource.insert(SGV);
1437
1438     if (DGV)
1439       // Make sure to remember this mapping.
1440       ValueMap[SGV] =
1441           ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
1442   }
1443
1444   if (DGV)
1445     HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1446
1447   GlobalValue *NewGV;
1448   if (!LinkFromSrc && DGV) {
1449     NewGV = DGV;
1450     // When linking from source we setVisibility from copyGlobalValueProto.
1451     setVisibility(NewGV, SGV, DGV);
1452   } else {
1453     NewGV = copyGlobalValueProto(TypeMap, SGV, DGV);
1454
1455     if (isPerformingImport() && !doImportAsDefinition(SGV))
1456       DoNotLinkFromSource.insert(SGV);
1457   }
1458
1459   NewGV->setUnnamedAddr(HasUnnamedAddr);
1460
1461   if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1462     if (C && LinkFromSrc)
1463       NewGO->setComdat(C);
1464
1465     if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1466       NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
1467   }
1468
1469   if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) {
1470     auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV);
1471     auto *SGVar = dyn_cast<GlobalVariable>(SGV);
1472     if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() &&
1473         (!DGVar->isConstant() || !SGVar->isConstant()))
1474       NewGVar->setConstant(false);
1475   }
1476
1477   // Make sure to remember this mapping.
1478   if (NewGV != DGV) {
1479     if (DGV) {
1480       DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
1481       DGV->eraseFromParent();
1482     }
1483     ValueMap[SGV] = NewGV;
1484   }
1485
1486   return false;
1487 }
1488
1489 /// Update the initializers in the Dest module now that all globals that may be
1490 /// referenced are in Dest.
1491 void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
1492   // Figure out what the initializer looks like in the dest module.
1493   Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap,
1494                               RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1495 }
1496
1497 /// Copy the source function over into the dest function and fix up references
1498 /// to values. At this point we know that Dest is an external function, and
1499 /// that Src is not.
1500 bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) {
1501   assert(Dst.isDeclaration() && !Src.isDeclaration());
1502
1503   // Materialize if needed.
1504   if (std::error_code EC = Src.materialize())
1505     return emitError(EC.message());
1506
1507   // Link in the prefix data.
1508   if (Src.hasPrefixData())
1509     Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap,
1510                                RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1511
1512   // Link in the prologue data.
1513   if (Src.hasPrologueData())
1514     Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap,
1515                                  RF_MoveDistinctMDs, &TypeMap,
1516                                  &ValMaterializer));
1517
1518   // Link in the personality function.
1519   if (Src.hasPersonalityFn())
1520     Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap,
1521                                   RF_MoveDistinctMDs, &TypeMap,
1522                                   &ValMaterializer));
1523
1524   // Go through and convert function arguments over, remembering the mapping.
1525   Function::arg_iterator DI = Dst.arg_begin();
1526   for (Argument &Arg : Src.args()) {
1527     DI->setName(Arg.getName()); // Copy the name over.
1528
1529     // Add a mapping to our mapping.
1530     ValueMap[&Arg] = &*DI;
1531     ++DI;
1532   }
1533
1534   // Copy over the metadata attachments.
1535   SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1536   Src.getAllMetadata(MDs);
1537   for (const auto &I : MDs)
1538     Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, RF_MoveDistinctMDs,
1539                                          &TypeMap, &ValMaterializer));
1540
1541   // Splice the body of the source function into the dest function.
1542   Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
1543
1544   // At this point, all of the instructions and values of the function are now
1545   // copied over.  The only problem is that they are still referencing values in
1546   // the Source function as operands.  Loop through all of the operands of the
1547   // functions and patch them up to point to the local versions.
1548   for (BasicBlock &BB : Dst)
1549     for (Instruction &I : BB)
1550       RemapInstruction(&I, ValueMap,
1551                        RF_IgnoreMissingEntries | RF_MoveDistinctMDs, &TypeMap,
1552                        &ValMaterializer);
1553
1554   // There is no need to map the arguments anymore.
1555   for (Argument &Arg : Src.args())
1556     ValueMap.erase(&Arg);
1557
1558   Src.dematerialize();
1559   return false;
1560 }
1561
1562 void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1563   Constant *Aliasee = Src.getAliasee();
1564   Constant *Val = MapValue(Aliasee, ValueMap, RF_MoveDistinctMDs, &TypeMap,
1565                            &ValMaterializer);
1566   Dst.setAliasee(Val);
1567 }
1568
1569 bool ModuleLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
1570   if (const Comdat *SC = Src.getComdat()) {
1571     // To ensure that we don't generate an incomplete comdat group,
1572     // we must materialize and map in any other members that are not
1573     // yet materialized in Dst, which also ensures their definitions
1574     // are linked in. Otherwise, linkonce and other lazy linked GVs will
1575     // not be materialized if they aren't referenced.
1576     for (auto *SGV : ComdatMembers[SC]) {
1577       auto *DGV = cast_or_null<GlobalValue>(ValueMap[SGV]);
1578       if (DGV && !DGV->isDeclaration())
1579         continue;
1580       MapValue(SGV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1581     }
1582   }
1583   if (shouldInternalizeLinkedSymbols())
1584     if (auto *DGV = dyn_cast<GlobalValue>(&Dst))
1585       DGV->setLinkage(GlobalValue::InternalLinkage);
1586   if (auto *F = dyn_cast<Function>(&Src))
1587     return linkFunctionBody(cast<Function>(Dst), *F);
1588   if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1589     linkGlobalInit(cast<GlobalVariable>(Dst), *GVar);
1590     return false;
1591   }
1592   linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
1593   return false;
1594 }
1595
1596 /// Insert all of the named MDNodes in Src into the Dest module.
1597 void ModuleLinker::linkNamedMDNodes() {
1598   const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1599   for (const NamedMDNode &NMD : SrcM.named_metadata()) {
1600     // Don't link module flags here. Do them separately.
1601     if (&NMD == SrcModFlags)
1602       continue;
1603     NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1604     // Add Src elements into Dest node.
1605     for (const MDNode *op : NMD.operands())
1606       DestNMD->addOperand(MapMetadata(
1607           op, ValueMap, RF_MoveDistinctMDs | RF_NullMapMissingGlobalValues,
1608           &TypeMap, &ValMaterializer));
1609   }
1610 }
1611
1612 /// Merge the linker flags in Src into the Dest module.
1613 bool ModuleLinker::linkModuleFlagsMetadata() {
1614   // If the source module has no module flags, we are done.
1615   const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1616   if (!SrcModFlags)
1617     return false;
1618
1619   // If the destination module doesn't have module flags yet, then just copy
1620   // over the source module's flags.
1621   NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1622   if (DstModFlags->getNumOperands() == 0) {
1623     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1624       DstModFlags->addOperand(SrcModFlags->getOperand(I));
1625
1626     return false;
1627   }
1628
1629   // First build a map of the existing module flags and requirements.
1630   DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1631   SmallSetVector<MDNode *, 16> Requirements;
1632   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1633     MDNode *Op = DstModFlags->getOperand(I);
1634     ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1635     MDString *ID = cast<MDString>(Op->getOperand(1));
1636
1637     if (Behavior->getZExtValue() == Module::Require) {
1638       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1639     } else {
1640       Flags[ID] = std::make_pair(Op, I);
1641     }
1642   }
1643
1644   // Merge in the flags from the source module, and also collect its set of
1645   // requirements.
1646   bool HasErr = false;
1647   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1648     MDNode *SrcOp = SrcModFlags->getOperand(I);
1649     ConstantInt *SrcBehavior =
1650         mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1651     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1652     MDNode *DstOp;
1653     unsigned DstIndex;
1654     std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1655     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1656
1657     // If this is a requirement, add it and continue.
1658     if (SrcBehaviorValue == Module::Require) {
1659       // If the destination module does not already have this requirement, add
1660       // it.
1661       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1662         DstModFlags->addOperand(SrcOp);
1663       }
1664       continue;
1665     }
1666
1667     // If there is no existing flag with this ID, just add it.
1668     if (!DstOp) {
1669       Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1670       DstModFlags->addOperand(SrcOp);
1671       continue;
1672     }
1673
1674     // Otherwise, perform a merge.
1675     ConstantInt *DstBehavior =
1676         mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1677     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1678
1679     // If either flag has override behavior, handle it first.
1680     if (DstBehaviorValue == Module::Override) {
1681       // Diagnose inconsistent flags which both have override behavior.
1682       if (SrcBehaviorValue == Module::Override &&
1683           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1684         HasErr |= emitError("linking module flags '" + ID->getString() +
1685                             "': IDs have conflicting override values");
1686       }
1687       continue;
1688     } else if (SrcBehaviorValue == Module::Override) {
1689       // Update the destination flag to that of the source.
1690       DstModFlags->setOperand(DstIndex, SrcOp);
1691       Flags[ID].first = SrcOp;
1692       continue;
1693     }
1694
1695     // Diagnose inconsistent merge behavior types.
1696     if (SrcBehaviorValue != DstBehaviorValue) {
1697       HasErr |= emitError("linking module flags '" + ID->getString() +
1698                           "': IDs have conflicting behaviors");
1699       continue;
1700     }
1701
1702     auto replaceDstValue = [&](MDNode *New) {
1703       Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1704       MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1705       DstModFlags->setOperand(DstIndex, Flag);
1706       Flags[ID].first = Flag;
1707     };
1708
1709     // Perform the merge for standard behavior types.
1710     switch (SrcBehaviorValue) {
1711     case Module::Require:
1712     case Module::Override:
1713       llvm_unreachable("not possible");
1714     case Module::Error: {
1715       // Emit an error if the values differ.
1716       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1717         HasErr |= emitError("linking module flags '" + ID->getString() +
1718                             "': IDs have conflicting values");
1719       }
1720       continue;
1721     }
1722     case Module::Warning: {
1723       // Emit a warning if the values differ.
1724       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1725         emitWarning("linking module flags '" + ID->getString() +
1726                     "': IDs have conflicting values");
1727       }
1728       continue;
1729     }
1730     case Module::Append: {
1731       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1732       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1733       SmallVector<Metadata *, 8> MDs;
1734       MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1735       MDs.append(DstValue->op_begin(), DstValue->op_end());
1736       MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1737
1738       replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1739       break;
1740     }
1741     case Module::AppendUnique: {
1742       SmallSetVector<Metadata *, 16> Elts;
1743       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1744       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1745       Elts.insert(DstValue->op_begin(), DstValue->op_end());
1746       Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1747
1748       replaceDstValue(MDNode::get(DstM.getContext(),
1749                                   makeArrayRef(Elts.begin(), Elts.end())));
1750       break;
1751     }
1752     }
1753   }
1754
1755   // Check all of the requirements.
1756   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1757     MDNode *Requirement = Requirements[I];
1758     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1759     Metadata *ReqValue = Requirement->getOperand(1);
1760
1761     MDNode *Op = Flags[Flag].first;
1762     if (!Op || Op->getOperand(2) != ReqValue) {
1763       HasErr |= emitError("linking module flags '" + Flag->getString() +
1764                           "': does not have the required value");
1765       continue;
1766     }
1767   }
1768
1769   return HasErr;
1770 }
1771
1772 // This function returns true if the triples match.
1773 static bool triplesMatch(const Triple &T0, const Triple &T1) {
1774   // If vendor is apple, ignore the version number.
1775   if (T0.getVendor() == Triple::Apple)
1776     return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1777            T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1778
1779   return T0 == T1;
1780 }
1781
1782 // This function returns the merged triple.
1783 static std::string mergeTriples(const Triple &SrcTriple,
1784                                 const Triple &DstTriple) {
1785   // If vendor is apple, pick the triple with the larger version number.
1786   if (SrcTriple.getVendor() == Triple::Apple)
1787     if (DstTriple.isOSVersionLT(SrcTriple))
1788       return SrcTriple.str();
1789
1790   return DstTriple.str();
1791 }
1792
1793 bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
1794   GlobalValue *DGV = getLinkedToGlobal(&GV);
1795
1796   if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
1797     return false;
1798
1799   if (DGV && !GV.hasLocalLinkage()) {
1800     GlobalValue::VisibilityTypes Visibility =
1801         getMinVisibility(DGV->getVisibility(), GV.getVisibility());
1802     DGV->setVisibility(Visibility);
1803     GV.setVisibility(Visibility);
1804   }
1805
1806   if (const Comdat *SC = GV.getComdat()) {
1807     bool LinkFromSrc;
1808     Comdat::SelectionKind SK;
1809     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1810     if (!LinkFromSrc) {
1811       DoNotLinkFromSource.insert(&GV);
1812       return false;
1813     }
1814   }
1815
1816   if (!DGV && !shouldOverrideFromSrc() &&
1817       (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
1818        GV.hasAvailableExternallyLinkage())) {
1819     return false;
1820   }
1821   MapValue(&GV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1822   return HasError;
1823 }
1824
1825 bool ModuleLinker::run() {
1826   // Inherit the target data from the source module if the destination module
1827   // doesn't have one already.
1828   if (DstM.getDataLayout().isDefault())
1829     DstM.setDataLayout(SrcM.getDataLayout());
1830
1831   if (SrcM.getDataLayout() != DstM.getDataLayout()) {
1832     emitWarning("Linking two modules of different data layouts: '" +
1833                 SrcM.getModuleIdentifier() + "' is '" +
1834                 SrcM.getDataLayoutStr() + "' whereas '" +
1835                 DstM.getModuleIdentifier() + "' is '" +
1836                 DstM.getDataLayoutStr() + "'\n");
1837   }
1838
1839   // Copy the target triple from the source to dest if the dest's is empty.
1840   if (DstM.getTargetTriple().empty() && !SrcM.getTargetTriple().empty())
1841     DstM.setTargetTriple(SrcM.getTargetTriple());
1842
1843   Triple SrcTriple(SrcM.getTargetTriple()), DstTriple(DstM.getTargetTriple());
1844
1845   if (!SrcM.getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
1846     emitWarning("Linking two modules of different target triples: " +
1847                 SrcM.getModuleIdentifier() + "' is '" + SrcM.getTargetTriple() +
1848                 "' whereas '" + DstM.getModuleIdentifier() + "' is '" +
1849                 DstM.getTargetTriple() + "'\n");
1850
1851   DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1852
1853   // Append the module inline asm string.
1854   if (!SrcM.getModuleInlineAsm().empty()) {
1855     if (DstM.getModuleInlineAsm().empty())
1856       DstM.setModuleInlineAsm(SrcM.getModuleInlineAsm());
1857     else
1858       DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
1859                               SrcM.getModuleInlineAsm());
1860   }
1861
1862   // Loop over all of the linked values to compute type mappings.
1863   computeTypeMapping();
1864
1865   ComdatsChosen.clear();
1866   for (const auto &SMEC : SrcM.getComdatSymbolTable()) {
1867     const Comdat &C = SMEC.getValue();
1868     if (ComdatsChosen.count(&C))
1869       continue;
1870     Comdat::SelectionKind SK;
1871     bool LinkFromSrc;
1872     if (getComdatResult(&C, SK, LinkFromSrc))
1873       return true;
1874     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1875   }
1876
1877   // Upgrade mismatched global arrays.
1878   upgradeMismatchedGlobals();
1879
1880   for (GlobalVariable &GV : SrcM.globals())
1881     if (const Comdat *SC = GV.getComdat())
1882       ComdatMembers[SC].push_back(&GV);
1883
1884   for (Function &SF : SrcM)
1885     if (const Comdat *SC = SF.getComdat())
1886       ComdatMembers[SC].push_back(&SF);
1887
1888   for (GlobalAlias &GA : SrcM.aliases())
1889     if (const Comdat *SC = GA.getComdat())
1890       ComdatMembers[SC].push_back(&GA);
1891
1892   // Insert all of the globals in src into the DstM module... without linking
1893   // initializers (which could refer to functions not yet mapped over).
1894   for (GlobalVariable &GV : SrcM.globals())
1895     if (linkIfNeeded(GV))
1896       return true;
1897
1898   for (Function &SF : SrcM)
1899     if (linkIfNeeded(SF))
1900       return true;
1901
1902   for (GlobalAlias &GA : SrcM.aliases())
1903     if (linkIfNeeded(GA))
1904       return true;
1905
1906   for (const auto &Entry : DstM.getComdatSymbolTable()) {
1907     const Comdat &C = Entry.getValue();
1908     if (C.getSelectionKind() == Comdat::Any)
1909       continue;
1910     const GlobalValue *GV = SrcM.getNamedValue(C.getName());
1911     if (GV)
1912       MapValue(GV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1913   }
1914
1915   // Note that we are done linking global value bodies. This prevents
1916   // metadata linking from creating new references.
1917   DoneLinkingBodies = true;
1918
1919   // Remap all of the named MDNodes in Src into the DstM module. We do this
1920   // after linking GlobalValues so that MDNodes that reference GlobalValues
1921   // are properly remapped.
1922   linkNamedMDNodes();
1923
1924   // Merge the module flags into the DstM module.
1925   if (linkModuleFlagsMetadata())
1926     return true;
1927
1928   return false;
1929 }
1930
1931 Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1932     : ETypes(E), IsPacked(P) {}
1933
1934 Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1935     : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1936
1937 bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1938   if (IsPacked != That.IsPacked)
1939     return false;
1940   if (ETypes != That.ETypes)
1941     return false;
1942   return true;
1943 }
1944
1945 bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1946   return !this->operator==(That);
1947 }
1948
1949 StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
1950   return DenseMapInfo<StructType *>::getEmptyKey();
1951 }
1952
1953 StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
1954   return DenseMapInfo<StructType *>::getTombstoneKey();
1955 }
1956
1957 unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1958   return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1959                       Key.IsPacked);
1960 }
1961
1962 unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1963   return getHashValue(KeyTy(ST));
1964 }
1965
1966 bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1967                                         const StructType *RHS) {
1968   if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1969     return false;
1970   return LHS == KeyTy(RHS);
1971 }
1972
1973 bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
1974                                         const StructType *RHS) {
1975   if (RHS == getEmptyKey())
1976     return LHS == getEmptyKey();
1977
1978   if (RHS == getTombstoneKey())
1979     return LHS == getTombstoneKey();
1980
1981   return KeyTy(LHS) == KeyTy(RHS);
1982 }
1983
1984 void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1985   assert(!Ty->isOpaque());
1986   NonOpaqueStructTypes.insert(Ty);
1987 }
1988
1989 void Linker::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1990   assert(!Ty->isOpaque());
1991   NonOpaqueStructTypes.insert(Ty);
1992   bool Removed = OpaqueStructTypes.erase(Ty);
1993   (void)Removed;
1994   assert(Removed);
1995 }
1996
1997 void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1998   assert(Ty->isOpaque());
1999   OpaqueStructTypes.insert(Ty);
2000 }
2001
2002 StructType *
2003 Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
2004                                                bool IsPacked) {
2005   Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
2006   auto I = NonOpaqueStructTypes.find_as(Key);
2007   if (I == NonOpaqueStructTypes.end())
2008     return nullptr;
2009   return *I;
2010 }
2011
2012 bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
2013   if (Ty->isOpaque())
2014     return OpaqueStructTypes.count(Ty);
2015   auto I = NonOpaqueStructTypes.find(Ty);
2016   if (I == NonOpaqueStructTypes.end())
2017     return false;
2018   return *I == Ty;
2019 }
2020
2021 Linker::Linker(Module &M, DiagnosticHandlerFunction DiagnosticHandler)
2022     : Composite(M), DiagnosticHandler(DiagnosticHandler) {
2023   TypeFinder StructTypes;
2024   StructTypes.run(M, true);
2025   for (StructType *Ty : StructTypes) {
2026     if (Ty->isOpaque())
2027       IdentifiedStructTypes.addOpaque(Ty);
2028     else
2029       IdentifiedStructTypes.addNonOpaque(Ty);
2030   }
2031 }
2032
2033 Linker::Linker(Module &M)
2034     : Linker(M, [this](const DiagnosticInfo &DI) {
2035         Composite.getContext().diagnose(DI);
2036       }) {}
2037
2038 bool Linker::linkInModule(Module &Src, unsigned Flags,
2039                           const FunctionInfoIndex *Index,
2040                           Function *FuncToImport) {
2041   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
2042                          DiagnosticHandler, Flags, Index, FuncToImport);
2043   bool RetCode = TheLinker.run();
2044   Composite.dropTriviallyDeadConstantArrays();
2045   return RetCode;
2046 }
2047
2048 //===----------------------------------------------------------------------===//
2049 // LinkModules entrypoint.
2050 //===----------------------------------------------------------------------===//
2051
2052 /// This function links two modules together, with the resulting Dest module
2053 /// modified to be the composite of the two input modules. If an error occurs,
2054 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
2055 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
2056 /// relied on to be consistent.
2057 bool Linker::linkModules(Module &Dest, Module &Src,
2058                          DiagnosticHandlerFunction DiagnosticHandler,
2059                          unsigned Flags) {
2060   Linker L(Dest, DiagnosticHandler);
2061   return L.linkInModule(Src, Flags);
2062 }
2063
2064 bool Linker::linkModules(Module &Dest, Module &Src, unsigned Flags) {
2065   Linker L(Dest);
2066   return L.linkInModule(Src, Flags);
2067 }
2068
2069 //===----------------------------------------------------------------------===//
2070 // C API.
2071 //===----------------------------------------------------------------------===//
2072
2073 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
2074                          LLVMLinkerMode Unused, char **OutMessages) {
2075   Module *D = unwrap(Dest);
2076   std::string Message;
2077   raw_string_ostream Stream(Message);
2078   DiagnosticPrinterRawOStream DP(Stream);
2079
2080   LLVMBool Result = Linker::linkModules(
2081       *D, *unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
2082
2083   if (OutMessages && Result) {
2084     Stream.flush();
2085     *OutMessages = strdup(Message.c_str());
2086   }
2087   return Result;
2088 }