95#define DEBUG_TYPE "aarch64-condopt"
97STATISTIC(NumConditionsAdjusted,
"Number of conditions adjusted");
108class AArch64ConditionOptimizerImpl {
113 MachineInstr *CondMI;
117 unsigned getOpc()
const {
return CmpMI->getOpcode(); }
120 const AArch64InstrInfo *TII;
121 const TargetRegisterInfo *TRI;
122 MachineDominatorTree *DomTree;
123 const MachineRegisterInfo *MRI;
126 bool run(MachineFunction &MF, MachineDominatorTree &MDT);
129 bool canAdjustCmp(MachineInstr &CmpMI);
130 bool registersMatch(MachineInstr *FirstMI, MachineInstr *SecondMI);
131 bool nzcvLivesOut(MachineBasicBlock *
MBB);
132 MachineInstr *getBccTerminator(MachineBasicBlock *
MBB);
133 MachineInstr *findAdjustableCmp(MachineInstr *CondMI);
135 void updateCmpInstr(MachineInstr *CmpMI,
int NewImm,
unsigned NewOpc);
137 void applyCmpAdjustment(CmpCondPair &Pair,
const CmpInfo &Info);
138 bool tryOptimizePair(CmpCondPair &
First, CmpCondPair &Second);
139 bool optimizeIntraBlock(MachineBasicBlock &
MBB);
140 bool optimizeCrossBlock(MachineBasicBlock &HBB);
146 AArch64ConditionOptimizerLegacy() : MachineFunctionPass(ID) {}
148 void getAnalysisUsage(AnalysisUsage &AU)
const override;
149 bool runOnMachineFunction(MachineFunction &MF)
override;
151 StringRef getPassName()
const override {
152 return "AArch64 Condition Optimizer";
158char AArch64ConditionOptimizerLegacy::ID = 0;
161 "AArch64 CondOpt Pass",
false,
false)
167 return new AArch64ConditionOptimizerLegacy();
170void AArch64ConditionOptimizerLegacy::getAnalysisUsage(
179bool AArch64ConditionOptimizerImpl::canAdjustCmp(MachineInstr &CmpMI) {
182 LLVM_DEBUG(
dbgs() <<
"Immediate of cmp is symbolic, " << CmpMI <<
'\n');
185 LLVM_DEBUG(
dbgs() <<
"Immediate of cmp may be out of range, " << CmpMI
189 LLVM_DEBUG(
dbgs() <<
"Destination of cmp is not dead, " << CmpMI <<
'\n');
197bool AArch64ConditionOptimizerImpl::registersMatch(MachineInstr *FirstMI,
198 MachineInstr *SecondMI) {
202 FirstReg.
isVirtual() ?
TRI->lookThruCopyLike(FirstReg, MRI) : FirstReg;
204 SecondReg.
isVirtual() ?
TRI->lookThruCopyLike(SecondReg, MRI) : SecondReg;
205 if (FirstCmpReg != SecondCmpReg) {
214bool AArch64ConditionOptimizerImpl::nzcvLivesOut(MachineBasicBlock *
MBB) {
216 if (SuccBB->isLiveIn(AArch64::NZCV)) {
230 case AArch64::SUBSWri:
231 case AArch64::SUBSXri:
233 case AArch64::ADDSWri:
234 case AArch64::ADDSXri:
242 return Opc == AArch64::CSINCWr ||
Opc == AArch64::CSINCXr;
247AArch64ConditionOptimizerImpl::getBccTerminator(MachineBasicBlock *
MBB) {
255 if (
Term->getOpcode() != AArch64::Bcc) {
269AArch64ConditionOptimizerImpl::findAdjustableCmp(MachineInstr *CondMI) {
270 assert(CondMI &&
"CondMI cannot be null");
279 MachineInstr &
I = *It;
280 assert(!
I.isTerminator() &&
"Spurious terminator");
282 if (
I.readsRegister(AArch64::NZCV,
nullptr))
286 if (!canAdjustCmp(
I)) {
292 if (
I.modifiesRegister(AArch64::NZCV,
nullptr))
303 case AArch64::ADDSWri:
return AArch64::SUBSWri;
304 case AArch64::ADDSXri:
return AArch64::SUBSXri;
305 case AArch64::SUBSWri:
return AArch64::ADDSWri;
306 case AArch64::SUBSXri:
return AArch64::ADDSXri;
339AArch64ConditionOptimizerImpl::getAdjustedCmpInfo(MachineInstr *CmpMI,
348 bool Negative = (
Opc == AArch64::ADDSWri ||
Opc == AArch64::ADDSXri);
353 Correction = -Correction;
357 const int NewImm = std::abs(OldImm + Correction);
361 if (OldImm == 0 && Negative)
362 return {OldImm,
Opc,
Cmp};
364 if ((OldImm == 1 && Negative && Correction == -1) ||
365 (OldImm == 0 && Correction == -1)) {
370 return {OldImm,
Opc,
Cmp};
378void AArch64ConditionOptimizerImpl::updateCmpInstr(MachineInstr *CmpMI,
386void AArch64ConditionOptimizerImpl::updateCondInstr(MachineInstr *CondMI,
390 assert(CCOpIdx >= 0 &&
"Unsupported conditional instruction");
392 ++NumConditionsAdjusted;
396void AArch64ConditionOptimizerImpl::applyCmpAdjustment(CmpCondPair &Pair,
397 const CmpInfo &Info) {
398 updateCmpInstr(Pair.CmpMI,
Info.Imm,
Info.Opc);
399 updateCondInstr(Pair.CondMI,
Info.CC);
405 assert(!
Cond.empty() &&
"Expected non-empty condition from analyzeBranch");
408 assert(
Cond.size() == 1 &&
"Unknown Cond array format");
422bool AArch64ConditionOptimizerImpl::tryOptimizePair(CmpCondPair &
First,
423 CmpCondPair &Second) {
428 int FirstImmTrueValue =
First.getImm();
429 int SecondImmTrueValue = Second.getImm();
432 if (
First.getOpc() == AArch64::ADDSWri ||
First.getOpc() == AArch64::ADDSXri)
433 FirstImmTrueValue = -FirstImmTrueValue;
434 if (Second.getOpc() == AArch64::ADDSWri ||
435 Second.getOpc() == AArch64::ADDSXri)
436 SecondImmTrueValue = -SecondImmTrueValue;
438 CmpInfo FirstAdj = getAdjustedCmpInfo(
First.CmpMI,
First.CC);
439 CmpInfo SecondAdj = getAdjustedCmpInfo(Second.CmpMI, Second.CC);
443 std::abs(SecondImmTrueValue - FirstImmTrueValue) == 2) {
456 if (FirstAdj.Imm != SecondAdj.Imm || FirstAdj.Opc != SecondAdj.Opc)
461 <<
First.getImm() <<
", "
463 << Second.getImm() <<
" -> "
465 << FirstAdj.Imm <<
", "
467 << SecondAdj.Imm <<
'\n');
468 applyCmpAdjustment(
First, FirstAdj);
469 applyCmpAdjustment(Second, SecondAdj);
474 std::abs(SecondImmTrueValue - FirstImmTrueValue) == 1) {
487 bool AdjustFirst = (FirstImmTrueValue < SecondImmTrueValue);
489 AdjustFirst = !AdjustFirst;
491 CmpCondPair &
Target = AdjustFirst ? Second :
First;
492 CmpCondPair &ToChange = AdjustFirst ?
First : Second;
493 CmpInfo &Adj = AdjustFirst ? FirstAdj : SecondAdj;
497 if (Adj.Imm !=
Target.getImm() || Adj.Opc !=
Target.getOpc())
502 << ToChange.getImm() <<
" -> "
505 applyCmpAdjustment(ToChange, Adj);
531bool AArch64ConditionOptimizerImpl::optimizeIntraBlock(MachineBasicBlock &
MBB) {
532 MachineInstr *FirstCSINC =
nullptr;
533 MachineInstr *SecondCSINC =
nullptr;
536 for (MachineInstr &
MI :
MBB) {
540 }
else if (!SecondCSINC) {
547 if (!FirstCSINC || !SecondCSINC) {
552 if (nzcvLivesOut(&
MBB))
556 MachineInstr *FirstCmpMI = findAdjustableCmp(FirstCSINC);
557 MachineInstr *SecondCmpMI = findAdjustableCmp(SecondCSINC);
558 if (!FirstCmpMI || !SecondCmpMI)
562 if (FirstCmpMI == SecondCmpMI) {
563 LLVM_DEBUG(
dbgs() <<
"Both CSINCs already controlled by same CMP\n");
567 if (!registersMatch(FirstCmpMI, SecondCmpMI))
574 if (&*It != SecondCmpMI &&
575 It->modifiesRegister(AArch64::NZCV,
nullptr)) {
576 LLVM_DEBUG(
dbgs() <<
"Flags modified between CMPs by: " << *It <<
'\n');
584 if (It->readsRegister(AArch64::NZCV,
nullptr)) {
585 LLVM_DEBUG(
dbgs() <<
"Flags read after second CSINC by: " << *It <<
'\n');
602 CmpCondPair
First{FirstCmpMI, FirstCSINC, FirstCondCode};
603 CmpCondPair Second{SecondCmpMI, SecondCSINC, SecondCondCode};
605 return tryOptimizePair(
First, Second);
609bool AArch64ConditionOptimizerImpl::optimizeCrossBlock(MachineBasicBlock &HBB) {
611 MachineBasicBlock *
TBB =
nullptr, *FBB =
nullptr;
617 if (!
TBB ||
TBB == &HBB) {
622 MachineBasicBlock *TBB_TBB =
nullptr, *TBB_FBB =
nullptr;
627 MachineInstr *HeadBrMI = getBccTerminator(&HBB);
628 MachineInstr *TrueBrMI = getBccTerminator(
TBB);
629 if (!HeadBrMI || !TrueBrMI)
633 if (nzcvLivesOut(&HBB) || nzcvLivesOut(
TBB))
637 MachineInstr *HeadCmpMI = findAdjustableCmp(HeadBrMI);
638 MachineInstr *TrueCmpMI = findAdjustableCmp(TrueBrMI);
639 if (!HeadCmpMI || !TrueCmpMI)
642 if (!registersMatch(HeadCmpMI, TrueCmpMI))
647 if (HeadCondCode == AArch64CC::CondCode::Invalid ||
648 TrueCondCode == AArch64CC::CondCode::Invalid) {
658 CmpCondPair Head{HeadCmpMI, HeadBrMI, HeadCondCode};
659 CmpCondPair True{TrueCmpMI, TrueBrMI, TrueCondCode};
661 return tryOptimizePair(Head, True);
664bool AArch64ConditionOptimizerLegacy::runOnMachineFunction(
665 MachineFunction &MF) {
668 MachineDominatorTree &MDT =
669 getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
670 return AArch64ConditionOptimizerImpl().run(MF, MDT);
673bool AArch64ConditionOptimizerImpl::run(MachineFunction &MF,
674 MachineDominatorTree &MDT) {
675 LLVM_DEBUG(
dbgs() <<
"********** AArch64 Conditional Compares **********\n"
676 <<
"********** Function: " << MF.
getName() <<
'\n');
678 TII =
static_cast<const AArch64InstrInfo *
>(MF.
getSubtarget().getInstrInfo());
691 MachineBasicBlock *HBB =
I->getBlock();
692 Changed |= optimizeIntraBlock(*HBB);
693 Changed |= optimizeCrossBlock(*HBB);
703 bool Changed = AArch64ConditionOptimizerImpl().run(MF, MDT);
static AArch64CC::CondCode parseCondCode(ArrayRef< MachineOperand > Cond)
static int getComplementOpc(int Opc)
static bool isGreaterThan(AArch64CC::CondCode Cmp)
static AArch64CC::CondCode getAdjustedCmp(AArch64CC::CondCode Cmp)
static bool isCSINCInstruction(unsigned Opc)
static bool isLessThan(AArch64CC::CondCode Cmp)
static bool isCmpInstruction(unsigned Opc)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
const HexagonInstrInfo * TII
Register const TargetRegisterInfo * TRI
Promote Memory to Register
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
static int findCondCodeUseOperandIdxForBranchOrSelect(const MachineInstr &Instr)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Represents analyses that only rely on functions' control flow.
FunctionPass class - This class is used to implement most global optimizations.
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....
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
iterator_range< succ_iterator > successors()
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
const MachineOperand & getOperand(unsigned i) const
void setImm(int64_t immVal)
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
Register getReg() const
getReg - Returns the register number.
bool use_nodbg_empty(Register RegNo) const
use_nodbg_empty - Return true if there are no non-Debug instructions using the specified register.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static const char * getCondCodeName(CondCode Code)
static unsigned getShiftValue(unsigned Imm)
getShiftValue - Extract the shift value.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
FunctionPass * createAArch64ConditionOptimizerLegacyPass()
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
DomTreeNodeBase< MachineBasicBlock > MachineDomTreeNode
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
iterator_range< df_iterator< T > > depth_first(const T &G)
IterT prev_nodbg(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It, then continue decrementing it while it points to a debug instruction.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.