ada17fc6308315d8c8b7b4eeb10a100ec87cd270
[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 // 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.
161 bool
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();
166   unsigned BRCT;
167   if (Opcode == SystemZ::AHI)
168     BRCT = SystemZ::BRCT;
169   else if (Opcode == SystemZ::AGHI)
170     BRCT = SystemZ::BRCTG;
171   else
172     return false;
173   if (MI->getOperand(2).getImm() != -1)
174     return false;
175
176   // Check whether we have a single JLH.
177   if (CCUsers.size() != 1)
178     return false;
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)
183     return false;
184
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))
192       return false;
193
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))
203     .addOperand(Target)
204     .addReg(SystemZ::CC, RegState::ImplicitDefine);
205   MI->eraseFromParent();
206   return true;
207 }
208
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());
213   if (!Opcode)
214     return false;
215
216   MI->setDesc(TII->get(Opcode));
217   MachineInstrBuilder(*MI->getParent()->getParent(), MI)
218     .addReg(SystemZ::CC, RegState::ImplicitDefine);
219   return true;
220 }
221
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;
233
234   // See which compare-style condition codes are available.
235   unsigned ReusableCCMask = SystemZII::getCompareZeroCCMask(MIFlags);
236
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;
241
242   if (ReusableCCMask == 0)
243     return false;
244
245   unsigned CCValues = SystemZII::getCCValues(MIFlags);
246   assert((ReusableCCMask & ~CCValues) == 0 && "Invalid CCValues");
247
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];
252
253     // Fail if this isn't a use of CC that we understand.
254     unsigned Flags = MI->getDesc().TSFlags;
255     unsigned FirstOpNum;
256     if (Flags & SystemZII::CCMaskFirst)
257       FirstOpNum = 0;
258     else if (Flags & SystemZII::CCMaskLast)
259       FirstOpNum = MI->getNumExplicitOperands() - 2;
260     else
261       return false;
262
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)
271       return false;
272
273     AlterMasks.push_back(&MI->getOperand(FirstOpNum));
274     AlterMasks.push_back(&MI->getOperand(FirstOpNum + 1));
275   }
276
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));
284   }
285
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);
290
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);
295
296   return true;
297 }
298
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:
305     return true;
306
307   default:
308     return (Compare->getNumExplicitOperands() == 2 &&
309             Compare->getOperand(1).isImm() &&
310             Compare->getOperand(1).getImm() == 0);
311   }
312 }
313
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))
322     return false;
323
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();
328   Reference CCRefs;
329   Reference SrcRefs;
330   while (MBBI != MBBE) {
331     --MBBI;
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
336       // Compare.
337       if (!CCRefs.Use && !SrcRefs && convertToBRCT(MI, Compare, CCUsers)) {
338         BranchOnCounts += 1;
339         return true;
340       }
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;
345         return true;
346       }
347     }
348     SrcRefs |= getRegReferences(MI, SrcReg);
349     if (SrcRefs.Def)
350       return false;
351     CCRefs |= getRegReferences(MI, SystemZ::CC);
352     if (CCRefs.Use && CCRefs.Def)
353       return false;
354   }
355   return false;
356 }
357
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(),
365                                                   Compare);
366   if (!FusedOpcode)
367     return false;
368
369   // See whether we have a single branch with which to fuse.
370   if (CCUsers.size() != 1)
371     return false;
372   MachineInstr *Branch = CCUsers[0];
373   if (Branch->getOpcode() != SystemZ::BRC)
374     return false;
375
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)))
384       return false;
385
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");
391
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);
399
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))
405     .addOperand(CCMask)
406     .addOperand(Target)
407     .addReg(SystemZ::CC, RegState::ImplicitDefine);
408
409   // Clear any intervening kills of SrcReg and SrcReg2.
410   MBBI = Compare;
411   for (++MBBI; MBBI != MBBE; ++MBBI) {
412     MBBI->clearRegisterKills(SrcReg, TRI);
413     if (SrcReg2)
414       MBBI->clearRegisterKills(SrcReg2, TRI);
415   }
416   FusedComparisons += 1;
417   return true;
418 }
419
420 // Process all comparison instructions in MBB.  Return true if something
421 // changed.
422 bool SystemZElimCompare::processBlock(MachineBasicBlock &MBB) {
423   bool Changed = false;
424
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 &&
434         MI->isCompare() &&
435         (optimizeCompareZero(MI, CCUsers) ||
436          fuseCompareAndBranch(MI, CCUsers))) {
437       ++MBBI;
438       MI->eraseFromParent();
439       Changed = true;
440       CCUsers.clear();
441       continue;
442     }
443
444     Reference CCRefs(getRegReferences(MI, SystemZ::CC));
445     if (CCRefs.Def) {
446       CCUsers.clear();
447       CompleteCCUsers = true;
448     }
449     if (CompleteCCUsers && CCRefs.Use)
450       CCUsers.push_back(MI);
451   }
452   return Changed;
453 }
454
455 bool SystemZElimCompare::runOnMachineFunction(MachineFunction &F) {
456   TII = static_cast<const SystemZInstrInfo *>(F.getSubtarget().getInstrInfo());
457   TRI = &TII->getRegisterInfo();
458
459   bool Changed = false;
460   for (auto &MBB : F)
461     Changed |= processBlock(MBB);
462
463   return Changed;
464 }