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