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