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;
63 /// Indicate that the specified type in the destination module is conceptually
64 /// equivalent to the specified type in the source module.
65 void addTypeMapping(Type *DstTy, Type *SrcTy);
67 /// Produce a body for an opaque type in the dest module from a type
68 /// definition in the source module.
69 void linkDefinedTypeBodies();
71 /// Return the mapped type to use for the specified input type from the
73 Type *get(Type *SrcTy);
75 FunctionType *get(FunctionType *T) {
76 return cast<FunctionType>(get((Type *)T));
79 /// Dump out the type map for debugging purposes.
81 for (auto &Pair : MappedTypes) {
82 dbgs() << "TypeMap: ";
83 Pair.first->print(dbgs());
85 Pair.second->print(dbgs());
91 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
93 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
97 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
98 assert(SpeculativeTypes.empty());
99 assert(SpeculativeDstOpaqueTypes.empty());
101 // Check to see if these types are recursively isomorphic and establish a
102 // mapping between them if so.
103 if (!areTypesIsomorphic(DstTy, SrcTy)) {
104 // Oops, they aren't isomorphic. Just discard this request by rolling out
105 // any speculative mappings we've established.
106 for (Type *Ty : SpeculativeTypes)
107 MappedTypes.erase(Ty);
109 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
110 SpeculativeDstOpaqueTypes.size());
111 for (StructType *Ty : SpeculativeDstOpaqueTypes)
112 DstResolvedOpaqueTypes.erase(Ty);
114 for (Type *Ty : SpeculativeTypes)
115 if (auto *STy = dyn_cast<StructType>(Ty))
119 SpeculativeTypes.clear();
120 SpeculativeDstOpaqueTypes.clear();
123 /// Recursively walk this pair of types, returning true if they are isomorphic,
124 /// false if they are not.
125 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
126 // Two types with differing kinds are clearly not isomorphic.
127 if (DstTy->getTypeID() != SrcTy->getTypeID())
130 // If we have an entry in the MappedTypes table, then we have our answer.
131 Type *&Entry = MappedTypes[SrcTy];
133 return Entry == DstTy;
135 // Two identical types are clearly isomorphic. Remember this
136 // non-speculatively.
137 if (DstTy == SrcTy) {
142 // Okay, we have two types with identical kinds that we haven't seen before.
144 // If this is an opaque struct type, special case it.
145 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
146 // Mapping an opaque type to any struct, just keep the dest struct.
147 if (SSTy->isOpaque()) {
149 SpeculativeTypes.push_back(SrcTy);
153 // Mapping a non-opaque source type to an opaque dest. If this is the first
154 // type that we're mapping onto this destination type then we succeed. Keep
155 // the dest, but fill it in later. If this is the second (different) type
156 // that we're trying to map onto the same opaque type then we fail.
157 if (cast<StructType>(DstTy)->isOpaque()) {
158 // We can only map one source type onto the opaque destination type.
159 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
161 SrcDefinitionsToResolve.push_back(SSTy);
162 SpeculativeTypes.push_back(SrcTy);
163 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
169 // If the number of subtypes disagree between the two types, then we fail.
170 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
173 // Fail if any of the extra properties (e.g. array size) of the type disagree.
174 if (isa<IntegerType>(DstTy))
175 return false; // bitwidth disagrees.
176 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
177 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
180 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
181 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
183 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
184 StructType *SSTy = cast<StructType>(SrcTy);
185 if (DSTy->isLiteral() != SSTy->isLiteral() ||
186 DSTy->isPacked() != SSTy->isPacked())
188 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
189 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
191 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
192 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
196 // Otherwise, we speculate that these two types will line up and recursively
197 // check the subelements.
199 SpeculativeTypes.push_back(SrcTy);
201 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
202 if (!areTypesIsomorphic(DstTy->getContainedType(I),
203 SrcTy->getContainedType(I)))
206 // If everything seems to have lined up, then everything is great.
210 void TypeMapTy::linkDefinedTypeBodies() {
211 SmallVector<Type*, 16> Elements;
212 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
213 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
214 assert(DstSTy->isOpaque());
216 // Map the body of the source type over to a new body for the dest type.
217 Elements.resize(SrcSTy->getNumElements());
218 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
219 Elements[I] = get(SrcSTy->getElementType(I));
221 DstSTy->setBody(Elements, SrcSTy->isPacked());
223 SrcDefinitionsToResolve.clear();
224 DstResolvedOpaqueTypes.clear();
227 Type *TypeMapTy::get(Type *Ty) {
228 // If we already have an entry for this type, return it.
229 Type **Entry = &MappedTypes[Ty];
233 // If this is not a named struct type, then just map all of the elements and
234 // then rebuild the type from inside out.
235 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
236 // If there are no element types to map, then the type is itself. This is
237 // true for the anonymous {} struct, things like 'float', integers, etc.
238 if (Ty->getNumContainedTypes() == 0)
241 // Remap all of the elements, keeping track of whether any of them change.
242 bool AnyChange = false;
243 SmallVector<Type*, 4> ElementTypes;
244 ElementTypes.resize(Ty->getNumContainedTypes());
245 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
246 ElementTypes[I] = get(Ty->getContainedType(I));
247 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
250 // If we found our type while recursively processing stuff, just use it.
251 Entry = &MappedTypes[Ty];
255 // If all of the element types mapped directly over, then the type is usable
260 // Otherwise, rebuild a modified type.
261 switch (Ty->getTypeID()) {
263 llvm_unreachable("unknown derived type to remap");
264 case Type::ArrayTyID:
265 return *Entry = ArrayType::get(ElementTypes[0],
266 cast<ArrayType>(Ty)->getNumElements());
267 case Type::VectorTyID:
268 return *Entry = VectorType::get(ElementTypes[0],
269 cast<VectorType>(Ty)->getNumElements());
270 case Type::PointerTyID:
271 return *Entry = PointerType::get(
272 ElementTypes[0], cast<PointerType>(Ty)->getAddressSpace());
273 case Type::FunctionTyID:
274 return *Entry = FunctionType::get(ElementTypes[0],
275 makeArrayRef(ElementTypes).slice(1),
276 cast<FunctionType>(Ty)->isVarArg());
277 case Type::StructTyID:
278 // Note that this is only reached for anonymous structs.
279 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
280 cast<StructType>(Ty)->isPacked());
284 // Otherwise, this is an unmapped named struct. If the struct can be directly
285 // mapped over, just use it as-is. This happens in a case when the linked-in
286 // module has something like:
287 // %T = type {%T*, i32}
288 // @GV = global %T* null
289 // where T does not exist at all in the destination module.
291 // The other case we watch for is when the type is not in the destination
292 // module, but that it has to be rebuilt because it refers to something that
293 // is already mapped. For example, if the destination module has:
295 // and the source module has something like
296 // %A' = type { i32 }
297 // %B = type { %A'* }
298 // @GV = global %B* null
299 // then we want to create a new type: "%B = type { %A*}" and have it take the
300 // pristine "%B" name from the source module.
302 // To determine which case this is, we have to recursively walk the type graph
303 // speculating that we'll be able to reuse it unmodified. Only if this is
304 // safe would we map the entire thing over. Because this is an optimization,
305 // and is not required for the prettiness of the linked module, we just skip
306 // it and always rebuild a type here.
307 StructType *STy = cast<StructType>(Ty);
309 // If the type is opaque, we can just use it directly.
310 if (STy->isOpaque()) {
311 // A named structure type from src module is used. Add it to the Set of
312 // identified structs in the destination module.
316 // Otherwise we create a new type.
317 StructType *DTy = StructType::create(STy->getContext());
318 // A new identified structure type was created. Add it to the set of
319 // identified structs in the destination module.
322 SmallVector<Type*, 4> ElementTypes;
323 ElementTypes.resize(STy->getNumElements());
324 for (unsigned I = 0, E = ElementTypes.size(); I != E; ++I)
325 ElementTypes[I] = get(STy->getElementType(I));
326 DTy->setBody(ElementTypes, STy->isPacked());
329 if (STy->hasName()) {
330 SmallString<16> TmpName = STy->getName();
332 DTy->setName(TmpName);
338 //===----------------------------------------------------------------------===//
339 // ModuleLinker implementation.
340 //===----------------------------------------------------------------------===//
345 /// Creates prototypes for functions that are lazily linked on the fly. This
346 /// speeds up linking for modules with many/ lazily linked functions of which
348 class ValueMaterializerTy : public ValueMaterializer {
351 std::vector<Function *> &LazilyLinkFunctions;
354 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
355 std::vector<Function *> &LazilyLinkFunctions)
356 : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
357 LazilyLinkFunctions(LazilyLinkFunctions) {}
359 Value *materializeValueFor(Value *V) override;
362 class LinkDiagnosticInfo : public DiagnosticInfo {
366 LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
367 void print(DiagnosticPrinter &DP) const override;
369 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
371 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
372 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
374 /// This is an implementation class for the LinkModules function, which is the
375 /// entrypoint for this file.
380 ValueMaterializerTy ValMaterializer;
382 /// Mapping of values from what they used to be in Src, to what they are now
383 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
384 /// due to the use of Value handles which the Linker doesn't actually need,
385 /// but this allows us to reuse the ValueMapper code.
386 ValueToValueMapTy ValueMap;
388 struct AppendingVarInfo {
389 GlobalVariable *NewGV; // New aggregate global in dest module.
390 const Constant *DstInit; // Old initializer from dest module.
391 const Constant *SrcInit; // Old initializer from src module.
394 std::vector<AppendingVarInfo> AppendingVars;
396 // Set of items not to link in from source.
397 SmallPtrSet<const Value *, 16> DoNotLinkFromSource;
399 // Vector of functions to lazily link in.
400 std::vector<Function *> LazilyLinkFunctions;
402 Linker::DiagnosticHandlerFunction DiagnosticHandler;
405 ModuleLinker(Module *dstM, Module *srcM,
406 Linker::DiagnosticHandlerFunction DiagnosticHandler)
407 : DstM(dstM), SrcM(srcM),
408 ValMaterializer(TypeMap, DstM, LazilyLinkFunctions),
409 DiagnosticHandler(DiagnosticHandler) {}
414 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
415 const GlobalValue &Src);
417 /// Helper method for setting a message and returning an error code.
418 bool emitError(const Twine &Message) {
419 DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
423 void emitWarning(const Twine &Message) {
424 DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
427 bool getComdatLeader(Module *M, StringRef ComdatName,
428 const GlobalVariable *&GVar);
429 bool computeResultingSelectionKind(StringRef ComdatName,
430 Comdat::SelectionKind Src,
431 Comdat::SelectionKind Dst,
432 Comdat::SelectionKind &Result,
434 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
436 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
439 /// Given a global in the source module, return the global in the
440 /// destination module that is being linked to, if any.
441 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
442 // If the source has no name it can't link. If it has local linkage,
443 // there is no name match-up going on.
444 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
447 // Otherwise see if we have a match in the destination module's symtab.
448 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
452 // If we found a global with the same name in the dest module, but it has
453 // internal linkage, we are really not doing any linkage here.
454 if (DGV->hasLocalLinkage())
457 // Otherwise, we do in fact link to the destination global.
461 void computeTypeMapping();
463 void upgradeMismatchedGlobalArray(StringRef Name);
464 void upgradeMismatchedGlobals();
466 bool linkAppendingVarProto(GlobalVariable *DstGV,
467 const GlobalVariable *SrcGV);
469 bool linkGlobalValueProto(GlobalValue *GV);
470 GlobalValue *linkGlobalVariableProto(const GlobalVariable *SGVar,
471 GlobalValue *DGV, bool LinkFromSrc);
472 GlobalValue *linkFunctionProto(const Function *SF, GlobalValue *DGV,
474 GlobalValue *linkGlobalAliasProto(const GlobalAlias *SGA, GlobalValue *DGV,
477 bool linkModuleFlagsMetadata();
479 void linkAppendingVarInit(const AppendingVarInfo &AVI);
480 void linkGlobalInits();
481 void linkFunctionBody(Function *Dst, Function *Src);
482 void linkAliasBodies();
483 void linkNamedMDNodes();
487 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
488 /// table. This is good for all clients except for us. Go through the trouble
489 /// to force this back.
490 static void forceRenaming(GlobalValue *GV, StringRef Name) {
491 // If the global doesn't force its name or if it already has the right name,
492 // there is nothing for us to do.
493 if (GV->hasLocalLinkage() || GV->getName() == Name)
496 Module *M = GV->getParent();
498 // If there is a conflict, rename the conflict.
499 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
500 GV->takeName(ConflictGV);
501 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
502 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
504 GV->setName(Name); // Force the name back
508 /// copy additional attributes (those not needed to construct a GlobalValue)
509 /// from the SrcGV to the DestGV.
510 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
511 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
512 auto *DestGO = dyn_cast<GlobalObject>(DestGV);
515 Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
517 DestGV->copyAttributesFrom(SrcGV);
520 DestGO->setAlignment(Alignment);
522 forceRenaming(DestGV, SrcGV->getName());
525 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
526 GlobalValue::VisibilityTypes b) {
527 if (a == GlobalValue::HiddenVisibility)
529 if (b == GlobalValue::HiddenVisibility)
531 if (a == GlobalValue::ProtectedVisibility)
533 if (b == GlobalValue::ProtectedVisibility)
538 Value *ValueMaterializerTy::materializeValueFor(Value *V) {
539 Function *SF = dyn_cast<Function>(V);
543 Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
544 SF->getLinkage(), SF->getName(), DstM);
545 copyGVAttributes(DF, SF);
547 if (Comdat *SC = SF->getComdat()) {
548 Comdat *DC = DstM->getOrInsertComdat(SC->getName());
552 LazilyLinkFunctions.push_back(SF);
556 bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
557 const GlobalVariable *&GVar) {
558 const GlobalValue *GVal = M->getNamedValue(ComdatName);
559 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
560 GVal = GA->getBaseObject();
562 // We cannot resolve the size of the aliasee yet.
563 return emitError("Linking COMDATs named '" + ComdatName +
564 "': COMDAT key involves incomputable alias size.");
567 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
570 "Linking COMDATs named '" + ComdatName +
571 "': GlobalVariable required for data dependent selection!");
576 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
577 Comdat::SelectionKind Src,
578 Comdat::SelectionKind Dst,
579 Comdat::SelectionKind &Result,
581 // The ability to mix Comdat::SelectionKind::Any with
582 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
583 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
584 Dst == Comdat::SelectionKind::Largest;
585 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
586 Src == Comdat::SelectionKind::Largest;
587 if (DstAnyOrLargest && SrcAnyOrLargest) {
588 if (Dst == Comdat::SelectionKind::Largest ||
589 Src == Comdat::SelectionKind::Largest)
590 Result = Comdat::SelectionKind::Largest;
592 Result = Comdat::SelectionKind::Any;
593 } else if (Src == Dst) {
596 return emitError("Linking COMDATs named '" + ComdatName +
597 "': invalid selection kinds!");
601 case Comdat::SelectionKind::Any:
605 case Comdat::SelectionKind::NoDuplicates:
606 return emitError("Linking COMDATs named '" + ComdatName +
607 "': noduplicates has been violated!");
608 case Comdat::SelectionKind::ExactMatch:
609 case Comdat::SelectionKind::Largest:
610 case Comdat::SelectionKind::SameSize: {
611 const GlobalVariable *DstGV;
612 const GlobalVariable *SrcGV;
613 if (getComdatLeader(DstM, ComdatName, DstGV) ||
614 getComdatLeader(SrcM, ComdatName, SrcGV))
617 const DataLayout *DstDL = DstM->getDataLayout();
618 const DataLayout *SrcDL = SrcM->getDataLayout();
619 if (!DstDL || !SrcDL) {
621 "Linking COMDATs named '" + ComdatName +
622 "': can't do size dependent selection without DataLayout!");
625 DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
627 SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
628 if (Result == Comdat::SelectionKind::ExactMatch) {
629 if (SrcGV->getInitializer() != DstGV->getInitializer())
630 return emitError("Linking COMDATs named '" + ComdatName +
631 "': ExactMatch violated!");
633 } else if (Result == Comdat::SelectionKind::Largest) {
634 LinkFromSrc = SrcSize > DstSize;
635 } else if (Result == Comdat::SelectionKind::SameSize) {
636 if (SrcSize != DstSize)
637 return emitError("Linking COMDATs named '" + ComdatName +
638 "': SameSize violated!");
641 llvm_unreachable("unknown selection kind");
650 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
651 Comdat::SelectionKind &Result,
653 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
654 StringRef ComdatName = SrcC->getName();
655 Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
656 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
658 if (DstCI == ComdatSymTab.end()) {
659 // Use the comdat if it is only available in one of the modules.
665 const Comdat *DstC = &DstCI->second;
666 Comdat::SelectionKind DSK = DstC->getSelectionKind();
667 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
671 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
672 const GlobalValue &Dest,
673 const GlobalValue &Src) {
674 // We always have to add Src if it has appending linkage.
675 if (Src.hasAppendingLinkage()) {
680 bool SrcIsDeclaration = Src.isDeclarationForLinker();
681 bool DestIsDeclaration = Dest.isDeclarationForLinker();
683 if (SrcIsDeclaration) {
684 // If Src is external or if both Src & Dest are external.. Just link the
685 // external globals, we aren't adding anything.
686 if (Src.hasDLLImportStorageClass()) {
687 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
688 LinkFromSrc = DestIsDeclaration;
691 // If the Dest is weak, use the source linkage.
692 LinkFromSrc = Dest.hasExternalWeakLinkage();
696 if (DestIsDeclaration) {
697 // If Dest is external but Src is not:
702 if (Src.hasCommonLinkage()) {
703 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
708 if (!Dest.hasCommonLinkage()) {
713 // FIXME: Make datalayout mandatory and just use getDataLayout().
714 DataLayout DL(Dest.getParent());
716 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
717 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
718 LinkFromSrc = SrcSize > DestSize;
722 if (Src.isWeakForLinker()) {
723 assert(!Dest.hasExternalWeakLinkage());
724 assert(!Dest.hasAvailableExternallyLinkage());
726 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
735 if (Dest.isWeakForLinker()) {
736 assert(Src.hasExternalLinkage());
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!");
749 /// Loop over all of the linked values to compute type mappings. For example,
750 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
751 /// types 'Foo' but one got renamed when the module was loaded into the same
753 void ModuleLinker::computeTypeMapping() {
754 for (GlobalValue &SGV : SrcM->globals()) {
755 GlobalValue *DGV = getLinkedToGlobal(&SGV);
759 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
760 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
764 // Unify the element type of appending arrays.
765 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
766 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
767 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
770 for (GlobalValue &SGV : *SrcM) {
771 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
772 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
775 for (GlobalValue &SGV : SrcM->aliases()) {
776 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
777 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
780 // Incorporate types by name, scanning all the types in the source module.
781 // At this point, the destination module may have a type "%foo = { i32 }" for
782 // example. When the source module got loaded into the same LLVMContext, if
783 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
784 TypeFinder SrcStructTypes;
785 SrcStructTypes.run(*SrcM, true);
786 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
787 SrcStructTypes.end());
789 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
790 StructType *ST = SrcStructTypes[i];
791 if (!ST->hasName()) continue;
793 // Check to see if there is a dot in the name followed by a digit.
794 size_t DotPos = ST->getName().rfind('.');
795 if (DotPos == 0 || DotPos == StringRef::npos ||
796 ST->getName().back() == '.' ||
797 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
800 // Check to see if the destination module has a struct with the prefix name.
801 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
802 // Don't use it if this actually came from the source module. They're in
803 // the same LLVMContext after all. Also don't use it unless the type is
804 // actually used in the destination module. This can happen in situations
809 // %Z = type { %A } %B = type { %C.1 }
810 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
811 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
812 // %C = type { i8* } %B.3 = type { %C.1 }
814 // When we link Module B with Module A, the '%B' in Module B is
815 // used. However, that would then use '%C.1'. But when we process '%C.1',
816 // we prefer to take the '%C' version. So we are then left with both
817 // '%C.1' and '%C' being used for the same types. This leads to some
818 // variables using one type and some using the other.
819 if (!SrcStructTypesSet.count(DST))
820 TypeMap.addTypeMapping(DST, ST);
823 // Now that we have discovered all of the type equivalences, get a body for
824 // any 'opaque' types in the dest module that are now resolved.
825 TypeMap.linkDefinedTypeBodies();
828 static void upgradeGlobalArray(GlobalVariable *GV) {
829 ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
830 StructType *OldTy = cast<StructType>(ATy->getElementType());
831 assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
833 // Get the upgraded 3 element type.
834 PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
835 Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
837 StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
839 // Build new constants with a null third field filled in.
840 Constant *OldInitC = GV->getInitializer();
841 ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
842 if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
843 // Invalid initializer; give up.
845 std::vector<Constant *> Initializers;
846 if (OldInit && OldInit->getNumOperands()) {
847 Value *Null = Constant::getNullValue(VoidPtrTy);
848 for (Use &U : OldInit->operands()) {
849 ConstantStruct *Init = cast<ConstantStruct>(U.get());
850 Initializers.push_back(ConstantStruct::get(
851 NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
854 assert(Initializers.size() == ATy->getNumElements() &&
855 "Failed to copy all array elements");
857 // Replace the old GV with a new one.
858 ATy = ArrayType::get(NewTy, Initializers.size());
859 Constant *NewInit = ConstantArray::get(ATy, Initializers);
860 GlobalVariable *NewGV = new GlobalVariable(
861 *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
862 GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
863 GV->isExternallyInitialized());
864 NewGV->copyAttributesFrom(GV);
866 assert(GV->use_empty() && "program cannot use initializer list");
867 GV->eraseFromParent();
870 void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
871 // Look for the global arrays.
872 auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
875 auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
879 // Check if the types already match.
880 auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
882 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
886 // Grab the element types. We can only upgrade an array of a two-field
887 // struct. Only bother if the other one has three-fields.
888 auto *DstEltTy = cast<StructType>(DstTy->getElementType());
889 auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
890 if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
891 upgradeGlobalArray(DstGV);
894 if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
895 upgradeGlobalArray(SrcGV);
897 // We can't upgrade any other differences.
900 void ModuleLinker::upgradeMismatchedGlobals() {
901 upgradeMismatchedGlobalArray("llvm.global_ctors");
902 upgradeMismatchedGlobalArray("llvm.global_dtors");
905 /// If there were any appending global variables, link them together now.
906 /// Return true on error.
907 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
908 const GlobalVariable *SrcGV) {
910 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
911 return emitError("Linking globals named '" + SrcGV->getName() +
912 "': can only link appending global with another appending global!");
914 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
916 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
917 Type *EltTy = DstTy->getElementType();
919 // Check to see that they two arrays agree on type.
920 if (EltTy != SrcTy->getElementType())
921 return emitError("Appending variables with different element types!");
922 if (DstGV->isConstant() != SrcGV->isConstant())
923 return emitError("Appending variables linked with different const'ness!");
925 if (DstGV->getAlignment() != SrcGV->getAlignment())
927 "Appending variables with different alignment need to be linked!");
929 if (DstGV->getVisibility() != SrcGV->getVisibility())
931 "Appending variables with different visibility need to be linked!");
933 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
935 "Appending variables with different unnamed_addr need to be linked!");
937 if (StringRef(DstGV->getSection()) != SrcGV->getSection())
939 "Appending variables with different section name need to be linked!");
941 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
942 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
944 // Create the new global variable.
946 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
947 DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
948 DstGV->getThreadLocalMode(),
949 DstGV->getType()->getAddressSpace());
951 // Propagate alignment, visibility and section info.
952 copyGVAttributes(NG, DstGV);
954 AppendingVarInfo AVI;
956 AVI.DstInit = DstGV->getInitializer();
957 AVI.SrcInit = SrcGV->getInitializer();
958 AppendingVars.push_back(AVI);
960 // Replace any uses of the two global variables with uses of the new
962 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
964 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
965 DstGV->eraseFromParent();
967 // Track the source variable so we don't try to link it.
968 DoNotLinkFromSource.insert(SrcGV);
973 bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
974 GlobalValue *DGV = getLinkedToGlobal(SGV);
976 // Handle the ultra special appending linkage case first.
977 if (DGV && DGV->hasAppendingLinkage())
978 return linkAppendingVarProto(cast<GlobalVariable>(DGV),
979 cast<GlobalVariable>(SGV));
981 bool LinkFromSrc = true;
983 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
984 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
986 if (const Comdat *SC = SGV->getComdat()) {
987 Comdat::SelectionKind SK;
988 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
989 C = DstM->getOrInsertComdat(SC->getName());
990 C->setSelectionKind(SK);
992 if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
997 // Track the source global so that we don't attempt to copy it over when
998 // processing global initializers.
999 DoNotLinkFromSource.insert(SGV);
1002 // Make sure to remember this mapping.
1004 ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
1008 Visibility = isLessConstraining(Visibility, DGV->getVisibility())
1009 ? DGV->getVisibility()
1011 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1014 if (!LinkFromSrc && !DGV)
1018 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
1019 NewGV = linkGlobalVariableProto(SGVar, DGV, LinkFromSrc);
1022 } else if (auto *SF = dyn_cast<Function>(SGV)) {
1023 NewGV = linkFunctionProto(SF, DGV, LinkFromSrc);
1025 NewGV = linkGlobalAliasProto(cast<GlobalAlias>(SGV), DGV, LinkFromSrc);
1030 copyGVAttributes(NewGV, SGV);
1032 NewGV->setUnnamedAddr(HasUnnamedAddr);
1033 NewGV->setVisibility(Visibility);
1035 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1037 NewGO->setComdat(C);
1040 // Make sure to remember this mapping.
1043 DGV->replaceAllUsesWith(
1044 ConstantExpr::getBitCast(NewGV, DGV->getType()));
1045 DGV->eraseFromParent();
1047 ValueMap[SGV] = NewGV;
1054 /// Loop through the global variables in the src module and merge them into the
1056 GlobalValue *ModuleLinker::linkGlobalVariableProto(const GlobalVariable *SGVar,
1059 unsigned Alignment = 0;
1060 bool ClearConstant = false;
1063 if (DGV->hasCommonLinkage() && SGVar->hasCommonLinkage())
1064 Alignment = std::max(SGVar->getAlignment(), DGV->getAlignment());
1066 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
1067 if (!SGVar->isConstant() || (DGVar && !DGVar->isConstant()))
1068 ClearConstant = true;
1072 if (auto *NewGVar = dyn_cast<GlobalVariable>(DGV)) {
1074 NewGVar->setAlignment(Alignment);
1075 if (NewGVar->isDeclaration() && ClearConstant)
1076 NewGVar->setConstant(false);
1081 // No linking to be performed or linking from the source: simply create an
1082 // identical version of the symbol over in the dest module... the
1083 // initializer will be filled in later by LinkGlobalInits.
1084 GlobalVariable *NewDGV = new GlobalVariable(
1085 *DstM, TypeMap.get(SGVar->getType()->getElementType()),
1086 SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr,
1087 SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
1088 SGVar->getType()->getAddressSpace());
1091 NewDGV->setAlignment(Alignment);
1096 /// Link the function in the source module into the destination module if
1097 /// needed, setting up mapping information.
1098 GlobalValue *ModuleLinker::linkFunctionProto(const Function *SF,
1104 // If the function is to be lazily linked, don't create it just yet.
1105 // The ValueMaterializerTy will deal with creating it if it's used.
1106 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1107 SF->hasAvailableExternallyLinkage())) {
1108 DoNotLinkFromSource.insert(SF);
1112 // If there is no linkage to be performed or we are linking from the source,
1114 return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(),
1115 SF->getName(), DstM);
1118 /// Set up prototypes for any aliases that come over from the source module.
1119 GlobalValue *ModuleLinker::linkGlobalAliasProto(const GlobalAlias *SGA,
1125 // If there is no linkage to be performed or we're linking from the source,
1127 auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
1128 return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1129 SGA->getLinkage(), SGA->getName(), DstM);
1132 static void getArrayElements(const Constant *C,
1133 SmallVectorImpl<Constant *> &Dest) {
1134 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1136 for (unsigned i = 0; i != NumElements; ++i)
1137 Dest.push_back(C->getAggregateElement(i));
1140 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1141 // Merge the initializer.
1142 SmallVector<Constant *, 16> DstElements;
1143 getArrayElements(AVI.DstInit, DstElements);
1145 SmallVector<Constant *, 16> SrcElements;
1146 getArrayElements(AVI.SrcInit, SrcElements);
1148 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1150 StringRef Name = AVI.NewGV->getName();
1151 bool IsNewStructor =
1152 (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1153 cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1155 for (auto *V : SrcElements) {
1156 if (IsNewStructor) {
1157 Constant *Key = V->getAggregateElement(2);
1158 if (DoNotLinkFromSource.count(Key))
1161 DstElements.push_back(
1162 MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1164 if (IsNewStructor) {
1165 NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1166 AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1169 AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1172 /// Update the initializers in the Dest module now that all globals that may be
1173 /// referenced are in Dest.
1174 void ModuleLinker::linkGlobalInits() {
1175 // Loop over all of the globals in the src module, mapping them over as we go
1176 for (Module::const_global_iterator I = SrcM->global_begin(),
1177 E = SrcM->global_end(); I != E; ++I) {
1179 // Only process initialized GV's or ones not already in dest.
1180 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1182 // Grab destination global variable.
1183 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1184 // Figure out what the initializer looks like in the dest module.
1185 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
1186 RF_None, &TypeMap, &ValMaterializer));
1190 /// Copy the source function over into the dest function and fix up references
1191 /// to values. At this point we know that Dest is an external function, and
1192 /// that Src is not.
1193 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1194 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
1196 // Go through and convert function arguments over, remembering the mapping.
1197 Function::arg_iterator DI = Dst->arg_begin();
1198 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1199 I != E; ++I, ++DI) {
1200 DI->setName(I->getName()); // Copy the name over.
1202 // Add a mapping to our mapping.
1206 // Splice the body of the source function into the dest function.
1207 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
1209 // At this point, all of the instructions and values of the function are now
1210 // copied over. The only problem is that they are still referencing values in
1211 // the Source function as operands. Loop through all of the operands of the
1212 // functions and patch them up to point to the local versions.
1213 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1214 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1215 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap,
1218 // There is no need to map the arguments anymore.
1219 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1225 /// Insert all of the aliases in Src into the Dest module.
1226 void ModuleLinker::linkAliasBodies() {
1227 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
1229 if (DoNotLinkFromSource.count(I))
1231 if (Constant *Aliasee = I->getAliasee()) {
1232 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
1234 MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1235 DA->setAliasee(Val);
1240 /// Insert all of the named MDNodes in Src into the Dest module.
1241 void ModuleLinker::linkNamedMDNodes() {
1242 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1243 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1244 E = SrcM->named_metadata_end(); I != E; ++I) {
1245 // Don't link module flags here. Do them separately.
1246 if (&*I == SrcModFlags) continue;
1247 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1248 // Add Src elements into Dest node.
1249 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1250 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
1251 RF_None, &TypeMap, &ValMaterializer));
1255 /// Merge the linker flags in Src into the Dest module.
1256 bool ModuleLinker::linkModuleFlagsMetadata() {
1257 // If the source module has no module flags, we are done.
1258 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1259 if (!SrcModFlags) return false;
1261 // If the destination module doesn't have module flags yet, then just copy
1262 // over the source module's flags.
1263 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1264 if (DstModFlags->getNumOperands() == 0) {
1265 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1266 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1271 // First build a map of the existing module flags and requirements.
1272 DenseMap<MDString*, MDNode*> Flags;
1273 SmallSetVector<MDNode*, 16> Requirements;
1274 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1275 MDNode *Op = DstModFlags->getOperand(I);
1276 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1277 MDString *ID = cast<MDString>(Op->getOperand(1));
1279 if (Behavior->getZExtValue() == Module::Require) {
1280 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1286 // Merge in the flags from the source module, and also collect its set of
1288 bool HasErr = false;
1289 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1290 MDNode *SrcOp = SrcModFlags->getOperand(I);
1291 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1292 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1293 MDNode *DstOp = Flags.lookup(ID);
1294 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1296 // If this is a requirement, add it and continue.
1297 if (SrcBehaviorValue == Module::Require) {
1298 // If the destination module does not already have this requirement, add
1300 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1301 DstModFlags->addOperand(SrcOp);
1306 // If there is no existing flag with this ID, just add it.
1309 DstModFlags->addOperand(SrcOp);
1313 // Otherwise, perform a merge.
1314 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1315 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1317 // If either flag has override behavior, handle it first.
1318 if (DstBehaviorValue == Module::Override) {
1319 // Diagnose inconsistent flags which both have override behavior.
1320 if (SrcBehaviorValue == Module::Override &&
1321 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1322 HasErr |= emitError("linking module flags '" + ID->getString() +
1323 "': IDs have conflicting override values");
1326 } else if (SrcBehaviorValue == Module::Override) {
1327 // Update the destination flag to that of the source.
1328 DstOp->replaceOperandWith(0, SrcBehavior);
1329 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1333 // Diagnose inconsistent merge behavior types.
1334 if (SrcBehaviorValue != DstBehaviorValue) {
1335 HasErr |= emitError("linking module flags '" + ID->getString() +
1336 "': IDs have conflicting behaviors");
1340 // Perform the merge for standard behavior types.
1341 switch (SrcBehaviorValue) {
1342 case Module::Require:
1343 case Module::Override: llvm_unreachable("not possible");
1344 case Module::Error: {
1345 // Emit an error if the values differ.
1346 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1347 HasErr |= emitError("linking module flags '" + ID->getString() +
1348 "': IDs have conflicting values");
1352 case Module::Warning: {
1353 // Emit a warning if the values differ.
1354 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1355 emitWarning("linking module flags '" + ID->getString() +
1356 "': IDs have conflicting values");
1360 case Module::Append: {
1361 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1362 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1363 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1364 Value **VP, **Values = VP = new Value*[NumOps];
1365 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1366 *VP = DstValue->getOperand(i);
1367 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1368 *VP = SrcValue->getOperand(i);
1369 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1370 ArrayRef<Value*>(Values,
1375 case Module::AppendUnique: {
1376 SmallSetVector<Value*, 16> Elts;
1377 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1378 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1379 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1380 Elts.insert(DstValue->getOperand(i));
1381 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1382 Elts.insert(SrcValue->getOperand(i));
1383 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1384 ArrayRef<Value*>(Elts.begin(),
1391 // Check all of the requirements.
1392 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1393 MDNode *Requirement = Requirements[I];
1394 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1395 Value *ReqValue = Requirement->getOperand(1);
1397 MDNode *Op = Flags[Flag];
1398 if (!Op || Op->getOperand(2) != ReqValue) {
1399 HasErr |= emitError("linking module flags '" + Flag->getString() +
1400 "': does not have the required value");
1408 bool ModuleLinker::run() {
1409 assert(DstM && "Null destination module");
1410 assert(SrcM && "Null source module");
1412 // Inherit the target data from the source module if the destination module
1413 // doesn't have one already.
1414 if (!DstM->getDataLayout() && SrcM->getDataLayout())
1415 DstM->setDataLayout(SrcM->getDataLayout());
1417 // Copy the target triple from the source to dest if the dest's is empty.
1418 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1419 DstM->setTargetTriple(SrcM->getTargetTriple());
1421 if (SrcM->getDataLayout() && DstM->getDataLayout() &&
1422 *SrcM->getDataLayout() != *DstM->getDataLayout()) {
1423 emitWarning("Linking two modules of different data layouts: '" +
1424 SrcM->getModuleIdentifier() + "' is '" +
1425 SrcM->getDataLayoutStr() + "' whereas '" +
1426 DstM->getModuleIdentifier() + "' is '" +
1427 DstM->getDataLayoutStr() + "'\n");
1429 if (!SrcM->getTargetTriple().empty() &&
1430 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1431 emitWarning("Linking two modules of different target triples: " +
1432 SrcM->getModuleIdentifier() + "' is '" +
1433 SrcM->getTargetTriple() + "' whereas '" +
1434 DstM->getModuleIdentifier() + "' is '" +
1435 DstM->getTargetTriple() + "'\n");
1438 // Append the module inline asm string.
1439 if (!SrcM->getModuleInlineAsm().empty()) {
1440 if (DstM->getModuleInlineAsm().empty())
1441 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1443 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1444 SrcM->getModuleInlineAsm());
1447 // Loop over all of the linked values to compute type mappings.
1448 computeTypeMapping();
1450 ComdatsChosen.clear();
1451 for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
1452 const Comdat &C = SMEC.getValue();
1453 if (ComdatsChosen.count(&C))
1455 Comdat::SelectionKind SK;
1457 if (getComdatResult(&C, SK, LinkFromSrc))
1459 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1462 // Upgrade mismatched global arrays.
1463 upgradeMismatchedGlobals();
1465 // Insert all of the globals in src into the DstM module... without linking
1466 // initializers (which could refer to functions not yet mapped over).
1467 for (Module::global_iterator I = SrcM->global_begin(),
1468 E = SrcM->global_end(); I != E; ++I)
1469 if (linkGlobalValueProto(I))
1472 // Link the functions together between the two modules, without doing function
1473 // bodies... this just adds external function prototypes to the DstM
1474 // function... We do this so that when we begin processing function bodies,
1475 // all of the global values that may be referenced are available in our
1477 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1478 if (linkGlobalValueProto(I))
1481 // If there were any aliases, link them now.
1482 for (Module::alias_iterator I = SrcM->alias_begin(),
1483 E = SrcM->alias_end(); I != E; ++I)
1484 if (linkGlobalValueProto(I))
1487 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1488 linkAppendingVarInit(AppendingVars[i]);
1490 // Link in the function bodies that are defined in the source module into
1492 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1493 // Skip if not linking from source.
1494 if (DoNotLinkFromSource.count(SF)) continue;
1496 Function *DF = cast<Function>(ValueMap[SF]);
1497 if (SF->hasPrefixData()) {
1498 // Link in the prefix data.
1499 DF->setPrefixData(MapValue(
1500 SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1503 // Materialize if needed.
1504 if (std::error_code EC = SF->materialize())
1505 return emitError(EC.message());
1507 // Skip if no body (function is external).
1508 if (SF->isDeclaration())
1511 linkFunctionBody(DF, SF);
1512 SF->Dematerialize();
1515 // Resolve all uses of aliases with aliasees.
1518 // Remap all of the named MDNodes in Src into the DstM module. We do this
1519 // after linking GlobalValues so that MDNodes that reference GlobalValues
1520 // are properly remapped.
1523 // Merge the module flags into the DstM module.
1524 if (linkModuleFlagsMetadata())
1527 // Update the initializers in the DstM module now that all globals that may
1528 // be referenced are in DstM.
1531 // Process vector of lazily linked in functions.
1532 bool LinkedInAnyFunctions;
1534 LinkedInAnyFunctions = false;
1536 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1537 E = LazilyLinkFunctions.end(); I != E; ++I) {
1542 Function *DF = cast<Function>(ValueMap[SF]);
1543 if (SF->hasPrefixData()) {
1544 // Link in the prefix data.
1545 DF->setPrefixData(MapValue(SF->getPrefixData(),
1552 // Materialize if needed.
1553 if (std::error_code EC = SF->materialize())
1554 return emitError(EC.message());
1556 // Skip if no body (function is external).
1557 if (SF->isDeclaration())
1560 // Erase from vector *before* the function body is linked - linkFunctionBody could
1562 LazilyLinkFunctions.erase(I);
1564 // Link in function body.
1565 linkFunctionBody(DF, SF);
1566 SF->Dematerialize();
1568 // Set flag to indicate we may have more functions to lazily link in
1569 // since we linked in a function.
1570 LinkedInAnyFunctions = true;
1573 } while (LinkedInAnyFunctions);
1578 void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1579 this->Composite = M;
1580 this->DiagnosticHandler = DiagnosticHandler;
1583 Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1584 init(M, DiagnosticHandler);
1587 Linker::Linker(Module *M) {
1588 init(M, [this](const DiagnosticInfo &DI) {
1589 Composite->getContext().diagnose(DI);
1596 void Linker::deleteModule() {
1598 Composite = nullptr;
1601 bool Linker::linkInModule(Module *Src) {
1602 ModuleLinker TheLinker(Composite, Src, DiagnosticHandler);
1603 return TheLinker.run();
1606 //===----------------------------------------------------------------------===//
1607 // LinkModules entrypoint.
1608 //===----------------------------------------------------------------------===//
1610 /// This function links two modules together, with the resulting Dest module
1611 /// modified to be the composite of the two input modules. If an error occurs,
1612 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
1613 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
1614 /// relied on to be consistent.
1615 bool Linker::LinkModules(Module *Dest, Module *Src,
1616 DiagnosticHandlerFunction DiagnosticHandler) {
1617 Linker L(Dest, DiagnosticHandler);
1618 return L.linkInModule(Src);
1621 bool Linker::LinkModules(Module *Dest, Module *Src) {
1623 return L.linkInModule(Src);
1626 //===----------------------------------------------------------------------===//
1628 //===----------------------------------------------------------------------===//
1630 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1631 LLVMLinkerMode Mode, char **OutMessages) {
1632 Module *D = unwrap(Dest);
1633 std::string Message;
1634 raw_string_ostream Stream(Message);
1635 DiagnosticPrinterRawOStream DP(Stream);
1637 LLVMBool Result = Linker::LinkModules(
1638 D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
1640 if (OutMessages && Result)
1641 *OutMessages = strdup(Message.c_str());