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