Thumb2SizeReduction.cpp revision e837dead3c8dc3445ef6a0e2322179c57e264a13
1//===-- Thumb2SizeReduction.cpp - Thumb2 code size reduction pass -*- C++ -*-=//
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#define DEBUG_TYPE "t2-reduce-size"
11#include "ARM.h"
12#include "ARMAddressingModes.h"
13#include "ARMBaseRegisterInfo.h"
14#include "ARMBaseInstrInfo.h"
15#include "ARMSubtarget.h"
16#include "Thumb2InstrInfo.h"
17#include "llvm/CodeGen/MachineInstr.h"
18#include "llvm/CodeGen/MachineInstrBuilder.h"
19#include "llvm/CodeGen/MachineFunctionPass.h"
20#include "llvm/Support/CommandLine.h"
21#include "llvm/Support/Debug.h"
22#include "llvm/Support/raw_ostream.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/Statistic.h"
25using namespace llvm;
26
27STATISTIC(NumNarrows,  "Number of 32-bit instrs reduced to 16-bit ones");
28STATISTIC(Num2Addrs,   "Number of 32-bit instrs reduced to 2addr 16-bit ones");
29STATISTIC(NumLdSts,    "Number of 32-bit load / store reduced to 16-bit ones");
30
31static cl::opt<int> ReduceLimit("t2-reduce-limit",
32                                cl::init(-1), cl::Hidden);
33static cl::opt<int> ReduceLimit2Addr("t2-reduce-limit2",
34                                     cl::init(-1), cl::Hidden);
35static cl::opt<int> ReduceLimitLdSt("t2-reduce-limit3",
36                                     cl::init(-1), cl::Hidden);
37
38namespace {
39  /// ReduceTable - A static table with information on mapping from wide
40  /// opcodes to narrow
41  struct ReduceEntry {
42    unsigned WideOpc;      // Wide opcode
43    unsigned NarrowOpc1;   // Narrow opcode to transform to
44    unsigned NarrowOpc2;   // Narrow opcode when it's two-address
45    uint8_t  Imm1Limit;    // Limit of immediate field (bits)
46    uint8_t  Imm2Limit;    // Limit of immediate field when it's two-address
47    unsigned LowRegs1 : 1; // Only possible if low-registers are used
48    unsigned LowRegs2 : 1; // Only possible if low-registers are used (2addr)
49    unsigned PredCC1  : 2; // 0 - If predicated, cc is on and vice versa.
50                           // 1 - No cc field.
51                           // 2 - Always set CPSR.
52    unsigned PredCC2  : 2;
53    unsigned PartFlag : 1; // 16-bit instruction does partial flag update
54    unsigned Special  : 1; // Needs to be dealt with specially
55  };
56
57  static const ReduceEntry ReduceTable[] = {
58    // Wide,        Narrow1,      Narrow2,     imm1,imm2,  lo1, lo2, P/C, PF, S
59    { ARM::t2ADCrr, 0,            ARM::tADC,     0,   0,    0,   1,  0,0, 0,0 },
60    { ARM::t2ADDri, ARM::tADDi3,  ARM::tADDi8,   3,   8,    1,   1,  0,0, 0,0 },
61    { ARM::t2ADDrr, ARM::tADDrr,  ARM::tADDhirr, 0,   0,    1,   0,  0,1, 0,0 },
62    // Note: immediate scale is 4.
63    { ARM::t2ADDrSPi,ARM::tADDrSPi,0,            8,   0,    1,   0,  1,0, 0,1 },
64    { ARM::t2ADDSri,ARM::tADDi3,  ARM::tADDi8,   3,   8,    1,   1,  2,2, 0,1 },
65    { ARM::t2ADDSrr,ARM::tADDrr,  0,             0,   0,    1,   0,  2,0, 0,1 },
66    { ARM::t2ANDrr, 0,            ARM::tAND,     0,   0,    0,   1,  0,0, 1,0 },
67    { ARM::t2ASRri, ARM::tASRri,  0,             5,   0,    1,   0,  0,0, 1,0 },
68    { ARM::t2ASRrr, 0,            ARM::tASRrr,   0,   0,    0,   1,  0,0, 1,0 },
69    { ARM::t2BICrr, 0,            ARM::tBIC,     0,   0,    0,   1,  0,0, 1,0 },
70    //FIXME: Disable CMN, as CCodes are backwards from compare expectations
71    //{ ARM::t2CMNrr, ARM::tCMN,  0,             0,   0,    1,   0,  2,0, 0,0 },
72    { ARM::t2CMPri, ARM::tCMPi8,  0,             8,   0,    1,   0,  2,0, 0,0 },
73    { ARM::t2CMPrr, ARM::tCMPhir, 0,             0,   0,    0,   0,  2,0, 0,1 },
74    { ARM::t2EORrr, 0,            ARM::tEOR,     0,   0,    0,   1,  0,0, 1,0 },
75    // FIXME: adr.n immediate offset must be multiple of 4.
76    //{ ARM::t2LEApcrelJT,ARM::tLEApcrelJT, 0,   0,   0,    1,   0,  1,0, 0,0 },
77    { ARM::t2LSLri, ARM::tLSLri,  0,             5,   0,    1,   0,  0,0, 1,0 },
78    { ARM::t2LSLrr, 0,            ARM::tLSLrr,   0,   0,    0,   1,  0,0, 1,0 },
79    { ARM::t2LSRri, ARM::tLSRri,  0,             5,   0,    1,   0,  0,0, 1,0 },
80    { ARM::t2LSRrr, 0,            ARM::tLSRrr,   0,   0,    0,   1,  0,0, 1,0 },
81    // FIXME: tMOVi8 and tMVN also partially update CPSR but they are less
82    // likely to cause issue in the loop. As a size / performance workaround,
83    // they are not marked as such.
84    { ARM::t2MOVi,  ARM::tMOVi8,  0,             8,   0,    1,   0,  0,0, 0,0 },
85    { ARM::t2MOVi16,ARM::tMOVi8,  0,             8,   0,    1,   0,  0,0, 0,1 },
86    // FIXME: Do we need the 16-bit 'S' variant?
87    { ARM::t2MOVr,ARM::tMOVgpr2gpr,0,            0,   0,    0,   0,  1,0, 0,0 },
88    { ARM::t2MOVCCr,0,            ARM::tMOVCCr,  0,   0,    0,   0,  0,1, 0,0 },
89    { ARM::t2MOVCCi,0,            ARM::tMOVCCi,  0,   8,    0,   1,  0,1, 0,0 },
90    { ARM::t2MUL,   0,            ARM::tMUL,     0,   0,    0,   1,  0,0, 1,0 },
91    { ARM::t2MVNr,  ARM::tMVN,    0,             0,   0,    1,   0,  0,0, 0,0 },
92    { ARM::t2ORRrr, 0,            ARM::tORR,     0,   0,    0,   1,  0,0, 1,0 },
93    { ARM::t2REV,   ARM::tREV,    0,             0,   0,    1,   0,  1,0, 0,0 },
94    { ARM::t2REV16, ARM::tREV16,  0,             0,   0,    1,   0,  1,0, 0,0 },
95    { ARM::t2REVSH, ARM::tREVSH,  0,             0,   0,    1,   0,  1,0, 0,0 },
96    { ARM::t2RORrr, 0,            ARM::tROR,     0,   0,    0,   1,  0,0, 1,0 },
97    { ARM::t2RSBri, ARM::tRSB,    0,             0,   0,    1,   0,  0,0, 0,1 },
98    { ARM::t2RSBSri,ARM::tRSB,    0,             0,   0,    1,   0,  2,0, 0,1 },
99    { ARM::t2SBCrr, 0,            ARM::tSBC,     0,   0,    0,   1,  0,0, 0,0 },
100    { ARM::t2SUBri, ARM::tSUBi3,  ARM::tSUBi8,   3,   8,    1,   1,  0,0, 0,0 },
101    { ARM::t2SUBrr, ARM::tSUBrr,  0,             0,   0,    1,   0,  0,0, 0,0 },
102    { ARM::t2SUBSri,ARM::tSUBi3,  ARM::tSUBi8,   3,   8,    1,   1,  2,2, 0,0 },
103    { ARM::t2SUBSrr,ARM::tSUBrr,  0,             0,   0,    1,   0,  2,0, 0,0 },
104    { ARM::t2SXTBr, ARM::tSXTB,   0,             0,   0,    1,   0,  1,0, 0,0 },
105    { ARM::t2SXTHr, ARM::tSXTH,   0,             0,   0,    1,   0,  1,0, 0,0 },
106    { ARM::t2TSTrr, ARM::tTST,    0,             0,   0,    1,   0,  2,0, 0,0 },
107    { ARM::t2UXTBr, ARM::tUXTB,   0,             0,   0,    1,   0,  1,0, 0,0 },
108    { ARM::t2UXTHr, ARM::tUXTH,   0,             0,   0,    1,   0,  1,0, 0,0 },
109
110    // FIXME: Clean this up after splitting each Thumb load / store opcode
111    // into multiple ones.
112    { ARM::t2LDRi12,ARM::tLDRi,   ARM::tLDRspi,  5,   8,    1,   0,  0,0, 0,1 },
113    { ARM::t2LDRs,  ARM::tLDRr,   0,             0,   0,    1,   0,  0,0, 0,1 },
114    { ARM::t2LDRBi12,ARM::tLDRBi, 0,             5,   0,    1,   0,  0,0, 0,1 },
115    { ARM::t2LDRBs, ARM::tLDRBr,  0,             0,   0,    1,   0,  0,0, 0,1 },
116    { ARM::t2LDRHi12,ARM::tLDRHi, 0,             5,   0,    1,   0,  0,0, 0,1 },
117    { ARM::t2LDRHs, ARM::tLDRHr,  0,             0,   0,    1,   0,  0,0, 0,1 },
118    { ARM::t2LDRSBs,ARM::tLDRSB,  0,             0,   0,    1,   0,  0,0, 0,1 },
119    { ARM::t2LDRSHs,ARM::tLDRSH,  0,             0,   0,    1,   0,  0,0, 0,1 },
120    { ARM::t2STRi12,ARM::tSTRi,   ARM::tSTRspi,  5,   8,    1,   0,  0,0, 0,1 },
121    { ARM::t2STRs,  ARM::tSTRr,   0,             0,   0,    1,   0,  0,0, 0,1 },
122    { ARM::t2STRBi12,ARM::tSTRBi, 0,             5,   0,    1,   0,  0,0, 0,1 },
123    { ARM::t2STRBs, ARM::tSTRBr,  0,             0,   0,    1,   0,  0,0, 0,1 },
124    { ARM::t2STRHi12,ARM::tSTRHi, 0,             5,   0,    1,   0,  0,0, 0,1 },
125    { ARM::t2STRHs, ARM::tSTRHr,  0,             0,   0,    1,   0,  0,0, 0,1 },
126
127    { ARM::t2LDMIA, ARM::tLDMIA,  0,             0,   0,    1,   1,  1,1, 0,1 },
128    { ARM::t2LDMIA_RET,0,         ARM::tPOP_RET, 0,   0,    1,   1,  1,1, 0,1 },
129    { ARM::t2LDMIA_UPD,ARM::tLDMIA_UPD,ARM::tPOP,0,   0,    1,   1,  1,1, 0,1 },
130    // ARM::t2STM (with no basereg writeback) has no Thumb1 equivalent
131    { ARM::t2STMIA_UPD,ARM::tSTMIA_UPD, 0,       0,   0,    1,   1,  1,1, 0,1 },
132    { ARM::t2STMDB_UPD, 0,        ARM::tPUSH,    0,   0,    1,   1,  1,1, 0,1 },
133  };
134
135  class Thumb2SizeReduce : public MachineFunctionPass {
136  public:
137    static char ID;
138    Thumb2SizeReduce();
139
140    const Thumb2InstrInfo *TII;
141    const ARMSubtarget *STI;
142
143    virtual bool runOnMachineFunction(MachineFunction &MF);
144
145    virtual const char *getPassName() const {
146      return "Thumb2 instruction size reduction pass";
147    }
148
149  private:
150    /// ReduceOpcodeMap - Maps wide opcode to index of entry in ReduceTable.
151    DenseMap<unsigned, unsigned> ReduceOpcodeMap;
152
153    bool canAddPseudoFlagDep(MachineInstr *Def, MachineInstr *Use);
154
155    bool VerifyPredAndCC(MachineInstr *MI, const ReduceEntry &Entry,
156                         bool is2Addr, ARMCC::CondCodes Pred,
157                         bool LiveCPSR, bool &HasCC, bool &CCDead);
158
159    bool ReduceLoadStore(MachineBasicBlock &MBB, MachineInstr *MI,
160                         const ReduceEntry &Entry);
161
162    bool ReduceSpecial(MachineBasicBlock &MBB, MachineInstr *MI,
163                       const ReduceEntry &Entry, bool LiveCPSR,
164                       MachineInstr *CPSRDef);
165
166    /// ReduceTo2Addr - Reduce a 32-bit instruction to a 16-bit two-address
167    /// instruction.
168    bool ReduceTo2Addr(MachineBasicBlock &MBB, MachineInstr *MI,
169                       const ReduceEntry &Entry,
170                       bool LiveCPSR, MachineInstr *CPSRDef);
171
172    /// ReduceToNarrow - Reduce a 32-bit instruction to a 16-bit
173    /// non-two-address instruction.
174    bool ReduceToNarrow(MachineBasicBlock &MBB, MachineInstr *MI,
175                        const ReduceEntry &Entry,
176                        bool LiveCPSR, MachineInstr *CPSRDef);
177
178    /// ReduceMBB - Reduce width of instructions in the specified basic block.
179    bool ReduceMBB(MachineBasicBlock &MBB);
180  };
181  char Thumb2SizeReduce::ID = 0;
182}
183
184Thumb2SizeReduce::Thumb2SizeReduce() : MachineFunctionPass(ID) {
185  for (unsigned i = 0, e = array_lengthof(ReduceTable); i != e; ++i) {
186    unsigned FromOpc = ReduceTable[i].WideOpc;
187    if (!ReduceOpcodeMap.insert(std::make_pair(FromOpc, i)).second)
188      assert(false && "Duplicated entries?");
189  }
190}
191
192static bool HasImplicitCPSRDef(const MCInstrDesc &MCID) {
193  for (const unsigned *Regs = MCID.ImplicitDefs; *Regs; ++Regs)
194    if (*Regs == ARM::CPSR)
195      return true;
196  return false;
197}
198
199/// canAddPseudoFlagDep - For A9 (and other out-of-order) implementations,
200/// the 's' 16-bit instruction partially update CPSR. Abort the
201/// transformation to avoid adding false dependency on last CPSR setting
202/// instruction which hurts the ability for out-of-order execution engine
203/// to do register renaming magic.
204/// This function checks if there is a read-of-write dependency between the
205/// last instruction that defines the CPSR and the current instruction. If there
206/// is, then there is no harm done since the instruction cannot be retired
207/// before the CPSR setting instruction anyway.
208/// Note, we are not doing full dependency analysis here for the sake of compile
209/// time. We're not looking for cases like:
210/// r0 = muls ...
211/// r1 = add.w r0, ...
212/// ...
213///    = mul.w r1
214/// In this case it would have been ok to narrow the mul.w to muls since there
215/// are indirect RAW dependency between the muls and the mul.w
216bool
217Thumb2SizeReduce::canAddPseudoFlagDep(MachineInstr *Def, MachineInstr *Use) {
218  if (!Def || !STI->avoidCPSRPartialUpdate())
219    return false;
220
221  SmallSet<unsigned, 2> Defs;
222  for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
223    const MachineOperand &MO = Def->getOperand(i);
224    if (!MO.isReg() || MO.isUndef() || MO.isUse())
225      continue;
226    unsigned Reg = MO.getReg();
227    if (Reg == 0 || Reg == ARM::CPSR)
228      continue;
229    Defs.insert(Reg);
230  }
231
232  for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
233    const MachineOperand &MO = Use->getOperand(i);
234    if (!MO.isReg() || MO.isUndef() || MO.isDef())
235      continue;
236    unsigned Reg = MO.getReg();
237    if (Defs.count(Reg))
238      return false;
239  }
240
241  // No read-after-write dependency. The narrowing will add false dependency.
242  return true;
243}
244
245bool
246Thumb2SizeReduce::VerifyPredAndCC(MachineInstr *MI, const ReduceEntry &Entry,
247                                  bool is2Addr, ARMCC::CondCodes Pred,
248                                  bool LiveCPSR, bool &HasCC, bool &CCDead) {
249  if ((is2Addr  && Entry.PredCC2 == 0) ||
250      (!is2Addr && Entry.PredCC1 == 0)) {
251    if (Pred == ARMCC::AL) {
252      // Not predicated, must set CPSR.
253      if (!HasCC) {
254        // Original instruction was not setting CPSR, but CPSR is not
255        // currently live anyway. It's ok to set it. The CPSR def is
256        // dead though.
257        if (!LiveCPSR) {
258          HasCC = true;
259          CCDead = true;
260          return true;
261        }
262        return false;
263      }
264    } else {
265      // Predicated, must not set CPSR.
266      if (HasCC)
267        return false;
268    }
269  } else if ((is2Addr  && Entry.PredCC2 == 2) ||
270             (!is2Addr && Entry.PredCC1 == 2)) {
271    /// Old opcode has an optional def of CPSR.
272    if (HasCC)
273      return true;
274    // If old opcode does not implicitly define CPSR, then it's not ok since
275    // these new opcodes' CPSR def is not meant to be thrown away. e.g. CMP.
276    if (!HasImplicitCPSRDef(MI->getDesc()))
277      return false;
278    HasCC = true;
279  } else {
280    // 16-bit instruction does not set CPSR.
281    if (HasCC)
282      return false;
283  }
284
285  return true;
286}
287
288static bool VerifyLowRegs(MachineInstr *MI) {
289  unsigned Opc = MI->getOpcode();
290  bool isPCOk = (Opc == ARM::t2LDMIA_RET || Opc == ARM::t2LDMIA     ||
291                 Opc == ARM::t2LDMDB     || Opc == ARM::t2LDMIA_UPD ||
292                 Opc == ARM::t2LDMDB_UPD);
293  bool isLROk = (Opc == ARM::t2STMIA_UPD || Opc == ARM::t2STMDB_UPD);
294  bool isSPOk = isPCOk || isLROk || (Opc == ARM::t2ADDrSPi);
295  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
296    const MachineOperand &MO = MI->getOperand(i);
297    if (!MO.isReg() || MO.isImplicit())
298      continue;
299    unsigned Reg = MO.getReg();
300    if (Reg == 0 || Reg == ARM::CPSR)
301      continue;
302    if (isPCOk && Reg == ARM::PC)
303      continue;
304    if (isLROk && Reg == ARM::LR)
305      continue;
306    if (Reg == ARM::SP) {
307      if (isSPOk)
308        continue;
309      if (i == 1 && (Opc == ARM::t2LDRi12 || Opc == ARM::t2STRi12))
310        // Special case for these ldr / str with sp as base register.
311        continue;
312    }
313    if (!isARMLowRegister(Reg))
314      return false;
315  }
316  return true;
317}
318
319bool
320Thumb2SizeReduce::ReduceLoadStore(MachineBasicBlock &MBB, MachineInstr *MI,
321                                  const ReduceEntry &Entry) {
322  if (ReduceLimitLdSt != -1 && ((int)NumLdSts >= ReduceLimitLdSt))
323    return false;
324
325  unsigned Scale = 1;
326  bool HasImmOffset = false;
327  bool HasShift = false;
328  bool HasOffReg = true;
329  bool isLdStMul = false;
330  unsigned Opc = Entry.NarrowOpc1;
331  unsigned OpNum = 3; // First 'rest' of operands.
332  uint8_t  ImmLimit = Entry.Imm1Limit;
333
334  switch (Entry.WideOpc) {
335  default:
336    llvm_unreachable("Unexpected Thumb2 load / store opcode!");
337  case ARM::t2LDRi12:
338  case ARM::t2STRi12:
339    if (MI->getOperand(1).getReg() == ARM::SP) {
340      Opc = Entry.NarrowOpc2;
341      ImmLimit = Entry.Imm2Limit;
342      HasOffReg = false;
343    }
344
345    Scale = 4;
346    HasImmOffset = true;
347    HasOffReg = false;
348    break;
349  case ARM::t2LDRBi12:
350  case ARM::t2STRBi12:
351    HasImmOffset = true;
352    HasOffReg = false;
353    break;
354  case ARM::t2LDRHi12:
355  case ARM::t2STRHi12:
356    Scale = 2;
357    HasImmOffset = true;
358    HasOffReg = false;
359    break;
360  case ARM::t2LDRs:
361  case ARM::t2LDRBs:
362  case ARM::t2LDRHs:
363  case ARM::t2LDRSBs:
364  case ARM::t2LDRSHs:
365  case ARM::t2STRs:
366  case ARM::t2STRBs:
367  case ARM::t2STRHs:
368    HasShift = true;
369    OpNum = 4;
370    break;
371  case ARM::t2LDMIA:
372  case ARM::t2LDMDB: {
373    unsigned BaseReg = MI->getOperand(0).getReg();
374    if (!isARMLowRegister(BaseReg) || Entry.WideOpc != ARM::t2LDMIA)
375      return false;
376
377    // For the non-writeback version (this one), the base register must be
378    // one of the registers being loaded.
379    bool isOK = false;
380    for (unsigned i = 4; i < MI->getNumOperands(); ++i) {
381      if (MI->getOperand(i).getReg() == BaseReg) {
382        isOK = true;
383        break;
384      }
385    }
386
387    if (!isOK)
388      return false;
389
390    OpNum = 0;
391    isLdStMul = true;
392    break;
393  }
394  case ARM::t2LDMIA_RET: {
395    unsigned BaseReg = MI->getOperand(1).getReg();
396    if (BaseReg != ARM::SP)
397      return false;
398    Opc = Entry.NarrowOpc2; // tPOP_RET
399    OpNum = 2;
400    isLdStMul = true;
401    break;
402  }
403  case ARM::t2LDMIA_UPD:
404  case ARM::t2LDMDB_UPD:
405  case ARM::t2STMIA_UPD:
406  case ARM::t2STMDB_UPD: {
407    OpNum = 0;
408
409    unsigned BaseReg = MI->getOperand(1).getReg();
410    if (BaseReg == ARM::SP &&
411        (Entry.WideOpc == ARM::t2LDMIA_UPD ||
412         Entry.WideOpc == ARM::t2STMDB_UPD)) {
413      Opc = Entry.NarrowOpc2; // tPOP or tPUSH
414      OpNum = 2;
415    } else if (!isARMLowRegister(BaseReg) ||
416               (Entry.WideOpc != ARM::t2LDMIA_UPD &&
417                Entry.WideOpc != ARM::t2STMIA_UPD)) {
418      return false;
419    }
420
421    isLdStMul = true;
422    break;
423  }
424  }
425
426  unsigned OffsetReg = 0;
427  bool OffsetKill = false;
428  if (HasShift) {
429    OffsetReg  = MI->getOperand(2).getReg();
430    OffsetKill = MI->getOperand(2).isKill();
431
432    if (MI->getOperand(3).getImm())
433      // Thumb1 addressing mode doesn't support shift.
434      return false;
435  }
436
437  unsigned OffsetImm = 0;
438  if (HasImmOffset) {
439    OffsetImm = MI->getOperand(2).getImm();
440    unsigned MaxOffset = ((1 << ImmLimit) - 1) * Scale;
441
442    if ((OffsetImm & (Scale - 1)) || OffsetImm > MaxOffset)
443      // Make sure the immediate field fits.
444      return false;
445  }
446
447  // Add the 16-bit load / store instruction.
448  DebugLoc dl = MI->getDebugLoc();
449  MachineInstrBuilder MIB = BuildMI(MBB, *MI, dl, TII->get(Opc));
450  if (!isLdStMul) {
451    MIB.addOperand(MI->getOperand(0));
452    MIB.addOperand(MI->getOperand(1));
453
454    if (HasImmOffset)
455      MIB.addImm(OffsetImm / Scale);
456
457    assert((!HasShift || OffsetReg) && "Invalid so_reg load / store address!");
458
459    if (HasOffReg)
460      MIB.addReg(OffsetReg, getKillRegState(OffsetKill));
461  }
462
463  // Transfer the rest of operands.
464  for (unsigned e = MI->getNumOperands(); OpNum != e; ++OpNum)
465    MIB.addOperand(MI->getOperand(OpNum));
466
467  // Transfer memoperands.
468  MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
469
470  // Transfer MI flags.
471  MIB.setMIFlags(MI->getFlags());
472
473  DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " << *MIB);
474
475  MBB.erase(MI);
476  ++NumLdSts;
477  return true;
478}
479
480bool
481Thumb2SizeReduce::ReduceSpecial(MachineBasicBlock &MBB, MachineInstr *MI,
482                                const ReduceEntry &Entry,
483                                bool LiveCPSR, MachineInstr *CPSRDef) {
484  if (Entry.LowRegs1 && !VerifyLowRegs(MI))
485    return false;
486
487  const MCInstrDesc &MCID = MI->getDesc();
488  if (MCID.mayLoad() || MCID.mayStore())
489    return ReduceLoadStore(MBB, MI, Entry);
490
491  unsigned Opc = MI->getOpcode();
492  switch (Opc) {
493  default: break;
494  case ARM::t2ADDSri:
495  case ARM::t2ADDSrr: {
496    unsigned PredReg = 0;
497    if (getInstrPredicate(MI, PredReg) == ARMCC::AL) {
498      switch (Opc) {
499      default: break;
500      case ARM::t2ADDSri: {
501        if (ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, CPSRDef))
502          return true;
503        // fallthrough
504      }
505      case ARM::t2ADDSrr:
506        return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef);
507      }
508    }
509    break;
510  }
511  case ARM::t2RSBri:
512  case ARM::t2RSBSri:
513    if (MI->getOperand(2).getImm() == 0)
514      return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef);
515    break;
516  case ARM::t2MOVi16:
517    // Can convert only 'pure' immediate operands, not immediates obtained as
518    // globals' addresses.
519    if (MI->getOperand(1).isImm())
520      return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef);
521    break;
522  case ARM::t2CMPrr: {
523    // Try to reduce to the lo-reg only version first. Why there are two
524    // versions of the instruction is a mystery.
525    // It would be nice to just have two entries in the master table that
526    // are prioritized, but the table assumes a unique entry for each
527    // source insn opcode. So for now, we hack a local entry record to use.
528    static const ReduceEntry NarrowEntry =
529      { ARM::t2CMPrr,ARM::tCMPr, 0, 0, 0, 1, 1,2, 0, 0,1 };
530    if (ReduceToNarrow(MBB, MI, NarrowEntry, LiveCPSR, CPSRDef))
531      return true;
532    return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef);
533  }
534  case ARM::t2ADDrSPi: {
535    static const ReduceEntry NarrowEntry =
536      { ARM::t2ADDrSPi,ARM::tADDspi, 0, 7, 0, 1, 0, 1, 0, 0,1 };
537    if (MI->getOperand(0).getReg() == ARM::SP)
538      return ReduceToNarrow(MBB, MI, NarrowEntry, LiveCPSR, CPSRDef);
539    return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef);
540  }
541  }
542  return false;
543}
544
545bool
546Thumb2SizeReduce::ReduceTo2Addr(MachineBasicBlock &MBB, MachineInstr *MI,
547                                const ReduceEntry &Entry,
548                                bool LiveCPSR, MachineInstr *CPSRDef) {
549
550  if (ReduceLimit2Addr != -1 && ((int)Num2Addrs >= ReduceLimit2Addr))
551    return false;
552
553  unsigned Reg0 = MI->getOperand(0).getReg();
554  unsigned Reg1 = MI->getOperand(1).getReg();
555  if (Reg0 != Reg1) {
556    // Try to commute the operands to make it a 2-address instruction.
557    unsigned CommOpIdx1, CommOpIdx2;
558    if (!TII->findCommutedOpIndices(MI, CommOpIdx1, CommOpIdx2) ||
559        CommOpIdx1 != 1 || MI->getOperand(CommOpIdx2).getReg() != Reg0)
560      return false;
561    MachineInstr *CommutedMI = TII->commuteInstruction(MI);
562    if (!CommutedMI)
563      return false;
564  }
565  if (Entry.LowRegs2 && !isARMLowRegister(Reg0))
566    return false;
567  if (Entry.Imm2Limit) {
568    unsigned Imm = MI->getOperand(2).getImm();
569    unsigned Limit = (1 << Entry.Imm2Limit) - 1;
570    if (Imm > Limit)
571      return false;
572  } else {
573    unsigned Reg2 = MI->getOperand(2).getReg();
574    if (Entry.LowRegs2 && !isARMLowRegister(Reg2))
575      return false;
576  }
577
578  // Check if it's possible / necessary to transfer the predicate.
579  const MCInstrDesc &NewMCID = TII->get(Entry.NarrowOpc2);
580  unsigned PredReg = 0;
581  ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
582  bool SkipPred = false;
583  if (Pred != ARMCC::AL) {
584    if (!NewMCID.isPredicable())
585      // Can't transfer predicate, fail.
586      return false;
587  } else {
588    SkipPred = !NewMCID.isPredicable();
589  }
590
591  bool HasCC = false;
592  bool CCDead = false;
593  const MCInstrDesc &MCID = MI->getDesc();
594  if (MCID.hasOptionalDef()) {
595    unsigned NumOps = MCID.getNumOperands();
596    HasCC = (MI->getOperand(NumOps-1).getReg() == ARM::CPSR);
597    if (HasCC && MI->getOperand(NumOps-1).isDead())
598      CCDead = true;
599  }
600  if (!VerifyPredAndCC(MI, Entry, true, Pred, LiveCPSR, HasCC, CCDead))
601    return false;
602
603  // Avoid adding a false dependency on partial flag update by some 16-bit
604  // instructions which has the 's' bit set.
605  if (Entry.PartFlag && NewMCID.hasOptionalDef() && HasCC &&
606      canAddPseudoFlagDep(CPSRDef, MI))
607    return false;
608
609  // Add the 16-bit instruction.
610  DebugLoc dl = MI->getDebugLoc();
611  MachineInstrBuilder MIB = BuildMI(MBB, *MI, dl, NewMCID);
612  MIB.addOperand(MI->getOperand(0));
613  if (NewMCID.hasOptionalDef()) {
614    if (HasCC)
615      AddDefaultT1CC(MIB, CCDead);
616    else
617      AddNoT1CC(MIB);
618  }
619
620  // Transfer the rest of operands.
621  unsigned NumOps = MCID.getNumOperands();
622  for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
623    if (i < NumOps && MCID.OpInfo[i].isOptionalDef())
624      continue;
625    if (SkipPred && MCID.OpInfo[i].isPredicate())
626      continue;
627    MIB.addOperand(MI->getOperand(i));
628  }
629
630  // Transfer MI flags.
631  MIB.setMIFlags(MI->getFlags());
632
633  DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " << *MIB);
634
635  MBB.erase(MI);
636  ++Num2Addrs;
637  return true;
638}
639
640bool
641Thumb2SizeReduce::ReduceToNarrow(MachineBasicBlock &MBB, MachineInstr *MI,
642                                 const ReduceEntry &Entry,
643                                 bool LiveCPSR, MachineInstr *CPSRDef) {
644  if (ReduceLimit != -1 && ((int)NumNarrows >= ReduceLimit))
645    return false;
646
647  unsigned Limit = ~0U;
648  unsigned Scale = (Entry.WideOpc == ARM::t2ADDrSPi) ? 4 : 1;
649  if (Entry.Imm1Limit)
650    Limit = ((1 << Entry.Imm1Limit) - 1) * Scale;
651
652  const MCInstrDesc &MCID = MI->getDesc();
653  for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
654    if (MCID.OpInfo[i].isPredicate())
655      continue;
656    const MachineOperand &MO = MI->getOperand(i);
657    if (MO.isReg()) {
658      unsigned Reg = MO.getReg();
659      if (!Reg || Reg == ARM::CPSR)
660        continue;
661      if (Entry.WideOpc == ARM::t2ADDrSPi && Reg == ARM::SP)
662        continue;
663      if (Entry.LowRegs1 && !isARMLowRegister(Reg))
664        return false;
665    } else if (MO.isImm() &&
666               !MCID.OpInfo[i].isPredicate()) {
667      if (((unsigned)MO.getImm()) > Limit || (MO.getImm() & (Scale-1)) != 0)
668        return false;
669    }
670  }
671
672  // Check if it's possible / necessary to transfer the predicate.
673  const MCInstrDesc &NewMCID = TII->get(Entry.NarrowOpc1);
674  unsigned PredReg = 0;
675  ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
676  bool SkipPred = false;
677  if (Pred != ARMCC::AL) {
678    if (!NewMCID.isPredicable())
679      // Can't transfer predicate, fail.
680      return false;
681  } else {
682    SkipPred = !NewMCID.isPredicable();
683  }
684
685  bool HasCC = false;
686  bool CCDead = false;
687  if (MCID.hasOptionalDef()) {
688    unsigned NumOps = MCID.getNumOperands();
689    HasCC = (MI->getOperand(NumOps-1).getReg() == ARM::CPSR);
690    if (HasCC && MI->getOperand(NumOps-1).isDead())
691      CCDead = true;
692  }
693  if (!VerifyPredAndCC(MI, Entry, false, Pred, LiveCPSR, HasCC, CCDead))
694    return false;
695
696  // Avoid adding a false dependency on partial flag update by some 16-bit
697  // instructions which has the 's' bit set.
698  if (Entry.PartFlag && NewMCID.hasOptionalDef() && HasCC &&
699      canAddPseudoFlagDep(CPSRDef, MI))
700    return false;
701
702  // Add the 16-bit instruction.
703  DebugLoc dl = MI->getDebugLoc();
704  MachineInstrBuilder MIB = BuildMI(MBB, *MI, dl, NewMCID);
705  MIB.addOperand(MI->getOperand(0));
706  if (NewMCID.hasOptionalDef()) {
707    if (HasCC)
708      AddDefaultT1CC(MIB, CCDead);
709    else
710      AddNoT1CC(MIB);
711  }
712
713  // Transfer the rest of operands.
714  unsigned NumOps = MCID.getNumOperands();
715  for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
716    if (i < NumOps && MCID.OpInfo[i].isOptionalDef())
717      continue;
718    if ((MCID.getOpcode() == ARM::t2RSBSri ||
719         MCID.getOpcode() == ARM::t2RSBri) && i == 2)
720      // Skip the zero immediate operand, it's now implicit.
721      continue;
722    bool isPred = (i < NumOps && MCID.OpInfo[i].isPredicate());
723    if (SkipPred && isPred)
724        continue;
725    const MachineOperand &MO = MI->getOperand(i);
726    if (Scale > 1 && !isPred && MO.isImm())
727      MIB.addImm(MO.getImm() / Scale);
728    else {
729      if (MO.isReg() && MO.isImplicit() && MO.getReg() == ARM::CPSR)
730        // Skip implicit def of CPSR. Either it's modeled as an optional
731        // def now or it's already an implicit def on the new instruction.
732        continue;
733      MIB.addOperand(MO);
734    }
735  }
736  if (!MCID.isPredicable() && NewMCID.isPredicable())
737    AddDefaultPred(MIB);
738
739  // Transfer MI flags.
740  MIB.setMIFlags(MI->getFlags());
741
742  DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " << *MIB);
743
744  MBB.erase(MI);
745  ++NumNarrows;
746  return true;
747}
748
749static bool UpdateCPSRDef(MachineInstr &MI, bool LiveCPSR, bool &DefCPSR) {
750  bool HasDef = false;
751  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
752    const MachineOperand &MO = MI.getOperand(i);
753    if (!MO.isReg() || MO.isUndef() || MO.isUse())
754      continue;
755    if (MO.getReg() != ARM::CPSR)
756      continue;
757
758    DefCPSR = true;
759    if (!MO.isDead())
760      HasDef = true;
761  }
762
763  return HasDef || LiveCPSR;
764}
765
766static bool UpdateCPSRUse(MachineInstr &MI, bool LiveCPSR) {
767  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
768    const MachineOperand &MO = MI.getOperand(i);
769    if (!MO.isReg() || MO.isUndef() || MO.isDef())
770      continue;
771    if (MO.getReg() != ARM::CPSR)
772      continue;
773    assert(LiveCPSR && "CPSR liveness tracking is wrong!");
774    if (MO.isKill()) {
775      LiveCPSR = false;
776      break;
777    }
778  }
779
780  return LiveCPSR;
781}
782
783bool Thumb2SizeReduce::ReduceMBB(MachineBasicBlock &MBB) {
784  bool Modified = false;
785
786  // Yes, CPSR could be livein.
787  bool LiveCPSR = MBB.isLiveIn(ARM::CPSR);
788  MachineInstr *CPSRDef = 0;
789
790  MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
791  MachineBasicBlock::iterator NextMII;
792  for (; MII != E; MII = NextMII) {
793    NextMII = llvm::next(MII);
794
795    MachineInstr *MI = &*MII;
796    LiveCPSR = UpdateCPSRUse(*MI, LiveCPSR);
797
798    unsigned Opcode = MI->getOpcode();
799    DenseMap<unsigned, unsigned>::iterator OPI = ReduceOpcodeMap.find(Opcode);
800    if (OPI != ReduceOpcodeMap.end()) {
801      const ReduceEntry &Entry = ReduceTable[OPI->second];
802      // Ignore "special" cases for now.
803      if (Entry.Special) {
804        if (ReduceSpecial(MBB, MI, Entry, LiveCPSR, CPSRDef)) {
805          Modified = true;
806          MachineBasicBlock::iterator I = prior(NextMII);
807          MI = &*I;
808        }
809        goto ProcessNext;
810      }
811
812      // Try to transform to a 16-bit two-address instruction.
813      if (Entry.NarrowOpc2 &&
814          ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, CPSRDef)) {
815        Modified = true;
816        MachineBasicBlock::iterator I = prior(NextMII);
817        MI = &*I;
818        goto ProcessNext;
819      }
820
821      // Try to transform to a 16-bit non-two-address instruction.
822      if (Entry.NarrowOpc1 &&
823          ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef)) {
824        Modified = true;
825        MachineBasicBlock::iterator I = prior(NextMII);
826        MI = &*I;
827      }
828    }
829
830  ProcessNext:
831    bool DefCPSR = false;
832    LiveCPSR = UpdateCPSRDef(*MI, LiveCPSR, DefCPSR);
833    if (MI->getDesc().isCall())
834      // Calls don't really set CPSR.
835      CPSRDef = 0;
836    else if (DefCPSR)
837      // This is the last CPSR defining instruction.
838      CPSRDef = MI;
839  }
840
841  return Modified;
842}
843
844bool Thumb2SizeReduce::runOnMachineFunction(MachineFunction &MF) {
845  const TargetMachine &TM = MF.getTarget();
846  TII = static_cast<const Thumb2InstrInfo*>(TM.getInstrInfo());
847  STI = &TM.getSubtarget<ARMSubtarget>();
848
849  bool Modified = false;
850  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
851    Modified |= ReduceMBB(*I);
852  return Modified;
853}
854
855/// createThumb2SizeReductionPass - Returns an instance of the Thumb2 size
856/// reduction pass.
857FunctionPass *llvm::createThumb2SizeReductionPass() {
858  return new Thumb2SizeReduce();
859}
860