1 //===-- SystemZElimCompare.cpp - Eliminate comparison instructions --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 // (1) tries to remove compares if CC already contains the required information
12 // (2) fuses compares and branches into COMPARE AND BRANCH instructions
14 //===----------------------------------------------------------------------===//
16 #include "SystemZTargetMachine.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetRegisterInfo.h"
29 #define DEBUG_TYPE "systemz-elim-compare"
31 STATISTIC(BranchOnCounts, "Number of branch-on-count instructions");
32 STATISTIC(EliminatedComparisons, "Number of eliminated comparisons");
33 STATISTIC(FusedComparisons, "Number of fused compare-and-branch instructions");
36 // Represents the references to a particular register in one or more
40 : Def(false), Use(false), IndirectDef(false), IndirectUse(false) {}
42 Reference &operator|=(const Reference &Other) {
44 IndirectDef |= Other.IndirectDef;
46 IndirectUse |= Other.IndirectUse;
50 explicit operator bool() const { return Def || Use; }
52 // True if the register is defined or used in some form, either directly or
53 // via a sub- or super-register.
57 // True if the register is defined or used indirectly, by a sub- or
63 class SystemZElimCompare : public MachineFunctionPass {
66 SystemZElimCompare(const SystemZTargetMachine &tm)
67 : MachineFunctionPass(ID), TII(nullptr), TRI(nullptr) {}
69 const char *getPassName() const override {
70 return "SystemZ Comparison Elimination";
73 bool processBlock(MachineBasicBlock &MBB);
74 bool runOnMachineFunction(MachineFunction &F) override;
77 Reference getRegReferences(MachineInstr *MI, unsigned Reg);
78 bool convertToBRCT(MachineInstr *MI, MachineInstr *Compare,
79 SmallVectorImpl<MachineInstr *> &CCUsers);
80 bool convertToLoadAndTest(MachineInstr *MI);
81 bool adjustCCMasksForInstr(MachineInstr *MI, MachineInstr *Compare,
82 SmallVectorImpl<MachineInstr *> &CCUsers);
83 bool optimizeCompareZero(MachineInstr *Compare,
84 SmallVectorImpl<MachineInstr *> &CCUsers);
85 bool fuseCompareAndBranch(MachineInstr *Compare,
86 SmallVectorImpl<MachineInstr *> &CCUsers);
88 const SystemZInstrInfo *TII;
89 const TargetRegisterInfo *TRI;
92 char SystemZElimCompare::ID = 0;
93 } // end anonymous namespace
95 FunctionPass *llvm::createSystemZElimComparePass(SystemZTargetMachine &TM) {
96 return new SystemZElimCompare(TM);
99 // Return true if CC is live out of MBB.
100 static bool isCCLiveOut(MachineBasicBlock &MBB) {
101 for (auto SI = MBB.succ_begin(), SE = MBB.succ_end(); SI != SE; ++SI)
102 if ((*SI)->isLiveIn(SystemZ::CC))
107 // Return true if any CC result of MI would reflect the value of Reg.
108 static bool resultTests(MachineInstr *MI, unsigned Reg) {
109 if (MI->getNumOperands() > 0 &&
110 MI->getOperand(0).isReg() &&
111 MI->getOperand(0).isDef() &&
112 MI->getOperand(0).getReg() == Reg)
115 switch (MI->getOpcode()) {
128 if (MI->getOperand(1).getReg() == Reg)
135 // Describe the references to Reg in MI, including sub- and super-registers.
136 Reference SystemZElimCompare::getRegReferences(MachineInstr *MI, unsigned Reg) {
138 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
139 const MachineOperand &MO = MI->getOperand(I);
141 if (unsigned MOReg = MO.getReg()) {
142 if (MOReg == Reg || TRI->regsOverlap(MOReg, Reg)) {
145 Ref.IndirectUse |= (MOReg != Reg);
149 Ref.IndirectDef |= (MOReg != Reg);
158 // Return true if this is a load and test which can be optimized the
159 // same way as compare instruction.
160 static bool isLoadAndTestAsCmp(MachineInstr *MI) {
161 // If we during isel used a load-and-test as a compare with 0, the
162 // def operand is dead.
163 return ((MI->getOpcode() == SystemZ::LTEBR ||
164 MI->getOpcode() == SystemZ::LTDBR ||
165 MI->getOpcode() == SystemZ::LTXBR) &&
166 MI->getOperand(0).isDead());
169 // Return the source register of Compare, which is the unknown value
171 static unsigned getCompareSourceReg(MachineInstr *Compare) {
173 if (Compare->isCompare())
174 reg = Compare->getOperand(0).getReg();
175 else if (isLoadAndTestAsCmp(Compare))
176 reg = Compare->getOperand(1).getReg();
182 // Compare compares the result of MI against zero. If MI is an addition
183 // of -1 and if CCUsers is a single branch on nonzero, eliminate the addition
184 // and convert the branch to a BRCT(G). Return true on success.
186 SystemZElimCompare::convertToBRCT(MachineInstr *MI, MachineInstr *Compare,
187 SmallVectorImpl<MachineInstr *> &CCUsers) {
188 // Check whether we have an addition of -1.
189 unsigned Opcode = MI->getOpcode();
191 if (Opcode == SystemZ::AHI)
192 BRCT = SystemZ::BRCT;
193 else if (Opcode == SystemZ::AGHI)
194 BRCT = SystemZ::BRCTG;
197 if (MI->getOperand(2).getImm() != -1)
200 // Check whether we have a single JLH.
201 if (CCUsers.size() != 1)
203 MachineInstr *Branch = CCUsers[0];
204 if (Branch->getOpcode() != SystemZ::BRC ||
205 Branch->getOperand(0).getImm() != SystemZ::CCMASK_ICMP ||
206 Branch->getOperand(1).getImm() != SystemZ::CCMASK_CMP_NE)
209 // We already know that there are no references to the register between
210 // MI and Compare. Make sure that there are also no references between
211 // Compare and Branch.
212 unsigned SrcReg = getCompareSourceReg(Compare);
213 MachineBasicBlock::iterator MBBI = Compare, MBBE = Branch;
214 for (++MBBI; MBBI != MBBE; ++MBBI)
215 if (getRegReferences(MBBI, SrcReg))
218 // The transformation is OK. Rebuild Branch as a BRCT(G).
219 MachineOperand Target(Branch->getOperand(2));
220 Branch->RemoveOperand(2);
221 Branch->RemoveOperand(1);
222 Branch->RemoveOperand(0);
223 Branch->setDesc(TII->get(BRCT));
224 MachineInstrBuilder(*Branch->getParent()->getParent(), Branch)
225 .addOperand(MI->getOperand(0))
226 .addOperand(MI->getOperand(1))
228 .addReg(SystemZ::CC, RegState::ImplicitDefine);
229 MI->eraseFromParent();
233 // If MI is a load instruction, try to convert it into a LOAD AND TEST.
234 // Return true on success.
235 bool SystemZElimCompare::convertToLoadAndTest(MachineInstr *MI) {
236 unsigned Opcode = TII->getLoadAndTest(MI->getOpcode());
240 MI->setDesc(TII->get(Opcode));
241 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
242 .addReg(SystemZ::CC, RegState::ImplicitDefine);
246 // The CC users in CCUsers are testing the result of a comparison of some
247 // value X against zero and we know that any CC value produced by MI
248 // would also reflect the value of X. Try to adjust CCUsers so that
249 // they test the result of MI directly, returning true on success.
250 // Leave everything unchanged on failure.
251 bool SystemZElimCompare::
252 adjustCCMasksForInstr(MachineInstr *MI, MachineInstr *Compare,
253 SmallVectorImpl<MachineInstr *> &CCUsers) {
254 int Opcode = MI->getOpcode();
255 const MCInstrDesc &Desc = TII->get(Opcode);
256 unsigned MIFlags = Desc.TSFlags;
258 // See which compare-style condition codes are available.
259 unsigned ReusableCCMask = SystemZII::getCompareZeroCCMask(MIFlags);
261 // For unsigned comparisons with zero, only equality makes sense.
262 unsigned CompareFlags = Compare->getDesc().TSFlags;
263 if (CompareFlags & SystemZII::IsLogical)
264 ReusableCCMask &= SystemZ::CCMASK_CMP_EQ;
266 if (ReusableCCMask == 0)
269 unsigned CCValues = SystemZII::getCCValues(MIFlags);
270 assert((ReusableCCMask & ~CCValues) == 0 && "Invalid CCValues");
272 // Now check whether these flags are enough for all users.
273 SmallVector<MachineOperand *, 4> AlterMasks;
274 for (unsigned int I = 0, E = CCUsers.size(); I != E; ++I) {
275 MachineInstr *MI = CCUsers[I];
277 // Fail if this isn't a use of CC that we understand.
278 unsigned Flags = MI->getDesc().TSFlags;
280 if (Flags & SystemZII::CCMaskFirst)
282 else if (Flags & SystemZII::CCMaskLast)
283 FirstOpNum = MI->getNumExplicitOperands() - 2;
287 // Check whether the instruction predicate treats all CC values
288 // outside of ReusableCCMask in the same way. In that case it
289 // doesn't matter what those CC values mean.
290 unsigned CCValid = MI->getOperand(FirstOpNum).getImm();
291 unsigned CCMask = MI->getOperand(FirstOpNum + 1).getImm();
292 unsigned OutValid = ~ReusableCCMask & CCValid;
293 unsigned OutMask = ~ReusableCCMask & CCMask;
294 if (OutMask != 0 && OutMask != OutValid)
297 AlterMasks.push_back(&MI->getOperand(FirstOpNum));
298 AlterMasks.push_back(&MI->getOperand(FirstOpNum + 1));
301 // All users are OK. Adjust the masks for MI.
302 for (unsigned I = 0, E = AlterMasks.size(); I != E; I += 2) {
303 AlterMasks[I]->setImm(CCValues);
304 unsigned CCMask = AlterMasks[I + 1]->getImm();
305 if (CCMask & ~ReusableCCMask)
306 AlterMasks[I + 1]->setImm((CCMask & ReusableCCMask) |
307 (CCValues & ~ReusableCCMask));
310 // CC is now live after MI.
311 int CCDef = MI->findRegisterDefOperandIdx(SystemZ::CC, false, true, TRI);
312 assert(CCDef >= 0 && "Couldn't find CC set");
313 MI->getOperand(CCDef).setIsDead(false);
315 // Clear any intervening kills of CC.
316 MachineBasicBlock::iterator MBBI = MI, MBBE = Compare;
317 for (++MBBI; MBBI != MBBE; ++MBBI)
318 MBBI->clearRegisterKills(SystemZ::CC, TRI);
323 // Return true if Compare is a comparison against zero.
324 static bool isCompareZero(MachineInstr *Compare) {
325 switch (Compare->getOpcode()) {
326 case SystemZ::LTEBRCompare:
327 case SystemZ::LTDBRCompare:
328 case SystemZ::LTXBRCompare:
333 if (isLoadAndTestAsCmp(Compare))
336 return (Compare->getNumExplicitOperands() == 2 &&
337 Compare->getOperand(1).isImm() &&
338 Compare->getOperand(1).getImm() == 0);
342 // Try to optimize cases where comparison instruction Compare is testing
343 // a value against zero. Return true on success and if Compare should be
344 // deleted as dead. CCUsers is the list of instructions that use the CC
345 // value produced by Compare.
346 bool SystemZElimCompare::
347 optimizeCompareZero(MachineInstr *Compare,
348 SmallVectorImpl<MachineInstr *> &CCUsers) {
349 if (!isCompareZero(Compare))
352 // Search back for CC results that are based on the first operand.
353 unsigned SrcReg = getCompareSourceReg(Compare);
354 MachineBasicBlock &MBB = *Compare->getParent();
355 MachineBasicBlock::iterator MBBI = Compare, MBBE = MBB.begin();
358 while (MBBI != MBBE) {
360 MachineInstr *MI = MBBI;
361 if (resultTests(MI, SrcReg)) {
362 // Try to remove both MI and Compare by converting a branch to BRCT(G).
363 // We don't care in this case whether CC is modified between MI and
365 if (!CCRefs.Use && !SrcRefs && convertToBRCT(MI, Compare, CCUsers)) {
369 // Try to eliminate Compare by reusing a CC result from MI.
370 if ((!CCRefs && convertToLoadAndTest(MI)) ||
371 (!CCRefs.Def && adjustCCMasksForInstr(MI, Compare, CCUsers))) {
372 EliminatedComparisons += 1;
376 SrcRefs |= getRegReferences(MI, SrcReg);
379 CCRefs |= getRegReferences(MI, SystemZ::CC);
380 if (CCRefs.Use && CCRefs.Def)
386 // Try to fuse comparison instruction Compare into a later branch.
387 // Return true on success and if Compare is therefore redundant.
388 bool SystemZElimCompare::
389 fuseCompareAndBranch(MachineInstr *Compare,
390 SmallVectorImpl<MachineInstr *> &CCUsers) {
391 // See whether we have a comparison that can be fused.
392 unsigned FusedOpcode = TII->getCompareAndBranch(Compare->getOpcode(),
397 // See whether we have a single branch with which to fuse.
398 if (CCUsers.size() != 1)
400 MachineInstr *Branch = CCUsers[0];
401 if (Branch->getOpcode() != SystemZ::BRC)
404 // Make sure that the operands are available at the branch.
405 unsigned SrcReg = Compare->getOperand(0).getReg();
406 unsigned SrcReg2 = (Compare->getOperand(1).isReg() ?
407 Compare->getOperand(1).getReg() : 0);
408 MachineBasicBlock::iterator MBBI = Compare, MBBE = Branch;
409 for (++MBBI; MBBI != MBBE; ++MBBI)
410 if (MBBI->modifiesRegister(SrcReg, TRI) ||
411 (SrcReg2 && MBBI->modifiesRegister(SrcReg2, TRI)))
414 // Read the branch mask and target.
415 MachineOperand CCMask(MBBI->getOperand(1));
416 MachineOperand Target(MBBI->getOperand(2));
417 assert((CCMask.getImm() & ~SystemZ::CCMASK_ICMP) == 0 &&
418 "Invalid condition-code mask for integer comparison");
420 // Clear out all current operands.
421 int CCUse = MBBI->findRegisterUseOperandIdx(SystemZ::CC, false, TRI);
422 assert(CCUse >= 0 && "BRC must use CC");
423 Branch->RemoveOperand(CCUse);
424 Branch->RemoveOperand(2);
425 Branch->RemoveOperand(1);
426 Branch->RemoveOperand(0);
428 // Rebuild Branch as a fused compare and branch.
429 Branch->setDesc(TII->get(FusedOpcode));
430 MachineInstrBuilder(*Branch->getParent()->getParent(), Branch)
431 .addOperand(Compare->getOperand(0))
432 .addOperand(Compare->getOperand(1))
435 .addReg(SystemZ::CC, RegState::ImplicitDefine);
437 // Clear any intervening kills of SrcReg and SrcReg2.
439 for (++MBBI; MBBI != MBBE; ++MBBI) {
440 MBBI->clearRegisterKills(SrcReg, TRI);
442 MBBI->clearRegisterKills(SrcReg2, TRI);
444 FusedComparisons += 1;
448 // Process all comparison instructions in MBB. Return true if something
450 bool SystemZElimCompare::processBlock(MachineBasicBlock &MBB) {
451 bool Changed = false;
453 // Walk backwards through the block looking for comparisons, recording
454 // all CC users as we go. The subroutines can delete Compare and
455 // instructions before it.
456 bool CompleteCCUsers = !isCCLiveOut(MBB);
457 SmallVector<MachineInstr *, 4> CCUsers;
458 MachineBasicBlock::iterator MBBI = MBB.end();
459 while (MBBI != MBB.begin()) {
460 MachineInstr *MI = --MBBI;
461 if (CompleteCCUsers &&
462 (MI->isCompare() || isLoadAndTestAsCmp(MI)) &&
463 (optimizeCompareZero(MI, CCUsers) ||
464 fuseCompareAndBranch(MI, CCUsers))) {
466 MI->eraseFromParent();
472 Reference CCRefs(getRegReferences(MI, SystemZ::CC));
475 CompleteCCUsers = true;
477 if (CompleteCCUsers && CCRefs.Use)
478 CCUsers.push_back(MI);
483 bool SystemZElimCompare::runOnMachineFunction(MachineFunction &F) {
484 TII = static_cast<const SystemZInstrInfo *>(F.getSubtarget().getInstrInfo());
485 TRI = &TII->getRegisterInfo();
487 bool Changed = false;
489 Changed |= processBlock(MBB);