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