43 #define DEBUG_TYPE "aarch64-ccmp"
49 cl::desc(
"Maximum number of instructions per speculated block."));
55 STATISTIC(NumConsidered,
"Number of ccmps considered");
56 STATISTIC(NumPhiRejs,
"Number of ccmps rejected (PHI)");
57 STATISTIC(NumPhysRejs,
"Number of ccmps rejected (Physregs)");
58 STATISTIC(NumPhi2Rejs,
"Number of ccmps rejected (PHI2)");
59 STATISTIC(NumHeadBranchRejs,
"Number of ccmps rejected (Head branch)");
60 STATISTIC(NumCmpBranchRejs,
"Number of ccmps rejected (CmpBB branch)");
61 STATISTIC(NumCmpTermRejs,
"Number of ccmps rejected (CmpBB is cbz...)");
62 STATISTIC(NumImmRangeRejs,
"Number of ccmps rejected (Imm out of range)");
63 STATISTIC(NumLiveDstRejs,
"Number of ccmps rejected (Cmp dest live)");
64 STATISTIC(NumMultNZCVUses,
"Number of ccmps rejected (NZCV used)");
65 STATISTIC(NumUnknNZCVDefs,
"Number of ccmps rejected (NZCV def unknown)");
67 STATISTIC(NumSpeculateRejs,
"Number of ccmps rejected (Can't speculate)");
69 STATISTIC(NumConverted,
"Number of ccmp instructions created");
70 STATISTIC(NumCompBranches,
"Number of cbz/cbnz branches converted");
173 bool trivialTailPHIs();
176 void updateTailPHIs();
179 bool isDeadDef(
unsigned DstReg);
210 int expectedCodeSizeDelta()
const;
216 bool SSACCmpConv::trivialTailPHIs() {
217 for (
auto &
I : *Tail) {
220 unsigned HeadReg = 0, CmpBBReg = 0;
222 for (
unsigned oi = 1, oe =
I.getNumOperands(); oi != oe; oi += 2) {
224 unsigned Reg =
I.getOperand(oi).getReg();
226 assert((!HeadReg || HeadReg == Reg) &&
"Inconsistent PHI operands");
230 assert((!CmpBBReg || CmpBBReg == Reg) &&
"Inconsistent PHI operands");
234 if (HeadReg != CmpBBReg)
242 void SSACCmpConv::updateTailPHIs() {
243 for (
auto &
I : *Tail) {
247 for (
unsigned oi =
I.getNumOperands(); oi > 2; oi -= 2) {
249 if (
I.getOperand(oi - 1).getMBB() == CmpBB) {
250 I.RemoveOperand(oi - 1);
251 I.RemoveOperand(oi - 2);
259 bool SSACCmpConv::isDeadDef(
unsigned DstReg) {
261 if (DstReg == AArch64::WZR || DstReg == AArch64::XZR)
267 return MRI->use_nodbg_empty(DstReg);
275 if (Cond[0].getImm() != -1) {
276 assert(Cond.
size() == 1 &&
"Unknown Cond array format");
281 switch (Cond[1].getImm()) {
288 assert(Cond.
size() == 3 &&
"Unknown Cond array format");
293 assert(Cond.
size() == 3 &&
"Unknown Cond array format");
304 if (!I->readsRegister(AArch64::NZCV)) {
305 switch (I->getOpcode()) {
314 DEBUG(
dbgs() <<
"Flags not used by terminator: " << *I);
321 assert(!I->isTerminator() &&
"Spurious terminator");
322 switch (I->getOpcode()) {
324 case AArch64::SUBSWri:
325 case AArch64::SUBSXri:
327 case AArch64::ADDSWri:
328 case AArch64::ADDSXri:
331 if (I->getOperand(3).getImm() || !isUInt<5>(I->getOperand(2).getImm())) {
332 DEBUG(
dbgs() <<
"Immediate out of range for ccmp: " << *I);
337 case AArch64::SUBSWrr:
338 case AArch64::SUBSXrr:
339 case AArch64::ADDSWrr:
340 case AArch64::ADDSXrr:
341 if (isDeadDef(I->getOperand(0).getReg()))
343 DEBUG(
dbgs() <<
"Can't convert compare with live destination: " << *I);
346 case AArch64::FCMPSrr:
347 case AArch64::FCMPDrr:
348 case AArch64::FCMPESrr:
349 case AArch64::FCMPEDrr:
354 MIOperands::PhysRegInfo PRI =
361 DEBUG(
dbgs() <<
"Can't create ccmp with multiple uses: " << *I);
366 if (PRI.Defined || PRI.Clobbered) {
367 DEBUG(
dbgs() <<
"Not convertible compare: " << *I);
395 if (I.isDebugValue())
414 DEBUG(
dbgs() <<
"Won't speculate load: " << I);
419 bool DontMoveAcrossStore =
true;
420 if (!I.isSafeToMove(
nullptr, DontMoveAcrossStore)) {
421 DEBUG(
dbgs() <<
"Can't speculate: " << I);
426 if (&I != CmpMI && I.modifiesRegister(AArch64::NZCV, TRI)) {
427 DEBUG(
dbgs() <<
"Clobbers flags: " << I);
439 Tail = CmpBB =
nullptr;
441 if (Head->succ_size() != 2)
457 if (!CmpBB->isSuccessor(Tail))
461 DEBUG(
dbgs() <<
"\nTriangle: BB#" << Head->getNumber() <<
" -> BB#"
462 << CmpBB->getNumber() <<
" -> BB#" << Tail->getNumber() <<
'\n');
471 if (!trivialTailPHIs()) {
472 DEBUG(
dbgs() <<
"Can't handle phis in Tail.\n");
477 if (!Tail->livein_empty()) {
478 DEBUG(
dbgs() <<
"Can't handle live-in physregs in Tail.\n");
485 if (!CmpBB->empty() && CmpBB->front().isPHI()) {
486 DEBUG(
dbgs() <<
"Can't handle phis in CmpBB.\n");
491 if (!CmpBB->livein_empty()) {
492 DEBUG(
dbgs() <<
"Can't handle live-in physregs in CmpBB.\n");
501 DEBUG(
dbgs() <<
"Head branch not analyzable.\n");
508 if (!TBB || HeadCond.
empty()) {
509 DEBUG(
dbgs() <<
"AnalyzeBranch didn't find conditional branch in Head.\n");
515 DEBUG(
dbgs() <<
"Unsupported branch type on Head\n");
522 assert(TBB == Tail &&
"Unexpected TBB");
529 DEBUG(
dbgs() <<
"CmpBB branch not analyzable.\n");
534 if (!TBB || CmpBBCond.
empty()) {
535 DEBUG(
dbgs() <<
"AnalyzeBranch didn't find conditional branch in CmpBB.\n");
540 if (!
parseCond(CmpBBCond, CmpBBTailCC)) {
541 DEBUG(
dbgs() <<
"Unsupported branch type on CmpBB\n");
553 CmpMI = findConvertibleCompare(CmpBB);
557 if (!canSpeculateInstrs(CmpBB, CmpMI)) {
565 DEBUG(
dbgs() <<
"Merging BB#" << CmpBB->getNumber() <<
" into BB#"
566 << Head->getNumber() <<
":\n" << *CmpBB);
577 Head->removeSuccessor(CmpBB);
578 CmpBB->removeSuccessor(Tail);
582 if (Head->hasSuccessorProbabilities() && CmpBB->hasSuccessorProbabilities()) {
589 assert(*Head->succ_begin() == Tail &&
"Head successor is not Tail");
591 Head->setSuccProbability(Head->succ_begin(),
592 Head2Tail + Head2CmpBB * CmpBB2Tail);
599 for (
auto I = CmpBB->succ_begin(),
E = CmpBB->succ_end(); I !=
E; ++
I) {
601 CmpBB->setSuccProbability(I, Head2CmpBB * CmpBB2I);
605 Head->transferSuccessorsAndUpdatePHIs(CmpBB);
606 DebugLoc TermDL = Head->getFirstTerminator()->getDebugLoc();
611 if (HeadCond[0].getImm() == -1) {
614 switch (HeadCond[1].getImm()) {
617 Opc = AArch64::SUBSWri;
621 Opc = AArch64::SUBSXri;
629 MRI->createVirtualRegister(
TII->getRegClass(MCID, 0, TRI, *MF));
631 BuildMI(*Head, Head->end(), TermDL, MCID)
637 MRI->constrainRegClass(HeadCond[2].
getReg(),
638 TII->getRegClass(MCID, 1, TRI, *MF));
641 Head->splice(Head->end(), CmpBB, CmpBB->begin(), CmpBB->end());
646 unsigned FirstOp = 1;
647 bool isZBranch =
false;
651 case AArch64::SUBSWri: Opc = AArch64::CCMPWi;
break;
652 case AArch64::SUBSWrr: Opc = AArch64::CCMPWr;
break;
653 case AArch64::SUBSXri: Opc = AArch64::CCMPXi;
break;
654 case AArch64::SUBSXrr: Opc = AArch64::CCMPXr;
break;
655 case AArch64::ADDSWri: Opc = AArch64::CCMNWi;
break;
656 case AArch64::ADDSWrr: Opc = AArch64::CCMNWr;
break;
657 case AArch64::ADDSXri: Opc = AArch64::CCMNXi;
break;
658 case AArch64::ADDSXrr: Opc = AArch64::CCMNXr;
break;
659 case AArch64::FCMPSrr: Opc = AArch64::FCCMPSrr; FirstOp = 0;
break;
660 case AArch64::FCMPDrr: Opc = AArch64::FCCMPDrr; FirstOp = 0;
break;
661 case AArch64::FCMPESrr: Opc = AArch64::FCCMPESrr; FirstOp = 0;
break;
662 case AArch64::FCMPEDrr: Opc = AArch64::FCCMPEDrr; FirstOp = 0;
break;
665 Opc = AArch64::CCMPWi;
671 Opc = AArch64::CCMPXi;
685 TII->getRegClass(MCID, 0, TRI, *MF));
688 TII->getRegClass(MCID, 1, TRI, *MF));
700 bool isNZ = CmpMI->
getOpcode() == AArch64::CBNZW ||
707 Head->updateTerminator();
710 CmpBB->eraseFromParent();
715 int SSACCmpConv::expectedCodeSizeDelta()
const {
720 if (HeadCond[0].getImm() == -1) {
721 switch (HeadCond[1].getImm()) {
777 return "AArch64 Conditional Compares";
784 void invalidateTraces();
792 "AArch64 CCMP Pass",
false,
false)
800 return new AArch64ConditionalCompares();
803 void AArch64ConditionalCompares::getAnalysisUsage(
AnalysisUsage &AU)
const {
815 void AArch64ConditionalCompares::updateDomTree(
822 assert(Node != HeadNode &&
"Cannot erase the head node");
823 assert(Node->
getIDom() == HeadNode &&
"CmpBB should be dominated by Head");
825 DomTree->changeImmediateDominator(Node->
getChildren().back(), HeadNode);
826 DomTree->eraseNode(RemovedMBB);
836 Loops->removeBlock(RemovedMBB);
840 void AArch64ConditionalCompares::invalidateTraces() {
841 Traces->invalidate(CmpConv.Head);
842 Traces->invalidate(CmpConv.CmpBB);
860 int CodeSizeDelta = CmpConv.expectedCodeSizeDelta();
861 DEBUG(
dbgs() <<
"Code size delta: " << CodeSizeDelta <<
'\n');
864 if (CodeSizeDelta < 0)
866 if (CodeSizeDelta > 0) {
867 DEBUG(
dbgs() <<
"Code size is increasing, give up on this one.\n");
879 unsigned DelayLimit = SchedModel.MispredictPenalty * 3 / 4;
884 unsigned CmpBBDepth =
886 DEBUG(
dbgs() <<
"Head depth: " << HeadDepth
887 <<
"\nCmpBB depth: " << CmpBBDepth <<
'\n');
888 if (CmpBBDepth > HeadDepth + DelayLimit) {
889 DEBUG(
dbgs() <<
"Branch delay would be larger than " << DelayLimit
897 DEBUG(
dbgs() <<
"Resources: " << ResDepth <<
'\n');
902 if (ResDepth > HeadDepth) {
903 DEBUG(
dbgs() <<
"Too many instructions to speculate.\n");
910 bool Changed =
false;
914 CmpConv.convert(RemovedBlocks);
916 updateDomTree(RemovedBlocks);
917 updateLoops(RemovedBlocks);
922 bool AArch64ConditionalCompares::runOnMachineFunction(
MachineFunction &MF) {
923 DEBUG(
dbgs() <<
"********** AArch64 Conditional Compares **********\n"
924 <<
"********** Function: " << MF.
getName() <<
'\n');
932 DomTree = &getAnalysis<MachineDominatorTree>();
933 Loops = getAnalysisIfAvailable<MachineLoopInfo>();
934 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
935 Traces = &getAnalysis<MachineTraceMetrics>();
939 bool Changed =
false;
940 CmpConv.runOnMachineFunction(MF, MBPI);
948 if (tryConvert(I->getBlock()))
Pass interface - Implemented by all 'passes'.
unsigned succ_size() const
void push_back(const T &Elt)
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")
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
aarch64 AArch64 CCMP false
static CondCode getInvertedCondCode(CondCode Code)
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.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
const MachineInstrBuilder & add(const MachineOperand &MO) const
INITIALIZE_PASS_BEGIN(AArch64ConditionalCompares,"aarch64-ccmp","AArch64 CCMP Pass", false, false) INITIALIZE_PASS_END(AArch64ConditionalCompares
A trace ensemble is a collection of traces selected using the same strategy, for example 'minimum res...
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
FunctionPass * createAArch64ConditionalCompares()
static unsigned InstrCount
bool optForMinSize() const
Optimize this function for minimum size (-Oz).
static cl::opt< unsigned > BlockInstrLimit("aarch64-ccmp-limit", cl::init(30), cl::Hidden, cl::desc("Maximum number of instructions per speculated block."))
const std::vector< DomTreeNodeBase * > & getChildren() const
InstrCycles getInstrCycles(const MachineInstr &MI) const
Return the depth and height of MI.
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e...
AnalysisUsage & addRequired()
static cl::opt< bool > Stress("aarch64-stress-ccmp", cl::Hidden, cl::desc("Turn all knobs to 11"))
#define INITIALIZE_PASS_DEPENDENCY(depName)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
Reg
All possible values of the reg field in the ModR/M byte.
const MCSchedModel & getSchedModel() const
Get the machine model for this subtarget's CPU.
static const char * getCondCodeName(CondCode Code)
PhysRegInfo analyzePhysReg(unsigned Reg, const TargetRegisterInfo *TRI)
analyzePhysReg - Analyze how the current instruction or bundle uses a physical register.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
Select the trace through a block that has the fewest instructions.
DomTreeNodeBase * getIDom() const
bool livein_empty() const
Base class for the actual dominator tree node.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
size_t size() const
size - Get the array size.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
TargetInstrInfo - Interface to description of machine instruction set.
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)
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.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
FunctionPass class - This class is used to implement most global optimizations.
succ_iterator succ_begin()
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
A trace represents a plausible sequence of executed basic blocks that passes through the current basi...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
static bool parseCond(ArrayRef< MachineOperand > Cond, AArch64CC::CondCode &CC)
MIOperands - Iterate over operands of a single instruction.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
static unsigned getNZCVToSatisfyCondCode(CondCode Code)
Given a condition code, return NZCV flags that would satisfy that condition.
static unsigned getReg(const void *D, unsigned RC, unsigned RegNo)
unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const override
Remove the branching code at the end of the specific MBB.
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.
Representation of each machine instruction.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
void initializeAArch64ConditionalComparesPass(PassRegistry &)
iterator_range< df_iterator< T > > depth_first(const T &G)
unsigned getReg() const
getReg - Returns the register number.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
virtual const TargetInstrInfo * getInstrInfo() const
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
unsigned getResourceDepth(bool Bottom) const
Return the resource depth of the top/bottom of the trace center block.
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
StringRef - Represent a constant reference to a string, i.e.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
Machine model for scheduling, bundling, and heuristics.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
unsigned pred_size() const
size_t getNumChildren() const