56#include <system_error>
62#define DEBUG_TYPE "function-import"
65 "Number of functions thin link decided to import");
67 "Number of hot functions thin link decided to import");
69 "Number of critical functions thin link decided to import");
71 "Number of global variables thin link decided to import");
72STATISTIC(NumImportedFunctions,
"Number of functions imported in backend");
74 "Number of function declarations imported in backend");
76 "Number of global variables imported in backend");
77STATISTIC(NumImportedModules,
"Number of modules imported from");
78STATISTIC(NumDeadSymbols,
"Number of dead stripped symbols in index");
79STATISTIC(NumLiveSymbols,
"Number of live symbols in index");
86 cl::desc(
"Import functions with noinline attribute"));
91 cl::desc(
"Only import functions with less than N instructions"));
95 cl::desc(
"Only import first N functions if N>=0 (default -1)"));
100 cl::desc(
"As we import functions, multiply the "
101 "`import-instr-limit` threshold by this factor "
102 "before processing newly imported functions"));
107 cl::desc(
"As we import functions called from hot callsite, multiply the "
108 "`import-instr-limit` threshold by this factor "
109 "before processing newly imported functions"));
113 cl::desc(
"Multiply the `import-instr-limit` threshold for hot callsites"));
119 "Multiply the `import-instr-limit` threshold for critical callsites"));
124 cl::desc(
"Multiply the `import-instr-limit` threshold for cold callsites"));
127 cl::desc(
"Print imported functions"));
131 cl::desc(
"Print information for functions rejected for importing"));
138 cl::desc(
"Enable import metadata like 'thinlto_src_module' and "
139 "'thinlto_src_file'"));
145 cl::desc(
"The summary file to use for function importing."));
151 cl::desc(
"Import all external functions in index."));
161 cl::desc(
"If true, import function declaration as fallback if the function "
162 "definition is not imported."));
173 "thinlto-workload-def",
174 cl::desc(
"Pass a workload definition. This is a file containing a JSON "
175 "dictionary. The keys are root functions, the values are lists of "
176 "functions to import in the module defining the root. It is "
177 "assumed -funique-internal-linkage-names was used, to ensure "
178 "local linkage functions have unique names. For example: \n"
180 " \"rootFunction_1\": [\"function_to_import_1\", "
181 "\"function_to_import_2\"], \n"
182 " \"rootFunction_2\": [\"function_to_import_3\", "
183 "\"function_to_import_4\"] \n"
190 "thinlto-move-ctxprof-trees",
191 cl::desc(
"Move contextual profiling roots and the graphs under them in "
192 "their own module."),
201static std::unique_ptr<Module>
loadFile(
const std::string &FileName,
207 std::unique_ptr<Module> Result =
211 Err.print(
"function-import",
errs());
240 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
244 [&Index, CalleeSummaryList,
245 CallerModulePath](
const std::unique_ptr<GlobalValueSummary> &SummaryPtr)
248 auto *GVSummary = SummaryPtr.get();
249 if (!Index.isGlobalValueLive(GVSummary))
286 if (Summary->notEligibleToImport())
311 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
312 unsigned Threshold,
StringRef CallerModulePath,
316 TooLargeOrNoInlineSummary =
nullptr;
317 auto QualifiedCandidates =
319 for (
auto QualifiedValue : QualifiedCandidates) {
320 Reason = QualifiedValue.first;
329 if ((Summary->instCount() > Threshold) && !Summary->fflags().AlwaysInline &&
331 TooLargeOrNoInlineSummary = Summary;
338 TooLargeOrNoInlineSummary = Summary;
357 auto [Def, Decl] = IDs.createImportIDs(FromModule, GUID);
358 if (!Imports.insert(Def).second)
370 auto [Def, Decl] = IDs.createImportIDs(FromModule, GUID);
373 if (!Imports.contains(Def))
374 Imports.insert(Decl);
380 for (
const auto &[SrcMod, GUID, ImportType] : *
this)
387std::optional<GlobalValueSummary::ImportKind>
390 if (
auto IDPair = IDs.getImportIDs(FromModule, GUID)) {
391 auto [Def, Decl] = *IDPair;
392 if (Imports.contains(Def))
394 if (Imports.contains(Decl))
411 const auto &GVS = DefinedGVSummaries.
find(VI.getGUID());
412 if (GVS == DefinedGVSummaries.end())
429 if (VI.getSummaryList().size() > 1 &&
431 !IsPrevailing(VI.getGUID(), GVS->second))
440 for (
const auto &VI : Summary.refs()) {
441 if (!shouldImportGlobal(VI, Summary.modulePath())) {
443 dbgs() <<
"Ref ignored! Target already in destination module.\n");
449 for (
const auto &RefSummary : VI.getSummaryList()) {
467 bool CanImportDecl =
false;
469 Summary.modulePath()) ||
470 !Index.canImportGlobalVar(GVS,
true,
473 ImportList.maybeAddDeclaration(RefSummary->modulePath(),
481 if (ImportList.addDefinition(RefSummary->modulePath(), VI.getGUID()) !=
487 NumImportedGlobalVarsThinLink++;
492 (*ExportLists)[RefSummary->modulePath()].insert(VI);
496 if (!Index.isWriteOnly(GVS))
510 : Index(Index), DefinedGVSummaries(DefinedGVSummaries),
511 IsPrevailing(IsPrevailing), ImportList(ImportList),
512 ExportLists(ExportLists) {}
516 onImportingSummaryImpl(Summary, Worklist);
517 while (!Worklist.
empty())
518 onImportingSummaryImpl(*Worklist.
pop_back_val(), Worklist);
526 void computeImportForFunction(
558 static std::unique_ptr<ModuleImportsManager>
592 if (SetIter == Workloads.end()) {
594 <<
" does not contain the root of any context.\n");
596 ModName, ImportList);
599 <<
" contains the root(s) of context(s).\n");
603 auto &ValueInfos = SetIter->second;
605 auto It = DefinedGVSummaries.
find(VI.getGUID());
606 if (It != DefinedGVSummaries.
end() &&
609 dbgs() <<
"[Workload] " << VI.name()
610 <<
" has the prevailing variant already in the module "
611 << ModName <<
". No need to import\n");
621 [&](
const auto &Candidate) {
623 <<
" from " << Candidate.second->modulePath()
624 <<
" ImportFailureReason: "
626 return Candidate.first ==
629 [](
const auto &Candidate) {
return Candidate.second; });
630 if (PotentialCandidates.empty()) {
632 <<
" because can't find eligible Callee. Guid is: "
633 << VI.getGUID() <<
"\n");
651 PotentialCandidates, [&](
const auto *Candidate) {
654 if (PrevailingCandidates.empty()) {
655 GVS = *PotentialCandidates.begin();
660 <<
"[Workload] Found multiple non-prevailing candidates for "
662 <<
". This is unexpected. Are module paths passed to the "
663 "compiler unique for the modules passed to the linker?");
672 GVS = *PrevailingCandidates.begin();
679 if (ExportingModule == ModName) {
681 <<
" because its defining module is the same as the "
685 LLVM_DEBUG(
dbgs() <<
"[Workload][Including]" << VI.name() <<
" from "
686 << ExportingModule <<
" : " << VI.getGUID() <<
"\n");
690 (*ExportLists)[ExportingModule].insert(VI);
695 void loadFromJson() {
702 if (!NameToValueInfo.
insert(std::make_pair(VI.name(), VI)).second)
705 auto DbgReportIfAmbiguous = [&](
StringRef Name) {
707 dbgs() <<
"[Workload] Function name " << Name
708 <<
" present in the workload definition is ambiguous. Consider "
709 "compiling with -funique-internal-linkage-names.";
714 if (std::error_code EC = BufferOrErr.getError()) {
718 auto Buffer = std::move(BufferOrErr.get());
719 std::map<std::string, std::vector<std::string>> WorkloadDefs;
732 for (
const auto &Workload : WorkloadDefs) {
733 const auto &Root = Workload.first;
734 DbgReportIfAmbiguous(Root);
736 const auto &AllCallees = Workload.second;
737 auto RootIt = NameToValueInfo.
find(Root);
738 if (RootIt == NameToValueInfo.
end()) {
740 <<
" not found in this linkage unit.\n");
743 auto RootVI = RootIt->second;
744 if (RootVI.getSummaryList().size() != 1) {
746 <<
" should have exactly one summary, but has "
747 << RootVI.getSummaryList().size() <<
". Skipping.\n");
751 RootVI.getSummaryList().
front()->modulePath();
752 LLVM_DEBUG(
dbgs() <<
"[Workload] Root defining module for " << Root
753 <<
" is : " << RootDefiningModule <<
"\n");
754 auto &Set = Workloads[RootDefiningModule];
755 for (
const auto &Callee : AllCallees) {
757 DbgReportIfAmbiguous(Callee);
758 auto ElemIt = NameToValueInfo.
find(Callee);
759 if (ElemIt == NameToValueInfo.
end()) {
763 Set.insert(ElemIt->second);
768 void loadFromCtxProf() {
771 if (std::error_code EC = BufferOrErr.getError()) {
775 auto Buffer = std::move(BufferOrErr.get());
783 const auto &CtxMap = Ctx->Contexts;
785 for (
const auto &[RootGuid, Root] : CtxMap) {
788 ContainedGUIDs.
clear();
790 auto RootVI =
Index.getValueInfo(RootGuid);
793 <<
" not found in this linkage unit.\n");
796 if (RootVI.getSummaryList().size() != 1) {
798 <<
" should have exactly one summary, but has "
799 << RootVI.getSummaryList().size() <<
". Skipping.\n");
802 std::string RootDefiningModule =
803 RootVI.getSummaryList().front()->modulePath().str();
805 RootDefiningModule = std::to_string(RootGuid);
807 dbgs() <<
"[Workload] Moving " << RootGuid
808 <<
" to a module with the filename without extension : "
809 << RootDefiningModule <<
"\n");
811 LLVM_DEBUG(
dbgs() <<
"[Workload] Root defining module for " << RootGuid
812 <<
" is : " << RootDefiningModule <<
"\n");
814 auto &Set = Workloads[RootDefiningModule];
815 Root.getContainedGuids(ContainedGUIDs);
816 Roots.insert(RootVI);
817 for (
auto Guid : ContainedGUIDs)
834 "Pass only one of: -thinlto-pgo-ctx-prof or -thinlto-workload-def");
842 for (
const auto &[Root, Set] : Workloads) {
843 dbgs() <<
"[Workload] Root: " << Root <<
" we have " << Set.size()
844 <<
" distinct callees.\n";
845 for (
const auto &VI : Set) {
846 dbgs() <<
"[Workload] Root: " << Root
847 <<
" Would include: " << VI.getGUID() <<
"\n";
860 LLVM_DEBUG(
dbgs() <<
"[Workload] Using the regular imports manager.\n");
861 return std::unique_ptr<ModuleImportsManager>(
864 LLVM_DEBUG(
dbgs() <<
"[Workload] Using the contextual imports manager.\n");
881 return "InterposableLinkage";
883 return "LocalLinkageNotInModule";
885 return "NotEligible";
895void ModuleImportsManager::computeImportForFunction(
896 const FunctionSummary &Summary,
const unsigned Threshold,
898 SmallVectorImpl<EdgeInfo> &Worklist, GlobalsImporter &GVImporter,
899 FunctionImporter::ImportMapTy &ImportList,
902 static int ImportCount = 0;
904 ValueInfo
VI =
Edge.first;
905 LLVM_DEBUG(
dbgs() <<
" edge -> " << VI <<
" Threshold:" << Threshold
914 if (DefinedGVSummaries.
count(
VI.getGUID())) {
918 LLVM_DEBUG(
dbgs() <<
"ignored! Target already in destination module.\n");
922 if (!canImport(VI)) {
924 dbgs() <<
"Skipping over " <<
VI.getGUID()
925 <<
" because its import is handled in a different module.");
926 assert(
VI.getSummaryList().size() == 1 &&
927 "The root was expected to be an external symbol");
941 const auto NewThreshold =
942 Threshold * GetBonusMultiplier(
Edge.second.getHotness());
944 auto IT = ImportThresholds.insert(std::make_pair(
945 VI.getGUID(), std::make_tuple(NewThreshold,
nullptr,
nullptr)));
946 bool PreviouslyVisited = !
IT.second;
947 auto &ProcessedThreshold = std::get<0>(
IT.first->second);
948 auto &CalleeSummary = std::get<1>(
IT.first->second);
949 auto &FailureInfo = std::get<2>(
IT.first->second);
953 bool IsCriticalCallsite =
956 const FunctionSummary *ResolvedCalleeSummary =
nullptr;
958 assert(PreviouslyVisited);
963 if (NewThreshold <= ProcessedThreshold) {
965 dbgs() <<
"ignored! Target was already imported with Threshold "
966 << ProcessedThreshold <<
"\n");
970 ProcessedThreshold = NewThreshold;
975 if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) {
977 dbgs() <<
"ignored! Target was already rejected with Threshold "
978 << ProcessedThreshold <<
"\n");
981 "Expected FailureInfo for previously rejected candidate");
982 FailureInfo->Attempts++;
990 const GlobalValueSummary *SummaryForDeclImport =
nullptr;
993 Summary.modulePath(), SummaryForDeclImport, Reason);
994 if (!CalleeSummary) {
998 StringRef DeclSourceModule = SummaryForDeclImport->
modulePath();
1007 if (PreviouslyVisited) {
1008 ProcessedThreshold = NewThreshold;
1011 "Expected FailureInfo for previously rejected candidate");
1012 FailureInfo->Reason = Reason;
1013 FailureInfo->Attempts++;
1014 FailureInfo->MaxHotness =
1015 std::max(FailureInfo->MaxHotness,
Edge.second.getHotness());
1019 "Expected no FailureInfo for newly rejected candidate");
1020 FailureInfo = std::make_unique<FunctionImporter::ImportFailureInfo>(
1021 VI,
Edge.second.getHotness(), Reason, 1);
1024 std::string
Msg = std::string(
"Failed to import function ") +
1025 VI.name().str() +
" due to " +
1030 "Error importing module: ");
1034 <<
"ignored! No qualifying callee with summary found.\n");
1040 CalleeSummary = CalleeSummary->getBaseObject();
1044 (ResolvedCalleeSummary->
instCount() <= NewThreshold)) &&
1045 "selectCallee() didn't honor the threshold");
1047 auto ExportModulePath = ResolvedCalleeSummary->
modulePath();
1053 NumImportedFunctionsThinLink++;
1055 NumImportedHotFunctionsThinLink++;
1056 if (IsCriticalCallsite)
1057 NumImportedCriticalFunctionsThinLink++;
1064 (*ExportLists)[ExportModulePath].insert(VI);
1067 auto GetAdjustedThreshold = [](
unsigned Threshold,
bool IsHotCallsite) {
1076 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
1081 Worklist.
emplace_back(ResolvedCalleeSummary, AdjThreshold);
1097 for (
const auto &GVSummary : DefinedGVSummaries) {
1101 auto VI =
Index.getValueInfo(GVSummary.first);
1103 if (!
Index.isGlobalValueLive(GVSummary.second)) {
1113 computeImportForFunction(*FuncSummary,
ImportInstrLimit, DefinedGVSummaries,
1114 Worklist, GVI, ImportList, ImportThresholds);
1118 while (!Worklist.
empty()) {
1120 auto *Summary = std::get<0>(GVInfo);
1121 auto Threshold = std::get<1>(GVInfo);
1123 computeImportForFunction(*Summary, Threshold, DefinedGVSummaries, Worklist,
1124 GVI, ImportList, ImportThresholds);
1130 dbgs() <<
"Missed imports into module " << ModName <<
"\n";
1131 for (
auto &
I : ImportThresholds) {
1132 auto &ProcessedThreshold = std::get<0>(
I.second);
1133 auto &CalleeSummary = std::get<1>(
I.second);
1134 auto &FailureInfo = std::get<2>(
I.second);
1139 if (!FailureInfo->VI.getSummaryList().empty())
1141 FailureInfo->VI.getSummaryList()[0]->getBaseObject());
1142 dbgs() << FailureInfo->VI
1144 <<
", Threshold = " << ProcessedThreshold
1145 <<
", Size = " << (FS ? (int)FS->instCount() : -1)
1147 <<
", Attempts = " << FailureInfo->Attempts <<
"\n";
1154 auto SL = VI.getSummaryList();
1162 if (
const auto &VI = Index.getValueInfo(
G))
1171 unsigned NumGVS = 0;
1172 for (
auto &VI : ExportSet)
1190 for (
const auto &[FromModule, GUID,
Type] : ImportList) {
1209 for (
const auto &ImportPerModule : ImportLists)
1210 for (
const auto &[FromModule, GUID, ImportType] : ImportPerModule.second)
1211 FlattenedImports.
insert(GUID);
1219 auto IsReadOrWriteOnlyVarNeedingImporting = [&](
StringRef ModulePath,
1222 Index.findSummaryInModule(VI, ModulePath));
1223 return GVS && (Index.isReadOnly(GVS) || Index.isWriteOnly(GVS)) &&
1229 for (
auto &ExportPerModule : ExportLists)
1230 for (
auto &VI : ExportPerModule.second)
1231 if (!FlattenedImports.
count(VI.getGUID()) &&
1232 IsReadOrWriteOnlyVarNeedingImporting(ExportPerModule.first, VI))
1249 for (
const auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
1250 auto &ImportList = ImportLists[DefinedGVSummaries.first];
1252 << DefinedGVSummaries.first <<
"'\n");
1253 MIS->computeImportForModule(DefinedGVSummaries.second,
1254 DefinedGVSummaries.first, ImportList);
1262 for (
auto &ELI : ExportLists) {
1266 const auto &DefinedGVSummaries =
1267 ModuleToDefinedGVSummaries.
lookup(ELI.first);
1268 for (
auto &EI : ELI.second) {
1275 auto DS = DefinedGVSummaries.
find(EI.getGUID());
1279 auto *S = DS->getSecond();
1280 S = S->getBaseObject();
1286 if (!Index.isWriteOnly(GVS))
1299 [&](
ValueInfo VI) {
return !DefinedGVSummaries.
count(VI.getGUID()); });
1300 ELI.second.insert_range(NewExports);
1307 for (
const auto &ModuleImports : ImportLists) {
1308 auto ModName = ModuleImports.first;
1309 auto &Exports = ExportLists[ModName];
1314 << Exports.
size() - NumGVS <<
" functions and " << NumGVS
1315 <<
" vars. Imports from " << Histogram.
size()
1317 for (
const auto &[SrcModName,
Stats] : Histogram) {
1319 <<
" function definitions and "
1321 <<
" function declarations imported from " << SrcModName
1324 <<
" global vars imported from " << SrcModName <<
"\n");
1336 LLVM_DEBUG(
dbgs() <<
"* Module " << ModulePath <<
" imports from "
1337 << Histogram.
size() <<
" modules.\n");
1338 for (
const auto &[SrcModName,
Stats] : Histogram) {
1340 <<
" function definitions and "
1342 <<
" function declarations imported from " << SrcModName
1345 << SrcModName <<
"\n");
1367 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
1370 LLVM_DEBUG(
dbgs() <<
"Computing import for Module '" << ModulePath <<
"'\n");
1372 MIS->computeImportForModule(FunctionSummaryMap, ModulePath, ImportList);
1387 for (
const auto &GlobalList : Index) {
1389 if (GlobalList.second.getSummaryList().empty())
1392 auto GUID = GlobalList.first;
1393 assert(GlobalList.second.getSummaryList().size() == 1 &&
1394 "Expected individual combined index to have one summary per GUID");
1395 auto &Summary = GlobalList.second.getSummaryList()[0];
1398 if (Summary->modulePath() == ModulePath)
1401 ImportList.
addGUID(Summary->modulePath(), GUID, Summary->importType());
1417 if (!CalleeVI || !CalleeVI.getSummaryList().empty())
1419 auto GUID = Index.getGUIDFromOriginalID(CalleeVI.getGUID());
1422 auto VI = Index.getValueInfo(GUID);
1424 VI.getSummaryList(),
1425 [&](
const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
1435 return SummaryPtr->getSummaryKind() ==
1436 GlobalValueSummary::GlobalVarKind;
1442 for (
auto &EI : FS->mutableCalls()) {
1444 if (
auto VI = GetUpdatedCallee(EI.first))
1455 if (FS->callsites().empty())
1457 for (
auto &CI : FS->mutableCallsites()) {
1458 if (
auto VI = GetUpdatedCallee(CI.Callee))
1464 for (
const auto &Entry : Index) {
1465 for (
const auto &S : Entry.second.getSummaryList()) {
1476 assert(!Index.withGlobalValueDeadStripping());
1479 GUIDPreservedSymbols.
empty()) {
1484 unsigned LiveSymbols = 0;
1486 Worklist.
reserve(GUIDPreservedSymbols.
size() * 2);
1487 for (
auto GUID : GUIDPreservedSymbols) {
1488 ValueInfo VI = Index.getValueInfo(GUID);
1491 for (
const auto &S : VI.getSummaryList())
1496 for (
const auto &Entry : Index) {
1497 auto VI = Index.getValueInfo(Entry);
1498 for (
const auto &S : Entry.second.getSummaryList()) {
1522 [](
const std::unique_ptr<llvm::GlobalValueSummary> &S) {
1533 bool KeepAliveLinkage =
false;
1534 bool Interposable =
false;
1535 for (
const auto &S : VI.getSummaryList()) {
1539 KeepAliveLinkage =
true;
1541 Interposable =
true;
1545 if (!KeepAliveLinkage)
1550 "Interposable and available_externally/linkonce_odr/weak_odr "
1555 for (
const auto &S : VI.getSummaryList())
1561 while (!Worklist.
empty()) {
1563 for (
const auto &Summary : VI.getSummaryList()) {
1568 visit(AS->getAliaseeVI(),
true);
1571 for (
auto Ref : Summary->refs())
1574 for (
auto Call : FS->calls())
1578 Index.setWithGlobalValueDeadStripping();
1580 unsigned DeadSymbols = Index.size() - LiveSymbols;
1581 LLVM_DEBUG(
dbgs() << LiveSymbols <<
" symbols Live, and " << DeadSymbols
1582 <<
" symbols Dead \n");
1583 NumDeadSymbols += DeadSymbols;
1584 NumLiveSymbols += LiveSymbols;
1592 bool ImportEnabled) {
1597 Index.propagateAttributes(GUIDPreservedSymbols);
1609 ModuleToSummariesForIndex[std::string(ModulePath)] =
1610 ModuleToDefinedGVSummaries.
lookup(ModulePath);
1619 auto It = Map.find(
Key);
1620 if (It == Map.end())
1621 std::tie(It, std::ignore) =
1627 for (
const auto &[FromModule, GUID, ImportType] : ImportList) {
1628 auto &SummariesForIndex =
1629 LookupOrCreate(ModuleToSummariesForIndex, FromModule);
1631 const auto &DefinedGVSummaries = ModuleToDefinedGVSummaries.
at(FromModule);
1632 const auto &DS = DefinedGVSummaries.
find(GUID);
1633 assert(DS != DefinedGVSummaries.
end() &&
1634 "Expected a defined summary for imported global value");
1636 DecSummaries.
insert(DS->second);
1638 SummariesForIndex[GUID] = DS->second;
1654 for (
auto &[ModPath, SummariesForIndex] : ModuleToSummariesForIndex) {
1655 if (ModPath == ModulePath)
1657 auto It = ModuleToDefinedGVSummaries.
find(ModPath);
1658 if (It == ModuleToDefinedGVSummaries.
end())
1660 for (
const auto &[GUID, Summary] : It->second) {
1661 if (Summary->noRenameOnPromotion()) {
1662 DecSummaries.
insert(Summary);
1663 SummariesForIndex.try_emplace(GUID, Summary);
1680 [&](
StringRef M) { ImportsOS << M <<
"\n"; });
1690 for (
const auto &ILI : ModuleToSummariesForIndex)
1694 if (ILI.first != ModulePath)
1703 UniqueID = GO->getMetadata(LLVMContext::MD_guid);
1709 F->setMetadata(LLVMContext::MD_guid,
UniqueID);
1710 F->setComdat(
nullptr);
1712 V->setInitializer(
nullptr);
1716 V->setMetadata(LLVMContext::MD_guid,
UniqueID);
1717 V->setComdat(
nullptr);
1746 auto FinalizeInModule = [&](
GlobalValue &GV,
bool Propagate =
false) {
1749 if (GS == DefinedGlobals.
end())
1756 if (FS->fflags().ReadNone && !
F->doesNotAccessMemory())
1757 F->setDoesNotAccessMemory();
1759 if (FS->fflags().ReadOnly && !
F->onlyReadsMemory())
1760 F->setOnlyReadsMemory();
1762 if (FS->fflags().NoRecurse && !
F->doesNotRecurse())
1763 F->setDoesNotRecurse();
1765 if (FS->fflags().NoUnwind && !
F->doesNotThrow())
1766 F->setDoesNotThrow();
1770 auto NewLinkage = GS->second->linkage();
1809 GS->second->canAutoHide()) {
1815 <<
"` from " << GV.
getLinkage() <<
" to " << NewLinkage
1823 if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
1824 if (GO->getComdat()->getName() == GO->getName())
1825 NonPrevailingComdats.
insert(GO->getComdat());
1826 GO->setComdat(
nullptr);
1831 for (
auto &GV : TheModule)
1833 for (
auto &GV : TheModule.
globals())
1834 FinalizeInModule(GV);
1835 for (
auto &GV : TheModule.
aliases())
1836 FinalizeInModule(GV);
1841 if (NonPrevailingComdats.
empty())
1844 if (
auto *
C = GO.getComdat();
C && NonPrevailingComdats.
count(
C)) {
1845 GO.setComdat(
nullptr);
1856 for (
auto &GA : TheModule.
aliases()) {
1857 if (GA.hasAvailableExternallyLinkage())
1860 assert(Obj &&
"aliasee without an base object is unimplemented");
1861 if (Obj->hasAvailableExternallyLinkage()) {
1875 auto MustPreserveGV = [&](
const GlobalValue &GV) ->
bool {
1885 auto GS = DefinedGlobals.
find(GV.getGUIDOrFallback());
1886 if (GS == DefinedGlobals.
end()) {
1897 GS = DefinedGlobals.
find(
1899 if (GS == DefinedGlobals.
end()) {
1906 GS = DefinedGlobals.
find(
1937 for (
auto &GV : M.globals())
1940 if (!GV.isDeclaration() && GV.hasAttribute(
"thinlto-internalize")) {
1954 if (!
F.hasAvailableExternallyLinkage() ||
1955 !
F.hasMetadata(LLVMContext::MD_implicit_ref))
1958 F.getMetadata(LLVMContext::MD_implicit_ref, MDs);
1960 auto *
Op = MD->getOperand(0).get();
1965 if (GV->hasAvailableExternallyLinkage() && Seen.
insert(GV).second)
1969 if (!ToProtect.
empty())
1979 unsigned ImportedCount = 0, ImportedGVCount = 0;
1986 for (
auto &
F : DestModule)
1987 if (!
F.isDeclaration() && MoveSymbolGUIDSet.
contains(
F.getGUIDOrFallback()))
1997 if (!SrcModuleOrErr)
1999 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
2001 "Context mismatch");
2005 if (
Error Err = SrcModule->materializeMetadata())
2006 return std::move(Err);
2018 auto GUID =
F.getGUIDOrFallback();
2019 auto MaybeImportType = ImportList.
getImportType(ModName, GUID);
2020 bool ImportDefinition =
2024 <<
" importing function"
2025 << (ImportDefinition
2027 : (MaybeImportType ?
" declaration " :
" "))
2028 << GUID <<
" " <<
F.getName() <<
" from "
2029 << SrcModule->getSourceFileName() <<
"\n");
2030 if (ImportDefinition) {
2031 if (
Error Err =
F.materialize())
2032 return std::move(Err);
2039 "thinlto_src_module",
2041 {MDString::get(DestModule.getContext(),
2042 SrcModule->getModuleIdentifier())}));
2046 {MDString::get(DestModule.getContext(),
2047 SrcModule->getSourceFileName())}));
2050 }
else if (MaybeImportType) {
2061 auto GUID = GV.getGUIDOrFallback();
2062 auto MaybeImportType = ImportList.
getImportType(ModName, GUID);
2063 bool ImportDefinition =
2067 <<
" importing global"
2068 << (ImportDefinition
2070 : (MaybeImportType ?
" declaration " :
" "))
2071 << GUID <<
" " << GV.getName() <<
" from "
2072 << SrcModule->getSourceFileName() <<
"\n");
2073 if (ImportDefinition) {
2074 if (
Error Err = GV.materialize())
2075 return std::move(Err);
2076 ImportedGVCount += GlobalsToImport.
insert(&GV);
2085 auto GUID = GA.getGUIDOrFallback();
2086 auto MaybeImportType = ImportList.
getImportType(ModName, GUID);
2087 bool ImportDefinition =
2091 <<
" importing alias"
2092 << (ImportDefinition
2094 : (MaybeImportType ?
" declaration " :
" "))
2095 << GUID <<
" " << GA.getName() <<
" from "
2096 << SrcModule->getSourceFileName() <<
"\n");
2097 if (ImportDefinition) {
2098 if (
Error Err = GA.materialize())
2099 return std::move(Err);
2103 return std::move(Err);
2109 <<
" " << GO->
getName() <<
" from "
2110 << SrcModule->getSourceFileName() <<
"\n");
2115 "thinlto_src_module",
2117 {MDString::get(DestModule.getContext(),
2118 SrcModule->getModuleIdentifier())}));
2122 {MDString::get(DestModule.getContext(),
2123 SrcModule->getSourceFileName())}));
2125 GlobalsToImport.
insert(Fn);
2126 }
else if (MaybeImportType) {
2142 SrcModule->setPartialSampleProfileRatio(Index);
2162 for (
auto [GV, GUID] : DeclsToImport) {
2163 assert(!GV->hasLocalLinkage() &&
2164 "Expected imported declaration to be promoted");
2171 DeclInfos.
push_back({GV->getName().str(),
F->getFunctionType(),
2172 F->getAddressSpace(),
F->getCallingConv(),
2173 F->getAttributes(), GV->getVisibility(),
2174 GV->isDSOLocal(), GUID});
2178 for (
const auto *GV : GlobalsToImport)
2180 <<
" from " << SrcModule->getSourceFileName() <<
"\n";
2183 if (
Error Err = Mover.
move(std::move(SrcModule),
2187 Twine(
"Function Import: link error: ") +
2190 ImportedCount += GlobalsToImport.
size();
2191 NumImportedModules++;
2205 for (
auto &DI : DeclInfos) {
2209 DI.AddrSpace, DI.Name, &DestModule);
2210 F->setCallingConv(DI.CC);
2211 F->setAttributes(DI.Attrs);
2214 F->setVisibility(DI.Visibility);
2215 F->setDSOLocal(DI.DSOLocal);
2219 F->setMetadata(LLVMContext::MD_guid,
2221 {ConstantAsMetadata::get(ConstantInt::get(
2222 Type::getInt64Ty(DestModule.getContext()),
2224 NumImportedFunctionDecls++;
2232 if (ImportedGVCount > 0)
2235 NumImportedFunctions += (ImportedCount - ImportedGVCount);
2236 NumImportedGlobalVars += ImportedGVCount;
2239 LLVM_DEBUG(
dbgs() <<
"Imported " << ImportedCount - ImportedGVCount
2240 <<
" functions for Module "
2243 <<
" global variables for Module "
2245 return ImportedCount;
2255 if (!IndexPtrOrErr) {
2260 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
2270 *Index, ImportList);
2273 isPrevailing, *Index, ImportList);
2279 for (
auto &
I : *Index) {
2280 for (
auto &S :
I.second.getSummaryList()) {
2282 S->setExternalLinkageForTest();
2292 auto ModuleLoader = [&M](
StringRef Identifier) {
2293 return loadFile(std::string(Identifier), M.getContext());
2302 "Error importing module: ");
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
static auto qualifyCalleeCandidates(const ModuleSummaryIndex &Index, ArrayRef< std::unique_ptr< GlobalValueSummary > > CalleeSummaryList, StringRef CallerModulePath)
Given a list of possible callee implementation for a call site, qualify the legality of importing eac...
static DenseMap< StringRef, ImportStatistics > collectImportStatistics(const ModuleSummaryIndex &Index, const FunctionImporter::ImportMapTy &ImportList)
static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index, FunctionImporter::ExportSetTy &ExportSet)
static bool checkVariableImport(const ModuleSummaryIndex &Index, FunctionImporter::ImportListsTy &ImportLists, DenseMap< StringRef, FunctionImporter::ExportSetTy > &ExportLists)
static bool doImportingForModuleForTest(Module &M, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
static const char * getFailureName(FunctionImporter::ImportFailureReason Reason)
static void internalizeGVsAfterImport(Module &M)
void updateValueInfoForIndirectCalls(ModuleSummaryIndex &Index, FunctionSummary *FS)
static std::unique_ptr< Module > loadFile(const std::string &FileName, LLVMContext &Context)
static bool shouldSkipLocalInAnotherModule(const GlobalValueSummary *RefSummary, size_t NumDefs, StringRef ImporterModule)
static bool isGlobalVarSummary(const ModuleSummaryIndex &Index, ValueInfo VI)
static Function * replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA)
Make alias a clone of its aliasee.
static void protectImplicitRefGlobals(Module &M)
When a function carrying !implicit.ref is imported via ThinLTO, the referenced global arrives as avai...
static void dumpImportListForModule(const ModuleSummaryIndex &Index, StringRef ModulePath, FunctionImporter::ImportMapTy &ImportList)
static void ComputeCrossModuleImportForModuleFromIndexForTest(StringRef ModulePath, const ModuleSummaryIndex &Index, FunctionImporter::ImportMapTy &ImportList)
Mark all external summaries in Index for import into the given module.
static const GlobalValueSummary * selectCallee(const ModuleSummaryIndex &Index, ArrayRef< std::unique_ptr< GlobalValueSummary > > CalleeSummaryList, unsigned Threshold, StringRef CallerModulePath, const GlobalValueSummary *&TooLargeOrNoInlineSummary, FunctionImporter::ImportFailureReason &Reason)
Given a list of possible callee implementation for a call site, select one that fits the Threshold fo...
static void ComputeCrossModuleImportForModuleForTest(StringRef ModulePath, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, const ModuleSummaryIndex &Index, FunctionImporter::ImportMapTy &ImportList)
Compute all the imports for the given module using the Index.
Module.h This file contains the declarations for the Module class.
This file supports working with JSON data.
block placement Basic Block Placement Stats
static cl::opt< std::string > OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"), cl::init("-"))
static cl::opt< bool > PropagateAttrs("propagate-attrs", cl::init(true), cl::Hidden, cl::desc("Propagate attributes in index"))
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
static constexpr StringLiteral Filename
Reader for contextual iFDO profile, which comes in bitstream format.
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
std::pair< BasicBlock *, BasicBlock * > Edge
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Import globals referenced by a function or other globals that are being imported, if importing such g...
void onImportingSummary(const GlobalValueSummary &Summary)
GlobalsImporter(const ModuleSummaryIndex &Index, const GVSummaryMapTy &DefinedGVSummaries, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> IsPrevailing, FunctionImporter::ImportMapTy &ImportList, DenseMap< StringRef, FunctionImporter::ExportSetTy > *ExportLists)
virtual bool canImport(ValueInfo VI)
DenseMap< StringRef, FunctionImporter::ExportSetTy > *const ExportLists
virtual ~ModuleImportsManager()=default
static std::unique_ptr< ModuleImportsManager > create(function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> IsPrevailing, const ModuleSummaryIndex &Index, DenseMap< StringRef, FunctionImporter::ExportSetTy > *ExportLists=nullptr)
function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> IsPrevailing
ModuleImportsManager(function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> IsPrevailing, const ModuleSummaryIndex &Index, DenseMap< StringRef, FunctionImporter::ExportSetTy > *ExportLists=nullptr)
const ModuleSummaryIndex & Index
virtual void computeImportForModule(const GVSummaryMapTy &DefinedGVSummaries, StringRef ModName, FunctionImporter::ImportMapTy &ImportList)
Given the list of globals defined in a module, compute the list of imports as well as the list of "ex...
WorkloadImportsManager(function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> IsPrevailing, const ModuleSummaryIndex &Index, DenseMap< StringRef, FunctionImporter::ExportSetTy > *ExportLists)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
iterator find(const_arg_type_t< KeyT > Val)
ValueT & at(const_arg_type_t< KeyT > Val)
Return the entry for the specified key, or abort if no such entry exists.
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Implements a dense probed hash-table based set.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
The map maintains the list of imports.
LLVM_ABI AddDefinitionStatus addDefinition(StringRef FromModule, GlobalValue::GUID GUID)
void addGUID(StringRef FromModule, GlobalValue::GUID GUID, GlobalValueSummary::ImportKind ImportKind)
LLVM_ABI SmallVector< StringRef, 0 > getSourceModules() const
LLVM_ABI std::optional< GlobalValueSummary::ImportKind > getImportType(StringRef FromModule, GlobalValue::GUID GUID) const
LLVM_ABI void maybeAddDeclaration(StringRef FromModule, GlobalValue::GUID GUID)
The function importer is automatically importing function from other modules based on the provided su...
LLVM_ABI Expected< bool > importFunctions(Module &M, const ImportMapTy &ImportList)
Import functions in Module M based on the supplied import list.
DenseMap< GlobalValue::GUID, std::tuple< unsigned, const GlobalValueSummary *, std::unique_ptr< ImportFailureInfo > > > ImportThresholdsTy
Map of callee GUID considered for import into a given module to a pair consisting of the largest thre...
ImportFailureReason
The different reasons selectCallee will chose not to import a candidate.
@ LocalLinkageNotInModule
DenseSet< ValueInfo > ExportSetTy
The set contains an entry for every global value that the module exports.
Function summary information to aid decisions and implementation of importing.
unsigned instCount() const
Get the instruction count recorded for this function.
FFlags fflags() const
Get function summary flags.
Class to represent function types.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
LLVM_ABI const GlobalObject * getAliaseeObject() const
Function and variable summary information to aid decisions and implementation of importing.
StringRef modulePath() const
Get the path to the module containing this function.
GlobalValue::LinkageTypes linkage() const
Return linkage type recorded for this global value.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
VisibilityTypes getVisibility() const
bool isImplicitDSOLocal() const
static bool isLocalLinkage(LinkageTypes Linkage)
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
LinkageTypes getLinkage() const
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
LLVM_ABI GUID getGUIDOrFallback() const
Return the GUID for this value if it has been assigned, otherwise fall back to computing it based on ...
ThreadLocalMode getThreadLocalMode() const
static bool isAvailableExternallyLinkage(LinkageTypes Linkage)
void setLinkage(LinkageTypes LT)
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI const GlobalObject * getAliaseeObject() const
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
void setVisibility(VisibilityTypes V)
static bool isInterposableLinkage(LinkageTypes Linkage)
Whether the definition of this global may be replaced by something non-equivalent at link time.
LLVM_ABI Error materialize()
Make sure this GlobalValue is fully read.
LLVM_ABI bool canBeOmittedFromSymbolTable() const
True if GV can be left out of the object symbol table.
@ InternalLinkage
Rename collisions when linking (static functions).
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Type * getValueType() const
LLVM_ABI Error move(std::unique_ptr< Module > Src, ArrayRef< GlobalValue * > ValuesToLink, LazyCallback AddLazyFor, bool IsPerformingImport)
Move in the provide values in ValuesToLink from Src.
This is an important class for using LLVM in a threaded context.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static StringRef getOriginalNameBeforePromote(StringRef Name)
Helper to obtain the unpromoted name for a global value (or the original name if not promoted).
A Module instance is used to store all the information related to an LLVM module.
LLVMContext & getContext() const
Get the global data context.
const std::string & getSourceFileName() const
Get the module's original source file name.
iterator_range< alias_iterator > aliases()
iterator_range< global_iterator > globals()
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
iterator_range< global_object_iterator > global_objects()
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type.
LLVM_ABI Expected< PGOCtxProfile > loadProfiles()
unsigned getAddressSpace() const
Return the address space of the Pointer type.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
A vector that has set insertion semantics.
ArrayRef< value_type > getArrayRef() const
size_type size() const
Determine the number of elements in the SetVector.
Vector takeVector()
Clear the SetVector and return the underlying vector.
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
void clear()
Completely clear the SetVector.
bool insert(const value_type &X)
Insert a new element into the SetVector.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
iterator find(StringRef Key)
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Represent a constant reference to a string, i.e.
constexpr size_t size() const
Get the string size.
char front() const
Get the first character in the string.
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
StringSet - A wrapper for StringMap that provides set-like functionality.
std::pair< typename Base::iterator, bool > insert(StringRef key)
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
bool isFunctionTy() const
True if this is an instance of FunctionType.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
std::pair< iterator, bool > insert(const ValueT &V)
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
void insert_range(Range &&R)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
bool remove_if(Predicate Pred)
Remove all elements for which Pred returns true.
An efficient, type-erasing, non-owning reference to a callable.
The root is the trivial Path to the root value.
A raw_ostream that writes to a file descriptor.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
initializer< Ty > init(const Ty &Val)
LLVM_ABI llvm::Expected< Value > parse(llvm::StringRef JSON)
Parses the provided JSON source, or returns a ParseError.
bool fromJSON(const Value &E, std::string &Out, Path P)
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
static cl::opt< float > ImportHotMultiplier("import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"), cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"))
static cl::opt< bool > CtxprofMoveRootsToOwnModule("thinlto-move-ctxprof-trees", cl::desc("Move contextual profiling roots and the graphs under them in " "their own module."), cl::Hidden, cl::init(false))
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
bool internalizeModule(Module &TheModule, std::function< bool(const GlobalValue &)> MustPreserveGV)
Helper function to internalize functions and variables in a Module.
static cl::opt< float > ImportColdMultiplier("import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"), cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"))
std::error_code make_error_code(BitcodeError E)
cl::list< GlobalValue::GUID > MoveSymbolGUID
const char * getHotnessName(CalleeInfo::HotnessType HT)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
static cl::opt< std::string > WorkloadDefinitions("thinlto-workload-def", cl::desc("Pass a workload definition. This is a file containing a JSON " "dictionary. The keys are root functions, the values are lists of " "functions to import in the module defining the root. It is " "assumed -funique-internal-linkage-names was used, to ensure " "local linkage functions have unique names. For example: \n" "{\n" " \"rootFunction_1\": [\"function_to_import_1\", " "\"function_to_import_2\"], \n" " \"rootFunction_2\": [\"function_to_import_3\", " "\"function_to_import_4\"] \n" "}"), cl::Hidden)
Pass a workload description file - an example of workload would be the functions executed to satisfy ...
DenseMap< GlobalValue::GUID, GlobalValueSummary * > GVSummaryMapTy
Map of global value GUID to its summary, used to identify values defined in a particular module,...
cl::opt< std::string > UseCtxProfile("use-ctx-profile", cl::init(""), cl::Hidden, cl::desc("Use the specified contextual profile file"))
static cl::opt< bool > PrintImportFailures("print-import-failures", cl::init(false), cl::Hidden, cl::desc("Print information for functions rejected for importing"))
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
LLVM_ABI bool convertToDeclaration(GlobalValue &GV)
Converts value GV to declaration, or replaces with a declaration if it is an alias.
static cl::opt< unsigned > ImportInstrLimit("import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"), cl::desc("Only import functions with less than N instructions"))
Limit on instruction count of imported functions.
LLVM_ABI void renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index, bool ClearDSOLocalOnDeclarations, SetVector< GlobalValue * > *GlobalsToImport=nullptr)
Perform in-place global value handling on the given Module for exported local functions renamed and p...
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
static cl::opt< float > ImportHotInstrFactor("import-hot-evolution-factor", cl::init(1.0), cl::Hidden, cl::value_desc("x"), cl::desc("As we import functions called from hot callsite, multiply the " "`import-instr-limit` threshold by this factor " "before processing newly imported functions"))
static cl::opt< bool > PrintImports("print-imports", cl::init(false), cl::Hidden, cl::desc("Print imported functions"))
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
LLVM_ABI void ComputeCrossModuleImport(const ModuleSummaryIndex &Index, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, FunctionImporter::ImportListsTy &ImportLists, DenseMap< StringRef, FunctionImporter::ExportSetTy > &ExportLists)
Compute all the imports and exports for every module in the Index.
auto dyn_cast_or_null(const Y &Val)
static cl::opt< float > ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7), cl::Hidden, cl::value_desc("x"), cl::desc("As we import functions, multiply the " "`import-instr-limit` threshold by this factor " "before processing newly imported functions"))
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
void sort(IteratorTy Start, IteratorTy End)
cl::opt< bool > AlwaysRenamePromotedLocals("always-rename-promoted-locals", cl::init(true), cl::Hidden, cl::desc("Always rename promoted locals."))
LLVM_ABI void computeDeadSymbolsAndUpdateIndirectCalls(ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols, function_ref< PrevailingType(GlobalValue::GUID)> isPrevailing)
Compute all the symbols that are "dead": i.e these that can't be reached in the graph from any of the...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
bool hasSingleElement(ContainerTy &&C)
Returns true if the given container only contains a single element.
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
static cl::opt< bool > ImportAllIndex("import-all-index", cl::desc("Import all external functions in index."))
Used when testing importing from distributed indexes via opt.
static cl::opt< int > ImportCutoff("import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"), cl::desc("Only import first N functions if N>=0 (default -1)"))
static cl::opt< bool > ImportDeclaration("import-declaration", cl::init(false), cl::Hidden, cl::desc("If true, import function declaration as fallback if the function " "definition is not imported."))
This is a test-only option.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
LLVM_ABI void updateIndirectCalls(ModuleSummaryIndex &Index)
Update call edges for indirect calls to local functions added from SamplePGO when needed.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Ref
The access may reference the value stored in memory.
cl::opt< bool > EnableMemProfContextDisambiguation
Enable MemProf context disambiguation for thin link.
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
LLVM_ABI std::unique_ptr< Module > getLazyIRFileModule(StringRef Filename, SMDiagnostic &Err, LLVMContext &Context, bool ShouldLazyLoadMetadata=false)
If the given file holds a bitcode image, return a Module for it which does lazy deserialization of fu...
LLVM_ABI void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Internalize TheModule based on the information recorded in the summaries during global summary-based ...
cl::opt< bool > ForceImportAll
DWARFExpression::Operation Op
LLVM_ABI void gatherImportedSummariesForModule(StringRef ModulePath, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, const FunctionImporter::ImportMapTy &ImportList, ModuleToSummariesForIndexTy &ModuleToSummariesForIndex, GVSummaryPtrSet &DecSummaries)
Compute the set of summaries needed for a ThinLTO backend compilation of ModulePath.
static cl::opt< std::string > SummaryFile("summary-file", cl::desc("The summary file to use for function importing."))
Summary file to use for function importing when using -function-import from the command line.
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI void processImportsFiles(StringRef ModulePath, const ModuleToSummariesForIndexTy &ModuleToSummariesForIndex, function_ref< void(const std::string &)> F)
Call F passing each of the files module ModulePath will import from.
static cl::opt< float > ImportCriticalMultiplier("import-critical-multiplier", cl::init(100.0), cl::Hidden, cl::value_desc("x"), cl::desc("Multiply the `import-instr-limit` threshold for critical callsites"))
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
PrevailingType
PrevailingType enum used as a return type of callback passed to computeDeadSymbolsAndUpdateIndirectCa...
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
static cl::opt< bool > EnableImportMetadata("enable-import-metadata", cl::init(false), cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module' and " "'thinlto_src_file'"))
SmallPtrSet< GlobalValueSummary *, 0 > GVSummaryPtrSet
A set of global value summary pointers.
LLVM_ABI Function * CloneFunction(Function *F, ValueToValueMapTy &VMap, ClonedCodeInfo *CodeInfo=nullptr)
Return a copy of the specified function and add it to that function's module.
LLVM_ABI void computeDeadSymbolsWithConstProp(ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols, function_ref< PrevailingType(GlobalValue::GUID)> isPrevailing, bool ImportEnabled)
Compute dead symbols and run constant propagation in combined index after that.
LLVM_ABI Error EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename, const ModuleToSummariesForIndexTy &ModuleToSummariesForIndex)
Emit into OutputFilename the files module ModulePath will import from.
static cl::opt< bool > ComputeDead("compute-dead", cl::init(true), cl::Hidden, cl::desc("Compute dead symbols"))
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndexForFile(StringRef Path, bool IgnoreEmptyThinLTOIndexFile=false)
Parse the module summary index out of an IR file and return the module summary index object if found,...
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
LLVM_ABI void thinLTOFinalizeInModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals, bool PropagateAttrs)
Based on the information recorded in the summaries during global summary-based analysis:
Struct that holds a reference to a particular GUID in a global value summary.