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