1 //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LLVM module linker.
12 //===----------------------------------------------------------------------===//
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"
34 //===----------------------------------------------------------------------===//
35 // TypeMap implementation.
36 //===----------------------------------------------------------------------===//
39 typedef SmallPtrSet<StructType *, 32> TypeSet;
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;
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
48 SmallVector<Type*, 16> SpeculativeTypes;
50 SmallVector<StructType*, 16> SpeculativeDstOpaqueTypes;
52 /// This is a list of non-opaque structs in the source module that are mapped
53 /// to an opaque struct in the destination module.
54 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
56 /// This is the set of opaque types in the destination modules who are
57 /// getting a body from the source module.
58 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
61 TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {}
63 TypeSet &DstStructTypesSet;
64 /// Indicate that the specified type in the destination module is conceptually
65 /// equivalent to the specified type in the source module.
66 void addTypeMapping(Type *DstTy, Type *SrcTy);
68 /// Produce a body for an opaque type in the dest module from a type
69 /// definition in the source module.
70 void linkDefinedTypeBodies();
72 /// Return the mapped type to use for the specified input type from the
74 Type *get(Type *SrcTy);
76 FunctionType *get(FunctionType *T) {
77 return cast<FunctionType>(get((Type *)T));
80 /// Dump out the type map for debugging purposes.
82 for (auto &Pair : MappedTypes) {
83 dbgs() << "TypeMap: ";
84 Pair.first->print(dbgs());
86 Pair.second->print(dbgs());
92 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
94 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
98 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
99 assert(SpeculativeTypes.empty());
100 assert(SpeculativeDstOpaqueTypes.empty());
102 // Check to see if these types are recursively isomorphic and establish a
103 // mapping between them if so.
104 if (!areTypesIsomorphic(DstTy, SrcTy)) {
105 // Oops, they aren't isomorphic. Just discard this request by rolling out
106 // any speculative mappings we've established.
107 for (Type *Ty : SpeculativeTypes)
108 MappedTypes.erase(Ty);
110 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
111 SpeculativeDstOpaqueTypes.size());
112 for (StructType *Ty : SpeculativeDstOpaqueTypes)
113 DstResolvedOpaqueTypes.erase(Ty);
115 SpeculativeTypes.clear();
116 SpeculativeDstOpaqueTypes.clear();
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())
126 // If we have an entry in the MappedTypes table, then we have our answer.
127 Type *&Entry = MappedTypes[SrcTy];
129 return Entry == DstTy;
131 // Two identical types are clearly isomorphic. Remember this
132 // non-speculatively.
133 if (DstTy == SrcTy) {
138 // Okay, we have two types with identical kinds that we haven't seen before.
140 // If this is an opaque struct type, special case it.
141 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
142 // Mapping an opaque type to any struct, just keep the dest struct.
143 if (SSTy->isOpaque()) {
145 SpeculativeTypes.push_back(SrcTy);
149 // Mapping a non-opaque source type to an opaque dest. If this is the first
150 // type that we're mapping onto this destination type then we succeed. Keep
151 // the dest, but fill it in later. If this is the second (different) type
152 // that we're trying to map onto the 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)
157 SrcDefinitionsToResolve.push_back(SSTy);
158 SpeculativeTypes.push_back(SrcTy);
159 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
165 // If the number of subtypes disagree between the two types, then we fail.
166 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
169 // Fail if any of the extra properties (e.g. array size) of the type disagree.
170 if (isa<IntegerType>(DstTy))
171 return false; // bitwidth disagrees.
172 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
173 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
176 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
177 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
179 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
180 StructType *SSTy = cast<StructType>(SrcTy);
181 if (DSTy->isLiteral() != SSTy->isLiteral() ||
182 DSTy->isPacked() != SSTy->isPacked())
184 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
185 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
187 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
188 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
192 // Otherwise, we speculate that these two types will line up and recursively
193 // check the subelements.
195 SpeculativeTypes.push_back(SrcTy);
197 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
198 if (!areTypesIsomorphic(DstTy->getContainedType(I),
199 SrcTy->getContainedType(I)))
202 // If everything seems to have lined up, then everything is great.
206 void TypeMapTy::linkDefinedTypeBodies() {
207 SmallVector<Type*, 16> Elements;
208 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
209 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
210 assert(DstSTy->isOpaque());
212 // Map the body of the source type over to a new body for the dest type.
213 Elements.resize(SrcSTy->getNumElements());
214 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
215 Elements[I] = get(SrcSTy->getElementType(I));
217 DstSTy->setBody(Elements, SrcSTy->isPacked());
219 SrcDefinitionsToResolve.clear();
220 DstResolvedOpaqueTypes.clear();
223 Type *TypeMapTy::get(Type *Ty) {
224 // If we already have an entry for this type, return it.
225 Type **Entry = &MappedTypes[Ty];
229 // If this is not a named struct type, then just map all of the elements and
230 // then rebuild the type from inside out.
231 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
232 // If there are no element types to map, then the type is itself. This is
233 // true for the anonymous {} struct, things like 'float', integers, etc.
234 if (Ty->getNumContainedTypes() == 0)
237 // Remap all of the elements, keeping track of whether any of them change.
238 bool AnyChange = false;
239 SmallVector<Type*, 4> ElementTypes;
240 ElementTypes.resize(Ty->getNumContainedTypes());
241 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
242 ElementTypes[I] = get(Ty->getContainedType(I));
243 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
246 // If we found our type while recursively processing stuff, just use it.
247 Entry = &MappedTypes[Ty];
251 // If all of the element types mapped directly over, then the type is usable
256 // Otherwise, rebuild a modified type.
257 switch (Ty->getTypeID()) {
259 llvm_unreachable("unknown derived type to remap");
260 case Type::ArrayTyID:
261 return *Entry = ArrayType::get(ElementTypes[0],
262 cast<ArrayType>(Ty)->getNumElements());
263 case Type::VectorTyID:
264 return *Entry = VectorType::get(ElementTypes[0],
265 cast<VectorType>(Ty)->getNumElements());
266 case Type::PointerTyID:
267 return *Entry = PointerType::get(
268 ElementTypes[0], cast<PointerType>(Ty)->getAddressSpace());
269 case Type::FunctionTyID:
270 return *Entry = FunctionType::get(ElementTypes[0],
271 makeArrayRef(ElementTypes).slice(1),
272 cast<FunctionType>(Ty)->isVarArg());
273 case Type::StructTyID:
274 // Note that this is only reached for anonymous structs.
275 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
276 cast<StructType>(Ty)->isPacked());
280 // Otherwise, this is an unmapped named struct. If the struct can be directly
281 // mapped over, just use it as-is. This happens in a case when the linked-in
282 // module has something like:
283 // %T = type {%T*, i32}
284 // @GV = global %T* null
285 // where T does not exist at all in the destination module.
287 // The other case we watch for is when the type is not in the destination
288 // module, but that it has to be rebuilt because it refers to something that
289 // is already mapped. For example, if the destination module has:
291 // and the source module has something like
292 // %A' = type { i32 }
293 // %B = type { %A'* }
294 // @GV = global %B* null
295 // then we want to create a new type: "%B = type { %A*}" and have it take the
296 // pristine "%B" name from the source module.
298 // To determine which case this is, we have to recursively walk the type graph
299 // speculating that we'll be able to reuse it unmodified. Only if this is
300 // safe would we map the entire thing over. Because this is an optimization,
301 // and is not required for the prettiness of the linked module, we just skip
302 // it and always rebuild a type here.
303 StructType *STy = cast<StructType>(Ty);
305 // If the type is opaque, we can just use it directly.
306 if (STy->isOpaque()) {
307 // A named structure type from src module is used. Add it to the Set of
308 // identified structs in the destination module.
309 DstStructTypesSet.insert(STy);
313 // Otherwise we create a new type.
314 StructType *DTy = StructType::create(STy->getContext());
315 // A new identified structure type was created. Add it to the set of
316 // identified structs in the destination module.
317 DstStructTypesSet.insert(DTy);
320 SmallVector<Type*, 4> ElementTypes;
321 ElementTypes.resize(STy->getNumElements());
322 for (unsigned I = 0, E = ElementTypes.size(); I != E; ++I)
323 ElementTypes[I] = get(STy->getElementType(I));
324 DTy->setBody(ElementTypes, STy->isPacked());
327 if (STy->hasName()) {
328 SmallString<16> TmpName = STy->getName();
330 DTy->setName(TmpName);
336 //===----------------------------------------------------------------------===//
337 // ModuleLinker implementation.
338 //===----------------------------------------------------------------------===//
343 /// Creates prototypes for functions that are lazily linked on the fly. This
344 /// speeds up linking for modules with many/ lazily linked functions of which
346 class ValueMaterializerTy : public ValueMaterializer {
349 std::vector<Function *> &LazilyLinkFunctions;
352 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
353 std::vector<Function *> &LazilyLinkFunctions)
354 : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
355 LazilyLinkFunctions(LazilyLinkFunctions) {}
357 Value *materializeValueFor(Value *V) override;
360 class LinkDiagnosticInfo : public DiagnosticInfo {
364 LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
365 void print(DiagnosticPrinter &DP) const override;
367 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
369 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
370 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
372 /// This is an implementation class for the LinkModules function, which is the
373 /// entrypoint for this file.
378 ValueMaterializerTy ValMaterializer;
380 /// Mapping of values from what they used to be in Src, to what they are now
381 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
382 /// due to the use of Value handles which the Linker doesn't actually need,
383 /// but this allows us to reuse the ValueMapper code.
384 ValueToValueMapTy ValueMap;
386 struct AppendingVarInfo {
387 GlobalVariable *NewGV; // New aggregate global in dest module.
388 const Constant *DstInit; // Old initializer from dest module.
389 const Constant *SrcInit; // Old initializer from src module.
392 std::vector<AppendingVarInfo> AppendingVars;
394 // Set of items not to link in from source.
395 SmallPtrSet<const Value *, 16> DoNotLinkFromSource;
397 // Vector of functions to lazily link in.
398 std::vector<Function *> LazilyLinkFunctions;
400 Linker::DiagnosticHandlerFunction DiagnosticHandler;
403 ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM,
404 Linker::DiagnosticHandlerFunction DiagnosticHandler)
405 : DstM(dstM), SrcM(srcM), TypeMap(Set),
406 ValMaterializer(TypeMap, DstM, LazilyLinkFunctions),
407 DiagnosticHandler(DiagnosticHandler) {}
412 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
413 const GlobalValue &Src);
415 /// Helper method for setting a message and returning an error code.
416 bool emitError(const Twine &Message) {
417 DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
421 void emitWarning(const Twine &Message) {
422 DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
425 bool getComdatLeader(Module *M, StringRef ComdatName,
426 const GlobalVariable *&GVar);
427 bool computeResultingSelectionKind(StringRef ComdatName,
428 Comdat::SelectionKind Src,
429 Comdat::SelectionKind Dst,
430 Comdat::SelectionKind &Result,
432 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
434 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
437 /// Given a global in the source module, return the global in the
438 /// destination module that is being linked to, if any.
439 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
440 // If the source has no name it can't link. If it has local linkage,
441 // there is no name match-up going on.
442 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
445 // Otherwise see if we have a match in the destination module's symtab.
446 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
450 // If we found a global with the same name in the dest module, but it has
451 // internal linkage, we are really not doing any linkage here.
452 if (DGV->hasLocalLinkage())
455 // Otherwise, we do in fact link to the destination global.
459 void computeTypeMapping();
461 void upgradeMismatchedGlobalArray(StringRef Name);
462 void upgradeMismatchedGlobals();
464 bool linkAppendingVarProto(GlobalVariable *DstGV,
465 const GlobalVariable *SrcGV);
467 bool linkGlobalValueProto(GlobalValue *GV);
468 GlobalValue *linkGlobalVariableProto(const GlobalVariable *SGVar,
469 GlobalValue *DGV, bool LinkFromSrc);
470 GlobalValue *linkFunctionProto(const Function *SF, GlobalValue *DGV,
472 GlobalValue *linkGlobalAliasProto(const GlobalAlias *SGA, GlobalValue *DGV,
475 bool linkModuleFlagsMetadata();
477 void linkAppendingVarInit(const AppendingVarInfo &AVI);
478 void linkGlobalInits();
479 void linkFunctionBody(Function *Dst, Function *Src);
480 void linkAliasBodies();
481 void linkNamedMDNodes();
485 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
486 /// table. This is good for all clients except for us. Go through the trouble
487 /// to force this back.
488 static void forceRenaming(GlobalValue *GV, StringRef Name) {
489 // If the global doesn't force its name or if it already has the right name,
490 // there is nothing for us to do.
491 if (GV->hasLocalLinkage() || GV->getName() == Name)
494 Module *M = GV->getParent();
496 // If there is a conflict, rename the conflict.
497 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
498 GV->takeName(ConflictGV);
499 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
500 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
502 GV->setName(Name); // Force the name back
506 /// copy additional attributes (those not needed to construct a GlobalValue)
507 /// from the SrcGV to the DestGV.
508 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
509 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
510 auto *DestGO = dyn_cast<GlobalObject>(DestGV);
513 Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
515 DestGV->copyAttributesFrom(SrcGV);
518 DestGO->setAlignment(Alignment);
520 forceRenaming(DestGV, SrcGV->getName());
523 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
524 GlobalValue::VisibilityTypes b) {
525 if (a == GlobalValue::HiddenVisibility)
527 if (b == GlobalValue::HiddenVisibility)
529 if (a == GlobalValue::ProtectedVisibility)
531 if (b == GlobalValue::ProtectedVisibility)
536 Value *ValueMaterializerTy::materializeValueFor(Value *V) {
537 Function *SF = dyn_cast<Function>(V);
541 Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
542 SF->getLinkage(), SF->getName(), DstM);
543 copyGVAttributes(DF, SF);
545 if (Comdat *SC = SF->getComdat()) {
546 Comdat *DC = DstM->getOrInsertComdat(SC->getName());
550 LazilyLinkFunctions.push_back(SF);
554 bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
555 const GlobalVariable *&GVar) {
556 const GlobalValue *GVal = M->getNamedValue(ComdatName);
557 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
558 GVal = GA->getBaseObject();
560 // We cannot resolve the size of the aliasee yet.
561 return emitError("Linking COMDATs named '" + ComdatName +
562 "': COMDAT key involves incomputable alias size.");
565 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
568 "Linking COMDATs named '" + ComdatName +
569 "': GlobalVariable required for data dependent selection!");
574 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
575 Comdat::SelectionKind Src,
576 Comdat::SelectionKind Dst,
577 Comdat::SelectionKind &Result,
579 // The ability to mix Comdat::SelectionKind::Any with
580 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
581 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
582 Dst == Comdat::SelectionKind::Largest;
583 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
584 Src == Comdat::SelectionKind::Largest;
585 if (DstAnyOrLargest && SrcAnyOrLargest) {
586 if (Dst == Comdat::SelectionKind::Largest ||
587 Src == Comdat::SelectionKind::Largest)
588 Result = Comdat::SelectionKind::Largest;
590 Result = Comdat::SelectionKind::Any;
591 } else if (Src == Dst) {
594 return emitError("Linking COMDATs named '" + ComdatName +
595 "': invalid selection kinds!");
599 case Comdat::SelectionKind::Any:
603 case Comdat::SelectionKind::NoDuplicates:
604 return emitError("Linking COMDATs named '" + ComdatName +
605 "': noduplicates has been violated!");
606 case Comdat::SelectionKind::ExactMatch:
607 case Comdat::SelectionKind::Largest:
608 case Comdat::SelectionKind::SameSize: {
609 const GlobalVariable *DstGV;
610 const GlobalVariable *SrcGV;
611 if (getComdatLeader(DstM, ComdatName, DstGV) ||
612 getComdatLeader(SrcM, ComdatName, SrcGV))
615 const DataLayout *DstDL = DstM->getDataLayout();
616 const DataLayout *SrcDL = SrcM->getDataLayout();
617 if (!DstDL || !SrcDL) {
619 "Linking COMDATs named '" + ComdatName +
620 "': can't do size dependent selection without DataLayout!");
623 DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
625 SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
626 if (Result == Comdat::SelectionKind::ExactMatch) {
627 if (SrcGV->getInitializer() != DstGV->getInitializer())
628 return emitError("Linking COMDATs named '" + ComdatName +
629 "': ExactMatch violated!");
631 } else if (Result == Comdat::SelectionKind::Largest) {
632 LinkFromSrc = SrcSize > DstSize;
633 } else if (Result == Comdat::SelectionKind::SameSize) {
634 if (SrcSize != DstSize)
635 return emitError("Linking COMDATs named '" + ComdatName +
636 "': SameSize violated!");
639 llvm_unreachable("unknown selection kind");
648 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
649 Comdat::SelectionKind &Result,
651 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
652 StringRef ComdatName = SrcC->getName();
653 Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
654 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
656 if (DstCI == ComdatSymTab.end()) {
657 // Use the comdat if it is only available in one of the modules.
663 const Comdat *DstC = &DstCI->second;
664 Comdat::SelectionKind DSK = DstC->getSelectionKind();
665 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
669 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
670 const GlobalValue &Dest,
671 const GlobalValue &Src) {
672 // We always have to add Src if it has appending linkage.
673 if (Src.hasAppendingLinkage()) {
678 bool SrcIsDeclaration = Src.isDeclarationForLinker();
679 bool DestIsDeclaration = Dest.isDeclarationForLinker();
681 if (SrcIsDeclaration) {
682 // If Src is external or if both Src & Dest are external.. Just link the
683 // external globals, we aren't adding anything.
684 if (Src.hasDLLImportStorageClass()) {
685 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
686 LinkFromSrc = DestIsDeclaration;
689 // If the Dest is weak, use the source linkage.
690 LinkFromSrc = Dest.hasExternalWeakLinkage();
694 if (DestIsDeclaration) {
695 // If Dest is external but Src is not:
700 if (Src.hasCommonLinkage()) {
701 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
706 if (!Dest.hasCommonLinkage()) {
711 // FIXME: Make datalayout mandatory and just use getDataLayout().
712 DataLayout DL(Dest.getParent());
714 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
715 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
716 LinkFromSrc = SrcSize > DestSize;
720 if (Src.isWeakForLinker()) {
721 assert(!Dest.hasExternalWeakLinkage());
722 assert(!Dest.hasAvailableExternallyLinkage());
724 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
733 if (Dest.isWeakForLinker()) {
734 assert(Src.hasExternalLinkage());
739 assert(!Src.hasExternalWeakLinkage());
740 assert(!Dest.hasExternalWeakLinkage());
741 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
742 "Unexpected linkage type!");
743 return emitError("Linking globals named '" + Src.getName() +
744 "': symbol multiply defined!");
747 /// Loop over all of the linked values to compute type mappings. For example,
748 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
749 /// types 'Foo' but one got renamed when the module was loaded into the same
751 void ModuleLinker::computeTypeMapping() {
752 for (GlobalValue &SGV : SrcM->globals()) {
753 GlobalValue *DGV = getLinkedToGlobal(&SGV);
757 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
758 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
762 // Unify the element type of appending arrays.
763 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
764 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
765 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
768 for (GlobalValue &SGV : *SrcM) {
769 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
770 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
773 for (GlobalValue &SGV : SrcM->aliases()) {
774 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
775 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
778 // Incorporate types by name, scanning all the types in the source module.
779 // At this point, the destination module may have a type "%foo = { i32 }" for
780 // example. When the source module got loaded into the same LLVMContext, if
781 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
782 TypeFinder SrcStructTypes;
783 SrcStructTypes.run(*SrcM, true);
784 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
785 SrcStructTypes.end());
787 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
788 StructType *ST = SrcStructTypes[i];
789 if (!ST->hasName()) continue;
791 // Check to see if there is a dot in the name followed by a digit.
792 size_t DotPos = ST->getName().rfind('.');
793 if (DotPos == 0 || DotPos == StringRef::npos ||
794 ST->getName().back() == '.' ||
795 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
798 // Check to see if the destination module has a struct with the prefix name.
799 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
800 // Don't use it if this actually came from the source module. They're in
801 // the same LLVMContext after all. Also don't use it unless the type is
802 // actually used in the destination module. This can happen in situations
807 // %Z = type { %A } %B = type { %C.1 }
808 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
809 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
810 // %C = type { i8* } %B.3 = type { %C.1 }
812 // When we link Module B with Module A, the '%B' in Module B is
813 // used. However, that would then use '%C.1'. But when we process '%C.1',
814 // we prefer to take the '%C' version. So we are then left with both
815 // '%C.1' and '%C' being used for the same types. This leads to some
816 // variables using one type and some using the other.
817 if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
818 TypeMap.addTypeMapping(DST, ST);
821 // Now that we have discovered all of the type equivalences, get a body for
822 // any 'opaque' types in the dest module that are now resolved.
823 TypeMap.linkDefinedTypeBodies();
826 static void upgradeGlobalArray(GlobalVariable *GV) {
827 ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
828 StructType *OldTy = cast<StructType>(ATy->getElementType());
829 assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
831 // Get the upgraded 3 element type.
832 PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
833 Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
835 StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
837 // Build new constants with a null third field filled in.
838 Constant *OldInitC = GV->getInitializer();
839 ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
840 if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
841 // Invalid initializer; give up.
843 std::vector<Constant *> Initializers;
844 if (OldInit && OldInit->getNumOperands()) {
845 Value *Null = Constant::getNullValue(VoidPtrTy);
846 for (Use &U : OldInit->operands()) {
847 ConstantStruct *Init = cast<ConstantStruct>(U.get());
848 Initializers.push_back(ConstantStruct::get(
849 NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
852 assert(Initializers.size() == ATy->getNumElements() &&
853 "Failed to copy all array elements");
855 // Replace the old GV with a new one.
856 ATy = ArrayType::get(NewTy, Initializers.size());
857 Constant *NewInit = ConstantArray::get(ATy, Initializers);
858 GlobalVariable *NewGV = new GlobalVariable(
859 *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
860 GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
861 GV->isExternallyInitialized());
862 NewGV->copyAttributesFrom(GV);
864 assert(GV->use_empty() && "program cannot use initializer list");
865 GV->eraseFromParent();
868 void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
869 // Look for the global arrays.
870 auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
873 auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
877 // Check if the types already match.
878 auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
880 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
884 // Grab the element types. We can only upgrade an array of a two-field
885 // struct. Only bother if the other one has three-fields.
886 auto *DstEltTy = cast<StructType>(DstTy->getElementType());
887 auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
888 if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
889 upgradeGlobalArray(DstGV);
892 if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
893 upgradeGlobalArray(SrcGV);
895 // We can't upgrade any other differences.
898 void ModuleLinker::upgradeMismatchedGlobals() {
899 upgradeMismatchedGlobalArray("llvm.global_ctors");
900 upgradeMismatchedGlobalArray("llvm.global_dtors");
903 /// If there were any appending global variables, link them together now.
904 /// Return true on error.
905 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
906 const GlobalVariable *SrcGV) {
908 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
909 return emitError("Linking globals named '" + SrcGV->getName() +
910 "': can only link appending global with another appending global!");
912 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
914 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
915 Type *EltTy = DstTy->getElementType();
917 // Check to see that they two arrays agree on type.
918 if (EltTy != SrcTy->getElementType())
919 return emitError("Appending variables with different element types!");
920 if (DstGV->isConstant() != SrcGV->isConstant())
921 return emitError("Appending variables linked with different const'ness!");
923 if (DstGV->getAlignment() != SrcGV->getAlignment())
925 "Appending variables with different alignment need to be linked!");
927 if (DstGV->getVisibility() != SrcGV->getVisibility())
929 "Appending variables with different visibility need to be linked!");
931 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
933 "Appending variables with different unnamed_addr need to be linked!");
935 if (StringRef(DstGV->getSection()) != SrcGV->getSection())
937 "Appending variables with different section name need to be linked!");
939 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
940 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
942 // Create the new global variable.
944 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
945 DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
946 DstGV->getThreadLocalMode(),
947 DstGV->getType()->getAddressSpace());
949 // Propagate alignment, visibility and section info.
950 copyGVAttributes(NG, DstGV);
952 AppendingVarInfo AVI;
954 AVI.DstInit = DstGV->getInitializer();
955 AVI.SrcInit = SrcGV->getInitializer();
956 AppendingVars.push_back(AVI);
958 // Replace any uses of the two global variables with uses of the new
960 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
962 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
963 DstGV->eraseFromParent();
965 // Track the source variable so we don't try to link it.
966 DoNotLinkFromSource.insert(SrcGV);
971 bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
972 GlobalValue *DGV = getLinkedToGlobal(SGV);
974 // Handle the ultra special appending linkage case first.
975 if (DGV && DGV->hasAppendingLinkage())
976 return linkAppendingVarProto(cast<GlobalVariable>(DGV),
977 cast<GlobalVariable>(SGV));
979 bool LinkFromSrc = true;
981 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
982 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
984 if (const Comdat *SC = SGV->getComdat()) {
985 Comdat::SelectionKind SK;
986 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
987 C = DstM->getOrInsertComdat(SC->getName());
988 C->setSelectionKind(SK);
990 if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
995 // Track the source global so that we don't attempt to copy it over when
996 // processing global initializers.
997 DoNotLinkFromSource.insert(SGV);
1000 // Make sure to remember this mapping.
1002 ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
1006 Visibility = isLessConstraining(Visibility, DGV->getVisibility())
1007 ? DGV->getVisibility()
1009 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1012 if (!LinkFromSrc && !DGV)
1016 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
1017 NewGV = linkGlobalVariableProto(SGVar, DGV, LinkFromSrc);
1020 } else if (auto *SF = dyn_cast<Function>(SGV)) {
1021 NewGV = linkFunctionProto(SF, DGV, LinkFromSrc);
1023 NewGV = linkGlobalAliasProto(cast<GlobalAlias>(SGV), DGV, LinkFromSrc);
1028 copyGVAttributes(NewGV, SGV);
1030 NewGV->setUnnamedAddr(HasUnnamedAddr);
1031 NewGV->setVisibility(Visibility);
1033 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1035 NewGO->setComdat(C);
1038 // Make sure to remember this mapping.
1041 DGV->replaceAllUsesWith(
1042 ConstantExpr::getBitCast(NewGV, DGV->getType()));
1043 DGV->eraseFromParent();
1045 ValueMap[SGV] = NewGV;
1052 /// Loop through the global variables in the src module and merge them into the
1054 GlobalValue *ModuleLinker::linkGlobalVariableProto(const GlobalVariable *SGVar,
1057 unsigned Alignment = 0;
1058 bool ClearConstant = false;
1061 if (DGV->hasCommonLinkage() && SGVar->hasCommonLinkage())
1062 Alignment = std::max(SGVar->getAlignment(), DGV->getAlignment());
1064 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
1065 if (!SGVar->isConstant() || (DGVar && !DGVar->isConstant()))
1066 ClearConstant = true;
1070 if (auto *NewGVar = dyn_cast<GlobalVariable>(DGV)) {
1072 NewGVar->setAlignment(Alignment);
1073 if (NewGVar->isDeclaration() && ClearConstant)
1074 NewGVar->setConstant(false);
1079 // No linking to be performed or linking from the source: simply create an
1080 // identical version of the symbol over in the dest module... the
1081 // initializer will be filled in later by LinkGlobalInits.
1082 GlobalVariable *NewDGV = new GlobalVariable(
1083 *DstM, TypeMap.get(SGVar->getType()->getElementType()),
1084 SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr,
1085 SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
1086 SGVar->getType()->getAddressSpace());
1089 NewDGV->setAlignment(Alignment);
1094 /// Link the function in the source module into the destination module if
1095 /// needed, setting up mapping information.
1096 GlobalValue *ModuleLinker::linkFunctionProto(const Function *SF,
1102 // If the function is to be lazily linked, don't create it just yet.
1103 // The ValueMaterializerTy will deal with creating it if it's used.
1104 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1105 SF->hasAvailableExternallyLinkage())) {
1106 DoNotLinkFromSource.insert(SF);
1110 // If there is no linkage to be performed or we are linking from the source,
1112 return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(),
1113 SF->getName(), DstM);
1116 /// Set up prototypes for any aliases that come over from the source module.
1117 GlobalValue *ModuleLinker::linkGlobalAliasProto(const GlobalAlias *SGA,
1123 // If there is no linkage to be performed or we're linking from the source,
1125 auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
1126 return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1127 SGA->getLinkage(), SGA->getName(), DstM);
1130 static void getArrayElements(const Constant *C,
1131 SmallVectorImpl<Constant *> &Dest) {
1132 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1134 for (unsigned i = 0; i != NumElements; ++i)
1135 Dest.push_back(C->getAggregateElement(i));
1138 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1139 // Merge the initializer.
1140 SmallVector<Constant *, 16> DstElements;
1141 getArrayElements(AVI.DstInit, DstElements);
1143 SmallVector<Constant *, 16> SrcElements;
1144 getArrayElements(AVI.SrcInit, SrcElements);
1146 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1148 StringRef Name = AVI.NewGV->getName();
1149 bool IsNewStructor =
1150 (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1151 cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1153 for (auto *V : SrcElements) {
1154 if (IsNewStructor) {
1155 Constant *Key = V->getAggregateElement(2);
1156 if (DoNotLinkFromSource.count(Key))
1159 DstElements.push_back(
1160 MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1162 if (IsNewStructor) {
1163 NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1164 AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1167 AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1170 /// Update the initializers in the Dest module now that all globals that may be
1171 /// referenced are in Dest.
1172 void ModuleLinker::linkGlobalInits() {
1173 // Loop over all of the globals in the src module, mapping them over as we go
1174 for (Module::const_global_iterator I = SrcM->global_begin(),
1175 E = SrcM->global_end(); I != E; ++I) {
1177 // Only process initialized GV's or ones not already in dest.
1178 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1180 // Grab destination global variable.
1181 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1182 // Figure out what the initializer looks like in the dest module.
1183 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
1184 RF_None, &TypeMap, &ValMaterializer));
1188 /// Copy the source function over into the dest function and fix up references
1189 /// to values. At this point we know that Dest is an external function, and
1190 /// that Src is not.
1191 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1192 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
1194 // Go through and convert function arguments over, remembering the mapping.
1195 Function::arg_iterator DI = Dst->arg_begin();
1196 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1197 I != E; ++I, ++DI) {
1198 DI->setName(I->getName()); // Copy the name over.
1200 // Add a mapping to our mapping.
1204 // Splice the body of the source function into the dest function.
1205 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
1207 // At this point, all of the instructions and values of the function are now
1208 // copied over. The only problem is that they are still referencing values in
1209 // the Source function as operands. Loop through all of the operands of the
1210 // functions and patch them up to point to the local versions.
1211 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1212 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1213 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap,
1216 // There is no need to map the arguments anymore.
1217 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1223 /// Insert all of the aliases in Src into the Dest module.
1224 void ModuleLinker::linkAliasBodies() {
1225 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
1227 if (DoNotLinkFromSource.count(I))
1229 if (Constant *Aliasee = I->getAliasee()) {
1230 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
1232 MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1233 DA->setAliasee(Val);
1238 /// Insert all of the named MDNodes in Src into the Dest module.
1239 void ModuleLinker::linkNamedMDNodes() {
1240 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1241 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1242 E = SrcM->named_metadata_end(); I != E; ++I) {
1243 // Don't link module flags here. Do them separately.
1244 if (&*I == SrcModFlags) continue;
1245 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1246 // Add Src elements into Dest node.
1247 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1248 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
1249 RF_None, &TypeMap, &ValMaterializer));
1253 /// Merge the linker flags in Src into the Dest module.
1254 bool ModuleLinker::linkModuleFlagsMetadata() {
1255 // If the source module has no module flags, we are done.
1256 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1257 if (!SrcModFlags) return false;
1259 // If the destination module doesn't have module flags yet, then just copy
1260 // over the source module's flags.
1261 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1262 if (DstModFlags->getNumOperands() == 0) {
1263 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1264 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1269 // First build a map of the existing module flags and requirements.
1270 DenseMap<MDString*, MDNode*> Flags;
1271 SmallSetVector<MDNode*, 16> Requirements;
1272 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1273 MDNode *Op = DstModFlags->getOperand(I);
1274 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1275 MDString *ID = cast<MDString>(Op->getOperand(1));
1277 if (Behavior->getZExtValue() == Module::Require) {
1278 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1284 // Merge in the flags from the source module, and also collect its set of
1286 bool HasErr = false;
1287 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1288 MDNode *SrcOp = SrcModFlags->getOperand(I);
1289 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1290 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1291 MDNode *DstOp = Flags.lookup(ID);
1292 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1294 // If this is a requirement, add it and continue.
1295 if (SrcBehaviorValue == Module::Require) {
1296 // If the destination module does not already have this requirement, add
1298 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1299 DstModFlags->addOperand(SrcOp);
1304 // If there is no existing flag with this ID, just add it.
1307 DstModFlags->addOperand(SrcOp);
1311 // Otherwise, perform a merge.
1312 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1313 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1315 // If either flag has override behavior, handle it first.
1316 if (DstBehaviorValue == Module::Override) {
1317 // Diagnose inconsistent flags which both have override behavior.
1318 if (SrcBehaviorValue == Module::Override &&
1319 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1320 HasErr |= emitError("linking module flags '" + ID->getString() +
1321 "': IDs have conflicting override values");
1324 } else if (SrcBehaviorValue == Module::Override) {
1325 // Update the destination flag to that of the source.
1326 DstOp->replaceOperandWith(0, SrcBehavior);
1327 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1331 // Diagnose inconsistent merge behavior types.
1332 if (SrcBehaviorValue != DstBehaviorValue) {
1333 HasErr |= emitError("linking module flags '" + ID->getString() +
1334 "': IDs have conflicting behaviors");
1338 // Perform the merge for standard behavior types.
1339 switch (SrcBehaviorValue) {
1340 case Module::Require:
1341 case Module::Override: llvm_unreachable("not possible");
1342 case Module::Error: {
1343 // Emit an error if the values differ.
1344 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1345 HasErr |= emitError("linking module flags '" + ID->getString() +
1346 "': IDs have conflicting values");
1350 case Module::Warning: {
1351 // Emit a warning if the values differ.
1352 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1353 emitWarning("linking module flags '" + ID->getString() +
1354 "': IDs have conflicting values");
1358 case Module::Append: {
1359 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1360 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1361 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1362 Value **VP, **Values = VP = new Value*[NumOps];
1363 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1364 *VP = DstValue->getOperand(i);
1365 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1366 *VP = SrcValue->getOperand(i);
1367 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1368 ArrayRef<Value*>(Values,
1373 case Module::AppendUnique: {
1374 SmallSetVector<Value*, 16> Elts;
1375 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1376 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1377 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1378 Elts.insert(DstValue->getOperand(i));
1379 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1380 Elts.insert(SrcValue->getOperand(i));
1381 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1382 ArrayRef<Value*>(Elts.begin(),
1389 // Check all of the requirements.
1390 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1391 MDNode *Requirement = Requirements[I];
1392 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1393 Value *ReqValue = Requirement->getOperand(1);
1395 MDNode *Op = Flags[Flag];
1396 if (!Op || Op->getOperand(2) != ReqValue) {
1397 HasErr |= emitError("linking module flags '" + Flag->getString() +
1398 "': does not have the required value");
1406 bool ModuleLinker::run() {
1407 assert(DstM && "Null destination module");
1408 assert(SrcM && "Null source module");
1410 // Inherit the target data from the source module if the destination module
1411 // doesn't have one already.
1412 if (!DstM->getDataLayout() && SrcM->getDataLayout())
1413 DstM->setDataLayout(SrcM->getDataLayout());
1415 // Copy the target triple from the source to dest if the dest's is empty.
1416 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1417 DstM->setTargetTriple(SrcM->getTargetTriple());
1419 if (SrcM->getDataLayout() && DstM->getDataLayout() &&
1420 *SrcM->getDataLayout() != *DstM->getDataLayout()) {
1421 emitWarning("Linking two modules of different data layouts: '" +
1422 SrcM->getModuleIdentifier() + "' is '" +
1423 SrcM->getDataLayoutStr() + "' whereas '" +
1424 DstM->getModuleIdentifier() + "' is '" +
1425 DstM->getDataLayoutStr() + "'\n");
1427 if (!SrcM->getTargetTriple().empty() &&
1428 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1429 emitWarning("Linking two modules of different target triples: " +
1430 SrcM->getModuleIdentifier() + "' is '" +
1431 SrcM->getTargetTriple() + "' whereas '" +
1432 DstM->getModuleIdentifier() + "' is '" +
1433 DstM->getTargetTriple() + "'\n");
1436 // Append the module inline asm string.
1437 if (!SrcM->getModuleInlineAsm().empty()) {
1438 if (DstM->getModuleInlineAsm().empty())
1439 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1441 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1442 SrcM->getModuleInlineAsm());
1445 // Loop over all of the linked values to compute type mappings.
1446 computeTypeMapping();
1448 ComdatsChosen.clear();
1449 for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
1450 const Comdat &C = SMEC.getValue();
1451 if (ComdatsChosen.count(&C))
1453 Comdat::SelectionKind SK;
1455 if (getComdatResult(&C, SK, LinkFromSrc))
1457 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1460 // Upgrade mismatched global arrays.
1461 upgradeMismatchedGlobals();
1463 // Insert all of the globals in src into the DstM module... without linking
1464 // initializers (which could refer to functions not yet mapped over).
1465 for (Module::global_iterator I = SrcM->global_begin(),
1466 E = SrcM->global_end(); I != E; ++I)
1467 if (linkGlobalValueProto(I))
1470 // Link the functions together between the two modules, without doing function
1471 // bodies... this just adds external function prototypes to the DstM
1472 // function... We do this so that when we begin processing function bodies,
1473 // all of the global values that may be referenced are available in our
1475 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1476 if (linkGlobalValueProto(I))
1479 // If there were any aliases, link them now.
1480 for (Module::alias_iterator I = SrcM->alias_begin(),
1481 E = SrcM->alias_end(); I != E; ++I)
1482 if (linkGlobalValueProto(I))
1485 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1486 linkAppendingVarInit(AppendingVars[i]);
1488 // Link in the function bodies that are defined in the source module into
1490 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1491 // Skip if not linking from source.
1492 if (DoNotLinkFromSource.count(SF)) continue;
1494 Function *DF = cast<Function>(ValueMap[SF]);
1495 if (SF->hasPrefixData()) {
1496 // Link in the prefix data.
1497 DF->setPrefixData(MapValue(
1498 SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1501 // Materialize if needed.
1502 if (std::error_code EC = SF->materialize())
1503 return emitError(EC.message());
1505 // Skip if no body (function is external).
1506 if (SF->isDeclaration())
1509 linkFunctionBody(DF, SF);
1510 SF->Dematerialize();
1513 // Resolve all uses of aliases with aliasees.
1516 // Remap all of the named MDNodes in Src into the DstM module. We do this
1517 // after linking GlobalValues so that MDNodes that reference GlobalValues
1518 // are properly remapped.
1521 // Merge the module flags into the DstM module.
1522 if (linkModuleFlagsMetadata())
1525 // Update the initializers in the DstM module now that all globals that may
1526 // be referenced are in DstM.
1529 // Process vector of lazily linked in functions.
1530 bool LinkedInAnyFunctions;
1532 LinkedInAnyFunctions = false;
1534 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1535 E = LazilyLinkFunctions.end(); I != E; ++I) {
1540 Function *DF = cast<Function>(ValueMap[SF]);
1541 if (SF->hasPrefixData()) {
1542 // Link in the prefix data.
1543 DF->setPrefixData(MapValue(SF->getPrefixData(),
1550 // Materialize if needed.
1551 if (std::error_code EC = SF->materialize())
1552 return emitError(EC.message());
1554 // Skip if no body (function is external).
1555 if (SF->isDeclaration())
1558 // Erase from vector *before* the function body is linked - linkFunctionBody could
1560 LazilyLinkFunctions.erase(I);
1562 // Link in function body.
1563 linkFunctionBody(DF, SF);
1564 SF->Dematerialize();
1566 // Set flag to indicate we may have more functions to lazily link in
1567 // since we linked in a function.
1568 LinkedInAnyFunctions = true;
1571 } while (LinkedInAnyFunctions);
1576 void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1577 this->Composite = M;
1578 this->DiagnosticHandler = DiagnosticHandler;
1580 TypeFinder StructTypes;
1581 StructTypes.run(*M, true);
1582 IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1585 Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1586 init(M, DiagnosticHandler);
1589 Linker::Linker(Module *M) {
1590 init(M, [this](const DiagnosticInfo &DI) {
1591 Composite->getContext().diagnose(DI);
1598 void Linker::deleteModule() {
1600 Composite = nullptr;
1603 bool Linker::linkInModule(Module *Src) {
1604 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
1606 return TheLinker.run();
1609 //===----------------------------------------------------------------------===//
1610 // LinkModules entrypoint.
1611 //===----------------------------------------------------------------------===//
1613 /// This function links two modules together, with the resulting Dest module
1614 /// modified to be the composite of the two input modules. If an error occurs,
1615 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
1616 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
1617 /// relied on to be consistent.
1618 bool Linker::LinkModules(Module *Dest, Module *Src,
1619 DiagnosticHandlerFunction DiagnosticHandler) {
1620 Linker L(Dest, DiagnosticHandler);
1621 return L.linkInModule(Src);
1624 bool Linker::LinkModules(Module *Dest, Module *Src) {
1626 return L.linkInModule(Src);
1629 //===----------------------------------------------------------------------===//
1631 //===----------------------------------------------------------------------===//
1633 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1634 LLVMLinkerMode Mode, char **OutMessages) {
1635 Module *D = unwrap(Dest);
1636 std::string Message;
1637 raw_string_ostream Stream(Message);
1638 DiagnosticPrinterRawOStream DP(Stream);
1640 LLVMBool Result = Linker::LinkModules(
1641 D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
1643 if (OutMessages && Result)
1644 *OutMessages = strdup(Message.c_str());