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