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