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