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