64 #define DEBUG_TYPE "machine-outliner"
68 STATISTIC(NumOutlined,
"Number of candidates outlined");
69 STATISTIC(FunctionsCreated,
"Number of functions created");
78 bool InCandidateList =
true;
99 Candidate(
size_t StartIdx,
size_t Len,
size_t FunctionIdx)
100 : StartIdx(StartIdx), Len(Len), FunctionIdx(FunctionIdx) {}
106 bool operator<(
const Candidate &RHS)
const {
return StartIdx > RHS.StartIdx; }
111 struct OutlinedFunction {
121 size_t OccurrenceCount = 0;
128 unsigned Benefit = 0;
132 bool IsTailCall =
false;
134 OutlinedFunction(
size_t Name,
size_t OccurrenceCount,
135 const std::vector<unsigned> &
Sequence,
136 unsigned Benefit,
bool IsTailCall)
137 : Name(Name), OccurrenceCount(OccurrenceCount), Sequence(Sequence),
138 Benefit(Benefit), IsTailCall(IsTailCall)
143 const size_t EmptyIdx = -1;
160 struct SuffixTreeNode {
170 bool IsInTree =
true;
173 size_t StartIdx = EmptyIdx;
181 size_t *EndIdx =
nullptr;
186 size_t SuffixIdx = EmptyIdx;
228 SuffixTreeNode *
Link =
nullptr;
231 SuffixTreeNode *Parent =
nullptr;
237 size_t OccurrenceCount = 0;
241 size_t ConcatLen = 0;
244 bool isLeaf()
const {
return SuffixIdx != EmptyIdx; }
247 bool isRoot()
const {
return StartIdx == EmptyIdx; }
250 size_t size()
const {
256 assert(*EndIdx != EmptyIdx &&
"EndIdx is undefined!");
260 return *EndIdx - StartIdx + 1;
263 SuffixTreeNode(
size_t StartIdx,
size_t *EndIdx, SuffixTreeNode *
Link,
264 SuffixTreeNode *Parent)
265 : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link), Parent(Parent) {}
304 SuffixTreeNode *Root =
nullptr;
309 std::vector<SuffixTreeNode *> LeafVector;
321 size_t LeafEndIdx = -1;
327 SuffixTreeNode *Node;
330 size_t Idx = EmptyIdx;
347 SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent,
size_t StartIdx,
350 assert(StartIdx <= LeafEndIdx &&
"String can't start after it ends!");
352 SuffixTreeNode *
N =
new (NodeAllocator.Allocate()) SuffixTreeNode(StartIdx,
356 Parent.Children[Edge] =
N;
369 SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent,
size_t StartIdx,
370 size_t EndIdx,
unsigned Edge) {
372 assert(StartIdx <= EndIdx &&
"String can't start after it ends!");
373 assert(!(!Parent && StartIdx != EmptyIdx) &&
374 "Non-root internal nodes must have parents!");
376 size_t *
E =
new (InternalEndIdxAllocator)
size_t(EndIdx);
377 SuffixTreeNode *N =
new (NodeAllocator.Allocate()) SuffixTreeNode(StartIdx,
382 Parent->Children[Edge] =
N;
393 void setSuffixIndices(SuffixTreeNode &CurrNode,
size_t CurrIdx) {
395 bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot();
399 if (!CurrNode.isRoot()) {
400 if (CurrNode.ConcatLen == 0)
401 CurrNode.ConcatLen = CurrNode.size();
404 CurrNode.ConcatLen += CurrNode.Parent->ConcatLen;
408 for (
auto &ChildPair : CurrNode.Children) {
409 assert(ChildPair.second &&
"Node had a null child!");
410 setSuffixIndices(*ChildPair.second,
411 CurrIdx + ChildPair.second->size());
417 CurrNode.SuffixIdx = Str.size() - CurrIdx;
418 assert(CurrNode.Parent &&
"CurrNode had no parent!");
419 CurrNode.Parent->OccurrenceCount++;
422 LeafVector[CurrNode.SuffixIdx] = &CurrNode;
440 unsigned extend(
size_t EndIdx,
size_t SuffixesToAdd) {
441 SuffixTreeNode *NeedsLink =
nullptr;
443 while (SuffixesToAdd > 0) {
446 if (Active.Len == 0) {
451 assert(Active.Idx <= EndIdx &&
"Start index can't be after end index!");
454 unsigned FirstChar = Str[Active.Idx];
457 if (Active.Node->Children.count(FirstChar) == 0) {
459 insertLeaf(*Active.Node, EndIdx, FirstChar);
464 NeedsLink->Link = Active.Node;
470 SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
472 size_t SubstringLen = NextNode->size();
476 if (Active.Len >= SubstringLen) {
479 Active.Idx += SubstringLen;
480 Active.Len -= SubstringLen;
481 Active.Node = NextNode;
487 unsigned LastChar = Str[EndIdx];
490 if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
494 if (NeedsLink && !Active.Node->isRoot()) {
495 NeedsLink->Link = Active.Node;
517 SuffixTreeNode *SplitNode =
518 insertInternalNode(Active.Node,
520 NextNode->StartIdx + Active.Len - 1,
525 insertLeaf(*SplitNode, EndIdx, LastChar);
529 NextNode->StartIdx += Active.Len;
530 NextNode->Parent = SplitNode;
531 SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
535 NeedsLink->Link = SplitNode;
537 NeedsLink = SplitNode;
544 if (Active.Node->isRoot()) {
545 if (Active.Len > 0) {
547 Active.Idx = EndIdx - SuffixesToAdd + 1;
551 Active.Node = Active.Node->Link;
555 return SuffixesToAdd;
576 size_t findCandidates(std::vector<Candidate> &CandidateList,
577 std::vector<OutlinedFunction> &FunctionList,
578 const std::function<
unsigned(SuffixTreeNode &,
size_t,
unsigned)>
581 CandidateList.clear();
582 FunctionList.clear();
586 for (SuffixTreeNode* Leaf : LeafVector) {
587 assert(Leaf &&
"Leaves in LeafVector cannot be null!");
591 assert(Leaf->Parent &&
"All leaves must have parents!");
592 SuffixTreeNode &Parent = *(Leaf->Parent);
595 if (Parent.OccurrenceCount < 2 || Parent.isRoot() || !Parent.IsInTree)
598 size_t StringLen = Leaf->ConcatLen - Leaf->size();
601 unsigned Benefit = BenefitFn(Parent,
602 StringLen, Str[Leaf->SuffixIdx + StringLen - 1]);
608 if (StringLen > MaxLen)
611 unsigned OccurrenceCount = 0;
612 for (
auto &ChildPair : Parent.Children) {
613 SuffixTreeNode *M = ChildPair.second;
616 if (M && M->IsInTree && M->isLeaf()) {
618 CandidateList.emplace_back(M->SuffixIdx, StringLen, FnIdx);
619 CandidateList.back().Benefit = Benefit;
625 std::vector<unsigned> CandidateSequence;
626 for (
unsigned i = Leaf->SuffixIdx; i < Leaf->SuffixIdx + StringLen; i++)
627 CandidateSequence.push_back(Str[i]);
629 FunctionList.emplace_back(FnIdx, OccurrenceCount, CandidateSequence,
634 Parent.IsInTree =
false;
643 SuffixTree(
const std::vector<unsigned> &Str) : Str(Str) {
644 Root = insertInternalNode(
nullptr, EmptyIdx, EmptyIdx, 0);
645 Root->IsInTree =
true;
647 LeafVector = std::vector<SuffixTreeNode*>(Str.size());
651 size_t SuffixesToAdd = 0;
657 for (
size_t PfxEndIdx = 0,
End = Str.size(); PfxEndIdx <
End; PfxEndIdx++) {
659 LeafEndIdx = PfxEndIdx;
660 SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
664 assert(Root &&
"Root node can't be nullptr!");
665 setSuffixIndices(*Root, 0);
670 struct InstructionMapper {
676 unsigned IllegalInstrNumber = -3;
680 unsigned LegalInstrNumber = 0;
684 InstructionIntegerMap;
691 std::vector<unsigned> UnsignedVec;
695 std::vector<MachineBasicBlock::iterator> InstrList;
707 InstrList.push_back(It);
712 std::tie(ResultIt, WasInserted) =
713 InstructionIntegerMap.
insert(std::make_pair(&MI, LegalInstrNumber));
714 unsigned MINumber = ResultIt->second;
719 IntegerInstructionMap.
insert(std::make_pair(MINumber, &MI));
722 UnsignedVec.push_back(MINumber);
725 if (LegalInstrNumber >= IllegalInstrNumber)
729 &&
"Tried to assign DenseMap tombstone or empty key to instruction.");
731 &&
"Tried to assign DenseMap tombstone or empty key to instruction.");
742 unsigned MINumber = IllegalInstrNumber;
744 InstrList.push_back(It);
745 UnsignedVec.push_back(IllegalInstrNumber);
746 IllegalInstrNumber--;
748 assert(LegalInstrNumber < IllegalInstrNumber &&
749 "Instruction mapping overflow!");
751 assert(IllegalInstrNumber !=
753 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
755 assert(IllegalInstrNumber !=
757 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
781 case TargetInstrInfo::MachineOutlinerInstrType::Illegal:
782 mapToIllegalUnsigned(It);
785 case TargetInstrInfo::MachineOutlinerInstrType::Legal:
786 mapToLegalUnsigned(It);
789 case TargetInstrInfo::MachineOutlinerInstrType::Invisible:
798 InstrList.push_back(MBB.
end());
799 UnsignedVec.push_back(IllegalInstrNumber);
800 IllegalInstrNumber--;
803 InstructionMapper() {
807 "DenseMapInfo<unsigned>'s empty key isn't -1!");
809 "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
826 StringRef getPassName()
const override {
return "Machine Outliner"; }
848 std::vector<OutlinedFunction> &FunctionList,
849 InstructionMapper &Mapper);
853 InstructionMapper &Mapper);
868 unsigned buildCandidateList(std::vector<Candidate> &CandidateList,
869 std::vector<OutlinedFunction> &FunctionList,
871 InstructionMapper &Mapper,
886 void pruneOverlaps(std::vector<Candidate> &CandidateList,
887 std::vector<OutlinedFunction> &FunctionList,
888 unsigned MaxCandidateLen,
893 bool runOnModule(
Module &M)
override;
905 "Machine Function Outliner",
false,
false)
907 void MachineOutliner::pruneOverlaps(std::vector<Candidate> &CandidateList,
908 std::vector<OutlinedFunction> &FunctionList,
909 unsigned MaxCandidateLen,
916 for (
auto It = CandidateList.begin(), Et = CandidateList.end(); It != Et;
919 OutlinedFunction &F1 = FunctionList[C1.FunctionIdx];
922 if (!C1.InCandidateList)
926 if (F1.Benefit < 1 || F1.OccurrenceCount < 2) {
927 assert(F1.OccurrenceCount > 0 &&
928 "Can't remove OutlinedFunction with no occurrences!");
929 F1.OccurrenceCount--;
930 C1.InCandidateList =
false;
936 unsigned FarthestPossibleIdx = 0;
939 if (C1.StartIdx > MaxCandidateLen)
940 FarthestPossibleIdx = C1.StartIdx - MaxCandidateLen;
945 for (
auto Sit = It + 1; Sit != Et; Sit++) {
946 Candidate &C2 = *Sit;
947 OutlinedFunction &F2 = FunctionList[C2.FunctionIdx];
950 if (C2.StartIdx < FarthestPossibleIdx)
954 if (!C2.InCandidateList)
958 if (F2.OccurrenceCount < 2 || F2.Benefit < 1) {
960 assert(F2.OccurrenceCount > 0 &&
961 "Can't remove OutlinedFunction with no occurrences!");
962 F2.OccurrenceCount--;
963 C2.InCandidateList =
false;
967 size_t C2End = C2.StartIdx + C2.Len - 1;
977 if (C2End < C1.StartIdx)
985 if (C1.Benefit >= C2.Benefit) {
989 assert(F2.OccurrenceCount > 0 &&
990 "Can't remove OutlinedFunction with no occurrences!");
991 F2.OccurrenceCount--;
992 F2.Benefit = TII.getOutliningBenefit(F2.Sequence.size(),
997 C2.InCandidateList =
false;
1000 dbgs() <<
"- Removed C2. \n";
1001 dbgs() <<
"--- Num fns left for C2: " << F2.OccurrenceCount <<
"\n";
1002 dbgs() <<
"--- C2's benefit: " << F2.Benefit <<
"\n";
1008 assert(F1.OccurrenceCount > 0 &&
1009 "Can't remove OutlinedFunction with no occurrences!");
1010 F1.OccurrenceCount--;
1011 F1.Benefit = TII.getOutliningBenefit(F1.Sequence.size(),
1015 C1.InCandidateList =
false;
1018 dbgs() <<
"- Removed C1. \n";
1019 dbgs() <<
"--- Num fns left for C1: " << F1.OccurrenceCount <<
"\n";
1020 dbgs() <<
"--- C1's benefit: " << F1.Benefit <<
"\n";
1031 MachineOutliner::buildCandidateList(std::vector<Candidate> &CandidateList,
1032 std::vector<OutlinedFunction> &FunctionList,
1034 InstructionMapper &Mapper,
1037 std::vector<unsigned> CandidateSequence;
1038 size_t MaxCandidateLen = 0;
1043 auto BenefitFn = [&
TII, &Mapper](
const SuffixTreeNode &Curr,
1044 size_t StringLen,
unsigned EndVal) {
1057 size_t Occurrences = Curr.OccurrenceCount;
1060 if (Occurrences < 2)
1065 Mapper.IntegerInstructionMap[EndVal];
1066 assert(LastInstr &&
"Last instruction in sequence was unmapped!");
1074 MaxCandidateLen = ST.findCandidates(CandidateList, FunctionList, BenefitFn);
1076 for (
auto &OF : FunctionList)
1077 OF.IsTailCall = Mapper.
1078 IntegerInstructionMap[OF.Sequence.back()]->isTerminator();
1083 std::stable_sort(CandidateList.begin(), CandidateList.end());
1085 return MaxCandidateLen;
1089 MachineOutliner::createOutlinedFunction(
Module &M,
const OutlinedFunction &OF,
1090 InstructionMapper &Mapper) {
1095 std::ostringstream NameStream;
1096 NameStream <<
"OUTLINED_FUNCTION" <<
"_" << OF.Name;
1102 assert(F &&
"Function was null!");
1111 Builder.CreateRetVoid();
1120 MF.insert(MF.begin(), &MBB);
1126 for (
unsigned Str : OF.Sequence) {
1128 MF.CloneMachineInstr(Mapper.IntegerInstructionMap.find(Str)->second);
1142 bool MachineOutliner::outline(
Module &M,
1144 std::vector<OutlinedFunction> &FunctionList,
1145 InstructionMapper &Mapper) {
1147 bool OutlinedSomething =
false;
1150 for (
const Candidate &C : CandidateList) {
1153 if (!C.InCandidateList)
1157 OutlinedFunction &OF = FunctionList[C.FunctionIdx];
1160 if (OF.OccurrenceCount < 2 || OF.Benefit < 1)
1164 assert(C.StartIdx < Mapper.InstrList.size() &&
"Candidate out of bounds!");
1167 unsigned EndIdx = C.StartIdx + C.Len - 1;
1169 assert(EndIdx < Mapper.InstrList.size() &&
"Candidate out of bounds!");
1171 assert(EndIt != MBB->end() &&
"EndIt out of bounds!");
1177 OF.MF = createOutlinedFunction(M, OF, Mapper);
1187 StartIt = Mapper.InstrList[C.StartIdx];
1188 MBB->erase(StartIt, EndIt);
1190 OutlinedSomething =
true;
1197 dbgs() <<
"OutlinedSomething = " << OutlinedSomething <<
"\n";
1200 return OutlinedSomething;
1203 bool MachineOutliner::runOnModule(
Module &M) {
1215 InstructionMapper Mapper;
1233 Mapper.convertToUnsignedVec(MBB, *TRI, *TII);
1238 SuffixTree
ST(Mapper.UnsignedVec);
1239 std::vector<Candidate> CandidateList;
1240 std::vector<OutlinedFunction> FunctionList;
1243 unsigned MaxCandidateLen =
1244 buildCandidateList(CandidateList, FunctionList, ST, Mapper, *TII);
1247 pruneOverlaps(CandidateList, FunctionList, MaxCandidateLen, *TII);
1250 return outline(M, CandidateList, FunctionList, Mapper);
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
STATISTIC(NumFunctions,"Total number of functions")
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
A Module instance is used to store all the information related to an LLVM module. ...
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Like Internal, but omit from symbol table.
virtual MachineBasicBlock::iterator insertOutlinedCall(Module &M, MachineBasicBlock &MBB, MachineBasicBlock::iterator &It, MachineFunction &MF, bool IsTailCall) const
Insert a call to an outlined function into the program.
virtual void insertOutlinerPrologue(MachineBasicBlock &MBB, MachineFunction &MF, bool IsTailCall) const
Insert a custom prologue for outlined functions.
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
This file defines the MallocAllocator and BumpPtrAllocator interfaces.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
AnalysisUsage & addRequired()
virtual unsigned getOutliningBenefit(size_t SequenceSize, size_t Occurrences, bool CanBeTailCall) const
Return how many instructions would be saved by outlining a sequence containing SequenceSize instructi...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const HexagonInstrInfo * TII
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
virtual void insertOutlinerEpilogue(MachineBasicBlock &MBB, MachineFunction &MF, bool IsTailCall) const
Insert a custom epilogue for outlined functions.
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
virtual MachineOutlinerInstrType getOutliningType(MachineInstr &MI) const
Returns how or if MI should be outlined.
TargetInstrInfo - Interface to description of machine instruction set.
bool isLeaf(ID id)
Returns true if the intrinsic is a leaf, i.e.
LLVM Basic Block Representation.
This is an important class for using LLVM in a threaded context.
Allocate memory in an ever growing pool, as if by bump-pointer.
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
static const unsigned End
ModulePass * createMachineOutlinerPass()
This pass performs outlining on machine instructions directly before printing assembly.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
MachineFunction & getOrCreateMachineFunction(const Function &F)
Returns the MachineFunction constructed for the IR function F.
void initializeMachineOutlinerPass(PassRegistry &)
void dropMemRefs()
Clear this MachineInstr's memory reference descriptor list.
A BumpPtrAllocator that allows only elements of a specific type to be allocated.
void setLinkage(LinkageTypes LT)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void setDebugLoc(DebugLoc dl)
Replace current source information with new such.
void setPreservesAll()
Set by analyses that do not transform their input at all.
TargetSubtargetInfo - Generic base class for all target subtargets.
Representation of each machine instruction.
virtual bool isFunctionSafeToOutlineFrom(MachineFunction &MF) const
Return true if the function can safely be outlined from.
void setUnnamedAddr(UnnamedAddr Val)
Sequence
A sequence of states that a pointer may go through in which an objc_retain and objc_release are actua...
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool operator<(int64_t V1, const APSInt &V2)
virtual const TargetInstrInfo * getInstrInfo() const
static const Function * getParent(const Value *V)
print Print MemDeps of function
StringRef - Represent a constant reference to a string, i.e.
INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE,"Machine Function Outliner", false, false) void MachineOutliner
This class contains meta information specific to a module.
LLVMContext & getContext() const
Get the global data context.