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