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