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