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 // Compare compares the result of MI against zero. If MI is an addition
159 // of -1 and if CCUsers is a single branch on nonzero, eliminate the addition
160 // and convert the branch to a BRCT(G). Return true on success.
162 SystemZElimCompare::convertToBRCT(MachineInstr *MI, MachineInstr *Compare,
163 SmallVectorImpl<MachineInstr *> &CCUsers) {
164 // Check whether we have an addition of -1.
165 unsigned Opcode = MI->getOpcode();
167 if (Opcode == SystemZ::AHI)
168 BRCT = SystemZ::BRCT;
169 else if (Opcode == SystemZ::AGHI)
170 BRCT = SystemZ::BRCTG;
173 if (MI->getOperand(2).getImm() != -1)
176 // Check whether we have a single JLH.
177 if (CCUsers.size() != 1)
179 MachineInstr *Branch = CCUsers[0];
180 if (Branch->getOpcode() != SystemZ::BRC ||
181 Branch->getOperand(0).getImm() != SystemZ::CCMASK_ICMP ||
182 Branch->getOperand(1).getImm() != SystemZ::CCMASK_CMP_NE)
185 // We already know that there are no references to the register between
186 // MI and Compare. Make sure that there are also no references between
187 // Compare and Branch.
188 unsigned SrcReg = Compare->getOperand(0).getReg();
189 MachineBasicBlock::iterator MBBI = Compare, MBBE = Branch;
190 for (++MBBI; MBBI != MBBE; ++MBBI)
191 if (getRegReferences(MBBI, SrcReg))
194 // The transformation is OK. Rebuild Branch as a BRCT(G).
195 MachineOperand Target(Branch->getOperand(2));
196 Branch->RemoveOperand(2);
197 Branch->RemoveOperand(1);
198 Branch->RemoveOperand(0);
199 Branch->setDesc(TII->get(BRCT));
200 MachineInstrBuilder(*Branch->getParent()->getParent(), Branch)
201 .addOperand(MI->getOperand(0))
202 .addOperand(MI->getOperand(1))
204 .addReg(SystemZ::CC, RegState::ImplicitDefine);
205 MI->eraseFromParent();
209 // If MI is a load instruction, try to convert it into a LOAD AND TEST.
210 // Return true on success.
211 bool SystemZElimCompare::convertToLoadAndTest(MachineInstr *MI) {
212 unsigned Opcode = TII->getLoadAndTest(MI->getOpcode());
216 MI->setDesc(TII->get(Opcode));
217 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
218 .addReg(SystemZ::CC, RegState::ImplicitDefine);
222 // The CC users in CCUsers are testing the result of a comparison of some
223 // value X against zero and we know that any CC value produced by MI
224 // would also reflect the value of X. Try to adjust CCUsers so that
225 // they test the result of MI directly, returning true on success.
226 // Leave everything unchanged on failure.
227 bool SystemZElimCompare::
228 adjustCCMasksForInstr(MachineInstr *MI, MachineInstr *Compare,
229 SmallVectorImpl<MachineInstr *> &CCUsers) {
230 int Opcode = MI->getOpcode();
231 const MCInstrDesc &Desc = TII->get(Opcode);
232 unsigned MIFlags = Desc.TSFlags;
234 // See which compare-style condition codes are available.
235 unsigned ReusableCCMask = SystemZII::getCompareZeroCCMask(MIFlags);
237 // For unsigned comparisons with zero, only equality makes sense.
238 unsigned CompareFlags = Compare->getDesc().TSFlags;
239 if (CompareFlags & SystemZII::IsLogical)
240 ReusableCCMask &= SystemZ::CCMASK_CMP_EQ;
242 if (ReusableCCMask == 0)
245 unsigned CCValues = SystemZII::getCCValues(MIFlags);
246 assert((ReusableCCMask & ~CCValues) == 0 && "Invalid CCValues");
248 // Now check whether these flags are enough for all users.
249 SmallVector<MachineOperand *, 4> AlterMasks;
250 for (unsigned int I = 0, E = CCUsers.size(); I != E; ++I) {
251 MachineInstr *MI = CCUsers[I];
253 // Fail if this isn't a use of CC that we understand.
254 unsigned Flags = MI->getDesc().TSFlags;
256 if (Flags & SystemZII::CCMaskFirst)
258 else if (Flags & SystemZII::CCMaskLast)
259 FirstOpNum = MI->getNumExplicitOperands() - 2;
263 // Check whether the instruction predicate treats all CC values
264 // outside of ReusableCCMask in the same way. In that case it
265 // doesn't matter what those CC values mean.
266 unsigned CCValid = MI->getOperand(FirstOpNum).getImm();
267 unsigned CCMask = MI->getOperand(FirstOpNum + 1).getImm();
268 unsigned OutValid = ~ReusableCCMask & CCValid;
269 unsigned OutMask = ~ReusableCCMask & CCMask;
270 if (OutMask != 0 && OutMask != OutValid)
273 AlterMasks.push_back(&MI->getOperand(FirstOpNum));
274 AlterMasks.push_back(&MI->getOperand(FirstOpNum + 1));
277 // All users are OK. Adjust the masks for MI.
278 for (unsigned I = 0, E = AlterMasks.size(); I != E; I += 2) {
279 AlterMasks[I]->setImm(CCValues);
280 unsigned CCMask = AlterMasks[I + 1]->getImm();
281 if (CCMask & ~ReusableCCMask)
282 AlterMasks[I + 1]->setImm((CCMask & ReusableCCMask) |
283 (CCValues & ~ReusableCCMask));
286 // CC is now live after MI.
287 int CCDef = MI->findRegisterDefOperandIdx(SystemZ::CC, false, true, TRI);
288 assert(CCDef >= 0 && "Couldn't find CC set");
289 MI->getOperand(CCDef).setIsDead(false);
291 // Clear any intervening kills of CC.
292 MachineBasicBlock::iterator MBBI = MI, MBBE = Compare;
293 for (++MBBI; MBBI != MBBE; ++MBBI)
294 MBBI->clearRegisterKills(SystemZ::CC, TRI);
299 // Return true if Compare is a comparison against zero.
300 static bool isCompareZero(MachineInstr *Compare) {
301 switch (Compare->getOpcode()) {
302 case SystemZ::LTEBRCompare:
303 case SystemZ::LTDBRCompare:
304 case SystemZ::LTXBRCompare:
308 return (Compare->getNumExplicitOperands() == 2 &&
309 Compare->getOperand(1).isImm() &&
310 Compare->getOperand(1).getImm() == 0);
314 // Try to optimize cases where comparison instruction Compare is testing
315 // a value against zero. Return true on success and if Compare should be
316 // deleted as dead. CCUsers is the list of instructions that use the CC
317 // value produced by Compare.
318 bool SystemZElimCompare::
319 optimizeCompareZero(MachineInstr *Compare,
320 SmallVectorImpl<MachineInstr *> &CCUsers) {
321 if (!isCompareZero(Compare))
324 // Search back for CC results that are based on the first operand.
325 unsigned SrcReg = Compare->getOperand(0).getReg();
326 MachineBasicBlock &MBB = *Compare->getParent();
327 MachineBasicBlock::iterator MBBI = Compare, MBBE = MBB.begin();
330 while (MBBI != MBBE) {
332 MachineInstr *MI = MBBI;
333 if (resultTests(MI, SrcReg)) {
334 // Try to remove both MI and Compare by converting a branch to BRCT(G).
335 // We don't care in this case whether CC is modified between MI and
337 if (!CCRefs.Use && !SrcRefs && convertToBRCT(MI, Compare, CCUsers)) {
341 // Try to eliminate Compare by reusing a CC result from MI.
342 if ((!CCRefs && convertToLoadAndTest(MI)) ||
343 (!CCRefs.Def && adjustCCMasksForInstr(MI, Compare, CCUsers))) {
344 EliminatedComparisons += 1;
348 SrcRefs |= getRegReferences(MI, SrcReg);
351 CCRefs |= getRegReferences(MI, SystemZ::CC);
352 if (CCRefs.Use && CCRefs.Def)
358 // Try to fuse comparison instruction Compare into a later branch.
359 // Return true on success and if Compare is therefore redundant.
360 bool SystemZElimCompare::
361 fuseCompareAndBranch(MachineInstr *Compare,
362 SmallVectorImpl<MachineInstr *> &CCUsers) {
363 // See whether we have a comparison that can be fused.
364 unsigned FusedOpcode = TII->getCompareAndBranch(Compare->getOpcode(),
369 // See whether we have a single branch with which to fuse.
370 if (CCUsers.size() != 1)
372 MachineInstr *Branch = CCUsers[0];
373 if (Branch->getOpcode() != SystemZ::BRC)
376 // Make sure that the operands are available at the branch.
377 unsigned SrcReg = Compare->getOperand(0).getReg();
378 unsigned SrcReg2 = (Compare->getOperand(1).isReg() ?
379 Compare->getOperand(1).getReg() : 0);
380 MachineBasicBlock::iterator MBBI = Compare, MBBE = Branch;
381 for (++MBBI; MBBI != MBBE; ++MBBI)
382 if (MBBI->modifiesRegister(SrcReg, TRI) ||
383 (SrcReg2 && MBBI->modifiesRegister(SrcReg2, TRI)))
386 // Read the branch mask and target.
387 MachineOperand CCMask(MBBI->getOperand(1));
388 MachineOperand Target(MBBI->getOperand(2));
389 assert((CCMask.getImm() & ~SystemZ::CCMASK_ICMP) == 0 &&
390 "Invalid condition-code mask for integer comparison");
392 // Clear out all current operands.
393 int CCUse = MBBI->findRegisterUseOperandIdx(SystemZ::CC, false, TRI);
394 assert(CCUse >= 0 && "BRC must use CC");
395 Branch->RemoveOperand(CCUse);
396 Branch->RemoveOperand(2);
397 Branch->RemoveOperand(1);
398 Branch->RemoveOperand(0);
400 // Rebuild Branch as a fused compare and branch.
401 Branch->setDesc(TII->get(FusedOpcode));
402 MachineInstrBuilder(*Branch->getParent()->getParent(), Branch)
403 .addOperand(Compare->getOperand(0))
404 .addOperand(Compare->getOperand(1))
407 .addReg(SystemZ::CC, RegState::ImplicitDefine);
409 // Clear any intervening kills of SrcReg and SrcReg2.
411 for (++MBBI; MBBI != MBBE; ++MBBI) {
412 MBBI->clearRegisterKills(SrcReg, TRI);
414 MBBI->clearRegisterKills(SrcReg2, TRI);
416 FusedComparisons += 1;
420 // Process all comparison instructions in MBB. Return true if something
422 bool SystemZElimCompare::processBlock(MachineBasicBlock &MBB) {
423 bool Changed = false;
425 // Walk backwards through the block looking for comparisons, recording
426 // all CC users as we go. The subroutines can delete Compare and
427 // instructions before it.
428 bool CompleteCCUsers = !isCCLiveOut(MBB);
429 SmallVector<MachineInstr *, 4> CCUsers;
430 MachineBasicBlock::iterator MBBI = MBB.end();
431 while (MBBI != MBB.begin()) {
432 MachineInstr *MI = --MBBI;
433 if (CompleteCCUsers &&
435 (optimizeCompareZero(MI, CCUsers) ||
436 fuseCompareAndBranch(MI, CCUsers))) {
438 MI->eraseFromParent();
444 Reference CCRefs(getRegReferences(MI, SystemZ::CC));
447 CompleteCCUsers = true;
449 if (CompleteCCUsers && CCRefs.Use)
450 CCUsers.push_back(MI);
455 bool SystemZElimCompare::runOnMachineFunction(MachineFunction &F) {
456 TII = static_cast<const SystemZInstrInfo *>(F.getSubtarget().getInstrInfo());
457 TRI = &TII->getRegisterInfo();
459 bool Changed = false;
461 Changed |= processBlock(MBB);