1 //===- lib/Linker/IRMover.cpp ---------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/Linker/IRMover.h"
10 #include "LinkDiagnosticInfo.h"
11 #include "llvm/ADT/SetVector.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/Triple.h"
14 #include "llvm/IR/Constants.h"
15 #include "llvm/IR/DebugInfo.h"
16 #include "llvm/IR/DiagnosticPrinter.h"
17 #include "llvm/IR/GVMaterializer.h"
18 #include "llvm/IR/Intrinsics.h"
19 #include "llvm/IR/TypeFinder.h"
20 #include "llvm/Support/Error.h"
21 #include "llvm/Transforms/Utils/Cloning.h"
22 #include <utility>
23 using namespace llvm;
24 
25 //===----------------------------------------------------------------------===//
26 // TypeMap implementation.
27 //===----------------------------------------------------------------------===//
28 
29 namespace {
30 class TypeMapTy : public ValueMapTypeRemapper {
31   /// This is a mapping from a source type to a destination type to use.
32   DenseMap<Type *, Type *> MappedTypes;
33 
34   /// When checking to see if two subgraphs are isomorphic, we speculatively
35   /// add types to MappedTypes, but keep track of them here in case we need to
36   /// roll back.
37   SmallVector<Type *, 16> SpeculativeTypes;
38 
39   SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
40 
41   /// This is a list of non-opaque structs in the source module that are mapped
42   /// to an opaque struct in the destination module.
43   SmallVector<StructType *, 16> SrcDefinitionsToResolve;
44 
45   /// This is the set of opaque types in the destination modules who are
46   /// getting a body from the source module.
47   SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
48 
49 public:
50   TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet)
51       : DstStructTypesSet(DstStructTypesSet) {}
52 
53   IRMover::IdentifiedStructTypeSet &DstStructTypesSet;
54   /// Indicate that the specified type in the destination module is conceptually
55   /// equivalent to the specified type in the source module.
56   void addTypeMapping(Type *DstTy, Type *SrcTy);
57 
58   /// Produce a body for an opaque type in the dest module from a type
59   /// definition in the source module.
60   void linkDefinedTypeBodies();
61 
62   /// Return the mapped type to use for the specified input type from the
63   /// source module.
64   Type *get(Type *SrcTy);
65   Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
66 
67   void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
68 
69   FunctionType *get(FunctionType *T) {
70     return cast<FunctionType>(get((Type *)T));
71   }
72 
73 private:
74   Type *remapType(Type *SrcTy) override { return get(SrcTy); }
75 
76   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
77 };
78 }
79 
80 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
81   assert(SpeculativeTypes.empty());
82   assert(SpeculativeDstOpaqueTypes.empty());
83 
84   // Check to see if these types are recursively isomorphic and establish a
85   // mapping between them if so.
86   if (!areTypesIsomorphic(DstTy, SrcTy)) {
87     // Oops, they aren't isomorphic.  Just discard this request by rolling out
88     // any speculative mappings we've established.
89     for (Type *Ty : SpeculativeTypes)
90       MappedTypes.erase(Ty);
91 
92     SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
93                                    SpeculativeDstOpaqueTypes.size());
94     for (StructType *Ty : SpeculativeDstOpaqueTypes)
95       DstResolvedOpaqueTypes.erase(Ty);
96   } else {
97     // SrcTy and DstTy are recursively ismorphic. We clear names of SrcTy
98     // and all its descendants to lower amount of renaming in LLVM context
99     // Renaming occurs because we load all source modules to the same context
100     // and declaration with existing name gets renamed (i.e Foo -> Foo.42).
101     // As a result we may get several different types in the destination
102     // module, which are in fact the same.
103     for (Type *Ty : SpeculativeTypes)
104       if (auto *STy = dyn_cast<StructType>(Ty))
105         if (STy->hasName())
106           STy->setName("");
107   }
108   SpeculativeTypes.clear();
109   SpeculativeDstOpaqueTypes.clear();
110 }
111 
112 /// Recursively walk this pair of types, returning true if they are isomorphic,
113 /// false if they are not.
114 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
115   // Two types with differing kinds are clearly not isomorphic.
116   if (DstTy->getTypeID() != SrcTy->getTypeID())
117     return false;
118 
119   // If we have an entry in the MappedTypes table, then we have our answer.
120   Type *&Entry = MappedTypes[SrcTy];
121   if (Entry)
122     return Entry == DstTy;
123 
124   // Two identical types are clearly isomorphic.  Remember this
125   // non-speculatively.
126   if (DstTy == SrcTy) {
127     Entry = DstTy;
128     return true;
129   }
130 
131   // Okay, we have two types with identical kinds that we haven't seen before.
132 
133   // If this is an opaque struct type, special case it.
134   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
135     // Mapping an opaque type to any struct, just keep the dest struct.
136     if (SSTy->isOpaque()) {
137       Entry = DstTy;
138       SpeculativeTypes.push_back(SrcTy);
139       return true;
140     }
141 
142     // Mapping a non-opaque source type to an opaque dest.  If this is the first
143     // type that we're mapping onto this destination type then we succeed.  Keep
144     // the dest, but fill it in later. If this is the second (different) type
145     // that we're trying to map onto the same opaque type then we fail.
146     if (cast<StructType>(DstTy)->isOpaque()) {
147       // We can only map one source type onto the opaque destination type.
148       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
149         return false;
150       SrcDefinitionsToResolve.push_back(SSTy);
151       SpeculativeTypes.push_back(SrcTy);
152       SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
153       Entry = DstTy;
154       return true;
155     }
156   }
157 
158   // If the number of subtypes disagree between the two types, then we fail.
159   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
160     return false;
161 
162   // Fail if any of the extra properties (e.g. array size) of the type disagree.
163   if (isa<IntegerType>(DstTy))
164     return false; // bitwidth disagrees.
165   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
166     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
167       return false;
168   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
169     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
170       return false;
171   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
172     StructType *SSTy = cast<StructType>(SrcTy);
173     if (DSTy->isLiteral() != SSTy->isLiteral() ||
174         DSTy->isPacked() != SSTy->isPacked())
175       return false;
176   } else if (auto *DArrTy = dyn_cast<ArrayType>(DstTy)) {
177     if (DArrTy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
178       return false;
179   } else if (auto *DVecTy = dyn_cast<VectorType>(DstTy)) {
180     if (DVecTy->getElementCount() != cast<VectorType>(SrcTy)->getElementCount())
181       return false;
182   }
183 
184   // Otherwise, we speculate that these two types will line up and recursively
185   // check the subelements.
186   Entry = DstTy;
187   SpeculativeTypes.push_back(SrcTy);
188 
189   for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
190     if (!areTypesIsomorphic(DstTy->getContainedType(I),
191                             SrcTy->getContainedType(I)))
192       return false;
193 
194   // If everything seems to have lined up, then everything is great.
195   return true;
196 }
197 
198 void TypeMapTy::linkDefinedTypeBodies() {
199   SmallVector<Type *, 16> Elements;
200   for (StructType *SrcSTy : SrcDefinitionsToResolve) {
201     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
202     assert(DstSTy->isOpaque());
203 
204     // Map the body of the source type over to a new body for the dest type.
205     Elements.resize(SrcSTy->getNumElements());
206     for (unsigned I = 0, E = Elements.size(); I != E; ++I)
207       Elements[I] = get(SrcSTy->getElementType(I));
208 
209     DstSTy->setBody(Elements, SrcSTy->isPacked());
210     DstStructTypesSet.switchToNonOpaque(DstSTy);
211   }
212   SrcDefinitionsToResolve.clear();
213   DstResolvedOpaqueTypes.clear();
214 }
215 
216 void TypeMapTy::finishType(StructType *DTy, StructType *STy,
217                            ArrayRef<Type *> ETypes) {
218   DTy->setBody(ETypes, STy->isPacked());
219 
220   // Steal STy's name.
221   if (STy->hasName()) {
222     SmallString<16> TmpName = STy->getName();
223     STy->setName("");
224     DTy->setName(TmpName);
225   }
226 
227   DstStructTypesSet.addNonOpaque(DTy);
228 }
229 
230 Type *TypeMapTy::get(Type *Ty) {
231   SmallPtrSet<StructType *, 8> Visited;
232   return get(Ty, Visited);
233 }
234 
235 Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
236   // If we already have an entry for this type, return it.
237   Type **Entry = &MappedTypes[Ty];
238   if (*Entry)
239     return *Entry;
240 
241   // These are types that LLVM itself will unique.
242   bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
243 
244   if (!IsUniqued) {
245     StructType *STy = cast<StructType>(Ty);
246     // This is actually a type from the destination module, this can be reached
247     // when this type is loaded in another module, added to DstStructTypesSet,
248     // and then we reach the same type in another module where it has not been
249     // added to MappedTypes. (PR37684)
250     if (STy->getContext().isODRUniquingDebugTypes() && !STy->isOpaque() &&
251         DstStructTypesSet.hasType(STy))
252       return *Entry = STy;
253 
254 #ifndef NDEBUG
255     for (auto &Pair : MappedTypes) {
256       assert(!(Pair.first != Ty && Pair.second == Ty) &&
257              "mapping to a source type");
258     }
259 #endif
260 
261     if (!Visited.insert(STy).second) {
262       StructType *DTy = StructType::create(Ty->getContext());
263       return *Entry = DTy;
264     }
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 named 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 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
349                                        const Twine &Msg)
350     : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
351 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
352 
353 //===----------------------------------------------------------------------===//
354 // IRLinker implementation.
355 //===----------------------------------------------------------------------===//
356 
357 namespace {
358 class IRLinker;
359 
360 /// Creates prototypes for functions that are lazily linked on the fly. This
361 /// speeds up linking for modules with many/ lazily linked functions of which
362 /// few get used.
363 class GlobalValueMaterializer final : public ValueMaterializer {
364   IRLinker &TheIRLinker;
365 
366 public:
367   GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
368   Value *materialize(Value *V) override;
369 };
370 
371 class LocalValueMaterializer final : public ValueMaterializer {
372   IRLinker &TheIRLinker;
373 
374 public:
375   LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
376   Value *materialize(Value *V) override;
377 };
378 
379 /// Type of the Metadata map in \a ValueToValueMapTy.
380 typedef DenseMap<const Metadata *, TrackingMDRef> MDMapT;
381 
382 /// This is responsible for keeping track of the state used for moving data
383 /// from SrcM to DstM.
384 class IRLinker {
385   Module &DstM;
386   std::unique_ptr<Module> SrcM;
387 
388   /// See IRMover::move().
389   std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor;
390 
391   TypeMapTy TypeMap;
392   GlobalValueMaterializer GValMaterializer;
393   LocalValueMaterializer LValMaterializer;
394 
395   /// A metadata map that's shared between IRLinker instances.
396   MDMapT &SharedMDs;
397 
398   /// Mapping of values from what they used to be in Src, to what they are now
399   /// in DstM.  ValueToValueMapTy is a ValueMap, which involves some overhead
400   /// due to the use of Value handles which the Linker doesn't actually need,
401   /// but this allows us to reuse the ValueMapper code.
402   ValueToValueMapTy ValueMap;
403   ValueToValueMapTy IndirectSymbolValueMap;
404 
405   DenseSet<GlobalValue *> ValuesToLink;
406   std::vector<GlobalValue *> Worklist;
407   std::vector<std::pair<GlobalValue *, Value*>> RAUWWorklist;
408 
409   void maybeAdd(GlobalValue *GV) {
410     if (ValuesToLink.insert(GV).second)
411       Worklist.push_back(GV);
412   }
413 
414   /// Whether we are importing globals for ThinLTO, as opposed to linking the
415   /// source module. If this flag is set, it means that we can rely on some
416   /// other object file to define any non-GlobalValue entities defined by the
417   /// source module. This currently causes us to not link retained types in
418   /// debug info metadata and module inline asm.
419   bool IsPerformingImport;
420 
421   /// Set to true when all global value body linking is complete (including
422   /// lazy linking). Used to prevent metadata linking from creating new
423   /// references.
424   bool DoneLinkingBodies = false;
425 
426   /// The Error encountered during materialization. We use an Optional here to
427   /// avoid needing to manage an unconsumed success value.
428   Optional<Error> FoundError;
429   void setError(Error E) {
430     if (E)
431       FoundError = std::move(E);
432   }
433 
434   /// Most of the errors produced by this module are inconvertible StringErrors.
435   /// This convenience function lets us return one of those more easily.
436   Error stringErr(const Twine &T) {
437     return make_error<StringError>(T, inconvertibleErrorCode());
438   }
439 
440   /// Entry point for mapping values and alternate context for mapping aliases.
441   ValueMapper Mapper;
442   unsigned IndirectSymbolMCID;
443 
444   /// Handles cloning of a global values from the source module into
445   /// the destination module, including setting the attributes and visibility.
446   GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
447 
448   void emitWarning(const Twine &Message) {
449     SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
450   }
451 
452   /// Given a global in the source module, return the global in the
453   /// destination module that is being linked to, if any.
454   GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
455     // If the source has no name it can't link.  If it has local linkage,
456     // there is no name match-up going on.
457     if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
458       return nullptr;
459 
460     // Otherwise see if we have a match in the destination module's symtab.
461     GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
462     if (!DGV)
463       return nullptr;
464 
465     // If we found a global with the same name in the dest module, but it has
466     // internal linkage, we are really not doing any linkage here.
467     if (DGV->hasLocalLinkage())
468       return nullptr;
469 
470     // Otherwise, we do in fact link to the destination global.
471     return DGV;
472   }
473 
474   void computeTypeMapping();
475 
476   Expected<Constant *> linkAppendingVarProto(GlobalVariable *DstGV,
477                                              const GlobalVariable *SrcGV);
478 
479   /// Given the GlobaValue \p SGV in the source module, and the matching
480   /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV
481   /// into the destination module.
482   ///
483   /// Note this code may call the client-provided \p AddLazyFor.
484   bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
485   Expected<Constant *> linkGlobalValueProto(GlobalValue *GV,
486                                             bool ForIndirectSymbol);
487 
488   Error linkModuleFlagsMetadata();
489 
490   void linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src);
491   Error linkFunctionBody(Function &Dst, Function &Src);
492   void linkIndirectSymbolBody(GlobalIndirectSymbol &Dst,
493                               GlobalIndirectSymbol &Src);
494   Error linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
495 
496   /// Replace all types in the source AttributeList with the
497   /// corresponding destination type.
498   AttributeList mapAttributeTypes(LLVMContext &C, AttributeList Attrs);
499 
500   /// Functions that take care of cloning a specific global value type
501   /// into the destination module.
502   GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
503   Function *copyFunctionProto(const Function *SF);
504   GlobalValue *copyGlobalIndirectSymbolProto(const GlobalIndirectSymbol *SGIS);
505 
506   /// Perform "replace all uses with" operations. These work items need to be
507   /// performed as part of materialization, but we postpone them to happen after
508   /// materialization is done. The materializer called by ValueMapper is not
509   /// expected to delete constants, as ValueMapper is holding pointers to some
510   /// of them, but constant destruction may be indirectly triggered by RAUW.
511   /// Hence, the need to move this out of the materialization call chain.
512   void flushRAUWWorklist();
513 
514   /// When importing for ThinLTO, prevent importing of types listed on
515   /// the DICompileUnit that we don't need a copy of in the importing
516   /// module.
517   void prepareCompileUnitsForImport();
518   void linkNamedMDNodes();
519 
520 public:
521   IRLinker(Module &DstM, MDMapT &SharedMDs,
522            IRMover::IdentifiedStructTypeSet &Set, std::unique_ptr<Module> SrcM,
523            ArrayRef<GlobalValue *> ValuesToLink,
524            std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor,
525            bool IsPerformingImport)
526       : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(std::move(AddLazyFor)),
527         TypeMap(Set), GValMaterializer(*this), LValMaterializer(*this),
528         SharedMDs(SharedMDs), IsPerformingImport(IsPerformingImport),
529         Mapper(ValueMap, RF_MoveDistinctMDs | RF_IgnoreMissingLocals, &TypeMap,
530                &GValMaterializer),
531         IndirectSymbolMCID(Mapper.registerAlternateMappingContext(
532             IndirectSymbolValueMap, &LValMaterializer)) {
533     ValueMap.getMDMap() = std::move(SharedMDs);
534     for (GlobalValue *GV : ValuesToLink)
535       maybeAdd(GV);
536     if (IsPerformingImport)
537       prepareCompileUnitsForImport();
538   }
539   ~IRLinker() { SharedMDs = std::move(*ValueMap.getMDMap()); }
540 
541   Error run();
542   Value *materialize(Value *V, bool ForIndirectSymbol);
543 };
544 }
545 
546 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
547 /// table. This is good for all clients except for us. Go through the trouble
548 /// to force this back.
549 static void forceRenaming(GlobalValue *GV, StringRef Name) {
550   // If the global doesn't force its name or if it already has the right name,
551   // there is nothing for us to do.
552   if (GV->hasLocalLinkage() || GV->getName() == Name)
553     return;
554 
555   Module *M = GV->getParent();
556 
557   // If there is a conflict, rename the conflict.
558   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
559     GV->takeName(ConflictGV);
560     ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
561     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
562   } else {
563     GV->setName(Name); // Force the name back
564   }
565 }
566 
567 Value *GlobalValueMaterializer::materialize(Value *SGV) {
568   return TheIRLinker.materialize(SGV, false);
569 }
570 
571 Value *LocalValueMaterializer::materialize(Value *SGV) {
572   return TheIRLinker.materialize(SGV, true);
573 }
574 
575 Value *IRLinker::materialize(Value *V, bool ForIndirectSymbol) {
576   auto *SGV = dyn_cast<GlobalValue>(V);
577   if (!SGV)
578     return nullptr;
579 
580   Expected<Constant *> NewProto = linkGlobalValueProto(SGV, ForIndirectSymbol);
581   if (!NewProto) {
582     setError(NewProto.takeError());
583     return nullptr;
584   }
585   if (!*NewProto)
586     return nullptr;
587 
588   GlobalValue *New = dyn_cast<GlobalValue>(*NewProto);
589   if (!New)
590     return *NewProto;
591 
592   // If we already created the body, just return.
593   if (auto *F = dyn_cast<Function>(New)) {
594     if (!F->isDeclaration())
595       return New;
596   } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
597     if (V->hasInitializer() || V->hasAppendingLinkage())
598       return New;
599   } else {
600     auto *IS = cast<GlobalIndirectSymbol>(New);
601     if (IS->getIndirectSymbol())
602       return New;
603   }
604 
605   // When linking a global for an indirect symbol, it will always be linked.
606   // However we need to check if it was not already scheduled to satisfy a
607   // reference from a regular global value initializer. We know if it has been
608   // schedule if the "New" GlobalValue that is mapped here for the indirect
609   // symbol is the same as the one already mapped. If there is an entry in the
610   // ValueMap but the value is different, it means that the value already had a
611   // definition in the destination module (linkonce for instance), but we need a
612   // new definition for the indirect symbol ("New" will be different.
613   if (ForIndirectSymbol && ValueMap.lookup(SGV) == New)
614     return New;
615 
616   if (ForIndirectSymbol || shouldLink(New, *SGV))
617     setError(linkGlobalValueBody(*New, *SGV));
618 
619   return New;
620 }
621 
622 /// Loop through the global variables in the src module and merge them into the
623 /// dest module.
624 GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
625   // No linking to be performed or linking from the source: simply create an
626   // identical version of the symbol over in the dest module... the
627   // initializer will be filled in later by LinkGlobalInits.
628   GlobalVariable *NewDGV =
629       new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()),
630                          SGVar->isConstant(), GlobalValue::ExternalLinkage,
631                          /*init*/ nullptr, SGVar->getName(),
632                          /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
633                          SGVar->getAddressSpace());
634   NewDGV->setAlignment(MaybeAlign(SGVar->getAlignment()));
635   NewDGV->copyAttributesFrom(SGVar);
636   return NewDGV;
637 }
638 
639 AttributeList IRLinker::mapAttributeTypes(LLVMContext &C, AttributeList Attrs) {
640   for (unsigned i = 0; i < Attrs.getNumAttrSets(); ++i) {
641     if (Attrs.hasAttribute(i, Attribute::ByVal)) {
642       Type *Ty = Attrs.getAttribute(i, Attribute::ByVal).getValueAsType();
643       if (!Ty)
644         continue;
645 
646       Attrs = Attrs.removeAttribute(C, i, Attribute::ByVal);
647       Attrs = Attrs.addAttribute(
648           C, i, Attribute::getWithByValType(C, TypeMap.get(Ty)));
649     }
650   }
651   return Attrs;
652 }
653 
654 /// Link the function in the source module into the destination module if
655 /// needed, setting up mapping information.
656 Function *IRLinker::copyFunctionProto(const Function *SF) {
657   // If there is no linkage to be performed or we are linking from the source,
658   // bring SF over.
659   auto *F = Function::Create(TypeMap.get(SF->getFunctionType()),
660                              GlobalValue::ExternalLinkage,
661                              SF->getAddressSpace(), SF->getName(), &DstM);
662   F->copyAttributesFrom(SF);
663   F->setAttributes(mapAttributeTypes(F->getContext(), F->getAttributes()));
664   return F;
665 }
666 
667 /// Set up prototypes for any indirect symbols that come over from the source
668 /// module.
669 GlobalValue *
670 IRLinker::copyGlobalIndirectSymbolProto(const GlobalIndirectSymbol *SGIS) {
671   // If there is no linkage to be performed or we're linking from the source,
672   // bring over SGA.
673   auto *Ty = TypeMap.get(SGIS->getValueType());
674   GlobalIndirectSymbol *GIS;
675   if (isa<GlobalAlias>(SGIS))
676     GIS = GlobalAlias::create(Ty, SGIS->getAddressSpace(),
677                               GlobalValue::ExternalLinkage, SGIS->getName(),
678                               &DstM);
679   else
680     GIS = GlobalIFunc::create(Ty, SGIS->getAddressSpace(),
681                               GlobalValue::ExternalLinkage, SGIS->getName(),
682                               nullptr, &DstM);
683   GIS->copyAttributesFrom(SGIS);
684   return GIS;
685 }
686 
687 GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
688                                             bool ForDefinition) {
689   GlobalValue *NewGV;
690   if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
691     NewGV = copyGlobalVariableProto(SGVar);
692   } else if (auto *SF = dyn_cast<Function>(SGV)) {
693     NewGV = copyFunctionProto(SF);
694   } else {
695     if (ForDefinition)
696       NewGV = copyGlobalIndirectSymbolProto(cast<GlobalIndirectSymbol>(SGV));
697     else if (SGV->getValueType()->isFunctionTy())
698       NewGV =
699           Function::Create(cast<FunctionType>(TypeMap.get(SGV->getValueType())),
700                            GlobalValue::ExternalLinkage, SGV->getAddressSpace(),
701                            SGV->getName(), &DstM);
702     else
703       NewGV =
704           new GlobalVariable(DstM, TypeMap.get(SGV->getValueType()),
705                              /*isConstant*/ false, GlobalValue::ExternalLinkage,
706                              /*init*/ nullptr, SGV->getName(),
707                              /*insertbefore*/ nullptr,
708                              SGV->getThreadLocalMode(), SGV->getAddressSpace());
709   }
710 
711   if (ForDefinition)
712     NewGV->setLinkage(SGV->getLinkage());
713   else if (SGV->hasExternalWeakLinkage())
714     NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
715 
716   if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
717     // Metadata for global variables and function declarations is copied eagerly.
718     if (isa<GlobalVariable>(SGV) || SGV->isDeclaration())
719       NewGO->copyMetadata(cast<GlobalObject>(SGV), 0);
720   }
721 
722   // Remove these copied constants in case this stays a declaration, since
723   // they point to the source module. If the def is linked the values will
724   // be mapped in during linkFunctionBody.
725   if (auto *NewF = dyn_cast<Function>(NewGV)) {
726     NewF->setPersonalityFn(nullptr);
727     NewF->setPrefixData(nullptr);
728     NewF->setPrologueData(nullptr);
729   }
730 
731   return NewGV;
732 }
733 
734 static StringRef getTypeNamePrefix(StringRef Name) {
735   size_t DotPos = Name.rfind('.');
736   return (DotPos == 0 || DotPos == StringRef::npos || Name.back() == '.' ||
737           !isdigit(static_cast<unsigned char>(Name[DotPos + 1])))
738              ? Name
739              : Name.substr(0, DotPos);
740 }
741 
742 /// Loop over all of the linked values to compute type mappings.  For example,
743 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
744 /// types 'Foo' but one got renamed when the module was loaded into the same
745 /// LLVMContext.
746 void IRLinker::computeTypeMapping() {
747   for (GlobalValue &SGV : SrcM->globals()) {
748     GlobalValue *DGV = getLinkedToGlobal(&SGV);
749     if (!DGV)
750       continue;
751 
752     if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
753       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
754       continue;
755     }
756 
757     // Unify the element type of appending arrays.
758     ArrayType *DAT = cast<ArrayType>(DGV->getValueType());
759     ArrayType *SAT = cast<ArrayType>(SGV.getValueType());
760     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
761   }
762 
763   for (GlobalValue &SGV : *SrcM)
764     if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) {
765       if (DGV->getType() == SGV.getType()) {
766         // If the types of DGV and SGV are the same, it means that DGV is from
767         // the source module and got added to DstM from a shared metadata.  We
768         // shouldn't map this type to itself in case the type's components get
769         // remapped to a new type from DstM (for instance, during the loop over
770         // SrcM->getIdentifiedStructTypes() below).
771         continue;
772       }
773 
774       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
775     }
776 
777   for (GlobalValue &SGV : SrcM->aliases())
778     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
779       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
780 
781   // Incorporate types by name, scanning all the types in the source module.
782   // At this point, the destination module may have a type "%foo = { i32 }" for
783   // example.  When the source module got loaded into the same LLVMContext, if
784   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
785   std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
786   for (StructType *ST : Types) {
787     if (!ST->hasName())
788       continue;
789 
790     if (TypeMap.DstStructTypesSet.hasType(ST)) {
791       // This is actually a type from the destination module.
792       // getIdentifiedStructTypes() can have found it by walking debug info
793       // metadata nodes, some of which get linked by name when ODR Type Uniquing
794       // is enabled on the Context, from the source to the destination module.
795       continue;
796     }
797 
798     auto STTypePrefix = getTypeNamePrefix(ST->getName());
799     if (STTypePrefix.size()== ST->getName().size())
800       continue;
801 
802     // Check to see if the destination module has a struct with the prefix name.
803     StructType *DST = DstM.getTypeByName(STTypePrefix);
804     if (!DST)
805       continue;
806 
807     // Don't use it if this actually came from the source module. They're in
808     // the same LLVMContext after all. Also don't use it unless the type is
809     // actually used in the destination module. This can happen in situations
810     // like this:
811     //
812     //      Module A                         Module B
813     //      --------                         --------
814     //   %Z = type { %A }                %B = type { %C.1 }
815     //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
816     //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
817     //   %C = type { i8* }               %B.3 = type { %C.1 }
818     //
819     // When we link Module B with Module A, the '%B' in Module B is
820     // used. However, that would then use '%C.1'. But when we process '%C.1',
821     // we prefer to take the '%C' version. So we are then left with both
822     // '%C.1' and '%C' being used for the same types. This leads to some
823     // variables using one type and some using the other.
824     if (TypeMap.DstStructTypesSet.hasType(DST))
825       TypeMap.addTypeMapping(DST, ST);
826   }
827 
828   // Now that we have discovered all of the type equivalences, get a body for
829   // any 'opaque' types in the dest module that are now resolved.
830   TypeMap.linkDefinedTypeBodies();
831 }
832 
833 static void getArrayElements(const Constant *C,
834                              SmallVectorImpl<Constant *> &Dest) {
835   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
836 
837   for (unsigned i = 0; i != NumElements; ++i)
838     Dest.push_back(C->getAggregateElement(i));
839 }
840 
841 /// If there were any appending global variables, link them together now.
842 Expected<Constant *>
843 IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
844                                 const GlobalVariable *SrcGV) {
845   Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
846                     ->getElementType();
847 
848   // FIXME: This upgrade is done during linking to support the C API.  Once the
849   // old form is deprecated, we should move this upgrade to
850   // llvm::UpgradeGlobalVariable() and simplify the logic here and in
851   // Mapper::mapAppendingVariable() in ValueMapper.cpp.
852   StringRef Name = SrcGV->getName();
853   bool IsNewStructor = false;
854   bool IsOldStructor = false;
855   if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
856     if (cast<StructType>(EltTy)->getNumElements() == 3)
857       IsNewStructor = true;
858     else
859       IsOldStructor = true;
860   }
861 
862   PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
863   if (IsOldStructor) {
864     auto &ST = *cast<StructType>(EltTy);
865     Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
866     EltTy = StructType::get(SrcGV->getContext(), Tys, false);
867   }
868 
869   uint64_t DstNumElements = 0;
870   if (DstGV) {
871     ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
872     DstNumElements = DstTy->getNumElements();
873 
874     if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
875       return stringErr(
876           "Linking globals named '" + SrcGV->getName() +
877           "': can only link appending global with another appending "
878           "global!");
879 
880     // Check to see that they two arrays agree on type.
881     if (EltTy != DstTy->getElementType())
882       return stringErr("Appending variables with different element types!");
883     if (DstGV->isConstant() != SrcGV->isConstant())
884       return stringErr("Appending variables linked with different const'ness!");
885 
886     if (DstGV->getAlignment() != SrcGV->getAlignment())
887       return stringErr(
888           "Appending variables with different alignment need to be linked!");
889 
890     if (DstGV->getVisibility() != SrcGV->getVisibility())
891       return stringErr(
892           "Appending variables with different visibility need to be linked!");
893 
894     if (DstGV->hasGlobalUnnamedAddr() != SrcGV->hasGlobalUnnamedAddr())
895       return stringErr(
896           "Appending variables with different unnamed_addr need to be linked!");
897 
898     if (DstGV->getSection() != SrcGV->getSection())
899       return stringErr(
900           "Appending variables with different section name need to be linked!");
901   }
902 
903   SmallVector<Constant *, 16> SrcElements;
904   getArrayElements(SrcGV->getInitializer(), SrcElements);
905 
906   if (IsNewStructor) {
907     auto It = remove_if(SrcElements, [this](Constant *E) {
908       auto *Key =
909           dyn_cast<GlobalValue>(E->getAggregateElement(2)->stripPointerCasts());
910       if (!Key)
911         return false;
912       GlobalValue *DGV = getLinkedToGlobal(Key);
913       return !shouldLink(DGV, *Key);
914     });
915     SrcElements.erase(It, SrcElements.end());
916   }
917   uint64_t NewSize = DstNumElements + SrcElements.size();
918   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
919 
920   // Create the new global variable.
921   GlobalVariable *NG = new GlobalVariable(
922       DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
923       /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
924       SrcGV->getAddressSpace());
925 
926   NG->copyAttributesFrom(SrcGV);
927   forceRenaming(NG, SrcGV->getName());
928 
929   Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
930 
931   Mapper.scheduleMapAppendingVariable(*NG,
932                                       DstGV ? DstGV->getInitializer() : nullptr,
933                                       IsOldStructor, SrcElements);
934 
935   // Replace any uses of the two global variables with uses of the new
936   // global.
937   if (DstGV) {
938     RAUWWorklist.push_back(
939         std::make_pair(DstGV, ConstantExpr::getBitCast(NG, DstGV->getType())));
940   }
941 
942   return Ret;
943 }
944 
945 bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
946   if (ValuesToLink.count(&SGV) || SGV.hasLocalLinkage())
947     return true;
948 
949   if (DGV && !DGV->isDeclarationForLinker())
950     return false;
951 
952   if (SGV.isDeclaration() || DoneLinkingBodies)
953     return false;
954 
955   // Callback to the client to give a chance to lazily add the Global to the
956   // list of value to link.
957   bool LazilyAdded = false;
958   AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) {
959     maybeAdd(&GV);
960     LazilyAdded = true;
961   });
962   return LazilyAdded;
963 }
964 
965 Expected<Constant *> IRLinker::linkGlobalValueProto(GlobalValue *SGV,
966                                                     bool ForIndirectSymbol) {
967   GlobalValue *DGV = getLinkedToGlobal(SGV);
968 
969   bool ShouldLink = shouldLink(DGV, *SGV);
970 
971   // just missing from map
972   if (ShouldLink) {
973     auto I = ValueMap.find(SGV);
974     if (I != ValueMap.end())
975       return cast<Constant>(I->second);
976 
977     I = IndirectSymbolValueMap.find(SGV);
978     if (I != IndirectSymbolValueMap.end())
979       return cast<Constant>(I->second);
980   }
981 
982   if (!ShouldLink && ForIndirectSymbol)
983     DGV = nullptr;
984 
985   // Handle the ultra special appending linkage case first.
986   assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
987   if (SGV->hasAppendingLinkage())
988     return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
989                                  cast<GlobalVariable>(SGV));
990 
991   GlobalValue *NewGV;
992   if (DGV && !ShouldLink) {
993     NewGV = DGV;
994   } else {
995     // If we are done linking global value bodies (i.e. we are performing
996     // metadata linking), don't link in the global value due to this
997     // reference, simply map it to null.
998     if (DoneLinkingBodies)
999       return nullptr;
1000 
1001     NewGV = copyGlobalValueProto(SGV, ShouldLink || ForIndirectSymbol);
1002     if (ShouldLink || !ForIndirectSymbol)
1003       forceRenaming(NewGV, SGV->getName());
1004   }
1005 
1006   // Overloaded intrinsics have overloaded types names as part of their
1007   // names. If we renamed overloaded types we should rename the intrinsic
1008   // as well.
1009   if (Function *F = dyn_cast<Function>(NewGV))
1010     if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F))
1011       NewGV = Remangled.getValue();
1012 
1013   if (ShouldLink || ForIndirectSymbol) {
1014     if (const Comdat *SC = SGV->getComdat()) {
1015       if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
1016         Comdat *DC = DstM.getOrInsertComdat(SC->getName());
1017         DC->setSelectionKind(SC->getSelectionKind());
1018         GO->setComdat(DC);
1019       }
1020     }
1021   }
1022 
1023   if (!ShouldLink && ForIndirectSymbol)
1024     NewGV->setLinkage(GlobalValue::InternalLinkage);
1025 
1026   Constant *C = NewGV;
1027   // Only create a bitcast if necessary. In particular, with
1028   // DebugTypeODRUniquing we may reach metadata in the destination module
1029   // containing a GV from the source module, in which case SGV will be
1030   // the same as DGV and NewGV, and TypeMap.get() will assert since it
1031   // assumes it is being invoked on a type in the source module.
1032   if (DGV && NewGV != SGV) {
1033     C = ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1034       NewGV, TypeMap.get(SGV->getType()));
1035   }
1036 
1037   if (DGV && NewGV != DGV) {
1038     // Schedule "replace all uses with" to happen after materializing is
1039     // done. It is not safe to do it now, since ValueMapper may be holding
1040     // pointers to constants that will get deleted if RAUW runs.
1041     RAUWWorklist.push_back(std::make_pair(
1042         DGV,
1043         ConstantExpr::getPointerBitCastOrAddrSpaceCast(NewGV, DGV->getType())));
1044   }
1045 
1046   return C;
1047 }
1048 
1049 /// Update the initializers in the Dest module now that all globals that may be
1050 /// referenced are in Dest.
1051 void IRLinker::linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src) {
1052   // Figure out what the initializer looks like in the dest module.
1053   Mapper.scheduleMapGlobalInitializer(Dst, *Src.getInitializer());
1054 }
1055 
1056 /// Copy the source function over into the dest function and fix up references
1057 /// to values. At this point we know that Dest is an external function, and
1058 /// that Src is not.
1059 Error IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
1060   assert(Dst.isDeclaration() && !Src.isDeclaration());
1061 
1062   // Materialize if needed.
1063   if (Error Err = Src.materialize())
1064     return Err;
1065 
1066   // Link in the operands without remapping.
1067   if (Src.hasPrefixData())
1068     Dst.setPrefixData(Src.getPrefixData());
1069   if (Src.hasPrologueData())
1070     Dst.setPrologueData(Src.getPrologueData());
1071   if (Src.hasPersonalityFn())
1072     Dst.setPersonalityFn(Src.getPersonalityFn());
1073 
1074   // Copy over the metadata attachments without remapping.
1075   Dst.copyMetadata(&Src, 0);
1076 
1077   // Steal arguments and splice the body of Src into Dst.
1078   Dst.stealArgumentListFrom(Src);
1079   Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
1080 
1081   // Everything has been moved over.  Remap it.
1082   Mapper.scheduleRemapFunction(Dst);
1083   return Error::success();
1084 }
1085 
1086 void IRLinker::linkIndirectSymbolBody(GlobalIndirectSymbol &Dst,
1087                                       GlobalIndirectSymbol &Src) {
1088   Mapper.scheduleMapGlobalIndirectSymbol(Dst, *Src.getIndirectSymbol(),
1089                                          IndirectSymbolMCID);
1090 }
1091 
1092 Error IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
1093   if (auto *F = dyn_cast<Function>(&Src))
1094     return linkFunctionBody(cast<Function>(Dst), *F);
1095   if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1096     linkGlobalVariable(cast<GlobalVariable>(Dst), *GVar);
1097     return Error::success();
1098   }
1099   linkIndirectSymbolBody(cast<GlobalIndirectSymbol>(Dst), cast<GlobalIndirectSymbol>(Src));
1100   return Error::success();
1101 }
1102 
1103 void IRLinker::flushRAUWWorklist() {
1104   for (const auto &Elem : RAUWWorklist) {
1105     GlobalValue *Old;
1106     Value *New;
1107     std::tie(Old, New) = Elem;
1108 
1109     Old->replaceAllUsesWith(New);
1110     Old->eraseFromParent();
1111   }
1112   RAUWWorklist.clear();
1113 }
1114 
1115 void IRLinker::prepareCompileUnitsForImport() {
1116   NamedMDNode *SrcCompileUnits = SrcM->getNamedMetadata("llvm.dbg.cu");
1117   if (!SrcCompileUnits)
1118     return;
1119   // When importing for ThinLTO, prevent importing of types listed on
1120   // the DICompileUnit that we don't need a copy of in the importing
1121   // module. They will be emitted by the originating module.
1122   for (unsigned I = 0, E = SrcCompileUnits->getNumOperands(); I != E; ++I) {
1123     auto *CU = cast<DICompileUnit>(SrcCompileUnits->getOperand(I));
1124     assert(CU && "Expected valid compile unit");
1125     // Enums, macros, and retained types don't need to be listed on the
1126     // imported DICompileUnit. This means they will only be imported
1127     // if reached from the mapped IR. Do this by setting their value map
1128     // entries to nullptr, which will automatically prevent their importing
1129     // when reached from the DICompileUnit during metadata mapping.
1130     ValueMap.MD()[CU->getRawEnumTypes()].reset(nullptr);
1131     ValueMap.MD()[CU->getRawMacros()].reset(nullptr);
1132     ValueMap.MD()[CU->getRawRetainedTypes()].reset(nullptr);
1133     // The original definition (or at least its debug info - if the variable is
1134     // internalized an optimized away) will remain in the source module, so
1135     // there's no need to import them.
1136     // If LLVM ever does more advanced optimizations on global variables
1137     // (removing/localizing write operations, for instance) that can track
1138     // through debug info, this decision may need to be revisited - but do so
1139     // with care when it comes to debug info size. Emitting small CUs containing
1140     // only a few imported entities into every destination module may be very
1141     // size inefficient.
1142     ValueMap.MD()[CU->getRawGlobalVariables()].reset(nullptr);
1143 
1144     // Imported entities only need to be mapped in if they have local
1145     // scope, as those might correspond to an imported entity inside a
1146     // function being imported (any locally scoped imported entities that
1147     // don't end up referenced by an imported function will not be emitted
1148     // into the object). Imported entities not in a local scope
1149     // (e.g. on the namespace) only need to be emitted by the originating
1150     // module. Create a list of the locally scoped imported entities, and
1151     // replace the source CUs imported entity list with the new list, so
1152     // only those are mapped in.
1153     // FIXME: Locally-scoped imported entities could be moved to the
1154     // functions they are local to instead of listing them on the CU, and
1155     // we would naturally only link in those needed by function importing.
1156     SmallVector<TrackingMDNodeRef, 4> AllImportedModules;
1157     bool ReplaceImportedEntities = false;
1158     for (auto *IE : CU->getImportedEntities()) {
1159       DIScope *Scope = IE->getScope();
1160       assert(Scope && "Invalid Scope encoding!");
1161       if (isa<DILocalScope>(Scope))
1162         AllImportedModules.emplace_back(IE);
1163       else
1164         ReplaceImportedEntities = true;
1165     }
1166     if (ReplaceImportedEntities) {
1167       if (!AllImportedModules.empty())
1168         CU->replaceImportedEntities(MDTuple::get(
1169             CU->getContext(),
1170             SmallVector<Metadata *, 16>(AllImportedModules.begin(),
1171                                         AllImportedModules.end())));
1172       else
1173         // If there were no local scope imported entities, we can map
1174         // the whole list to nullptr.
1175         ValueMap.MD()[CU->getRawImportedEntities()].reset(nullptr);
1176     }
1177   }
1178 }
1179 
1180 /// Insert all of the named MDNodes in Src into the Dest module.
1181 void IRLinker::linkNamedMDNodes() {
1182   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1183   for (const NamedMDNode &NMD : SrcM->named_metadata()) {
1184     // Don't link module flags here. Do them separately.
1185     if (&NMD == SrcModFlags)
1186       continue;
1187     NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1188     // Add Src elements into Dest node.
1189     for (const MDNode *Op : NMD.operands())
1190       DestNMD->addOperand(Mapper.mapMDNode(*Op));
1191   }
1192 }
1193 
1194 /// Merge the linker flags in Src into the Dest module.
1195 Error IRLinker::linkModuleFlagsMetadata() {
1196   // If the source module has no module flags, we are done.
1197   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1198   if (!SrcModFlags)
1199     return Error::success();
1200 
1201   // If the destination module doesn't have module flags yet, then just copy
1202   // over the source module's flags.
1203   NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1204   if (DstModFlags->getNumOperands() == 0) {
1205     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1206       DstModFlags->addOperand(SrcModFlags->getOperand(I));
1207 
1208     return Error::success();
1209   }
1210 
1211   // First build a map of the existing module flags and requirements.
1212   DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1213   SmallSetVector<MDNode *, 16> Requirements;
1214   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1215     MDNode *Op = DstModFlags->getOperand(I);
1216     ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1217     MDString *ID = cast<MDString>(Op->getOperand(1));
1218 
1219     if (Behavior->getZExtValue() == Module::Require) {
1220       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1221     } else {
1222       Flags[ID] = std::make_pair(Op, I);
1223     }
1224   }
1225 
1226   // Merge in the flags from the source module, and also collect its set of
1227   // requirements.
1228   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1229     MDNode *SrcOp = SrcModFlags->getOperand(I);
1230     ConstantInt *SrcBehavior =
1231         mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1232     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1233     MDNode *DstOp;
1234     unsigned DstIndex;
1235     std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1236     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1237 
1238     // If this is a requirement, add it and continue.
1239     if (SrcBehaviorValue == Module::Require) {
1240       // If the destination module does not already have this requirement, add
1241       // it.
1242       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1243         DstModFlags->addOperand(SrcOp);
1244       }
1245       continue;
1246     }
1247 
1248     // If there is no existing flag with this ID, just add it.
1249     if (!DstOp) {
1250       Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1251       DstModFlags->addOperand(SrcOp);
1252       continue;
1253     }
1254 
1255     // Otherwise, perform a merge.
1256     ConstantInt *DstBehavior =
1257         mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1258     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1259 
1260     auto overrideDstValue = [&]() {
1261       DstModFlags->setOperand(DstIndex, SrcOp);
1262       Flags[ID].first = SrcOp;
1263     };
1264 
1265     // If either flag has override behavior, handle it first.
1266     if (DstBehaviorValue == Module::Override) {
1267       // Diagnose inconsistent flags which both have override behavior.
1268       if (SrcBehaviorValue == Module::Override &&
1269           SrcOp->getOperand(2) != DstOp->getOperand(2))
1270         return stringErr("linking module flags '" + ID->getString() +
1271                          "': IDs have conflicting override values in '" +
1272                          SrcM->getModuleIdentifier() + "' and '" +
1273                          DstM.getModuleIdentifier() + "'");
1274       continue;
1275     } else if (SrcBehaviorValue == Module::Override) {
1276       // Update the destination flag to that of the source.
1277       overrideDstValue();
1278       continue;
1279     }
1280 
1281     // Diagnose inconsistent merge behavior types.
1282     if (SrcBehaviorValue != DstBehaviorValue) {
1283       bool MaxAndWarn = (SrcBehaviorValue == Module::Max &&
1284                          DstBehaviorValue == Module::Warning) ||
1285                         (DstBehaviorValue == Module::Max &&
1286                          SrcBehaviorValue == Module::Warning);
1287       if (!MaxAndWarn)
1288         return stringErr("linking module flags '" + ID->getString() +
1289                          "': IDs have conflicting behaviors in '" +
1290                          SrcM->getModuleIdentifier() + "' and '" +
1291                          DstM.getModuleIdentifier() + "'");
1292     }
1293 
1294     auto replaceDstValue = [&](MDNode *New) {
1295       Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1296       MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1297       DstModFlags->setOperand(DstIndex, Flag);
1298       Flags[ID].first = Flag;
1299     };
1300 
1301     // Emit a warning if the values differ and either source or destination
1302     // request Warning behavior.
1303     if ((DstBehaviorValue == Module::Warning ||
1304          SrcBehaviorValue == Module::Warning) &&
1305         SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1306       std::string Str;
1307       raw_string_ostream(Str)
1308           << "linking module flags '" << ID->getString()
1309           << "': IDs have conflicting values ('" << *SrcOp->getOperand(2)
1310           << "' from " << SrcM->getModuleIdentifier() << " with '"
1311           << *DstOp->getOperand(2) << "' from " << DstM.getModuleIdentifier()
1312           << ')';
1313       emitWarning(Str);
1314     }
1315 
1316     // Choose the maximum if either source or destination request Max behavior.
1317     if (DstBehaviorValue == Module::Max || SrcBehaviorValue == Module::Max) {
1318       ConstantInt *DstValue =
1319           mdconst::extract<ConstantInt>(DstOp->getOperand(2));
1320       ConstantInt *SrcValue =
1321           mdconst::extract<ConstantInt>(SrcOp->getOperand(2));
1322 
1323       // The resulting flag should have a Max behavior, and contain the maximum
1324       // value from between the source and destination values.
1325       Metadata *FlagOps[] = {
1326           (DstBehaviorValue != Module::Max ? SrcOp : DstOp)->getOperand(0), ID,
1327           (SrcValue->getZExtValue() > DstValue->getZExtValue() ? SrcOp : DstOp)
1328               ->getOperand(2)};
1329       MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1330       DstModFlags->setOperand(DstIndex, Flag);
1331       Flags[ID].first = Flag;
1332       continue;
1333     }
1334 
1335     // Perform the merge for standard behavior types.
1336     switch (SrcBehaviorValue) {
1337     case Module::Require:
1338     case Module::Override:
1339       llvm_unreachable("not possible");
1340     case Module::Error: {
1341       // Emit an error if the values differ.
1342       if (SrcOp->getOperand(2) != DstOp->getOperand(2))
1343         return stringErr("linking module flags '" + ID->getString() +
1344                          "': IDs have conflicting values in '" +
1345                          SrcM->getModuleIdentifier() + "' and '" +
1346                          DstM.getModuleIdentifier() + "'");
1347       continue;
1348     }
1349     case Module::Warning: {
1350       break;
1351     }
1352     case Module::Max: {
1353       break;
1354     }
1355     case Module::Append: {
1356       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1357       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1358       SmallVector<Metadata *, 8> MDs;
1359       MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1360       MDs.append(DstValue->op_begin(), DstValue->op_end());
1361       MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1362 
1363       replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1364       break;
1365     }
1366     case Module::AppendUnique: {
1367       SmallSetVector<Metadata *, 16> Elts;
1368       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1369       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1370       Elts.insert(DstValue->op_begin(), DstValue->op_end());
1371       Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1372 
1373       replaceDstValue(MDNode::get(DstM.getContext(),
1374                                   makeArrayRef(Elts.begin(), Elts.end())));
1375       break;
1376     }
1377     }
1378 
1379   }
1380 
1381   // Check all of the requirements.
1382   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1383     MDNode *Requirement = Requirements[I];
1384     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1385     Metadata *ReqValue = Requirement->getOperand(1);
1386 
1387     MDNode *Op = Flags[Flag].first;
1388     if (!Op || Op->getOperand(2) != ReqValue)
1389       return stringErr("linking module flags '" + Flag->getString() +
1390                        "': does not have the required value");
1391   }
1392   return Error::success();
1393 }
1394 
1395 /// Return InlineAsm adjusted with target-specific directives if required.
1396 /// For ARM and Thumb, we have to add directives to select the appropriate ISA
1397 /// to support mixing module-level inline assembly from ARM and Thumb modules.
1398 static std::string adjustInlineAsm(const std::string &InlineAsm,
1399                                    const Triple &Triple) {
1400   if (Triple.getArch() == Triple::thumb || Triple.getArch() == Triple::thumbeb)
1401     return ".text\n.balign 2\n.thumb\n" + InlineAsm;
1402   if (Triple.getArch() == Triple::arm || Triple.getArch() == Triple::armeb)
1403     return ".text\n.balign 4\n.arm\n" + InlineAsm;
1404   return InlineAsm;
1405 }
1406 
1407 Error IRLinker::run() {
1408   // Ensure metadata materialized before value mapping.
1409   if (SrcM->getMaterializer())
1410     if (Error Err = SrcM->getMaterializer()->materializeMetadata())
1411       return Err;
1412 
1413   // Inherit the target data from the source module if the destination module
1414   // doesn't have one already.
1415   if (DstM.getDataLayout().isDefault())
1416     DstM.setDataLayout(SrcM->getDataLayout());
1417 
1418   if (SrcM->getDataLayout() != DstM.getDataLayout()) {
1419     emitWarning("Linking two modules of different data layouts: '" +
1420                 SrcM->getModuleIdentifier() + "' is '" +
1421                 SrcM->getDataLayoutStr() + "' whereas '" +
1422                 DstM.getModuleIdentifier() + "' is '" +
1423                 DstM.getDataLayoutStr() + "'\n");
1424   }
1425 
1426   // Copy the target triple from the source to dest if the dest's is empty.
1427   if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1428     DstM.setTargetTriple(SrcM->getTargetTriple());
1429 
1430   Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple());
1431 
1432   if (!SrcM->getTargetTriple().empty()&&
1433       !SrcTriple.isCompatibleWith(DstTriple))
1434     emitWarning("Linking two modules of different target triples: " +
1435                 SrcM->getModuleIdentifier() + "' is '" +
1436                 SrcM->getTargetTriple() + "' whereas '" +
1437                 DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
1438                 "'\n");
1439 
1440   DstM.setTargetTriple(SrcTriple.merge(DstTriple));
1441 
1442   // Append the module inline asm string.
1443   if (!IsPerformingImport && !SrcM->getModuleInlineAsm().empty()) {
1444     std::string SrcModuleInlineAsm = adjustInlineAsm(SrcM->getModuleInlineAsm(),
1445                                                      SrcTriple);
1446     if (DstM.getModuleInlineAsm().empty())
1447       DstM.setModuleInlineAsm(SrcModuleInlineAsm);
1448     else
1449       DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
1450                               SrcModuleInlineAsm);
1451   }
1452 
1453   // Loop over all of the linked values to compute type mappings.
1454   computeTypeMapping();
1455 
1456   std::reverse(Worklist.begin(), Worklist.end());
1457   while (!Worklist.empty()) {
1458     GlobalValue *GV = Worklist.back();
1459     Worklist.pop_back();
1460 
1461     // Already mapped.
1462     if (ValueMap.find(GV) != ValueMap.end() ||
1463         IndirectSymbolValueMap.find(GV) != IndirectSymbolValueMap.end())
1464       continue;
1465 
1466     assert(!GV->isDeclaration());
1467     Mapper.mapValue(*GV);
1468     if (FoundError)
1469       return std::move(*FoundError);
1470     flushRAUWWorklist();
1471   }
1472 
1473   // Note that we are done linking global value bodies. This prevents
1474   // metadata linking from creating new references.
1475   DoneLinkingBodies = true;
1476   Mapper.addFlags(RF_NullMapMissingGlobalValues);
1477 
1478   // Remap all of the named MDNodes in Src into the DstM module. We do this
1479   // after linking GlobalValues so that MDNodes that reference GlobalValues
1480   // are properly remapped.
1481   linkNamedMDNodes();
1482 
1483   // Merge the module flags into the DstM module.
1484   return linkModuleFlagsMetadata();
1485 }
1486 
1487 IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1488     : ETypes(E), IsPacked(P) {}
1489 
1490 IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1491     : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1492 
1493 bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1494   return IsPacked == That.IsPacked && ETypes == That.ETypes;
1495 }
1496 
1497 bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1498   return !this->operator==(That);
1499 }
1500 
1501 StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1502   return DenseMapInfo<StructType *>::getEmptyKey();
1503 }
1504 
1505 StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1506   return DenseMapInfo<StructType *>::getTombstoneKey();
1507 }
1508 
1509 unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1510   return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1511                       Key.IsPacked);
1512 }
1513 
1514 unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1515   return getHashValue(KeyTy(ST));
1516 }
1517 
1518 bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1519                                          const StructType *RHS) {
1520   if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1521     return false;
1522   return LHS == KeyTy(RHS);
1523 }
1524 
1525 bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
1526                                          const StructType *RHS) {
1527   if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1528     return LHS == RHS;
1529   return KeyTy(LHS) == KeyTy(RHS);
1530 }
1531 
1532 void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1533   assert(!Ty->isOpaque());
1534   NonOpaqueStructTypes.insert(Ty);
1535 }
1536 
1537 void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1538   assert(!Ty->isOpaque());
1539   NonOpaqueStructTypes.insert(Ty);
1540   bool Removed = OpaqueStructTypes.erase(Ty);
1541   (void)Removed;
1542   assert(Removed);
1543 }
1544 
1545 void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1546   assert(Ty->isOpaque());
1547   OpaqueStructTypes.insert(Ty);
1548 }
1549 
1550 StructType *
1551 IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1552                                                 bool IsPacked) {
1553   IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1554   auto I = NonOpaqueStructTypes.find_as(Key);
1555   return I == NonOpaqueStructTypes.end() ? nullptr : *I;
1556 }
1557 
1558 bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1559   if (Ty->isOpaque())
1560     return OpaqueStructTypes.count(Ty);
1561   auto I = NonOpaqueStructTypes.find(Ty);
1562   return I == NonOpaqueStructTypes.end() ? false : *I == Ty;
1563 }
1564 
1565 IRMover::IRMover(Module &M) : Composite(M) {
1566   TypeFinder StructTypes;
1567   StructTypes.run(M, /* OnlyNamed */ false);
1568   for (StructType *Ty : StructTypes) {
1569     if (Ty->isOpaque())
1570       IdentifiedStructTypes.addOpaque(Ty);
1571     else
1572       IdentifiedStructTypes.addNonOpaque(Ty);
1573   }
1574   // Self-map metadatas in the destination module. This is needed when
1575   // DebugTypeODRUniquing is enabled on the LLVMContext, since metadata in the
1576   // destination module may be reached from the source module.
1577   for (auto *MD : StructTypes.getVisitedMetadata()) {
1578     SharedMDs[MD].reset(const_cast<MDNode *>(MD));
1579   }
1580 }
1581 
1582 Error IRMover::move(
1583     std::unique_ptr<Module> Src, ArrayRef<GlobalValue *> ValuesToLink,
1584     std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor,
1585     bool IsPerformingImport) {
1586   IRLinker TheIRLinker(Composite, SharedMDs, IdentifiedStructTypes,
1587                        std::move(Src), ValuesToLink, std::move(AddLazyFor),
1588                        IsPerformingImport);
1589   Error E = TheIRLinker.run();
1590   Composite.dropTriviallyDeadConstantArrays();
1591   return E;
1592 }
1593