91#define DEBUG_TYPE "machine-outliner"
98STATISTIC(NumOutlined,
"Number of candidates outlined");
99STATISTIC(FunctionsCreated,
"Number of functions created");
102STATISTIC(NumLegalInUnsignedVec,
"Outlinable instructions mapped");
104 "Unoutlinable instructions mapped + number of sentinel values");
105STATISTIC(NumSentinels,
"Sentinel values inserted during mapping");
107 "Non-debug invisible instructions skipped during mapping");
109 "Total number of instructions mapped and saved to mapping vector");
111 "Count of hashing attempts made for outlined functions");
113 "Count of unsuccessful hashing attempts for outlined functions");
115 "Number of locally unprofitable candidate groups published");
117 "Number of locally unprofitable candidate sites published");
118STATISTIC(NumRemovedLOHs,
"Total number of Linker Optimization Hints removed");
120 "Number of times outlining was blocked by PGO");
122 "Number of times outlining was allowed from cold functions");
124 "Number of times outlining was blocked conservatively when profile "
125 "counts were missing");
127 "Number of times outlining was allowed optimistically when profile "
128 "counts were missing");
133struct InstructionMapper {
140 unsigned IllegalInstrNumber = -3;
144 unsigned LegalInstrNumber = 0;
148 InstructionIntegerMap;
164 bool AddedIllegalLastTime =
false;
172 unsigned mapToLegalUnsigned(
174 bool &HaveLegalRange,
unsigned &NumLegalInBlock,
179 AddedIllegalLastTime =
false;
183 if (CanOutlineWithPrevInstr)
184 HaveLegalRange =
true;
185 CanOutlineWithPrevInstr =
true;
197 std::tie(ResultIt, WasInserted) =
198 InstructionIntegerMap.
insert(std::make_pair(&
MI, LegalInstrNumber));
199 unsigned MINumber = ResultIt->second;
208 if (LegalInstrNumber >= IllegalInstrNumber)
212 ++NumLegalInUnsignedVec;
222 unsigned mapToIllegalUnsigned(
224 SmallVector<unsigned> &UnsignedVecForMBB,
227 CanOutlineWithPrevInstr =
false;
230 if (AddedIllegalLastTime)
231 return IllegalInstrNumber;
234 AddedIllegalLastTime =
true;
235 unsigned MINumber = IllegalInstrNumber;
238 UnsignedVecForMBB.
push_back(IllegalInstrNumber);
239 IllegalInstrNumber--;
241 ++NumIllegalInUnsignedVec;
243 assert(LegalInstrNumber < IllegalInstrNumber &&
244 "Instruction mapping overflow!");
259 void convertToUnsignedVec(MachineBasicBlock &
MBB,
260 const TargetInstrInfo &
TII) {
262 <<
"' to unsigned vector ***\n");
266 if (!
TII.isMBBSafeToOutlineFrom(
MBB, Flags))
269 auto OutlinableRanges =
TII.getOutlinableRanges(
MBB, Flags);
271 <<
" outlinable range(s)\n");
272 if (OutlinableRanges.empty())
282 unsigned NumLegalInBlock = 0;
286 bool HaveLegalRange =
false;
290 bool CanOutlineWithPrevInstr =
false;
294 SmallVector<unsigned> UnsignedVecForMBB;
298 for (
auto &OutlinableRange : OutlinableRanges) {
299 auto OutlinableRangeBegin = OutlinableRange.first;
300 auto OutlinableRangeEnd = OutlinableRange.second;
304 << std::distance(OutlinableRangeBegin, OutlinableRangeEnd)
305 <<
" instruction range\n");
307 unsigned NumSkippedInRange = 0;
309 for (; It != OutlinableRangeBegin; ++It) {
310 if (It->isDebugInstr())
315 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
320 <<
" instructions outside outlinable range\n");
322 assert(It !=
MBB.
end() &&
"Should still have instructions?");
325 for (; It != OutlinableRangeEnd; ++It) {
326 if (It->isDebugInstr())
329 switch (
TII.getOutliningType(MMI, It, Flags)) {
330 case InstrType::Illegal:
331 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
335 case InstrType::Legal:
336 mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
337 NumLegalInBlock, UnsignedVecForMBB,
341 case InstrType::LegalTerminator:
342 mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
343 NumLegalInBlock, UnsignedVecForMBB,
347 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
351 case InstrType::Invisible:
355 AddedIllegalLastTime =
false;
361 LLVM_DEBUG(
dbgs() <<
"HaveLegalRange = " << HaveLegalRange <<
"\n");
365 if (HaveLegalRange) {
370 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
378 InstructionMapper(
const MachineModuleInfo &MMI_) : MMI(MMI_) {}
394 const CodeGenOptions *Opts =
nullptr;
395 MachineModuleInfo *MMI =
nullptr;
396 const TargetMachine *TM =
nullptr;
400 bool OutlineFromLinkOnceODRs =
false;
403 unsigned OutlineRepeatedNum = 0;
408 RunOutliner RunOutlinerMode = RunOutliner::AlwaysOutline;
416 std::unique_ptr<OutlinedHashTree> LocalHashTree;
432 OutlinedHashTree UnprofitableCandidateHashTree;
434 StringRef getPassName()
const override {
return "Machine Outliner"; }
436 void getAnalysisUsage(AnalysisUsage &AU)
const override {
441 if (RunOutlinerMode == RunOutliner::OptimisticPGO ||
442 RunOutlinerMode == RunOutliner::ConservativePGO) {
447 ModulePass::getAnalysisUsage(AU);
450 MachineOutliner() : ModulePass(ID) {}
454 void emitNotOutliningCheaperRemark(
455 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
456 OutlinedFunction &OF);
460 void createOutlinedFunctionIfBeneficial(
461 std::vector<Candidate> &Candidates,
unsigned StringLen,
462 unsigned MinRepeats,
const TargetInstrInfo &
TII,
463 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList);
466 void emitOutlinedFunctionRemark(OutlinedFunction &OF);
482 findCandidates(InstructionMapper &Mapper,
483 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList);
491 void findGlobalCandidates(
492 InstructionMapper &Mapper,
493 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList);
503 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList,
504 InstructionMapper &Mapper,
unsigned &OutlinedFunctionNum);
508 InstructionMapper &Mapper,
514 void computeAndPublishHashSequence(
MachineFunction &MF,
unsigned CandSize);
517 void recordUnprofitableCandidate(OutlinedFunction &OF);
520 bool publishUnprofitableCandidates(InstructionMapper &Mapper);
523 void initializeOutlinerMode(
const Module &M);
526 void emitOutlinedHashTree(
Module &M);
529 bool runOnModule(
Module &M)
override;
534 bool doOutline(
Module &M, std::optional<InstructionMapper> &Mapper,
535 unsigned &OutlinedFunctionNum);
539 DISubprogram *getSubprogramOrNull(
const OutlinedFunction &OF) {
540 for (
const Candidate &
C :
OF.Candidates)
542 if (DISubprogram *SP = MF->getFunction().getSubprogram())
549 void populateMapper(InstructionMapper &Mapper,
Module &M);
555 void initSizeRemarkInfo(
const Module &M,
556 StringMap<unsigned> &FunctionToInstrCount);
561 emitInstrCountChangedRemark(
const Module &M,
562 const StringMap<unsigned> &FunctionToInstrCount);
566char MachineOutliner::ID = 0;
569 MachineOutliner *OL =
new MachineOutliner();
570 OL->RunOutlinerMode = RunOutlinerMode;
577void MachineOutliner::emitNotOutliningCheaperRemark(
578 unsigned StringLen,
std::vector<
Candidate> &CandidatesForRepeatedSeq,
584 Candidate &
C = CandidatesForRepeatedSeq.front();
588 C.front().getDebugLoc(),
C.getMBB());
589 R <<
"Did not outline " <<
NV(
"Length", StringLen) <<
" instructions"
590 <<
" from " <<
NV(
"NumOccurrences", CandidatesForRepeatedSeq.size())
592 <<
" Bytes from outlining all occurrences ("
593 <<
NV(
"OutliningCost", OF.getOutliningCost()) <<
")"
594 <<
" >= Unoutlined instruction bytes ("
595 <<
NV(
"NotOutliningCost", OF.getNotOutlinedCost()) <<
")"
596 <<
" (Also found at: ";
599 for (
unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) {
601 CandidatesForRepeatedSeq[i].front().
getDebugLoc());
612 MachineBasicBlock *
MBB = &*
OF.MF->begin();
613 MachineOptimizationRemarkEmitter
MORE(*
OF.MF,
nullptr);
614 MachineOptimizationRemark
R(
DEBUG_TYPE,
"OutlinedFunction",
616 R <<
"Saved " <<
NV(
"OutliningBenefit",
OF.getBenefit()) <<
" bytes by "
617 <<
"outlining " <<
NV(
"Length",
OF.getNumInstrs()) <<
" instructions "
618 <<
"from " <<
NV(
"NumOccurrences",
OF.getOccurrenceCount())
623 for (
size_t i = 0, e =
OF.Candidates.size(); i < e; i++) {
625 R <<
NV((Twine(
"StartLoc") + Twine(i)).str(),
626 OF.Candidates[i].front().getDebugLoc());
660 auto &InstrList = Mapper.InstrList;
661 auto &UnsignedVec = Mapper.UnsignedVec;
666 const auto *RootNode = HashTree.
getRoot();
668 auto getValidInstr = [&](
unsigned Index) ->
const MachineInstr * {
669 if (UnsignedVec[Index] >= Mapper.LegalInstrNumber)
671 return &(*InstrList[Index]);
674 auto getStableHashAndFollow =
679 auto It = CurrNode->Successors.find(StableHash);
680 return (It == CurrNode->Successors.end()) ? nullptr : It->second.get();
683 for (
unsigned I = 0;
I <
Size; ++
I) {
685 if (!
MI ||
MI->isDebugInstr())
687 const HashNode *CurrNode = getStableHashAndFollow(*
MI, RootNode);
691 for (
unsigned J =
I + 1; J <
Size; ++J) {
698 CurrNode = getStableHashAndFollow(*MJ, CurrNode);
708 return MatchedEntries;
711void MachineOutliner::findGlobalCandidates(
712 InstructionMapper &Mapper,
713 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList) {
714 FunctionList.
clear();
716 auto &MBBFlagsMap =
Mapper.MBBFlagsMap;
718 const cl::LibraryOptionsContext &LibraryOptions =
719 Mapper.MMI.getModule()->getContext().getLibraryOptions();
722 std::vector<Candidate> CandidatesForRepeatedSeq;
724 CandidatesForRepeatedSeq.clear();
727 auto Length = ME.EndIdx - ME.StartIdx + 1;
728 MachineBasicBlock *
MBB = StartIt->getParent();
729 CandidatesForRepeatedSeq.emplace_back(ME.StartIdx,
Length, StartIt, EndIt,
731 const TargetInstrInfo *
TII =
733 unsigned MinRepeats = 1;
734 std::optional<std::unique_ptr<OutlinedFunction>>
OF =
735 TII->getOutliningCandidateInfo(*MMI, CandidatesForRepeatedSeq,
737 if (!
OF.has_value() ||
OF.value()->Candidates.empty())
740 assert(
OF.value()->Candidates.size() == MinRepeats);
741 FunctionList.emplace_back(std::make_unique<GlobalOutlinedFunction>(
742 std::move(
OF.value()), ME.Count));
748 return F.hasSection() ?
F.getSection() :
StringRef();
760 if (It == Sections.
end()) {
763 It = Sections.
end() - 1;
765 Partitions[std::distance(Sections.
begin(), It)].
push_back(std::move(
C));
770void MachineOutliner::createOutlinedFunctionIfBeneficial(
771 std::vector<Candidate> &Candidates,
unsigned StringLen,
unsigned MinRepeats,
772 const TargetInstrInfo &
TII,
773 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList) {
774 if (Candidates.size() < MinRepeats)
777 std::optional<std::unique_ptr<OutlinedFunction>>
OF =
778 TII.getOutliningCandidateInfo(*MMI, Candidates, MinRepeats);
782 if (!
OF.has_value() ||
OF.value()->Candidates.size() < MinRepeats)
786 if (
OF.value()->getBenefit() < Opts->outliner_benefit_threshold) {
787 recordUnprofitableCandidate(*
OF.value());
788 emitNotOutliningCheaperRemark(StringLen, Candidates, *
OF.value());
792 FunctionList.emplace_back(std::move(
OF.value()));
795void MachineOutliner::findCandidates(
796 InstructionMapper &Mapper,
797 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList) {
798 FunctionList.clear();
800 SuffixTree
ST(
Mapper.UnsignedVec, Opts->outliner_leaf_descendants,
801 Mapper.IllegalInstrNumber + 1);
805 std::vector<Candidate> CandidatesForRepeatedSeq;
806 LLVM_DEBUG(
dbgs() <<
"*** Discarding overlapping candidates *** \n");
808 dbgs() <<
"Searching for overlaps in all repeated sequences...\n");
809 for (SuffixTree::RepeatedSubstring &RS : ST) {
810 CandidatesForRepeatedSeq.clear();
811 unsigned StringLen =
RS.Length;
815 unsigned NumDiscarded = 0;
816 unsigned NumKept = 0;
821 for (
const unsigned &StartIdx :
RS.StartIndices) {
843 unsigned EndIdx = StartIdx + StringLen - 1;
844 if (!CandidatesForRepeatedSeq.empty() &&
845 StartIdx <= CandidatesForRepeatedSeq.back().getEndIdx()) {
848 LLVM_DEBUG(
dbgs() <<
" .. DISCARD candidate @ [" << StartIdx <<
", "
849 << EndIdx <<
"]; overlaps with candidate @ ["
850 << CandidatesForRepeatedSeq.back().getStartIdx()
851 <<
", " << CandidatesForRepeatedSeq.back().getEndIdx()
864 MachineBasicBlock *
MBB = StartIt->getParent();
865 CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt, EndIt,
873 unsigned MinRepeats = 2;
878 if (CandidatesForRepeatedSeq.size() < MinRepeats)
883 const TargetInstrInfo *
TII =
884 CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo();
889 if (!
TII->supportsSectionAwareOutlining()) {
890 createOutlinedFunctionIfBeneficial(CandidatesForRepeatedSeq, StringLen,
891 MinRepeats, *
TII, FunctionList);
897 <<
"*** Section Aware Outlining is enabled for the target *** \n");
904 for (std::vector<Candidate> &Partition : Partitions) {
907 dbgs() <<
" .. section '"
908 << (
Section.empty() ? StringRef(
"<none>") : Section)
909 <<
"': " << Partition.size() <<
" candidates\n";
911 createOutlinedFunctionIfBeneficial(Partition, StringLen, MinRepeats, *
TII,
917void MachineOutliner::computeAndPublishHashSequence(
MachineFunction &MF,
920 SmallVector<stable_hash> OutlinedHashSequence;
921 for (
auto &
MBB : MF) {
922 for (
auto &NewMI :
MBB) {
925 OutlinedHashSequence.
clear();
933 if (Opts->append_content_hash_outlined_name &&
934 !OutlinedHashSequence.
empty()) {
937 MF.getName().str() +
".content." + std::to_string(CombinedHash);
938 MF.getFunction().setName(NewName);
942 if (OutlinerMode == CGDataMode::Write) {
943 StableHashAttempts++;
944 if (!OutlinedHashSequence.
empty())
945 LocalHashTree->insert({OutlinedHashSequence, CandSize});
951void MachineOutliner::recordUnprofitableCandidate(OutlinedFunction &OF) {
952 if (!Opts->machine_outliner_publish_unprofitable_candidates ||
953 OutlinerMode != CGDataMode::Write ||
955 Opts->machine_outliner_unprofitable_candidate_max_instrs)
960 return OF.SequenceSize <= C.getCallOverhead();
964 SmallVector<stable_hash> HashSequence;
965 for (MachineInstr &
MI :
OF.Candidates.front()) {
966 if (
MI.isDebugInstr())
973 if (HashSequence.
empty() ||
974 UnprofitableCandidateHashTree.
find(HashSequence).value_or(0))
977 const unsigned SequenceID = UnprofitableCandidates.
size();
980 UnprofitableCandidateHashTree.
insert({HashSequence, SequenceID + 1});
981 UnprofitableCandidates.
push_back(std::move(HashSequence));
984bool MachineOutliner::publishUnprofitableCandidates(InstructionMapper &Mapper) {
985 if (!Opts->machine_outliner_publish_unprofitable_candidates ||
986 OutlinerMode != CGDataMode::Write || UnprofitableCandidates.
empty())
990 UnprofitableCandidates.
size());
991 BitVector ConflictingGroups(UnprofitableCandidates.
size());
993 for (
const auto &ME :
995 assert(ME.Count && ME.Count <= CandidateGroups.size());
998 const unsigned SequenceID = ME.Count - 1;
1003 return Other.EndIdx < ME.StartIdx;
1005 for (
const MatchedEntry &
Other : ActiveMatches) {
1006 if (
Other.Count == ME.Count)
1011 const bool MEContained = ME.EndIdx <=
Other.EndIdx;
1012 const bool OtherContained =
1013 Other.StartIdx == ME.StartIdx &&
Other.EndIdx <= ME.EndIdx;
1014 if (!OtherContained)
1015 ConflictingGroups.set(SequenceID);
1017 ConflictingGroups.set(
Other.Count - 1);
1019 ActiveMatches.push_back(ME);
1021 auto &Candidates = CandidateGroups[SequenceID];
1022 if (!Candidates.empty() && ME.StartIdx <= Candidates.back().getEndIdx())
1025 auto StartIt =
Mapper.InstrList[ME.StartIdx];
1026 auto EndIt =
Mapper.InstrList[ME.EndIdx];
1027 auto *
MBB = StartIt->getParent();
1028 Candidates.emplace_back(ME.StartIdx, ME.EndIdx - ME.StartIdx + 1, StartIt,
1032 bool Published =
false;
1033 for (
const auto &[SequenceID, Candidates] :
1039 if (Candidates.empty() || ConflictingGroups.test(SequenceID))
1042 unsigned NumSites = 0;
1045 Partition.front().getMF()->getSubtarget().getInstrInfo();
1047 TII->getOutliningCandidateInfo(*MMI, Partition, 1);
1048 if (!OF ||
OF.value()->Candidates.empty())
1052 return OF.value()->SequenceSize > C.getCallOverhead();
1058 LocalHashTree->insert({UnprofitableCandidates[SequenceID], NumSites});
1059 ++UnprofitableCandidateGroupsPublished;
1060 UnprofitableCandidateSitesPublished += NumSites;
1067 Module &M, OutlinedFunction &OF, InstructionMapper &Mapper,
unsigned Name) {
1072 std::string FunctionName =
"OUTLINED_FUNCTION_";
1073 if (OutlineRepeatedNum > 0)
1074 FunctionName += std::to_string(OutlineRepeatedNum + 1) +
"_";
1075 FunctionName += std::to_string(Name);
1079 LLVMContext &
C =
M.getContext();
1081 Function::ExternalLinkage, FunctionName, M);
1086 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1090 F->addFnAttr(Attribute::OptimizeForSize);
1091 F->addFnAttr(Attribute::MinSize);
1093 Candidate &FirstCand =
OF.Candidates.front();
1094 const TargetInstrInfo &
TII =
1097 TII.mergeOutliningCandidateAttributes(*
F,
OF.Candidates);
1099 if (
TII.supportsSectionAwareOutlining()) {
1110 OF.Candidates.cbegin(),
OF.Candidates.cend(), UWTableKind::None,
1112 return std::max(K, C.getMF()->getFunction().getUWTableKind());
1114 F->setUWTableKind(UW);
1118 Builder.CreateRetVoid();
1120 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
1129 const std::vector<MCCFIInstruction> &Instrs =
1131 for (
auto &
MI : FirstCand) {
1132 if (
MI.isDebugInstr())
1137 if (
MI.isCFIInstruction()) {
1138 unsigned CFIIndex =
MI.getOperand(0).getCFIIndex();
1139 MCCFIInstruction CFI = Instrs[CFIIndex];
1150 for (
auto I = std::next(NewMI.
getIterator());
I != BundleEnd; ++
I) {
1158 if (OutlinerMode != CGDataMode::None)
1159 computeAndPublishHashSequence(MF,
OF.Candidates.size());
1171 LivePhysRegs LiveIns(
TRI);
1172 for (
auto &Cand :
OF.Candidates) {
1174 MachineBasicBlock &OutlineBB = *Cand.front().getParent();
1175 LivePhysRegs CandLiveIns(
TRI);
1176 CandLiveIns.addLiveOuts(OutlineBB);
1177 for (
const MachineInstr &
MI :
1179 CandLiveIns.stepBackward(
MI);
1184 LiveIns.addReg(
Reg);
1188 TII.buildOutlinedFrame(
MBB, MF, OF);
1192 if (DISubprogram *SP = getSubprogramOrNull(OF)) {
1194 DICompileUnit *CU =
SP->getUnit();
1195 DIBuilder
DB(M,
true, CU);
1196 DIFile *
Unit =
SP->getFile();
1200 raw_string_ostream MangledNameStream(Dummy);
1203 DISubprogram *OutlinedSP =
DB.createFunction(
1204 Unit ,
F->getName(), StringRef(Dummy), Unit ,
1206 DB.createSubroutineType(
DB.getOrCreateTypeArray({})),
1208 DINode::DIFlags::FlagArtificial ,
1210 DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
1213 F->setSubprogram(OutlinedSP);
1221bool MachineOutliner::outline(
1222 Module &M, std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList,
1223 InstructionMapper &Mapper,
unsigned &OutlinedFunctionNum) {
1225 LLVM_DEBUG(
dbgs() <<
"NUMBER OF POTENTIAL FUNCTIONS: " << FunctionList.size()
1227 bool OutlinedSomething =
false;
1231 stable_sort(FunctionList, [](
const std::unique_ptr<OutlinedFunction> &
LHS,
1232 const std::unique_ptr<OutlinedFunction> &
RHS) {
1233 return LHS->getNotOutlinedCost() *
RHS->getOutliningCost() >
1234 RHS->getNotOutlinedCost() *
LHS->getOutliningCost();
1239 auto *UnsignedVecBegin =
Mapper.UnsignedVec.begin();
1241 for (
auto &OF : FunctionList) {
1243 auto NumCandidatesBefore =
OF->Candidates.size();
1247 erase_if(
OF->Candidates, [&UnsignedVecBegin](Candidate &
C) {
1248 return std::any_of(UnsignedVecBegin + C.getStartIdx(),
1249 UnsignedVecBegin + C.getEndIdx() + 1, [](unsigned I) {
1250 return I == static_cast<unsigned>(-1);
1255 auto NumCandidatesAfter =
OF->Candidates.size();
1256 LLVM_DEBUG(
dbgs() <<
"PRUNED: " << NumCandidatesBefore - NumCandidatesAfter
1257 <<
"/" << NumCandidatesBefore <<
" candidates\n");
1261 if (
OF->getBenefit() < Opts->outliner_benefit_threshold) {
1264 if (!
OF->Candidates.empty())
1265 recordUnprofitableCandidate(*OF);
1267 <<
" B) < threshold ("
1268 << Opts->outliner_benefit_threshold <<
" B)\n");
1273 <<
" B) > threshold (" << Opts->outliner_benefit_threshold
1279 SmallPtrSet<MachineInstr *, 2> MIs;
1280 for (Candidate &
C :
OF->Candidates) {
1281 for (MachineInstr &
MI :
C)
1290 emitOutlinedFunctionRemark(*OF);
1292 OutlinedFunctionNum++;
1299 for (Candidate &
C :
OF->Candidates) {
1300 MachineBasicBlock &
MBB = *
C.getMBB();
1307 for (MachineInstr &
MI :
C) {
1308 if (
MI.isDebugInstr())
1311 if (!
DL || !
DL.getLine())
1316 MergedCallLoc = MergedCallLoc
1327 auto CallInst =
TII.insertOutlinedCall(M,
MBB, StartIt, *MF,
C);
1336 !CallInst->isTerminator() && MergedCallLoc ? MergedCallLoc : FirstLoc;
1346 for (MachineInstr &
MI :
make_range(SeqBegin, std::next(StartIt)))
1347 MI.setDebugLoc(CallLoc);
1350 auto MBBBeingOutlinedFromName =
1356 << MFBeingOutlinedFromName <<
":"
1357 << MBBBeingOutlinedFromName <<
"\n");
1369 SmallSet<Register, 2> UseRegs, DefRegs;
1370 LiveRegUnits LiveUnits(
1380 Last = std::next(CallInst.getReverse());
1381 Iter !=
Last; Iter++) {
1382 MachineInstr *
MI = &*Iter;
1383 if (
MI->isDebugInstr())
1385 LiveUnits.stepBackward(*
MI);
1386 for (MachineOperand &MOP :
MI->operands()) {
1387 if (!MOP.isReg() || !MOP.getReg())
1391 DefRegs.
insert(MOP.getReg());
1392 else if (MOP.readsReg() && MOP.getReg().isPhysical())
1393 UseRegs.
insert(MOP.getReg());
1395 if (
MI->isCandidateForAdditionalCallInfo())
1396 MI->getMF()->eraseAdditionalCallInfo(
MI);
1401 CallInst->addOperand(
1407 if (!LiveUnits.available(
I.asMCReg()))
1408 CallInst->addOperand(
1416 MBB.
erase(std::next(StartIt), std::next(EndIt));
1419 for (
unsigned &
I :
make_range(UnsignedVecBegin +
C.getStartIdx(),
1420 UnsignedVecBegin +
C.getEndIdx() + 1))
1421 I =
static_cast<unsigned>(-1);
1422 OutlinedSomething =
true;
1429 LLVM_DEBUG(
dbgs() <<
"OutlinedSomething = " << OutlinedSomething <<
"\n");
1430 return OutlinedSomething;
1440 auto *MF =
MBB.getParent();
1442 ++NumPGOAllowedCold;
1446 auto *BB =
MBB.getBasicBlock();
1447 if (BB && PSI && BFI)
1453 if (
TII->shouldOutlineFromFunctionByDefault(*MF)) {
1455 ++NumPGOOptimisticOutlined;
1462 ++NumPGOConservativeBlockedOutlined;
1466void MachineOutliner::populateMapper(InstructionMapper &Mapper,
Module &M) {
1470 bool EnableProfileGuidedOutlining =
1471 RunOutlinerMode == RunOutliner::OptimisticPGO ||
1472 RunOutlinerMode == RunOutliner::ConservativePGO;
1473 ProfileSummaryInfo *PSI =
nullptr;
1474 if (EnableProfileGuidedOutlining)
1475 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
1479 if (
F.hasFnAttribute(Attribute::NoOutline)) {
1480 LLVM_DEBUG(
dbgs() <<
"SKIP: Function has nooutline attribute\n");
1491 LLVM_DEBUG(
dbgs() <<
"SKIP: Function does not have a MachineFunction\n");
1499 if (
F.hasFnAttribute(Attribute::ReturnsTwice)) {
1500 LLVM_DEBUG(
dbgs() <<
"SKIP: Function has returnstwice attribute\n");
1508 "returnstwice attribute\n");
1513 BlockFrequencyInfo *BFI =
nullptr;
1514 if (EnableProfileGuidedOutlining &&
F.hasProfileData())
1515 BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>(
F).getBFI();
1516 if (RunOutlinerMode == RunOutliner::TargetDefault &&
1517 !
TII->shouldOutlineFromFunctionByDefault(*MF)) {
1518 LLVM_DEBUG(
dbgs() <<
"SKIP: Target does not want to outline from "
1519 "function by default\n");
1525 if (!
TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs)) {
1527 <<
": unsafe to outline from\n");
1534 const unsigned MinMBBSize = 2;
1536 for (MachineBasicBlock &
MBB : *MF) {
1551 LLVM_DEBUG(
dbgs() <<
" SKIP: MBB size less than minimum size of "
1552 << MinMBBSize <<
"\n");
1564 ++NumPGOBlockedOutlined;
1573 UnsignedVecSize =
Mapper.UnsignedVec.size();
1576void MachineOutliner::initSizeRemarkInfo(
1577 const Module &M, StringMap<unsigned> &FunctionToInstrCount) {
1591void MachineOutliner::emitInstrCountChangedRemark(
1592 const Module &M,
const StringMap<unsigned> &FunctionToInstrCount) {
1604 std::string Fname = std::string(
F.getName());
1606 unsigned FnCountBefore = 0;
1609 auto It = FunctionToInstrCount.
find(Fname);
1613 if (It != FunctionToInstrCount.
end())
1614 FnCountBefore = It->second;
1617 int64_t FnDelta =
static_cast<int64_t
>(FnCountAfter) -
1618 static_cast<int64_t
>(FnCountBefore);
1622 MachineOptimizationRemarkEmitter
MORE(*MF,
nullptr);
1624 MachineOptimizationRemarkAnalysis
R(
"size-info",
"FunctionMISizeChange",
1625 DiagnosticLocation(), &MF->
front());
1626 R << DiagnosticInfoOptimizationBase::Argument(
"Pass",
"Machine Outliner")
1628 << DiagnosticInfoOptimizationBase::Argument(
"Function",
F.getName())
1629 <<
": MI instruction count changed from "
1630 << DiagnosticInfoOptimizationBase::Argument(
"MIInstrsBefore",
1633 << DiagnosticInfoOptimizationBase::Argument(
"MIInstrsAfter",
1636 << DiagnosticInfoOptimizationBase::Argument(
"Delta", FnDelta);
1642void MachineOutliner::initializeOutlinerMode(
const Module &M) {
1643 if (!Opts->global_outlining)
1646 if (
auto *IndexWrapperPass =
1647 getAnalysisIfAvailable<ImmutableModuleSummaryIndexWrapperPass>()) {
1648 auto *TheIndex = IndexWrapperPass->getIndex();
1651 if (TheIndex && !TheIndex->hasExportedFunctions(M))
1659 const cl::LibraryOptionsContext &LibraryOptions =
1660 M.getContext().getLibraryOptions();
1662 OutlinerMode = CGDataMode::Write;
1664 LocalHashTree = std::make_unique<OutlinedHashTree>();
1667 OutlinerMode = CGDataMode::Read;
1670void MachineOutliner::emitOutlinedHashTree(
Module &M) {
1672 if (!LocalHashTree->empty()) {
1674 dbgs() <<
"Emit outlined hash tree. Size: " << LocalHashTree->size()
1677 SmallVector<char> Buf;
1678 raw_svector_ostream OS(Buf);
1680 OutlinedHashTreeRecord HTR(std::move(LocalHashTree));
1683 llvm::StringRef
Data(Buf.data(), Buf.size());
1684 std::unique_ptr<MemoryBuffer> Buffer =
1687 Triple
TT(
M.getTargetTriple());
1694bool MachineOutliner::runOnModule(
Module &M) {
1706 initializeOutlinerMode(M);
1708 MMI = &getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
1709 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
1712 unsigned OutlinedFunctionNum = 0;
1714 OutlineRepeatedNum = 0;
1717 UnprofitableCandidates.
clear();
1718 UnprofitableCandidateHashTree.
clear();
1720 std::optional<InstructionMapper>
Mapper;
1721 const bool OutlinedSomething = doOutline(M, Mapper, OutlinedFunctionNum);
1723 for (
unsigned I = 0; OutlinedSomething &&
I < Opts->machine_outliner_reruns;
1725 OutlinedFunctionNum = 0;
1726 OutlineRepeatedNum++;
1727 if (!doOutline(M, Mapper, OutlinedFunctionNum)) {
1729 dbgs() <<
"Did not outline on iteration " <<
I + 2 <<
" out of "
1730 << Opts->machine_outliner_reruns + 1 <<
"\n";
1739 const bool PublishedUnprofitableCandidates =
1740 publishUnprofitableCandidates(*Mapper);
1741 if (!OutlinedSomething && !PublishedUnprofitableCandidates)
1744 if (OutlinerMode == CGDataMode::Write)
1745 emitOutlinedHashTree(M);
1750bool MachineOutliner::doOutline(
Module &M,
1751 std::optional<InstructionMapper> &Mapper,
1752 unsigned &OutlinedFunctionNum) {
1759 dbgs() <<
"Machine Outliner: Running on ";
1760 switch (RunOutlinerMode) {
1761 case RunOutliner::AlwaysOutline:
1762 dbgs() <<
"all functions";
1764 case RunOutliner::OptimisticPGO:
1765 dbgs() <<
"optimistically cold functions";
1767 case RunOutliner::ConservativePGO:
1768 dbgs() <<
"conservatively cold functions";
1770 case RunOutliner::TargetDefault:
1771 dbgs() <<
"target-default functions";
1773 case RunOutliner::NeverOutline:
1781 OutlineFromLinkOnceODRs = Opts->enable_linkonceodr_outlining;
1785 populateMapper(*Mapper, M);
1786 std::vector<std::unique_ptr<OutlinedFunction>> FunctionList;
1789 if (OutlinerMode == CGDataMode::Read)
1790 findGlobalCandidates(*Mapper, FunctionList);
1792 findCandidates(*Mapper, FunctionList);
1803 bool ShouldEmitSizeRemarks =
M.shouldEmitInstrCountChangedRemark();
1804 StringMap<unsigned> FunctionToInstrCount;
1805 if (ShouldEmitSizeRemarks)
1806 initSizeRemarkInfo(M, FunctionToInstrCount);
1809 bool OutlinedSomething =
1810 outline(M, FunctionList, *Mapper, OutlinedFunctionNum);
1815 if (ShouldEmitSizeRemarks && OutlinedSomething)
1816 emitInstrCountChangedRemark(M, FunctionToInstrCount);
1819 if (!OutlinedSomething)
1820 dbgs() <<
"Stopped outlining at iteration " << OutlineRepeatedNum
1821 <<
" because no changes were found.\n";
1824 return OutlinedSomething;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file defines the DenseMap class.
const HexagonInstrInfo * TII
Module.h This file contains the declarations for the Module class.
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
Machine Check Debug Module
static bool allowPGOOutlining(RunOutliner RunOutlinerMode, const ProfileSummaryInfo *PSI, const BlockFrequencyInfo *BFI, MachineBasicBlock &MBB)
static SmallVector< std::vector< Candidate > > partitionCandidatesByInputSection(std::vector< Candidate > &Candidates)
static StringRef getCandidateInputSection(const Candidate &C)
static stable_hash hashInstruction(const MachineInstr &MI)
static SmallVector< MatchedEntry > getMatchedEntries(InstructionMapper &Mapper, const OutlinedHashTree &HashTree)
Contains all data structures shared between the outliner implemented in MachineOutliner....
Register const TargetRegisterInfo * TRI
Promote Memory to Register
This is the interface to build a ModuleSummaryIndex for a module.
static Expected< Function * > createOutlinedFunction(OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder, const OpenMPIRBuilder::TargetKernelDefaultAttrs &DefaultAttrs, StringRef FuncName, SmallVectorImpl< Value * > &Inputs, OpenMPIRBuilder::TargetBodyGenCallbackTy &CBFunc, OpenMPIRBuilder::TargetGenArgAccessorsCallbackTy &ArgAccessorFuncCB, DebugLoc OutlinedFnLoc)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
MachineRegisterInfo & MRI
This file defines the SmallSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Target-Independent Code Generator Pass Configuration Options pass.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI std::optional< uint64_t > getBlockProfileCount(const BasicBlock *BB) const
Returns the estimated profile count of BB.
static LLVM_ABI DebugLoc getMergedLocation(DebugLoc LocA, DebugLoc LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
StringRef getSection() const
Get the custom section of this global if it has one.
bool hasSection() const
Check if this global has a custom object file section.
@ InternalLinkage
Rename collisions when linking (static functions).
instr_iterator instr_begin()
bool hasAddressTaken() const
Test whether this block is used as something other than the target of a terminator,...
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
instr_iterator instr_end()
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
unsigned getInstructionCount() const
Return the number of MachineInstrs in this MachineFunction.
unsigned addFrameInst(const MCCFIInstruction &Inst)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const std::vector< MCCFIInstruction > & getFrameInstructions() const
Returns a reference to a list of cfi instructions in the function's prologue.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
bool exposesReturnsTwice() const
exposesReturnsTwice - Returns true if the function calls setjmp or any other similar functions with a...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
void setIsOutlined(bool V)
const MachineFunctionProperties & getProperties() const
Get the function properties.
const MachineBasicBlock & front() const
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & addCFIIndex(unsigned CFIIndex) const
reverse_iterator getReverse() const
Get a reverse iterator to the same node.
Representation of each machine instruction.
bool isDebugInstr() const
LLVM_ABI void dropMemRefs(MachineFunction &MF)
Clear this MachineInstr's memory reference descriptor list.
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
bool isBundledWithSucc() const
Return true if this instruction is part of a bundle, and it is not the last instruction in the bundle...
LLVM_ABI void clearKillInfo()
Clears kill flags on all operands.
void setDebugLoc(DebugLoc DL)
Replace current source information with new such.
This class contains meta information specific to a module.
LLVM_ABI MachineFunction & getOrCreateMachineFunction(Function &F)
Returns the MachineFunction constructed for the IR function F.
LLVM_ABI MachineFunction * getMachineFunction(const Function &F) const
Returns the MachineFunction associated to IR function F if there is one, otherwise nullptr.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
LLVM_ABI void freezeReservedRegs()
freezeReservedRegs - Called by the register allocator to freeze the set of reserved registers before ...
const TargetRegisterInfo * getTargetRegisterInfo() const
LLVM_ABI void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
void clear()
Release all hash nodes except the root hash node.
LLVM_ABI std::optional< unsigned > find(const HashSequence &Sequence) const
const HashNode * getRoot() const
LLVM_ABI void insert(const HashSequencePair &SequencePair)
Inserts a Sequence into the this tree.
Analysis providing profile information.
LLVM_ABI uint64_t getOrCompColdCountThreshold() const
Returns ColdCountThreshold if set.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
iterator find(StringRef Key)
Represent a constant reference to a string, i.e.
std::string str() const
Get the contents as an std::string.
constexpr bool empty() const
Check if the string is empty.
constexpr size_t size() const
Get the string size.
virtual size_t clearLinkerOptimizationHints(const SmallPtrSetImpl< MachineInstr * > &MIs) const
Remove all Linker Optimization Hints (LOH) associated with instructions in MIs and.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
self_iterator getIterator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
SmallVector< const MachineInstr * > InstrList
const OutlinedHashTree * getOutlinedHashTree(const cl::LibraryOptionsContext &LibraryOptions)
bool hasOutlinedHashTree(const cl::LibraryOptionsContext &LibraryOptions)
bool emitCGData(const cl::LibraryOptionsContext &LibraryOptions)
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
void stable_sort(R &&Range)
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
uint64_t stable_hash
An opaque object representing a stable hash code.
LLVM_ABI stable_hash stableHashValue(const MachineOperand &MO, bool SourceQualifyLocalGlobals=false)
bool hasNItemsOrMore(IterTy &&Begin, IterTy &&End, unsigned N, Pred &&ShouldBeCounted=[](const decltype(*std::declval< IterTy >()) &) { return true;}, std::enable_if_t< !std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< std::remove_reference_t< decltype(Begin)> >::iterator_category >::value, void > *=nullptr)
Return true if the sequence [Begin, End) has N or more items.
auto reverse(ContainerTy &&C)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
MachineBasicBlock::instr_iterator getBundleEnd(MachineBasicBlock::instr_iterator I)
Returns an iterator pointing beyond the bundle containing I.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
auto instructionsWithoutDebug(IterT It, IterT End, bool SkipPseudoOp=true)
Construct a range iterator which begins at It and moves forwards until End is reached,...
LLVM_ABI ModulePass * createMachineOutlinerPass(RunOutliner RunOutlinerMode)
This pass performs outlining on machine instructions directly before printing assembly.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
stable_hash stable_hash_combine(ArrayRef< stable_hash > Buffer)
LLVM_ABI GlobalVariable * embedBufferInModule(Module &M, MemoryBufferRef Buf, StringRef SectionName, Align Alignment=Align(1), bool SectionExclude=true)
Embed the memory buffer Buf into the module M as a global using the specified section name.
LLVM_ABI void addLiveIns(MachineBasicBlock &MBB, const LivePhysRegs &LiveRegs)
Adds registers contained in LiveRegs to the block live-in list of MBB.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
LLVM_ABI std::string getCodeGenDataSectionName(CGDataSectKind CGSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Implement std::hash so that hash_code can be used in STL containers.
MatchedEntry(unsigned StartIdx, unsigned EndIdx, unsigned Count)
A HashNode is an entry in an OutlinedHashTree, holding a hash value and a collection of Successors (o...
std::optional< unsigned > Terminals
The number of terminals in the sequence ending at this node.
An individual sequence of instructions to be replaced with a call to an outlined function.
MachineFunction * getMF() const
The information necessary to create an outlined function for some class of candidate.