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/Hashing.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DebugInfo.h"
24 #include "llvm/IR/DiagnosticInfo.h"
25 #include "llvm/IR/DiagnosticPrinter.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/TypeFinder.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Transforms/Utils/Cloning.h"
38 //===----------------------------------------------------------------------===//
39 // TypeMap implementation.
40 //===----------------------------------------------------------------------===//
43 class TypeMapTy : public ValueMapTypeRemapper {
44 /// This is a mapping from a source type to a destination type to use.
45 DenseMap<Type*, Type*> MappedTypes;
47 /// When checking to see if two subgraphs are isomorphic, we speculatively
48 /// add types to MappedTypes, but keep track of them here in case we need to
50 SmallVector<Type*, 16> SpeculativeTypes;
52 SmallVector<StructType*, 16> SpeculativeDstOpaqueTypes;
54 /// This is a list of non-opaque structs in the source module that are mapped
55 /// to an opaque struct in the destination module.
56 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
58 /// This is the set of opaque types in the destination modules who are
59 /// getting a body from the source module.
60 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
63 TypeMapTy(Linker::IdentifiedStructTypeSet &DstStructTypesSet)
64 : DstStructTypesSet(DstStructTypesSet) {}
66 Linker::IdentifiedStructTypeSet &DstStructTypesSet;
67 /// Indicate that the specified type in the destination module is conceptually
68 /// equivalent to the specified type in the source module.
69 void addTypeMapping(Type *DstTy, Type *SrcTy);
71 /// Produce a body for an opaque type in the dest module from a type
72 /// definition in the source module.
73 void linkDefinedTypeBodies();
75 /// Return the mapped type to use for the specified input type from the
77 Type *get(Type *SrcTy);
78 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
80 void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
82 FunctionType *get(FunctionType *T) {
83 return cast<FunctionType>(get((Type *)T));
86 /// Dump out the type map for debugging purposes.
88 for (auto &Pair : MappedTypes) {
89 dbgs() << "TypeMap: ";
90 Pair.first->print(dbgs());
92 Pair.second->print(dbgs());
98 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
100 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
104 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
105 assert(SpeculativeTypes.empty());
106 assert(SpeculativeDstOpaqueTypes.empty());
108 // Check to see if these types are recursively isomorphic and establish a
109 // mapping between them if so.
110 if (!areTypesIsomorphic(DstTy, SrcTy)) {
111 // Oops, they aren't isomorphic. Just discard this request by rolling out
112 // any speculative mappings we've established.
113 for (Type *Ty : SpeculativeTypes)
114 MappedTypes.erase(Ty);
116 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
117 SpeculativeDstOpaqueTypes.size());
118 for (StructType *Ty : SpeculativeDstOpaqueTypes)
119 DstResolvedOpaqueTypes.erase(Ty);
121 for (Type *Ty : SpeculativeTypes)
122 if (auto *STy = dyn_cast<StructType>(Ty))
126 SpeculativeTypes.clear();
127 SpeculativeDstOpaqueTypes.clear();
130 /// Recursively walk this pair of types, returning true if they are isomorphic,
131 /// false if they are not.
132 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
133 // Two types with differing kinds are clearly not isomorphic.
134 if (DstTy->getTypeID() != SrcTy->getTypeID())
137 // If we have an entry in the MappedTypes table, then we have our answer.
138 Type *&Entry = MappedTypes[SrcTy];
140 return Entry == DstTy;
142 // Two identical types are clearly isomorphic. Remember this
143 // non-speculatively.
144 if (DstTy == SrcTy) {
149 // Okay, we have two types with identical kinds that we haven't seen before.
151 // If this is an opaque struct type, special case it.
152 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
153 // Mapping an opaque type to any struct, just keep the dest struct.
154 if (SSTy->isOpaque()) {
156 SpeculativeTypes.push_back(SrcTy);
160 // Mapping a non-opaque source type to an opaque dest. If this is the first
161 // type that we're mapping onto this destination type then we succeed. Keep
162 // the dest, but fill it in later. If this is the second (different) type
163 // that we're trying to map onto the same opaque type then we fail.
164 if (cast<StructType>(DstTy)->isOpaque()) {
165 // We can only map one source type onto the opaque destination type.
166 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
168 SrcDefinitionsToResolve.push_back(SSTy);
169 SpeculativeTypes.push_back(SrcTy);
170 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
176 // If the number of subtypes disagree between the two types, then we fail.
177 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
180 // Fail if any of the extra properties (e.g. array size) of the type disagree.
181 if (isa<IntegerType>(DstTy))
182 return false; // bitwidth disagrees.
183 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
184 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
187 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
188 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
190 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
191 StructType *SSTy = cast<StructType>(SrcTy);
192 if (DSTy->isLiteral() != SSTy->isLiteral() ||
193 DSTy->isPacked() != SSTy->isPacked())
195 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
196 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
198 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
199 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
203 // Otherwise, we speculate that these two types will line up and recursively
204 // check the subelements.
206 SpeculativeTypes.push_back(SrcTy);
208 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
209 if (!areTypesIsomorphic(DstTy->getContainedType(I),
210 SrcTy->getContainedType(I)))
213 // If everything seems to have lined up, then everything is great.
217 void TypeMapTy::linkDefinedTypeBodies() {
218 SmallVector<Type*, 16> Elements;
219 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
220 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
221 assert(DstSTy->isOpaque());
223 // Map the body of the source type over to a new body for the dest type.
224 Elements.resize(SrcSTy->getNumElements());
225 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
226 Elements[I] = get(SrcSTy->getElementType(I));
228 DstSTy->setBody(Elements, SrcSTy->isPacked());
229 DstStructTypesSet.switchToNonOpaque(DstSTy);
231 SrcDefinitionsToResolve.clear();
232 DstResolvedOpaqueTypes.clear();
235 void TypeMapTy::finishType(StructType *DTy, StructType *STy,
236 ArrayRef<Type *> ETypes) {
237 DTy->setBody(ETypes, STy->isPacked());
240 if (STy->hasName()) {
241 SmallString<16> TmpName = STy->getName();
243 DTy->setName(TmpName);
246 DstStructTypesSet.addNonOpaque(DTy);
249 Type *TypeMapTy::get(Type *Ty) {
250 SmallPtrSet<StructType *, 8> Visited;
251 return get(Ty, Visited);
254 Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
255 // If we already have an entry for this type, return it.
256 Type **Entry = &MappedTypes[Ty];
260 // These are types that LLVM itself will unique.
261 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
265 for (auto &Pair : MappedTypes) {
266 assert(!(Pair.first != Ty && Pair.second == Ty) &&
267 "mapping to a source type");
272 if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
273 StructType *DTy = StructType::create(Ty->getContext());
277 // If this is not a recursive type, then just map all of the elements and
278 // then rebuild the type from inside out.
279 SmallVector<Type *, 4> ElementTypes;
281 // If there are no element types to map, then the type is itself. This is
282 // true for the anonymous {} struct, things like 'float', integers, etc.
283 if (Ty->getNumContainedTypes() == 0 && IsUniqued)
286 // Remap all of the elements, keeping track of whether any of them change.
287 bool AnyChange = false;
288 ElementTypes.resize(Ty->getNumContainedTypes());
289 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
290 ElementTypes[I] = get(Ty->getContainedType(I), Visited);
291 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
294 // If we found our type while recursively processing stuff, just use it.
295 Entry = &MappedTypes[Ty];
297 if (auto *DTy = dyn_cast<StructType>(*Entry)) {
298 if (DTy->isOpaque()) {
299 auto *STy = cast<StructType>(Ty);
300 finishType(DTy, STy, ElementTypes);
306 // If all of the element types mapped directly over and the type is not
307 // a nomed struct, then the type is usable as-is.
308 if (!AnyChange && IsUniqued)
311 // Otherwise, rebuild a modified type.
312 switch (Ty->getTypeID()) {
314 llvm_unreachable("unknown derived type to remap");
315 case Type::ArrayTyID:
316 return *Entry = ArrayType::get(ElementTypes[0],
317 cast<ArrayType>(Ty)->getNumElements());
318 case Type::VectorTyID:
319 return *Entry = VectorType::get(ElementTypes[0],
320 cast<VectorType>(Ty)->getNumElements());
321 case Type::PointerTyID:
322 return *Entry = PointerType::get(ElementTypes[0],
323 cast<PointerType>(Ty)->getAddressSpace());
324 case Type::FunctionTyID:
325 return *Entry = FunctionType::get(ElementTypes[0],
326 makeArrayRef(ElementTypes).slice(1),
327 cast<FunctionType>(Ty)->isVarArg());
328 case Type::StructTyID: {
329 auto *STy = cast<StructType>(Ty);
330 bool IsPacked = STy->isPacked();
332 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
334 // If the type is opaque, we can just use it directly.
335 if (STy->isOpaque()) {
336 DstStructTypesSet.addOpaque(STy);
340 if (StructType *OldT =
341 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
343 return *Entry = OldT;
347 DstStructTypesSet.addNonOpaque(STy);
351 StructType *DTy = StructType::create(Ty->getContext());
352 finishType(DTy, STy, ElementTypes);
358 //===----------------------------------------------------------------------===//
359 // ModuleLinker implementation.
360 //===----------------------------------------------------------------------===//
365 /// Creates prototypes for functions that are lazily linked on the fly. This
366 /// speeds up linking for modules with many/ lazily linked functions of which
368 class ValueMaterializerTy final : public ValueMaterializer {
371 std::vector<GlobalValue *> &LazilyLinkGlobalValues;
372 ModuleLinker *ModLinker;
375 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
376 std::vector<GlobalValue *> &LazilyLinkGlobalValues,
377 ModuleLinker *ModLinker)
378 : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
379 LazilyLinkGlobalValues(LazilyLinkGlobalValues), ModLinker(ModLinker) {}
381 Value *materializeValueFor(Value *V) override;
384 class LinkDiagnosticInfo : public DiagnosticInfo {
388 LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
389 void print(DiagnosticPrinter &DP) const override;
391 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
393 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
394 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
396 /// This is an implementation class for the LinkModules function, which is the
397 /// entrypoint for this file.
402 ValueMaterializerTy ValMaterializer;
404 /// Mapping of values from what they used to be in Src, to what they are now
405 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
406 /// due to the use of Value handles which the Linker doesn't actually need,
407 /// but this allows us to reuse the ValueMapper code.
408 ValueToValueMapTy ValueMap;
410 struct AppendingVarInfo {
411 GlobalVariable *NewGV; // New aggregate global in dest module.
412 const Constant *DstInit; // Old initializer from dest module.
413 const Constant *SrcInit; // Old initializer from src module.
416 std::vector<AppendingVarInfo> AppendingVars;
418 // Set of items not to link in from source.
419 SmallPtrSet<const Value *, 16> DoNotLinkFromSource;
421 // Vector of GlobalValues to lazily link in.
422 std::vector<GlobalValue *> LazilyLinkGlobalValues;
424 DiagnosticHandlerFunction DiagnosticHandler;
426 /// For symbol clashes, prefer those from Src.
429 /// Function index passed into ModuleLinker for using in function
430 /// importing/exporting handling.
431 FunctionInfoIndex *ImportIndex;
433 /// Function to import from source module, all other functions are
434 /// imported as declarations instead of definitions.
435 Function *ImportFunction;
437 /// Set to true if the given FunctionInfoIndex contains any functions
438 /// from this source module, in which case we must conservatively assume
439 /// that any of its functions may be imported into another module
440 /// as part of a different backend compilation process.
441 bool HasExportedFunctions;
444 ModuleLinker(Module *dstM, Linker::IdentifiedStructTypeSet &Set, Module *srcM,
445 DiagnosticHandlerFunction DiagnosticHandler, unsigned Flags,
446 FunctionInfoIndex *Index = nullptr,
447 Function *FuncToImport = nullptr)
448 : DstM(dstM), SrcM(srcM), TypeMap(Set),
449 ValMaterializer(TypeMap, DstM, LazilyLinkGlobalValues, this),
450 DiagnosticHandler(DiagnosticHandler), Flags(Flags), ImportIndex(Index),
451 ImportFunction(FuncToImport), HasExportedFunctions(false) {
452 assert((ImportIndex || !ImportFunction) &&
453 "Expect a FunctionInfoIndex when importing");
454 // If we have a FunctionInfoIndex but no function to import,
455 // then this is the primary module being compiled in a ThinLTO
456 // backend compilation, and we need to see if it has functions that
457 // may be exported to another backend compilation.
458 if (ImportIndex && !ImportFunction)
459 HasExportedFunctions = ImportIndex->hasExportedFunctions(SrcM);
464 bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
465 bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
466 bool shouldInternalizeLinkedSymbols() {
467 return Flags & Linker::InternalizeLinkedSymbols;
470 /// Handles cloning of a global values from the source module into
471 /// the destination module, including setting the attributes and visibility.
472 GlobalValue *copyGlobalValueProto(TypeMapTy &TypeMap, const GlobalValue *SGV,
473 const GlobalValue *DGV = nullptr);
475 /// Check if we should promote the given local value to global scope.
476 bool doPromoteLocalToGlobal(const GlobalValue *SGV);
479 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
480 const GlobalValue &Src);
482 /// Helper method for setting a message and returning an error code.
483 bool emitError(const Twine &Message) {
484 DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
488 void emitWarning(const Twine &Message) {
489 DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
492 bool getComdatLeader(Module *M, StringRef ComdatName,
493 const GlobalVariable *&GVar);
494 bool computeResultingSelectionKind(StringRef ComdatName,
495 Comdat::SelectionKind Src,
496 Comdat::SelectionKind Dst,
497 Comdat::SelectionKind &Result,
499 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
501 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
504 /// Given a global in the source module, return the global in the
505 /// destination module that is being linked to, if any.
506 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
507 // If the source has no name it can't link. If it has local linkage,
508 // there is no name match-up going on.
509 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
512 // Otherwise see if we have a match in the destination module's symtab.
513 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
517 // If we found a global with the same name in the dest module, but it has
518 // internal linkage, we are really not doing any linkage here.
519 if (DGV->hasLocalLinkage())
522 // Otherwise, we do in fact link to the destination global.
526 void computeTypeMapping();
528 void upgradeMismatchedGlobalArray(StringRef Name);
529 void upgradeMismatchedGlobals();
531 bool linkAppendingVarProto(GlobalVariable *DstGV,
532 const GlobalVariable *SrcGV);
534 bool linkGlobalValueProto(GlobalValue *GV);
535 bool linkModuleFlagsMetadata();
537 void linkAppendingVarInit(const AppendingVarInfo &AVI);
539 void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
540 bool linkFunctionBody(Function &Dst, Function &Src);
541 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
542 bool linkGlobalValueBody(GlobalValue &Src);
544 /// Functions that take care of cloning a specific global value type
545 /// into the destination module.
546 GlobalVariable *copyGlobalVariableProto(TypeMapTy &TypeMap,
547 const GlobalVariable *SGVar);
548 Function *copyFunctionProto(TypeMapTy &TypeMap, const Function *SF);
549 GlobalValue *copyGlobalAliasProto(TypeMapTy &TypeMap, const GlobalAlias *SGA);
551 /// Helper methods to check if we are importing from or potentially
552 /// exporting from the current source module.
553 bool isPerformingImport() { return ImportFunction != nullptr; }
554 bool isModuleExporting() { return HasExportedFunctions; }
556 /// If we are importing from the source module, checks if we should
557 /// import SGV as a definition, otherwise import as a declaration.
558 bool doImportAsDefinition(const GlobalValue *SGV);
560 /// Get the name for SGV that should be used in the linked destination
561 /// module. Specifically, this handles the case where we need to rename
562 /// a local that is being promoted to global scope.
563 std::string getName(const GlobalValue *SGV);
565 /// Get the new linkage for SGV that should be used in the linked destination
566 /// module. Specifically, for ThinLTO importing or exporting it may need
568 GlobalValue::LinkageTypes getLinkage(const GlobalValue *SGV);
570 /// Copies the necessary global value attributes and name from the source
571 /// to the newly cloned global value.
572 void copyGVAttributes(GlobalValue *NewGV, const GlobalValue *SrcGV);
574 /// Updates the visibility for the new global cloned from the source
575 /// and, if applicable, linked with an existing destination global.
576 /// Handles visibility change required for promoted locals.
577 void setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
578 const GlobalValue *DGV = nullptr);
580 void linkNamedMDNodes();
584 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
585 /// table. This is good for all clients except for us. Go through the trouble
586 /// to force this back.
587 static void forceRenaming(GlobalValue *GV, StringRef Name) {
588 // If the global doesn't force its name or if it already has the right name,
589 // there is nothing for us to do.
590 // Note that any required local to global promotion should already be done,
591 // so promoted locals will not skip this handling as their linkage is no
593 if (GV->hasLocalLinkage() || GV->getName() == Name)
596 Module *M = GV->getParent();
598 // If there is a conflict, rename the conflict.
599 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
600 GV->takeName(ConflictGV);
601 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
602 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
604 GV->setName(Name); // Force the name back
608 /// copy additional attributes (those not needed to construct a GlobalValue)
609 /// from the SrcGV to the DestGV.
610 void ModuleLinker::copyGVAttributes(GlobalValue *NewGV,
611 const GlobalValue *SrcGV) {
612 auto *GA = dyn_cast<GlobalAlias>(SrcGV);
613 // Check for the special case of converting an alias (definition) to a
614 // non-alias (declaration). This can happen when we are importing and
615 // encounter a weak_any alias (weak_any defs may not be imported, see
616 // comments in ModuleLinker::getLinkage) or an alias whose base object is
617 // being imported as a declaration. In that case copy the attributes from the
619 if (GA && !dyn_cast<GlobalAlias>(NewGV)) {
620 assert(isPerformingImport() &&
621 (GA->hasWeakAnyLinkage() ||
622 !doImportAsDefinition(GA->getBaseObject())));
623 NewGV->copyAttributesFrom(GA->getBaseObject());
625 NewGV->copyAttributesFrom(SrcGV);
626 forceRenaming(NewGV, getName(SrcGV));
629 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
630 GlobalValue::VisibilityTypes b) {
631 if (a == GlobalValue::HiddenVisibility)
633 if (b == GlobalValue::HiddenVisibility)
635 if (a == GlobalValue::ProtectedVisibility)
637 if (b == GlobalValue::ProtectedVisibility)
642 bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
643 if (!isPerformingImport())
645 // Always import GlobalVariable definitions. The linkage changes
646 // described in ModuleLinker::getLinkage ensure the correct behavior (e.g.
647 // global variables with external linkage are transformed to
648 // available_externally defintions, which are ultimately turned into
649 // declaratios after the EliminateAvailableExternally pass).
650 if (dyn_cast<GlobalVariable>(SGV) && !SGV->isDeclaration())
652 // Only import the function requested for importing.
653 auto *SF = dyn_cast<Function>(SGV);
654 if (SF && SF == ImportFunction)
660 bool ModuleLinker::doPromoteLocalToGlobal(const GlobalValue *SGV) {
661 assert(SGV->hasLocalLinkage());
662 // Both the imported references and the original local variable must
664 if (!isPerformingImport() && !isModuleExporting())
667 // Local const variables never need to be promoted unless they are address
668 // taken. The imported uses can simply use the clone created in this module.
669 // For now we are conservative in determining which variables are not
670 // address taken by checking the unnamed addr flag. To be more aggressive,
671 // the address taken information must be checked earlier during parsing
672 // of the module and recorded in the function index for use when importing
674 auto *GVar = dyn_cast<GlobalVariable>(SGV);
675 if (GVar && GVar->isConstant() && GVar->hasUnnamedAddr())
678 // Eventually we only need to promote functions in the exporting module that
679 // are referenced by a potentially exported function (i.e. one that is in the
684 std::string ModuleLinker::getName(const GlobalValue *SGV) {
685 // For locals that must be promoted to global scope, ensure that
686 // the promoted name uniquely identifies the copy in the original module,
687 // using the ID assigned during combined index creation. When importing,
688 // we rename all locals (not just those that are promoted) in order to
689 // avoid naming conflicts between locals imported from different modules.
690 if (SGV->hasLocalLinkage() &&
691 (doPromoteLocalToGlobal(SGV) || isPerformingImport()))
692 return FunctionInfoIndex::getGlobalNameForLocal(
694 ImportIndex->getModuleId(SGV->getParent()->getModuleIdentifier()));
695 return SGV->getName();
698 GlobalValue::LinkageTypes ModuleLinker::getLinkage(const GlobalValue *SGV) {
699 // Any local variable that is referenced by an exported function needs
700 // to be promoted to global scope. Since we don't currently know which
701 // functions reference which local variables/functions, we must treat
702 // all as potentially exported if this module is exporting anything.
703 if (isModuleExporting()) {
704 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
705 return GlobalValue::ExternalLinkage;
706 return SGV->getLinkage();
709 // Otherwise, if we aren't importing, no linkage change is needed.
710 if (!isPerformingImport())
711 return SGV->getLinkage();
713 switch (SGV->getLinkage()) {
714 case GlobalValue::ExternalLinkage:
715 // External defnitions are converted to available_externally
716 // definitions upon import, so that they are available for inlining
717 // and/or optimization, but are turned into declarations later
718 // during the EliminateAvailableExternally pass.
719 if (doImportAsDefinition(SGV))
720 return GlobalValue::AvailableExternallyLinkage;
721 // An imported external declaration stays external.
722 return SGV->getLinkage();
724 case GlobalValue::AvailableExternallyLinkage:
725 // An imported available_externally definition converts
726 // to external if imported as a declaration.
727 if (!doImportAsDefinition(SGV))
728 return GlobalValue::ExternalLinkage;
729 // An imported available_externally declaration stays that way.
730 return SGV->getLinkage();
732 case GlobalValue::LinkOnceAnyLinkage:
733 case GlobalValue::LinkOnceODRLinkage:
734 // These both stay the same when importing the definition.
735 // The ThinLTO pass will eventually force-import their definitions.
736 return SGV->getLinkage();
738 case GlobalValue::WeakAnyLinkage:
739 // Can't import weak_any definitions correctly, or we might change the
740 // program semantics, since the linker will pick the first weak_any
741 // definition and importing would change the order they are seen by the
742 // linker. The module linking caller needs to enforce this.
743 assert(!doImportAsDefinition(SGV));
744 // If imported as a declaration, it becomes external_weak.
745 return GlobalValue::ExternalWeakLinkage;
747 case GlobalValue::WeakODRLinkage:
748 // For weak_odr linkage, there is a guarantee that all copies will be
749 // equivalent, so the issue described above for weak_any does not exist,
750 // and the definition can be imported. It can be treated similarly
751 // to an imported externally visible global value.
752 if (doImportAsDefinition(SGV))
753 return GlobalValue::AvailableExternallyLinkage;
755 return GlobalValue::ExternalLinkage;
757 case GlobalValue::AppendingLinkage:
758 // It would be incorrect to import an appending linkage variable,
759 // since it would cause global constructors/destructors to be
760 // executed multiple times. This should have already been handled
761 // by linkGlobalValueProto.
762 assert(false && "Cannot import appending linkage variable");
764 case GlobalValue::InternalLinkage:
765 case GlobalValue::PrivateLinkage:
766 // If we are promoting the local to global scope, it is handled
767 // similarly to a normal externally visible global.
768 if (doPromoteLocalToGlobal(SGV)) {
769 if (doImportAsDefinition(SGV))
770 return GlobalValue::AvailableExternallyLinkage;
772 return GlobalValue::ExternalLinkage;
774 // A non-promoted imported local definition stays local.
775 // The ThinLTO pass will eventually force-import their definitions.
776 return SGV->getLinkage();
778 case GlobalValue::ExternalWeakLinkage:
779 // External weak doesn't apply to definitions, must be a declaration.
780 assert(!doImportAsDefinition(SGV));
781 // Linkage stays external_weak.
782 return SGV->getLinkage();
784 case GlobalValue::CommonLinkage:
785 // Linkage stays common on definitions.
786 // The ThinLTO pass will eventually force-import their definitions.
787 return SGV->getLinkage();
790 llvm_unreachable("unknown linkage type");
793 /// Loop through the global variables in the src module and merge them into the
796 ModuleLinker::copyGlobalVariableProto(TypeMapTy &TypeMap,
797 const GlobalVariable *SGVar) {
798 // No linking to be performed or linking from the source: simply create an
799 // identical version of the symbol over in the dest module... the
800 // initializer will be filled in later by LinkGlobalInits.
801 GlobalVariable *NewDGV = new GlobalVariable(
802 *DstM, TypeMap.get(SGVar->getType()->getElementType()),
803 SGVar->isConstant(), getLinkage(SGVar), /*init*/ nullptr, getName(SGVar),
804 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
805 SGVar->getType()->getAddressSpace());
810 /// Link the function in the source module into the destination module if
811 /// needed, setting up mapping information.
812 Function *ModuleLinker::copyFunctionProto(TypeMapTy &TypeMap,
813 const Function *SF) {
814 // If there is no linkage to be performed or we are linking from the source,
816 return Function::Create(TypeMap.get(SF->getFunctionType()), getLinkage(SF),
820 /// Set up prototypes for any aliases that come over from the source module.
821 GlobalValue *ModuleLinker::copyGlobalAliasProto(TypeMapTy &TypeMap,
822 const GlobalAlias *SGA) {
823 // If we are importing and encounter a weak_any alias, or an alias to
824 // an object being imported as a declaration, we must import the alias
825 // as a declaration as well, which involves converting it to a non-alias.
826 // See comments in ModuleLinker::getLinkage for why we cannot import
827 // weak_any defintions.
828 if (isPerformingImport() && (SGA->hasWeakAnyLinkage() ||
829 !doImportAsDefinition(SGA->getBaseObject()))) {
830 // Need to convert to declaration. All aliases must be definitions.
831 const GlobalValue *GVal = SGA->getBaseObject();
833 if (auto *GVar = dyn_cast<GlobalVariable>(GVal))
834 NewGV = copyGlobalVariableProto(TypeMap, GVar);
836 auto *F = dyn_cast<Function>(GVal);
838 NewGV = copyFunctionProto(TypeMap, F);
840 // Set the linkage to External or ExternalWeak (see comments in
841 // ModuleLinker::getLinkage for why WeakAny is converted to ExternalWeak).
842 if (SGA->hasWeakAnyLinkage())
843 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
845 NewGV->setLinkage(GlobalValue::ExternalLinkage);
846 // Don't attempt to link body, needs to be a declaration.
847 DoNotLinkFromSource.insert(SGA);
850 // If there is no linkage to be performed or we're linking from the source,
852 auto *Ty = TypeMap.get(SGA->getValueType());
853 return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
854 getLinkage(SGA), getName(SGA), DstM);
857 void ModuleLinker::setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
858 const GlobalValue *DGV) {
859 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
861 Visibility = isLessConstraining(Visibility, DGV->getVisibility())
862 ? DGV->getVisibility()
864 // For promoted locals, mark them hidden so that they can later be
865 // stripped from the symbol table to reduce bloat.
866 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
867 Visibility = GlobalValue::HiddenVisibility;
868 NewGV->setVisibility(Visibility);
871 GlobalValue *ModuleLinker::copyGlobalValueProto(TypeMapTy &TypeMap,
872 const GlobalValue *SGV,
873 const GlobalValue *DGV) {
875 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV))
876 NewGV = copyGlobalVariableProto(TypeMap, SGVar);
877 else if (auto *SF = dyn_cast<Function>(SGV))
878 NewGV = copyFunctionProto(TypeMap, SF);
880 NewGV = copyGlobalAliasProto(TypeMap, cast<GlobalAlias>(SGV));
881 copyGVAttributes(NewGV, SGV);
882 setVisibility(NewGV, SGV, DGV);
886 Value *ValueMaterializerTy::materializeValueFor(Value *V) {
887 auto *SGV = dyn_cast<GlobalValue>(V);
891 GlobalValue *DGV = ModLinker->copyGlobalValueProto(TypeMap, SGV);
893 if (Comdat *SC = SGV->getComdat()) {
894 if (auto *DGO = dyn_cast<GlobalObject>(DGV)) {
895 Comdat *DC = DstM->getOrInsertComdat(SC->getName());
900 LazilyLinkGlobalValues.push_back(SGV);
904 bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
905 const GlobalVariable *&GVar) {
906 const GlobalValue *GVal = M->getNamedValue(ComdatName);
907 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
908 GVal = GA->getBaseObject();
910 // We cannot resolve the size of the aliasee yet.
911 return emitError("Linking COMDATs named '" + ComdatName +
912 "': COMDAT key involves incomputable alias size.");
915 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
918 "Linking COMDATs named '" + ComdatName +
919 "': GlobalVariable required for data dependent selection!");
924 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
925 Comdat::SelectionKind Src,
926 Comdat::SelectionKind Dst,
927 Comdat::SelectionKind &Result,
929 // The ability to mix Comdat::SelectionKind::Any with
930 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
931 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
932 Dst == Comdat::SelectionKind::Largest;
933 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
934 Src == Comdat::SelectionKind::Largest;
935 if (DstAnyOrLargest && SrcAnyOrLargest) {
936 if (Dst == Comdat::SelectionKind::Largest ||
937 Src == Comdat::SelectionKind::Largest)
938 Result = Comdat::SelectionKind::Largest;
940 Result = Comdat::SelectionKind::Any;
941 } else if (Src == Dst) {
944 return emitError("Linking COMDATs named '" + ComdatName +
945 "': invalid selection kinds!");
949 case Comdat::SelectionKind::Any:
953 case Comdat::SelectionKind::NoDuplicates:
954 return emitError("Linking COMDATs named '" + ComdatName +
955 "': noduplicates has been violated!");
956 case Comdat::SelectionKind::ExactMatch:
957 case Comdat::SelectionKind::Largest:
958 case Comdat::SelectionKind::SameSize: {
959 const GlobalVariable *DstGV;
960 const GlobalVariable *SrcGV;
961 if (getComdatLeader(DstM, ComdatName, DstGV) ||
962 getComdatLeader(SrcM, ComdatName, SrcGV))
965 const DataLayout &DstDL = DstM->getDataLayout();
966 const DataLayout &SrcDL = SrcM->getDataLayout();
968 DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
970 SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
971 if (Result == Comdat::SelectionKind::ExactMatch) {
972 if (SrcGV->getInitializer() != DstGV->getInitializer())
973 return emitError("Linking COMDATs named '" + ComdatName +
974 "': ExactMatch violated!");
976 } else if (Result == Comdat::SelectionKind::Largest) {
977 LinkFromSrc = SrcSize > DstSize;
978 } else if (Result == Comdat::SelectionKind::SameSize) {
979 if (SrcSize != DstSize)
980 return emitError("Linking COMDATs named '" + ComdatName +
981 "': SameSize violated!");
984 llvm_unreachable("unknown selection kind");
993 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
994 Comdat::SelectionKind &Result,
996 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
997 StringRef ComdatName = SrcC->getName();
998 Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
999 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
1001 if (DstCI == ComdatSymTab.end()) {
1002 // Use the comdat if it is only available in one of the modules.
1008 const Comdat *DstC = &DstCI->second;
1009 Comdat::SelectionKind DSK = DstC->getSelectionKind();
1010 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
1014 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
1015 const GlobalValue &Dest,
1016 const GlobalValue &Src) {
1017 // Should we unconditionally use the Src?
1018 if (shouldOverrideFromSrc()) {
1023 // We always have to add Src if it has appending linkage.
1024 if (Src.hasAppendingLinkage()) {
1025 // Caller should have already determined that we can't link from source
1026 // when importing (see comments in linkGlobalValueProto).
1027 assert(!isPerformingImport());
1032 bool SrcIsDeclaration = Src.isDeclarationForLinker();
1033 bool DestIsDeclaration = Dest.isDeclarationForLinker();
1035 if (isPerformingImport()) {
1036 if (isa<Function>(&Src)) {
1037 // For functions, LinkFromSrc iff this is the function requested
1038 // for importing. For variables, decide below normally.
1039 LinkFromSrc = (&Src == ImportFunction);
1043 // Check if this is an alias with an already existing definition
1044 // in Dest, which must have come from a prior importing pass from
1045 // the same Src module. Unlike imported function and variable
1046 // definitions, which are imported as available_externally and are
1047 // not definitions for the linker, that is not a valid linkage for
1048 // imported aliases which must be definitions. Simply use the existing
1050 if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
1051 assert(isa<GlobalAlias>(&Dest));
1052 LinkFromSrc = false;
1057 if (SrcIsDeclaration) {
1058 // If Src is external or if both Src & Dest are external.. Just link the
1059 // external globals, we aren't adding anything.
1060 if (Src.hasDLLImportStorageClass()) {
1061 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
1062 LinkFromSrc = DestIsDeclaration;
1065 // If the Dest is weak, use the source linkage.
1066 LinkFromSrc = Dest.hasExternalWeakLinkage();
1070 if (DestIsDeclaration) {
1071 // If Dest is external but Src is not:
1076 if (Src.hasCommonLinkage()) {
1077 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
1082 if (!Dest.hasCommonLinkage()) {
1083 LinkFromSrc = false;
1087 const DataLayout &DL = Dest.getParent()->getDataLayout();
1088 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
1089 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
1090 LinkFromSrc = SrcSize > DestSize;
1094 if (Src.isWeakForLinker()) {
1095 assert(!Dest.hasExternalWeakLinkage());
1096 assert(!Dest.hasAvailableExternallyLinkage());
1098 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
1103 LinkFromSrc = false;
1107 if (Dest.isWeakForLinker()) {
1108 assert(Src.hasExternalLinkage());
1113 assert(!Src.hasExternalWeakLinkage());
1114 assert(!Dest.hasExternalWeakLinkage());
1115 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
1116 "Unexpected linkage type!");
1117 return emitError("Linking globals named '" + Src.getName() +
1118 "': symbol multiply defined!");
1121 /// Loop over all of the linked values to compute type mappings. For example,
1122 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
1123 /// types 'Foo' but one got renamed when the module was loaded into the same
1125 void ModuleLinker::computeTypeMapping() {
1126 for (GlobalValue &SGV : SrcM->globals()) {
1127 GlobalValue *DGV = getLinkedToGlobal(&SGV);
1131 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
1132 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1136 // Unify the element type of appending arrays.
1137 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
1138 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
1139 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
1142 for (GlobalValue &SGV : *SrcM) {
1143 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1144 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1147 for (GlobalValue &SGV : SrcM->aliases()) {
1148 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1149 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1152 // Incorporate types by name, scanning all the types in the source module.
1153 // At this point, the destination module may have a type "%foo = { i32 }" for
1154 // example. When the source module got loaded into the same LLVMContext, if
1155 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
1156 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
1157 for (StructType *ST : Types) {
1161 // Check to see if there is a dot in the name followed by a digit.
1162 size_t DotPos = ST->getName().rfind('.');
1163 if (DotPos == 0 || DotPos == StringRef::npos ||
1164 ST->getName().back() == '.' ||
1165 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
1168 // Check to see if the destination module has a struct with the prefix name.
1169 StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos));
1173 // Don't use it if this actually came from the source module. They're in
1174 // the same LLVMContext after all. Also don't use it unless the type is
1175 // actually used in the destination module. This can happen in situations
1178 // Module A Module B
1179 // -------- --------
1180 // %Z = type { %A } %B = type { %C.1 }
1181 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
1182 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
1183 // %C = type { i8* } %B.3 = type { %C.1 }
1185 // When we link Module B with Module A, the '%B' in Module B is
1186 // used. However, that would then use '%C.1'. But when we process '%C.1',
1187 // we prefer to take the '%C' version. So we are then left with both
1188 // '%C.1' and '%C' being used for the same types. This leads to some
1189 // variables using one type and some using the other.
1190 if (TypeMap.DstStructTypesSet.hasType(DST))
1191 TypeMap.addTypeMapping(DST, ST);
1194 // Now that we have discovered all of the type equivalences, get a body for
1195 // any 'opaque' types in the dest module that are now resolved.
1196 TypeMap.linkDefinedTypeBodies();
1199 static void upgradeGlobalArray(GlobalVariable *GV) {
1200 ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
1201 StructType *OldTy = cast<StructType>(ATy->getElementType());
1202 assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
1204 // Get the upgraded 3 element type.
1205 PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
1206 Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
1208 StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
1210 // Build new constants with a null third field filled in.
1211 Constant *OldInitC = GV->getInitializer();
1212 ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
1213 if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
1214 // Invalid initializer; give up.
1216 std::vector<Constant *> Initializers;
1217 if (OldInit && OldInit->getNumOperands()) {
1218 Value *Null = Constant::getNullValue(VoidPtrTy);
1219 for (Use &U : OldInit->operands()) {
1220 ConstantStruct *Init = cast<ConstantStruct>(U.get());
1221 Initializers.push_back(ConstantStruct::get(
1222 NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
1225 assert(Initializers.size() == ATy->getNumElements() &&
1226 "Failed to copy all array elements");
1228 // Replace the old GV with a new one.
1229 ATy = ArrayType::get(NewTy, Initializers.size());
1230 Constant *NewInit = ConstantArray::get(ATy, Initializers);
1231 GlobalVariable *NewGV = new GlobalVariable(
1232 *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
1233 GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
1234 GV->isExternallyInitialized());
1235 NewGV->copyAttributesFrom(GV);
1236 NewGV->takeName(GV);
1237 assert(GV->use_empty() && "program cannot use initializer list");
1238 GV->eraseFromParent();
1241 void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
1242 // Look for the global arrays.
1243 auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
1246 auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
1250 // Check if the types already match.
1251 auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
1253 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
1257 // Grab the element types. We can only upgrade an array of a two-field
1258 // struct. Only bother if the other one has three-fields.
1259 auto *DstEltTy = cast<StructType>(DstTy->getElementType());
1260 auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
1261 if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
1262 upgradeGlobalArray(DstGV);
1265 if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
1266 upgradeGlobalArray(SrcGV);
1268 // We can't upgrade any other differences.
1271 void ModuleLinker::upgradeMismatchedGlobals() {
1272 upgradeMismatchedGlobalArray("llvm.global_ctors");
1273 upgradeMismatchedGlobalArray("llvm.global_dtors");
1276 /// If there were any appending global variables, link them together now.
1277 /// Return true on error.
1278 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
1279 const GlobalVariable *SrcGV) {
1281 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
1282 return emitError("Linking globals named '" + SrcGV->getName() +
1283 "': can only link appending global with another appending global!");
1285 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
1287 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
1288 Type *EltTy = DstTy->getElementType();
1290 // Check to see that they two arrays agree on type.
1291 if (EltTy != SrcTy->getElementType())
1292 return emitError("Appending variables with different element types!");
1293 if (DstGV->isConstant() != SrcGV->isConstant())
1294 return emitError("Appending variables linked with different const'ness!");
1296 if (DstGV->getAlignment() != SrcGV->getAlignment())
1298 "Appending variables with different alignment need to be linked!");
1300 if (DstGV->getVisibility() != SrcGV->getVisibility())
1302 "Appending variables with different visibility need to be linked!");
1304 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
1306 "Appending variables with different unnamed_addr need to be linked!");
1308 if (StringRef(DstGV->getSection()) != SrcGV->getSection())
1310 "Appending variables with different section name need to be linked!");
1312 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
1313 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
1315 // Create the new global variable.
1316 GlobalVariable *NG =
1317 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
1318 DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
1319 DstGV->getThreadLocalMode(),
1320 DstGV->getType()->getAddressSpace());
1322 // Propagate alignment, visibility and section info.
1323 copyGVAttributes(NG, DstGV);
1325 AppendingVarInfo AVI;
1327 AVI.DstInit = DstGV->getInitializer();
1328 AVI.SrcInit = SrcGV->getInitializer();
1329 AppendingVars.push_back(AVI);
1331 // Replace any uses of the two global variables with uses of the new
1333 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
1335 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
1336 DstGV->eraseFromParent();
1338 // Track the source variable so we don't try to link it.
1339 DoNotLinkFromSource.insert(SrcGV);
1344 bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
1345 GlobalValue *DGV = getLinkedToGlobal(SGV);
1347 // Handle the ultra special appending linkage case first.
1348 assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
1349 if (SGV->hasAppendingLinkage() && isPerformingImport()) {
1350 // Don't want to append to global_ctors list, for example, when we
1351 // are importing for ThinLTO, otherwise the global ctors and dtors
1352 // get executed multiple times for local variables (the latter causing
1354 DoNotLinkFromSource.insert(SGV);
1357 if (DGV && DGV->hasAppendingLinkage())
1358 return linkAppendingVarProto(cast<GlobalVariable>(DGV),
1359 cast<GlobalVariable>(SGV));
1361 bool LinkFromSrc = true;
1362 Comdat *C = nullptr;
1363 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
1365 if (const Comdat *SC = SGV->getComdat()) {
1366 Comdat::SelectionKind SK;
1367 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1368 C = DstM->getOrInsertComdat(SC->getName());
1369 C->setSelectionKind(SK);
1371 if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1376 // Track the source global so that we don't attempt to copy it over when
1377 // processing global initializers.
1378 DoNotLinkFromSource.insert(SGV);
1381 // Make sure to remember this mapping.
1383 ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
1387 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1389 if (!LinkFromSrc && !DGV)
1395 // When linking from source we setVisibility from copyGlobalValueProto.
1396 setVisibility(NewGV, SGV, DGV);
1398 // If the GV is to be lazily linked, don't create it just yet.
1399 // The ValueMaterializerTy will deal with creating it if it's used.
1400 if (!DGV && !shouldOverrideFromSrc() && SGV != ImportFunction &&
1401 (SGV->hasLocalLinkage() || SGV->hasLinkOnceLinkage() ||
1402 SGV->hasAvailableExternallyLinkage())) {
1403 DoNotLinkFromSource.insert(SGV);
1407 // When we only want to link in unresolved dependencies, blacklist
1408 // the symbol unless unless DestM has a matching declaration (DGV).
1409 if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration())) {
1410 DoNotLinkFromSource.insert(SGV);
1414 NewGV = copyGlobalValueProto(TypeMap, SGV, DGV);
1417 NewGV->setUnnamedAddr(HasUnnamedAddr);
1419 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1421 NewGO->setComdat(C);
1423 if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1424 NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
1427 if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) {
1428 auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV);
1429 auto *SGVar = dyn_cast<GlobalVariable>(SGV);
1430 if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() &&
1431 (!DGVar->isConstant() || !SGVar->isConstant()))
1432 NewGVar->setConstant(false);
1435 // Make sure to remember this mapping.
1438 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
1439 DGV->eraseFromParent();
1441 ValueMap[SGV] = NewGV;
1447 static void getArrayElements(const Constant *C,
1448 SmallVectorImpl<Constant *> &Dest) {
1449 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1451 for (unsigned i = 0; i != NumElements; ++i)
1452 Dest.push_back(C->getAggregateElement(i));
1455 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1456 // Merge the initializer.
1457 SmallVector<Constant *, 16> DstElements;
1458 getArrayElements(AVI.DstInit, DstElements);
1460 SmallVector<Constant *, 16> SrcElements;
1461 getArrayElements(AVI.SrcInit, SrcElements);
1463 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1465 StringRef Name = AVI.NewGV->getName();
1466 bool IsNewStructor =
1467 (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1468 cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1470 for (auto *V : SrcElements) {
1471 if (IsNewStructor) {
1472 Constant *Key = V->getAggregateElement(2);
1473 if (DoNotLinkFromSource.count(Key))
1476 DstElements.push_back(
1477 MapValue(V, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1479 if (IsNewStructor) {
1480 NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1481 AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1484 AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1487 /// Update the initializers in the Dest module now that all globals that may be
1488 /// referenced are in Dest.
1489 void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
1490 // Figure out what the initializer looks like in the dest module.
1491 Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap,
1492 RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1495 /// Copy the source function over into the dest function and fix up references
1496 /// to values. At this point we know that Dest is an external function, and
1497 /// that Src is not.
1498 bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) {
1499 assert(Dst.isDeclaration() && !Src.isDeclaration());
1501 // Materialize if needed.
1502 if (std::error_code EC = Src.materialize())
1503 return emitError(EC.message());
1505 // Link in the prefix data.
1506 if (Src.hasPrefixData())
1507 Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap,
1508 RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1510 // Link in the prologue data.
1511 if (Src.hasPrologueData())
1512 Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap,
1513 RF_MoveDistinctMDs, &TypeMap,
1516 // Link in the personality function.
1517 if (Src.hasPersonalityFn())
1518 Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap,
1519 RF_MoveDistinctMDs, &TypeMap,
1522 // Go through and convert function arguments over, remembering the mapping.
1523 Function::arg_iterator DI = Dst.arg_begin();
1524 for (Argument &Arg : Src.args()) {
1525 DI->setName(Arg.getName()); // Copy the name over.
1527 // Add a mapping to our mapping.
1528 ValueMap[&Arg] = &*DI;
1532 // Copy over the metadata attachments.
1533 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1534 Src.getAllMetadata(MDs);
1535 for (const auto &I : MDs)
1536 Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, RF_MoveDistinctMDs,
1537 &TypeMap, &ValMaterializer));
1539 // Splice the body of the source function into the dest function.
1540 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
1542 // At this point, all of the instructions and values of the function are now
1543 // copied over. The only problem is that they are still referencing values in
1544 // the Source function as operands. Loop through all of the operands of the
1545 // functions and patch them up to point to the local versions.
1546 for (BasicBlock &BB : Dst)
1547 for (Instruction &I : BB)
1548 RemapInstruction(&I, ValueMap,
1549 RF_IgnoreMissingEntries | RF_MoveDistinctMDs, &TypeMap,
1552 // There is no need to map the arguments anymore.
1553 for (Argument &Arg : Src.args())
1554 ValueMap.erase(&Arg);
1556 Src.dematerialize();
1560 void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1561 Constant *Aliasee = Src.getAliasee();
1562 Constant *Val = MapValue(Aliasee, ValueMap, RF_MoveDistinctMDs, &TypeMap,
1564 Dst.setAliasee(Val);
1567 bool ModuleLinker::linkGlobalValueBody(GlobalValue &Src) {
1568 Value *Dst = ValueMap[&Src];
1570 if (shouldInternalizeLinkedSymbols())
1571 if (auto *DGV = dyn_cast<GlobalValue>(Dst))
1572 DGV->setLinkage(GlobalValue::InternalLinkage);
1573 if (auto *F = dyn_cast<Function>(&Src))
1574 return linkFunctionBody(cast<Function>(*Dst), *F);
1575 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1576 linkGlobalInit(cast<GlobalVariable>(*Dst), *GVar);
1579 linkAliasBody(cast<GlobalAlias>(*Dst), cast<GlobalAlias>(Src));
1583 /// Insert all of the named MDNodes in Src into the Dest module.
1584 void ModuleLinker::linkNamedMDNodes() {
1585 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1586 for (const NamedMDNode &NMD : SrcM->named_metadata()) {
1587 // Don't link module flags here. Do them separately.
1588 if (&NMD == SrcModFlags)
1590 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(NMD.getName());
1591 // Add Src elements into Dest node.
1592 for (const MDNode *op : NMD.operands())
1593 DestNMD->addOperand(MapMetadata(op, ValueMap, RF_MoveDistinctMDs,
1594 &TypeMap, &ValMaterializer));
1598 /// Merge the linker flags in Src into the Dest module.
1599 bool ModuleLinker::linkModuleFlagsMetadata() {
1600 // If the source module has no module flags, we are done.
1601 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1602 if (!SrcModFlags) return false;
1604 // If the destination module doesn't have module flags yet, then just copy
1605 // over the source module's flags.
1606 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1607 if (DstModFlags->getNumOperands() == 0) {
1608 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1609 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1614 // First build a map of the existing module flags and requirements.
1615 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1616 SmallSetVector<MDNode*, 16> Requirements;
1617 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1618 MDNode *Op = DstModFlags->getOperand(I);
1619 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1620 MDString *ID = cast<MDString>(Op->getOperand(1));
1622 if (Behavior->getZExtValue() == Module::Require) {
1623 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1625 Flags[ID] = std::make_pair(Op, I);
1629 // Merge in the flags from the source module, and also collect its set of
1631 bool HasErr = false;
1632 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1633 MDNode *SrcOp = SrcModFlags->getOperand(I);
1634 ConstantInt *SrcBehavior =
1635 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1636 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1639 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1640 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1642 // If this is a requirement, add it and continue.
1643 if (SrcBehaviorValue == Module::Require) {
1644 // If the destination module does not already have this requirement, add
1646 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1647 DstModFlags->addOperand(SrcOp);
1652 // If there is no existing flag with this ID, just add it.
1654 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1655 DstModFlags->addOperand(SrcOp);
1659 // Otherwise, perform a merge.
1660 ConstantInt *DstBehavior =
1661 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1662 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1664 // If either flag has override behavior, handle it first.
1665 if (DstBehaviorValue == Module::Override) {
1666 // Diagnose inconsistent flags which both have override behavior.
1667 if (SrcBehaviorValue == Module::Override &&
1668 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1669 HasErr |= emitError("linking module flags '" + ID->getString() +
1670 "': IDs have conflicting override values");
1673 } else if (SrcBehaviorValue == Module::Override) {
1674 // Update the destination flag to that of the source.
1675 DstModFlags->setOperand(DstIndex, SrcOp);
1676 Flags[ID].first = SrcOp;
1680 // Diagnose inconsistent merge behavior types.
1681 if (SrcBehaviorValue != DstBehaviorValue) {
1682 HasErr |= emitError("linking module flags '" + ID->getString() +
1683 "': IDs have conflicting behaviors");
1687 auto replaceDstValue = [&](MDNode *New) {
1688 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1689 MDNode *Flag = MDNode::get(DstM->getContext(), FlagOps);
1690 DstModFlags->setOperand(DstIndex, Flag);
1691 Flags[ID].first = Flag;
1694 // Perform the merge for standard behavior types.
1695 switch (SrcBehaviorValue) {
1696 case Module::Require:
1697 case Module::Override: llvm_unreachable("not possible");
1698 case Module::Error: {
1699 // Emit an error if the values differ.
1700 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1701 HasErr |= emitError("linking module flags '" + ID->getString() +
1702 "': IDs have conflicting values");
1706 case Module::Warning: {
1707 // Emit a warning if the values differ.
1708 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1709 emitWarning("linking module flags '" + ID->getString() +
1710 "': IDs have conflicting values");
1714 case Module::Append: {
1715 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1716 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1717 SmallVector<Metadata *, 8> MDs;
1718 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1719 MDs.append(DstValue->op_begin(), DstValue->op_end());
1720 MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1722 replaceDstValue(MDNode::get(DstM->getContext(), MDs));
1725 case Module::AppendUnique: {
1726 SmallSetVector<Metadata *, 16> Elts;
1727 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1728 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1729 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1730 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1732 replaceDstValue(MDNode::get(DstM->getContext(),
1733 makeArrayRef(Elts.begin(), Elts.end())));
1739 // Check all of the requirements.
1740 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1741 MDNode *Requirement = Requirements[I];
1742 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1743 Metadata *ReqValue = Requirement->getOperand(1);
1745 MDNode *Op = Flags[Flag].first;
1746 if (!Op || Op->getOperand(2) != ReqValue) {
1747 HasErr |= emitError("linking module flags '" + Flag->getString() +
1748 "': does not have the required value");
1756 // This function returns true if the triples match.
1757 static bool triplesMatch(const Triple &T0, const Triple &T1) {
1758 // If vendor is apple, ignore the version number.
1759 if (T0.getVendor() == Triple::Apple)
1760 return T0.getArch() == T1.getArch() &&
1761 T0.getSubArch() == T1.getSubArch() &&
1762 T0.getVendor() == T1.getVendor() &&
1763 T0.getOS() == T1.getOS();
1768 // This function returns the merged triple.
1769 static std::string mergeTriples(const Triple &SrcTriple, const Triple &DstTriple) {
1770 // If vendor is apple, pick the triple with the larger version number.
1771 if (SrcTriple.getVendor() == Triple::Apple)
1772 if (DstTriple.isOSVersionLT(SrcTriple))
1773 return SrcTriple.str();
1775 return DstTriple.str();
1778 bool ModuleLinker::run() {
1779 assert(DstM && "Null destination module");
1780 assert(SrcM && "Null source module");
1782 // Inherit the target data from the source module if the destination module
1783 // doesn't have one already.
1784 if (DstM->getDataLayout().isDefault())
1785 DstM->setDataLayout(SrcM->getDataLayout());
1787 if (SrcM->getDataLayout() != DstM->getDataLayout()) {
1788 emitWarning("Linking two modules of different data layouts: '" +
1789 SrcM->getModuleIdentifier() + "' is '" +
1790 SrcM->getDataLayoutStr() + "' whereas '" +
1791 DstM->getModuleIdentifier() + "' is '" +
1792 DstM->getDataLayoutStr() + "'\n");
1795 // Copy the target triple from the source to dest if the dest's is empty.
1796 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1797 DstM->setTargetTriple(SrcM->getTargetTriple());
1799 Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM->getTargetTriple());
1801 if (!SrcM->getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
1802 emitWarning("Linking two modules of different target triples: " +
1803 SrcM->getModuleIdentifier() + "' is '" +
1804 SrcM->getTargetTriple() + "' whereas '" +
1805 DstM->getModuleIdentifier() + "' is '" +
1806 DstM->getTargetTriple() + "'\n");
1808 DstM->setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1810 // Append the module inline asm string.
1811 if (!SrcM->getModuleInlineAsm().empty()) {
1812 if (DstM->getModuleInlineAsm().empty())
1813 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1815 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1816 SrcM->getModuleInlineAsm());
1819 // Loop over all of the linked values to compute type mappings.
1820 computeTypeMapping();
1822 ComdatsChosen.clear();
1823 for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
1824 const Comdat &C = SMEC.getValue();
1825 if (ComdatsChosen.count(&C))
1827 Comdat::SelectionKind SK;
1829 if (getComdatResult(&C, SK, LinkFromSrc))
1831 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1834 // Upgrade mismatched global arrays.
1835 upgradeMismatchedGlobals();
1837 // Insert all of the globals in src into the DstM module... without linking
1838 // initializers (which could refer to functions not yet mapped over).
1839 for (GlobalVariable &GV : SrcM->globals())
1840 if (linkGlobalValueProto(&GV))
1843 // Link the functions together between the two modules, without doing function
1844 // bodies... this just adds external function prototypes to the DstM
1845 // function... We do this so that when we begin processing function bodies,
1846 // all of the global values that may be referenced are available in our
1848 for (Function &F :*SrcM)
1849 if (linkGlobalValueProto(&F))
1852 // If there were any aliases, link them now.
1853 for (GlobalAlias &GA : SrcM->aliases())
1854 if (linkGlobalValueProto(&GA))
1857 for (const AppendingVarInfo &AppendingVar : AppendingVars)
1858 linkAppendingVarInit(AppendingVar);
1860 for (const auto &Entry : DstM->getComdatSymbolTable()) {
1861 const Comdat &C = Entry.getValue();
1862 if (C.getSelectionKind() == Comdat::Any)
1864 const GlobalValue *GV = SrcM->getNamedValue(C.getName());
1866 MapValue(GV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1869 // Link in the function bodies that are defined in the source module into
1871 for (Function &SF : *SrcM) {
1872 // Skip if no body (function is external).
1873 if (SF.isDeclaration())
1876 // Skip if not linking from source.
1877 if (DoNotLinkFromSource.count(&SF))
1880 // When importing, only materialize the function requested for import.
1881 if (isPerformingImport() && &SF != ImportFunction)
1884 if (linkGlobalValueBody(SF))
1888 // Resolve all uses of aliases with aliasees.
1889 for (GlobalAlias &Src : SrcM->aliases()) {
1890 if (DoNotLinkFromSource.count(&Src))
1892 linkGlobalValueBody(Src);
1895 // Update the initializers in the DstM module now that all globals that may
1896 // be referenced are in DstM.
1897 for (GlobalVariable &Src : SrcM->globals()) {
1898 // Only process initialized GV's or ones not already in dest.
1899 if (!Src.hasInitializer() || DoNotLinkFromSource.count(&Src))
1901 linkGlobalValueBody(Src);
1904 // Process vector of lazily linked in functions.
1905 while (!LazilyLinkGlobalValues.empty()) {
1906 GlobalValue *SGV = LazilyLinkGlobalValues.back();
1907 LazilyLinkGlobalValues.pop_back();
1908 if (isPerformingImport() && !doImportAsDefinition(SGV))
1911 // Skip declarations that ValueMaterializer may have created in
1912 // case we link in only some of SrcM.
1913 if (shouldLinkOnlyNeeded() && SGV->isDeclaration())
1916 assert(!SGV->isDeclaration() && "users should not pass down decls");
1917 if (linkGlobalValueBody(*SGV))
1921 // Remap all of the named MDNodes in Src into the DstM module. We do this
1922 // after linking GlobalValues so that MDNodes that reference GlobalValues
1923 // are properly remapped.
1926 // Merge the module flags into the DstM module.
1927 if (linkModuleFlagsMetadata())
1933 Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1934 : ETypes(E), IsPacked(P) {}
1936 Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1937 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1939 bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1940 if (IsPacked != That.IsPacked)
1942 if (ETypes != That.ETypes)
1947 bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1948 return !this->operator==(That);
1951 StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
1952 return DenseMapInfo<StructType *>::getEmptyKey();
1955 StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
1956 return DenseMapInfo<StructType *>::getTombstoneKey();
1959 unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1960 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1964 unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1965 return getHashValue(KeyTy(ST));
1968 bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1969 const StructType *RHS) {
1970 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1972 return LHS == KeyTy(RHS);
1975 bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
1976 const StructType *RHS) {
1977 if (RHS == getEmptyKey())
1978 return LHS == getEmptyKey();
1980 if (RHS == getTombstoneKey())
1981 return LHS == getTombstoneKey();
1983 return KeyTy(LHS) == KeyTy(RHS);
1986 void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1987 assert(!Ty->isOpaque());
1988 NonOpaqueStructTypes.insert(Ty);
1991 void Linker::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1992 assert(!Ty->isOpaque());
1993 NonOpaqueStructTypes.insert(Ty);
1994 bool Removed = OpaqueStructTypes.erase(Ty);
1999 void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
2000 assert(Ty->isOpaque());
2001 OpaqueStructTypes.insert(Ty);
2005 Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
2007 Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
2008 auto I = NonOpaqueStructTypes.find_as(Key);
2009 if (I == NonOpaqueStructTypes.end())
2014 bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
2016 return OpaqueStructTypes.count(Ty);
2017 auto I = NonOpaqueStructTypes.find(Ty);
2018 if (I == NonOpaqueStructTypes.end())
2023 void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
2024 this->Composite = M;
2025 this->DiagnosticHandler = DiagnosticHandler;
2027 TypeFinder StructTypes;
2028 StructTypes.run(*M, true);
2029 for (StructType *Ty : StructTypes) {
2031 IdentifiedStructTypes.addOpaque(Ty);
2033 IdentifiedStructTypes.addNonOpaque(Ty);
2037 Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
2038 init(M, DiagnosticHandler);
2041 Linker::Linker(Module *M) {
2042 init(M, [this](const DiagnosticInfo &DI) {
2043 Composite->getContext().diagnose(DI);
2047 void Linker::deleteModule() {
2049 Composite = nullptr;
2052 bool Linker::linkInModule(Module *Src, unsigned Flags, FunctionInfoIndex *Index,
2053 Function *FuncToImport) {
2054 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
2055 DiagnosticHandler, Flags, Index, FuncToImport);
2056 bool RetCode = TheLinker.run();
2057 Composite->dropTriviallyDeadConstantArrays();
2061 void Linker::setModule(Module *Dst) {
2062 init(Dst, DiagnosticHandler);
2065 //===----------------------------------------------------------------------===//
2066 // LinkModules entrypoint.
2067 //===----------------------------------------------------------------------===//
2069 /// This function links two modules together, with the resulting Dest module
2070 /// modified to be the composite of the two input modules. If an error occurs,
2071 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
2072 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
2073 /// relied on to be consistent.
2074 bool Linker::LinkModules(Module *Dest, Module *Src,
2075 DiagnosticHandlerFunction DiagnosticHandler,
2077 Linker L(Dest, DiagnosticHandler);
2078 return L.linkInModule(Src, Flags);
2081 bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Flags) {
2083 return L.linkInModule(Src, Flags);
2086 //===----------------------------------------------------------------------===//
2088 //===----------------------------------------------------------------------===//
2090 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
2091 LLVMLinkerMode Unused, char **OutMessages) {
2092 Module *D = unwrap(Dest);
2093 std::string Message;
2094 raw_string_ostream Stream(Message);
2095 DiagnosticPrinterRawOStream DP(Stream);
2097 LLVMBool Result = Linker::LinkModules(
2098 D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
2100 if (OutMessages && Result) {
2102 *OutMessages = strdup(Message.c_str());