Change how we keep track of which types are in the dest module.
[oota-llvm.git] / lib / Linker / LinkModules.cpp
1 //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
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 // This file implements the LLVM module linker.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Linker/Linker.h"
15 #include "llvm-c/Linker.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DiagnosticInfo.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/TypeFinder.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Transforms/Utils/Cloning.h"
29 #include <cctype>
30 #include <tuple>
31 using namespace llvm;
32
33
34 //===----------------------------------------------------------------------===//
35 // TypeMap implementation.
36 //===----------------------------------------------------------------------===//
37
38 namespace {
39 typedef SmallPtrSet<StructType *, 32> TypeSet;
40
41 class TypeMapTy : public ValueMapTypeRemapper {
42   /// This is a mapping from a source type to a destination type to use.
43   DenseMap<Type*, Type*> MappedTypes;
44
45   /// When checking to see if two subgraphs are isomorphic, we speculatively
46   /// add types to MappedTypes, but keep track of them here in case we need to
47   /// roll back.
48   SmallVector<Type*, 16> SpeculativeTypes;
49
50   SmallVector<StructType*, 16> SpeculativeDstOpaqueTypes;
51
52   /// This is a list of non-opaque structs in the source module that are mapped
53   /// to an opaque struct in the destination module.
54   SmallVector<StructType*, 16> SrcDefinitionsToResolve;
55
56   /// This is the set of opaque types in the destination modules who are
57   /// getting a body from the source module.
58   SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
59
60 public:
61   TypeMapTy() {}
62
63   /// Indicate that the specified type in the destination module is conceptually
64   /// equivalent to the specified type in the source module.
65   void addTypeMapping(Type *DstTy, Type *SrcTy);
66
67   /// Produce a body for an opaque type in the dest module from a type
68   /// definition in the source module.
69   void linkDefinedTypeBodies();
70
71   /// Return the mapped type to use for the specified input type from the
72   /// source module.
73   Type *get(Type *SrcTy);
74
75   FunctionType *get(FunctionType *T) {
76     return cast<FunctionType>(get((Type *)T));
77   }
78
79   /// Dump out the type map for debugging purposes.
80   void dump() const {
81     for (auto &Pair : MappedTypes) {
82       dbgs() << "TypeMap: ";
83       Pair.first->print(dbgs());
84       dbgs() << " => ";
85       Pair.second->print(dbgs());
86       dbgs() << '\n';
87     }
88   }
89
90 private:
91   Type *remapType(Type *SrcTy) override { return get(SrcTy); }
92
93   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
94 };
95 }
96
97 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
98   assert(SpeculativeTypes.empty());
99   assert(SpeculativeDstOpaqueTypes.empty());
100
101   // Check to see if these types are recursively isomorphic and establish a
102   // mapping between them if so.
103   if (!areTypesIsomorphic(DstTy, SrcTy)) {
104     // Oops, they aren't isomorphic.  Just discard this request by rolling out
105     // any speculative mappings we've established.
106     for (Type *Ty : SpeculativeTypes)
107       MappedTypes.erase(Ty);
108
109     SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
110                                    SpeculativeDstOpaqueTypes.size());
111     for (StructType *Ty : SpeculativeDstOpaqueTypes)
112       DstResolvedOpaqueTypes.erase(Ty);
113   } else {
114     for (Type *Ty : SpeculativeTypes)
115       if (auto *STy = dyn_cast<StructType>(Ty))
116         if (STy->hasName())
117           STy->setName("");
118   }
119   SpeculativeTypes.clear();
120   SpeculativeDstOpaqueTypes.clear();
121 }
122
123 /// Recursively walk this pair of types, returning true if they are isomorphic,
124 /// false if they are not.
125 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
126   // Two types with differing kinds are clearly not isomorphic.
127   if (DstTy->getTypeID() != SrcTy->getTypeID())
128     return false;
129
130   // If we have an entry in the MappedTypes table, then we have our answer.
131   Type *&Entry = MappedTypes[SrcTy];
132   if (Entry)
133     return Entry == DstTy;
134
135   // Two identical types are clearly isomorphic.  Remember this
136   // non-speculatively.
137   if (DstTy == SrcTy) {
138     Entry = DstTy;
139     return true;
140   }
141
142   // Okay, we have two types with identical kinds that we haven't seen before.
143
144   // If this is an opaque struct type, special case it.
145   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
146     // Mapping an opaque type to any struct, just keep the dest struct.
147     if (SSTy->isOpaque()) {
148       Entry = DstTy;
149       SpeculativeTypes.push_back(SrcTy);
150       return true;
151     }
152
153     // Mapping a non-opaque source type to an opaque dest.  If this is the first
154     // type that we're mapping onto this destination type then we succeed.  Keep
155     // the dest, but fill it in later. If this is the second (different) type
156     // that we're trying to map onto the same opaque type then we fail.
157     if (cast<StructType>(DstTy)->isOpaque()) {
158       // We can only map one source type onto the opaque destination type.
159       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
160         return false;
161       SrcDefinitionsToResolve.push_back(SSTy);
162       SpeculativeTypes.push_back(SrcTy);
163       SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
164       Entry = DstTy;
165       return true;
166     }
167   }
168
169   // If the number of subtypes disagree between the two types, then we fail.
170   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
171     return false;
172
173   // Fail if any of the extra properties (e.g. array size) of the type disagree.
174   if (isa<IntegerType>(DstTy))
175     return false;  // bitwidth disagrees.
176   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
177     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
178       return false;
179
180   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
181     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
182       return false;
183   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
184     StructType *SSTy = cast<StructType>(SrcTy);
185     if (DSTy->isLiteral() != SSTy->isLiteral() ||
186         DSTy->isPacked() != SSTy->isPacked())
187       return false;
188   } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
189     if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
190       return false;
191   } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
192     if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
193       return false;
194   }
195
196   // Otherwise, we speculate that these two types will line up and recursively
197   // check the subelements.
198   Entry = DstTy;
199   SpeculativeTypes.push_back(SrcTy);
200
201   for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
202     if (!areTypesIsomorphic(DstTy->getContainedType(I),
203                             SrcTy->getContainedType(I)))
204       return false;
205
206   // If everything seems to have lined up, then everything is great.
207   return true;
208 }
209
210 void TypeMapTy::linkDefinedTypeBodies() {
211   SmallVector<Type*, 16> Elements;
212   for (StructType *SrcSTy : SrcDefinitionsToResolve) {
213     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
214     assert(DstSTy->isOpaque());
215
216     // Map the body of the source type over to a new body for the dest type.
217     Elements.resize(SrcSTy->getNumElements());
218     for (unsigned I = 0, E = Elements.size(); I != E; ++I)
219       Elements[I] = get(SrcSTy->getElementType(I));
220
221     DstSTy->setBody(Elements, SrcSTy->isPacked());
222   }
223   SrcDefinitionsToResolve.clear();
224   DstResolvedOpaqueTypes.clear();
225 }
226
227 Type *TypeMapTy::get(Type *Ty) {
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   // If this is not a named struct type, then just map all of the elements and
234   // then rebuild the type from inside out.
235   if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
236     // If there are no element types to map, then the type is itself.  This is
237     // true for the anonymous {} struct, things like 'float', integers, etc.
238     if (Ty->getNumContainedTypes() == 0)
239       return *Entry = Ty;
240
241     // Remap all of the elements, keeping track of whether any of them change.
242     bool AnyChange = false;
243     SmallVector<Type*, 4> ElementTypes;
244     ElementTypes.resize(Ty->getNumContainedTypes());
245     for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
246       ElementTypes[I] = get(Ty->getContainedType(I));
247       AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
248     }
249
250     // If we found our type while recursively processing stuff, just use it.
251     Entry = &MappedTypes[Ty];
252     if (*Entry)
253       return *Entry;
254
255     // If all of the element types mapped directly over, then the type is usable
256     // as-is.
257     if (!AnyChange)
258       return *Entry = Ty;
259
260     // Otherwise, rebuild a modified type.
261     switch (Ty->getTypeID()) {
262     default:
263       llvm_unreachable("unknown derived type to remap");
264     case Type::ArrayTyID:
265       return *Entry = ArrayType::get(ElementTypes[0],
266                                      cast<ArrayType>(Ty)->getNumElements());
267     case Type::VectorTyID:
268       return *Entry = VectorType::get(ElementTypes[0],
269                                       cast<VectorType>(Ty)->getNumElements());
270     case Type::PointerTyID:
271       return *Entry = PointerType::get(
272                  ElementTypes[0], cast<PointerType>(Ty)->getAddressSpace());
273     case Type::FunctionTyID:
274       return *Entry = FunctionType::get(ElementTypes[0],
275                                         makeArrayRef(ElementTypes).slice(1),
276                                         cast<FunctionType>(Ty)->isVarArg());
277     case Type::StructTyID:
278       // Note that this is only reached for anonymous structs.
279       return *Entry = StructType::get(Ty->getContext(), ElementTypes,
280                                       cast<StructType>(Ty)->isPacked());
281     }
282   }
283
284   // Otherwise, this is an unmapped named struct.  If the struct can be directly
285   // mapped over, just use it as-is.  This happens in a case when the linked-in
286   // module has something like:
287   //   %T = type {%T*, i32}
288   //   @GV = global %T* null
289   // where T does not exist at all in the destination module.
290   //
291   // The other case we watch for is when the type is not in the destination
292   // module, but that it has to be rebuilt because it refers to something that
293   // is already mapped.  For example, if the destination module has:
294   //  %A = type { i32 }
295   // and the source module has something like
296   //  %A' = type { i32 }
297   //  %B = type { %A'* }
298   //  @GV = global %B* null
299   // then we want to create a new type: "%B = type { %A*}" and have it take the
300   // pristine "%B" name from the source module.
301   //
302   // To determine which case this is, we have to recursively walk the type graph
303   // speculating that we'll be able to reuse it unmodified.  Only if this is
304   // safe would we map the entire thing over.  Because this is an optimization,
305   // and is not required for the prettiness of the linked module, we just skip
306   // it and always rebuild a type here.
307   StructType *STy = cast<StructType>(Ty);
308
309   // If the type is opaque, we can just use it directly.
310   if (STy->isOpaque()) {
311     // A named structure type from src module is used. Add it to the Set of
312     // identified structs in the destination module.
313     return *Entry = STy;
314   }
315
316   // Otherwise we create a new type.
317   StructType *DTy = StructType::create(STy->getContext());
318   // A new identified structure type was created. Add it to the set of
319   // identified structs in the destination module.
320   *Entry = DTy;
321
322   SmallVector<Type*, 4> ElementTypes;
323   ElementTypes.resize(STy->getNumElements());
324   for (unsigned I = 0, E = ElementTypes.size(); I != E; ++I)
325     ElementTypes[I] = get(STy->getElementType(I));
326   DTy->setBody(ElementTypes, STy->isPacked());
327
328   // Steal STy's name.
329   if (STy->hasName()) {
330     SmallString<16> TmpName = STy->getName();
331     STy->setName("");
332     DTy->setName(TmpName);
333   }
334
335   return DTy;
336 }
337
338 //===----------------------------------------------------------------------===//
339 // ModuleLinker implementation.
340 //===----------------------------------------------------------------------===//
341
342 namespace {
343 class ModuleLinker;
344
345 /// Creates prototypes for functions that are lazily linked on the fly. This
346 /// speeds up linking for modules with many/ lazily linked functions of which
347 /// few get used.
348 class ValueMaterializerTy : public ValueMaterializer {
349   TypeMapTy &TypeMap;
350   Module *DstM;
351   std::vector<Function *> &LazilyLinkFunctions;
352
353 public:
354   ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
355                       std::vector<Function *> &LazilyLinkFunctions)
356       : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
357         LazilyLinkFunctions(LazilyLinkFunctions) {}
358
359   Value *materializeValueFor(Value *V) override;
360 };
361
362 class LinkDiagnosticInfo : public DiagnosticInfo {
363   const Twine &Msg;
364
365 public:
366   LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
367   void print(DiagnosticPrinter &DP) const override;
368 };
369 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
370                                        const Twine &Msg)
371     : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
372 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
373
374 /// This is an implementation class for the LinkModules function, which is the
375 /// entrypoint for this file.
376 class ModuleLinker {
377   Module *DstM, *SrcM;
378
379   TypeMapTy TypeMap;
380   ValueMaterializerTy ValMaterializer;
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
388   struct AppendingVarInfo {
389     GlobalVariable *NewGV;   // New aggregate global in dest module.
390     const Constant *DstInit; // Old initializer from dest module.
391     const Constant *SrcInit; // Old initializer from src module.
392   };
393
394   std::vector<AppendingVarInfo> AppendingVars;
395
396   // Set of items not to link in from source.
397   SmallPtrSet<const Value *, 16> DoNotLinkFromSource;
398
399   // Vector of functions to lazily link in.
400   std::vector<Function *> LazilyLinkFunctions;
401
402   Linker::DiagnosticHandlerFunction DiagnosticHandler;
403
404 public:
405   ModuleLinker(Module *dstM, Module *srcM,
406                Linker::DiagnosticHandlerFunction DiagnosticHandler)
407       : DstM(dstM), SrcM(srcM),
408         ValMaterializer(TypeMap, DstM, LazilyLinkFunctions),
409         DiagnosticHandler(DiagnosticHandler) {}
410
411   bool run();
412
413 private:
414   bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
415                             const GlobalValue &Src);
416
417   /// Helper method for setting a message and returning an error code.
418   bool emitError(const Twine &Message) {
419     DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
420     return true;
421   }
422
423   void emitWarning(const Twine &Message) {
424     DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
425   }
426
427   bool getComdatLeader(Module *M, StringRef ComdatName,
428                        const GlobalVariable *&GVar);
429   bool computeResultingSelectionKind(StringRef ComdatName,
430                                      Comdat::SelectionKind Src,
431                                      Comdat::SelectionKind Dst,
432                                      Comdat::SelectionKind &Result,
433                                      bool &LinkFromSrc);
434   std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
435       ComdatsChosen;
436   bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
437                        bool &LinkFromSrc);
438
439   /// Given a global in the source module, return the global in the
440   /// destination module that is being linked to, if any.
441   GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
442     // If the source has no name it can't link.  If it has local linkage,
443     // there is no name match-up going on.
444     if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
445       return nullptr;
446
447     // Otherwise see if we have a match in the destination module's symtab.
448     GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
449     if (!DGV)
450       return nullptr;
451
452     // If we found a global with the same name in the dest module, but it has
453     // internal linkage, we are really not doing any linkage here.
454     if (DGV->hasLocalLinkage())
455       return nullptr;
456
457     // Otherwise, we do in fact link to the destination global.
458     return DGV;
459   }
460
461   void computeTypeMapping();
462
463   void upgradeMismatchedGlobalArray(StringRef Name);
464   void upgradeMismatchedGlobals();
465
466   bool linkAppendingVarProto(GlobalVariable *DstGV,
467                              const GlobalVariable *SrcGV);
468
469   bool linkGlobalValueProto(GlobalValue *GV);
470   GlobalValue *linkGlobalVariableProto(const GlobalVariable *SGVar,
471                                        GlobalValue *DGV, bool LinkFromSrc);
472   GlobalValue *linkFunctionProto(const Function *SF, GlobalValue *DGV,
473                                  bool LinkFromSrc);
474   GlobalValue *linkGlobalAliasProto(const GlobalAlias *SGA, GlobalValue *DGV,
475                                     bool LinkFromSrc);
476
477   bool linkModuleFlagsMetadata();
478
479   void linkAppendingVarInit(const AppendingVarInfo &AVI);
480   void linkGlobalInits();
481   void linkFunctionBody(Function *Dst, Function *Src);
482   void linkAliasBodies();
483   void linkNamedMDNodes();
484 };
485 }
486
487 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
488 /// table. This is good for all clients except for us. Go through the trouble
489 /// to force this back.
490 static void forceRenaming(GlobalValue *GV, StringRef Name) {
491   // If the global doesn't force its name or if it already has the right name,
492   // there is nothing for us to do.
493   if (GV->hasLocalLinkage() || GV->getName() == Name)
494     return;
495
496   Module *M = GV->getParent();
497
498   // If there is a conflict, rename the conflict.
499   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
500     GV->takeName(ConflictGV);
501     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
502     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
503   } else {
504     GV->setName(Name);              // Force the name back
505   }
506 }
507
508 /// copy additional attributes (those not needed to construct a GlobalValue)
509 /// from the SrcGV to the DestGV.
510 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
511   // Use the maximum alignment, rather than just copying the alignment of SrcGV.
512   auto *DestGO = dyn_cast<GlobalObject>(DestGV);
513   unsigned Alignment;
514   if (DestGO)
515     Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
516
517   DestGV->copyAttributesFrom(SrcGV);
518
519   if (DestGO)
520     DestGO->setAlignment(Alignment);
521
522   forceRenaming(DestGV, SrcGV->getName());
523 }
524
525 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
526                                GlobalValue::VisibilityTypes b) {
527   if (a == GlobalValue::HiddenVisibility)
528     return false;
529   if (b == GlobalValue::HiddenVisibility)
530     return true;
531   if (a == GlobalValue::ProtectedVisibility)
532     return false;
533   if (b == GlobalValue::ProtectedVisibility)
534     return true;
535   return false;
536 }
537
538 Value *ValueMaterializerTy::materializeValueFor(Value *V) {
539   Function *SF = dyn_cast<Function>(V);
540   if (!SF)
541     return nullptr;
542
543   Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
544                                   SF->getLinkage(), SF->getName(), DstM);
545   copyGVAttributes(DF, SF);
546
547   if (Comdat *SC = SF->getComdat()) {
548     Comdat *DC = DstM->getOrInsertComdat(SC->getName());
549     DF->setComdat(DC);
550   }
551
552   LazilyLinkFunctions.push_back(SF);
553   return DF;
554 }
555
556 bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
557                                    const GlobalVariable *&GVar) {
558   const GlobalValue *GVal = M->getNamedValue(ComdatName);
559   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
560     GVal = GA->getBaseObject();
561     if (!GVal)
562       // We cannot resolve the size of the aliasee yet.
563       return emitError("Linking COMDATs named '" + ComdatName +
564                        "': COMDAT key involves incomputable alias size.");
565   }
566
567   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
568   if (!GVar)
569     return emitError(
570         "Linking COMDATs named '" + ComdatName +
571         "': GlobalVariable required for data dependent selection!");
572
573   return false;
574 }
575
576 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
577                                                  Comdat::SelectionKind Src,
578                                                  Comdat::SelectionKind Dst,
579                                                  Comdat::SelectionKind &Result,
580                                                  bool &LinkFromSrc) {
581   // The ability to mix Comdat::SelectionKind::Any with
582   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
583   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
584                          Dst == Comdat::SelectionKind::Largest;
585   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
586                          Src == Comdat::SelectionKind::Largest;
587   if (DstAnyOrLargest && SrcAnyOrLargest) {
588     if (Dst == Comdat::SelectionKind::Largest ||
589         Src == Comdat::SelectionKind::Largest)
590       Result = Comdat::SelectionKind::Largest;
591     else
592       Result = Comdat::SelectionKind::Any;
593   } else if (Src == Dst) {
594     Result = Dst;
595   } else {
596     return emitError("Linking COMDATs named '" + ComdatName +
597                      "': invalid selection kinds!");
598   }
599
600   switch (Result) {
601   case Comdat::SelectionKind::Any:
602     // Go with Dst.
603     LinkFromSrc = false;
604     break;
605   case Comdat::SelectionKind::NoDuplicates:
606     return emitError("Linking COMDATs named '" + ComdatName +
607                      "': noduplicates has been violated!");
608   case Comdat::SelectionKind::ExactMatch:
609   case Comdat::SelectionKind::Largest:
610   case Comdat::SelectionKind::SameSize: {
611     const GlobalVariable *DstGV;
612     const GlobalVariable *SrcGV;
613     if (getComdatLeader(DstM, ComdatName, DstGV) ||
614         getComdatLeader(SrcM, ComdatName, SrcGV))
615       return true;
616
617     const DataLayout *DstDL = DstM->getDataLayout();
618     const DataLayout *SrcDL = SrcM->getDataLayout();
619     if (!DstDL || !SrcDL) {
620       return emitError(
621           "Linking COMDATs named '" + ComdatName +
622           "': can't do size dependent selection without DataLayout!");
623     }
624     uint64_t DstSize =
625         DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
626     uint64_t SrcSize =
627         SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
628     if (Result == Comdat::SelectionKind::ExactMatch) {
629       if (SrcGV->getInitializer() != DstGV->getInitializer())
630         return emitError("Linking COMDATs named '" + ComdatName +
631                          "': ExactMatch violated!");
632       LinkFromSrc = false;
633     } else if (Result == Comdat::SelectionKind::Largest) {
634       LinkFromSrc = SrcSize > DstSize;
635     } else if (Result == Comdat::SelectionKind::SameSize) {
636       if (SrcSize != DstSize)
637         return emitError("Linking COMDATs named '" + ComdatName +
638                          "': SameSize violated!");
639       LinkFromSrc = false;
640     } else {
641       llvm_unreachable("unknown selection kind");
642     }
643     break;
644   }
645   }
646
647   return false;
648 }
649
650 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
651                                    Comdat::SelectionKind &Result,
652                                    bool &LinkFromSrc) {
653   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
654   StringRef ComdatName = SrcC->getName();
655   Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
656   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
657
658   if (DstCI == ComdatSymTab.end()) {
659     // Use the comdat if it is only available in one of the modules.
660     LinkFromSrc = true;
661     Result = SSK;
662     return false;
663   }
664
665   const Comdat *DstC = &DstCI->second;
666   Comdat::SelectionKind DSK = DstC->getSelectionKind();
667   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
668                                        LinkFromSrc);
669 }
670
671 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
672                                         const GlobalValue &Dest,
673                                         const GlobalValue &Src) {
674   // We always have to add Src if it has appending linkage.
675   if (Src.hasAppendingLinkage()) {
676     LinkFromSrc = true;
677     return false;
678   }
679
680   bool SrcIsDeclaration = Src.isDeclarationForLinker();
681   bool DestIsDeclaration = Dest.isDeclarationForLinker();
682
683   if (SrcIsDeclaration) {
684     // If Src is external or if both Src & Dest are external..  Just link the
685     // external globals, we aren't adding anything.
686     if (Src.hasDLLImportStorageClass()) {
687       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
688       LinkFromSrc = DestIsDeclaration;
689       return false;
690     }
691     // If the Dest is weak, use the source linkage.
692     LinkFromSrc = Dest.hasExternalWeakLinkage();
693     return false;
694   }
695
696   if (DestIsDeclaration) {
697     // If Dest is external but Src is not:
698     LinkFromSrc = true;
699     return false;
700   }
701
702   if (Src.hasCommonLinkage()) {
703     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
704       LinkFromSrc = true;
705       return false;
706     }
707
708     if (!Dest.hasCommonLinkage()) {
709       LinkFromSrc = false;
710       return false;
711     }
712
713     // FIXME: Make datalayout mandatory and just use getDataLayout().
714     DataLayout DL(Dest.getParent());
715
716     uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
717     uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
718     LinkFromSrc = SrcSize > DestSize;
719     return false;
720   }
721
722   if (Src.isWeakForLinker()) {
723     assert(!Dest.hasExternalWeakLinkage());
724     assert(!Dest.hasAvailableExternallyLinkage());
725
726     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
727       LinkFromSrc = true;
728       return false;
729     }
730
731     LinkFromSrc = false;
732     return false;
733   }
734
735   if (Dest.isWeakForLinker()) {
736     assert(Src.hasExternalLinkage());
737     LinkFromSrc = true;
738     return false;
739   }
740
741   assert(!Src.hasExternalWeakLinkage());
742   assert(!Dest.hasExternalWeakLinkage());
743   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
744          "Unexpected linkage type!");
745   return emitError("Linking globals named '" + Src.getName() +
746                    "': symbol multiply defined!");
747 }
748
749 /// Loop over all of the linked values to compute type mappings.  For example,
750 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
751 /// types 'Foo' but one got renamed when the module was loaded into the same
752 /// LLVMContext.
753 void ModuleLinker::computeTypeMapping() {
754   for (GlobalValue &SGV : SrcM->globals()) {
755     GlobalValue *DGV = getLinkedToGlobal(&SGV);
756     if (!DGV)
757       continue;
758
759     if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
760       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
761       continue;
762     }
763
764     // Unify the element type of appending arrays.
765     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
766     ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
767     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
768   }
769
770   for (GlobalValue &SGV : *SrcM) {
771     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
772       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
773   }
774
775   for (GlobalValue &SGV : SrcM->aliases()) {
776     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
777       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
778   }
779
780   // Incorporate types by name, scanning all the types in the source module.
781   // At this point, the destination module may have a type "%foo = { i32 }" for
782   // example.  When the source module got loaded into the same LLVMContext, if
783   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
784   TypeFinder SrcStructTypes;
785   SrcStructTypes.run(*SrcM, true);
786   SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
787                                                  SrcStructTypes.end());
788
789   for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
790     StructType *ST = SrcStructTypes[i];
791     if (!ST->hasName()) continue;
792
793     // Check to see if there is a dot in the name followed by a digit.
794     size_t DotPos = ST->getName().rfind('.');
795     if (DotPos == 0 || DotPos == StringRef::npos ||
796         ST->getName().back() == '.' ||
797         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
798       continue;
799
800     // Check to see if the destination module has a struct with the prefix name.
801     if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
802       // Don't use it if this actually came from the source module. They're in
803       // the same LLVMContext after all. Also don't use it unless the type is
804       // actually used in the destination module. This can happen in situations
805       // like this:
806       //
807       //      Module A                         Module B
808       //      --------                         --------
809       //   %Z = type { %A }                %B = type { %C.1 }
810       //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
811       //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
812       //   %C = type { i8* }               %B.3 = type { %C.1 }
813       //
814       // When we link Module B with Module A, the '%B' in Module B is
815       // used. However, that would then use '%C.1'. But when we process '%C.1',
816       // we prefer to take the '%C' version. So we are then left with both
817       // '%C.1' and '%C' being used for the same types. This leads to some
818       // variables using one type and some using the other.
819       if (!SrcStructTypesSet.count(DST))
820         TypeMap.addTypeMapping(DST, ST);
821   }
822
823   // Now that we have discovered all of the type equivalences, get a body for
824   // any 'opaque' types in the dest module that are now resolved.
825   TypeMap.linkDefinedTypeBodies();
826 }
827
828 static void upgradeGlobalArray(GlobalVariable *GV) {
829   ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
830   StructType *OldTy = cast<StructType>(ATy->getElementType());
831   assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
832
833   // Get the upgraded 3 element type.
834   PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
835   Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
836                   VoidPtrTy};
837   StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
838
839   // Build new constants with a null third field filled in.
840   Constant *OldInitC = GV->getInitializer();
841   ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
842   if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
843     // Invalid initializer; give up.
844     return;
845   std::vector<Constant *> Initializers;
846   if (OldInit && OldInit->getNumOperands()) {
847     Value *Null = Constant::getNullValue(VoidPtrTy);
848     for (Use &U : OldInit->operands()) {
849       ConstantStruct *Init = cast<ConstantStruct>(U.get());
850       Initializers.push_back(ConstantStruct::get(
851           NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
852     }
853   }
854   assert(Initializers.size() == ATy->getNumElements() &&
855          "Failed to copy all array elements");
856
857   // Replace the old GV with a new one.
858   ATy = ArrayType::get(NewTy, Initializers.size());
859   Constant *NewInit = ConstantArray::get(ATy, Initializers);
860   GlobalVariable *NewGV = new GlobalVariable(
861       *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
862       GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
863       GV->isExternallyInitialized());
864   NewGV->copyAttributesFrom(GV);
865   NewGV->takeName(GV);
866   assert(GV->use_empty() && "program cannot use initializer list");
867   GV->eraseFromParent();
868 }
869
870 void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
871   // Look for the global arrays.
872   auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
873   if (!DstGV)
874     return;
875   auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
876   if (!SrcGV)
877     return;
878
879   // Check if the types already match.
880   auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
881   auto *SrcTy =
882       cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
883   if (DstTy == SrcTy)
884     return;
885
886   // Grab the element types.  We can only upgrade an array of a two-field
887   // struct.  Only bother if the other one has three-fields.
888   auto *DstEltTy = cast<StructType>(DstTy->getElementType());
889   auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
890   if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
891     upgradeGlobalArray(DstGV);
892     return;
893   }
894   if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
895     upgradeGlobalArray(SrcGV);
896
897   // We can't upgrade any other differences.
898 }
899
900 void ModuleLinker::upgradeMismatchedGlobals() {
901   upgradeMismatchedGlobalArray("llvm.global_ctors");
902   upgradeMismatchedGlobalArray("llvm.global_dtors");
903 }
904
905 /// If there were any appending global variables, link them together now.
906 /// Return true on error.
907 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
908                                          const GlobalVariable *SrcGV) {
909
910   if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
911     return emitError("Linking globals named '" + SrcGV->getName() +
912            "': can only link appending global with another appending global!");
913
914   ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
915   ArrayType *SrcTy =
916     cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
917   Type *EltTy = DstTy->getElementType();
918
919   // Check to see that they two arrays agree on type.
920   if (EltTy != SrcTy->getElementType())
921     return emitError("Appending variables with different element types!");
922   if (DstGV->isConstant() != SrcGV->isConstant())
923     return emitError("Appending variables linked with different const'ness!");
924
925   if (DstGV->getAlignment() != SrcGV->getAlignment())
926     return emitError(
927              "Appending variables with different alignment need to be linked!");
928
929   if (DstGV->getVisibility() != SrcGV->getVisibility())
930     return emitError(
931             "Appending variables with different visibility need to be linked!");
932
933   if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
934     return emitError(
935         "Appending variables with different unnamed_addr need to be linked!");
936
937   if (StringRef(DstGV->getSection()) != SrcGV->getSection())
938     return emitError(
939           "Appending variables with different section name need to be linked!");
940
941   uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
942   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
943
944   // Create the new global variable.
945   GlobalVariable *NG =
946     new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
947                        DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
948                        DstGV->getThreadLocalMode(),
949                        DstGV->getType()->getAddressSpace());
950
951   // Propagate alignment, visibility and section info.
952   copyGVAttributes(NG, DstGV);
953
954   AppendingVarInfo AVI;
955   AVI.NewGV = NG;
956   AVI.DstInit = DstGV->getInitializer();
957   AVI.SrcInit = SrcGV->getInitializer();
958   AppendingVars.push_back(AVI);
959
960   // Replace any uses of the two global variables with uses of the new
961   // global.
962   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
963
964   DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
965   DstGV->eraseFromParent();
966
967   // Track the source variable so we don't try to link it.
968   DoNotLinkFromSource.insert(SrcGV);
969
970   return false;
971 }
972
973 bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
974   GlobalValue *DGV = getLinkedToGlobal(SGV);
975
976   // Handle the ultra special appending linkage case first.
977   if (DGV && DGV->hasAppendingLinkage())
978     return linkAppendingVarProto(cast<GlobalVariable>(DGV),
979                                  cast<GlobalVariable>(SGV));
980
981   bool LinkFromSrc = true;
982   Comdat *C = nullptr;
983   GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
984   bool HasUnnamedAddr = SGV->hasUnnamedAddr();
985
986   if (const Comdat *SC = SGV->getComdat()) {
987     Comdat::SelectionKind SK;
988     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
989     C = DstM->getOrInsertComdat(SC->getName());
990     C->setSelectionKind(SK);
991   } else if (DGV) {
992     if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
993       return true;
994   }
995
996   if (!LinkFromSrc) {
997     // Track the source global so that we don't attempt to copy it over when
998     // processing global initializers.
999     DoNotLinkFromSource.insert(SGV);
1000
1001     if (DGV)
1002       // Make sure to remember this mapping.
1003       ValueMap[SGV] =
1004           ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
1005   }
1006
1007   if (DGV) {
1008     Visibility = isLessConstraining(Visibility, DGV->getVisibility())
1009                      ? DGV->getVisibility()
1010                      : Visibility;
1011     HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1012   }
1013
1014   if (!LinkFromSrc && !DGV)
1015     return false;
1016
1017   GlobalValue *NewGV;
1018   if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
1019     NewGV = linkGlobalVariableProto(SGVar, DGV, LinkFromSrc);
1020     if (!NewGV)
1021       return true;
1022   } else if (auto *SF = dyn_cast<Function>(SGV)) {
1023     NewGV = linkFunctionProto(SF, DGV, LinkFromSrc);
1024   } else {
1025     NewGV = linkGlobalAliasProto(cast<GlobalAlias>(SGV), DGV, LinkFromSrc);
1026   }
1027
1028   if (NewGV) {
1029     if (NewGV != DGV)
1030       copyGVAttributes(NewGV, SGV);
1031
1032     NewGV->setUnnamedAddr(HasUnnamedAddr);
1033     NewGV->setVisibility(Visibility);
1034
1035     if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1036       if (C)
1037         NewGO->setComdat(C);
1038     }
1039
1040     // Make sure to remember this mapping.
1041     if (NewGV != DGV) {
1042       if (DGV) {
1043         DGV->replaceAllUsesWith(
1044             ConstantExpr::getBitCast(NewGV, DGV->getType()));
1045         DGV->eraseFromParent();
1046       }
1047       ValueMap[SGV] = NewGV;
1048     }
1049   }
1050
1051   return false;
1052 }
1053
1054 /// Loop through the global variables in the src module and merge them into the
1055 /// dest module.
1056 GlobalValue *ModuleLinker::linkGlobalVariableProto(const GlobalVariable *SGVar,
1057                                                    GlobalValue *DGV,
1058                                                    bool LinkFromSrc) {
1059   unsigned Alignment = 0;
1060   bool ClearConstant = false;
1061
1062   if (DGV) {
1063     if (DGV->hasCommonLinkage() && SGVar->hasCommonLinkage())
1064       Alignment = std::max(SGVar->getAlignment(), DGV->getAlignment());
1065
1066     auto *DGVar = dyn_cast<GlobalVariable>(DGV);
1067     if (!SGVar->isConstant() || (DGVar && !DGVar->isConstant()))
1068       ClearConstant = true;
1069   }
1070
1071   if (!LinkFromSrc) {
1072     if (auto *NewGVar = dyn_cast<GlobalVariable>(DGV)) {
1073       if (Alignment)
1074         NewGVar->setAlignment(Alignment);
1075       if (NewGVar->isDeclaration() && ClearConstant)
1076         NewGVar->setConstant(false);
1077     }
1078     return DGV;
1079   }
1080
1081   // No linking to be performed or linking from the source: simply create an
1082   // identical version of the symbol over in the dest module... the
1083   // initializer will be filled in later by LinkGlobalInits.
1084   GlobalVariable *NewDGV = new GlobalVariable(
1085       *DstM, TypeMap.get(SGVar->getType()->getElementType()),
1086       SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr,
1087       SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
1088       SGVar->getType()->getAddressSpace());
1089
1090   if (Alignment)
1091     NewDGV->setAlignment(Alignment);
1092
1093   return NewDGV;
1094 }
1095
1096 /// Link the function in the source module into the destination module if
1097 /// needed, setting up mapping information.
1098 GlobalValue *ModuleLinker::linkFunctionProto(const Function *SF,
1099                                              GlobalValue *DGV,
1100                                              bool LinkFromSrc) {
1101   if (!LinkFromSrc)
1102     return DGV;
1103
1104   // If the function is to be lazily linked, don't create it just yet.
1105   // The ValueMaterializerTy will deal with creating it if it's used.
1106   if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1107                SF->hasAvailableExternallyLinkage())) {
1108     DoNotLinkFromSource.insert(SF);
1109     return nullptr;
1110   }
1111
1112   // If there is no linkage to be performed or we are linking from the source,
1113   // bring SF over.
1114   return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(),
1115                           SF->getName(), DstM);
1116 }
1117
1118 /// Set up prototypes for any aliases that come over from the source module.
1119 GlobalValue *ModuleLinker::linkGlobalAliasProto(const GlobalAlias *SGA,
1120                                                 GlobalValue *DGV,
1121                                                 bool LinkFromSrc) {
1122   if (!LinkFromSrc)
1123     return DGV;
1124
1125   // If there is no linkage to be performed or we're linking from the source,
1126   // bring over SGA.
1127   auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
1128   return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1129                              SGA->getLinkage(), SGA->getName(), DstM);
1130 }
1131
1132 static void getArrayElements(const Constant *C,
1133                              SmallVectorImpl<Constant *> &Dest) {
1134   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1135
1136   for (unsigned i = 0; i != NumElements; ++i)
1137     Dest.push_back(C->getAggregateElement(i));
1138 }
1139
1140 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1141   // Merge the initializer.
1142   SmallVector<Constant *, 16> DstElements;
1143   getArrayElements(AVI.DstInit, DstElements);
1144
1145   SmallVector<Constant *, 16> SrcElements;
1146   getArrayElements(AVI.SrcInit, SrcElements);
1147
1148   ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1149
1150   StringRef Name = AVI.NewGV->getName();
1151   bool IsNewStructor =
1152       (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1153       cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1154
1155   for (auto *V : SrcElements) {
1156     if (IsNewStructor) {
1157       Constant *Key = V->getAggregateElement(2);
1158       if (DoNotLinkFromSource.count(Key))
1159         continue;
1160     }
1161     DstElements.push_back(
1162         MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1163   }
1164   if (IsNewStructor) {
1165     NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1166     AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1167   }
1168
1169   AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1170 }
1171
1172 /// Update the initializers in the Dest module now that all globals that may be
1173 /// referenced are in Dest.
1174 void ModuleLinker::linkGlobalInits() {
1175   // Loop over all of the globals in the src module, mapping them over as we go
1176   for (Module::const_global_iterator I = SrcM->global_begin(),
1177        E = SrcM->global_end(); I != E; ++I) {
1178
1179     // Only process initialized GV's or ones not already in dest.
1180     if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1181
1182     // Grab destination global variable.
1183     GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1184     // Figure out what the initializer looks like in the dest module.
1185     DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
1186                                  RF_None, &TypeMap, &ValMaterializer));
1187   }
1188 }
1189
1190 /// Copy the source function over into the dest function and fix up references
1191 /// to values. At this point we know that Dest is an external function, and
1192 /// that Src is not.
1193 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1194   assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
1195
1196   // Go through and convert function arguments over, remembering the mapping.
1197   Function::arg_iterator DI = Dst->arg_begin();
1198   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1199        I != E; ++I, ++DI) {
1200     DI->setName(I->getName());  // Copy the name over.
1201
1202     // Add a mapping to our mapping.
1203     ValueMap[I] = DI;
1204   }
1205
1206   // Splice the body of the source function into the dest function.
1207   Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
1208
1209   // At this point, all of the instructions and values of the function are now
1210   // copied over.  The only problem is that they are still referencing values in
1211   // the Source function as operands.  Loop through all of the operands of the
1212   // functions and patch them up to point to the local versions.
1213   for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1214     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1215       RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap,
1216                        &ValMaterializer);
1217
1218   // There is no need to map the arguments anymore.
1219   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1220        I != E; ++I)
1221     ValueMap.erase(I);
1222
1223 }
1224
1225 /// Insert all of the aliases in Src into the Dest module.
1226 void ModuleLinker::linkAliasBodies() {
1227   for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
1228        I != E; ++I) {
1229     if (DoNotLinkFromSource.count(I))
1230       continue;
1231     if (Constant *Aliasee = I->getAliasee()) {
1232       GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
1233       Constant *Val =
1234           MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1235       DA->setAliasee(Val);
1236     }
1237   }
1238 }
1239
1240 /// Insert all of the named MDNodes in Src into the Dest module.
1241 void ModuleLinker::linkNamedMDNodes() {
1242   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1243   for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1244        E = SrcM->named_metadata_end(); I != E; ++I) {
1245     // Don't link module flags here. Do them separately.
1246     if (&*I == SrcModFlags) continue;
1247     NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1248     // Add Src elements into Dest node.
1249     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1250       DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
1251                                    RF_None, &TypeMap, &ValMaterializer));
1252   }
1253 }
1254
1255 /// Merge the linker flags in Src into the Dest module.
1256 bool ModuleLinker::linkModuleFlagsMetadata() {
1257   // If the source module has no module flags, we are done.
1258   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1259   if (!SrcModFlags) return false;
1260
1261   // If the destination module doesn't have module flags yet, then just copy
1262   // over the source module's flags.
1263   NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1264   if (DstModFlags->getNumOperands() == 0) {
1265     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1266       DstModFlags->addOperand(SrcModFlags->getOperand(I));
1267
1268     return false;
1269   }
1270
1271   // First build a map of the existing module flags and requirements.
1272   DenseMap<MDString*, MDNode*> Flags;
1273   SmallSetVector<MDNode*, 16> Requirements;
1274   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1275     MDNode *Op = DstModFlags->getOperand(I);
1276     ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1277     MDString *ID = cast<MDString>(Op->getOperand(1));
1278
1279     if (Behavior->getZExtValue() == Module::Require) {
1280       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1281     } else {
1282       Flags[ID] = Op;
1283     }
1284   }
1285
1286   // Merge in the flags from the source module, and also collect its set of
1287   // requirements.
1288   bool HasErr = false;
1289   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1290     MDNode *SrcOp = SrcModFlags->getOperand(I);
1291     ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1292     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1293     MDNode *DstOp = Flags.lookup(ID);
1294     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1295
1296     // If this is a requirement, add it and continue.
1297     if (SrcBehaviorValue == Module::Require) {
1298       // If the destination module does not already have this requirement, add
1299       // it.
1300       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1301         DstModFlags->addOperand(SrcOp);
1302       }
1303       continue;
1304     }
1305
1306     // If there is no existing flag with this ID, just add it.
1307     if (!DstOp) {
1308       Flags[ID] = SrcOp;
1309       DstModFlags->addOperand(SrcOp);
1310       continue;
1311     }
1312
1313     // Otherwise, perform a merge.
1314     ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1315     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1316
1317     // If either flag has override behavior, handle it first.
1318     if (DstBehaviorValue == Module::Override) {
1319       // Diagnose inconsistent flags which both have override behavior.
1320       if (SrcBehaviorValue == Module::Override &&
1321           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1322         HasErr |= emitError("linking module flags '" + ID->getString() +
1323                             "': IDs have conflicting override values");
1324       }
1325       continue;
1326     } else if (SrcBehaviorValue == Module::Override) {
1327       // Update the destination flag to that of the source.
1328       DstOp->replaceOperandWith(0, SrcBehavior);
1329       DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1330       continue;
1331     }
1332
1333     // Diagnose inconsistent merge behavior types.
1334     if (SrcBehaviorValue != DstBehaviorValue) {
1335       HasErr |= emitError("linking module flags '" + ID->getString() +
1336                           "': IDs have conflicting behaviors");
1337       continue;
1338     }
1339
1340     // Perform the merge for standard behavior types.
1341     switch (SrcBehaviorValue) {
1342     case Module::Require:
1343     case Module::Override: llvm_unreachable("not possible");
1344     case Module::Error: {
1345       // Emit an error if the values differ.
1346       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1347         HasErr |= emitError("linking module flags '" + ID->getString() +
1348                             "': IDs have conflicting values");
1349       }
1350       continue;
1351     }
1352     case Module::Warning: {
1353       // Emit a warning if the values differ.
1354       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1355         emitWarning("linking module flags '" + ID->getString() +
1356                     "': IDs have conflicting values");
1357       }
1358       continue;
1359     }
1360     case Module::Append: {
1361       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1362       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1363       unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1364       Value **VP, **Values = VP = new Value*[NumOps];
1365       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1366         *VP = DstValue->getOperand(i);
1367       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1368         *VP = SrcValue->getOperand(i);
1369       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1370                                                ArrayRef<Value*>(Values,
1371                                                                 NumOps)));
1372       delete[] Values;
1373       break;
1374     }
1375     case Module::AppendUnique: {
1376       SmallSetVector<Value*, 16> Elts;
1377       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1378       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1379       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1380         Elts.insert(DstValue->getOperand(i));
1381       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1382         Elts.insert(SrcValue->getOperand(i));
1383       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1384                                                ArrayRef<Value*>(Elts.begin(),
1385                                                                 Elts.end())));
1386       break;
1387     }
1388     }
1389   }
1390
1391   // Check all of the requirements.
1392   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1393     MDNode *Requirement = Requirements[I];
1394     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1395     Value *ReqValue = Requirement->getOperand(1);
1396
1397     MDNode *Op = Flags[Flag];
1398     if (!Op || Op->getOperand(2) != ReqValue) {
1399       HasErr |= emitError("linking module flags '" + Flag->getString() +
1400                           "': does not have the required value");
1401       continue;
1402     }
1403   }
1404
1405   return HasErr;
1406 }
1407
1408 bool ModuleLinker::run() {
1409   assert(DstM && "Null destination module");
1410   assert(SrcM && "Null source module");
1411
1412   // Inherit the target data from the source module if the destination module
1413   // doesn't have one already.
1414   if (!DstM->getDataLayout() && SrcM->getDataLayout())
1415     DstM->setDataLayout(SrcM->getDataLayout());
1416
1417   // Copy the target triple from the source to dest if the dest's is empty.
1418   if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1419     DstM->setTargetTriple(SrcM->getTargetTriple());
1420
1421   if (SrcM->getDataLayout() && DstM->getDataLayout() &&
1422       *SrcM->getDataLayout() != *DstM->getDataLayout()) {
1423     emitWarning("Linking two modules of different data layouts: '" +
1424                 SrcM->getModuleIdentifier() + "' is '" +
1425                 SrcM->getDataLayoutStr() + "' whereas '" +
1426                 DstM->getModuleIdentifier() + "' is '" +
1427                 DstM->getDataLayoutStr() + "'\n");
1428   }
1429   if (!SrcM->getTargetTriple().empty() &&
1430       DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1431     emitWarning("Linking two modules of different target triples: " +
1432                 SrcM->getModuleIdentifier() + "' is '" +
1433                 SrcM->getTargetTriple() + "' whereas '" +
1434                 DstM->getModuleIdentifier() + "' is '" +
1435                 DstM->getTargetTriple() + "'\n");
1436   }
1437
1438   // Append the module inline asm string.
1439   if (!SrcM->getModuleInlineAsm().empty()) {
1440     if (DstM->getModuleInlineAsm().empty())
1441       DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1442     else
1443       DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1444                                SrcM->getModuleInlineAsm());
1445   }
1446
1447   // Loop over all of the linked values to compute type mappings.
1448   computeTypeMapping();
1449
1450   ComdatsChosen.clear();
1451   for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
1452     const Comdat &C = SMEC.getValue();
1453     if (ComdatsChosen.count(&C))
1454       continue;
1455     Comdat::SelectionKind SK;
1456     bool LinkFromSrc;
1457     if (getComdatResult(&C, SK, LinkFromSrc))
1458       return true;
1459     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1460   }
1461
1462   // Upgrade mismatched global arrays.
1463   upgradeMismatchedGlobals();
1464
1465   // Insert all of the globals in src into the DstM module... without linking
1466   // initializers (which could refer to functions not yet mapped over).
1467   for (Module::global_iterator I = SrcM->global_begin(),
1468        E = SrcM->global_end(); I != E; ++I)
1469     if (linkGlobalValueProto(I))
1470       return true;
1471
1472   // Link the functions together between the two modules, without doing function
1473   // bodies... this just adds external function prototypes to the DstM
1474   // function...  We do this so that when we begin processing function bodies,
1475   // all of the global values that may be referenced are available in our
1476   // ValueMap.
1477   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1478     if (linkGlobalValueProto(I))
1479       return true;
1480
1481   // If there were any aliases, link them now.
1482   for (Module::alias_iterator I = SrcM->alias_begin(),
1483        E = SrcM->alias_end(); I != E; ++I)
1484     if (linkGlobalValueProto(I))
1485       return true;
1486
1487   for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1488     linkAppendingVarInit(AppendingVars[i]);
1489
1490   // Link in the function bodies that are defined in the source module into
1491   // DstM.
1492   for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1493     // Skip if not linking from source.
1494     if (DoNotLinkFromSource.count(SF)) continue;
1495
1496     Function *DF = cast<Function>(ValueMap[SF]);
1497     if (SF->hasPrefixData()) {
1498       // Link in the prefix data.
1499       DF->setPrefixData(MapValue(
1500           SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1501     }
1502
1503     // Materialize if needed.
1504     if (std::error_code EC = SF->materialize())
1505       return emitError(EC.message());
1506
1507     // Skip if no body (function is external).
1508     if (SF->isDeclaration())
1509       continue;
1510
1511     linkFunctionBody(DF, SF);
1512     SF->Dematerialize();
1513   }
1514
1515   // Resolve all uses of aliases with aliasees.
1516   linkAliasBodies();
1517
1518   // Remap all of the named MDNodes in Src into the DstM module. We do this
1519   // after linking GlobalValues so that MDNodes that reference GlobalValues
1520   // are properly remapped.
1521   linkNamedMDNodes();
1522
1523   // Merge the module flags into the DstM module.
1524   if (linkModuleFlagsMetadata())
1525     return true;
1526
1527   // Update the initializers in the DstM module now that all globals that may
1528   // be referenced are in DstM.
1529   linkGlobalInits();
1530
1531   // Process vector of lazily linked in functions.
1532   bool LinkedInAnyFunctions;
1533   do {
1534     LinkedInAnyFunctions = false;
1535
1536     for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1537         E = LazilyLinkFunctions.end(); I != E; ++I) {
1538       Function *SF = *I;
1539       if (!SF)
1540         continue;
1541
1542       Function *DF = cast<Function>(ValueMap[SF]);
1543       if (SF->hasPrefixData()) {
1544         // Link in the prefix data.
1545         DF->setPrefixData(MapValue(SF->getPrefixData(),
1546                                    ValueMap,
1547                                    RF_None,
1548                                    &TypeMap,
1549                                    &ValMaterializer));
1550       }
1551
1552       // Materialize if needed.
1553       if (std::error_code EC = SF->materialize())
1554         return emitError(EC.message());
1555
1556       // Skip if no body (function is external).
1557       if (SF->isDeclaration())
1558         continue;
1559
1560       // Erase from vector *before* the function body is linked - linkFunctionBody could
1561       // invalidate I.
1562       LazilyLinkFunctions.erase(I);
1563
1564       // Link in function body.
1565       linkFunctionBody(DF, SF);
1566       SF->Dematerialize();
1567
1568       // Set flag to indicate we may have more functions to lazily link in
1569       // since we linked in a function.
1570       LinkedInAnyFunctions = true;
1571       break;
1572     }
1573   } while (LinkedInAnyFunctions);
1574
1575   return false;
1576 }
1577
1578 void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1579   this->Composite = M;
1580   this->DiagnosticHandler = DiagnosticHandler;
1581 }
1582
1583 Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1584   init(M, DiagnosticHandler);
1585 }
1586
1587 Linker::Linker(Module *M) {
1588   init(M, [this](const DiagnosticInfo &DI) {
1589     Composite->getContext().diagnose(DI);
1590   });
1591 }
1592
1593 Linker::~Linker() {
1594 }
1595
1596 void Linker::deleteModule() {
1597   delete Composite;
1598   Composite = nullptr;
1599 }
1600
1601 bool Linker::linkInModule(Module *Src) {
1602   ModuleLinker TheLinker(Composite, Src, DiagnosticHandler);
1603   return TheLinker.run();
1604 }
1605
1606 //===----------------------------------------------------------------------===//
1607 // LinkModules entrypoint.
1608 //===----------------------------------------------------------------------===//
1609
1610 /// This function links two modules together, with the resulting Dest module
1611 /// modified to be the composite of the two input modules. If an error occurs,
1612 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
1613 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
1614 /// relied on to be consistent.
1615 bool Linker::LinkModules(Module *Dest, Module *Src,
1616                          DiagnosticHandlerFunction DiagnosticHandler) {
1617   Linker L(Dest, DiagnosticHandler);
1618   return L.linkInModule(Src);
1619 }
1620
1621 bool Linker::LinkModules(Module *Dest, Module *Src) {
1622   Linker L(Dest);
1623   return L.linkInModule(Src);
1624 }
1625
1626 //===----------------------------------------------------------------------===//
1627 // C API.
1628 //===----------------------------------------------------------------------===//
1629
1630 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1631                          LLVMLinkerMode Mode, char **OutMessages) {
1632   Module *D = unwrap(Dest);
1633   std::string Message;
1634   raw_string_ostream Stream(Message);
1635   DiagnosticPrinterRawOStream DP(Stream);
1636
1637   LLVMBool Result = Linker::LinkModules(
1638       D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
1639
1640   if (OutMessages && Result)
1641     *OutMessages = strdup(Message.c_str());
1642   return Result;
1643 }