[SystemZ] SystemZElimCompare pass improved.
[oota-llvm.git] / lib / Target / SystemZ / SystemZElimCompare.cpp
1 //===-- SystemZElimCompare.cpp - Eliminate comparison instructions --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass:
11 // (1) tries to remove compares if CC already contains the required information
12 // (2) fuses compares and branches into COMPARE AND BRANCH instructions
13 //
14 //===----------------------------------------------------------------------===//
15
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"
26
27 using namespace llvm;
28
29 #define DEBUG_TYPE "systemz-elim-compare"
30
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");
34
35 namespace {
36 // Represents the references to a particular register in one or more
37 // instructions.
38 struct Reference {
39   Reference()
40     : Def(false), Use(false), IndirectDef(false), IndirectUse(false) {}
41
42   Reference &operator|=(const Reference &Other) {
43     Def |= Other.Def;
44     IndirectDef |= Other.IndirectDef;
45     Use |= Other.Use;
46     IndirectUse |= Other.IndirectUse;
47     return *this;
48   }
49
50   explicit operator bool() const { return Def || Use; }
51
52   // True if the register is defined or used in some form, either directly or
53   // via a sub- or super-register.
54   bool Def;
55   bool Use;
56
57   // True if the register is defined or used indirectly, by a sub- or
58   // super-register.
59   bool IndirectDef;
60   bool IndirectUse;
61 };
62
63 class SystemZElimCompare : public MachineFunctionPass {
64 public:
65   static char ID;
66   SystemZElimCompare(const SystemZTargetMachine &tm)
67     : MachineFunctionPass(ID), TII(nullptr), TRI(nullptr) {}
68
69   const char *getPassName() const override {
70     return "SystemZ Comparison Elimination";
71   }
72
73   bool processBlock(MachineBasicBlock &MBB);
74   bool runOnMachineFunction(MachineFunction &F) override;
75
76 private:
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);
87
88   const SystemZInstrInfo *TII;
89   const TargetRegisterInfo *TRI;
90 };
91
92 char SystemZElimCompare::ID = 0;
93 } // end anonymous namespace
94
95 FunctionPass *llvm::createSystemZElimComparePass(SystemZTargetMachine &TM) {
96   return new SystemZElimCompare(TM);
97 }
98
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))
103       return true;
104   return false;
105 }
106
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)
113     return true;
114
115   switch (MI->getOpcode()) {
116   case SystemZ::LR:
117   case SystemZ::LGR:
118   case SystemZ::LGFR:
119   case SystemZ::LTR:
120   case SystemZ::LTGR:
121   case SystemZ::LTGFR:
122   case SystemZ::LER:
123   case SystemZ::LDR:
124   case SystemZ::LXR:
125   case SystemZ::LTEBR:
126   case SystemZ::LTDBR:
127   case SystemZ::LTXBR:
128     if (MI->getOperand(1).getReg() == Reg)
129       return true;
130   }
131
132   return false;
133 }
134
135 // Describe the references to Reg in MI, including sub- and super-registers.
136 Reference SystemZElimCompare::getRegReferences(MachineInstr *MI, unsigned Reg) {
137   Reference Ref;
138   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
139     const MachineOperand &MO = MI->getOperand(I);
140     if (MO.isReg()) {
141       if (unsigned MOReg = MO.getReg()) {
142         if (MOReg == Reg || TRI->regsOverlap(MOReg, Reg)) {
143           if (MO.isUse()) {
144             Ref.Use = true;
145             Ref.IndirectUse |= (MOReg != Reg);
146           }
147           if (MO.isDef()) {
148             Ref.Def = true;
149             Ref.IndirectDef |= (MOReg != Reg);
150           }
151         }
152       }
153     }
154   }
155   return Ref;
156 }
157
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());
167 }
168
169 // Return the source register of Compare, which is the unknown value
170 // being tested.
171 static unsigned getCompareSourceReg(MachineInstr *Compare) {
172   unsigned reg = 0;
173   if (Compare->isCompare())
174     reg = Compare->getOperand(0).getReg();
175   else if (isLoadAndTestAsCmp(Compare))
176     reg = Compare->getOperand(1).getReg();
177   assert (reg);
178
179   return reg;
180 }
181
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.
185 bool
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();
190   unsigned BRCT;
191   if (Opcode == SystemZ::AHI)
192     BRCT = SystemZ::BRCT;
193   else if (Opcode == SystemZ::AGHI)
194     BRCT = SystemZ::BRCTG;
195   else
196     return false;
197   if (MI->getOperand(2).getImm() != -1)
198     return false;
199
200   // Check whether we have a single JLH.
201   if (CCUsers.size() != 1)
202     return false;
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)
207     return false;
208
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))
216       return false;
217
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))
227     .addOperand(Target)
228     .addReg(SystemZ::CC, RegState::ImplicitDefine);
229   MI->eraseFromParent();
230   return true;
231 }
232
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());
237   if (!Opcode)
238     return false;
239
240   MI->setDesc(TII->get(Opcode));
241   MachineInstrBuilder(*MI->getParent()->getParent(), MI)
242     .addReg(SystemZ::CC, RegState::ImplicitDefine);
243   return true;
244 }
245
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;
257
258   // See which compare-style condition codes are available.
259   unsigned ReusableCCMask = SystemZII::getCompareZeroCCMask(MIFlags);
260
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;
265
266   if (ReusableCCMask == 0)
267     return false;
268
269   unsigned CCValues = SystemZII::getCCValues(MIFlags);
270   assert((ReusableCCMask & ~CCValues) == 0 && "Invalid CCValues");
271
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];
276
277     // Fail if this isn't a use of CC that we understand.
278     unsigned Flags = MI->getDesc().TSFlags;
279     unsigned FirstOpNum;
280     if (Flags & SystemZII::CCMaskFirst)
281       FirstOpNum = 0;
282     else if (Flags & SystemZII::CCMaskLast)
283       FirstOpNum = MI->getNumExplicitOperands() - 2;
284     else
285       return false;
286
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)
295       return false;
296
297     AlterMasks.push_back(&MI->getOperand(FirstOpNum));
298     AlterMasks.push_back(&MI->getOperand(FirstOpNum + 1));
299   }
300
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));
308   }
309
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);
314
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);
319
320   return true;
321 }
322
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:
329     return true;
330
331   default:
332
333     if (isLoadAndTestAsCmp(Compare))
334       return true;
335
336     return (Compare->getNumExplicitOperands() == 2 &&
337             Compare->getOperand(1).isImm() &&
338             Compare->getOperand(1).getImm() == 0);
339   }
340 }
341
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))
350     return false;
351
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();
356   Reference CCRefs;
357   Reference SrcRefs;
358   while (MBBI != MBBE) {
359     --MBBI;
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
364       // Compare.
365       if (!CCRefs.Use && !SrcRefs && convertToBRCT(MI, Compare, CCUsers)) {
366         BranchOnCounts += 1;
367         return true;
368       }
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;
373         return true;
374       }
375     }
376     SrcRefs |= getRegReferences(MI, SrcReg);
377     if (SrcRefs.Def)
378       return false;
379     CCRefs |= getRegReferences(MI, SystemZ::CC);
380     if (CCRefs.Use && CCRefs.Def)
381       return false;
382   }
383   return false;
384 }
385
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(),
393                                                   Compare);
394   if (!FusedOpcode)
395     return false;
396
397   // See whether we have a single branch with which to fuse.
398   if (CCUsers.size() != 1)
399     return false;
400   MachineInstr *Branch = CCUsers[0];
401   if (Branch->getOpcode() != SystemZ::BRC)
402     return false;
403
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)))
412       return false;
413
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");
419
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);
427
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))
433     .addOperand(CCMask)
434     .addOperand(Target)
435     .addReg(SystemZ::CC, RegState::ImplicitDefine);
436
437   // Clear any intervening kills of SrcReg and SrcReg2.
438   MBBI = Compare;
439   for (++MBBI; MBBI != MBBE; ++MBBI) {
440     MBBI->clearRegisterKills(SrcReg, TRI);
441     if (SrcReg2)
442       MBBI->clearRegisterKills(SrcReg2, TRI);
443   }
444   FusedComparisons += 1;
445   return true;
446 }
447
448 // Process all comparison instructions in MBB.  Return true if something
449 // changed.
450 bool SystemZElimCompare::processBlock(MachineBasicBlock &MBB) {
451   bool Changed = false;
452
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))) {
465       ++MBBI;
466       MI->eraseFromParent();
467       Changed = true;
468       CCUsers.clear();
469       continue;
470     }
471
472     Reference CCRefs(getRegReferences(MI, SystemZ::CC));
473     if (CCRefs.Def) {
474       CCUsers.clear();
475       CompleteCCUsers = true;
476     }
477     if (CompleteCCUsers && CCRefs.Use)
478       CCUsers.push_back(MI);
479   }
480   return Changed;
481 }
482
483 bool SystemZElimCompare::runOnMachineFunction(MachineFunction &F) {
484   TII = static_cast<const SystemZInstrInfo *>(F.getSubtarget().getInstrInfo());
485   TRI = &TII->getRegisterInfo();
486
487   bool Changed = false;
488   for (auto &MBB : F)
489     Changed |= processBlock(MBB);
490
491   return Changed;
492 }