91#define DEBUG_TYPE "aarch64-condopt"
93STATISTIC(NumConditionsAdjusted,
"Number of conditions adjusted");
104class AArch64ConditionOptimizerImpl {
109 MachineInstr *CondMI;
113 unsigned getOpc()
const {
return CmpMI->getOpcode(); }
116 const AArch64InstrInfo *TII;
117 const TargetRegisterInfo *TRI;
118 MachineDominatorTree *DomTree;
119 const MachineRegisterInfo *MRI;
122 bool run(MachineFunction &MF, MachineDominatorTree &MDT);
125 bool canAdjustCmp(MachineInstr &CmpMI);
126 bool registersMatch(MachineInstr *FirstMI, MachineInstr *SecondMI);
127 bool nzcvLivesOut(MachineBasicBlock *
MBB);
128 MachineInstr *getBccTerminator(MachineBasicBlock *
MBB);
129 MachineInstr *findAdjustableCmp(MachineInstr *CondMI);
131 void updateCmpInstr(MachineInstr *CmpMI,
int NewImm,
unsigned NewOpc);
133 void applyCmpAdjustment(CmpCondPair &Pair,
const CmpInfo &Info);
134 bool commitPendingPair(std::optional<CmpCondPair> &PendingPair,
135 SmallDenseMap<Register, CmpCondPair> &PairsByReg);
136 bool tryOptimizePair(CmpCondPair &
First, CmpCondPair &Second);
137 bool optimizeIntraBlock(MachineBasicBlock &
MBB);
138 bool optimizeCrossBlock(MachineBasicBlock &HBB);
144 AArch64ConditionOptimizerLegacy() : MachineFunctionPass(ID) {}
146 void getAnalysisUsage(AnalysisUsage &AU)
const override;
147 bool runOnMachineFunction(MachineFunction &MF)
override;
149 StringRef getPassName()
const override {
150 return "AArch64 Condition Optimizer";
156char AArch64ConditionOptimizerLegacy::ID = 0;
159 "AArch64 CondOpt Pass",
false,
false)
165 return new AArch64ConditionOptimizerLegacy();
168void AArch64ConditionOptimizerLegacy::getAnalysisUsage(
177bool AArch64ConditionOptimizerImpl::canAdjustCmp(MachineInstr &CmpMI) {
180 LLVM_DEBUG(
dbgs() <<
"Immediate of cmp is symbolic, " << CmpMI <<
'\n');
183 LLVM_DEBUG(
dbgs() <<
"Immediate of cmp may be out of range, " << CmpMI
187 LLVM_DEBUG(
dbgs() <<
"Destination of cmp is not dead, " << CmpMI <<
'\n');
195bool AArch64ConditionOptimizerImpl::registersMatch(MachineInstr *FirstMI,
196 MachineInstr *SecondMI) {
200 FirstReg.
isVirtual() ?
TRI->lookThruCopyLike(FirstReg, MRI) : FirstReg;
202 SecondReg.
isVirtual() ?
TRI->lookThruCopyLike(SecondReg, MRI) : SecondReg;
203 if (FirstCmpReg != SecondCmpReg) {
212bool AArch64ConditionOptimizerImpl::nzcvLivesOut(MachineBasicBlock *
MBB) {
214 if (SuccBB->isLiveIn(AArch64::NZCV)) {
228 case AArch64::SUBSWri:
229 case AArch64::SUBSXri:
231 case AArch64::ADDSWri:
232 case AArch64::ADDSXri:
241AArch64ConditionOptimizerImpl::getBccTerminator(MachineBasicBlock *
MBB) {
249 if (
Term->getOpcode() != AArch64::Bcc) {
263AArch64ConditionOptimizerImpl::findAdjustableCmp(MachineInstr *CondMI) {
264 assert(CondMI &&
"CondMI cannot be null");
273 MachineInstr &
I = *It;
274 assert(!
I.isTerminator() &&
"Spurious terminator");
276 if (
I.readsRegister(AArch64::NZCV,
nullptr))
280 if (!canAdjustCmp(
I)) {
286 if (
I.modifiesRegister(AArch64::NZCV,
nullptr))
297 case AArch64::ADDSWri:
return AArch64::SUBSWri;
298 case AArch64::ADDSXri:
return AArch64::SUBSXri;
299 case AArch64::SUBSWri:
return AArch64::ADDSWri;
300 case AArch64::SUBSXri:
return AArch64::ADDSXri;
333AArch64ConditionOptimizerImpl::getAdjustedCmpInfo(MachineInstr *CmpMI,
342 bool Negative = (
Opc == AArch64::ADDSWri ||
Opc == AArch64::ADDSXri);
347 Correction = -Correction;
351 const int NewImm = std::abs(OldImm + Correction);
355 if (OldImm == 0 && Negative)
356 return {OldImm,
Opc,
Cmp};
358 if ((OldImm == 1 && Negative && Correction == -1) ||
359 (OldImm == 0 && Correction == -1)) {
364 return {OldImm,
Opc,
Cmp};
372void AArch64ConditionOptimizerImpl::updateCmpInstr(MachineInstr *CmpMI,
380void AArch64ConditionOptimizerImpl::updateCondInstr(MachineInstr *CondMI,
383 AArch64InstrInfo::findCondCodeUseOperandIdxForBranchOrSelect(*CondMI);
384 assert(CCOpIdx >= 0 &&
"Unsupported conditional instruction");
386 ++NumConditionsAdjusted;
390void AArch64ConditionOptimizerImpl::applyCmpAdjustment(CmpCondPair &Pair,
391 const CmpInfo &Info) {
392 updateCmpInstr(Pair.CmpMI,
Info.Imm,
Info.Opc);
393 updateCondInstr(Pair.CondMI,
Info.CC);
400 assert(!
Cond.empty() &&
"Expected non-empty condition from analyzeBranch");
403 assert(
Cond.size() == 1 &&
"Unknown Cond array format");
417bool AArch64ConditionOptimizerImpl::tryOptimizePair(CmpCondPair &
First,
418 CmpCondPair &Second) {
423 int FirstImmTrueValue =
First.getImm();
424 int SecondImmTrueValue = Second.getImm();
427 if (
First.getOpc() == AArch64::ADDSWri ||
First.getOpc() == AArch64::ADDSXri)
428 FirstImmTrueValue = -FirstImmTrueValue;
429 if (Second.getOpc() == AArch64::ADDSWri ||
430 Second.getOpc() == AArch64::ADDSXri)
431 SecondImmTrueValue = -SecondImmTrueValue;
433 CmpInfo FirstAdj = getAdjustedCmpInfo(
First.CmpMI,
First.CC);
434 CmpInfo SecondAdj = getAdjustedCmpInfo(Second.CmpMI, Second.CC);
438 std::abs(SecondImmTrueValue - FirstImmTrueValue) == 2) {
451 if (FirstAdj.Imm != SecondAdj.Imm || FirstAdj.Opc != SecondAdj.Opc)
456 <<
First.getImm() <<
", "
458 << Second.getImm() <<
" -> "
460 << FirstAdj.Imm <<
", "
462 << SecondAdj.Imm <<
'\n');
463 applyCmpAdjustment(
First, FirstAdj);
464 applyCmpAdjustment(Second, SecondAdj);
469 std::abs(SecondImmTrueValue - FirstImmTrueValue) == 1) {
482 bool AdjustFirst = (FirstImmTrueValue < SecondImmTrueValue);
484 AdjustFirst = !AdjustFirst;
486 CmpCondPair &
Target = AdjustFirst ? Second :
First;
487 CmpCondPair &ToChange = AdjustFirst ?
First : Second;
488 CmpInfo &Adj = AdjustFirst ? FirstAdj : SecondAdj;
492 if (Adj.Imm !=
Target.getImm() || Adj.Opc !=
Target.getOpc())
497 << ToChange.getImm() <<
" -> "
500 applyCmpAdjustment(ToChange, Adj);
509bool AArch64ConditionOptimizerImpl::commitPendingPair(
510 std::optional<CmpCondPair> &PendingPair,
511 SmallDenseMap<Register, CmpCondPair> &PairsByReg) {
515 Register Reg = PendingPair->CmpMI->getOperand(1).getReg();
518 auto MatchingPair = PairsByReg.
find(
Key);
519 bool Changed = MatchingPair != PairsByReg.
end() &&
520 tryOptimizePair(MatchingPair->second, *PendingPair);
522 PairsByReg[
Key] = *PendingPair;
523 PendingPair = std::nullopt;
547bool AArch64ConditionOptimizerImpl::optimizeIntraBlock(MachineBasicBlock &
MBB) {
548 SmallDenseMap<Register, CmpCondPair> PairsByReg;
549 std::optional<CmpCondPair> PendingPair;
550 MachineInstr *ActiveCmp =
nullptr;
553 for (MachineInstr &
MI :
MBB) {
554 if (
MI.isDebugInstr())
558 Changed |= commitPendingPair(PendingPair, PairsByReg);
563 if (
MI.modifiesRegister(AArch64::NZCV,
nullptr)) {
566 Changed |= commitPendingPair(PendingPair, PairsByReg);
572 if (AArch64InstrInfo::findCondCodeUseOperandIdxForBranchOrSelect(
MI) >= 0 &&
578 PendingPair = std::nullopt;
580 }
else if (ActiveCmp) {
582 AArch64InstrInfo::findCondCodeUseOperandIdxForBranchOrSelect(
MI);
583 assert(CCOpIdx >= 0 &&
"Unsupported conditional instruction");
586 PendingPair = CmpCondPair{ActiveCmp, &
MI, CC};
591 if (
MI.readsRegister(AArch64::NZCV,
nullptr)) {
593 PendingPair = std::nullopt;
600 if (!nzcvLivesOut(&
MBB))
601 Changed |= commitPendingPair(PendingPair, PairsByReg);
607bool AArch64ConditionOptimizerImpl::optimizeCrossBlock(MachineBasicBlock &HBB) {
609 MachineBasicBlock *
TBB =
nullptr, *FBB =
nullptr;
615 if (!
TBB ||
TBB == &HBB) {
620 MachineBasicBlock *TBB_TBB =
nullptr, *TBB_FBB =
nullptr;
625 MachineInstr *HeadBrMI = getBccTerminator(&HBB);
626 MachineInstr *TrueBrMI = getBccTerminator(
TBB);
627 if (!HeadBrMI || !TrueBrMI)
631 if (nzcvLivesOut(&HBB) || nzcvLivesOut(
TBB))
635 MachineInstr *HeadCmpMI = findAdjustableCmp(HeadBrMI);
636 MachineInstr *TrueCmpMI = findAdjustableCmp(TrueBrMI);
637 if (!HeadCmpMI || !TrueCmpMI)
640 if (!registersMatch(HeadCmpMI, TrueCmpMI))
645 if (HeadCondCode == AArch64CC::CondCode::Invalid ||
646 TrueCondCode == AArch64CC::CondCode::Invalid) {
656 CmpCondPair Head{HeadCmpMI, HeadBrMI, HeadCondCode};
657 CmpCondPair True{TrueCmpMI, TrueBrMI, TrueCondCode};
659 return tryOptimizePair(Head, True);
662bool AArch64ConditionOptimizerLegacy::runOnMachineFunction(
663 MachineFunction &MF) {
666 MachineDominatorTree &MDT =
667 getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
668 return AArch64ConditionOptimizerImpl().run(MF, MDT);
671bool AArch64ConditionOptimizerImpl::run(MachineFunction &MF,
672 MachineDominatorTree &MDT) {
673 LLVM_DEBUG(
dbgs() <<
"********** AArch64 Conditional Compares **********\n"
674 <<
"********** Function: " << MF.
getName() <<
'\n');
676 TII =
static_cast<const AArch64InstrInfo *
>(MF.
getSubtarget().getInstrInfo());
689 MachineBasicBlock *HBB =
I->getBlock();
690 Changed |= optimizeIntraBlock(*HBB);
691 Changed |= optimizeCrossBlock(*HBB);
701 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 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)
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.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Represents analyses that only rely on functions' control flow.
iterator find(const_arg_type_t< KeyT > Val)
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.
DXILDebugInfoMap run(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
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ 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.