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 #define DEBUG_TYPE "systemz-elim-compare"
18 #include "SystemZTargetMachine.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
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 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(0), TRI(0) {}
69 virtual const char *getPassName() const {
70 return "SystemZ Comparison Elimination";
73 bool processBlock(MachineBasicBlock *MBB);
74 bool runOnMachineFunction(MachineFunction &F);
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 of 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 (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
102 SE = MBB->succ_end(); SI != SE; ++SI)
103 if ((*SI)->isLiveIn(SystemZ::CC))
108 // Return true if any CC result of MI would reflect the value of subreg
110 static bool resultTests(MachineInstr *MI, unsigned Reg, unsigned SubReg) {
111 if (MI->getNumOperands() > 0 &&
112 MI->getOperand(0).isReg() &&
113 MI->getOperand(0).isDef() &&
114 MI->getOperand(0).getReg() == Reg &&
115 MI->getOperand(0).getSubReg() == SubReg)
118 switch (MI->getOpcode()) {
131 if (MI->getOperand(1).getReg() == Reg &&
132 MI->getOperand(1).getSubReg() == SubReg)
139 // Describe the references to Reg in MI, including sub- and super-registers.
140 Reference SystemZElimCompare::getRegReferences(MachineInstr *MI, unsigned Reg) {
142 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
143 const MachineOperand &MO = MI->getOperand(I);
145 if (unsigned MOReg = MO.getReg()) {
146 if (MOReg == Reg || TRI->regsOverlap(MOReg, Reg)) {
149 Ref.IndirectUse |= (MOReg != Reg);
153 Ref.IndirectDef |= (MOReg != Reg);
162 // Compare compares the result of MI against zero. If MI is an addition
163 // of -1 and if CCUsers is a single branch on nonzero, eliminate the addition
164 // and convert the branch to a BRCT(G). Return true on success.
166 SystemZElimCompare::convertToBRCT(MachineInstr *MI, MachineInstr *Compare,
167 SmallVectorImpl<MachineInstr *> &CCUsers) {
168 // Check whether we have an addition of -1.
169 unsigned Opcode = MI->getOpcode();
171 if (Opcode == SystemZ::AHI)
172 BRCT = SystemZ::BRCT;
173 else if (Opcode == SystemZ::AGHI)
174 BRCT = SystemZ::BRCTG;
177 if (MI->getOperand(2).getImm() != -1)
180 // Check whether we have a single JLH.
181 if (CCUsers.size() != 1)
183 MachineInstr *Branch = CCUsers[0];
184 if (Branch->getOpcode() != SystemZ::BRC ||
185 Branch->getOperand(0).getImm() != SystemZ::CCMASK_ICMP ||
186 Branch->getOperand(1).getImm() != SystemZ::CCMASK_CMP_NE)
189 // We already know that there are no references to the register between
190 // MI and Compare. Make sure that there are also no references between
191 // Compare and Branch.
192 unsigned SrcReg = Compare->getOperand(0).getReg();
193 MachineBasicBlock::iterator MBBI = Compare, MBBE = Branch;
194 for (++MBBI; MBBI != MBBE; ++MBBI)
195 if (getRegReferences(MBBI, SrcReg))
198 // The transformation is OK. Rebuild Branch as a BRCT(G).
199 MachineOperand Target(Branch->getOperand(2));
200 Branch->RemoveOperand(2);
201 Branch->RemoveOperand(1);
202 Branch->RemoveOperand(0);
203 Branch->setDesc(TII->get(BRCT));
204 MachineInstrBuilder(*Branch->getParent()->getParent(), Branch)
205 .addOperand(MI->getOperand(0))
206 .addOperand(MI->getOperand(1))
208 .addReg(SystemZ::CC, RegState::ImplicitDefine);
209 MI->removeFromParent();
213 // If MI is a load instruction, try to convert it into a LOAD AND TEST.
214 // Return true on success.
215 bool SystemZElimCompare::convertToLoadAndTest(MachineInstr *MI) {
216 unsigned Opcode = TII->getLoadAndTest(MI->getOpcode());
220 MI->setDesc(TII->get(Opcode));
221 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
222 .addReg(SystemZ::CC, RegState::ImplicitDefine);
226 // The CC users in CCUsers are testing the result of a comparison of some
227 // value X against zero and we know that any CC value produced by MI
228 // would also reflect the value of X. Try to adjust CCUsers so that
229 // they test the result of MI directly, returning true on success.
230 // Leave everything unchanged on failure.
231 bool SystemZElimCompare::
232 adjustCCMasksForInstr(MachineInstr *MI, MachineInstr *Compare,
233 SmallVectorImpl<MachineInstr *> &CCUsers) {
234 int Opcode = MI->getOpcode();
235 const MCInstrDesc &Desc = TII->get(Opcode);
236 unsigned MIFlags = Desc.TSFlags;
238 // See which compare-style condition codes are available.
239 unsigned ReusableCCMask = SystemZII::getCompareZeroCCMask(MIFlags);
241 // For unsigned comparisons with zero, only equality makes sense.
242 unsigned CompareFlags = Compare->getDesc().TSFlags;
243 if (CompareFlags & SystemZII::IsLogical)
244 ReusableCCMask &= SystemZ::CCMASK_CMP_EQ;
246 if (ReusableCCMask == 0)
249 unsigned CCValues = SystemZII::getCCValues(MIFlags);
250 assert((ReusableCCMask & ~CCValues) == 0 && "Invalid CCValues");
252 // Now check whether these flags are enough for all users.
253 SmallVector<MachineOperand *, 4> AlterMasks;
254 for (unsigned int I = 0, E = CCUsers.size(); I != E; ++I) {
255 MachineInstr *MI = CCUsers[I];
257 // Fail if this isn't a use of CC that we understand.
258 unsigned Flags = MI->getDesc().TSFlags;
260 if (Flags & SystemZII::CCMaskFirst)
262 else if (Flags & SystemZII::CCMaskLast)
263 FirstOpNum = MI->getNumExplicitOperands() - 2;
267 // Check whether the instruction predicate treats all CC values
268 // outside of ReusableCCMask in the same way. In that case it
269 // doesn't matter what those CC values mean.
270 unsigned CCValid = MI->getOperand(FirstOpNum).getImm();
271 unsigned CCMask = MI->getOperand(FirstOpNum + 1).getImm();
272 unsigned OutValid = ~ReusableCCMask & CCValid;
273 unsigned OutMask = ~ReusableCCMask & CCMask;
274 if (OutMask != 0 && OutMask != OutValid)
277 AlterMasks.push_back(&MI->getOperand(FirstOpNum));
278 AlterMasks.push_back(&MI->getOperand(FirstOpNum + 1));
281 // All users are OK. Adjust the masks for MI.
282 for (unsigned I = 0, E = AlterMasks.size(); I != E; I += 2) {
283 AlterMasks[I]->setImm(CCValues);
284 unsigned CCMask = AlterMasks[I + 1]->getImm();
285 if (CCMask & ~ReusableCCMask)
286 AlterMasks[I + 1]->setImm((CCMask & ReusableCCMask) |
287 (CCValues & ~ReusableCCMask));
290 // CC is now live after MI.
291 int CCDef = MI->findRegisterDefOperandIdx(SystemZ::CC, false, true, TRI);
292 assert(CCDef >= 0 && "Couldn't find CC set");
293 MI->getOperand(CCDef).setIsDead(false);
295 // Clear any intervening kills of CC.
296 MachineBasicBlock::iterator MBBI = MI, MBBE = Compare;
297 for (++MBBI; MBBI != MBBE; ++MBBI)
298 MBBI->clearRegisterKills(SystemZ::CC, TRI);
303 // Return true if Compare is a comparison against zero.
304 static bool isCompareZero(MachineInstr *Compare) {
305 switch (Compare->getOpcode()) {
306 case SystemZ::LTEBRCompare:
307 case SystemZ::LTDBRCompare:
308 case SystemZ::LTXBRCompare:
312 return (Compare->getNumExplicitOperands() == 2 &&
313 Compare->getOperand(1).isImm() &&
314 Compare->getOperand(1).getImm() == 0);
318 // Try to optimize cases where comparison instruction Compare is testing
319 // a value against zero. Return true on success and if Compare should be
320 // deleted as dead. CCUsers is the list of instructions that use the CC
321 // value produced by Compare.
322 bool SystemZElimCompare::
323 optimizeCompareZero(MachineInstr *Compare,
324 SmallVectorImpl<MachineInstr *> &CCUsers) {
325 if (!isCompareZero(Compare))
328 // Search back for CC results that are based on the first operand.
329 unsigned SrcReg = Compare->getOperand(0).getReg();
330 unsigned SrcSubReg = Compare->getOperand(0).getSubReg();
331 MachineBasicBlock *MBB = Compare->getParent();
332 MachineBasicBlock::iterator MBBI = Compare, MBBE = MBB->begin();
335 while (MBBI != MBBE) {
337 MachineInstr *MI = MBBI;
338 if (resultTests(MI, SrcReg, SrcSubReg)) {
339 // Try to remove both MI and Compare by converting a branch to BRCT(G).
340 // We don't care in this case whether CC is modified between MI and
342 if (!CCRefs.Use && !SrcRefs && convertToBRCT(MI, Compare, CCUsers)) {
346 // Try to eliminate Compare by reusing a CC result from MI.
347 if ((!CCRefs && convertToLoadAndTest(MI)) ||
348 (!CCRefs.Def && adjustCCMasksForInstr(MI, Compare, CCUsers))) {
349 EliminatedComparisons += 1;
353 SrcRefs |= getRegReferences(MI, SrcReg);
356 CCRefs |= getRegReferences(MI, SystemZ::CC);
357 if (CCRefs.Use && CCRefs.Def)
363 // Try to fuse comparison instruction Compare into a later branch.
364 // Return true on success and if Compare is therefore redundant.
365 bool SystemZElimCompare::
366 fuseCompareAndBranch(MachineInstr *Compare,
367 SmallVectorImpl<MachineInstr *> &CCUsers) {
368 // See whether we have a comparison that can be fused.
369 unsigned FusedOpcode = TII->getCompareAndBranch(Compare->getOpcode(),
374 // See whether we have a single branch with which to fuse.
375 if (CCUsers.size() != 1)
377 MachineInstr *Branch = CCUsers[0];
378 if (Branch->getOpcode() != SystemZ::BRC)
381 // Make sure that the operands are available at the branch.
382 unsigned SrcReg = Compare->getOperand(0).getReg();
383 unsigned SrcReg2 = (Compare->getOperand(1).isReg() ?
384 Compare->getOperand(1).getReg() : 0);
385 MachineBasicBlock::iterator MBBI = Compare, MBBE = Branch;
386 for (++MBBI; MBBI != MBBE; ++MBBI)
387 if (MBBI->modifiesRegister(SrcReg, TRI) ||
388 (SrcReg2 && MBBI->modifiesRegister(SrcReg2, TRI)))
391 // Read the branch mask and target.
392 MachineOperand CCMask(MBBI->getOperand(1));
393 MachineOperand Target(MBBI->getOperand(2));
394 assert((CCMask.getImm() & ~SystemZ::CCMASK_ICMP) == 0 &&
395 "Invalid condition-code mask for integer comparison");
397 // Clear out all current operands.
398 int CCUse = MBBI->findRegisterUseOperandIdx(SystemZ::CC, false, TRI);
399 assert(CCUse >= 0 && "BRC must use CC");
400 Branch->RemoveOperand(CCUse);
401 Branch->RemoveOperand(2);
402 Branch->RemoveOperand(1);
403 Branch->RemoveOperand(0);
405 // Rebuild Branch as a fused compare and branch.
406 Branch->setDesc(TII->get(FusedOpcode));
407 MachineInstrBuilder(*Branch->getParent()->getParent(), Branch)
408 .addOperand(Compare->getOperand(0))
409 .addOperand(Compare->getOperand(1))
412 .addReg(SystemZ::CC, RegState::ImplicitDefine);
414 // Clear any intervening kills of SrcReg and SrcReg2.
416 for (++MBBI; MBBI != MBBE; ++MBBI) {
417 MBBI->clearRegisterKills(SrcReg, TRI);
419 MBBI->clearRegisterKills(SrcReg2, TRI);
421 FusedComparisons += 1;
425 // Process all comparison instructions in MBB. Return true if something
427 bool SystemZElimCompare::processBlock(MachineBasicBlock *MBB) {
428 bool Changed = false;
430 // Walk backwards through the block looking for comparisons, recording
431 // all CC users as we go. The subroutines can delete Compare and
432 // instructions before it.
433 bool CompleteCCUsers = !isCCLiveOut(MBB);
434 SmallVector<MachineInstr *, 4> CCUsers;
435 MachineBasicBlock::iterator MBBI = MBB->end();
436 while (MBBI != MBB->begin()) {
437 MachineInstr *MI = --MBBI;
438 if (CompleteCCUsers &&
440 (optimizeCompareZero(MI, CCUsers) ||
441 fuseCompareAndBranch(MI, CCUsers))) {
443 MI->removeFromParent();
446 CompleteCCUsers = true;
450 Reference CCRefs(getRegReferences(MI, SystemZ::CC));
453 CompleteCCUsers = !CCRefs.IndirectDef;
455 if (CompleteCCUsers && CCRefs.Use)
456 CCUsers.push_back(MI);
461 bool SystemZElimCompare::runOnMachineFunction(MachineFunction &F) {
462 TII = static_cast<const SystemZInstrInfo *>(F.getTarget().getInstrInfo());
463 TRI = &TII->getRegisterInfo();
465 bool Changed = false;
466 for (MachineFunction::iterator MFI = F.begin(), MFE = F.end();
468 Changed |= processBlock(MFI);