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/SetVector.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/Triple.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/Transforms/Utils/Cloning.h"
28 //===----------------------------------------------------------------------===//
29 // TypeMap implementation.
30 //===----------------------------------------------------------------------===//
33 class TypeMapTy : public ValueMapTypeRemapper {
34 /// This is a mapping from a source type to a destination type to use.
35 DenseMap<Type *, Type *> MappedTypes;
37 /// When checking to see if two subgraphs are isomorphic, we speculatively
38 /// add types to MappedTypes, but keep track of them here in case we need to
40 SmallVector<Type *, 16> SpeculativeTypes;
42 SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
44 /// This is a list of non-opaque structs in the source module that are mapped
45 /// to an opaque struct in the destination module.
46 SmallVector<StructType *, 16> SrcDefinitionsToResolve;
48 /// This is the set of opaque types in the destination modules who are
49 /// getting a body from the source module.
50 SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
53 TypeMapTy(Linker::IdentifiedStructTypeSet &DstStructTypesSet)
54 : DstStructTypesSet(DstStructTypesSet) {}
56 Linker::IdentifiedStructTypeSet &DstStructTypesSet;
57 /// Indicate that the specified type in the destination module is conceptually
58 /// equivalent to the specified type in the source module.
59 void addTypeMapping(Type *DstTy, Type *SrcTy);
61 /// Produce a body for an opaque type in the dest module from a type
62 /// definition in the source module.
63 void linkDefinedTypeBodies();
65 /// Return the mapped type to use for the specified input type from the
67 Type *get(Type *SrcTy);
68 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
70 void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
72 FunctionType *get(FunctionType *T) {
73 return cast<FunctionType>(get((Type *)T));
76 /// Dump out the type map for debugging purposes.
78 for (auto &Pair : MappedTypes) {
79 dbgs() << "TypeMap: ";
80 Pair.first->print(dbgs());
82 Pair.second->print(dbgs());
88 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
90 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
94 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
95 assert(SpeculativeTypes.empty());
96 assert(SpeculativeDstOpaqueTypes.empty());
98 // Check to see if these types are recursively isomorphic and establish a
99 // mapping between them if so.
100 if (!areTypesIsomorphic(DstTy, SrcTy)) {
101 // Oops, they aren't isomorphic. Just discard this request by rolling out
102 // any speculative mappings we've established.
103 for (Type *Ty : SpeculativeTypes)
104 MappedTypes.erase(Ty);
106 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
107 SpeculativeDstOpaqueTypes.size());
108 for (StructType *Ty : SpeculativeDstOpaqueTypes)
109 DstResolvedOpaqueTypes.erase(Ty);
111 for (Type *Ty : SpeculativeTypes)
112 if (auto *STy = dyn_cast<StructType>(Ty))
116 SpeculativeTypes.clear();
117 SpeculativeDstOpaqueTypes.clear();
120 /// Recursively walk this pair of types, returning true if they are isomorphic,
121 /// false if they are not.
122 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
123 // Two types with differing kinds are clearly not isomorphic.
124 if (DstTy->getTypeID() != SrcTy->getTypeID())
127 // If we have an entry in the MappedTypes table, then we have our answer.
128 Type *&Entry = MappedTypes[SrcTy];
130 return Entry == DstTy;
132 // Two identical types are clearly isomorphic. Remember this
133 // non-speculatively.
134 if (DstTy == SrcTy) {
139 // Okay, we have two types with identical kinds that we haven't seen before.
141 // If this is an opaque struct type, special case it.
142 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
143 // Mapping an opaque type to any struct, just keep the dest struct.
144 if (SSTy->isOpaque()) {
146 SpeculativeTypes.push_back(SrcTy);
150 // Mapping a non-opaque source type to an opaque dest. If this is the first
151 // type that we're mapping onto this destination type then we succeed. Keep
152 // the dest, but fill it in later. If this is the second (different) type
153 // that we're trying to map onto the same opaque type then we fail.
154 if (cast<StructType>(DstTy)->isOpaque()) {
155 // We can only map one source type onto the opaque destination type.
156 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
158 SrcDefinitionsToResolve.push_back(SSTy);
159 SpeculativeTypes.push_back(SrcTy);
160 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
166 // If the number of subtypes disagree between the two types, then we fail.
167 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
170 // Fail if any of the extra properties (e.g. array size) of the type disagree.
171 if (isa<IntegerType>(DstTy))
172 return false; // bitwidth disagrees.
173 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
174 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
177 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
178 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
180 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
181 StructType *SSTy = cast<StructType>(SrcTy);
182 if (DSTy->isLiteral() != SSTy->isLiteral() ||
183 DSTy->isPacked() != SSTy->isPacked())
185 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
186 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
188 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
189 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
193 // Otherwise, we speculate that these two types will line up and recursively
194 // check the subelements.
196 SpeculativeTypes.push_back(SrcTy);
198 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
199 if (!areTypesIsomorphic(DstTy->getContainedType(I),
200 SrcTy->getContainedType(I)))
203 // If everything seems to have lined up, then everything is great.
207 void TypeMapTy::linkDefinedTypeBodies() {
208 SmallVector<Type *, 16> Elements;
209 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
210 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
211 assert(DstSTy->isOpaque());
213 // Map the body of the source type over to a new body for the dest type.
214 Elements.resize(SrcSTy->getNumElements());
215 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
216 Elements[I] = get(SrcSTy->getElementType(I));
218 DstSTy->setBody(Elements, SrcSTy->isPacked());
219 DstStructTypesSet.switchToNonOpaque(DstSTy);
221 SrcDefinitionsToResolve.clear();
222 DstResolvedOpaqueTypes.clear();
225 void TypeMapTy::finishType(StructType *DTy, StructType *STy,
226 ArrayRef<Type *> ETypes) {
227 DTy->setBody(ETypes, STy->isPacked());
230 if (STy->hasName()) {
231 SmallString<16> TmpName = STy->getName();
233 DTy->setName(TmpName);
236 DstStructTypesSet.addNonOpaque(DTy);
239 Type *TypeMapTy::get(Type *Ty) {
240 SmallPtrSet<StructType *, 8> Visited;
241 return get(Ty, Visited);
244 Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
245 // If we already have an entry for this type, return it.
246 Type **Entry = &MappedTypes[Ty];
250 // These are types that LLVM itself will unique.
251 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
255 for (auto &Pair : MappedTypes) {
256 assert(!(Pair.first != Ty && Pair.second == Ty) &&
257 "mapping to a source type");
262 if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
263 StructType *DTy = StructType::create(Ty->getContext());
267 // If this is not a recursive type, then just map all of the elements and
268 // then rebuild the type from inside out.
269 SmallVector<Type *, 4> ElementTypes;
271 // If there are no element types to map, then the type is itself. This is
272 // true for the anonymous {} struct, things like 'float', integers, etc.
273 if (Ty->getNumContainedTypes() == 0 && IsUniqued)
276 // Remap all of the elements, keeping track of whether any of them change.
277 bool AnyChange = false;
278 ElementTypes.resize(Ty->getNumContainedTypes());
279 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
280 ElementTypes[I] = get(Ty->getContainedType(I), Visited);
281 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
284 // If we found our type while recursively processing stuff, just use it.
285 Entry = &MappedTypes[Ty];
287 if (auto *DTy = dyn_cast<StructType>(*Entry)) {
288 if (DTy->isOpaque()) {
289 auto *STy = cast<StructType>(Ty);
290 finishType(DTy, STy, ElementTypes);
296 // If all of the element types mapped directly over and the type is not
297 // a nomed struct, then the type is usable as-is.
298 if (!AnyChange && IsUniqued)
301 // Otherwise, rebuild a modified type.
302 switch (Ty->getTypeID()) {
304 llvm_unreachable("unknown derived type to remap");
305 case Type::ArrayTyID:
306 return *Entry = ArrayType::get(ElementTypes[0],
307 cast<ArrayType>(Ty)->getNumElements());
308 case Type::VectorTyID:
309 return *Entry = VectorType::get(ElementTypes[0],
310 cast<VectorType>(Ty)->getNumElements());
311 case Type::PointerTyID:
312 return *Entry = PointerType::get(ElementTypes[0],
313 cast<PointerType>(Ty)->getAddressSpace());
314 case Type::FunctionTyID:
315 return *Entry = FunctionType::get(ElementTypes[0],
316 makeArrayRef(ElementTypes).slice(1),
317 cast<FunctionType>(Ty)->isVarArg());
318 case Type::StructTyID: {
319 auto *STy = cast<StructType>(Ty);
320 bool IsPacked = STy->isPacked();
322 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
324 // If the type is opaque, we can just use it directly.
325 if (STy->isOpaque()) {
326 DstStructTypesSet.addOpaque(STy);
330 if (StructType *OldT =
331 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
333 return *Entry = OldT;
337 DstStructTypesSet.addNonOpaque(STy);
341 StructType *DTy = StructType::create(Ty->getContext());
342 finishType(DTy, STy, ElementTypes);
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 final : public ValueMaterializer {
359 ModuleLinker *ModLinker;
362 ValueMaterializerTy(ModuleLinker *ModLinker) : ModLinker(ModLinker) {}
364 Value *materializeDeclFor(Value *V) override;
365 void materializeInitFor(GlobalValue *New, GlobalValue *Old) override;
368 class LinkDiagnosticInfo : public DiagnosticInfo {
372 LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
373 void print(DiagnosticPrinter &DP) const override;
375 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
377 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
378 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
380 /// This is an implementation class for the LinkModules function, which is the
381 /// entrypoint for this file.
387 ValueMaterializerTy ValMaterializer;
389 /// Mapping of values from what they used to be in Src, to what they are now
390 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
391 /// due to the use of Value handles which the Linker doesn't actually need,
392 /// but this allows us to reuse the ValueMapper code.
393 ValueToValueMapTy ValueMap;
395 // Set of items not to link in from source.
396 SmallPtrSet<const GlobalValue *, 16> DoNotLinkFromSource;
398 DiagnosticHandlerFunction DiagnosticHandler;
400 /// For symbol clashes, prefer those from Src.
403 /// Function index passed into ModuleLinker for using in function
404 /// importing/exporting handling.
405 const FunctionInfoIndex *ImportIndex;
407 /// Function to import from source module, all other functions are
408 /// imported as declarations instead of definitions.
409 DenseSet<const GlobalValue *> *ImportFunction;
411 /// Set to true if the given FunctionInfoIndex contains any functions
412 /// from this source module, in which case we must conservatively assume
413 /// that any of its functions may be imported into another module
414 /// as part of a different backend compilation process.
415 bool HasExportedFunctions = false;
417 /// Set to true when all global value body linking is complete (including
418 /// lazy linking). Used to prevent metadata linking from creating new
420 bool DoneLinkingBodies = false;
422 bool HasError = false;
425 ModuleLinker(Module &DstM, Linker::IdentifiedStructTypeSet &Set, Module &SrcM,
426 DiagnosticHandlerFunction DiagnosticHandler, unsigned Flags,
427 const FunctionInfoIndex *Index = nullptr,
428 DenseSet<const GlobalValue *> *FuncToImport = nullptr)
429 : DstM(DstM), SrcM(SrcM), TypeMap(Set), ValMaterializer(this),
430 DiagnosticHandler(DiagnosticHandler), Flags(Flags), ImportIndex(Index),
431 ImportFunction(FuncToImport) {
432 assert((ImportIndex || !ImportFunction) &&
433 "Expect a FunctionInfoIndex when importing");
434 // If we have a FunctionInfoIndex but no function to import,
435 // then this is the primary module being compiled in a ThinLTO
436 // backend compilation, and we need to see if it has functions that
437 // may be exported to another backend compilation.
438 if (ImportIndex && !ImportFunction)
439 HasExportedFunctions = ImportIndex->hasExportedFunctions(&SrcM);
443 Value *materializeDeclFor(Value *V);
444 void materializeInitFor(GlobalValue *New, GlobalValue *Old);
447 bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
448 bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
449 bool shouldInternalizeLinkedSymbols() {
450 return Flags & Linker::InternalizeLinkedSymbols;
453 /// Handles cloning of a global values from the source module into
454 /// the destination module, including setting the attributes and visibility.
455 GlobalValue *copyGlobalValueProto(TypeMapTy &TypeMap, const GlobalValue *SGV,
456 const GlobalValue *DGV, bool ForDefinition);
458 /// Check if we should promote the given local value to global scope.
459 bool doPromoteLocalToGlobal(const GlobalValue *SGV);
461 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
462 const GlobalValue &Src);
464 /// Helper method for setting a message and returning an error code.
465 bool emitError(const Twine &Message) {
466 DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
471 void emitWarning(const Twine &Message) {
472 DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
475 bool getComdatLeader(Module &M, StringRef ComdatName,
476 const GlobalVariable *&GVar);
477 bool computeResultingSelectionKind(StringRef ComdatName,
478 Comdat::SelectionKind Src,
479 Comdat::SelectionKind Dst,
480 Comdat::SelectionKind &Result,
482 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
484 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
486 // Keep track of the global value members of each comdat in source.
487 DenseMap<const Comdat *, std::vector<GlobalValue *>> ComdatMembers;
489 /// Given a global in the source module, return the global in the
490 /// destination module that is being linked to, if any.
491 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
492 // If the source has no name it can't link. If it has local linkage,
493 // there is no name match-up going on.
494 if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(getLinkage(SrcGV)))
497 // Otherwise see if we have a match in the destination module's symtab.
498 GlobalValue *DGV = DstM.getNamedValue(getName(SrcGV));
502 // If we found a global with the same name in the dest module, but it has
503 // internal linkage, we are really not doing any linkage here.
504 if (DGV->hasLocalLinkage())
507 // Otherwise, we do in fact link to the destination global.
511 void computeTypeMapping();
513 void upgradeMismatchedGlobalArray(StringRef Name);
514 void upgradeMismatchedGlobals();
516 bool linkIfNeeded(GlobalValue &GV);
517 bool linkAppendingVarProto(GlobalVariable *DstGV,
518 const GlobalVariable *SrcGV);
520 bool linkGlobalValueProto(GlobalValue *GV);
521 bool linkModuleFlagsMetadata();
523 void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
524 bool linkFunctionBody(Function &Dst, Function &Src);
525 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
526 bool linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
528 /// Functions that take care of cloning a specific global value type
529 /// into the destination module.
530 GlobalVariable *copyGlobalVariableProto(TypeMapTy &TypeMap,
531 const GlobalVariable *SGVar);
532 Function *copyFunctionProto(TypeMapTy &TypeMap, const Function *SF);
533 GlobalValue *copyGlobalAliasProto(TypeMapTy &TypeMap, const GlobalAlias *SGA);
535 /// Helper methods to check if we are importing from or potentially
536 /// exporting from the current source module.
537 bool isPerformingImport() { return ImportFunction != nullptr; }
538 bool isModuleExporting() { return HasExportedFunctions; }
540 /// If we are importing from the source module, checks if we should
541 /// import SGV as a definition, otherwise import as a declaration.
542 bool doImportAsDefinition(const GlobalValue *SGV);
544 /// Get the name for SGV that should be used in the linked destination
545 /// module. Specifically, this handles the case where we need to rename
546 /// a local that is being promoted to global scope.
547 std::string getName(const GlobalValue *SGV);
549 /// Get the new linkage for SGV that should be used in the linked destination
550 /// module. Specifically, for ThinLTO importing or exporting it may need
552 GlobalValue::LinkageTypes getLinkage(const GlobalValue *SGV);
554 /// Copies the necessary global value attributes and name from the source
555 /// to the newly cloned global value.
556 void copyGVAttributes(GlobalValue *NewGV, const GlobalValue *SrcGV);
558 /// Updates the visibility for the new global cloned from the source
559 /// and, if applicable, linked with an existing destination global.
560 /// Handles visibility change required for promoted locals.
561 void setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
562 const GlobalValue *DGV = nullptr);
564 void linkNamedMDNodes();
568 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
569 /// table. This is good for all clients except for us. Go through the trouble
570 /// to force this back.
571 static void forceRenaming(GlobalValue *GV, StringRef Name) {
572 // If the global doesn't force its name or if it already has the right name,
573 // there is nothing for us to do.
574 // Note that any required local to global promotion should already be done,
575 // so promoted locals will not skip this handling as their linkage is no
577 if (GV->hasLocalLinkage() || GV->getName() == Name)
580 Module *M = GV->getParent();
582 // If there is a conflict, rename the conflict.
583 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
584 GV->takeName(ConflictGV);
585 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
586 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
588 GV->setName(Name); // Force the name back
592 /// copy additional attributes (those not needed to construct a GlobalValue)
593 /// from the SrcGV to the DestGV.
594 void ModuleLinker::copyGVAttributes(GlobalValue *NewGV,
595 const GlobalValue *SrcGV) {
596 auto *GA = dyn_cast<GlobalAlias>(SrcGV);
597 if (GA && !dyn_cast<GlobalAlias>(NewGV)) {
598 // FIXME: this is likelly bogus:
599 NewGV->copyAttributesFrom(GA->getBaseObject());
601 NewGV->copyAttributesFrom(SrcGV);
602 forceRenaming(NewGV, getName(SrcGV));
605 bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
606 if (!isPerformingImport())
608 auto *GA = dyn_cast<GlobalAlias>(SGV);
610 if (GA->hasWeakAnyLinkage())
612 const GlobalObject *GO = GA->getBaseObject();
613 if (!GO->hasLinkOnceODRLinkage())
615 return doImportAsDefinition(GO);
617 // Always import GlobalVariable definitions, except for the special
618 // case of WeakAny which are imported as ExternalWeak declarations
619 // (see comments in ModuleLinker::getLinkage). The linkage changes
620 // described in ModuleLinker::getLinkage ensure the correct behavior (e.g.
621 // global variables with external linkage are transformed to
622 // available_externally definitions, which are ultimately turned into
623 // declarations after the EliminateAvailableExternally pass).
624 if (isa<GlobalVariable>(SGV) && !SGV->isDeclaration() &&
625 !SGV->hasWeakAnyLinkage())
627 // Only import the function requested for importing.
628 auto *SF = dyn_cast<Function>(SGV);
629 if (SF && ImportFunction->count(SF))
635 bool ModuleLinker::doPromoteLocalToGlobal(const GlobalValue *SGV) {
636 assert(SGV->hasLocalLinkage());
637 // Both the imported references and the original local variable must
639 if (!isPerformingImport() && !isModuleExporting())
642 // Local const variables never need to be promoted unless they are address
643 // taken. The imported uses can simply use the clone created in this module.
644 // For now we are conservative in determining which variables are not
645 // address taken by checking the unnamed addr flag. To be more aggressive,
646 // the address taken information must be checked earlier during parsing
647 // of the module and recorded in the function index for use when importing
649 auto *GVar = dyn_cast<GlobalVariable>(SGV);
650 if (GVar && GVar->isConstant() && GVar->hasUnnamedAddr())
653 // Eventually we only need to promote functions in the exporting module that
654 // are referenced by a potentially exported function (i.e. one that is in the
659 std::string ModuleLinker::getName(const GlobalValue *SGV) {
660 // For locals that must be promoted to global scope, ensure that
661 // the promoted name uniquely identifies the copy in the original module,
662 // using the ID assigned during combined index creation. When importing,
663 // we rename all locals (not just those that are promoted) in order to
664 // avoid naming conflicts between locals imported from different modules.
665 if (SGV->hasLocalLinkage() &&
666 (doPromoteLocalToGlobal(SGV) || isPerformingImport()))
667 return FunctionInfoIndex::getGlobalNameForLocal(
669 ImportIndex->getModuleId(SGV->getParent()->getModuleIdentifier()));
670 return SGV->getName();
673 GlobalValue::LinkageTypes ModuleLinker::getLinkage(const GlobalValue *SGV) {
674 // Any local variable that is referenced by an exported function needs
675 // to be promoted to global scope. Since we don't currently know which
676 // functions reference which local variables/functions, we must treat
677 // all as potentially exported if this module is exporting anything.
678 if (isModuleExporting()) {
679 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
680 return GlobalValue::ExternalLinkage;
681 return SGV->getLinkage();
684 // Otherwise, if we aren't importing, no linkage change is needed.
685 if (!isPerformingImport())
686 return SGV->getLinkage();
688 switch (SGV->getLinkage()) {
689 case GlobalValue::ExternalLinkage:
690 // External defnitions are converted to available_externally
691 // definitions upon import, so that they are available for inlining
692 // and/or optimization, but are turned into declarations later
693 // during the EliminateAvailableExternally pass.
694 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
695 return GlobalValue::AvailableExternallyLinkage;
696 // An imported external declaration stays external.
697 return SGV->getLinkage();
699 case GlobalValue::AvailableExternallyLinkage:
700 // An imported available_externally definition converts
701 // to external if imported as a declaration.
702 if (!doImportAsDefinition(SGV))
703 return GlobalValue::ExternalLinkage;
704 // An imported available_externally declaration stays that way.
705 return SGV->getLinkage();
707 case GlobalValue::LinkOnceAnyLinkage:
708 case GlobalValue::LinkOnceODRLinkage:
709 // These both stay the same when importing the definition.
710 // The ThinLTO pass will eventually force-import their definitions.
711 return SGV->getLinkage();
713 case GlobalValue::WeakAnyLinkage:
714 // Can't import weak_any definitions correctly, or we might change the
715 // program semantics, since the linker will pick the first weak_any
716 // definition and importing would change the order they are seen by the
717 // linker. The module linking caller needs to enforce this.
718 assert(!doImportAsDefinition(SGV));
719 // If imported as a declaration, it becomes external_weak.
720 return GlobalValue::ExternalWeakLinkage;
722 case GlobalValue::WeakODRLinkage:
723 // For weak_odr linkage, there is a guarantee that all copies will be
724 // equivalent, so the issue described above for weak_any does not exist,
725 // and the definition can be imported. It can be treated similarly
726 // to an imported externally visible global value.
727 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
728 return GlobalValue::AvailableExternallyLinkage;
730 return GlobalValue::ExternalLinkage;
732 case GlobalValue::AppendingLinkage:
733 // It would be incorrect to import an appending linkage variable,
734 // since it would cause global constructors/destructors to be
735 // executed multiple times. This should have already been handled
736 // by linkGlobalValueProto.
737 llvm_unreachable("Cannot import appending linkage variable");
739 case GlobalValue::InternalLinkage:
740 case GlobalValue::PrivateLinkage:
741 // If we are promoting the local to global scope, it is handled
742 // similarly to a normal externally visible global.
743 if (doPromoteLocalToGlobal(SGV)) {
744 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
745 return GlobalValue::AvailableExternallyLinkage;
747 return GlobalValue::ExternalLinkage;
749 // A non-promoted imported local definition stays local.
750 // The ThinLTO pass will eventually force-import their definitions.
751 return SGV->getLinkage();
753 case GlobalValue::ExternalWeakLinkage:
754 // External weak doesn't apply to definitions, must be a declaration.
755 assert(!doImportAsDefinition(SGV));
756 // Linkage stays external_weak.
757 return SGV->getLinkage();
759 case GlobalValue::CommonLinkage:
760 // Linkage stays common on definitions.
761 // The ThinLTO pass will eventually force-import their definitions.
762 return SGV->getLinkage();
765 llvm_unreachable("unknown linkage type");
768 /// Loop through the global variables in the src module and merge them into the
771 ModuleLinker::copyGlobalVariableProto(TypeMapTy &TypeMap,
772 const GlobalVariable *SGVar) {
773 // No linking to be performed or linking from the source: simply create an
774 // identical version of the symbol over in the dest module... the
775 // initializer will be filled in later by LinkGlobalInits.
776 GlobalVariable *NewDGV =
777 new GlobalVariable(DstM, TypeMap.get(SGVar->getType()->getElementType()),
778 SGVar->isConstant(), GlobalValue::ExternalLinkage,
779 /*init*/ nullptr, getName(SGVar),
780 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
781 SGVar->getType()->getAddressSpace());
786 /// Link the function in the source module into the destination module if
787 /// needed, setting up mapping information.
788 Function *ModuleLinker::copyFunctionProto(TypeMapTy &TypeMap,
789 const Function *SF) {
790 // If there is no linkage to be performed or we are linking from the source,
792 return Function::Create(TypeMap.get(SF->getFunctionType()),
793 GlobalValue::ExternalLinkage, getName(SF), &DstM);
796 /// Set up prototypes for any aliases that come over from the source module.
797 GlobalValue *ModuleLinker::copyGlobalAliasProto(TypeMapTy &TypeMap,
798 const GlobalAlias *SGA) {
799 // If we are importing and encounter a weak_any alias, or an alias to
800 // an object being imported as a declaration, we must import the alias
801 // as a declaration as well, which involves converting it to a non-alias.
802 // See comments in ModuleLinker::getLinkage for why we cannot import
803 // weak_any defintions.
804 if (isPerformingImport() && !doImportAsDefinition(SGA)) {
805 // Need to convert to declaration. All aliases must be definitions.
806 const GlobalValue *GVal = SGA->getBaseObject();
808 if (auto *GVar = dyn_cast<GlobalVariable>(GVal))
809 NewGV = copyGlobalVariableProto(TypeMap, GVar);
811 auto *F = dyn_cast<Function>(GVal);
813 NewGV = copyFunctionProto(TypeMap, F);
815 // Set the linkage to External or ExternalWeak (see comments in
816 // ModuleLinker::getLinkage for why WeakAny is converted to ExternalWeak).
817 if (SGA->hasWeakAnyLinkage())
818 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
820 NewGV->setLinkage(GlobalValue::ExternalLinkage);
823 // If there is no linkage to be performed or we're linking from the source,
825 auto *Ty = TypeMap.get(SGA->getValueType());
826 return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
827 GlobalValue::ExternalLinkage, getName(SGA), &DstM);
830 static GlobalValue::VisibilityTypes
831 getMinVisibility(GlobalValue::VisibilityTypes A,
832 GlobalValue::VisibilityTypes B) {
833 if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
834 return GlobalValue::HiddenVisibility;
835 if (A == GlobalValue::ProtectedVisibility ||
836 B == GlobalValue::ProtectedVisibility)
837 return GlobalValue::ProtectedVisibility;
838 return GlobalValue::DefaultVisibility;
841 void ModuleLinker::setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
842 const GlobalValue *DGV) {
843 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
845 Visibility = getMinVisibility(DGV->getVisibility(), Visibility);
846 // For promoted locals, mark them hidden so that they can later be
847 // stripped from the symbol table to reduce bloat.
848 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
849 Visibility = GlobalValue::HiddenVisibility;
850 NewGV->setVisibility(Visibility);
853 GlobalValue *ModuleLinker::copyGlobalValueProto(TypeMapTy &TypeMap,
854 const GlobalValue *SGV,
855 const GlobalValue *DGV,
856 bool ForDefinition) {
858 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
859 NewGV = copyGlobalVariableProto(TypeMap, SGVar);
860 } else if (auto *SF = dyn_cast<Function>(SGV)) {
861 NewGV = copyFunctionProto(TypeMap, SF);
864 NewGV = copyGlobalAliasProto(TypeMap, cast<GlobalAlias>(SGV));
866 NewGV = new GlobalVariable(
867 DstM, TypeMap.get(SGV->getType()->getElementType()),
868 /*isConstant*/ false, GlobalValue::ExternalLinkage,
869 /*init*/ nullptr, getName(SGV),
870 /*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
871 SGV->getType()->getAddressSpace());
875 NewGV->setLinkage(getLinkage(SGV));
876 else if (SGV->hasAvailableExternallyLinkage() || SGV->hasWeakLinkage() ||
877 SGV->hasLinkOnceLinkage())
878 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
880 copyGVAttributes(NewGV, SGV);
881 setVisibility(NewGV, SGV, DGV);
885 Value *ValueMaterializerTy::materializeDeclFor(Value *V) {
886 return ModLinker->materializeDeclFor(V);
889 Value *ModuleLinker::materializeDeclFor(Value *V) {
890 auto *SGV = dyn_cast<GlobalValue>(V);
894 // If we are done linking global value bodies (i.e. we are performing
895 // metadata linking), don't link in the global value due to this
896 // reference, simply map it to null.
897 if (DoneLinkingBodies)
900 linkGlobalValueProto(SGV);
903 Value *Ret = ValueMap[SGV];
908 void ValueMaterializerTy::materializeInitFor(GlobalValue *New,
910 return ModLinker->materializeInitFor(New, Old);
913 void ModuleLinker::materializeInitFor(GlobalValue *New, GlobalValue *Old) {
914 if (auto *F = dyn_cast<Function>(New)) {
915 if (!F->isDeclaration())
917 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
918 if (V->hasInitializer())
921 auto *A = cast<GlobalAlias>(New);
926 if (Old->isDeclaration())
929 if (isPerformingImport() && !doImportAsDefinition(Old))
932 if (!New->hasLocalLinkage() && DoNotLinkFromSource.count(Old))
935 linkGlobalValueBody(*New, *Old);
938 bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
939 const GlobalVariable *&GVar) {
940 const GlobalValue *GVal = M.getNamedValue(ComdatName);
941 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
942 GVal = GA->getBaseObject();
944 // We cannot resolve the size of the aliasee yet.
945 return emitError("Linking COMDATs named '" + ComdatName +
946 "': COMDAT key involves incomputable alias size.");
949 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
952 "Linking COMDATs named '" + ComdatName +
953 "': GlobalVariable required for data dependent selection!");
958 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
959 Comdat::SelectionKind Src,
960 Comdat::SelectionKind Dst,
961 Comdat::SelectionKind &Result,
963 // The ability to mix Comdat::SelectionKind::Any with
964 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
965 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
966 Dst == Comdat::SelectionKind::Largest;
967 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
968 Src == Comdat::SelectionKind::Largest;
969 if (DstAnyOrLargest && SrcAnyOrLargest) {
970 if (Dst == Comdat::SelectionKind::Largest ||
971 Src == Comdat::SelectionKind::Largest)
972 Result = Comdat::SelectionKind::Largest;
974 Result = Comdat::SelectionKind::Any;
975 } else if (Src == Dst) {
978 return emitError("Linking COMDATs named '" + ComdatName +
979 "': invalid selection kinds!");
983 case Comdat::SelectionKind::Any:
987 case Comdat::SelectionKind::NoDuplicates:
988 return emitError("Linking COMDATs named '" + ComdatName +
989 "': noduplicates has been violated!");
990 case Comdat::SelectionKind::ExactMatch:
991 case Comdat::SelectionKind::Largest:
992 case Comdat::SelectionKind::SameSize: {
993 const GlobalVariable *DstGV;
994 const GlobalVariable *SrcGV;
995 if (getComdatLeader(DstM, ComdatName, DstGV) ||
996 getComdatLeader(SrcM, ComdatName, SrcGV))
999 const DataLayout &DstDL = DstM.getDataLayout();
1000 const DataLayout &SrcDL = SrcM.getDataLayout();
1002 DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
1004 SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
1005 if (Result == Comdat::SelectionKind::ExactMatch) {
1006 if (SrcGV->getInitializer() != DstGV->getInitializer())
1007 return emitError("Linking COMDATs named '" + ComdatName +
1008 "': ExactMatch violated!");
1009 LinkFromSrc = false;
1010 } else if (Result == Comdat::SelectionKind::Largest) {
1011 LinkFromSrc = SrcSize > DstSize;
1012 } else if (Result == Comdat::SelectionKind::SameSize) {
1013 if (SrcSize != DstSize)
1014 return emitError("Linking COMDATs named '" + ComdatName +
1015 "': SameSize violated!");
1016 LinkFromSrc = false;
1018 llvm_unreachable("unknown selection kind");
1027 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
1028 Comdat::SelectionKind &Result,
1029 bool &LinkFromSrc) {
1030 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
1031 StringRef ComdatName = SrcC->getName();
1032 Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
1033 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
1035 if (DstCI == ComdatSymTab.end()) {
1036 // Use the comdat if it is only available in one of the modules.
1042 const Comdat *DstC = &DstCI->second;
1043 Comdat::SelectionKind DSK = DstC->getSelectionKind();
1044 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
1048 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
1049 const GlobalValue &Dest,
1050 const GlobalValue &Src) {
1051 // Should we unconditionally use the Src?
1052 if (shouldOverrideFromSrc()) {
1057 // We always have to add Src if it has appending linkage.
1058 if (Src.hasAppendingLinkage()) {
1059 // Caller should have already determined that we can't link from source
1060 // when importing (see comments in linkGlobalValueProto).
1061 assert(!isPerformingImport());
1066 bool SrcIsDeclaration = Src.isDeclarationForLinker();
1067 bool DestIsDeclaration = Dest.isDeclarationForLinker();
1069 if (isPerformingImport()) {
1070 if (isa<Function>(&Src)) {
1071 // For functions, LinkFromSrc iff this is the function requested
1072 // for importing. For variables, decide below normally.
1073 LinkFromSrc = ImportFunction->count(&Src);
1077 // Check if this is an alias with an already existing definition
1078 // in Dest, which must have come from a prior importing pass from
1079 // the same Src module. Unlike imported function and variable
1080 // definitions, which are imported as available_externally and are
1081 // not definitions for the linker, that is not a valid linkage for
1082 // imported aliases which must be definitions. Simply use the existing
1084 if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
1085 assert(isa<GlobalAlias>(&Dest));
1086 LinkFromSrc = false;
1091 if (SrcIsDeclaration) {
1092 // If Src is external or if both Src & Dest are external.. Just link the
1093 // external globals, we aren't adding anything.
1094 if (Src.hasDLLImportStorageClass()) {
1095 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
1096 LinkFromSrc = DestIsDeclaration;
1099 // If the Dest is weak, use the source linkage.
1100 LinkFromSrc = Dest.hasExternalWeakLinkage();
1104 if (DestIsDeclaration) {
1105 // If Dest is external but Src is not:
1110 if (Src.hasCommonLinkage()) {
1111 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
1116 if (!Dest.hasCommonLinkage()) {
1117 LinkFromSrc = false;
1121 const DataLayout &DL = Dest.getParent()->getDataLayout();
1122 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
1123 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
1124 LinkFromSrc = SrcSize > DestSize;
1128 if (Src.isWeakForLinker()) {
1129 assert(!Dest.hasExternalWeakLinkage());
1130 assert(!Dest.hasAvailableExternallyLinkage());
1132 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
1137 LinkFromSrc = false;
1141 if (Dest.isWeakForLinker()) {
1142 assert(Src.hasExternalLinkage());
1147 assert(!Src.hasExternalWeakLinkage());
1148 assert(!Dest.hasExternalWeakLinkage());
1149 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
1150 "Unexpected linkage type!");
1151 return emitError("Linking globals named '" + Src.getName() +
1152 "': symbol multiply defined!");
1155 /// Loop over all of the linked values to compute type mappings. For example,
1156 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
1157 /// types 'Foo' but one got renamed when the module was loaded into the same
1159 void ModuleLinker::computeTypeMapping() {
1160 for (GlobalValue &SGV : SrcM.globals()) {
1161 GlobalValue *DGV = getLinkedToGlobal(&SGV);
1165 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
1166 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1170 // Unify the element type of appending arrays.
1171 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
1172 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
1173 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
1176 for (GlobalValue &SGV : SrcM) {
1177 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1178 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1181 for (GlobalValue &SGV : SrcM.aliases()) {
1182 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1183 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1186 // Incorporate types by name, scanning all the types in the source module.
1187 // At this point, the destination module may have a type "%foo = { i32 }" for
1188 // example. When the source module got loaded into the same LLVMContext, if
1189 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
1190 std::vector<StructType *> Types = SrcM.getIdentifiedStructTypes();
1191 for (StructType *ST : Types) {
1195 // Check to see if there is a dot in the name followed by a digit.
1196 size_t DotPos = ST->getName().rfind('.');
1197 if (DotPos == 0 || DotPos == StringRef::npos ||
1198 ST->getName().back() == '.' ||
1199 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
1202 // Check to see if the destination module has a struct with the prefix name.
1203 StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
1207 // Don't use it if this actually came from the source module. They're in
1208 // the same LLVMContext after all. Also don't use it unless the type is
1209 // actually used in the destination module. This can happen in situations
1212 // Module A Module B
1213 // -------- --------
1214 // %Z = type { %A } %B = type { %C.1 }
1215 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
1216 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
1217 // %C = type { i8* } %B.3 = type { %C.1 }
1219 // When we link Module B with Module A, the '%B' in Module B is
1220 // used. However, that would then use '%C.1'. But when we process '%C.1',
1221 // we prefer to take the '%C' version. So we are then left with both
1222 // '%C.1' and '%C' being used for the same types. This leads to some
1223 // variables using one type and some using the other.
1224 if (TypeMap.DstStructTypesSet.hasType(DST))
1225 TypeMap.addTypeMapping(DST, ST);
1228 // Now that we have discovered all of the type equivalences, get a body for
1229 // any 'opaque' types in the dest module that are now resolved.
1230 TypeMap.linkDefinedTypeBodies();
1233 static void upgradeGlobalArray(GlobalVariable *GV) {
1234 ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
1235 StructType *OldTy = cast<StructType>(ATy->getElementType());
1236 assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
1238 // Get the upgraded 3 element type.
1239 PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
1240 Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
1242 StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
1244 // Build new constants with a null third field filled in.
1245 Constant *OldInitC = GV->getInitializer();
1246 ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
1247 if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
1248 // Invalid initializer; give up.
1250 std::vector<Constant *> Initializers;
1251 if (OldInit && OldInit->getNumOperands()) {
1252 Value *Null = Constant::getNullValue(VoidPtrTy);
1253 for (Use &U : OldInit->operands()) {
1254 ConstantStruct *Init = cast<ConstantStruct>(U.get());
1255 Initializers.push_back(ConstantStruct::get(
1256 NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
1259 assert(Initializers.size() == ATy->getNumElements() &&
1260 "Failed to copy all array elements");
1262 // Replace the old GV with a new one.
1263 ATy = ArrayType::get(NewTy, Initializers.size());
1264 Constant *NewInit = ConstantArray::get(ATy, Initializers);
1265 GlobalVariable *NewGV = new GlobalVariable(
1266 *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
1267 GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
1268 GV->isExternallyInitialized());
1269 NewGV->copyAttributesFrom(GV);
1270 NewGV->takeName(GV);
1271 assert(GV->use_empty() && "program cannot use initializer list");
1272 GV->eraseFromParent();
1275 void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
1276 // Look for the global arrays.
1277 auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM.getNamedValue(Name));
1280 auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM.getNamedValue(Name));
1284 // Check if the types already match.
1285 auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
1287 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
1291 // Grab the element types. We can only upgrade an array of a two-field
1292 // struct. Only bother if the other one has three-fields.
1293 auto *DstEltTy = cast<StructType>(DstTy->getElementType());
1294 auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
1295 if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
1296 upgradeGlobalArray(DstGV);
1299 if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
1300 upgradeGlobalArray(SrcGV);
1302 // We can't upgrade any other differences.
1305 void ModuleLinker::upgradeMismatchedGlobals() {
1306 upgradeMismatchedGlobalArray("llvm.global_ctors");
1307 upgradeMismatchedGlobalArray("llvm.global_dtors");
1310 static void getArrayElements(const Constant *C,
1311 SmallVectorImpl<Constant *> &Dest) {
1312 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1314 for (unsigned i = 0; i != NumElements; ++i)
1315 Dest.push_back(C->getAggregateElement(i));
1318 /// If there were any appending global variables, link them together now.
1319 /// Return true on error.
1320 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
1321 const GlobalVariable *SrcGV) {
1323 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
1324 Type *EltTy = SrcTy->getElementType();
1327 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
1329 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
1331 "Linking globals named '" + SrcGV->getName() +
1332 "': can only link appending global with another appending global!");
1334 // Check to see that they two arrays agree on type.
1335 if (EltTy != DstTy->getElementType())
1336 return emitError("Appending variables with different element types!");
1337 if (DstGV->isConstant() != SrcGV->isConstant())
1338 return emitError("Appending variables linked with different const'ness!");
1340 if (DstGV->getAlignment() != SrcGV->getAlignment())
1342 "Appending variables with different alignment need to be linked!");
1344 if (DstGV->getVisibility() != SrcGV->getVisibility())
1346 "Appending variables with different visibility need to be linked!");
1348 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
1350 "Appending variables with different unnamed_addr need to be linked!");
1352 if (StringRef(DstGV->getSection()) != SrcGV->getSection())
1354 "Appending variables with different section name need to be linked!");
1357 SmallVector<Constant *, 16> DstElements;
1359 getArrayElements(DstGV->getInitializer(), DstElements);
1361 SmallVector<Constant *, 16> SrcElements;
1362 getArrayElements(SrcGV->getInitializer(), SrcElements);
1364 StringRef Name = SrcGV->getName();
1365 bool IsNewStructor =
1366 (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1367 cast<StructType>(EltTy)->getNumElements() == 3;
1370 std::remove_if(SrcElements.begin(), SrcElements.end(),
1371 [this](Constant *E) {
1372 auto *Key = dyn_cast<GlobalValue>(
1373 E->getAggregateElement(2)->stripPointerCasts());
1374 return DoNotLinkFromSource.count(Key);
1377 uint64_t NewSize = DstElements.size() + SrcElements.size();
1378 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
1380 // Create the new global variable.
1381 GlobalVariable *NG = new GlobalVariable(
1382 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
1383 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
1384 SrcGV->getType()->getAddressSpace());
1386 // Propagate alignment, visibility and section info.
1387 copyGVAttributes(NG, SrcGV);
1389 // Replace any uses of the two global variables with uses of the new
1391 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
1393 for (auto *V : SrcElements) {
1394 DstElements.push_back(
1395 MapValue(V, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1398 NG->setInitializer(ConstantArray::get(NewType, DstElements));
1401 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
1402 DstGV->eraseFromParent();
1408 bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
1409 GlobalValue *DGV = getLinkedToGlobal(SGV);
1411 // Handle the ultra special appending linkage case first.
1412 assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
1413 if (SGV->hasAppendingLinkage() && isPerformingImport()) {
1414 // Don't want to append to global_ctors list, for example, when we
1415 // are importing for ThinLTO, otherwise the global ctors and dtors
1416 // get executed multiple times for local variables (the latter causing
1418 DoNotLinkFromSource.insert(SGV);
1421 if (SGV->hasAppendingLinkage())
1422 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
1423 cast<GlobalVariable>(SGV));
1425 bool LinkFromSrc = true;
1426 Comdat *C = nullptr;
1427 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
1429 if (const Comdat *SC = SGV->getComdat()) {
1430 Comdat::SelectionKind SK;
1431 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1432 C = DstM.getOrInsertComdat(SC->getName());
1433 C->setSelectionKind(SK);
1434 if (SGV->hasInternalLinkage())
1437 if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1442 // Track the source global so that we don't attempt to copy it over when
1443 // processing global initializers.
1444 DoNotLinkFromSource.insert(SGV);
1447 // Make sure to remember this mapping.
1449 ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
1453 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1456 if (!LinkFromSrc && DGV) {
1458 // When linking from source we setVisibility from copyGlobalValueProto.
1459 setVisibility(NewGV, SGV, DGV);
1461 NewGV = copyGlobalValueProto(TypeMap, SGV, DGV, LinkFromSrc);
1463 if (isPerformingImport() && !doImportAsDefinition(SGV))
1464 DoNotLinkFromSource.insert(SGV);
1467 NewGV->setUnnamedAddr(HasUnnamedAddr);
1469 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1470 if (C && LinkFromSrc)
1471 NewGO->setComdat(C);
1473 if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1474 NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
1477 if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) {
1478 auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV);
1479 auto *SGVar = dyn_cast<GlobalVariable>(SGV);
1480 if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() &&
1481 (!DGVar->isConstant() || !SGVar->isConstant()))
1482 NewGVar->setConstant(false);
1485 // Make sure to remember this mapping.
1488 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
1489 DGV->eraseFromParent();
1491 ValueMap[SGV] = NewGV;
1497 /// Update the initializers in the Dest module now that all globals that may be
1498 /// referenced are in Dest.
1499 void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
1500 // Figure out what the initializer looks like in the dest module.
1501 Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap,
1502 RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1505 /// Copy the source function over into the dest function and fix up references
1506 /// to values. At this point we know that Dest is an external function, and
1507 /// that Src is not.
1508 bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) {
1509 assert(Dst.isDeclaration() && !Src.isDeclaration());
1511 // Materialize if needed.
1512 if (std::error_code EC = Src.materialize())
1513 return emitError(EC.message());
1515 // Link in the prefix data.
1516 if (Src.hasPrefixData())
1517 Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap,
1518 RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1520 // Link in the prologue data.
1521 if (Src.hasPrologueData())
1522 Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap,
1523 RF_MoveDistinctMDs, &TypeMap,
1526 // Link in the personality function.
1527 if (Src.hasPersonalityFn())
1528 Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap,
1529 RF_MoveDistinctMDs, &TypeMap,
1532 // Go through and convert function arguments over, remembering the mapping.
1533 Function::arg_iterator DI = Dst.arg_begin();
1534 for (Argument &Arg : Src.args()) {
1535 DI->setName(Arg.getName()); // Copy the name over.
1537 // Add a mapping to our mapping.
1538 ValueMap[&Arg] = &*DI;
1542 // Copy over the metadata attachments.
1543 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1544 Src.getAllMetadata(MDs);
1545 for (const auto &I : MDs)
1546 Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, RF_MoveDistinctMDs,
1547 &TypeMap, &ValMaterializer));
1549 // Splice the body of the source function into the dest function.
1550 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
1552 // At this point, all of the instructions and values of the function are now
1553 // copied over. The only problem is that they are still referencing values in
1554 // the Source function as operands. Loop through all of the operands of the
1555 // functions and patch them up to point to the local versions.
1556 for (BasicBlock &BB : Dst)
1557 for (Instruction &I : BB)
1558 RemapInstruction(&I, ValueMap,
1559 RF_IgnoreMissingEntries | RF_MoveDistinctMDs, &TypeMap,
1562 // There is no need to map the arguments anymore.
1563 for (Argument &Arg : Src.args())
1564 ValueMap.erase(&Arg);
1566 Src.dematerialize();
1570 void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1571 Constant *Aliasee = Src.getAliasee();
1572 Constant *Val = MapValue(Aliasee, ValueMap, RF_MoveDistinctMDs, &TypeMap,
1574 Dst.setAliasee(Val);
1577 bool ModuleLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
1578 if (const Comdat *SC = Src.getComdat()) {
1579 // To ensure that we don't generate an incomplete comdat group,
1580 // we must materialize and map in any other members that are not
1581 // yet materialized in Dst, which also ensures their definitions
1582 // are linked in. Otherwise, linkonce and other lazy linked GVs will
1583 // not be materialized if they aren't referenced.
1584 for (auto *SGV : ComdatMembers[SC]) {
1585 auto *DGV = cast_or_null<GlobalValue>(ValueMap[SGV]);
1586 if (DGV && !DGV->isDeclaration())
1588 MapValue(SGV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1591 if (shouldInternalizeLinkedSymbols())
1592 if (auto *DGV = dyn_cast<GlobalValue>(&Dst))
1593 DGV->setLinkage(GlobalValue::InternalLinkage);
1594 if (auto *F = dyn_cast<Function>(&Src))
1595 return linkFunctionBody(cast<Function>(Dst), *F);
1596 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1597 linkGlobalInit(cast<GlobalVariable>(Dst), *GVar);
1600 linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
1604 /// Insert all of the named MDNodes in Src into the Dest module.
1605 void ModuleLinker::linkNamedMDNodes() {
1606 const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1607 for (const NamedMDNode &NMD : SrcM.named_metadata()) {
1608 // Don't link module flags here. Do them separately.
1609 if (&NMD == SrcModFlags)
1611 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1612 // Add Src elements into Dest node.
1613 for (const MDNode *op : NMD.operands())
1614 DestNMD->addOperand(MapMetadata(
1615 op, ValueMap, RF_MoveDistinctMDs | RF_NullMapMissingGlobalValues,
1616 &TypeMap, &ValMaterializer));
1620 /// Merge the linker flags in Src into the Dest module.
1621 bool ModuleLinker::linkModuleFlagsMetadata() {
1622 // If the source module has no module flags, we are done.
1623 const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1627 // If the destination module doesn't have module flags yet, then just copy
1628 // over the source module's flags.
1629 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1630 if (DstModFlags->getNumOperands() == 0) {
1631 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1632 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1637 // First build a map of the existing module flags and requirements.
1638 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1639 SmallSetVector<MDNode *, 16> Requirements;
1640 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1641 MDNode *Op = DstModFlags->getOperand(I);
1642 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1643 MDString *ID = cast<MDString>(Op->getOperand(1));
1645 if (Behavior->getZExtValue() == Module::Require) {
1646 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1648 Flags[ID] = std::make_pair(Op, I);
1652 // Merge in the flags from the source module, and also collect its set of
1654 bool HasErr = false;
1655 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1656 MDNode *SrcOp = SrcModFlags->getOperand(I);
1657 ConstantInt *SrcBehavior =
1658 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1659 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1662 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1663 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1665 // If this is a requirement, add it and continue.
1666 if (SrcBehaviorValue == Module::Require) {
1667 // If the destination module does not already have this requirement, add
1669 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1670 DstModFlags->addOperand(SrcOp);
1675 // If there is no existing flag with this ID, just add it.
1677 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1678 DstModFlags->addOperand(SrcOp);
1682 // Otherwise, perform a merge.
1683 ConstantInt *DstBehavior =
1684 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1685 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1687 // If either flag has override behavior, handle it first.
1688 if (DstBehaviorValue == Module::Override) {
1689 // Diagnose inconsistent flags which both have override behavior.
1690 if (SrcBehaviorValue == Module::Override &&
1691 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1692 HasErr |= emitError("linking module flags '" + ID->getString() +
1693 "': IDs have conflicting override values");
1696 } else if (SrcBehaviorValue == Module::Override) {
1697 // Update the destination flag to that of the source.
1698 DstModFlags->setOperand(DstIndex, SrcOp);
1699 Flags[ID].first = SrcOp;
1703 // Diagnose inconsistent merge behavior types.
1704 if (SrcBehaviorValue != DstBehaviorValue) {
1705 HasErr |= emitError("linking module flags '" + ID->getString() +
1706 "': IDs have conflicting behaviors");
1710 auto replaceDstValue = [&](MDNode *New) {
1711 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1712 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1713 DstModFlags->setOperand(DstIndex, Flag);
1714 Flags[ID].first = Flag;
1717 // Perform the merge for standard behavior types.
1718 switch (SrcBehaviorValue) {
1719 case Module::Require:
1720 case Module::Override:
1721 llvm_unreachable("not possible");
1722 case Module::Error: {
1723 // Emit an error if the values differ.
1724 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1725 HasErr |= emitError("linking module flags '" + ID->getString() +
1726 "': IDs have conflicting values");
1730 case Module::Warning: {
1731 // Emit a warning if the values differ.
1732 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1733 emitWarning("linking module flags '" + ID->getString() +
1734 "': IDs have conflicting values");
1738 case Module::Append: {
1739 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1740 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1741 SmallVector<Metadata *, 8> MDs;
1742 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1743 MDs.append(DstValue->op_begin(), DstValue->op_end());
1744 MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1746 replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1749 case Module::AppendUnique: {
1750 SmallSetVector<Metadata *, 16> Elts;
1751 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1752 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1753 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1754 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1756 replaceDstValue(MDNode::get(DstM.getContext(),
1757 makeArrayRef(Elts.begin(), Elts.end())));
1763 // Check all of the requirements.
1764 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1765 MDNode *Requirement = Requirements[I];
1766 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1767 Metadata *ReqValue = Requirement->getOperand(1);
1769 MDNode *Op = Flags[Flag].first;
1770 if (!Op || Op->getOperand(2) != ReqValue) {
1771 HasErr |= emitError("linking module flags '" + Flag->getString() +
1772 "': does not have the required value");
1780 // This function returns true if the triples match.
1781 static bool triplesMatch(const Triple &T0, const Triple &T1) {
1782 // If vendor is apple, ignore the version number.
1783 if (T0.getVendor() == Triple::Apple)
1784 return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1785 T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1790 // This function returns the merged triple.
1791 static std::string mergeTriples(const Triple &SrcTriple,
1792 const Triple &DstTriple) {
1793 // If vendor is apple, pick the triple with the larger version number.
1794 if (SrcTriple.getVendor() == Triple::Apple)
1795 if (DstTriple.isOSVersionLT(SrcTriple))
1796 return SrcTriple.str();
1798 return DstTriple.str();
1801 bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
1802 GlobalValue *DGV = getLinkedToGlobal(&GV);
1804 if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
1807 if (DGV && !GV.hasLocalLinkage()) {
1808 GlobalValue::VisibilityTypes Visibility =
1809 getMinVisibility(DGV->getVisibility(), GV.getVisibility());
1810 DGV->setVisibility(Visibility);
1811 GV.setVisibility(Visibility);
1814 if (const Comdat *SC = GV.getComdat()) {
1816 Comdat::SelectionKind SK;
1817 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1819 DoNotLinkFromSource.insert(&GV);
1824 if (!DGV && !shouldOverrideFromSrc() &&
1825 (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
1826 GV.hasAvailableExternallyLinkage())) {
1829 MapValue(&GV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1833 bool ModuleLinker::run() {
1834 // Inherit the target data from the source module if the destination module
1835 // doesn't have one already.
1836 if (DstM.getDataLayout().isDefault())
1837 DstM.setDataLayout(SrcM.getDataLayout());
1839 if (SrcM.getDataLayout() != DstM.getDataLayout()) {
1840 emitWarning("Linking two modules of different data layouts: '" +
1841 SrcM.getModuleIdentifier() + "' is '" +
1842 SrcM.getDataLayoutStr() + "' whereas '" +
1843 DstM.getModuleIdentifier() + "' is '" +
1844 DstM.getDataLayoutStr() + "'\n");
1847 // Copy the target triple from the source to dest if the dest's is empty.
1848 if (DstM.getTargetTriple().empty() && !SrcM.getTargetTriple().empty())
1849 DstM.setTargetTriple(SrcM.getTargetTriple());
1851 Triple SrcTriple(SrcM.getTargetTriple()), DstTriple(DstM.getTargetTriple());
1853 if (!SrcM.getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
1854 emitWarning("Linking two modules of different target triples: " +
1855 SrcM.getModuleIdentifier() + "' is '" + SrcM.getTargetTriple() +
1856 "' whereas '" + DstM.getModuleIdentifier() + "' is '" +
1857 DstM.getTargetTriple() + "'\n");
1859 DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1861 // Append the module inline asm string.
1862 if (!SrcM.getModuleInlineAsm().empty()) {
1863 if (DstM.getModuleInlineAsm().empty())
1864 DstM.setModuleInlineAsm(SrcM.getModuleInlineAsm());
1866 DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
1867 SrcM.getModuleInlineAsm());
1870 // Loop over all of the linked values to compute type mappings.
1871 computeTypeMapping();
1873 ComdatsChosen.clear();
1874 for (const auto &SMEC : SrcM.getComdatSymbolTable()) {
1875 const Comdat &C = SMEC.getValue();
1876 if (ComdatsChosen.count(&C))
1878 Comdat::SelectionKind SK;
1880 if (getComdatResult(&C, SK, LinkFromSrc))
1882 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1885 // Upgrade mismatched global arrays.
1886 upgradeMismatchedGlobals();
1888 for (GlobalVariable &GV : SrcM.globals())
1889 if (const Comdat *SC = GV.getComdat())
1890 ComdatMembers[SC].push_back(&GV);
1892 for (Function &SF : SrcM)
1893 if (const Comdat *SC = SF.getComdat())
1894 ComdatMembers[SC].push_back(&SF);
1896 for (GlobalAlias &GA : SrcM.aliases())
1897 if (const Comdat *SC = GA.getComdat())
1898 ComdatMembers[SC].push_back(&GA);
1900 // Insert all of the globals in src into the DstM module... without linking
1901 // initializers (which could refer to functions not yet mapped over).
1902 for (GlobalVariable &GV : SrcM.globals())
1903 if (linkIfNeeded(GV))
1906 for (Function &SF : SrcM)
1907 if (linkIfNeeded(SF))
1910 for (GlobalAlias &GA : SrcM.aliases())
1911 if (linkIfNeeded(GA))
1914 for (const auto &Entry : DstM.getComdatSymbolTable()) {
1915 const Comdat &C = Entry.getValue();
1916 if (C.getSelectionKind() == Comdat::Any)
1918 const GlobalValue *GV = SrcM.getNamedValue(C.getName());
1920 MapValue(GV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1923 // Note that we are done linking global value bodies. This prevents
1924 // metadata linking from creating new references.
1925 DoneLinkingBodies = true;
1927 // Remap all of the named MDNodes in Src into the DstM module. We do this
1928 // after linking GlobalValues so that MDNodes that reference GlobalValues
1929 // are properly remapped.
1932 // Merge the module flags into the DstM module.
1933 if (linkModuleFlagsMetadata())
1939 Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1940 : ETypes(E), IsPacked(P) {}
1942 Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1943 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1945 bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1946 if (IsPacked != That.IsPacked)
1948 if (ETypes != That.ETypes)
1953 bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1954 return !this->operator==(That);
1957 StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
1958 return DenseMapInfo<StructType *>::getEmptyKey();
1961 StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
1962 return DenseMapInfo<StructType *>::getTombstoneKey();
1965 unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1966 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1970 unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1971 return getHashValue(KeyTy(ST));
1974 bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1975 const StructType *RHS) {
1976 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1978 return LHS == KeyTy(RHS);
1981 bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
1982 const StructType *RHS) {
1983 if (RHS == getEmptyKey())
1984 return LHS == getEmptyKey();
1986 if (RHS == getTombstoneKey())
1987 return LHS == getTombstoneKey();
1989 return KeyTy(LHS) == KeyTy(RHS);
1992 void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1993 assert(!Ty->isOpaque());
1994 NonOpaqueStructTypes.insert(Ty);
1997 void Linker::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1998 assert(!Ty->isOpaque());
1999 NonOpaqueStructTypes.insert(Ty);
2000 bool Removed = OpaqueStructTypes.erase(Ty);
2005 void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
2006 assert(Ty->isOpaque());
2007 OpaqueStructTypes.insert(Ty);
2011 Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
2013 Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
2014 auto I = NonOpaqueStructTypes.find_as(Key);
2015 if (I == NonOpaqueStructTypes.end())
2020 bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
2022 return OpaqueStructTypes.count(Ty);
2023 auto I = NonOpaqueStructTypes.find(Ty);
2024 if (I == NonOpaqueStructTypes.end())
2029 Linker::Linker(Module &M, DiagnosticHandlerFunction DiagnosticHandler)
2030 : Composite(M), DiagnosticHandler(DiagnosticHandler) {
2031 TypeFinder StructTypes;
2032 StructTypes.run(M, true);
2033 for (StructType *Ty : StructTypes) {
2035 IdentifiedStructTypes.addOpaque(Ty);
2037 IdentifiedStructTypes.addNonOpaque(Ty);
2041 Linker::Linker(Module &M)
2042 : Linker(M, [this](const DiagnosticInfo &DI) {
2043 Composite.getContext().diagnose(DI);
2046 bool Linker::linkInModule(Module &Src, unsigned Flags,
2047 const FunctionInfoIndex *Index,
2048 DenseSet<const GlobalValue *> *FuncToImport) {
2049 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
2050 DiagnosticHandler, Flags, Index, FuncToImport);
2051 bool RetCode = TheLinker.run();
2052 Composite.dropTriviallyDeadConstantArrays();
2056 //===----------------------------------------------------------------------===//
2057 // LinkModules entrypoint.
2058 //===----------------------------------------------------------------------===//
2060 /// This function links two modules together, with the resulting Dest module
2061 /// modified to be the composite of the two input modules. If an error occurs,
2062 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
2063 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
2064 /// relied on to be consistent.
2065 bool Linker::linkModules(Module &Dest, Module &Src,
2066 DiagnosticHandlerFunction DiagnosticHandler,
2068 Linker L(Dest, DiagnosticHandler);
2069 return L.linkInModule(Src, Flags);
2072 bool Linker::linkModules(Module &Dest, Module &Src, unsigned Flags) {
2074 return L.linkInModule(Src, Flags);
2077 //===----------------------------------------------------------------------===//
2079 //===----------------------------------------------------------------------===//
2081 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
2082 LLVMLinkerMode Unused, char **OutMessages) {
2083 Module *D = unwrap(Dest);
2084 std::string Message;
2085 raw_string_ostream Stream(Message);
2086 DiagnosticPrinterRawOStream DP(Stream);
2088 LLVMBool Result = Linker::linkModules(
2089 *D, *unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
2091 if (OutMessages && Result) {
2093 *OutMessages = strdup(Message.c_str());