1//===-- HexagonPeephole.cpp - Hexagon Peephole Optimiztions ---------------===//
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// This peephole pass optimizes in the following cases.
9// 1. Optimizes redundant sign extends for the following case
10//    Transform the following pattern
11//    %vreg170<def> = SXTW %vreg166
12//    ...
13//    %vreg176<def> = COPY %vreg170:subreg_loreg
14//
15//    Into
16//    %vreg176<def> = COPY vreg166
17//
18//  2. Optimizes redundant negation of predicates.
19//     %vreg15<def> = CMPGTrr %vreg6, %vreg2
20//     ...
21//     %vreg16<def> = NOT_p %vreg15<kill>
22//     ...
23//     JMP_c %vreg16<kill>, <BB#1>, %PC<imp-def,dead>
24//
25//     Into
26//     %vreg15<def> = CMPGTrr %vreg6, %vreg2;
27//     ...
28//     JMP_cNot %vreg15<kill>, <BB#1>, %PC<imp-def,dead>;
29//
30// Note: The peephole pass makes the instrucstions like
31// %vreg170<def> = SXTW %vreg166 or %vreg16<def> = NOT_p %vreg15<kill>
32// redundant and relies on some form of dead removal instrucions, like
33// DCE or DIE to actually eliminate them.
34
35
36//===----------------------------------------------------------------------===//
37
38#define DEBUG_TYPE "hexagon-peephole"
39#include "Hexagon.h"
40#include "HexagonTargetMachine.h"
41#include "llvm/Constants.h"
42#include "llvm/PassSupport.h"
43#include "llvm/ADT/DenseMap.h"
44#include "llvm/ADT/Statistic.h"
45#include "llvm/CodeGen/Passes.h"
46#include "llvm/CodeGen/MachineFunction.h"
47#include "llvm/CodeGen/MachineFunctionPass.h"
48#include "llvm/CodeGen/MachineInstrBuilder.h"
49#include "llvm/CodeGen/MachineRegisterInfo.h"
50#include "llvm/Support/CommandLine.h"
51#include "llvm/Support/Debug.h"
52#include "llvm/Support/raw_ostream.h"
53#include "llvm/Target/TargetMachine.h"
54#include "llvm/Target/TargetRegisterInfo.h"
55#include "llvm/Target/TargetInstrInfo.h"
56#include <algorithm>
57
58using namespace llvm;
59
60static cl::opt<bool> DisableHexagonPeephole("disable-hexagon-peephole",
61    cl::Hidden, cl::ZeroOrMore, cl::init(false),
62    cl::desc("Disable Peephole Optimization"));
63
64static cl::opt<int>
65DbgPNPCount("pnp-count", cl::init(-1), cl::Hidden,
66  cl::desc("Maximum number of P=NOT(P) to be optimized"));
67
68static cl::opt<bool> DisablePNotP("disable-hexagon-pnotp",
69    cl::Hidden, cl::ZeroOrMore, cl::init(false),
70    cl::desc("Disable Optimization of PNotP"));
71
72static cl::opt<bool> DisableOptSZExt("disable-hexagon-optszext",
73    cl::Hidden, cl::ZeroOrMore, cl::init(false),
74    cl::desc("Disable Optimization of Sign/Zero Extends"));
75
76namespace {
77  struct HexagonPeephole : public MachineFunctionPass {
78    const HexagonInstrInfo    *QII;
79    const HexagonRegisterInfo *QRI;
80    const MachineRegisterInfo *MRI;
81
82  public:
83    static char ID;
84    HexagonPeephole() : MachineFunctionPass(ID) { }
85
86    bool runOnMachineFunction(MachineFunction &MF);
87
88    const char *getPassName() const {
89      return "Hexagon optimize redundant zero and size extends";
90    }
91
92    void getAnalysisUsage(AnalysisUsage &AU) const {
93      MachineFunctionPass::getAnalysisUsage(AU);
94    }
95
96  private:
97    void ChangeOpInto(MachineOperand &Dst, MachineOperand &Src);
98  };
99}
100
101char HexagonPeephole::ID = 0;
102
103bool HexagonPeephole::runOnMachineFunction(MachineFunction &MF) {
104
105  QII = static_cast<const HexagonInstrInfo *>(MF.getTarget().
106                                        getInstrInfo());
107  QRI = static_cast<const HexagonRegisterInfo *>(MF.getTarget().
108                                       getRegisterInfo());
109  MRI = &MF.getRegInfo();
110
111  DenseMap<unsigned, unsigned> PeepholeMap;
112  DenseMap<unsigned, std::pair<unsigned, unsigned> > PeepholeDoubleRegsMap;
113
114  if (DisableHexagonPeephole) return false;
115
116  // Loop over all of the basic blocks.
117  for (MachineFunction::iterator MBBb = MF.begin(), MBBe = MF.end();
118       MBBb != MBBe; ++MBBb) {
119    MachineBasicBlock* MBB = MBBb;
120    PeepholeMap.clear();
121    PeepholeDoubleRegsMap.clear();
122
123    // Traverse the basic block.
124    for (MachineBasicBlock::iterator MII = MBB->begin(); MII != MBB->end();
125                                     ++MII) {
126      MachineInstr *MI = MII;
127      // Look for sign extends:
128      // %vreg170<def> = SXTW %vreg166
129      if (!DisableOptSZExt && MI->getOpcode() == Hexagon::SXTW) {
130        assert (MI->getNumOperands() == 2);
131        MachineOperand &Dst = MI->getOperand(0);
132        MachineOperand &Src  = MI->getOperand(1);
133        unsigned DstReg = Dst.getReg();
134        unsigned SrcReg = Src.getReg();
135        // Just handle virtual registers.
136        if (TargetRegisterInfo::isVirtualRegister(DstReg) &&
137            TargetRegisterInfo::isVirtualRegister(SrcReg)) {
138          // Map the following:
139          // %vreg170<def> = SXTW %vreg166
140          // PeepholeMap[170] = vreg166
141          PeepholeMap[DstReg] = SrcReg;
142        }
143      }
144
145      // Look for this sequence below
146      // %vregDoubleReg1 = LSRd_ri %vregDoubleReg0, 32
147      // %vregIntReg = COPY %vregDoubleReg1:subreg_loreg.
148      // and convert into
149      // %vregIntReg = COPY %vregDoubleReg0:subreg_hireg.
150      if (MI->getOpcode() == Hexagon::LSRd_ri) {
151        assert(MI->getNumOperands() == 3);
152        MachineOperand &Dst = MI->getOperand(0);
153        MachineOperand &Src1 = MI->getOperand(1);
154        MachineOperand &Src2 = MI->getOperand(2);
155        if (Src2.getImm() != 32)
156          continue;
157        unsigned DstReg = Dst.getReg();
158        unsigned SrcReg = Src1.getReg();
159        PeepholeDoubleRegsMap[DstReg] =
160          std::make_pair(*&SrcReg, 1/*Hexagon::subreg_hireg*/);
161      }
162
163      // Look for P=NOT(P).
164      if (!DisablePNotP &&
165          (MI->getOpcode() == Hexagon::NOT_p)) {
166        assert (MI->getNumOperands() == 2);
167        MachineOperand &Dst = MI->getOperand(0);
168        MachineOperand &Src  = MI->getOperand(1);
169        unsigned DstReg = Dst.getReg();
170        unsigned SrcReg = Src.getReg();
171        // Just handle virtual registers.
172        if (TargetRegisterInfo::isVirtualRegister(DstReg) &&
173            TargetRegisterInfo::isVirtualRegister(SrcReg)) {
174          // Map the following:
175          // %vreg170<def> = NOT_xx %vreg166
176          // PeepholeMap[170] = vreg166
177          PeepholeMap[DstReg] = SrcReg;
178        }
179      }
180
181      // Look for copy:
182      // %vreg176<def> = COPY %vreg170:subreg_loreg
183      if (!DisableOptSZExt && MI->isCopy()) {
184        assert (MI->getNumOperands() == 2);
185        MachineOperand &Dst = MI->getOperand(0);
186        MachineOperand &Src  = MI->getOperand(1);
187
188        // Make sure we are copying the lower 32 bits.
189        if (Src.getSubReg() != Hexagon::subreg_loreg)
190          continue;
191
192        unsigned DstReg = Dst.getReg();
193        unsigned SrcReg = Src.getReg();
194        if (TargetRegisterInfo::isVirtualRegister(DstReg) &&
195            TargetRegisterInfo::isVirtualRegister(SrcReg)) {
196          // Try to find in the map.
197          if (unsigned PeepholeSrc = PeepholeMap.lookup(SrcReg)) {
198            // Change the 1st operand.
199            MI->RemoveOperand(1);
200            MI->addOperand(MachineOperand::CreateReg(PeepholeSrc, false));
201          } else  {
202            DenseMap<unsigned, std::pair<unsigned, unsigned> >::iterator DI =
203              PeepholeDoubleRegsMap.find(SrcReg);
204            if (DI != PeepholeDoubleRegsMap.end()) {
205              std::pair<unsigned,unsigned> PeepholeSrc = DI->second;
206              MI->RemoveOperand(1);
207              MI->addOperand(MachineOperand::CreateReg(PeepholeSrc.first,
208                                                       false /*isDef*/,
209                                                       false /*isImp*/,
210                                                       false /*isKill*/,
211                                                       false /*isDead*/,
212                                                       false /*isUndef*/,
213                                                       false /*isEarlyClobber*/,
214                                                       PeepholeSrc.second));
215            }
216          }
217        }
218      }
219
220      // Look for Predicated instructions.
221      if (!DisablePNotP) {
222        bool Done = false;
223        if (QII->isPredicated(MI)) {
224          MachineOperand &Op0 = MI->getOperand(0);
225          unsigned Reg0 = Op0.getReg();
226          const TargetRegisterClass *RC0 = MRI->getRegClass(Reg0);
227          if (RC0->getID() == Hexagon::PredRegsRegClassID) {
228            // Handle instructions that have a prediate register in op0
229            // (most cases of predicable instructions).
230            if (TargetRegisterInfo::isVirtualRegister(Reg0)) {
231              // Try to find in the map.
232              if (unsigned PeepholeSrc = PeepholeMap.lookup(Reg0)) {
233                // Change the 1st operand and, flip the opcode.
234                MI->getOperand(0).setReg(PeepholeSrc);
235                int NewOp = QII->getInvertedPredicatedOpcode(MI->getOpcode());
236                MI->setDesc(QII->get(NewOp));
237                Done = true;
238              }
239            }
240          }
241        }
242
243        if (!Done) {
244          // Handle special instructions.
245          unsigned Op = MI->getOpcode();
246          unsigned NewOp = 0;
247          unsigned PR = 1, S1 = 2, S2 = 3;   // Operand indices.
248
249          switch (Op) {
250            case Hexagon::TFR_condset_rr:
251            case Hexagon::TFR_condset_ii:
252            case Hexagon::MUX_ii:
253            case Hexagon::MUX_rr:
254              NewOp = Op;
255              break;
256            case Hexagon::TFR_condset_ri:
257              NewOp = Hexagon::TFR_condset_ir;
258              break;
259            case Hexagon::TFR_condset_ir:
260              NewOp = Hexagon::TFR_condset_ri;
261              break;
262            case Hexagon::MUX_ri:
263              NewOp = Hexagon::MUX_ir;
264              break;
265            case Hexagon::MUX_ir:
266              NewOp = Hexagon::MUX_ri;
267              break;
268          }
269          if (NewOp) {
270            unsigned PSrc = MI->getOperand(PR).getReg();
271            if (unsigned POrig = PeepholeMap.lookup(PSrc)) {
272              MI->getOperand(PR).setReg(POrig);
273              MI->setDesc(QII->get(NewOp));
274              // Swap operands S1 and S2.
275              MachineOperand Op1 = MI->getOperand(S1);
276              MachineOperand Op2 = MI->getOperand(S2);
277              ChangeOpInto(MI->getOperand(S1), Op2);
278              ChangeOpInto(MI->getOperand(S2), Op1);
279            }
280          } // if (NewOp)
281        } // if (!Done)
282
283      } // if (!DisablePNotP)
284
285    } // Instruction
286  } // Basic Block
287  return true;
288}
289
290void HexagonPeephole::ChangeOpInto(MachineOperand &Dst, MachineOperand &Src) {
291  assert (&Dst != &Src && "Cannot duplicate into itself");
292  switch (Dst.getType()) {
293    case MachineOperand::MO_Register:
294      if (Src.isReg()) {
295        Dst.setReg(Src.getReg());
296      } else if (Src.isImm()) {
297        Dst.ChangeToImmediate(Src.getImm());
298      } else {
299        llvm_unreachable("Unexpected src operand type");
300      }
301      break;
302
303    case MachineOperand::MO_Immediate:
304      if (Src.isImm()) {
305        Dst.setImm(Src.getImm());
306      } else if (Src.isReg()) {
307        Dst.ChangeToRegister(Src.getReg(), Src.isDef(), Src.isImplicit(),
308                             Src.isKill(), Src.isDead(), Src.isUndef(),
309                             Src.isDebug());
310      } else {
311        llvm_unreachable("Unexpected src operand type");
312      }
313      break;
314
315    default:
316      llvm_unreachable("Unexpected dst operand type");
317      break;
318  }
319}
320
321FunctionPass *llvm::createHexagonPeephole() {
322  return new HexagonPeephole();
323}
324