96#define DEBUG_TYPE "aarch64-condopt"
98STATISTIC(NumConditionsAdjusted,
"Number of conditions adjusted");
111 using CmpInfo = std::tuple<int, unsigned, AArch64CC::CondCode>;
117 void getAnalysisUsage(AnalysisUsage &AU)
const override;
118 bool canAdjustCmp(MachineInstr &CmpMI);
119 bool registersMatch(MachineInstr *FirstMI, MachineInstr *SecondMI);
120 bool nzcvLivesOut(MachineBasicBlock *
MBB);
121 MachineInstr *findSuitableCompare(MachineBasicBlock *
MBB);
123 void modifyCmp(MachineInstr *CmpMI,
const CmpInfo &Info);
126 bool isPureCmp(MachineInstr &CmpMI);
127 bool optimizeIntraBlock(MachineBasicBlock &
MBB);
128 bool optimizeCrossBlock(MachineBasicBlock &HBB);
129 bool runOnMachineFunction(MachineFunction &MF)
override;
131 StringRef getPassName()
const override {
132 return "AArch64 Condition Optimizer";
138char AArch64ConditionOptimizer::ID = 0;
141 "AArch64 CondOpt Pass",
false,
false)
147 return new AArch64ConditionOptimizer();
150void AArch64ConditionOptimizer::getAnalysisUsage(
AnalysisUsage &AU)
const {
158bool AArch64ConditionOptimizer::canAdjustCmp(MachineInstr &CmpMI) {
161 LLVM_DEBUG(
dbgs() <<
"Immediate of cmp is symbolic, " << CmpMI <<
'\n');
164 LLVM_DEBUG(
dbgs() <<
"Immediate of cmp may be out of range, " << CmpMI
168 LLVM_DEBUG(
dbgs() <<
"Destination of cmp is not dead, " << CmpMI <<
'\n');
176bool AArch64ConditionOptimizer::registersMatch(MachineInstr *FirstMI,
177 MachineInstr *SecondMI) {
181 FirstReg.
isVirtual() ?
TRI->lookThruCopyLike(FirstReg,
MRI) : FirstReg;
183 SecondReg.
isVirtual() ?
TRI->lookThruCopyLike(SecondReg,
MRI) : SecondReg;
184 if (FirstCmpReg != SecondCmpReg) {
193bool AArch64ConditionOptimizer::nzcvLivesOut(MachineBasicBlock *
MBB) {
195 if (SuccBB->isLiveIn(AArch64::NZCV)) {
209 case AArch64::SUBSWri:
210 case AArch64::SUBSXri:
212 case AArch64::ADDSWri:
213 case AArch64::ADDSXri:
221 return Opc == AArch64::CSINCWr ||
Opc == AArch64::CSINCXr;
227MachineInstr *AArch64ConditionOptimizer::findSuitableCompare(
228 MachineBasicBlock *
MBB) {
233 if (
Term->getOpcode() != AArch64::Bcc)
237 if (nzcvLivesOut(
MBB))
243 MachineInstr &
I = *It;
244 assert(!
I.isTerminator() &&
"Spurious terminator");
246 if (
I.readsRegister(AArch64::NZCV,
nullptr))
250 if (!canAdjustCmp(
I)) {
256 if (
I.modifiesRegister(AArch64::NZCV,
nullptr))
267 case AArch64::ADDSWri:
return AArch64::SUBSWri;
268 case AArch64::ADDSXri:
return AArch64::SUBSXri;
269 case AArch64::SUBSWri:
return AArch64::ADDSWri;
270 case AArch64::SUBSXri:
return AArch64::ADDSXri;
290AArch64ConditionOptimizer::CmpInfo AArch64ConditionOptimizer::adjustCmp(
296 bool Negative = (
Opc == AArch64::ADDSWri ||
Opc == AArch64::ADDSXri);
301 Correction = -Correction;
305 const int NewImm = std::abs(OldImm + Correction);
309 if (OldImm == 0 && ((Negative && Correction == 1) ||
310 (!Negative && Correction == -1))) {
318void AArch64ConditionOptimizer::modifyCmp(MachineInstr *CmpMI,
319 const CmpInfo &Info) {
323 std::tie(Imm,
Opc, Cmp) =
Info;
345 ++NumConditionsAdjusted;
354 assert(
Cond.size() == 1 &&
"Unknown Cond array format");
364bool AArch64ConditionOptimizer::adjustTo(MachineInstr *CmpMI,
367 CmpInfo
Info = adjustCmp(CmpMI, Cmp);
368 if (std::get<0>(Info) == ToImm && std::get<1>(Info) == To->
getOpcode()) {
369 modifyCmp(CmpMI, Info);
375bool AArch64ConditionOptimizer::isPureCmp(MachineInstr &CmpMI) {
378 LLVM_DEBUG(
dbgs() <<
"Immediate of cmp is symbolic, " << CmpMI <<
'\n');
381 LLVM_DEBUG(
dbgs() <<
"Immediate of cmp may be out of range, " << CmpMI
385 LLVM_DEBUG(
dbgs() <<
"Destination of cmp is not dead, " << CmpMI <<
'\n');
409bool AArch64ConditionOptimizer::optimizeIntraBlock(MachineBasicBlock &
MBB) {
410 MachineInstr *FirstCmp =
nullptr;
411 MachineInstr *FirstCSINC =
nullptr;
412 MachineInstr *SecondCmp =
nullptr;
413 MachineInstr *SecondCSINC =
nullptr;
416 for (MachineInstr &
MI :
MBB) {
420 }
else if (FirstCSINC && !SecondCmp) {
428 if (FirstCmp && !FirstCSINC) {
430 }
else if (SecondCmp && !SecondCSINC) {
439 if (!SecondCmp || !SecondCSINC) {
445 if (nzcvLivesOut(&
MBB))
448 if (!registersMatch(FirstCmp, SecondCmp))
451 if (!isPureCmp(*FirstCmp) || !isPureCmp(*SecondCmp)) {
460 if (&*It != SecondCmp &&
461 It->modifiesRegister(AArch64::NZCV,
nullptr)) {
462 LLVM_DEBUG(
dbgs() <<
"Flags modified between CMPs by: " << *It <<
'\n');
470 if (It->readsRegister(AArch64::NZCV,
nullptr)) {
471 LLVM_DEBUG(
dbgs() <<
"Flags read after second CSINC by: " << *It <<
'\n');
488 << SecondImm <<
'\n');
493 std::abs(SecondImm - FirstImm) == 1) {
497 bool adjustFirst = (FirstImm < SecondImm);
499 adjustFirst = !adjustFirst;
502 MachineInstr *CmpToAdjust = adjustFirst ? FirstCmp : SecondCmp;
503 MachineInstr *CSINCToAdjust = adjustFirst ? FirstCSINC : SecondCSINC;
505 int TargetImm = adjustFirst ? SecondImm : FirstImm;
507 CmpInfo AdjustedInfo = adjustCmp(CmpToAdjust, CondToAdjust);
509 if (std::get<0>(AdjustedInfo) == TargetImm &&
510 std::get<1>(AdjustedInfo) ==
511 (adjustFirst ? SecondCmp : FirstCmp)->
getOpcode()) {
512 LLVM_DEBUG(
dbgs() <<
"Successfully optimizing intra-block CSINC pair\n");
516 CmpToAdjust->
setDesc(
TII->get(std::get<1>(AdjustedInfo)));
527bool AArch64ConditionOptimizer::optimizeCrossBlock(MachineBasicBlock &HBB) {
529 MachineBasicBlock *
TBB =
nullptr, *FBB =
nullptr;
535 if (!
TBB ||
TBB == &HBB) {
540 MachineBasicBlock *TBB_TBB =
nullptr, *TBB_FBB =
nullptr;
545 MachineInstr *HeadCmpMI = findSuitableCompare(&HBB);
550 MachineInstr *TrueCmpMI = findSuitableCompare(
TBB);
555 if (!registersMatch(HeadCmpMI, TrueCmpMI)) {
584 std::abs(TrueImm - HeadImm) == 2) {
595 CmpInfo HeadCmpInfo = adjustCmp(HeadCmpMI, HeadCmp);
596 CmpInfo TrueCmpInfo = adjustCmp(TrueCmpMI, TrueCmp);
597 if (std::get<0>(HeadCmpInfo) == std::get<0>(TrueCmpInfo) &&
598 std::get<1>(HeadCmpInfo) == std::get<1>(TrueCmpInfo)) {
599 modifyCmp(HeadCmpMI, HeadCmpInfo);
600 modifyCmp(TrueCmpMI, TrueCmpInfo);
605 std::abs(TrueImm - HeadImm) == 1) {
618 bool adjustHeadCond = (HeadImm < TrueImm);
620 adjustHeadCond = !adjustHeadCond;
623 if (adjustHeadCond) {
624 return adjustTo(HeadCmpMI, HeadCmp, TrueCmpMI, TrueImm);
626 return adjustTo(TrueCmpMI, TrueCmp, HeadCmpMI, HeadImm);
635bool AArch64ConditionOptimizer::runOnMachineFunction(MachineFunction &MF) {
636 LLVM_DEBUG(
dbgs() <<
"********** AArch64 Conditional Compares **********\n"
637 <<
"********** Function: " << MF.
getName() <<
'\n');
643 DomTree = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
654 MachineBasicBlock *HBB =
I->getBlock();
655 Changed |= optimizeIntraBlock(*HBB);
656 Changed |= optimizeCrossBlock(*HBB);
unsigned const MachineRegisterInfo * MRI
static int getComplementOpc(int Opc)
static AArch64CC::CondCode getAdjustedCmp(AArch64CC::CondCode Cmp)
static bool isCSINCInstruction(unsigned Opc)
static bool isCmpInstruction(unsigned Opc)
static bool parseCond(ArrayRef< MachineOperand > Cond, AArch64CC::CondCode &CC)
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)
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
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),...
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.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
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.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
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 DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
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.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
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.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
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.
FunctionPass * createAArch64ConditionOptimizerPass()
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
DomTreeNodeBase< MachineBasicBlock > MachineDomTreeNode
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.