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