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) {}
42 Reference &operator|=(const Reference &Other) {
48 explicit operator bool() const { return Def || Use; }
50 // True if the register is defined or used in some form, either directly or
51 // via a sub- or super-register.
56 class SystemZElimCompare : public MachineFunctionPass {
59 SystemZElimCompare(const SystemZTargetMachine &tm)
60 : MachineFunctionPass(ID), TII(nullptr), TRI(nullptr) {}
62 const char *getPassName() const override {
63 return "SystemZ Comparison Elimination";
66 bool processBlock(MachineBasicBlock &MBB);
67 bool runOnMachineFunction(MachineFunction &F) override;
70 Reference getRegReferences(MachineInstr *MI, unsigned Reg);
71 bool convertToBRCT(MachineInstr *MI, MachineInstr *Compare,
72 SmallVectorImpl<MachineInstr *> &CCUsers);
73 bool convertToLoadAndTest(MachineInstr *MI);
74 bool adjustCCMasksForInstr(MachineInstr *MI, MachineInstr *Compare,
75 SmallVectorImpl<MachineInstr *> &CCUsers);
76 bool optimizeCompareZero(MachineInstr *Compare,
77 SmallVectorImpl<MachineInstr *> &CCUsers);
78 bool fuseCompareAndBranch(MachineInstr *Compare,
79 SmallVectorImpl<MachineInstr *> &CCUsers);
81 const SystemZInstrInfo *TII;
82 const TargetRegisterInfo *TRI;
85 char SystemZElimCompare::ID = 0;
86 } // end anonymous namespace
88 FunctionPass *llvm::createSystemZElimComparePass(SystemZTargetMachine &TM) {
89 return new SystemZElimCompare(TM);
92 // Return true if CC is live out of MBB.
93 static bool isCCLiveOut(MachineBasicBlock &MBB) {
94 for (auto SI = MBB.succ_begin(), SE = MBB.succ_end(); SI != SE; ++SI)
95 if ((*SI)->isLiveIn(SystemZ::CC))
100 // Return true if any CC result of MI would reflect the value of Reg.
101 static bool resultTests(MachineInstr *MI, unsigned Reg) {
102 if (MI->getNumOperands() > 0 &&
103 MI->getOperand(0).isReg() &&
104 MI->getOperand(0).isDef() &&
105 MI->getOperand(0).getReg() == Reg)
108 switch (MI->getOpcode()) {
121 if (MI->getOperand(1).getReg() == Reg)
128 // Describe the references to Reg or any of its aliases in MI.
129 Reference SystemZElimCompare::getRegReferences(MachineInstr *MI, unsigned Reg) {
131 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
132 const MachineOperand &MO = MI->getOperand(I);
134 if (unsigned MOReg = MO.getReg()) {
135 if (TRI->regsOverlap(MOReg, Reg)) {
147 // Return true if this is a load and test which can be optimized the
148 // same way as compare instruction.
149 static bool isLoadAndTestAsCmp(MachineInstr *MI) {
150 // If we during isel used a load-and-test as a compare with 0, the
151 // def operand is dead.
152 return ((MI->getOpcode() == SystemZ::LTEBR ||
153 MI->getOpcode() == SystemZ::LTDBR ||
154 MI->getOpcode() == SystemZ::LTXBR) &&
155 MI->getOperand(0).isDead());
158 // Return the source register of Compare, which is the unknown value
160 static unsigned getCompareSourceReg(MachineInstr *Compare) {
162 if (Compare->isCompare())
163 reg = Compare->getOperand(0).getReg();
164 else if (isLoadAndTestAsCmp(Compare))
165 reg = Compare->getOperand(1).getReg();
171 // Compare compares the result of MI against zero. If MI is an addition
172 // of -1 and if CCUsers is a single branch on nonzero, eliminate the addition
173 // and convert the branch to a BRCT(G). Return true on success.
175 SystemZElimCompare::convertToBRCT(MachineInstr *MI, MachineInstr *Compare,
176 SmallVectorImpl<MachineInstr *> &CCUsers) {
177 // Check whether we have an addition of -1.
178 unsigned Opcode = MI->getOpcode();
180 if (Opcode == SystemZ::AHI)
181 BRCT = SystemZ::BRCT;
182 else if (Opcode == SystemZ::AGHI)
183 BRCT = SystemZ::BRCTG;
186 if (MI->getOperand(2).getImm() != -1)
189 // Check whether we have a single JLH.
190 if (CCUsers.size() != 1)
192 MachineInstr *Branch = CCUsers[0];
193 if (Branch->getOpcode() != SystemZ::BRC ||
194 Branch->getOperand(0).getImm() != SystemZ::CCMASK_ICMP ||
195 Branch->getOperand(1).getImm() != SystemZ::CCMASK_CMP_NE)
198 // We already know that there are no references to the register between
199 // MI and Compare. Make sure that there are also no references between
200 // Compare and Branch.
201 unsigned SrcReg = getCompareSourceReg(Compare);
202 MachineBasicBlock::iterator MBBI = Compare, MBBE = Branch;
203 for (++MBBI; MBBI != MBBE; ++MBBI)
204 if (getRegReferences(MBBI, SrcReg))
207 // The transformation is OK. Rebuild Branch as a BRCT(G).
208 MachineOperand Target(Branch->getOperand(2));
209 Branch->RemoveOperand(2);
210 Branch->RemoveOperand(1);
211 Branch->RemoveOperand(0);
212 Branch->setDesc(TII->get(BRCT));
213 MachineInstrBuilder(*Branch->getParent()->getParent(), Branch)
214 .addOperand(MI->getOperand(0))
215 .addOperand(MI->getOperand(1))
217 .addReg(SystemZ::CC, RegState::ImplicitDefine);
218 MI->eraseFromParent();
222 // If MI is a load instruction, try to convert it into a LOAD AND TEST.
223 // Return true on success.
224 bool SystemZElimCompare::convertToLoadAndTest(MachineInstr *MI) {
225 unsigned Opcode = TII->getLoadAndTest(MI->getOpcode());
229 MI->setDesc(TII->get(Opcode));
230 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
231 .addReg(SystemZ::CC, RegState::ImplicitDefine);
235 // The CC users in CCUsers are testing the result of a comparison of some
236 // value X against zero and we know that any CC value produced by MI
237 // would also reflect the value of X. Try to adjust CCUsers so that
238 // they test the result of MI directly, returning true on success.
239 // Leave everything unchanged on failure.
240 bool SystemZElimCompare::
241 adjustCCMasksForInstr(MachineInstr *MI, MachineInstr *Compare,
242 SmallVectorImpl<MachineInstr *> &CCUsers) {
243 int Opcode = MI->getOpcode();
244 const MCInstrDesc &Desc = TII->get(Opcode);
245 unsigned MIFlags = Desc.TSFlags;
247 // See which compare-style condition codes are available.
248 unsigned ReusableCCMask = SystemZII::getCompareZeroCCMask(MIFlags);
250 // For unsigned comparisons with zero, only equality makes sense.
251 unsigned CompareFlags = Compare->getDesc().TSFlags;
252 if (CompareFlags & SystemZII::IsLogical)
253 ReusableCCMask &= SystemZ::CCMASK_CMP_EQ;
255 if (ReusableCCMask == 0)
258 unsigned CCValues = SystemZII::getCCValues(MIFlags);
259 assert((ReusableCCMask & ~CCValues) == 0 && "Invalid CCValues");
261 // Now check whether these flags are enough for all users.
262 SmallVector<MachineOperand *, 4> AlterMasks;
263 for (unsigned int I = 0, E = CCUsers.size(); I != E; ++I) {
264 MachineInstr *MI = CCUsers[I];
266 // Fail if this isn't a use of CC that we understand.
267 unsigned Flags = MI->getDesc().TSFlags;
269 if (Flags & SystemZII::CCMaskFirst)
271 else if (Flags & SystemZII::CCMaskLast)
272 FirstOpNum = MI->getNumExplicitOperands() - 2;
276 // Check whether the instruction predicate treats all CC values
277 // outside of ReusableCCMask in the same way. In that case it
278 // doesn't matter what those CC values mean.
279 unsigned CCValid = MI->getOperand(FirstOpNum).getImm();
280 unsigned CCMask = MI->getOperand(FirstOpNum + 1).getImm();
281 unsigned OutValid = ~ReusableCCMask & CCValid;
282 unsigned OutMask = ~ReusableCCMask & CCMask;
283 if (OutMask != 0 && OutMask != OutValid)
286 AlterMasks.push_back(&MI->getOperand(FirstOpNum));
287 AlterMasks.push_back(&MI->getOperand(FirstOpNum + 1));
290 // All users are OK. Adjust the masks for MI.
291 for (unsigned I = 0, E = AlterMasks.size(); I != E; I += 2) {
292 AlterMasks[I]->setImm(CCValues);
293 unsigned CCMask = AlterMasks[I + 1]->getImm();
294 if (CCMask & ~ReusableCCMask)
295 AlterMasks[I + 1]->setImm((CCMask & ReusableCCMask) |
296 (CCValues & ~ReusableCCMask));
299 // CC is now live after MI.
300 int CCDef = MI->findRegisterDefOperandIdx(SystemZ::CC, false, true, TRI);
301 assert(CCDef >= 0 && "Couldn't find CC set");
302 MI->getOperand(CCDef).setIsDead(false);
304 // Clear any intervening kills of CC.
305 MachineBasicBlock::iterator MBBI = MI, MBBE = Compare;
306 for (++MBBI; MBBI != MBBE; ++MBBI)
307 MBBI->clearRegisterKills(SystemZ::CC, TRI);
312 // Return true if Compare is a comparison against zero.
313 static bool isCompareZero(MachineInstr *Compare) {
314 switch (Compare->getOpcode()) {
315 case SystemZ::LTEBRCompare:
316 case SystemZ::LTDBRCompare:
317 case SystemZ::LTXBRCompare:
322 if (isLoadAndTestAsCmp(Compare))
325 return (Compare->getNumExplicitOperands() == 2 &&
326 Compare->getOperand(1).isImm() &&
327 Compare->getOperand(1).getImm() == 0);
331 // Try to optimize cases where comparison instruction Compare is testing
332 // a value against zero. Return true on success and if Compare should be
333 // deleted as dead. CCUsers is the list of instructions that use the CC
334 // value produced by Compare.
335 bool SystemZElimCompare::
336 optimizeCompareZero(MachineInstr *Compare,
337 SmallVectorImpl<MachineInstr *> &CCUsers) {
338 if (!isCompareZero(Compare))
341 // Search back for CC results that are based on the first operand.
342 unsigned SrcReg = getCompareSourceReg(Compare);
343 MachineBasicBlock &MBB = *Compare->getParent();
344 MachineBasicBlock::iterator MBBI = Compare, MBBE = MBB.begin();
347 while (MBBI != MBBE) {
349 MachineInstr *MI = MBBI;
350 if (resultTests(MI, SrcReg)) {
351 // Try to remove both MI and Compare by converting a branch to BRCT(G).
352 // We don't care in this case whether CC is modified between MI and
354 if (!CCRefs.Use && !SrcRefs && convertToBRCT(MI, Compare, CCUsers)) {
358 // Try to eliminate Compare by reusing a CC result from MI.
359 if ((!CCRefs && convertToLoadAndTest(MI)) ||
360 (!CCRefs.Def && adjustCCMasksForInstr(MI, Compare, CCUsers))) {
361 EliminatedComparisons += 1;
365 SrcRefs |= getRegReferences(MI, SrcReg);
368 CCRefs |= getRegReferences(MI, SystemZ::CC);
369 if (CCRefs.Use && CCRefs.Def)
375 // Try to fuse comparison instruction Compare into a later branch.
376 // Return true on success and if Compare is therefore redundant.
377 bool SystemZElimCompare::
378 fuseCompareAndBranch(MachineInstr *Compare,
379 SmallVectorImpl<MachineInstr *> &CCUsers) {
380 // See whether we have a comparison that can be fused.
381 unsigned FusedOpcode = TII->getCompareAndBranch(Compare->getOpcode(),
386 // See whether we have a single branch with which to fuse.
387 if (CCUsers.size() != 1)
389 MachineInstr *Branch = CCUsers[0];
390 if (Branch->getOpcode() != SystemZ::BRC)
393 // Make sure that the operands are available at the branch.
394 unsigned SrcReg = Compare->getOperand(0).getReg();
395 unsigned SrcReg2 = (Compare->getOperand(1).isReg() ?
396 Compare->getOperand(1).getReg() : 0);
397 MachineBasicBlock::iterator MBBI = Compare, MBBE = Branch;
398 for (++MBBI; MBBI != MBBE; ++MBBI)
399 if (MBBI->modifiesRegister(SrcReg, TRI) ||
400 (SrcReg2 && MBBI->modifiesRegister(SrcReg2, TRI)))
403 // Read the branch mask and target.
404 MachineOperand CCMask(MBBI->getOperand(1));
405 MachineOperand Target(MBBI->getOperand(2));
406 assert((CCMask.getImm() & ~SystemZ::CCMASK_ICMP) == 0 &&
407 "Invalid condition-code mask for integer comparison");
409 // Clear out all current operands.
410 int CCUse = MBBI->findRegisterUseOperandIdx(SystemZ::CC, false, TRI);
411 assert(CCUse >= 0 && "BRC must use CC");
412 Branch->RemoveOperand(CCUse);
413 Branch->RemoveOperand(2);
414 Branch->RemoveOperand(1);
415 Branch->RemoveOperand(0);
417 // Rebuild Branch as a fused compare and branch.
418 Branch->setDesc(TII->get(FusedOpcode));
419 MachineInstrBuilder(*Branch->getParent()->getParent(), Branch)
420 .addOperand(Compare->getOperand(0))
421 .addOperand(Compare->getOperand(1))
424 .addReg(SystemZ::CC, RegState::ImplicitDefine);
426 // Clear any intervening kills of SrcReg and SrcReg2.
428 for (++MBBI; MBBI != MBBE; ++MBBI) {
429 MBBI->clearRegisterKills(SrcReg, TRI);
431 MBBI->clearRegisterKills(SrcReg2, TRI);
433 FusedComparisons += 1;
437 // Process all comparison instructions in MBB. Return true if something
439 bool SystemZElimCompare::processBlock(MachineBasicBlock &MBB) {
440 bool Changed = false;
442 // Walk backwards through the block looking for comparisons, recording
443 // all CC users as we go. The subroutines can delete Compare and
444 // instructions before it.
445 bool CompleteCCUsers = !isCCLiveOut(MBB);
446 SmallVector<MachineInstr *, 4> CCUsers;
447 MachineBasicBlock::iterator MBBI = MBB.end();
448 while (MBBI != MBB.begin()) {
449 MachineInstr *MI = --MBBI;
450 if (CompleteCCUsers &&
451 (MI->isCompare() || isLoadAndTestAsCmp(MI)) &&
452 (optimizeCompareZero(MI, CCUsers) ||
453 fuseCompareAndBranch(MI, CCUsers))) {
455 MI->eraseFromParent();
461 if (MI->definesRegister(SystemZ::CC)) {
463 CompleteCCUsers = true;
465 if (MI->readsRegister(SystemZ::CC) && CompleteCCUsers)
466 CCUsers.push_back(MI);
471 bool SystemZElimCompare::runOnMachineFunction(MachineFunction &F) {
472 TII = static_cast<const SystemZInstrInfo *>(F.getSubtarget().getInstrInfo());
473 TRI = &TII->getRegisterInfo();
475 bool Changed = false;
477 Changed |= processBlock(MBB);