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 SetVector<GlobalValue *> ValuesToLink;
397 DiagnosticHandlerFunction DiagnosticHandler;
399 /// For symbol clashes, prefer those from Src.
402 /// Function index passed into ModuleLinker for using in function
403 /// importing/exporting handling.
404 const FunctionInfoIndex *ImportIndex;
406 /// Function to import from source module, all other functions are
407 /// imported as declarations instead of definitions.
408 DenseSet<const GlobalValue *> *ImportFunction;
410 /// Set to true if the given FunctionInfoIndex contains any functions
411 /// from this source module, in which case we must conservatively assume
412 /// that any of its functions may be imported into another module
413 /// as part of a different backend compilation process.
414 bool HasExportedFunctions = false;
416 /// Set to true when all global value body linking is complete (including
417 /// lazy linking). Used to prevent metadata linking from creating new
419 bool DoneLinkingBodies = false;
421 bool HasError = false;
423 bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
424 bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
425 bool shouldInternalizeLinkedSymbols() {
426 return Flags & Linker::InternalizeLinkedSymbols;
429 /// Handles cloning of a global values from the source module into
430 /// the destination module, including setting the attributes and visibility.
431 GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
433 /// Check if we should promote the given local value to global scope.
434 bool doPromoteLocalToGlobal(const GlobalValue *SGV);
436 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
437 const GlobalValue &Src);
439 /// Helper method for setting a message and returning an error code.
440 bool emitError(const Twine &Message) {
441 DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
446 void emitWarning(const Twine &Message) {
447 DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
450 bool getComdatLeader(Module &M, StringRef ComdatName,
451 const GlobalVariable *&GVar);
452 bool computeResultingSelectionKind(StringRef ComdatName,
453 Comdat::SelectionKind Src,
454 Comdat::SelectionKind Dst,
455 Comdat::SelectionKind &Result,
457 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
459 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
461 // Keep track of the global value members of each comdat in source.
462 DenseMap<const Comdat *, std::vector<GlobalValue *>> ComdatMembers;
464 /// Given a global in the source module, return the global in the
465 /// destination module that is being linked to, if any.
466 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
467 // If the source has no name it can't link. If it has local linkage,
468 // there is no name match-up going on.
469 if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(getLinkage(SrcGV)))
472 // Otherwise see if we have a match in the destination module's symtab.
473 GlobalValue *DGV = DstM.getNamedValue(getName(SrcGV));
477 // If we found a global with the same name in the dest module, but it has
478 // internal linkage, we are really not doing any linkage here.
479 if (DGV->hasLocalLinkage())
482 // Otherwise, we do in fact link to the destination global.
486 void computeTypeMapping();
488 bool linkIfNeeded(GlobalValue &GV);
489 Constant *linkAppendingVarProto(GlobalVariable *DstGV,
490 const GlobalVariable *SrcGV);
492 Constant *linkGlobalValueProto(GlobalValue *GV);
493 bool linkModuleFlagsMetadata();
495 void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
496 bool linkFunctionBody(Function &Dst, Function &Src);
497 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
498 bool linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
500 /// Functions that take care of cloning a specific global value type
501 /// into the destination module.
502 GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
503 Function *copyFunctionProto(const Function *SF);
504 GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA);
506 /// Helper methods to check if we are importing from or potentially
507 /// exporting from the current source module.
508 bool isPerformingImport() { return ImportFunction != nullptr; }
509 bool isModuleExporting() { return HasExportedFunctions; }
511 /// If we are importing from the source module, checks if we should
512 /// import SGV as a definition, otherwise import as a declaration.
513 bool doImportAsDefinition(const GlobalValue *SGV);
515 /// Get the name for SGV that should be used in the linked destination
516 /// module. Specifically, this handles the case where we need to rename
517 /// a local that is being promoted to global scope.
518 std::string getName(const GlobalValue *SGV);
520 /// Get the new linkage for SGV that should be used in the linked destination
521 /// module. Specifically, for ThinLTO importing or exporting it may need
523 GlobalValue::LinkageTypes getLinkage(const GlobalValue *SGV);
525 /// Copies the necessary global value attributes and name from the source
526 /// to the newly cloned global value.
527 void copyGVAttributes(GlobalValue *NewGV, const GlobalValue *SrcGV);
529 /// Updates the visibility for the new global cloned from the source
530 /// and, if applicable, linked with an existing destination global.
531 /// Handles visibility change required for promoted locals.
532 void setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
533 const GlobalValue *DGV = nullptr);
535 void linkNamedMDNodes();
538 ModuleLinker(Module &DstM, Linker::IdentifiedStructTypeSet &Set, Module &SrcM,
539 DiagnosticHandlerFunction DiagnosticHandler, unsigned Flags,
540 const FunctionInfoIndex *Index = nullptr,
541 DenseSet<const GlobalValue *> *FunctionsToImport = nullptr)
542 : DstM(DstM), SrcM(SrcM), TypeMap(Set), ValMaterializer(this),
543 DiagnosticHandler(DiagnosticHandler), Flags(Flags), ImportIndex(Index),
544 ImportFunction(FunctionsToImport) {
545 assert((ImportIndex || !ImportFunction) &&
546 "Expect a FunctionInfoIndex when importing");
547 // If we have a FunctionInfoIndex but no function to import,
548 // then this is the primary module being compiled in a ThinLTO
549 // backend compilation, and we need to see if it has functions that
550 // may be exported to another backend compilation.
551 if (ImportIndex && !ImportFunction)
552 HasExportedFunctions = ImportIndex->hasExportedFunctions(SrcM);
556 Value *materializeDeclFor(Value *V);
557 void materializeInitFor(GlobalValue *New, GlobalValue *Old);
561 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
562 /// table. This is good for all clients except for us. Go through the trouble
563 /// to force this back.
564 static void forceRenaming(GlobalValue *GV, StringRef Name) {
565 // If the global doesn't force its name or if it already has the right name,
566 // there is nothing for us to do.
567 // Note that any required local to global promotion should already be done,
568 // so promoted locals will not skip this handling as their linkage is no
570 if (GV->hasLocalLinkage() || GV->getName() == Name)
573 Module *M = GV->getParent();
575 // If there is a conflict, rename the conflict.
576 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
577 GV->takeName(ConflictGV);
578 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
579 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
581 GV->setName(Name); // Force the name back
585 /// copy additional attributes (those not needed to construct a GlobalValue)
586 /// from the SrcGV to the DestGV.
587 void ModuleLinker::copyGVAttributes(GlobalValue *NewGV,
588 const GlobalValue *SrcGV) {
589 NewGV->copyAttributesFrom(SrcGV);
590 forceRenaming(NewGV, getName(SrcGV));
593 bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
594 if (!isPerformingImport())
596 auto *GA = dyn_cast<GlobalAlias>(SGV);
598 if (GA->hasWeakAnyLinkage())
600 const GlobalObject *GO = GA->getBaseObject();
601 if (!GO->hasLinkOnceODRLinkage())
603 return doImportAsDefinition(GO);
605 // Always import GlobalVariable definitions, except for the special
606 // case of WeakAny which are imported as ExternalWeak declarations
607 // (see comments in ModuleLinker::getLinkage). The linkage changes
608 // described in ModuleLinker::getLinkage ensure the correct behavior (e.g.
609 // global variables with external linkage are transformed to
610 // available_externally definitions, which are ultimately turned into
611 // declarations after the EliminateAvailableExternally pass).
612 if (isa<GlobalVariable>(SGV) && !SGV->isDeclaration() &&
613 !SGV->hasWeakAnyLinkage())
615 // Only import the function requested for importing.
616 auto *SF = dyn_cast<Function>(SGV);
617 if (SF && ImportFunction->count(SF))
623 bool ModuleLinker::doPromoteLocalToGlobal(const GlobalValue *SGV) {
624 assert(SGV->hasLocalLinkage());
625 // Both the imported references and the original local variable must
627 if (!isPerformingImport() && !isModuleExporting())
630 // Local const variables never need to be promoted unless they are address
631 // taken. The imported uses can simply use the clone created in this module.
632 // For now we are conservative in determining which variables are not
633 // address taken by checking the unnamed addr flag. To be more aggressive,
634 // the address taken information must be checked earlier during parsing
635 // of the module and recorded in the function index for use when importing
637 auto *GVar = dyn_cast<GlobalVariable>(SGV);
638 if (GVar && GVar->isConstant() && GVar->hasUnnamedAddr())
641 // Eventually we only need to promote functions in the exporting module that
642 // are referenced by a potentially exported function (i.e. one that is in the
647 std::string ModuleLinker::getName(const GlobalValue *SGV) {
648 // For locals that must be promoted to global scope, ensure that
649 // the promoted name uniquely identifies the copy in the original module,
650 // using the ID assigned during combined index creation. When importing,
651 // we rename all locals (not just those that are promoted) in order to
652 // avoid naming conflicts between locals imported from different modules.
653 if (SGV->hasLocalLinkage() &&
654 (doPromoteLocalToGlobal(SGV) || isPerformingImport()))
655 return FunctionInfoIndex::getGlobalNameForLocal(
657 ImportIndex->getModuleId(SGV->getParent()->getModuleIdentifier()));
658 return SGV->getName();
661 GlobalValue::LinkageTypes ModuleLinker::getLinkage(const GlobalValue *SGV) {
662 // Any local variable that is referenced by an exported function needs
663 // to be promoted to global scope. Since we don't currently know which
664 // functions reference which local variables/functions, we must treat
665 // all as potentially exported if this module is exporting anything.
666 if (isModuleExporting()) {
667 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
668 return GlobalValue::ExternalLinkage;
669 return SGV->getLinkage();
672 // Otherwise, if we aren't importing, no linkage change is needed.
673 if (!isPerformingImport())
674 return SGV->getLinkage();
676 switch (SGV->getLinkage()) {
677 case GlobalValue::ExternalLinkage:
678 // External defnitions are converted to available_externally
679 // definitions upon import, so that they are available for inlining
680 // and/or optimization, but are turned into declarations later
681 // during the EliminateAvailableExternally pass.
682 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
683 return GlobalValue::AvailableExternallyLinkage;
684 // An imported external declaration stays external.
685 return SGV->getLinkage();
687 case GlobalValue::AvailableExternallyLinkage:
688 // An imported available_externally definition converts
689 // to external if imported as a declaration.
690 if (!doImportAsDefinition(SGV))
691 return GlobalValue::ExternalLinkage;
692 // An imported available_externally declaration stays that way.
693 return SGV->getLinkage();
695 case GlobalValue::LinkOnceAnyLinkage:
696 case GlobalValue::LinkOnceODRLinkage:
697 // These both stay the same when importing the definition.
698 // The ThinLTO pass will eventually force-import their definitions.
699 return SGV->getLinkage();
701 case GlobalValue::WeakAnyLinkage:
702 // Can't import weak_any definitions correctly, or we might change the
703 // program semantics, since the linker will pick the first weak_any
704 // definition and importing would change the order they are seen by the
705 // linker. The module linking caller needs to enforce this.
706 assert(!doImportAsDefinition(SGV));
707 // If imported as a declaration, it becomes external_weak.
708 return GlobalValue::ExternalWeakLinkage;
710 case GlobalValue::WeakODRLinkage:
711 // For weak_odr linkage, there is a guarantee that all copies will be
712 // equivalent, so the issue described above for weak_any does not exist,
713 // and the definition can be imported. It can be treated similarly
714 // to an imported externally visible global value.
715 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
716 return GlobalValue::AvailableExternallyLinkage;
718 return GlobalValue::ExternalLinkage;
720 case GlobalValue::AppendingLinkage:
721 // It would be incorrect to import an appending linkage variable,
722 // since it would cause global constructors/destructors to be
723 // executed multiple times. This should have already been handled
724 // by linkIfNeeded, and we will assert in shouldLinkFromSource
725 // if we try to import, so we simply return AppendingLinkage here
726 // as this helper is called more widely in getLinkedToGlobal.
727 return GlobalValue::AppendingLinkage;
729 case GlobalValue::InternalLinkage:
730 case GlobalValue::PrivateLinkage:
731 // If we are promoting the local to global scope, it is handled
732 // similarly to a normal externally visible global.
733 if (doPromoteLocalToGlobal(SGV)) {
734 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
735 return GlobalValue::AvailableExternallyLinkage;
737 return GlobalValue::ExternalLinkage;
739 // A non-promoted imported local definition stays local.
740 // The ThinLTO pass will eventually force-import their definitions.
741 return SGV->getLinkage();
743 case GlobalValue::ExternalWeakLinkage:
744 // External weak doesn't apply to definitions, must be a declaration.
745 assert(!doImportAsDefinition(SGV));
746 // Linkage stays external_weak.
747 return SGV->getLinkage();
749 case GlobalValue::CommonLinkage:
750 // Linkage stays common on definitions.
751 // The ThinLTO pass will eventually force-import their definitions.
752 return SGV->getLinkage();
755 llvm_unreachable("unknown linkage type");
758 /// Loop through the global variables in the src module and merge them into the
761 ModuleLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
762 // No linking to be performed or linking from the source: simply create an
763 // identical version of the symbol over in the dest module... the
764 // initializer will be filled in later by LinkGlobalInits.
765 GlobalVariable *NewDGV =
766 new GlobalVariable(DstM, TypeMap.get(SGVar->getType()->getElementType()),
767 SGVar->isConstant(), GlobalValue::ExternalLinkage,
768 /*init*/ nullptr, getName(SGVar),
769 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
770 SGVar->getType()->getAddressSpace());
775 /// Link the function in the source module into the destination module if
776 /// needed, setting up mapping information.
777 Function *ModuleLinker::copyFunctionProto(const Function *SF) {
778 // If there is no linkage to be performed or we are linking from the source,
780 return Function::Create(TypeMap.get(SF->getFunctionType()),
781 GlobalValue::ExternalLinkage, getName(SF), &DstM);
784 /// Set up prototypes for any aliases that come over from the source module.
785 GlobalValue *ModuleLinker::copyGlobalAliasProto(const GlobalAlias *SGA) {
786 // If there is no linkage to be performed or we're linking from the source,
788 auto *Ty = TypeMap.get(SGA->getValueType());
789 return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
790 GlobalValue::ExternalLinkage, getName(SGA), &DstM);
793 static GlobalValue::VisibilityTypes
794 getMinVisibility(GlobalValue::VisibilityTypes A,
795 GlobalValue::VisibilityTypes B) {
796 if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
797 return GlobalValue::HiddenVisibility;
798 if (A == GlobalValue::ProtectedVisibility ||
799 B == GlobalValue::ProtectedVisibility)
800 return GlobalValue::ProtectedVisibility;
801 return GlobalValue::DefaultVisibility;
804 void ModuleLinker::setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
805 const GlobalValue *DGV) {
806 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
808 Visibility = getMinVisibility(DGV->getVisibility(), Visibility);
809 // For promoted locals, mark them hidden so that they can later be
810 // stripped from the symbol table to reduce bloat.
811 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
812 Visibility = GlobalValue::HiddenVisibility;
813 NewGV->setVisibility(Visibility);
816 GlobalValue *ModuleLinker::copyGlobalValueProto(const GlobalValue *SGV,
817 bool ForDefinition) {
819 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
820 NewGV = copyGlobalVariableProto(SGVar);
821 } else if (auto *SF = dyn_cast<Function>(SGV)) {
822 NewGV = copyFunctionProto(SF);
825 NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV));
827 NewGV = new GlobalVariable(
828 DstM, TypeMap.get(SGV->getType()->getElementType()),
829 /*isConstant*/ false, GlobalValue::ExternalLinkage,
830 /*init*/ nullptr, getName(SGV),
831 /*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
832 SGV->getType()->getAddressSpace());
836 NewGV->setLinkage(getLinkage(SGV));
837 else if (SGV->hasAvailableExternallyLinkage() || SGV->hasWeakLinkage() ||
838 SGV->hasLinkOnceLinkage())
839 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
841 copyGVAttributes(NewGV, SGV);
845 Value *ValueMaterializerTy::materializeDeclFor(Value *V) {
846 return ModLinker->materializeDeclFor(V);
849 Value *ModuleLinker::materializeDeclFor(Value *V) {
850 auto *SGV = dyn_cast<GlobalValue>(V);
854 return linkGlobalValueProto(SGV);
857 void ValueMaterializerTy::materializeInitFor(GlobalValue *New,
859 return ModLinker->materializeInitFor(New, Old);
862 static bool shouldLazyLink(const GlobalValue &GV) {
863 return GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
864 GV.hasAvailableExternallyLinkage();
867 void ModuleLinker::materializeInitFor(GlobalValue *New, GlobalValue *Old) {
868 if (auto *F = dyn_cast<Function>(New)) {
869 if (!F->isDeclaration())
871 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
872 if (V->hasInitializer())
875 auto *A = cast<GlobalAlias>(New);
880 if (Old->isDeclaration())
883 if (isPerformingImport() && !doImportAsDefinition(Old))
886 if (!ValuesToLink.count(Old) && !shouldLazyLink(*Old))
889 linkGlobalValueBody(*New, *Old);
892 bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
893 const GlobalVariable *&GVar) {
894 const GlobalValue *GVal = M.getNamedValue(ComdatName);
895 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
896 GVal = GA->getBaseObject();
898 // We cannot resolve the size of the aliasee yet.
899 return emitError("Linking COMDATs named '" + ComdatName +
900 "': COMDAT key involves incomputable alias size.");
903 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
906 "Linking COMDATs named '" + ComdatName +
907 "': GlobalVariable required for data dependent selection!");
912 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
913 Comdat::SelectionKind Src,
914 Comdat::SelectionKind Dst,
915 Comdat::SelectionKind &Result,
917 // The ability to mix Comdat::SelectionKind::Any with
918 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
919 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
920 Dst == Comdat::SelectionKind::Largest;
921 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
922 Src == Comdat::SelectionKind::Largest;
923 if (DstAnyOrLargest && SrcAnyOrLargest) {
924 if (Dst == Comdat::SelectionKind::Largest ||
925 Src == Comdat::SelectionKind::Largest)
926 Result = Comdat::SelectionKind::Largest;
928 Result = Comdat::SelectionKind::Any;
929 } else if (Src == Dst) {
932 return emitError("Linking COMDATs named '" + ComdatName +
933 "': invalid selection kinds!");
937 case Comdat::SelectionKind::Any:
941 case Comdat::SelectionKind::NoDuplicates:
942 return emitError("Linking COMDATs named '" + ComdatName +
943 "': noduplicates has been violated!");
944 case Comdat::SelectionKind::ExactMatch:
945 case Comdat::SelectionKind::Largest:
946 case Comdat::SelectionKind::SameSize: {
947 const GlobalVariable *DstGV;
948 const GlobalVariable *SrcGV;
949 if (getComdatLeader(DstM, ComdatName, DstGV) ||
950 getComdatLeader(SrcM, ComdatName, SrcGV))
953 const DataLayout &DstDL = DstM.getDataLayout();
954 const DataLayout &SrcDL = SrcM.getDataLayout();
956 DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
958 SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
959 if (Result == Comdat::SelectionKind::ExactMatch) {
960 if (SrcGV->getInitializer() != DstGV->getInitializer())
961 return emitError("Linking COMDATs named '" + ComdatName +
962 "': ExactMatch violated!");
964 } else if (Result == Comdat::SelectionKind::Largest) {
965 LinkFromSrc = SrcSize > DstSize;
966 } else if (Result == Comdat::SelectionKind::SameSize) {
967 if (SrcSize != DstSize)
968 return emitError("Linking COMDATs named '" + ComdatName +
969 "': SameSize violated!");
972 llvm_unreachable("unknown selection kind");
981 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
982 Comdat::SelectionKind &Result,
984 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
985 StringRef ComdatName = SrcC->getName();
986 Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
987 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
989 if (DstCI == ComdatSymTab.end()) {
990 // Use the comdat if it is only available in one of the modules.
996 const Comdat *DstC = &DstCI->second;
997 Comdat::SelectionKind DSK = DstC->getSelectionKind();
998 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
1002 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
1003 const GlobalValue &Dest,
1004 const GlobalValue &Src) {
1005 // Should we unconditionally use the Src?
1006 if (shouldOverrideFromSrc()) {
1011 // We always have to add Src if it has appending linkage.
1012 if (Src.hasAppendingLinkage()) {
1013 // Should have prevented importing for appending linkage in linkIfNeeded.
1014 assert(!isPerformingImport());
1019 bool SrcIsDeclaration = Src.isDeclarationForLinker();
1020 bool DestIsDeclaration = Dest.isDeclarationForLinker();
1022 if (isPerformingImport()) {
1023 if (isa<Function>(&Src)) {
1024 // For functions, LinkFromSrc iff this is the function requested
1025 // for importing. For variables, decide below normally.
1026 LinkFromSrc = ImportFunction->count(&Src);
1030 // Check if this is an alias with an already existing definition
1031 // in Dest, which must have come from a prior importing pass from
1032 // the same Src module. Unlike imported function and variable
1033 // definitions, which are imported as available_externally and are
1034 // not definitions for the linker, that is not a valid linkage for
1035 // imported aliases which must be definitions. Simply use the existing
1037 if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
1038 assert(isa<GlobalAlias>(&Dest));
1039 LinkFromSrc = false;
1044 if (SrcIsDeclaration) {
1045 // If Src is external or if both Src & Dest are external.. Just link the
1046 // external globals, we aren't adding anything.
1047 if (Src.hasDLLImportStorageClass()) {
1048 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
1049 LinkFromSrc = DestIsDeclaration;
1052 // If the Dest is weak, use the source linkage.
1053 if (Dest.hasExternalWeakLinkage()) {
1057 // Link an available_externally over a declaration.
1058 LinkFromSrc = !Src.isDeclaration() && Dest.isDeclaration();
1062 if (DestIsDeclaration) {
1063 // If Dest is external but Src is not:
1068 if (Src.hasCommonLinkage()) {
1069 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
1074 if (!Dest.hasCommonLinkage()) {
1075 LinkFromSrc = false;
1079 const DataLayout &DL = Dest.getParent()->getDataLayout();
1080 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
1081 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
1082 LinkFromSrc = SrcSize > DestSize;
1086 if (Src.isWeakForLinker()) {
1087 assert(!Dest.hasExternalWeakLinkage());
1088 assert(!Dest.hasAvailableExternallyLinkage());
1090 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
1095 LinkFromSrc = false;
1099 if (Dest.isWeakForLinker()) {
1100 assert(Src.hasExternalLinkage());
1105 assert(!Src.hasExternalWeakLinkage());
1106 assert(!Dest.hasExternalWeakLinkage());
1107 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
1108 "Unexpected linkage type!");
1109 return emitError("Linking globals named '" + Src.getName() +
1110 "': symbol multiply defined!");
1113 /// Loop over all of the linked values to compute type mappings. For example,
1114 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
1115 /// types 'Foo' but one got renamed when the module was loaded into the same
1117 void ModuleLinker::computeTypeMapping() {
1118 for (GlobalValue &SGV : SrcM.globals()) {
1119 GlobalValue *DGV = getLinkedToGlobal(&SGV);
1123 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
1124 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1128 // Unify the element type of appending arrays.
1129 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
1130 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
1131 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
1134 for (GlobalValue &SGV : SrcM) {
1135 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1136 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1139 for (GlobalValue &SGV : SrcM.aliases()) {
1140 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1141 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1144 // Incorporate types by name, scanning all the types in the source module.
1145 // At this point, the destination module may have a type "%foo = { i32 }" for
1146 // example. When the source module got loaded into the same LLVMContext, if
1147 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
1148 std::vector<StructType *> Types = SrcM.getIdentifiedStructTypes();
1149 for (StructType *ST : Types) {
1153 // Check to see if there is a dot in the name followed by a digit.
1154 size_t DotPos = ST->getName().rfind('.');
1155 if (DotPos == 0 || DotPos == StringRef::npos ||
1156 ST->getName().back() == '.' ||
1157 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
1160 // Check to see if the destination module has a struct with the prefix name.
1161 StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
1165 // Don't use it if this actually came from the source module. They're in
1166 // the same LLVMContext after all. Also don't use it unless the type is
1167 // actually used in the destination module. This can happen in situations
1170 // Module A Module B
1171 // -------- --------
1172 // %Z = type { %A } %B = type { %C.1 }
1173 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
1174 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
1175 // %C = type { i8* } %B.3 = type { %C.1 }
1177 // When we link Module B with Module A, the '%B' in Module B is
1178 // used. However, that would then use '%C.1'. But when we process '%C.1',
1179 // we prefer to take the '%C' version. So we are then left with both
1180 // '%C.1' and '%C' being used for the same types. This leads to some
1181 // variables using one type and some using the other.
1182 if (TypeMap.DstStructTypesSet.hasType(DST))
1183 TypeMap.addTypeMapping(DST, ST);
1186 // Now that we have discovered all of the type equivalences, get a body for
1187 // any 'opaque' types in the dest module that are now resolved.
1188 TypeMap.linkDefinedTypeBodies();
1191 static void getArrayElements(const Constant *C,
1192 SmallVectorImpl<Constant *> &Dest) {
1193 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1195 for (unsigned i = 0; i != NumElements; ++i)
1196 Dest.push_back(C->getAggregateElement(i));
1199 /// If there were any appending global variables, link them together now.
1200 /// Return true on error.
1201 Constant *ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
1202 const GlobalVariable *SrcGV) {
1203 Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()))
1206 StringRef Name = SrcGV->getName();
1207 bool IsNewStructor = false;
1208 bool IsOldStructor = false;
1209 if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
1210 if (cast<StructType>(EltTy)->getNumElements() == 3)
1211 IsNewStructor = true;
1213 IsOldStructor = true;
1216 PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
1217 if (IsOldStructor) {
1218 auto &ST = *cast<StructType>(EltTy);
1219 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
1220 EltTy = StructType::get(SrcGV->getContext(), Tys, false);
1224 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
1226 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) {
1228 "Linking globals named '" + SrcGV->getName() +
1229 "': can only link appending global with another appending global!");
1233 // Check to see that they two arrays agree on type.
1234 if (EltTy != DstTy->getElementType()) {
1235 emitError("Appending variables with different element types!");
1238 if (DstGV->isConstant() != SrcGV->isConstant()) {
1239 emitError("Appending variables linked with different const'ness!");
1243 if (DstGV->getAlignment() != SrcGV->getAlignment()) {
1245 "Appending variables with different alignment need to be linked!");
1249 if (DstGV->getVisibility() != SrcGV->getVisibility()) {
1251 "Appending variables with different visibility need to be linked!");
1255 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) {
1257 "Appending variables with different unnamed_addr need to be linked!");
1261 if (StringRef(DstGV->getSection()) != SrcGV->getSection()) {
1263 "Appending variables with different section name need to be linked!");
1268 SmallVector<Constant *, 16> DstElements;
1270 getArrayElements(DstGV->getInitializer(), DstElements);
1272 SmallVector<Constant *, 16> SrcElements;
1273 getArrayElements(SrcGV->getInitializer(), SrcElements);
1277 std::remove_if(SrcElements.begin(), SrcElements.end(),
1278 [this](Constant *E) {
1279 auto *Key = dyn_cast<GlobalValue>(
1280 E->getAggregateElement(2)->stripPointerCasts());
1281 return Key && !ValuesToLink.count(Key) &&
1282 !shouldLazyLink(*Key);
1285 uint64_t NewSize = DstElements.size() + SrcElements.size();
1286 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
1288 // Create the new global variable.
1289 GlobalVariable *NG = new GlobalVariable(
1290 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
1291 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
1292 SrcGV->getType()->getAddressSpace());
1294 // Propagate alignment, visibility and section info.
1295 copyGVAttributes(NG, SrcGV);
1297 Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
1300 ValueMap[SrcGV] = Ret;
1302 for (auto *V : SrcElements) {
1304 if (IsOldStructor) {
1305 auto *S = cast<ConstantStruct>(V);
1306 auto *E1 = MapValue(S->getOperand(0), ValueMap, RF_MoveDistinctMDs,
1307 &TypeMap, &ValMaterializer);
1308 auto *E2 = MapValue(S->getOperand(1), ValueMap, RF_MoveDistinctMDs,
1309 &TypeMap, &ValMaterializer);
1310 Value *Null = Constant::getNullValue(VoidPtrTy);
1312 ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null, nullptr);
1315 MapValue(V, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1317 DstElements.push_back(NewV);
1320 NG->setInitializer(ConstantArray::get(NewType, DstElements));
1322 // Replace any uses of the two global variables with uses of the new
1325 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
1326 DstGV->eraseFromParent();
1332 Constant *ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
1333 GlobalValue *DGV = getLinkedToGlobal(SGV);
1335 // Handle the ultra special appending linkage case first.
1336 assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
1337 if (SGV->hasAppendingLinkage()) {
1338 // Should have prevented importing for appending linkage in linkIfNeeded.
1339 assert(!isPerformingImport());
1340 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
1341 cast<GlobalVariable>(SGV));
1344 bool LinkFromSrc = true;
1345 Comdat *C = nullptr;
1346 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
1348 if (isPerformingImport() && !doImportAsDefinition(SGV)) {
1349 LinkFromSrc = false;
1350 } else if (const Comdat *SC = SGV->getComdat()) {
1351 Comdat::SelectionKind SK;
1352 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1353 C = DstM.getOrInsertComdat(SC->getName());
1354 C->setSelectionKind(SK);
1355 if (SGV->hasLocalLinkage())
1358 if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1363 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1366 if (!LinkFromSrc && DGV) {
1369 // If we are done linking global value bodies (i.e. we are performing
1370 // metadata linking), don't link in the global value due to this
1371 // reference, simply map it to null.
1372 if (DoneLinkingBodies)
1375 NewGV = copyGlobalValueProto(SGV, LinkFromSrc);
1378 setVisibility(NewGV, SGV, DGV);
1379 NewGV->setUnnamedAddr(HasUnnamedAddr);
1381 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1382 if (C && LinkFromSrc)
1383 NewGO->setComdat(C);
1385 if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1386 NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
1389 if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) {
1390 auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV);
1391 auto *SGVar = dyn_cast<GlobalVariable>(SGV);
1392 if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() &&
1393 (!DGVar->isConstant() || !SGVar->isConstant()))
1394 NewGVar->setConstant(false);
1397 if (NewGV != DGV && DGV) {
1398 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
1399 DGV->eraseFromParent();
1402 return ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType()));
1405 /// Update the initializers in the Dest module now that all globals that may be
1406 /// referenced are in Dest.
1407 void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
1408 // Figure out what the initializer looks like in the dest module.
1409 Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap,
1410 RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1413 /// Copy the source function over into the dest function and fix up references
1414 /// to values. At this point we know that Dest is an external function, and
1415 /// that Src is not.
1416 bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) {
1417 assert(Dst.isDeclaration() && !Src.isDeclaration());
1419 // Materialize if needed.
1420 if (std::error_code EC = Src.materialize())
1421 return emitError(EC.message());
1423 // Link in the prefix data.
1424 if (Src.hasPrefixData())
1425 Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap,
1426 RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1428 // Link in the prologue data.
1429 if (Src.hasPrologueData())
1430 Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap,
1431 RF_MoveDistinctMDs, &TypeMap,
1434 // Link in the personality function.
1435 if (Src.hasPersonalityFn())
1436 Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap,
1437 RF_MoveDistinctMDs, &TypeMap,
1440 // Go through and convert function arguments over, remembering the mapping.
1441 Function::arg_iterator DI = Dst.arg_begin();
1442 for (Argument &Arg : Src.args()) {
1443 DI->setName(Arg.getName()); // Copy the name over.
1445 // Add a mapping to our mapping.
1446 ValueMap[&Arg] = &*DI;
1450 // Copy over the metadata attachments.
1451 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1452 Src.getAllMetadata(MDs);
1453 for (const auto &I : MDs)
1454 Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, RF_MoveDistinctMDs,
1455 &TypeMap, &ValMaterializer));
1457 // Splice the body of the source function into the dest function.
1458 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
1460 // At this point, all of the instructions and values of the function are now
1461 // copied over. The only problem is that they are still referencing values in
1462 // the Source function as operands. Loop through all of the operands of the
1463 // functions and patch them up to point to the local versions.
1464 for (BasicBlock &BB : Dst)
1465 for (Instruction &I : BB)
1466 RemapInstruction(&I, ValueMap,
1467 RF_IgnoreMissingEntries | RF_MoveDistinctMDs, &TypeMap,
1470 // There is no need to map the arguments anymore.
1471 for (Argument &Arg : Src.args())
1472 ValueMap.erase(&Arg);
1474 Src.dematerialize();
1478 void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1479 Constant *Aliasee = Src.getAliasee();
1480 Constant *Val = MapValue(Aliasee, ValueMap, RF_MoveDistinctMDs, &TypeMap,
1482 Dst.setAliasee(Val);
1485 bool ModuleLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
1486 if (const Comdat *SC = Src.getComdat()) {
1487 // To ensure that we don't generate an incomplete comdat group,
1488 // we must materialize and map in any other members that are not
1489 // yet materialized in Dst, which also ensures their definitions
1490 // are linked in. Otherwise, linkonce and other lazy linked GVs will
1491 // not be materialized if they aren't referenced.
1492 for (auto *SGV : ComdatMembers[SC]) {
1493 auto *DGV = cast_or_null<GlobalValue>(ValueMap.lookup(SGV));
1494 if (DGV && !DGV->isDeclaration())
1496 MapValue(SGV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1499 if (shouldInternalizeLinkedSymbols())
1500 if (auto *DGV = dyn_cast<GlobalValue>(&Dst))
1501 DGV->setLinkage(GlobalValue::InternalLinkage);
1502 if (auto *F = dyn_cast<Function>(&Src))
1503 return linkFunctionBody(cast<Function>(Dst), *F);
1504 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1505 linkGlobalInit(cast<GlobalVariable>(Dst), *GVar);
1508 linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
1512 /// Insert all of the named MDNodes in Src into the Dest module.
1513 void ModuleLinker::linkNamedMDNodes() {
1514 const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1515 for (const NamedMDNode &NMD : SrcM.named_metadata()) {
1516 // Don't link module flags here. Do them separately.
1517 if (&NMD == SrcModFlags)
1519 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1520 // Add Src elements into Dest node.
1521 for (const MDNode *op : NMD.operands())
1522 DestNMD->addOperand(MapMetadata(
1523 op, ValueMap, RF_MoveDistinctMDs | RF_NullMapMissingGlobalValues,
1524 &TypeMap, &ValMaterializer));
1528 /// Merge the linker flags in Src into the Dest module.
1529 bool ModuleLinker::linkModuleFlagsMetadata() {
1530 // If the source module has no module flags, we are done.
1531 const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1535 // If the destination module doesn't have module flags yet, then just copy
1536 // over the source module's flags.
1537 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1538 if (DstModFlags->getNumOperands() == 0) {
1539 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1540 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1545 // First build a map of the existing module flags and requirements.
1546 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1547 SmallSetVector<MDNode *, 16> Requirements;
1548 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1549 MDNode *Op = DstModFlags->getOperand(I);
1550 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1551 MDString *ID = cast<MDString>(Op->getOperand(1));
1553 if (Behavior->getZExtValue() == Module::Require) {
1554 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1556 Flags[ID] = std::make_pair(Op, I);
1560 // Merge in the flags from the source module, and also collect its set of
1562 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1563 MDNode *SrcOp = SrcModFlags->getOperand(I);
1564 ConstantInt *SrcBehavior =
1565 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1566 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1569 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1570 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1572 // If this is a requirement, add it and continue.
1573 if (SrcBehaviorValue == Module::Require) {
1574 // If the destination module does not already have this requirement, add
1576 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1577 DstModFlags->addOperand(SrcOp);
1582 // If there is no existing flag with this ID, just add it.
1584 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1585 DstModFlags->addOperand(SrcOp);
1589 // Otherwise, perform a merge.
1590 ConstantInt *DstBehavior =
1591 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1592 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1594 // If either flag has override behavior, handle it first.
1595 if (DstBehaviorValue == Module::Override) {
1596 // Diagnose inconsistent flags which both have override behavior.
1597 if (SrcBehaviorValue == Module::Override &&
1598 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1599 emitError("linking module flags '" + ID->getString() +
1600 "': IDs have conflicting override values");
1603 } else if (SrcBehaviorValue == Module::Override) {
1604 // Update the destination flag to that of the source.
1605 DstModFlags->setOperand(DstIndex, SrcOp);
1606 Flags[ID].first = SrcOp;
1610 // Diagnose inconsistent merge behavior types.
1611 if (SrcBehaviorValue != DstBehaviorValue) {
1612 emitError("linking module flags '" + ID->getString() +
1613 "': IDs have conflicting behaviors");
1617 auto replaceDstValue = [&](MDNode *New) {
1618 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1619 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1620 DstModFlags->setOperand(DstIndex, Flag);
1621 Flags[ID].first = Flag;
1624 // Perform the merge for standard behavior types.
1625 switch (SrcBehaviorValue) {
1626 case Module::Require:
1627 case Module::Override:
1628 llvm_unreachable("not possible");
1629 case Module::Error: {
1630 // Emit an error if the values differ.
1631 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1632 emitError("linking module flags '" + ID->getString() +
1633 "': IDs have conflicting values");
1637 case Module::Warning: {
1638 // Emit a warning if the values differ.
1639 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1640 emitWarning("linking module flags '" + ID->getString() +
1641 "': IDs have conflicting values");
1645 case Module::Append: {
1646 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1647 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1648 SmallVector<Metadata *, 8> MDs;
1649 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1650 MDs.append(DstValue->op_begin(), DstValue->op_end());
1651 MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1653 replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1656 case Module::AppendUnique: {
1657 SmallSetVector<Metadata *, 16> Elts;
1658 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1659 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1660 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1661 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1663 replaceDstValue(MDNode::get(DstM.getContext(),
1664 makeArrayRef(Elts.begin(), Elts.end())));
1670 // Check all of the requirements.
1671 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1672 MDNode *Requirement = Requirements[I];
1673 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1674 Metadata *ReqValue = Requirement->getOperand(1);
1676 MDNode *Op = Flags[Flag].first;
1677 if (!Op || Op->getOperand(2) != ReqValue) {
1678 emitError("linking module flags '" + Flag->getString() +
1679 "': does not have the required value");
1687 // This function returns true if the triples match.
1688 static bool triplesMatch(const Triple &T0, const Triple &T1) {
1689 // If vendor is apple, ignore the version number.
1690 if (T0.getVendor() == Triple::Apple)
1691 return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1692 T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1697 // This function returns the merged triple.
1698 static std::string mergeTriples(const Triple &SrcTriple,
1699 const Triple &DstTriple) {
1700 // If vendor is apple, pick the triple with the larger version number.
1701 if (SrcTriple.getVendor() == Triple::Apple)
1702 if (DstTriple.isOSVersionLT(SrcTriple))
1703 return SrcTriple.str();
1705 return DstTriple.str();
1708 bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
1709 GlobalValue *DGV = getLinkedToGlobal(&GV);
1711 if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
1714 if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) {
1715 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
1716 auto *SGVar = dyn_cast<GlobalVariable>(&GV);
1717 if (DGVar && SGVar) {
1718 if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
1719 (!DGVar->isConstant() || !SGVar->isConstant())) {
1720 DGVar->setConstant(false);
1721 SGVar->setConstant(false);
1723 if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
1724 unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment());
1725 SGVar->setAlignment(Align);
1726 DGVar->setAlignment(Align);
1730 GlobalValue::VisibilityTypes Visibility =
1731 getMinVisibility(DGV->getVisibility(), GV.getVisibility());
1732 DGV->setVisibility(Visibility);
1733 GV.setVisibility(Visibility);
1735 bool HasUnnamedAddr = GV.hasUnnamedAddr() && DGV->hasUnnamedAddr();
1736 DGV->setUnnamedAddr(HasUnnamedAddr);
1737 GV.setUnnamedAddr(HasUnnamedAddr);
1740 // Don't want to append to global_ctors list, for example, when we
1741 // are importing for ThinLTO, otherwise the global ctors and dtors
1742 // get executed multiple times for local variables (the latter causing
1744 if (GV.hasAppendingLinkage() && isPerformingImport())
1747 if (isPerformingImport() && !doImportAsDefinition(&GV))
1750 if (!DGV && !shouldOverrideFromSrc() &&
1751 (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
1752 GV.hasAvailableExternallyLinkage()))
1755 if (GV.isDeclaration())
1758 if (const Comdat *SC = GV.getComdat()) {
1760 Comdat::SelectionKind SK;
1761 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1763 ValuesToLink.insert(&GV);
1767 bool LinkFromSrc = true;
1768 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
1771 ValuesToLink.insert(&GV);
1775 bool ModuleLinker::run() {
1776 // Inherit the target data from the source module if the destination module
1777 // doesn't have one already.
1778 if (DstM.getDataLayout().isDefault())
1779 DstM.setDataLayout(SrcM.getDataLayout());
1781 if (SrcM.getDataLayout() != DstM.getDataLayout()) {
1782 emitWarning("Linking two modules of different data layouts: '" +
1783 SrcM.getModuleIdentifier() + "' is '" +
1784 SrcM.getDataLayoutStr() + "' whereas '" +
1785 DstM.getModuleIdentifier() + "' is '" +
1786 DstM.getDataLayoutStr() + "'\n");
1789 // Copy the target triple from the source to dest if the dest's is empty.
1790 if (DstM.getTargetTriple().empty() && !SrcM.getTargetTriple().empty())
1791 DstM.setTargetTriple(SrcM.getTargetTriple());
1793 Triple SrcTriple(SrcM.getTargetTriple()), DstTriple(DstM.getTargetTriple());
1795 if (!SrcM.getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
1796 emitWarning("Linking two modules of different target triples: " +
1797 SrcM.getModuleIdentifier() + "' is '" + SrcM.getTargetTriple() +
1798 "' whereas '" + DstM.getModuleIdentifier() + "' is '" +
1799 DstM.getTargetTriple() + "'\n");
1801 DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1803 // Append the module inline asm string.
1804 if (!SrcM.getModuleInlineAsm().empty()) {
1805 if (DstM.getModuleInlineAsm().empty())
1806 DstM.setModuleInlineAsm(SrcM.getModuleInlineAsm());
1808 DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
1809 SrcM.getModuleInlineAsm());
1812 // Loop over all of the linked values to compute type mappings.
1813 computeTypeMapping();
1815 ComdatsChosen.clear();
1816 for (const auto &SMEC : SrcM.getComdatSymbolTable()) {
1817 const Comdat &C = SMEC.getValue();
1818 if (ComdatsChosen.count(&C))
1820 Comdat::SelectionKind SK;
1822 if (getComdatResult(&C, SK, LinkFromSrc))
1824 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1827 for (GlobalVariable &GV : SrcM.globals())
1828 if (const Comdat *SC = GV.getComdat())
1829 ComdatMembers[SC].push_back(&GV);
1831 for (Function &SF : SrcM)
1832 if (const Comdat *SC = SF.getComdat())
1833 ComdatMembers[SC].push_back(&SF);
1835 for (GlobalAlias &GA : SrcM.aliases())
1836 if (const Comdat *SC = GA.getComdat())
1837 ComdatMembers[SC].push_back(&GA);
1839 // Insert all of the globals in src into the DstM module... without linking
1840 // initializers (which could refer to functions not yet mapped over).
1841 for (GlobalVariable &GV : SrcM.globals())
1842 if (linkIfNeeded(GV))
1845 for (Function &SF : SrcM)
1846 if (linkIfNeeded(SF))
1849 for (GlobalAlias &GA : SrcM.aliases())
1850 if (linkIfNeeded(GA))
1853 for (GlobalValue *GV : ValuesToLink) {
1854 MapValue(GV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1859 // Note that we are done linking global value bodies. This prevents
1860 // metadata linking from creating new references.
1861 DoneLinkingBodies = true;
1863 // Remap all of the named MDNodes in Src into the DstM module. We do this
1864 // after linking GlobalValues so that MDNodes that reference GlobalValues
1865 // are properly remapped.
1868 // Merge the module flags into the DstM module.
1869 if (linkModuleFlagsMetadata())
1875 Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1876 : ETypes(E), IsPacked(P) {}
1878 Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1879 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1881 bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1882 if (IsPacked != That.IsPacked)
1884 if (ETypes != That.ETypes)
1889 bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1890 return !this->operator==(That);
1893 StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
1894 return DenseMapInfo<StructType *>::getEmptyKey();
1897 StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
1898 return DenseMapInfo<StructType *>::getTombstoneKey();
1901 unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1902 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1906 unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1907 return getHashValue(KeyTy(ST));
1910 bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1911 const StructType *RHS) {
1912 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1914 return LHS == KeyTy(RHS);
1917 bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
1918 const StructType *RHS) {
1919 if (RHS == getEmptyKey())
1920 return LHS == getEmptyKey();
1922 if (RHS == getTombstoneKey())
1923 return LHS == getTombstoneKey();
1925 return KeyTy(LHS) == KeyTy(RHS);
1928 void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1929 assert(!Ty->isOpaque());
1930 NonOpaqueStructTypes.insert(Ty);
1933 void Linker::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1934 assert(!Ty->isOpaque());
1935 NonOpaqueStructTypes.insert(Ty);
1936 bool Removed = OpaqueStructTypes.erase(Ty);
1941 void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1942 assert(Ty->isOpaque());
1943 OpaqueStructTypes.insert(Ty);
1947 Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1949 Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1950 auto I = NonOpaqueStructTypes.find_as(Key);
1951 if (I == NonOpaqueStructTypes.end())
1956 bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1958 return OpaqueStructTypes.count(Ty);
1959 auto I = NonOpaqueStructTypes.find(Ty);
1960 if (I == NonOpaqueStructTypes.end())
1965 Linker::Linker(Module &M, DiagnosticHandlerFunction DiagnosticHandler)
1966 : Composite(M), DiagnosticHandler(DiagnosticHandler) {
1967 TypeFinder StructTypes;
1968 StructTypes.run(M, true);
1969 for (StructType *Ty : StructTypes) {
1971 IdentifiedStructTypes.addOpaque(Ty);
1973 IdentifiedStructTypes.addNonOpaque(Ty);
1977 bool Linker::linkInModule(Module &Src, unsigned Flags,
1978 const FunctionInfoIndex *Index,
1979 DenseSet<const GlobalValue *> *FunctionsToImport) {
1980 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
1981 DiagnosticHandler, Flags, Index, FunctionsToImport);
1982 bool RetCode = TheLinker.run();
1983 Composite.dropTriviallyDeadConstantArrays();
1987 //===----------------------------------------------------------------------===//
1988 // LinkModules entrypoint.
1989 //===----------------------------------------------------------------------===//
1991 /// This function links two modules together, with the resulting Dest module
1992 /// modified to be the composite of the two input modules. If an error occurs,
1993 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
1994 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
1995 /// relied on to be consistent.
1996 bool Linker::linkModules(Module &Dest, Module &Src,
1997 DiagnosticHandlerFunction DiagnosticHandler,
1999 Linker L(Dest, DiagnosticHandler);
2000 return L.linkInModule(Src, Flags);
2003 std::unique_ptr<Module>
2004 llvm::renameModuleForThinLTO(std::unique_ptr<Module> &M,
2005 const FunctionInfoIndex *Index,
2006 DiagnosticHandlerFunction DiagnosticHandler) {
2007 std::unique_ptr<llvm::Module> RenamedModule(
2008 new llvm::Module(M->getModuleIdentifier(), M->getContext()));
2009 Linker L(*RenamedModule.get(), DiagnosticHandler);
2010 if (L.linkInModule(*M.get(), llvm::Linker::Flags::None, Index))
2012 return RenamedModule;
2015 //===----------------------------------------------------------------------===//
2017 //===----------------------------------------------------------------------===//
2019 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
2020 LLVMLinkerMode Unused, char **OutMessages) {
2021 Module *D = unwrap(Dest);
2022 std::string Message;
2023 raw_string_ostream Stream(Message);
2024 DiagnosticPrinterRawOStream DP(Stream);
2026 LLVMBool Result = Linker::linkModules(
2027 *D, *unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
2029 if (OutMessages && Result) {
2031 *OutMessages = strdup(Message.c_str());