/// Make sure GV is visible from both modules. Delete is true if it is /// being deleted from this module. /// This also makes sure GV cannot be dropped so that references from /// the split module remain valid. static void makeVisible(GlobalValue &GV, bool Delete) { bool Local = GV.hasLocalLinkage(); if (Local) GV.setVisibility(GlobalValue::HiddenVisibility); if (Local || Delete) { GV.setLinkage(GlobalValue::ExternalLinkage); return; } if (!GV.hasLinkOnceLinkage()) { assert(!GV.isDiscardableIfUnused()); return; } // Map linkonce* to weak* so that llvm doesn't drop this GV. switch(GV.getLinkage()) { default: llvm_unreachable("Unexpected linkage"); case GlobalValue::LinkOnceAnyLinkage: GV.setLinkage(GlobalValue::WeakAnyLinkage); return; case GlobalValue::LinkOnceODRLinkage: GV.setLinkage(GlobalValue::WeakODRLinkage); return; } }
void FunctionImportGlobalProcessing::processGlobalForThinLTO(GlobalValue &GV) { bool DoPromote = false; if (GV.hasLocalLinkage() && ((DoPromote = shouldPromoteLocalToGlobal(&GV)) || isPerformingImport())) { // Once we change the name or linkage it is difficult to determine // again whether we should promote since shouldPromoteLocalToGlobal needs // to locate the summary (based on GUID from name and linkage). Therefore, // use DoPromote result saved above. GV.setName(getName(&GV, DoPromote)); GV.setLinkage(getLinkage(&GV, DoPromote)); if (!GV.hasLocalLinkage()) GV.setVisibility(GlobalValue::HiddenVisibility); } else GV.setLinkage(getLinkage(&GV, /* DoPromote */ false)); // Remove functions imported as available externally defs from comdats, // as this is a declaration for the linker, and will be dropped eventually. // It is illegal for comdats to contain declarations. auto *GO = dyn_cast_or_null<GlobalObject>(&GV); if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) { // The IRMover should not have placed any imported declarations in // a comdat, so the only declaration that should be in a comdat // at this point would be a definition imported as available_externally. assert(GO->hasAvailableExternallyLinkage() && "Expected comdat on definition (possibly available external)"); GO->setComdat(nullptr); } }
/// Make sure GV is visible from both modules. Delete is true if it is /// being deleted from this module. /// This also makes sure GV cannot be dropped so that references from /// the split module remain valid. static void makeVisible(GlobalValue &GV, bool Delete, bool IsDeletePass) { bool Local = GV.hasLocalLinkage(); if (Local || Delete) { // This changes members from private -> hidden -> causes linker errors when using llvm-link if (!IsDeletePass) GV.setLinkage(GlobalValue::ExternalLinkage); if (Local) GV.setVisibility(GlobalValue::HiddenVisibility); return; } if (!GV.hasLinkOnceLinkage()) { assert(!GV.isDiscardableIfUnused()); return; } // Map linkonce* to weak* so that llvm doesn't drop this GV. switch(GV.getLinkage()) { default: llvm_unreachable("Unexpected linkage"); case GlobalValue::LinkOnceAnyLinkage: GV.setLinkage(GlobalValue::WeakAnyLinkage); return; case GlobalValue::LinkOnceODRLinkage: GV.setLinkage(GlobalValue::WeakODRLinkage); return; } }
static void raiseVisibilityOnValue(GlobalValue &V, GlobalRenamer &R) { if (V.hasLocalLinkage()) { if (R.needsRenaming(V)) V.setName(R.getRename(V)); V.setLinkage(GlobalValue::ExternalLinkage); V.setVisibility(GlobalValue::HiddenVisibility); } V.setUnnamedAddr(GlobalValue::UnnamedAddr::None); assert(!R.needsRenaming(V) && "Invalid global name."); }
/// linkFunctionProto - Link the function in the source module into the /// destination module if needed, setting up mapping information. bool ModuleLinker::linkFunctionProto(Function *SF) { GlobalValue *DGV = getLinkedToGlobal(SF); llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility; if (DGV) { GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage; bool LinkFromSrc = false; GlobalValue::VisibilityTypes NV; if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc)) return true; NewVisibility = NV; if (!LinkFromSrc) { // Set calculated linkage DGV->setLinkage(NewLinkage); DGV->setVisibility(*NewVisibility); // Make sure to remember this mapping. ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType())); // Track the function from the source module so we don't attempt to remap // it. DoNotLinkFromSource.insert(SF); return false; } } // If there is no linkage to be performed or we are linking from the source, // bring SF over. Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(), SF->getName(), DstM); CopyGVAttributes(NewDF, SF); if (NewVisibility) NewDF->setVisibility(*NewVisibility); if (DGV) { // Any uses of DF need to change to NewDF, with cast. DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType())); DGV->eraseFromParent(); } else { // Internal, LO_ODR, or LO linkage - stick in set to ignore and lazily link. if (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() || SF->hasAvailableExternallyLinkage()) { DoNotLinkFromSource.insert(SF); LazilyLinkFunctions.push_back(SF); } } ValueMap[SF] = NewDF; return false; }
void ThinLTOGlobalProcessing::processGlobalForThinLTO(GlobalValue &GV) { if (GV.hasLocalLinkage() && (doPromoteLocalToGlobal(&GV) || isPerformingImport())) { GV.setName(getName(&GV)); GV.setLinkage(getLinkage(&GV)); if (!GV.hasLocalLinkage()) GV.setVisibility(GlobalValue::HiddenVisibility); if (isModuleExporting()) NewExportedValues.insert(&GV); return; } GV.setLinkage(getLinkage(&GV)); }
void FunctionImportGlobalProcessing::processGlobalForThinLTO(GlobalValue &GV) { // Check the summaries to see if the symbol gets resolved to a known local // definition. if (GV.hasName()) { ValueInfo VI = ImportIndex.getValueInfo(GV.getGUID()); if (VI) { // Need to check all summaries are local in case of hash collisions. bool IsLocal = VI.getSummaryList().size() && llvm::all_of(VI.getSummaryList(), [](const std::unique_ptr<GlobalValueSummary> &Summary) { return Summary->isDSOLocal(); }); if (IsLocal) GV.setDSOLocal(true); } } bool DoPromote = false; if (GV.hasLocalLinkage() && ((DoPromote = shouldPromoteLocalToGlobal(&GV)) || isPerformingImport())) { // Once we change the name or linkage it is difficult to determine // again whether we should promote since shouldPromoteLocalToGlobal needs // to locate the summary (based on GUID from name and linkage). Therefore, // use DoPromote result saved above. GV.setName(getName(&GV, DoPromote)); GV.setLinkage(getLinkage(&GV, DoPromote)); if (!GV.hasLocalLinkage()) GV.setVisibility(GlobalValue::HiddenVisibility); } else GV.setLinkage(getLinkage(&GV, /* DoPromote */ false)); // Remove functions imported as available externally defs from comdats, // as this is a declaration for the linker, and will be dropped eventually. // It is illegal for comdats to contain declarations. auto *GO = dyn_cast_or_null<GlobalObject>(&GV); if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) { // The IRMover should not have placed any imported declarations in // a comdat, so the only declaration that should be in a comdat // at this point would be a definition imported as available_externally. assert(GO->hasAvailableExternallyLinkage() && "Expected comdat on definition (possibly available external)"); GO->setComdat(nullptr); } }
/// LinkAliasProto - Set up prototypes for any aliases that come over from the /// source module. bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) { GlobalValue *DGV = getLinkedToGlobal(SGA); llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility; if (DGV) { GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage; GlobalValue::VisibilityTypes NV; bool LinkFromSrc = false; if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc)) return true; NewVisibility = NV; if (!LinkFromSrc) { // Set calculated linkage. DGV->setLinkage(NewLinkage); DGV->setVisibility(*NewVisibility); // Make sure to remember this mapping. ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType())); // Track the alias from the source module so we don't attempt to remap it. DoNotLinkFromSource.insert(SGA); return false; } } // If there is no linkage to be performed or we're linking from the source, // bring over SGA. GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()), SGA->getLinkage(), SGA->getName(), /*aliasee*/0, DstM); CopyGVAttributes(NewDA, SGA); if (NewVisibility) NewDA->setVisibility(*NewVisibility); if (DGV) { // Any uses of DGV need to change to NewDA, with cast. DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType())); DGV->eraseFromParent(); } ValueMap[SGA] = NewDA; return false; }
bool ModuleLinker::linkIfNeeded(GlobalValue &GV) { GlobalValue *DGV = getLinkedToGlobal(&GV); if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration())) return false; if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) { auto *DGVar = dyn_cast<GlobalVariable>(DGV); auto *SGVar = dyn_cast<GlobalVariable>(&GV); if (DGVar && SGVar) { if (DGVar->isDeclaration() && SGVar->isDeclaration() && (!DGVar->isConstant() || !SGVar->isConstant())) { DGVar->setConstant(false); SGVar->setConstant(false); } if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) { unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment()); SGVar->setAlignment(Align); DGVar->setAlignment(Align); } } GlobalValue::VisibilityTypes Visibility = getMinVisibility(DGV->getVisibility(), GV.getVisibility()); DGV->setVisibility(Visibility); GV.setVisibility(Visibility); bool HasUnnamedAddr = GV.hasUnnamedAddr() && DGV->hasUnnamedAddr(); DGV->setUnnamedAddr(HasUnnamedAddr); GV.setUnnamedAddr(HasUnnamedAddr); } // Don't want to append to global_ctors list, for example, when we // are importing for ThinLTO, otherwise the global ctors and dtors // get executed multiple times for local variables (the latter causing // double frees). if (GV.hasAppendingLinkage() && isPerformingImport()) return false; if (isPerformingImport()) { if (!doImportAsDefinition(&GV)) return false; } else if (!DGV && !shouldOverrideFromSrc() && (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() || GV.hasAvailableExternallyLinkage())) return false; if (GV.isDeclaration()) return false; if (const Comdat *SC = GV.getComdat()) { bool LinkFromSrc; Comdat::SelectionKind SK; std::tie(SK, LinkFromSrc) = ComdatsChosen[SC]; if (!LinkFromSrc) return false; } bool LinkFromSrc = true; if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV)) return true; if (LinkFromSrc) ValuesToLink.insert(&GV); return false; }
static std::unique_ptr<Module> getModuleForFile(LLVMContext &Context, claimed_file &F, const void *View, ld_plugin_input_file &Info, raw_fd_ostream *ApiFile, StringSet<> &Internalize, StringSet<> &Maybe, std::vector<GlobalValue *> &Keep, StringMap<unsigned> &Realign) { MemoryBufferRef BufferRef(StringRef((const char *)View, Info.filesize), Info.name); ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr = object::IRObjectFile::create(BufferRef, Context); if (std::error_code EC = ObjOrErr.getError()) message(LDPL_FATAL, "Could not read bitcode from file : %s", EC.message().c_str()); object::IRObjectFile &Obj = **ObjOrErr; Module &M = Obj.getModule(); M.materializeMetadata(); UpgradeDebugInfo(M); SmallPtrSet<GlobalValue *, 8> Used; collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false); unsigned SymNum = 0; for (auto &ObjSym : Obj.symbols()) { GlobalValue *GV = Obj.getSymbolGV(ObjSym.getRawDataRefImpl()); if (GV && GV->hasAppendingLinkage()) Keep.push_back(GV); if (shouldSkip(ObjSym.getFlags())) continue; ld_plugin_symbol &Sym = F.syms[SymNum]; ++SymNum; ld_plugin_symbol_resolution Resolution = (ld_plugin_symbol_resolution)Sym.resolution; if (options::generate_api_file) *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n'; if (!GV) { freeSymName(Sym); continue; // Asm symbol. } ResolutionInfo &Res = ResInfo[Sym.name]; if (Resolution == LDPR_PREVAILING_DEF_IRONLY_EXP && !Res.IsLinkonceOdr) Resolution = LDPR_PREVAILING_DEF; // In ThinLTO mode change all prevailing resolutions to LDPR_PREVAILING_DEF. // For ThinLTO the IR files are compiled through the backend independently, // so we need to ensure that any prevailing linkonce copy will be emitted // into the object file by making it weak. Additionally, we can skip the // IRONLY handling for internalization, which isn't performed in ThinLTO // mode currently anyway. if (options::thinlto && (Resolution == LDPR_PREVAILING_DEF_IRONLY_EXP || Resolution == LDPR_PREVAILING_DEF_IRONLY)) Resolution = LDPR_PREVAILING_DEF; GV->setUnnamedAddr(Res.UnnamedAddr); GV->setVisibility(Res.Visibility); // Override gold's resolution for common symbols. We want the largest // one to win. if (GV->hasCommonLinkage()) { if (Resolution == LDPR_PREVAILING_DEF_IRONLY) Res.CommonInternal = true; if (Resolution == LDPR_PREVAILING_DEF_IRONLY || Resolution == LDPR_PREVAILING_DEF) Res.UseCommon = true; const DataLayout &DL = GV->getParent()->getDataLayout(); uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType()); unsigned Align = GV->getAlignment(); if (Res.UseCommon && Size >= Res.CommonSize) { // Take GV. if (Res.CommonInternal) Resolution = LDPR_PREVAILING_DEF_IRONLY; else Resolution = LDPR_PREVAILING_DEF; cast<GlobalVariable>(GV)->setAlignment( std::max(Res.CommonAlign, Align)); } else { // Do not take GV, it's smaller than what we already have in the // combined module. Resolution = LDPR_PREEMPTED_IR; if (Align > Res.CommonAlign) // Need to raise the alignment though. Realign[Sym.name] = Align; } Res.CommonSize = std::max(Res.CommonSize, Size); Res.CommonAlign = std::max(Res.CommonAlign, Align); } switch (Resolution) { case LDPR_UNKNOWN: llvm_unreachable("Unexpected resolution"); case LDPR_RESOLVED_IR: case LDPR_RESOLVED_EXEC: case LDPR_RESOLVED_DYN: case LDPR_PREEMPTED_IR: case LDPR_PREEMPTED_REG: break; case LDPR_UNDEF: if (!GV->isDeclarationForLinker()) assert(GV->hasComdat()); break; case LDPR_PREVAILING_DEF_IRONLY: { Keep.push_back(GV); // The IR linker has to be able to map this value to a declaration, // so we can only internalize after linking. if (!Used.count(GV)) Internalize.insert(GV->getName()); break; } case LDPR_PREVAILING_DEF: Keep.push_back(GV); // There is a non IR use, so we have to force optimizations to keep this. switch (GV->getLinkage()) { default: break; case GlobalValue::LinkOnceAnyLinkage: GV->setLinkage(GlobalValue::WeakAnyLinkage); break; case GlobalValue::LinkOnceODRLinkage: GV->setLinkage(GlobalValue::WeakODRLinkage); break; } break; case LDPR_PREVAILING_DEF_IRONLY_EXP: { // We can only check for address uses after we merge the modules. The // reason is that this GV might have a copy in another module // and in that module the address might be significant, but that // copy will be LDPR_PREEMPTED_IR. Maybe.insert(GV->getName()); Keep.push_back(GV); break; } } freeSymName(Sym); } return Obj.takeModule(); }
void FunctionImportGlobalProcessing::processGlobalForThinLTO(GlobalValue &GV) { ValueInfo VI; if (GV.hasName()) { VI = ImportIndex.getValueInfo(GV.getGUID()); // Set synthetic function entry counts. if (VI && ImportIndex.hasSyntheticEntryCounts()) { if (Function *F = dyn_cast<Function>(&GV)) { if (!F->isDeclaration()) { for (auto &S : VI.getSummaryList()) { FunctionSummary *FS = dyn_cast<FunctionSummary>(S->getBaseObject()); if (FS->modulePath() == M.getModuleIdentifier()) { F->setEntryCount(Function::ProfileCount(FS->entryCount(), Function::PCT_Synthetic)); break; } } } } } // Check the summaries to see if the symbol gets resolved to a known local // definition. if (VI && VI.isDSOLocal()) { GV.setDSOLocal(true); if (GV.hasDLLImportStorageClass()) GV.setDLLStorageClass(GlobalValue::DefaultStorageClass); } } // Mark read-only variables which can be imported with specific attribute. // We can't internalize them now because IRMover will fail to link variable // definitions to their external declarations during ThinLTO import. We'll // internalize read-only variables later, after import is finished. // See internalizeImmutableGVs. // // If global value dead stripping is not enabled in summary then // propagateConstants hasn't been run. We can't internalize GV // in such case. if (!GV.isDeclaration() && VI && ImportIndex.withGlobalValueDeadStripping()) { const auto &SL = VI.getSummaryList(); auto *GVS = SL.empty() ? nullptr : dyn_cast<GlobalVarSummary>(SL[0].get()); if (GVS && GVS->isReadOnly()) cast<GlobalVariable>(&GV)->addAttribute("thinlto-internalize"); } bool DoPromote = false; if (GV.hasLocalLinkage() && ((DoPromote = shouldPromoteLocalToGlobal(&GV)) || isPerformingImport())) { // Save the original name string before we rename GV below. auto Name = GV.getName().str(); // Once we change the name or linkage it is difficult to determine // again whether we should promote since shouldPromoteLocalToGlobal needs // to locate the summary (based on GUID from name and linkage). Therefore, // use DoPromote result saved above. GV.setName(getName(&GV, DoPromote)); GV.setLinkage(getLinkage(&GV, DoPromote)); if (!GV.hasLocalLinkage()) GV.setVisibility(GlobalValue::HiddenVisibility); // If we are renaming a COMDAT leader, ensure that we record the COMDAT // for later renaming as well. This is required for COFF. if (const auto *C = GV.getComdat()) if (C->getName() == Name) RenamedComdats.try_emplace(C, M.getOrInsertComdat(GV.getName())); } else GV.setLinkage(getLinkage(&GV, /* DoPromote */ false)); // Remove functions imported as available externally defs from comdats, // as this is a declaration for the linker, and will be dropped eventually. // It is illegal for comdats to contain declarations. auto *GO = dyn_cast<GlobalObject>(&GV); if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) { // The IRMover should not have placed any imported declarations in // a comdat, so the only declaration that should be in a comdat // at this point would be a definition imported as available_externally. assert(GO->hasAvailableExternallyLinkage() && "Expected comdat on definition (possibly available external)"); GO->setComdat(nullptr); } }
/// linkGlobalProto - Loop through the global variables in the src module and /// merge them into the dest module. bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) { GlobalValue *DGV = getLinkedToGlobal(SGV); llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility; if (DGV) { // Concatenation of appending linkage variables is magic and handled later. if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage()) return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV); // Determine whether linkage of these two globals follows the source // module's definition or the destination module's definition. GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage; GlobalValue::VisibilityTypes NV; bool LinkFromSrc = false; if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc)) return true; NewVisibility = NV; // If we're not linking from the source, then keep the definition that we // have. if (!LinkFromSrc) { // Special case for const propagation. if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant()) DGVar->setConstant(true); // Set calculated linkage and visibility. DGV->setLinkage(NewLinkage); DGV->setVisibility(*NewVisibility); // Make sure to remember this mapping. ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType())); // Track the source global so that we don't attempt to copy it over when // processing global initializers. DoNotLinkFromSource.insert(SGV); return false; } } // No linking to be performed or linking from the source: simply create an // identical version of the symbol over in the dest module... the // initializer will be filled in later by LinkGlobalInits. GlobalVariable *NewDGV = new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()), SGV->isConstant(), SGV->getLinkage(), /*init*/0, SGV->getName(), /*insertbefore*/0, SGV->isThreadLocal(), SGV->getType()->getAddressSpace()); // Propagate alignment, visibility and section info. CopyGVAttributes(NewDGV, SGV); if (NewVisibility) NewDGV->setVisibility(*NewVisibility); if (DGV) { DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType())); DGV->eraseFromParent(); } // Make sure to remember this mapping. ValueMap[SGV] = NewDGV; return false; }