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