1 //===- lib/Linker/IRMover.cpp ---------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/Linker/IRMover.h"
11 #include "LinkDiagnosticInfo.h"
12 #include "llvm/ADT/SetVector.h"
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/IR/Constants.h"
16 #include "llvm/IR/DebugInfo.h"
17 #include "llvm/IR/DiagnosticPrinter.h"
18 #include "llvm/IR/GVMaterializer.h"
19 #include "llvm/IR/Intrinsics.h"
20 #include "llvm/IR/TypeFinder.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     for (Type *Ty : SpeculativeTypes)
99       if (auto *STy = dyn_cast<StructType>(Ty))
100         if (STy->hasName())
101           STy->setName("");
102   }
103   SpeculativeTypes.clear();
104   SpeculativeDstOpaqueTypes.clear();
105 }
106 
107 /// Recursively walk this pair of types, returning true if they are isomorphic,
108 /// false if they are not.
109 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
110   // Two types with differing kinds are clearly not isomorphic.
111   if (DstTy->getTypeID() != SrcTy->getTypeID())
112     return false;
113 
114   // If we have an entry in the MappedTypes table, then we have our answer.
115   Type *&Entry = MappedTypes[SrcTy];
116   if (Entry)
117     return Entry == DstTy;
118 
119   // Two identical types are clearly isomorphic.  Remember this
120   // non-speculatively.
121   if (DstTy == SrcTy) {
122     Entry = DstTy;
123     return true;
124   }
125 
126   // Okay, we have two types with identical kinds that we haven't seen before.
127 
128   // If this is an opaque struct type, special case it.
129   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
130     // Mapping an opaque type to any struct, just keep the dest struct.
131     if (SSTy->isOpaque()) {
132       Entry = DstTy;
133       SpeculativeTypes.push_back(SrcTy);
134       return true;
135     }
136 
137     // Mapping a non-opaque source type to an opaque dest.  If this is the first
138     // type that we're mapping onto this destination type then we succeed.  Keep
139     // the dest, but fill it in later. If this is the second (different) type
140     // that we're trying to map onto the same opaque type then we fail.
141     if (cast<StructType>(DstTy)->isOpaque()) {
142       // We can only map one source type onto the opaque destination type.
143       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
144         return false;
145       SrcDefinitionsToResolve.push_back(SSTy);
146       SpeculativeTypes.push_back(SrcTy);
147       SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
148       Entry = DstTy;
149       return true;
150     }
151   }
152 
153   // If the number of subtypes disagree between the two types, then we fail.
154   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
155     return false;
156 
157   // Fail if any of the extra properties (e.g. array size) of the type disagree.
158   if (isa<IntegerType>(DstTy))
159     return false; // bitwidth disagrees.
160   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
161     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
162       return false;
163 
164   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
165     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
166       return false;
167   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
168     StructType *SSTy = cast<StructType>(SrcTy);
169     if (DSTy->isLiteral() != SSTy->isLiteral() ||
170         DSTy->isPacked() != SSTy->isPacked())
171       return false;
172   } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
173     if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
174       return false;
175   } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
176     if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
177       return false;
178   }
179 
180   // Otherwise, we speculate that these two types will line up and recursively
181   // check the subelements.
182   Entry = DstTy;
183   SpeculativeTypes.push_back(SrcTy);
184 
185   for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
186     if (!areTypesIsomorphic(DstTy->getContainedType(I),
187                             SrcTy->getContainedType(I)))
188       return false;
189 
190   // If everything seems to have lined up, then everything is great.
191   return true;
192 }
193 
194 void TypeMapTy::linkDefinedTypeBodies() {
195   SmallVector<Type *, 16> Elements;
196   for (StructType *SrcSTy : SrcDefinitionsToResolve) {
197     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
198     assert(DstSTy->isOpaque());
199 
200     // Map the body of the source type over to a new body for the dest type.
201     Elements.resize(SrcSTy->getNumElements());
202     for (unsigned I = 0, E = Elements.size(); I != E; ++I)
203       Elements[I] = get(SrcSTy->getElementType(I));
204 
205     DstSTy->setBody(Elements, SrcSTy->isPacked());
206     DstStructTypesSet.switchToNonOpaque(DstSTy);
207   }
208   SrcDefinitionsToResolve.clear();
209   DstResolvedOpaqueTypes.clear();
210 }
211 
212 void TypeMapTy::finishType(StructType *DTy, StructType *STy,
213                            ArrayRef<Type *> ETypes) {
214   DTy->setBody(ETypes, STy->isPacked());
215 
216   // Steal STy's name.
217   if (STy->hasName()) {
218     SmallString<16> TmpName = STy->getName();
219     STy->setName("");
220     DTy->setName(TmpName);
221   }
222 
223   DstStructTypesSet.addNonOpaque(DTy);
224 }
225 
226 Type *TypeMapTy::get(Type *Ty) {
227   SmallPtrSet<StructType *, 8> Visited;
228   return get(Ty, Visited);
229 }
230 
231 Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
232   // If we already have an entry for this type, return it.
233   Type **Entry = &MappedTypes[Ty];
234   if (*Entry)
235     return *Entry;
236 
237   // These are types that LLVM itself will unique.
238   bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
239 
240 #ifndef NDEBUG
241   if (!IsUniqued) {
242     for (auto &Pair : MappedTypes) {
243       assert(!(Pair.first != Ty && Pair.second == Ty) &&
244              "mapping to a source type");
245     }
246   }
247 #endif
248 
249   if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
250     StructType *DTy = StructType::create(Ty->getContext());
251     return *Entry = DTy;
252   }
253 
254   // If this is not a recursive type, then just map all of the elements and
255   // then rebuild the type from inside out.
256   SmallVector<Type *, 4> ElementTypes;
257 
258   // If there are no element types to map, then the type is itself.  This is
259   // true for the anonymous {} struct, things like 'float', integers, etc.
260   if (Ty->getNumContainedTypes() == 0 && IsUniqued)
261     return *Entry = Ty;
262 
263   // Remap all of the elements, keeping track of whether any of them change.
264   bool AnyChange = false;
265   ElementTypes.resize(Ty->getNumContainedTypes());
266   for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
267     ElementTypes[I] = get(Ty->getContainedType(I), Visited);
268     AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
269   }
270 
271   // If we found our type while recursively processing stuff, just use it.
272   Entry = &MappedTypes[Ty];
273   if (*Entry) {
274     if (auto *DTy = dyn_cast<StructType>(*Entry)) {
275       if (DTy->isOpaque()) {
276         auto *STy = cast<StructType>(Ty);
277         finishType(DTy, STy, ElementTypes);
278       }
279     }
280     return *Entry;
281   }
282 
283   // If all of the element types mapped directly over and the type is not
284   // a nomed struct, then the type is usable as-is.
285   if (!AnyChange && IsUniqued)
286     return *Entry = Ty;
287 
288   // Otherwise, rebuild a modified type.
289   switch (Ty->getTypeID()) {
290   default:
291     llvm_unreachable("unknown derived type to remap");
292   case Type::ArrayTyID:
293     return *Entry = ArrayType::get(ElementTypes[0],
294                                    cast<ArrayType>(Ty)->getNumElements());
295   case Type::VectorTyID:
296     return *Entry = VectorType::get(ElementTypes[0],
297                                     cast<VectorType>(Ty)->getNumElements());
298   case Type::PointerTyID:
299     return *Entry = PointerType::get(ElementTypes[0],
300                                      cast<PointerType>(Ty)->getAddressSpace());
301   case Type::FunctionTyID:
302     return *Entry = FunctionType::get(ElementTypes[0],
303                                       makeArrayRef(ElementTypes).slice(1),
304                                       cast<FunctionType>(Ty)->isVarArg());
305   case Type::StructTyID: {
306     auto *STy = cast<StructType>(Ty);
307     bool IsPacked = STy->isPacked();
308     if (IsUniqued)
309       return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
310 
311     // If the type is opaque, we can just use it directly.
312     if (STy->isOpaque()) {
313       DstStructTypesSet.addOpaque(STy);
314       return *Entry = Ty;
315     }
316 
317     if (StructType *OldT =
318             DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
319       STy->setName("");
320       return *Entry = OldT;
321     }
322 
323     if (!AnyChange) {
324       DstStructTypesSet.addNonOpaque(STy);
325       return *Entry = Ty;
326     }
327 
328     StructType *DTy = StructType::create(Ty->getContext());
329     finishType(DTy, STy, ElementTypes);
330     return *Entry = DTy;
331   }
332   }
333 }
334 
335 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
336                                        const Twine &Msg)
337     : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
338 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
339 
340 //===----------------------------------------------------------------------===//
341 // IRLinker implementation.
342 //===----------------------------------------------------------------------===//
343 
344 namespace {
345 class IRLinker;
346 
347 /// Creates prototypes for functions that are lazily linked on the fly. This
348 /// speeds up linking for modules with many/ lazily linked functions of which
349 /// few get used.
350 class GlobalValueMaterializer final : public ValueMaterializer {
351   IRLinker &TheIRLinker;
352 
353 public:
354   GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
355   Value *materialize(Value *V) override;
356 };
357 
358 class LocalValueMaterializer final : public ValueMaterializer {
359   IRLinker &TheIRLinker;
360 
361 public:
362   LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
363   Value *materialize(Value *V) override;
364 };
365 
366 /// Type of the Metadata map in \a ValueToValueMapTy.
367 typedef DenseMap<const Metadata *, TrackingMDRef> MDMapT;
368 
369 /// This is responsible for keeping track of the state used for moving data
370 /// from SrcM to DstM.
371 class IRLinker {
372   Module &DstM;
373   std::unique_ptr<Module> SrcM;
374 
375   /// See IRMover::move().
376   std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor;
377 
378   TypeMapTy TypeMap;
379   GlobalValueMaterializer GValMaterializer;
380   LocalValueMaterializer LValMaterializer;
381 
382   /// A metadata map that's shared between IRLinker instances.
383   MDMapT &SharedMDs;
384 
385   /// Mapping of values from what they used to be in Src, to what they are now
386   /// in DstM.  ValueToValueMapTy is a ValueMap, which involves some overhead
387   /// due to the use of Value handles which the Linker doesn't actually need,
388   /// but this allows us to reuse the ValueMapper code.
389   ValueToValueMapTy ValueMap;
390   ValueToValueMapTy AliasValueMap;
391 
392   DenseSet<GlobalValue *> ValuesToLink;
393   std::vector<GlobalValue *> Worklist;
394 
395   void maybeAdd(GlobalValue *GV) {
396     if (ValuesToLink.insert(GV).second)
397       Worklist.push_back(GV);
398   }
399 
400   /// Flag whether the ModuleInlineAsm string in Src should be linked with
401   /// (concatenated into) the ModuleInlineAsm string for the destination
402   /// module. It should be true for full LTO, but not when importing for
403   /// ThinLTO, otherwise we can have duplicate symbols.
404   bool LinkModuleInlineAsm;
405 
406   /// Set to true when all global value body linking is complete (including
407   /// lazy linking). Used to prevent metadata linking from creating new
408   /// references.
409   bool DoneLinkingBodies = false;
410 
411   /// The Error encountered during materialization. We use an Optional here to
412   /// avoid needing to manage an unconsumed success value.
413   Optional<Error> FoundError;
414   void setError(Error E) {
415     if (E)
416       FoundError = std::move(E);
417   }
418 
419   /// Most of the errors produced by this module are inconvertible StringErrors.
420   /// This convenience function lets us return one of those more easily.
421   Error stringErr(const Twine &T) {
422     return make_error<StringError>(T, inconvertibleErrorCode());
423   }
424 
425   /// Entry point for mapping values and alternate context for mapping aliases.
426   ValueMapper Mapper;
427   unsigned AliasMCID;
428 
429   /// Handles cloning of a global values from the source module into
430   /// the destination module, including setting the attributes and visibility.
431   GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
432 
433   void emitWarning(const Twine &Message) {
434     SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
435   }
436 
437   /// Given a global in the source module, return the global in the
438   /// destination module that is being linked to, if any.
439   GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
440     // If the source has no name it can't link.  If it has local linkage,
441     // there is no name match-up going on.
442     if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
443       return nullptr;
444 
445     // Otherwise see if we have a match in the destination module's symtab.
446     GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
447     if (!DGV)
448       return nullptr;
449 
450     // If we found a global with the same name in the dest module, but it has
451     // internal linkage, we are really not doing any linkage here.
452     if (DGV->hasLocalLinkage())
453       return nullptr;
454 
455     // Otherwise, we do in fact link to the destination global.
456     return DGV;
457   }
458 
459   void computeTypeMapping();
460 
461   Expected<Constant *> linkAppendingVarProto(GlobalVariable *DstGV,
462                                              const GlobalVariable *SrcGV);
463 
464   /// Given the GlobaValue \p SGV in the source module, and the matching
465   /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV
466   /// into the destination module.
467   ///
468   /// Note this code may call the client-provided \p AddLazyFor.
469   bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
470   Expected<Constant *> linkGlobalValueProto(GlobalValue *GV, bool ForAlias);
471 
472   Error linkModuleFlagsMetadata();
473 
474   void linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src);
475   Error linkFunctionBody(Function &Dst, Function &Src);
476   void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
477   Error linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
478 
479   /// Functions that take care of cloning a specific global value type
480   /// into the destination module.
481   GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
482   Function *copyFunctionProto(const Function *SF);
483   GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA);
484 
485   void linkNamedMDNodes();
486 
487 public:
488   IRLinker(Module &DstM, MDMapT &SharedMDs,
489            IRMover::IdentifiedStructTypeSet &Set, std::unique_ptr<Module> SrcM,
490            ArrayRef<GlobalValue *> ValuesToLink,
491            std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor,
492            bool LinkModuleInlineAsm)
493       : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(std::move(AddLazyFor)),
494         TypeMap(Set), GValMaterializer(*this), LValMaterializer(*this),
495         SharedMDs(SharedMDs), LinkModuleInlineAsm(LinkModuleInlineAsm),
496         Mapper(ValueMap, RF_MoveDistinctMDs | RF_IgnoreMissingLocals, &TypeMap,
497                &GValMaterializer),
498         AliasMCID(Mapper.registerAlternateMappingContext(AliasValueMap,
499                                                          &LValMaterializer)) {
500     ValueMap.getMDMap() = std::move(SharedMDs);
501     for (GlobalValue *GV : ValuesToLink)
502       maybeAdd(GV);
503   }
504   ~IRLinker() { SharedMDs = std::move(*ValueMap.getMDMap()); }
505 
506   Error run();
507   Value *materialize(Value *V, bool ForAlias);
508 };
509 }
510 
511 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
512 /// table. This is good for all clients except for us. Go through the trouble
513 /// to force this back.
514 static void forceRenaming(GlobalValue *GV, StringRef Name) {
515   // If the global doesn't force its name or if it already has the right name,
516   // there is nothing for us to do.
517   if (GV->hasLocalLinkage() || GV->getName() == Name)
518     return;
519 
520   Module *M = GV->getParent();
521 
522   // If there is a conflict, rename the conflict.
523   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
524     GV->takeName(ConflictGV);
525     ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
526     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
527   } else {
528     GV->setName(Name); // Force the name back
529   }
530 }
531 
532 Value *GlobalValueMaterializer::materialize(Value *SGV) {
533   return TheIRLinker.materialize(SGV, false);
534 }
535 
536 Value *LocalValueMaterializer::materialize(Value *SGV) {
537   return TheIRLinker.materialize(SGV, true);
538 }
539 
540 Value *IRLinker::materialize(Value *V, bool ForAlias) {
541   auto *SGV = dyn_cast<GlobalValue>(V);
542   if (!SGV)
543     return nullptr;
544 
545   Expected<Constant *> NewProto = linkGlobalValueProto(SGV, ForAlias);
546   if (!NewProto) {
547     setError(NewProto.takeError());
548     return nullptr;
549   }
550   if (!*NewProto)
551     return nullptr;
552 
553   GlobalValue *New = dyn_cast<GlobalValue>(*NewProto);
554   if (!New)
555     return *NewProto;
556 
557   // If we already created the body, just return.
558   if (auto *F = dyn_cast<Function>(New)) {
559     if (!F->isDeclaration())
560       return New;
561   } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
562     if (V->hasInitializer() || V->hasAppendingLinkage())
563       return New;
564   } else {
565     auto *A = cast<GlobalAlias>(New);
566     if (A->getAliasee())
567       return New;
568   }
569 
570   // When linking a global for an alias, it will always be linked. However we
571   // need to check if it was not already scheduled to satify a reference from a
572   // regular global value initializer. We know if it has been schedule if the
573   // "New" GlobalValue that is mapped here for the alias is the same as the one
574   // already mapped. If there is an entry in the ValueMap but the value is
575   // different, it means that the value already had a definition in the
576   // destination module (linkonce for instance), but we need a new definition
577   // for the alias ("New" will be different.
578   if (ForAlias && ValueMap.lookup(SGV) == New)
579     return New;
580 
581   if (ForAlias || shouldLink(New, *SGV))
582     setError(linkGlobalValueBody(*New, *SGV));
583 
584   return New;
585 }
586 
587 /// Loop through the global variables in the src module and merge them into the
588 /// dest module.
589 GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
590   // No linking to be performed or linking from the source: simply create an
591   // identical version of the symbol over in the dest module... the
592   // initializer will be filled in later by LinkGlobalInits.
593   GlobalVariable *NewDGV =
594       new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()),
595                          SGVar->isConstant(), GlobalValue::ExternalLinkage,
596                          /*init*/ nullptr, SGVar->getName(),
597                          /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
598                          SGVar->getType()->getAddressSpace());
599   NewDGV->setAlignment(SGVar->getAlignment());
600   return NewDGV;
601 }
602 
603 /// Link the function in the source module into the destination module if
604 /// needed, setting up mapping information.
605 Function *IRLinker::copyFunctionProto(const Function *SF) {
606   // If there is no linkage to be performed or we are linking from the source,
607   // bring SF over.
608   return Function::Create(TypeMap.get(SF->getFunctionType()),
609                           GlobalValue::ExternalLinkage, SF->getName(), &DstM);
610 }
611 
612 /// Set up prototypes for any aliases that come over from the source module.
613 GlobalValue *IRLinker::copyGlobalAliasProto(const GlobalAlias *SGA) {
614   // If there is no linkage to be performed or we're linking from the source,
615   // bring over SGA.
616   auto *Ty = TypeMap.get(SGA->getValueType());
617   return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
618                              GlobalValue::ExternalLinkage, SGA->getName(),
619                              &DstM);
620 }
621 
622 GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
623                                             bool ForDefinition) {
624   GlobalValue *NewGV;
625   if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
626     NewGV = copyGlobalVariableProto(SGVar);
627   } else if (auto *SF = dyn_cast<Function>(SGV)) {
628     NewGV = copyFunctionProto(SF);
629   } else {
630     if (ForDefinition)
631       NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV));
632     else
633       NewGV = new GlobalVariable(
634           DstM, TypeMap.get(SGV->getValueType()),
635           /*isConstant*/ false, GlobalValue::ExternalLinkage,
636           /*init*/ nullptr, SGV->getName(),
637           /*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
638           SGV->getType()->getAddressSpace());
639   }
640 
641   if (ForDefinition)
642     NewGV->setLinkage(SGV->getLinkage());
643   else if (SGV->hasExternalWeakLinkage())
644     NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
645 
646   NewGV->copyAttributesFrom(SGV);
647 
648   if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
649     // Metadata for global variables and function declarations is copied eagerly.
650     if (isa<GlobalVariable>(SGV) || SGV->isDeclaration())
651       NewGO->copyMetadata(cast<GlobalObject>(SGV), 0);
652   }
653 
654   // Remove these copied constants in case this stays a declaration, since
655   // they point to the source module. If the def is linked the values will
656   // be mapped in during linkFunctionBody.
657   if (auto *NewF = dyn_cast<Function>(NewGV)) {
658     NewF->setPersonalityFn(nullptr);
659     NewF->setPrefixData(nullptr);
660     NewF->setPrologueData(nullptr);
661   }
662 
663   return NewGV;
664 }
665 
666 /// Loop over all of the linked values to compute type mappings.  For example,
667 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
668 /// types 'Foo' but one got renamed when the module was loaded into the same
669 /// LLVMContext.
670 void IRLinker::computeTypeMapping() {
671   for (GlobalValue &SGV : SrcM->globals()) {
672     GlobalValue *DGV = getLinkedToGlobal(&SGV);
673     if (!DGV)
674       continue;
675 
676     if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
677       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
678       continue;
679     }
680 
681     // Unify the element type of appending arrays.
682     ArrayType *DAT = cast<ArrayType>(DGV->getValueType());
683     ArrayType *SAT = cast<ArrayType>(SGV.getValueType());
684     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
685   }
686 
687   for (GlobalValue &SGV : *SrcM)
688     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
689       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
690 
691   for (GlobalValue &SGV : SrcM->aliases())
692     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
693       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
694 
695   // Incorporate types by name, scanning all the types in the source module.
696   // At this point, the destination module may have a type "%foo = { i32 }" for
697   // example.  When the source module got loaded into the same LLVMContext, if
698   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
699   std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
700   for (StructType *ST : Types) {
701     if (!ST->hasName())
702       continue;
703 
704     // Check to see if there is a dot in the name followed by a digit.
705     size_t DotPos = ST->getName().rfind('.');
706     if (DotPos == 0 || DotPos == StringRef::npos ||
707         ST->getName().back() == '.' ||
708         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
709       continue;
710 
711     // Check to see if the destination module has a struct with the prefix name.
712     StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
713     if (!DST)
714       continue;
715 
716     // Don't use it if this actually came from the source module. They're in
717     // the same LLVMContext after all. Also don't use it unless the type is
718     // actually used in the destination module. This can happen in situations
719     // like this:
720     //
721     //      Module A                         Module B
722     //      --------                         --------
723     //   %Z = type { %A }                %B = type { %C.1 }
724     //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
725     //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
726     //   %C = type { i8* }               %B.3 = type { %C.1 }
727     //
728     // When we link Module B with Module A, the '%B' in Module B is
729     // used. However, that would then use '%C.1'. But when we process '%C.1',
730     // we prefer to take the '%C' version. So we are then left with both
731     // '%C.1' and '%C' being used for the same types. This leads to some
732     // variables using one type and some using the other.
733     if (TypeMap.DstStructTypesSet.hasType(DST))
734       TypeMap.addTypeMapping(DST, ST);
735   }
736 
737   // Now that we have discovered all of the type equivalences, get a body for
738   // any 'opaque' types in the dest module that are now resolved.
739   TypeMap.linkDefinedTypeBodies();
740 }
741 
742 static void getArrayElements(const Constant *C,
743                              SmallVectorImpl<Constant *> &Dest) {
744   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
745 
746   for (unsigned i = 0; i != NumElements; ++i)
747     Dest.push_back(C->getAggregateElement(i));
748 }
749 
750 /// If there were any appending global variables, link them together now.
751 Expected<Constant *>
752 IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
753                                 const GlobalVariable *SrcGV) {
754   Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
755                     ->getElementType();
756 
757   // FIXME: This upgrade is done during linking to support the C API.  Once the
758   // old form is deprecated, we should move this upgrade to
759   // llvm::UpgradeGlobalVariable() and simplify the logic here and in
760   // Mapper::mapAppendingVariable() in ValueMapper.cpp.
761   StringRef Name = SrcGV->getName();
762   bool IsNewStructor = false;
763   bool IsOldStructor = false;
764   if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
765     if (cast<StructType>(EltTy)->getNumElements() == 3)
766       IsNewStructor = true;
767     else
768       IsOldStructor = true;
769   }
770 
771   PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
772   if (IsOldStructor) {
773     auto &ST = *cast<StructType>(EltTy);
774     Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
775     EltTy = StructType::get(SrcGV->getContext(), Tys, false);
776   }
777 
778   uint64_t DstNumElements = 0;
779   if (DstGV) {
780     ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
781     DstNumElements = DstTy->getNumElements();
782 
783     if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
784       return stringErr(
785           "Linking globals named '" + SrcGV->getName() +
786           "': can only link appending global with another appending "
787           "global!");
788 
789     // Check to see that they two arrays agree on type.
790     if (EltTy != DstTy->getElementType())
791       return stringErr("Appending variables with different element types!");
792     if (DstGV->isConstant() != SrcGV->isConstant())
793       return stringErr("Appending variables linked with different const'ness!");
794 
795     if (DstGV->getAlignment() != SrcGV->getAlignment())
796       return stringErr(
797           "Appending variables with different alignment need to be linked!");
798 
799     if (DstGV->getVisibility() != SrcGV->getVisibility())
800       return stringErr(
801           "Appending variables with different visibility need to be linked!");
802 
803     if (DstGV->hasGlobalUnnamedAddr() != SrcGV->hasGlobalUnnamedAddr())
804       return stringErr(
805           "Appending variables with different unnamed_addr need to be linked!");
806 
807     if (DstGV->getSection() != SrcGV->getSection())
808       return stringErr(
809           "Appending variables with different section name need to be linked!");
810   }
811 
812   SmallVector<Constant *, 16> SrcElements;
813   getArrayElements(SrcGV->getInitializer(), SrcElements);
814 
815   if (IsNewStructor) {
816     auto It = remove_if(SrcElements, [this](Constant *E) {
817       auto *Key =
818           dyn_cast<GlobalValue>(E->getAggregateElement(2)->stripPointerCasts());
819       if (!Key)
820         return false;
821       GlobalValue *DGV = getLinkedToGlobal(Key);
822       return !shouldLink(DGV, *Key);
823     });
824     SrcElements.erase(It, SrcElements.end());
825   }
826   uint64_t NewSize = DstNumElements + SrcElements.size();
827   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
828 
829   // Create the new global variable.
830   GlobalVariable *NG = new GlobalVariable(
831       DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
832       /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
833       SrcGV->getType()->getAddressSpace());
834 
835   NG->copyAttributesFrom(SrcGV);
836   forceRenaming(NG, SrcGV->getName());
837 
838   Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
839 
840   Mapper.scheduleMapAppendingVariable(*NG,
841                                       DstGV ? DstGV->getInitializer() : nullptr,
842                                       IsOldStructor, SrcElements);
843 
844   // Replace any uses of the two global variables with uses of the new
845   // global.
846   if (DstGV) {
847     DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
848     DstGV->eraseFromParent();
849   }
850 
851   return Ret;
852 }
853 
854 bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
855   if (ValuesToLink.count(&SGV) || SGV.hasLocalLinkage())
856     return true;
857 
858   if (DGV && !DGV->isDeclarationForLinker())
859     return false;
860 
861   if (SGV.hasAvailableExternallyLinkage())
862     return true;
863 
864   if (SGV.isDeclaration() || DoneLinkingBodies)
865     return false;
866 
867   // Callback to the client to give a chance to lazily add the Global to the
868   // list of value to link.
869   bool LazilyAdded = false;
870   AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) {
871     maybeAdd(&GV);
872     LazilyAdded = true;
873   });
874   return LazilyAdded;
875 }
876 
877 Expected<Constant *> IRLinker::linkGlobalValueProto(GlobalValue *SGV,
878                                                     bool ForAlias) {
879   GlobalValue *DGV = getLinkedToGlobal(SGV);
880 
881   bool ShouldLink = shouldLink(DGV, *SGV);
882 
883   // just missing from map
884   if (ShouldLink) {
885     auto I = ValueMap.find(SGV);
886     if (I != ValueMap.end())
887       return cast<Constant>(I->second);
888 
889     I = AliasValueMap.find(SGV);
890     if (I != AliasValueMap.end())
891       return cast<Constant>(I->second);
892   }
893 
894   if (!ShouldLink && ForAlias)
895     DGV = nullptr;
896 
897   // Handle the ultra special appending linkage case first.
898   assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
899   if (SGV->hasAppendingLinkage())
900     return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
901                                  cast<GlobalVariable>(SGV));
902 
903   GlobalValue *NewGV;
904   if (DGV && !ShouldLink) {
905     NewGV = DGV;
906   } else {
907     // If we are done linking global value bodies (i.e. we are performing
908     // metadata linking), don't link in the global value due to this
909     // reference, simply map it to null.
910     if (DoneLinkingBodies)
911       return nullptr;
912 
913     NewGV = copyGlobalValueProto(SGV, ShouldLink);
914     if (ShouldLink || !ForAlias)
915       forceRenaming(NewGV, SGV->getName());
916   }
917 
918   // Overloaded intrinsics have overloaded types names as part of their
919   // names. If we renamed overloaded types we should rename the intrinsic
920   // as well.
921   if (Function *F = dyn_cast<Function>(NewGV))
922     if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F))
923       NewGV = Remangled.getValue();
924 
925   if (ShouldLink || ForAlias) {
926     if (const Comdat *SC = SGV->getComdat()) {
927       if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
928         Comdat *DC = DstM.getOrInsertComdat(SC->getName());
929         DC->setSelectionKind(SC->getSelectionKind());
930         GO->setComdat(DC);
931       }
932     }
933   }
934 
935   if (!ShouldLink && ForAlias)
936     NewGV->setLinkage(GlobalValue::InternalLinkage);
937 
938   Constant *C = NewGV;
939   if (DGV)
940     C = ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType()));
941 
942   if (DGV && NewGV != DGV) {
943     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
944     DGV->eraseFromParent();
945   }
946 
947   return C;
948 }
949 
950 /// Update the initializers in the Dest module now that all globals that may be
951 /// referenced are in Dest.
952 void IRLinker::linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src) {
953   Dst.copyMetadata(&Src, 0);
954 
955   // Figure out what the initializer looks like in the dest module.
956   Mapper.scheduleMapGlobalInitializer(Dst, *Src.getInitializer());
957 }
958 
959 /// Copy the source function over into the dest function and fix up references
960 /// to values. At this point we know that Dest is an external function, and
961 /// that Src is not.
962 Error IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
963   assert(Dst.isDeclaration() && !Src.isDeclaration());
964 
965   // Materialize if needed.
966   if (std::error_code EC = Src.materialize())
967     return errorCodeToError(EC);
968 
969   // Link in the operands without remapping.
970   if (Src.hasPrefixData())
971     Dst.setPrefixData(Src.getPrefixData());
972   if (Src.hasPrologueData())
973     Dst.setPrologueData(Src.getPrologueData());
974   if (Src.hasPersonalityFn())
975     Dst.setPersonalityFn(Src.getPersonalityFn());
976 
977   // Copy over the metadata attachments without remapping.
978   Dst.copyMetadata(&Src, 0);
979 
980   // Steal arguments and splice the body of Src into Dst.
981   Dst.stealArgumentListFrom(Src);
982   Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
983 
984   // Everything has been moved over.  Remap it.
985   Mapper.scheduleRemapFunction(Dst);
986   return Error::success();
987 }
988 
989 void IRLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
990   Mapper.scheduleMapGlobalAliasee(Dst, *Src.getAliasee(), AliasMCID);
991 }
992 
993 Error IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
994   if (auto *F = dyn_cast<Function>(&Src))
995     return linkFunctionBody(cast<Function>(Dst), *F);
996   if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
997     linkGlobalVariable(cast<GlobalVariable>(Dst), *GVar);
998     return Error::success();
999   }
1000   linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
1001   return Error::success();
1002 }
1003 
1004 /// Insert all of the named MDNodes in Src into the Dest module.
1005 void IRLinker::linkNamedMDNodes() {
1006   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1007   for (const NamedMDNode &NMD : SrcM->named_metadata()) {
1008     // Don't link module flags here. Do them separately.
1009     if (&NMD == SrcModFlags)
1010       continue;
1011     NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1012     // Add Src elements into Dest node.
1013     for (const MDNode *Op : NMD.operands())
1014       DestNMD->addOperand(Mapper.mapMDNode(*Op));
1015   }
1016 }
1017 
1018 /// Merge the linker flags in Src into the Dest module.
1019 Error IRLinker::linkModuleFlagsMetadata() {
1020   // If the source module has no module flags, we are done.
1021   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1022   if (!SrcModFlags)
1023     return Error::success();
1024 
1025   // If the destination module doesn't have module flags yet, then just copy
1026   // over the source module's flags.
1027   NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1028   if (DstModFlags->getNumOperands() == 0) {
1029     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1030       DstModFlags->addOperand(SrcModFlags->getOperand(I));
1031 
1032     return Error::success();
1033   }
1034 
1035   // First build a map of the existing module flags and requirements.
1036   DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1037   SmallSetVector<MDNode *, 16> Requirements;
1038   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1039     MDNode *Op = DstModFlags->getOperand(I);
1040     ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1041     MDString *ID = cast<MDString>(Op->getOperand(1));
1042 
1043     if (Behavior->getZExtValue() == Module::Require) {
1044       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1045     } else {
1046       Flags[ID] = std::make_pair(Op, I);
1047     }
1048   }
1049 
1050   // Merge in the flags from the source module, and also collect its set of
1051   // requirements.
1052   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1053     MDNode *SrcOp = SrcModFlags->getOperand(I);
1054     ConstantInt *SrcBehavior =
1055         mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1056     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1057     MDNode *DstOp;
1058     unsigned DstIndex;
1059     std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1060     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1061 
1062     // If this is a requirement, add it and continue.
1063     if (SrcBehaviorValue == Module::Require) {
1064       // If the destination module does not already have this requirement, add
1065       // it.
1066       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1067         DstModFlags->addOperand(SrcOp);
1068       }
1069       continue;
1070     }
1071 
1072     // If there is no existing flag with this ID, just add it.
1073     if (!DstOp) {
1074       Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1075       DstModFlags->addOperand(SrcOp);
1076       continue;
1077     }
1078 
1079     // Otherwise, perform a merge.
1080     ConstantInt *DstBehavior =
1081         mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1082     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1083 
1084     // If either flag has override behavior, handle it first.
1085     if (DstBehaviorValue == Module::Override) {
1086       // Diagnose inconsistent flags which both have override behavior.
1087       if (SrcBehaviorValue == Module::Override &&
1088           SrcOp->getOperand(2) != DstOp->getOperand(2))
1089         return stringErr("linking module flags '" + ID->getString() +
1090                          "': IDs have conflicting override values");
1091       continue;
1092     } else if (SrcBehaviorValue == Module::Override) {
1093       // Update the destination flag to that of the source.
1094       DstModFlags->setOperand(DstIndex, SrcOp);
1095       Flags[ID].first = SrcOp;
1096       continue;
1097     }
1098 
1099     // Diagnose inconsistent merge behavior types.
1100     if (SrcBehaviorValue != DstBehaviorValue)
1101       return stringErr("linking module flags '" + ID->getString() +
1102                        "': IDs have conflicting behaviors");
1103 
1104     auto replaceDstValue = [&](MDNode *New) {
1105       Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1106       MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1107       DstModFlags->setOperand(DstIndex, Flag);
1108       Flags[ID].first = Flag;
1109     };
1110 
1111     // Perform the merge for standard behavior types.
1112     switch (SrcBehaviorValue) {
1113     case Module::Require:
1114     case Module::Override:
1115       llvm_unreachable("not possible");
1116     case Module::Error: {
1117       // Emit an error if the values differ.
1118       if (SrcOp->getOperand(2) != DstOp->getOperand(2))
1119         return stringErr("linking module flags '" + ID->getString() +
1120                          "': IDs have conflicting values");
1121       continue;
1122     }
1123     case Module::Warning: {
1124       // Emit a warning if the values differ.
1125       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1126         emitWarning("linking module flags '" + ID->getString() +
1127                     "': IDs have conflicting values");
1128       }
1129       continue;
1130     }
1131     case Module::Append: {
1132       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1133       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1134       SmallVector<Metadata *, 8> MDs;
1135       MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1136       MDs.append(DstValue->op_begin(), DstValue->op_end());
1137       MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1138 
1139       replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1140       break;
1141     }
1142     case Module::AppendUnique: {
1143       SmallSetVector<Metadata *, 16> Elts;
1144       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1145       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1146       Elts.insert(DstValue->op_begin(), DstValue->op_end());
1147       Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1148 
1149       replaceDstValue(MDNode::get(DstM.getContext(),
1150                                   makeArrayRef(Elts.begin(), Elts.end())));
1151       break;
1152     }
1153     }
1154   }
1155 
1156   // Check all of the requirements.
1157   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1158     MDNode *Requirement = Requirements[I];
1159     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1160     Metadata *ReqValue = Requirement->getOperand(1);
1161 
1162     MDNode *Op = Flags[Flag].first;
1163     if (!Op || Op->getOperand(2) != ReqValue)
1164       return stringErr("linking module flags '" + Flag->getString() +
1165                        "': does not have the required value");
1166   }
1167   return Error::success();
1168 }
1169 
1170 // This function returns true if the triples match.
1171 static bool triplesMatch(const Triple &T0, const Triple &T1) {
1172   // If vendor is apple, ignore the version number.
1173   if (T0.getVendor() == Triple::Apple)
1174     return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1175            T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1176 
1177   return T0 == T1;
1178 }
1179 
1180 // This function returns the merged triple.
1181 static std::string mergeTriples(const Triple &SrcTriple,
1182                                 const Triple &DstTriple) {
1183   // If vendor is apple, pick the triple with the larger version number.
1184   if (SrcTriple.getVendor() == Triple::Apple)
1185     if (DstTriple.isOSVersionLT(SrcTriple))
1186       return SrcTriple.str();
1187 
1188   return DstTriple.str();
1189 }
1190 
1191 Error IRLinker::run() {
1192   // Ensure metadata materialized before value mapping.
1193   if (SrcM->getMaterializer())
1194     if (std::error_code EC = SrcM->getMaterializer()->materializeMetadata())
1195       return errorCodeToError(EC);
1196 
1197   // Inherit the target data from the source module if the destination module
1198   // doesn't have one already.
1199   if (DstM.getDataLayout().isDefault())
1200     DstM.setDataLayout(SrcM->getDataLayout());
1201 
1202   if (SrcM->getDataLayout() != DstM.getDataLayout()) {
1203     emitWarning("Linking two modules of different data layouts: '" +
1204                 SrcM->getModuleIdentifier() + "' is '" +
1205                 SrcM->getDataLayoutStr() + "' whereas '" +
1206                 DstM.getModuleIdentifier() + "' is '" +
1207                 DstM.getDataLayoutStr() + "'\n");
1208   }
1209 
1210   // Copy the target triple from the source to dest if the dest's is empty.
1211   if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1212     DstM.setTargetTriple(SrcM->getTargetTriple());
1213 
1214   Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple());
1215 
1216   if (!SrcM->getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
1217     emitWarning("Linking two modules of different target triples: " +
1218                 SrcM->getModuleIdentifier() + "' is '" +
1219                 SrcM->getTargetTriple() + "' whereas '" +
1220                 DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
1221                 "'\n");
1222 
1223   DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1224 
1225   // Append the module inline asm string.
1226   if (LinkModuleInlineAsm && !SrcM->getModuleInlineAsm().empty()) {
1227     if (DstM.getModuleInlineAsm().empty())
1228       DstM.setModuleInlineAsm(SrcM->getModuleInlineAsm());
1229     else
1230       DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
1231                               SrcM->getModuleInlineAsm());
1232   }
1233 
1234   // Loop over all of the linked values to compute type mappings.
1235   computeTypeMapping();
1236 
1237   std::reverse(Worklist.begin(), Worklist.end());
1238   while (!Worklist.empty()) {
1239     GlobalValue *GV = Worklist.back();
1240     Worklist.pop_back();
1241 
1242     // Already mapped.
1243     if (ValueMap.find(GV) != ValueMap.end() ||
1244         AliasValueMap.find(GV) != AliasValueMap.end())
1245       continue;
1246 
1247     assert(!GV->isDeclaration());
1248     Mapper.mapValue(*GV);
1249     if (FoundError)
1250       return std::move(*FoundError);
1251   }
1252 
1253   // Note that we are done linking global value bodies. This prevents
1254   // metadata linking from creating new references.
1255   DoneLinkingBodies = true;
1256   Mapper.addFlags(RF_NullMapMissingGlobalValues);
1257 
1258   // Remap all of the named MDNodes in Src into the DstM module. We do this
1259   // after linking GlobalValues so that MDNodes that reference GlobalValues
1260   // are properly remapped.
1261   linkNamedMDNodes();
1262 
1263   // Merge the module flags into the DstM module.
1264   return linkModuleFlagsMetadata();
1265 }
1266 
1267 IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1268     : ETypes(E), IsPacked(P) {}
1269 
1270 IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1271     : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1272 
1273 bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1274   return IsPacked == That.IsPacked && ETypes == That.ETypes;
1275 }
1276 
1277 bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1278   return !this->operator==(That);
1279 }
1280 
1281 StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1282   return DenseMapInfo<StructType *>::getEmptyKey();
1283 }
1284 
1285 StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1286   return DenseMapInfo<StructType *>::getTombstoneKey();
1287 }
1288 
1289 unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1290   return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1291                       Key.IsPacked);
1292 }
1293 
1294 unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1295   return getHashValue(KeyTy(ST));
1296 }
1297 
1298 bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1299                                          const StructType *RHS) {
1300   if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1301     return false;
1302   return LHS == KeyTy(RHS);
1303 }
1304 
1305 bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
1306                                          const StructType *RHS) {
1307   if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1308     return LHS == RHS;
1309   return KeyTy(LHS) == KeyTy(RHS);
1310 }
1311 
1312 void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1313   assert(!Ty->isOpaque());
1314   NonOpaqueStructTypes.insert(Ty);
1315 }
1316 
1317 void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1318   assert(!Ty->isOpaque());
1319   NonOpaqueStructTypes.insert(Ty);
1320   bool Removed = OpaqueStructTypes.erase(Ty);
1321   (void)Removed;
1322   assert(Removed);
1323 }
1324 
1325 void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1326   assert(Ty->isOpaque());
1327   OpaqueStructTypes.insert(Ty);
1328 }
1329 
1330 StructType *
1331 IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1332                                                 bool IsPacked) {
1333   IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1334   auto I = NonOpaqueStructTypes.find_as(Key);
1335   return I == NonOpaqueStructTypes.end() ? nullptr : *I;
1336 }
1337 
1338 bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1339   if (Ty->isOpaque())
1340     return OpaqueStructTypes.count(Ty);
1341   auto I = NonOpaqueStructTypes.find(Ty);
1342   return I == NonOpaqueStructTypes.end() ? false : *I == Ty;
1343 }
1344 
1345 IRMover::IRMover(Module &M) : Composite(M) {
1346   TypeFinder StructTypes;
1347   StructTypes.run(M, true);
1348   for (StructType *Ty : StructTypes) {
1349     if (Ty->isOpaque())
1350       IdentifiedStructTypes.addOpaque(Ty);
1351     else
1352       IdentifiedStructTypes.addNonOpaque(Ty);
1353   }
1354   // Self-map metadatas in the destination module. This is needed when
1355   // DebugTypeODRUniquing is enabled on the LLVMContext, since metadata in the
1356   // destination module may be reached from the source module.
1357   for (auto *MD : StructTypes.getVisitedMetadata()) {
1358     SharedMDs[MD].reset(const_cast<MDNode *>(MD));
1359   }
1360 }
1361 
1362 Error IRMover::move(
1363     std::unique_ptr<Module> Src, ArrayRef<GlobalValue *> ValuesToLink,
1364     std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor,
1365     bool LinkModuleInlineAsm) {
1366   IRLinker TheIRLinker(Composite, SharedMDs, IdentifiedStructTypes,
1367                        std::move(Src), ValuesToLink, std::move(AddLazyFor),
1368                        LinkModuleInlineAsm);
1369   Error E = TheIRLinker.run();
1370   Composite.dropTriviallyDeadConstantArrays();
1371   return E;
1372 }
1373