91 #define DEBUG_TYPE "hexagon-eif"
107 cl::desc(
"Size limit in Hexagon early if-conversion"));
117 return OS <<
"<none>";
118 return OS <<
'#' << P.MB->getNumber();
122 FlowPattern() =
default;
125 : SplitB(B), TrueB(TB), FalseB(FB), JoinB(JB), PredR(PR) {}
138 const FlowPattern &FP;
145 OS <<
"{ SplitB:" << PrintMB(P.FP.SplitB)
146 <<
", PredR:" <<
PrintReg(P.FP.PredR, &P.TRI)
147 <<
", TrueB:" << PrintMB(P.FP.TrueB)
148 <<
", FalseB:" << PrintMB(P.FP.FalseB)
149 <<
", JoinB:" << PrintMB(P.FP.JoinB) <<
" }";
158 HII(nullptr), TRI(nullptr), MFN(nullptr),
MRI(nullptr), MDT(nullptr),
164 return "Hexagon early if conversion";
190 bool isValid(
const FlowPattern &FP)
const;
193 const FlowPattern &FP)
const;
194 bool isProfitable(
const FlowPattern &FP)
const;
198 unsigned getCondStoreOpcode(
unsigned Opc,
bool IfTrue)
const;
203 unsigned PredR,
bool IfTrue);
207 unsigned TSR,
unsigned FR,
unsigned FSR);
209 void convert(
const FlowPattern &FP);
215 void simplifyFlowGraph(
const FlowPattern &FP);
223 BlockSetType Deleted;
232 "Hexagon early if conversion",
false,
false)
235 if (B->succ_size() != 1)
239 return L && SB == L->
getHeader() && MDT->dominates(B, SB);
253 unsigned Opc = T1I->getOpcode();
254 if (Opc != Hexagon::J2_jumpt && Opc != Hexagon::J2_jumpf)
256 unsigned PredR = T1I->getOperand(0).getReg();
265 assert(T2I == B->
end() || T2I->getOpcode() == Hexagon::J2_jump);
267 : T2I->getOperand(0).getMBB();
276 if (Opc == Hexagon::J2_jumpt)
281 if (!MDT->properlyDominates(B, TB) || !MDT->properlyDominates(B, FB))
288 unsigned TNP = TB->
pred_size(), FNP = FB->pred_size();
289 unsigned TNS = TB->succ_size(), FNS = FB->succ_size();
296 bool TOk = (TNP == 1 && TNS == 1 && MLI->getLoopFor(TB) ==
L);
297 bool FOk = (FNP == 1 && FNS == 1 && MLI->getLoopFor(FB) ==
L);
301 if (SkipExitBranches && MLI->getLoopFor(TB) != MLI->getLoopFor(FB))
330 if ((TB && isPreheader(TB)) || (FB && isPreheader(FB))) {
331 DEBUG(
dbgs() <<
"One of blocks " << PrintMB(TB) <<
", " << PrintMB(FB)
332 <<
" is a loop preheader. Skipping.\n");
336 FP = FlowPattern(B, PredR, TB, FB, JB);
337 DEBUG(
dbgs() <<
"Detected " << PrintFP(FP, *TRI) <<
"\n");
372 for (
auto &
MI : *B) {
373 if (
MI.isDebugValue())
375 if (
MI.isConditionalBranch())
377 unsigned Opc =
MI.getOpcode();
378 bool IsJMP = (Opc == Hexagon::J2_jump);
379 if (!isPredicableStore(&
MI) && !IsJMP && !isSafeToSpeculate(&
MI))
388 if (!MO.isReg() || !MO.isDef())
390 unsigned R = MO.getReg();
393 switch (
MRI->getRegClass(R)->getID()) {
394 case Hexagon::PredRegsRegClassID:
395 case Hexagon::VecPredRegsRegClassID:
396 case Hexagon::VecPredRegs128BRegClassID:
401 for (
auto U =
MRI->use_begin(R); U !=
MRI->use_end(); ++U)
402 if (U->getParent()->isPHI())
409 bool HexagonEarlyIfConversion::usesUndefVReg(
const MachineInstr *
MI)
const {
411 if (!MO.isReg() || !MO.isUse())
413 unsigned R = MO.getReg();
418 assert(DefI &&
"Expecting a reaching def in MRI");
426 if (hasEHLabel(FP.SplitB))
428 if (FP.TrueB && !isValidCandidate(FP.TrueB))
430 if (FP.FalseB && !isValidCandidate(FP.FalseB))
447 if (usesUndefVReg(&MI))
451 if (RC == &Hexagon::PredRegsRegClass)
459 const FlowPattern &FP)
const {
474 if (BB == FP.SplitB || BB == FP.TrueB || BB == FP.FalseB)
491 if (!HII->isPredicable(*Def1) || !HII->isPredicable(*Def3))
497 unsigned HexagonEarlyIfConversion::countPredicateDefs(
499 unsigned PredDefs = 0;
500 for (
auto &MI : *B) {
502 if (!MO.isReg() || !MO.isDef())
504 unsigned R = MO.getReg();
507 if (
MRI->getRegClass(R) == &Hexagon::PredRegsRegClass)
514 bool HexagonEarlyIfConversion::isProfitable(
const FlowPattern &FP)
const {
515 if (FP.TrueB && FP.FalseB) {
519 if (MBPI->getEdgeProbability(FP.SplitB, FP.TrueB) > Prob)
521 if (MBPI->getEdgeProbability(FP.SplitB, FP.FalseB) > Prob)
549 unsigned TotalIn = TotalCount(FP.TrueB, Spare) + TotalCount(FP.FalseB, Spare);
550 DEBUG(
dbgs() <<
"Total number of instructions to be predicated/speculated: "
551 << TotalIn <<
", spare room: " << Spare <<
"\n");
552 if (TotalIn >= SizeLimit+Spare)
561 unsigned TotalPh = 0;
562 unsigned PredDefs = countPredicateDefs(FP.SplitB);
564 TotalPh = computePhiCost(FP.JoinB, FP);
565 PredDefs += countPredicateDefs(FP.JoinB);
567 if (FP.TrueB && FP.TrueB->succ_size() > 0) {
569 TotalPh += computePhiCost(SB, FP);
570 PredDefs += countPredicateDefs(SB);
572 if (FP.FalseB && FP.FalseB->succ_size() > 0) {
574 TotalPh += computePhiCost(SB, FP);
575 PredDefs += countPredicateDefs(SB);
578 DEBUG(
dbgs() <<
"Total number of extra muxes from converted phis: "
580 if (TotalIn+TotalPh >= SizeLimit+Spare)
583 DEBUG(
dbgs() <<
"Total number of predicate registers: " << PredDefs <<
"\n");
592 bool Changed =
false;
605 DTNodeVectType Cn(GTN::child_begin(N), GTN::child_end(N));
606 for (DTNodeVectType::iterator I = Cn.begin(),
E = Cn.end(); I !=
E; ++
I) {
608 if (!Deleted.count(SB))
609 Changed |= visitBlock(SB, L);
614 if (MLI->getLoopFor(B) !=
L)
618 if (!matchFlowPattern(B, L, FP))
622 DEBUG(
dbgs() <<
"Conversion is not valid\n");
625 if (!isProfitable(FP)) {
626 DEBUG(
dbgs() <<
"Conversion is not profitable\n");
631 simplifyFlowGraph(FP);
635 bool HexagonEarlyIfConversion::visitLoop(
MachineLoop *L) {
637 DEBUG((L ?
dbgs() <<
"Visiting loop H:" << PrintMB(HB)
638 :
dbgs() <<
"Visiting function") <<
"\n");
639 bool Changed =
false;
642 Changed |= visitLoop(*I);
646 Changed |= visitBlock(L ? HB : EntryB, L);
650 bool HexagonEarlyIfConversion::isPredicableStore(
const MachineInstr *MI)
657 case Hexagon::S2_storerb_io:
658 case Hexagon::S2_storerbnew_io:
659 case Hexagon::S2_storerh_io:
660 case Hexagon::S2_storerhnew_io:
661 case Hexagon::S2_storeri_io:
662 case Hexagon::S2_storerinew_io:
663 case Hexagon::S2_storerd_io:
664 case Hexagon::S4_storeirb_io:
665 case Hexagon::S4_storeirh_io:
666 case Hexagon::S4_storeiri_io:
671 return MI->
mayStore() && HII->isPredicable(const_cast<MachineInstr&>(*MI));
674 bool HexagonEarlyIfConversion::isSafeToSpeculate(
const MachineInstr *MI)
686 unsigned HexagonEarlyIfConversion::getCondStoreOpcode(
unsigned Opc,
688 return HII->getCondOpcode(Opc, !IfTrue);
693 unsigned PredR,
bool IfTrue) {
695 if (At != ToB->
end())
696 DL = At->getDebugLoc();
697 else if (!ToB->
empty())
702 if (isPredicableStore(MI)) {
703 unsigned COpc = getCondStoreOpcode(Opc, IfTrue);
707 if (HII->isPostIncrement(*MI)) {
724 if (Opc == Hexagon::J2_jump) {
726 const MCInstrDesc &
D = HII->get(IfTrue ? Hexagon::J2_jumpt
727 : Hexagon::J2_jumpf);
746 unsigned PredR,
bool IfTrue) {
747 DEBUG(
dbgs() <<
"Predicating block " << PrintMB(FromB) <<
"\n");
751 for (I = FromB->
begin(); I !=
End; I = NextI) {
753 NextI = std::next(I);
754 if (isSafeToSpeculate(&*I))
755 ToB->
splice(At, FromB, I);
757 predicateInstr(ToB, At, &*I, PredR, IfTrue);
763 unsigned PredR,
unsigned TR,
unsigned TSR,
unsigned FR,
unsigned FSR) {
765 switch (DRC->
getID()) {
766 case Hexagon::IntRegsRegClassID:
767 Opc = Hexagon::C2_mux;
769 case Hexagon::DoubleRegsRegClassID:
770 Opc = Hexagon::PS_pselect;
772 case Hexagon::VectorRegsRegClassID:
773 Opc = Hexagon::PS_vselect;
775 case Hexagon::VecDblRegsRegClassID:
776 Opc = Hexagon::PS_wselect;
778 case Hexagon::VectorRegs128BRegClassID:
779 Opc = Hexagon::PS_vselect_128B;
781 case Hexagon::VecDblRegs128BRegClassID:
782 Opc = Hexagon::PS_wselect_128B;
790 unsigned MuxR =
MRI->createVirtualRegister(DRC);
799 const FlowPattern &FP) {
803 for (
auto I = WhereB->
begin(); I != NonPHI; ++
I) {
806 unsigned TR = 0, TSR = 0, FR = 0, FSR = 0, SR = 0, SSR = 0;
809 if (BO.getMBB() == FP.SplitB)
811 else if (BO.getMBB() == FP.TrueB)
813 else if (BO.getMBB() == FP.FalseB)
826 unsigned MuxR = 0, MuxSR = 0;
831 MuxR = buildMux(FP.SplitB, FP.SplitB->getFirstTerminator(), RC,
832 FP.PredR, TR, TSR, FR, FSR);
842 false,
false, MuxSR));
847 void HexagonEarlyIfConversion::convert(
const FlowPattern &FP) {
850 assert(OldTI != FP.SplitB->end());
854 TSB = *FP.TrueB->succ_begin();
855 predicateBlockNB(FP.SplitB, OldTI, FP.TrueB, FP.PredR,
true);
858 FSB = *FP.FalseB->succ_begin();
860 predicateBlockNB(FP.SplitB, At, FP.FalseB, FP.PredR,
false);
867 FP.SplitB->erase(OldTI, FP.SplitB->end());
868 while (FP.SplitB->succ_size() > 0) {
884 if (T != FP.TrueB && T != FP.FalseB) {
888 FP.SplitB->removeSuccessor(FP.SplitB->succ_begin());
896 assert(!SSB || SSB == FP.JoinB);
897 BuildMI(*FP.SplitB, FP.SplitB->end(),
DL, HII->get(Hexagon::J2_jump))
899 FP.SplitB->addSuccessor(FP.JoinB);
901 bool HasBranch =
false;
903 BuildMI(*FP.SplitB, FP.SplitB->end(),
DL, HII->get(Hexagon::J2_jumpt))
906 FP.SplitB->addSuccessor(TSB);
910 const MCInstrDesc &D = HasBranch ? HII->get(Hexagon::J2_jump)
911 : HII->get(Hexagon::J2_jumpf);
916 FP.SplitB->addSuccessor(FSB);
923 BuildMI(*FP.SplitB, FP.SplitB->end(),
DL, HII->get(Hexagon::J2_jump))
925 FP.SplitB->addSuccessor(SSB);
943 DEBUG(
dbgs() <<
"Removing block " << PrintMB(B) <<
"\n");
952 DTNodeVectType Cn(GTN::child_begin(N), GTN::child_end(N));
953 for (DTNodeVectType::iterator I = Cn.begin(),
E = Cn.end(); I !=
E; ++
I) {
955 MDT->changeImmediateDominator(SB, IDB);
963 (*I)->removeSuccessor(B,
true);
971 DEBUG(
dbgs() <<
"Removing phi nodes from block " << PrintMB(B) <<
"\n");
973 for (I = B->
begin(); I != NonPHI; I = NextI) {
974 NextI = std::next(I);
978 unsigned UseR = UO.
getReg(), UseSR = UO.getSubReg();
980 unsigned NewR = UseR;
987 NewR =
MRI->createVirtualRegister(RC);
988 NonPHI =
BuildMI(*B, NonPHI, DL, HII->
get(TargetOpcode::COPY), NewR)
989 .addReg(UseR, 0, UseSR);
991 MRI->replaceRegWith(DefR, NewR);
1001 for (P = SB->
begin(); P !=
N; ++
P) {
1004 if (MO.isMBB() && MO.getMBB() == OldB)
1012 DEBUG(
dbgs() <<
"Merging blocks " << PrintMB(PredB) <<
" and "
1013 << PrintMB(SuccB) <<
"\n");
1014 bool TermOk = hasUncondBranch(SuccB);
1015 eliminatePhis(SuccB);
1016 HII->removeBranch(*PredB);
1023 replacePhiEdges(SuccB, PredB);
1029 void HexagonEarlyIfConversion::simplifyFlowGraph(
const FlowPattern &FP) {
1031 removeBlock(FP.TrueB);
1033 removeBlock(FP.FalseB);
1035 FP.SplitB->updateTerminator();
1036 if (FP.SplitB->succ_size() != 1)
1048 if (!hasEHLabel(SB) || hasUncondBranch(SB))
1049 mergeBlocks(FP.SplitB, SB);
1052 bool HexagonEarlyIfConversion::runOnMachineFunction(
MachineFunction &MF) {
1057 HII =
ST.getInstrInfo();
1058 TRI =
ST.getRegisterInfo();
1061 MDT = &getAnalysis<MachineDominatorTree>();
1062 MLI = &getAnalysis<MachineLoopInfo>();
1063 MBPI = EnableHexagonBP ? &getAnalysis<MachineBranchProbabilityInfo>() :
1067 bool Changed =
false;
1070 Changed |= visitLoop(*I);
1071 Changed |= visitLoop(
nullptr);
1080 return new HexagonEarlyIfConversion();
unsigned succ_size() const
void push_back(const T &Elt)
bool isEHPad() const
Returns true if the block is a landing pad.
mop_iterator operands_end()
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...
bool isBranch(QueryType Type=AnyInBundle) const
Returns true if this is a conditional, unconditional, or indirect branch.
MachineBasicBlock * getMBB() const
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
Implements a dense probed hash-table based set.
static void updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred, BasicBlock *NewPred, PHINode *LandingPadReplacement)
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
Describe properties that are true of each instruction in the target description file.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
A global registry used in conjunction with static constructors to make pluggable components (like tar...
const MachineInstrBuilder & add(const MachineOperand &MO) const
unsigned getID() const
Return the register class ID number.
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
iterator_range< mop_iterator > operands()
BlockT * getHeader() const
AnalysisUsage & addRequired()
A description of a memory reference used in the backend.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
static MachineOperand CreateReg(unsigned 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)
#define HEXAGON_PACKET_SIZE
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
unsigned getNumOperands() const
Access to explicit operands of the instruction.
void RemoveOperand(unsigned i)
Erase an operand from an instruction, leaving it with one fewer operand than it started with...
DomTreeNodeBase * getIDom() const
Base class for the actual dominator tree node.
Printable PrintReg(unsigned Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubRegIdx=0)
Prints virtual and physical registers with or without a TRI instance.
void normalizeSuccProbs()
Normalize probabilities of all successors so that the sum of them becomes one.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool isImplicitDef() const
mmo_iterator memoperands_end() const
INITIALIZE_PASS(HexagonEarlyIfConversion,"hexagon-eif","Hexagon early if conversion", false, false) bool HexagonEarlyIfConversion MachineBasicBlock * SB
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
initializer< Ty > init(const Ty &Val)
const MachineInstrBuilder & setMemRefs(MachineInstr::mmo_iterator b, MachineInstr::mmo_iterator e) const
FunctionPass * createHexagonEarlyIfConversion()
unsigned const MachineRegisterInfo * MRI
const MachineOperand & getOperand(unsigned i) const
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Represent the analysis usage information of a pass.
#define LLVM_ATTRIBUTE_UNUSED
static const unsigned End
bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore...
FunctionPass class - This class is used to implement most global optimizations.
self_iterator getIterator()
succ_iterator succ_begin()
unsigned getSubReg() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
pred_iterator pred_begin()
void initializeHexagonEarlyIfConversionPass(PassRegistry &Registry)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Iterator for intrusive lists based on ilist_node.
void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
MachineOperand class - Representation of each machine instruction operand.
void updateTerminator()
Update the terminator instructions in block to account for changes to the layout. ...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
DebugLoc findBranchDebugLoc()
Find and return the merged DebugLoc of the branch instructions of the block.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
llvm_unreachable("Unknown RegBank!")
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Representation of each machine instruction.
bool hasAddressTaken() const
Test whether this block is potentially the target of an indirect branch.
static MachineOperand CreateMBB(MachineBasicBlock *MBB, unsigned char TargetFlags=0)
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
bool isCall(QueryType Type=AnyInBundle) const
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
LoopInfoBase< MachineBasicBlock, MachineLoop >::iterator iterator
The iterator interface to the top-level loops in the current function.
INITIALIZE_PASS(HexagonGenMux,"hexagon-gen-mux","Hexagon generate mux instructions", false, false) void HexagonGenMux I isValid()
iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
unsigned getReg() const
getReg - Returns the register number.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
mop_iterator operands_begin()
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned char TargetFlags=0) const
This class implements an extremely fast bulk output stream that can only output to a stream...
StringRef - Represent a constant reference to a string, i.e.
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
std::vector< LoopT * >::const_iterator iterator
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
unsigned pred_size() const
bool isBarrier(QueryType Type=AnyInBundle) const
Returns true if the specified instruction stops control flow from executing the instruction immediate...
std::vector< MachineBasicBlock * >::iterator succ_iterator
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.