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