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 for (Type *Ty : SpeculativeTypes)
116 if (auto *STy = dyn_cast<StructType>(Ty))
120 SpeculativeTypes.clear();
121 SpeculativeDstOpaqueTypes.clear();
124 /// Recursively walk this pair of types, returning true if they are isomorphic,
125 /// false if they are not.
126 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
127 // Two types with differing kinds are clearly not isomorphic.
128 if (DstTy->getTypeID() != SrcTy->getTypeID())
131 // If we have an entry in the MappedTypes table, then we have our answer.
132 Type *&Entry = MappedTypes[SrcTy];
134 return Entry == DstTy;
136 // Two identical types are clearly isomorphic. Remember this
137 // non-speculatively.
138 if (DstTy == SrcTy) {
143 // Okay, we have two types with identical kinds that we haven't seen before.
145 // If this is an opaque struct type, special case it.
146 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
147 // Mapping an opaque type to any struct, just keep the dest struct.
148 if (SSTy->isOpaque()) {
150 SpeculativeTypes.push_back(SrcTy);
154 // Mapping a non-opaque source type to an opaque dest. If this is the first
155 // type that we're mapping onto this destination type then we succeed. Keep
156 // the dest, but fill it in later. If this is the second (different) type
157 // that we're trying to map onto the same opaque type then we fail.
158 if (cast<StructType>(DstTy)->isOpaque()) {
159 // We can only map one source type onto the opaque destination type.
160 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
162 SrcDefinitionsToResolve.push_back(SSTy);
163 SpeculativeTypes.push_back(SrcTy);
164 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
170 // If the number of subtypes disagree between the two types, then we fail.
171 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
174 // Fail if any of the extra properties (e.g. array size) of the type disagree.
175 if (isa<IntegerType>(DstTy))
176 return false; // bitwidth disagrees.
177 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
178 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
181 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
182 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
184 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
185 StructType *SSTy = cast<StructType>(SrcTy);
186 if (DSTy->isLiteral() != SSTy->isLiteral() ||
187 DSTy->isPacked() != SSTy->isPacked())
189 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
190 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
192 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
193 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
197 // Otherwise, we speculate that these two types will line up and recursively
198 // check the subelements.
200 SpeculativeTypes.push_back(SrcTy);
202 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
203 if (!areTypesIsomorphic(DstTy->getContainedType(I),
204 SrcTy->getContainedType(I)))
207 // If everything seems to have lined up, then everything is great.
211 void TypeMapTy::linkDefinedTypeBodies() {
212 SmallVector<Type*, 16> Elements;
213 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
214 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
215 assert(DstSTy->isOpaque());
217 // Map the body of the source type over to a new body for the dest type.
218 Elements.resize(SrcSTy->getNumElements());
219 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
220 Elements[I] = get(SrcSTy->getElementType(I));
222 DstSTy->setBody(Elements, SrcSTy->isPacked());
224 SrcDefinitionsToResolve.clear();
225 DstResolvedOpaqueTypes.clear();
228 Type *TypeMapTy::get(Type *Ty) {
230 for (auto &Pair : MappedTypes) {
231 assert(!(Pair.first != Ty && Pair.second == Ty) &&
232 "mapping to a source type");
236 // If we already have an entry for this type, return it.
237 Type **Entry = &MappedTypes[Ty];
241 // If this is not a named struct type, then just map all of the elements and
242 // then rebuild the type from inside out.
243 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
244 // If there are no element types to map, then the type is itself. This is
245 // true for the anonymous {} struct, things like 'float', integers, etc.
246 if (Ty->getNumContainedTypes() == 0)
249 // Remap all of the elements, keeping track of whether any of them change.
250 bool AnyChange = false;
251 SmallVector<Type*, 4> ElementTypes;
252 ElementTypes.resize(Ty->getNumContainedTypes());
253 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
254 ElementTypes[I] = get(Ty->getContainedType(I));
255 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
258 // If we found our type while recursively processing stuff, just use it.
259 Entry = &MappedTypes[Ty];
263 // If all of the element types mapped directly over, then the type is usable
268 // Otherwise, rebuild a modified type.
269 switch (Ty->getTypeID()) {
271 llvm_unreachable("unknown derived type to remap");
272 case Type::ArrayTyID:
273 return *Entry = ArrayType::get(ElementTypes[0],
274 cast<ArrayType>(Ty)->getNumElements());
275 case Type::VectorTyID:
276 return *Entry = VectorType::get(ElementTypes[0],
277 cast<VectorType>(Ty)->getNumElements());
278 case Type::PointerTyID:
279 return *Entry = PointerType::get(
280 ElementTypes[0], cast<PointerType>(Ty)->getAddressSpace());
281 case Type::FunctionTyID:
282 return *Entry = FunctionType::get(ElementTypes[0],
283 makeArrayRef(ElementTypes).slice(1),
284 cast<FunctionType>(Ty)->isVarArg());
285 case Type::StructTyID:
286 // Note that this is only reached for anonymous structs.
287 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
288 cast<StructType>(Ty)->isPacked());
292 // Otherwise, this is an unmapped named struct. If the struct can be directly
293 // mapped over, just use it as-is. This happens in a case when the linked-in
294 // module has something like:
295 // %T = type {%T*, i32}
296 // @GV = global %T* null
297 // where T does not exist at all in the destination module.
299 // The other case we watch for is when the type is not in the destination
300 // module, but that it has to be rebuilt because it refers to something that
301 // is already mapped. For example, if the destination module has:
303 // and the source module has something like
304 // %A' = type { i32 }
305 // %B = type { %A'* }
306 // @GV = global %B* null
307 // then we want to create a new type: "%B = type { %A*}" and have it take the
308 // pristine "%B" name from the source module.
310 // To determine which case this is, we have to recursively walk the type graph
311 // speculating that we'll be able to reuse it unmodified. Only if this is
312 // safe would we map the entire thing over. Because this is an optimization,
313 // and is not required for the prettiness of the linked module, we just skip
314 // it and always rebuild a type here.
315 StructType *STy = cast<StructType>(Ty);
317 // If the type is opaque, we can just use it directly.
318 if (STy->isOpaque()) {
319 // A named structure type from src module is used. Add it to the Set of
320 // identified structs in the destination module.
321 DstStructTypesSet.insert(STy);
325 // Otherwise we create a new type.
326 StructType *DTy = StructType::create(STy->getContext());
327 // A new identified structure type was created. Add it to the set of
328 // identified structs in the destination module.
329 DstStructTypesSet.insert(DTy);
332 SmallVector<Type*, 4> ElementTypes;
333 ElementTypes.resize(STy->getNumElements());
334 for (unsigned I = 0, E = ElementTypes.size(); I != E; ++I)
335 ElementTypes[I] = get(STy->getElementType(I));
336 DTy->setBody(ElementTypes, STy->isPacked());
339 if (STy->hasName()) {
340 SmallString<16> TmpName = STy->getName();
342 DTy->setName(TmpName);
348 //===----------------------------------------------------------------------===//
349 // ModuleLinker implementation.
350 //===----------------------------------------------------------------------===//
355 /// Creates prototypes for functions that are lazily linked on the fly. This
356 /// speeds up linking for modules with many/ lazily linked functions of which
358 class ValueMaterializerTy : public ValueMaterializer {
361 std::vector<Function *> &LazilyLinkFunctions;
364 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
365 std::vector<Function *> &LazilyLinkFunctions)
366 : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
367 LazilyLinkFunctions(LazilyLinkFunctions) {}
369 Value *materializeValueFor(Value *V) override;
372 class LinkDiagnosticInfo : public DiagnosticInfo {
376 LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
377 void print(DiagnosticPrinter &DP) const override;
379 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
381 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
382 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
384 /// This is an implementation class for the LinkModules function, which is the
385 /// entrypoint for this file.
390 ValueMaterializerTy ValMaterializer;
392 /// Mapping of values from what they used to be in Src, to what they are now
393 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
394 /// due to the use of Value handles which the Linker doesn't actually need,
395 /// but this allows us to reuse the ValueMapper code.
396 ValueToValueMapTy ValueMap;
398 struct AppendingVarInfo {
399 GlobalVariable *NewGV; // New aggregate global in dest module.
400 const Constant *DstInit; // Old initializer from dest module.
401 const Constant *SrcInit; // Old initializer from src module.
404 std::vector<AppendingVarInfo> AppendingVars;
406 // Set of items not to link in from source.
407 SmallPtrSet<const Value *, 16> DoNotLinkFromSource;
409 // Vector of functions to lazily link in.
410 std::vector<Function *> LazilyLinkFunctions;
412 Linker::DiagnosticHandlerFunction DiagnosticHandler;
415 ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM,
416 Linker::DiagnosticHandlerFunction DiagnosticHandler)
417 : DstM(dstM), SrcM(srcM), TypeMap(Set),
418 ValMaterializer(TypeMap, DstM, LazilyLinkFunctions),
419 DiagnosticHandler(DiagnosticHandler) {}
424 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
425 const GlobalValue &Src);
427 /// Helper method for setting a message and returning an error code.
428 bool emitError(const Twine &Message) {
429 DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
433 void emitWarning(const Twine &Message) {
434 DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
437 bool getComdatLeader(Module *M, StringRef ComdatName,
438 const GlobalVariable *&GVar);
439 bool computeResultingSelectionKind(StringRef ComdatName,
440 Comdat::SelectionKind Src,
441 Comdat::SelectionKind Dst,
442 Comdat::SelectionKind &Result,
444 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
446 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
449 /// Given a global in the source module, return the global in the
450 /// destination module that is being linked to, if any.
451 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
452 // If the source has no name it can't link. If it has local linkage,
453 // there is no name match-up going on.
454 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
457 // Otherwise see if we have a match in the destination module's symtab.
458 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
462 // If we found a global with the same name in the dest module, but it has
463 // internal linkage, we are really not doing any linkage here.
464 if (DGV->hasLocalLinkage())
467 // Otherwise, we do in fact link to the destination global.
471 void computeTypeMapping();
473 void upgradeMismatchedGlobalArray(StringRef Name);
474 void upgradeMismatchedGlobals();
476 bool linkAppendingVarProto(GlobalVariable *DstGV,
477 const GlobalVariable *SrcGV);
479 bool linkGlobalValueProto(GlobalValue *GV);
480 GlobalValue *linkGlobalVariableProto(const GlobalVariable *SGVar,
481 GlobalValue *DGV, bool LinkFromSrc);
482 GlobalValue *linkFunctionProto(const Function *SF, GlobalValue *DGV,
484 GlobalValue *linkGlobalAliasProto(const GlobalAlias *SGA, GlobalValue *DGV,
487 bool linkModuleFlagsMetadata();
489 void linkAppendingVarInit(const AppendingVarInfo &AVI);
490 void linkGlobalInits();
491 void linkFunctionBody(Function *Dst, Function *Src);
492 void linkAliasBodies();
493 void linkNamedMDNodes();
497 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
498 /// table. This is good for all clients except for us. Go through the trouble
499 /// to force this back.
500 static void forceRenaming(GlobalValue *GV, StringRef Name) {
501 // If the global doesn't force its name or if it already has the right name,
502 // there is nothing for us to do.
503 if (GV->hasLocalLinkage() || GV->getName() == Name)
506 Module *M = GV->getParent();
508 // If there is a conflict, rename the conflict.
509 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
510 GV->takeName(ConflictGV);
511 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
512 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
514 GV->setName(Name); // Force the name back
518 /// copy additional attributes (those not needed to construct a GlobalValue)
519 /// from the SrcGV to the DestGV.
520 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
521 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
522 auto *DestGO = dyn_cast<GlobalObject>(DestGV);
525 Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
527 DestGV->copyAttributesFrom(SrcGV);
530 DestGO->setAlignment(Alignment);
532 forceRenaming(DestGV, SrcGV->getName());
535 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
536 GlobalValue::VisibilityTypes b) {
537 if (a == GlobalValue::HiddenVisibility)
539 if (b == GlobalValue::HiddenVisibility)
541 if (a == GlobalValue::ProtectedVisibility)
543 if (b == GlobalValue::ProtectedVisibility)
548 Value *ValueMaterializerTy::materializeValueFor(Value *V) {
549 Function *SF = dyn_cast<Function>(V);
553 Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
554 SF->getLinkage(), SF->getName(), DstM);
555 copyGVAttributes(DF, SF);
557 if (Comdat *SC = SF->getComdat()) {
558 Comdat *DC = DstM->getOrInsertComdat(SC->getName());
562 LazilyLinkFunctions.push_back(SF);
566 bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
567 const GlobalVariable *&GVar) {
568 const GlobalValue *GVal = M->getNamedValue(ComdatName);
569 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
570 GVal = GA->getBaseObject();
572 // We cannot resolve the size of the aliasee yet.
573 return emitError("Linking COMDATs named '" + ComdatName +
574 "': COMDAT key involves incomputable alias size.");
577 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
580 "Linking COMDATs named '" + ComdatName +
581 "': GlobalVariable required for data dependent selection!");
586 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
587 Comdat::SelectionKind Src,
588 Comdat::SelectionKind Dst,
589 Comdat::SelectionKind &Result,
591 // The ability to mix Comdat::SelectionKind::Any with
592 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
593 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
594 Dst == Comdat::SelectionKind::Largest;
595 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
596 Src == Comdat::SelectionKind::Largest;
597 if (DstAnyOrLargest && SrcAnyOrLargest) {
598 if (Dst == Comdat::SelectionKind::Largest ||
599 Src == Comdat::SelectionKind::Largest)
600 Result = Comdat::SelectionKind::Largest;
602 Result = Comdat::SelectionKind::Any;
603 } else if (Src == Dst) {
606 return emitError("Linking COMDATs named '" + ComdatName +
607 "': invalid selection kinds!");
611 case Comdat::SelectionKind::Any:
615 case Comdat::SelectionKind::NoDuplicates:
616 return emitError("Linking COMDATs named '" + ComdatName +
617 "': noduplicates has been violated!");
618 case Comdat::SelectionKind::ExactMatch:
619 case Comdat::SelectionKind::Largest:
620 case Comdat::SelectionKind::SameSize: {
621 const GlobalVariable *DstGV;
622 const GlobalVariable *SrcGV;
623 if (getComdatLeader(DstM, ComdatName, DstGV) ||
624 getComdatLeader(SrcM, ComdatName, SrcGV))
627 const DataLayout *DstDL = DstM->getDataLayout();
628 const DataLayout *SrcDL = SrcM->getDataLayout();
629 if (!DstDL || !SrcDL) {
631 "Linking COMDATs named '" + ComdatName +
632 "': can't do size dependent selection without DataLayout!");
635 DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
637 SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
638 if (Result == Comdat::SelectionKind::ExactMatch) {
639 if (SrcGV->getInitializer() != DstGV->getInitializer())
640 return emitError("Linking COMDATs named '" + ComdatName +
641 "': ExactMatch violated!");
643 } else if (Result == Comdat::SelectionKind::Largest) {
644 LinkFromSrc = SrcSize > DstSize;
645 } else if (Result == Comdat::SelectionKind::SameSize) {
646 if (SrcSize != DstSize)
647 return emitError("Linking COMDATs named '" + ComdatName +
648 "': SameSize violated!");
651 llvm_unreachable("unknown selection kind");
660 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
661 Comdat::SelectionKind &Result,
663 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
664 StringRef ComdatName = SrcC->getName();
665 Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
666 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
668 if (DstCI == ComdatSymTab.end()) {
669 // Use the comdat if it is only available in one of the modules.
675 const Comdat *DstC = &DstCI->second;
676 Comdat::SelectionKind DSK = DstC->getSelectionKind();
677 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
681 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
682 const GlobalValue &Dest,
683 const GlobalValue &Src) {
684 // We always have to add Src if it has appending linkage.
685 if (Src.hasAppendingLinkage()) {
690 bool SrcIsDeclaration = Src.isDeclarationForLinker();
691 bool DestIsDeclaration = Dest.isDeclarationForLinker();
693 if (SrcIsDeclaration) {
694 // If Src is external or if both Src & Dest are external.. Just link the
695 // external globals, we aren't adding anything.
696 if (Src.hasDLLImportStorageClass()) {
697 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
698 LinkFromSrc = DestIsDeclaration;
701 // If the Dest is weak, use the source linkage.
702 LinkFromSrc = Dest.hasExternalWeakLinkage();
706 if (DestIsDeclaration) {
707 // If Dest is external but Src is not:
712 if (Src.hasCommonLinkage()) {
713 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
718 if (!Dest.hasCommonLinkage()) {
723 // FIXME: Make datalayout mandatory and just use getDataLayout().
724 DataLayout DL(Dest.getParent());
726 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
727 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
728 LinkFromSrc = SrcSize > DestSize;
732 if (Src.isWeakForLinker()) {
733 assert(!Dest.hasExternalWeakLinkage());
734 assert(!Dest.hasAvailableExternallyLinkage());
736 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
745 if (Dest.isWeakForLinker()) {
746 assert(Src.hasExternalLinkage());
751 assert(!Src.hasExternalWeakLinkage());
752 assert(!Dest.hasExternalWeakLinkage());
753 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
754 "Unexpected linkage type!");
755 return emitError("Linking globals named '" + Src.getName() +
756 "': symbol multiply defined!");
759 /// Loop over all of the linked values to compute type mappings. For example,
760 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
761 /// types 'Foo' but one got renamed when the module was loaded into the same
763 void ModuleLinker::computeTypeMapping() {
764 for (GlobalValue &SGV : SrcM->globals()) {
765 GlobalValue *DGV = getLinkedToGlobal(&SGV);
769 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
770 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
774 // Unify the element type of appending arrays.
775 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
776 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
777 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
780 for (GlobalValue &SGV : *SrcM) {
781 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
782 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
785 for (GlobalValue &SGV : SrcM->aliases()) {
786 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
787 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
790 // Incorporate types by name, scanning all the types in the source module.
791 // At this point, the destination module may have a type "%foo = { i32 }" for
792 // example. When the source module got loaded into the same LLVMContext, if
793 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
794 TypeFinder SrcStructTypes;
795 SrcStructTypes.run(*SrcM, true);
797 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
798 StructType *ST = SrcStructTypes[i];
799 if (!ST->hasName()) continue;
801 // Check to see if there is a dot in the name followed by a digit.
802 size_t DotPos = ST->getName().rfind('.');
803 if (DotPos == 0 || DotPos == StringRef::npos ||
804 ST->getName().back() == '.' ||
805 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
808 // Check to see if the destination module has a struct with the prefix name.
809 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
810 // Don't use it if this actually came from the source module. They're in
811 // the same LLVMContext after all. Also don't use it unless the type is
812 // actually used in the destination module. This can happen in situations
817 // %Z = type { %A } %B = type { %C.1 }
818 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
819 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
820 // %C = type { i8* } %B.3 = type { %C.1 }
822 // When we link Module B with Module A, the '%B' in Module B is
823 // used. However, that would then use '%C.1'. But when we process '%C.1',
824 // we prefer to take the '%C' version. So we are then left with both
825 // '%C.1' and '%C' being used for the same types. This leads to some
826 // variables using one type and some using the other.
827 if (TypeMap.DstStructTypesSet.count(DST))
828 TypeMap.addTypeMapping(DST, ST);
831 // Now that we have discovered all of the type equivalences, get a body for
832 // any 'opaque' types in the dest module that are now resolved.
833 TypeMap.linkDefinedTypeBodies();
836 static void upgradeGlobalArray(GlobalVariable *GV) {
837 ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
838 StructType *OldTy = cast<StructType>(ATy->getElementType());
839 assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
841 // Get the upgraded 3 element type.
842 PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
843 Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
845 StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
847 // Build new constants with a null third field filled in.
848 Constant *OldInitC = GV->getInitializer();
849 ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
850 if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
851 // Invalid initializer; give up.
853 std::vector<Constant *> Initializers;
854 if (OldInit && OldInit->getNumOperands()) {
855 Value *Null = Constant::getNullValue(VoidPtrTy);
856 for (Use &U : OldInit->operands()) {
857 ConstantStruct *Init = cast<ConstantStruct>(U.get());
858 Initializers.push_back(ConstantStruct::get(
859 NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
862 assert(Initializers.size() == ATy->getNumElements() &&
863 "Failed to copy all array elements");
865 // Replace the old GV with a new one.
866 ATy = ArrayType::get(NewTy, Initializers.size());
867 Constant *NewInit = ConstantArray::get(ATy, Initializers);
868 GlobalVariable *NewGV = new GlobalVariable(
869 *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
870 GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
871 GV->isExternallyInitialized());
872 NewGV->copyAttributesFrom(GV);
874 assert(GV->use_empty() && "program cannot use initializer list");
875 GV->eraseFromParent();
878 void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
879 // Look for the global arrays.
880 auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
883 auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
887 // Check if the types already match.
888 auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
890 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
894 // Grab the element types. We can only upgrade an array of a two-field
895 // struct. Only bother if the other one has three-fields.
896 auto *DstEltTy = cast<StructType>(DstTy->getElementType());
897 auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
898 if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
899 upgradeGlobalArray(DstGV);
902 if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
903 upgradeGlobalArray(SrcGV);
905 // We can't upgrade any other differences.
908 void ModuleLinker::upgradeMismatchedGlobals() {
909 upgradeMismatchedGlobalArray("llvm.global_ctors");
910 upgradeMismatchedGlobalArray("llvm.global_dtors");
913 /// If there were any appending global variables, link them together now.
914 /// Return true on error.
915 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
916 const GlobalVariable *SrcGV) {
918 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
919 return emitError("Linking globals named '" + SrcGV->getName() +
920 "': can only link appending global with another appending global!");
922 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
924 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
925 Type *EltTy = DstTy->getElementType();
927 // Check to see that they two arrays agree on type.
928 if (EltTy != SrcTy->getElementType())
929 return emitError("Appending variables with different element types!");
930 if (DstGV->isConstant() != SrcGV->isConstant())
931 return emitError("Appending variables linked with different const'ness!");
933 if (DstGV->getAlignment() != SrcGV->getAlignment())
935 "Appending variables with different alignment need to be linked!");
937 if (DstGV->getVisibility() != SrcGV->getVisibility())
939 "Appending variables with different visibility need to be linked!");
941 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
943 "Appending variables with different unnamed_addr need to be linked!");
945 if (StringRef(DstGV->getSection()) != SrcGV->getSection())
947 "Appending variables with different section name need to be linked!");
949 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
950 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
952 // Create the new global variable.
954 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
955 DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
956 DstGV->getThreadLocalMode(),
957 DstGV->getType()->getAddressSpace());
959 // Propagate alignment, visibility and section info.
960 copyGVAttributes(NG, DstGV);
962 AppendingVarInfo AVI;
964 AVI.DstInit = DstGV->getInitializer();
965 AVI.SrcInit = SrcGV->getInitializer();
966 AppendingVars.push_back(AVI);
968 // Replace any uses of the two global variables with uses of the new
970 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
972 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
973 DstGV->eraseFromParent();
975 // Track the source variable so we don't try to link it.
976 DoNotLinkFromSource.insert(SrcGV);
981 bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
982 GlobalValue *DGV = getLinkedToGlobal(SGV);
984 // Handle the ultra special appending linkage case first.
985 if (DGV && DGV->hasAppendingLinkage())
986 return linkAppendingVarProto(cast<GlobalVariable>(DGV),
987 cast<GlobalVariable>(SGV));
989 bool LinkFromSrc = true;
991 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
992 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
994 if (const Comdat *SC = SGV->getComdat()) {
995 Comdat::SelectionKind SK;
996 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
997 C = DstM->getOrInsertComdat(SC->getName());
998 C->setSelectionKind(SK);
1000 if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1005 // Track the source global so that we don't attempt to copy it over when
1006 // processing global initializers.
1007 DoNotLinkFromSource.insert(SGV);
1010 // Make sure to remember this mapping.
1012 ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
1016 Visibility = isLessConstraining(Visibility, DGV->getVisibility())
1017 ? DGV->getVisibility()
1019 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1022 if (!LinkFromSrc && !DGV)
1026 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
1027 NewGV = linkGlobalVariableProto(SGVar, DGV, LinkFromSrc);
1030 } else if (auto *SF = dyn_cast<Function>(SGV)) {
1031 NewGV = linkFunctionProto(SF, DGV, LinkFromSrc);
1033 NewGV = linkGlobalAliasProto(cast<GlobalAlias>(SGV), DGV, LinkFromSrc);
1038 copyGVAttributes(NewGV, SGV);
1040 NewGV->setUnnamedAddr(HasUnnamedAddr);
1041 NewGV->setVisibility(Visibility);
1043 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1045 NewGO->setComdat(C);
1048 // Make sure to remember this mapping.
1051 DGV->replaceAllUsesWith(
1052 ConstantExpr::getBitCast(NewGV, DGV->getType()));
1053 DGV->eraseFromParent();
1055 ValueMap[SGV] = NewGV;
1062 /// Loop through the global variables in the src module and merge them into the
1064 GlobalValue *ModuleLinker::linkGlobalVariableProto(const GlobalVariable *SGVar,
1067 unsigned Alignment = 0;
1068 bool ClearConstant = false;
1071 if (DGV->hasCommonLinkage() && SGVar->hasCommonLinkage())
1072 Alignment = std::max(SGVar->getAlignment(), DGV->getAlignment());
1074 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
1075 if (!SGVar->isConstant() || (DGVar && !DGVar->isConstant()))
1076 ClearConstant = true;
1080 if (auto *NewGVar = dyn_cast<GlobalVariable>(DGV)) {
1082 NewGVar->setAlignment(Alignment);
1083 if (NewGVar->isDeclaration() && ClearConstant)
1084 NewGVar->setConstant(false);
1089 // No linking to be performed or linking from the source: simply create an
1090 // identical version of the symbol over in the dest module... the
1091 // initializer will be filled in later by LinkGlobalInits.
1092 GlobalVariable *NewDGV = new GlobalVariable(
1093 *DstM, TypeMap.get(SGVar->getType()->getElementType()),
1094 SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr,
1095 SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
1096 SGVar->getType()->getAddressSpace());
1099 NewDGV->setAlignment(Alignment);
1104 /// Link the function in the source module into the destination module if
1105 /// needed, setting up mapping information.
1106 GlobalValue *ModuleLinker::linkFunctionProto(const Function *SF,
1112 // If the function is to be lazily linked, don't create it just yet.
1113 // The ValueMaterializerTy will deal with creating it if it's used.
1114 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1115 SF->hasAvailableExternallyLinkage())) {
1116 DoNotLinkFromSource.insert(SF);
1120 // If there is no linkage to be performed or we are linking from the source,
1122 return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(),
1123 SF->getName(), DstM);
1126 /// Set up prototypes for any aliases that come over from the source module.
1127 GlobalValue *ModuleLinker::linkGlobalAliasProto(const GlobalAlias *SGA,
1133 // If there is no linkage to be performed or we're linking from the source,
1135 auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
1136 return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1137 SGA->getLinkage(), SGA->getName(), DstM);
1140 static void getArrayElements(const Constant *C,
1141 SmallVectorImpl<Constant *> &Dest) {
1142 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1144 for (unsigned i = 0; i != NumElements; ++i)
1145 Dest.push_back(C->getAggregateElement(i));
1148 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1149 // Merge the initializer.
1150 SmallVector<Constant *, 16> DstElements;
1151 getArrayElements(AVI.DstInit, DstElements);
1153 SmallVector<Constant *, 16> SrcElements;
1154 getArrayElements(AVI.SrcInit, SrcElements);
1156 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1158 StringRef Name = AVI.NewGV->getName();
1159 bool IsNewStructor =
1160 (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1161 cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1163 for (auto *V : SrcElements) {
1164 if (IsNewStructor) {
1165 Constant *Key = V->getAggregateElement(2);
1166 if (DoNotLinkFromSource.count(Key))
1169 DstElements.push_back(
1170 MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1172 if (IsNewStructor) {
1173 NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1174 AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1177 AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1180 /// Update the initializers in the Dest module now that all globals that may be
1181 /// referenced are in Dest.
1182 void ModuleLinker::linkGlobalInits() {
1183 // Loop over all of the globals in the src module, mapping them over as we go
1184 for (Module::const_global_iterator I = SrcM->global_begin(),
1185 E = SrcM->global_end(); I != E; ++I) {
1187 // Only process initialized GV's or ones not already in dest.
1188 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1190 // Grab destination global variable.
1191 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1192 // Figure out what the initializer looks like in the dest module.
1193 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
1194 RF_None, &TypeMap, &ValMaterializer));
1198 /// Copy the source function over into the dest function and fix up references
1199 /// to values. At this point we know that Dest is an external function, and
1200 /// that Src is not.
1201 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1202 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
1204 // Go through and convert function arguments over, remembering the mapping.
1205 Function::arg_iterator DI = Dst->arg_begin();
1206 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1207 I != E; ++I, ++DI) {
1208 DI->setName(I->getName()); // Copy the name over.
1210 // Add a mapping to our mapping.
1214 // Splice the body of the source function into the dest function.
1215 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
1217 // At this point, all of the instructions and values of the function are now
1218 // copied over. The only problem is that they are still referencing values in
1219 // the Source function as operands. Loop through all of the operands of the
1220 // functions and patch them up to point to the local versions.
1221 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1222 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1223 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap,
1226 // There is no need to map the arguments anymore.
1227 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1233 /// Insert all of the aliases in Src into the Dest module.
1234 void ModuleLinker::linkAliasBodies() {
1235 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
1237 if (DoNotLinkFromSource.count(I))
1239 if (Constant *Aliasee = I->getAliasee()) {
1240 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
1242 MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1243 DA->setAliasee(Val);
1248 /// Insert all of the named MDNodes in Src into the Dest module.
1249 void ModuleLinker::linkNamedMDNodes() {
1250 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1251 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1252 E = SrcM->named_metadata_end(); I != E; ++I) {
1253 // Don't link module flags here. Do them separately.
1254 if (&*I == SrcModFlags) continue;
1255 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1256 // Add Src elements into Dest node.
1257 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1258 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
1259 RF_None, &TypeMap, &ValMaterializer));
1263 /// Merge the linker flags in Src into the Dest module.
1264 bool ModuleLinker::linkModuleFlagsMetadata() {
1265 // If the source module has no module flags, we are done.
1266 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1267 if (!SrcModFlags) return false;
1269 // If the destination module doesn't have module flags yet, then just copy
1270 // over the source module's flags.
1271 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1272 if (DstModFlags->getNumOperands() == 0) {
1273 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1274 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1279 // First build a map of the existing module flags and requirements.
1280 DenseMap<MDString*, MDNode*> Flags;
1281 SmallSetVector<MDNode*, 16> Requirements;
1282 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1283 MDNode *Op = DstModFlags->getOperand(I);
1284 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1285 MDString *ID = cast<MDString>(Op->getOperand(1));
1287 if (Behavior->getZExtValue() == Module::Require) {
1288 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1294 // Merge in the flags from the source module, and also collect its set of
1296 bool HasErr = false;
1297 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1298 MDNode *SrcOp = SrcModFlags->getOperand(I);
1299 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1300 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1301 MDNode *DstOp = Flags.lookup(ID);
1302 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1304 // If this is a requirement, add it and continue.
1305 if (SrcBehaviorValue == Module::Require) {
1306 // If the destination module does not already have this requirement, add
1308 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1309 DstModFlags->addOperand(SrcOp);
1314 // If there is no existing flag with this ID, just add it.
1317 DstModFlags->addOperand(SrcOp);
1321 // Otherwise, perform a merge.
1322 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1323 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1325 // If either flag has override behavior, handle it first.
1326 if (DstBehaviorValue == Module::Override) {
1327 // Diagnose inconsistent flags which both have override behavior.
1328 if (SrcBehaviorValue == Module::Override &&
1329 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1330 HasErr |= emitError("linking module flags '" + ID->getString() +
1331 "': IDs have conflicting override values");
1334 } else if (SrcBehaviorValue == Module::Override) {
1335 // Update the destination flag to that of the source.
1336 DstOp->replaceOperandWith(0, SrcBehavior);
1337 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1341 // Diagnose inconsistent merge behavior types.
1342 if (SrcBehaviorValue != DstBehaviorValue) {
1343 HasErr |= emitError("linking module flags '" + ID->getString() +
1344 "': IDs have conflicting behaviors");
1348 // Perform the merge for standard behavior types.
1349 switch (SrcBehaviorValue) {
1350 case Module::Require:
1351 case Module::Override: llvm_unreachable("not possible");
1352 case Module::Error: {
1353 // Emit an error if the values differ.
1354 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1355 HasErr |= emitError("linking module flags '" + ID->getString() +
1356 "': IDs have conflicting values");
1360 case Module::Warning: {
1361 // Emit a warning if the values differ.
1362 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1363 emitWarning("linking module flags '" + ID->getString() +
1364 "': IDs have conflicting values");
1368 case Module::Append: {
1369 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1370 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1371 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1372 Value **VP, **Values = VP = new Value*[NumOps];
1373 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1374 *VP = DstValue->getOperand(i);
1375 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1376 *VP = SrcValue->getOperand(i);
1377 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1378 ArrayRef<Value*>(Values,
1383 case Module::AppendUnique: {
1384 SmallSetVector<Value*, 16> Elts;
1385 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1386 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1387 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1388 Elts.insert(DstValue->getOperand(i));
1389 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1390 Elts.insert(SrcValue->getOperand(i));
1391 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1392 ArrayRef<Value*>(Elts.begin(),
1399 // Check all of the requirements.
1400 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1401 MDNode *Requirement = Requirements[I];
1402 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1403 Value *ReqValue = Requirement->getOperand(1);
1405 MDNode *Op = Flags[Flag];
1406 if (!Op || Op->getOperand(2) != ReqValue) {
1407 HasErr |= emitError("linking module flags '" + Flag->getString() +
1408 "': does not have the required value");
1416 bool ModuleLinker::run() {
1417 assert(DstM && "Null destination module");
1418 assert(SrcM && "Null source module");
1420 // Inherit the target data from the source module if the destination module
1421 // doesn't have one already.
1422 if (!DstM->getDataLayout() && SrcM->getDataLayout())
1423 DstM->setDataLayout(SrcM->getDataLayout());
1425 // Copy the target triple from the source to dest if the dest's is empty.
1426 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1427 DstM->setTargetTriple(SrcM->getTargetTriple());
1429 if (SrcM->getDataLayout() && DstM->getDataLayout() &&
1430 *SrcM->getDataLayout() != *DstM->getDataLayout()) {
1431 emitWarning("Linking two modules of different data layouts: '" +
1432 SrcM->getModuleIdentifier() + "' is '" +
1433 SrcM->getDataLayoutStr() + "' whereas '" +
1434 DstM->getModuleIdentifier() + "' is '" +
1435 DstM->getDataLayoutStr() + "'\n");
1437 if (!SrcM->getTargetTriple().empty() &&
1438 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1439 emitWarning("Linking two modules of different target triples: " +
1440 SrcM->getModuleIdentifier() + "' is '" +
1441 SrcM->getTargetTriple() + "' whereas '" +
1442 DstM->getModuleIdentifier() + "' is '" +
1443 DstM->getTargetTriple() + "'\n");
1446 // Append the module inline asm string.
1447 if (!SrcM->getModuleInlineAsm().empty()) {
1448 if (DstM->getModuleInlineAsm().empty())
1449 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1451 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1452 SrcM->getModuleInlineAsm());
1455 // Loop over all of the linked values to compute type mappings.
1456 computeTypeMapping();
1458 ComdatsChosen.clear();
1459 for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
1460 const Comdat &C = SMEC.getValue();
1461 if (ComdatsChosen.count(&C))
1463 Comdat::SelectionKind SK;
1465 if (getComdatResult(&C, SK, LinkFromSrc))
1467 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1470 // Upgrade mismatched global arrays.
1471 upgradeMismatchedGlobals();
1473 // Insert all of the globals in src into the DstM module... without linking
1474 // initializers (which could refer to functions not yet mapped over).
1475 for (Module::global_iterator I = SrcM->global_begin(),
1476 E = SrcM->global_end(); I != E; ++I)
1477 if (linkGlobalValueProto(I))
1480 // Link the functions together between the two modules, without doing function
1481 // bodies... this just adds external function prototypes to the DstM
1482 // function... We do this so that when we begin processing function bodies,
1483 // all of the global values that may be referenced are available in our
1485 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1486 if (linkGlobalValueProto(I))
1489 // If there were any aliases, link them now.
1490 for (Module::alias_iterator I = SrcM->alias_begin(),
1491 E = SrcM->alias_end(); I != E; ++I)
1492 if (linkGlobalValueProto(I))
1495 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1496 linkAppendingVarInit(AppendingVars[i]);
1498 // Link in the function bodies that are defined in the source module into
1500 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1501 // Skip if not linking from source.
1502 if (DoNotLinkFromSource.count(SF)) continue;
1504 Function *DF = cast<Function>(ValueMap[SF]);
1505 if (SF->hasPrefixData()) {
1506 // Link in the prefix data.
1507 DF->setPrefixData(MapValue(
1508 SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1511 // Materialize if needed.
1512 if (std::error_code EC = SF->materialize())
1513 return emitError(EC.message());
1515 // Skip if no body (function is external).
1516 if (SF->isDeclaration())
1519 linkFunctionBody(DF, SF);
1520 SF->Dematerialize();
1523 // Resolve all uses of aliases with aliasees.
1526 // Remap all of the named MDNodes in Src into the DstM module. We do this
1527 // after linking GlobalValues so that MDNodes that reference GlobalValues
1528 // are properly remapped.
1531 // Merge the module flags into the DstM module.
1532 if (linkModuleFlagsMetadata())
1535 // Update the initializers in the DstM module now that all globals that may
1536 // be referenced are in DstM.
1539 // Process vector of lazily linked in functions.
1540 bool LinkedInAnyFunctions;
1542 LinkedInAnyFunctions = false;
1544 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1545 E = LazilyLinkFunctions.end(); I != E; ++I) {
1550 Function *DF = cast<Function>(ValueMap[SF]);
1551 if (SF->hasPrefixData()) {
1552 // Link in the prefix data.
1553 DF->setPrefixData(MapValue(SF->getPrefixData(),
1560 // Materialize if needed.
1561 if (std::error_code EC = SF->materialize())
1562 return emitError(EC.message());
1564 // Skip if no body (function is external).
1565 if (SF->isDeclaration())
1568 // Erase from vector *before* the function body is linked - linkFunctionBody could
1570 LazilyLinkFunctions.erase(I);
1572 // Link in function body.
1573 linkFunctionBody(DF, SF);
1574 SF->Dematerialize();
1576 // Set flag to indicate we may have more functions to lazily link in
1577 // since we linked in a function.
1578 LinkedInAnyFunctions = true;
1581 } while (LinkedInAnyFunctions);
1586 void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1587 this->Composite = M;
1588 this->DiagnosticHandler = DiagnosticHandler;
1590 TypeFinder StructTypes;
1591 StructTypes.run(*M, true);
1592 IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1595 Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1596 init(M, DiagnosticHandler);
1599 Linker::Linker(Module *M) {
1600 init(M, [this](const DiagnosticInfo &DI) {
1601 Composite->getContext().diagnose(DI);
1608 void Linker::deleteModule() {
1610 Composite = nullptr;
1613 bool Linker::linkInModule(Module *Src) {
1614 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
1616 return TheLinker.run();
1619 //===----------------------------------------------------------------------===//
1620 // LinkModules entrypoint.
1621 //===----------------------------------------------------------------------===//
1623 /// This function links two modules together, with the resulting Dest module
1624 /// modified to be the composite of the two input modules. If an error occurs,
1625 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
1626 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
1627 /// relied on to be consistent.
1628 bool Linker::LinkModules(Module *Dest, Module *Src,
1629 DiagnosticHandlerFunction DiagnosticHandler) {
1630 Linker L(Dest, DiagnosticHandler);
1631 return L.linkInModule(Src);
1634 bool Linker::LinkModules(Module *Dest, Module *Src) {
1636 return L.linkInModule(Src);
1639 //===----------------------------------------------------------------------===//
1641 //===----------------------------------------------------------------------===//
1643 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1644 LLVMLinkerMode Mode, char **OutMessages) {
1645 Module *D = unwrap(Dest);
1646 std::string Message;
1647 raw_string_ostream Stream(Message);
1648 DiagnosticPrinterRawOStream DP(Stream);
1650 LLVMBool Result = Linker::LinkModules(
1651 D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
1653 if (OutMessages && Result)
1654 *OutMessages = strdup(Message.c_str());