Correctly size-reduce the t2CMPzrr instruction to tCMPzr when possible.
[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, 0 },
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   }
473   return false;
474 }
475
476 bool
477 Thumb2SizeReduce::ReduceTo2Addr(MachineBasicBlock &MBB, MachineInstr *MI,
478                                 const ReduceEntry &Entry,
479                                 bool LiveCPSR) {
480
481   if (ReduceLimit2Addr != -1 && ((int)Num2Addrs >= ReduceLimit2Addr))
482     return false;
483
484   unsigned Reg0 = MI->getOperand(0).getReg();
485   unsigned Reg1 = MI->getOperand(1).getReg();
486   if (Reg0 != Reg1) {
487     // Try to commute the operands to make it a 2-address instruction.
488     unsigned CommOpIdx1, CommOpIdx2;
489     if (!TII->findCommutedOpIndices(MI, CommOpIdx1, CommOpIdx2) ||
490         CommOpIdx1 != 1 || MI->getOperand(CommOpIdx2).getReg() != Reg0)
491       return false;
492     MachineInstr *CommutedMI = TII->commuteInstruction(MI);
493     if (!CommutedMI)
494       return false;
495   }
496   if (Entry.LowRegs2 && !isARMLowRegister(Reg0))
497     return false;
498   if (Entry.Imm2Limit) {
499     unsigned Imm = MI->getOperand(2).getImm();
500     unsigned Limit = (1 << Entry.Imm2Limit) - 1;
501     if (Imm > Limit)
502       return false;
503   } else {
504     unsigned Reg2 = MI->getOperand(2).getReg();
505     if (Entry.LowRegs2 && !isARMLowRegister(Reg2))
506       return false;
507   }
508
509   // Check if it's possible / necessary to transfer the predicate.
510   const TargetInstrDesc &NewTID = TII->get(Entry.NarrowOpc2);
511   unsigned PredReg = 0;
512   ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
513   bool SkipPred = false;
514   if (Pred != ARMCC::AL) {
515     if (!NewTID.isPredicable())
516       // Can't transfer predicate, fail.
517       return false;
518   } else {
519     SkipPred = !NewTID.isPredicable();
520   }
521
522   bool HasCC = false;
523   bool CCDead = false;
524   const TargetInstrDesc &TID = MI->getDesc();
525   if (TID.hasOptionalDef()) {
526     unsigned NumOps = TID.getNumOperands();
527     HasCC = (MI->getOperand(NumOps-1).getReg() == ARM::CPSR);
528     if (HasCC && MI->getOperand(NumOps-1).isDead())
529       CCDead = true;
530   }
531   if (!VerifyPredAndCC(MI, Entry, true, Pred, LiveCPSR, HasCC, CCDead))
532     return false;
533
534   // Add the 16-bit instruction.
535   DebugLoc dl = MI->getDebugLoc();
536   MachineInstrBuilder MIB = BuildMI(MBB, *MI, dl, NewTID);
537   MIB.addOperand(MI->getOperand(0));
538   if (NewTID.hasOptionalDef()) {
539     if (HasCC)
540       AddDefaultT1CC(MIB, CCDead);
541     else
542       AddNoT1CC(MIB);
543   }
544
545   // Transfer the rest of operands.
546   unsigned NumOps = TID.getNumOperands();
547   for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
548     if (i < NumOps && TID.OpInfo[i].isOptionalDef())
549       continue;
550     if (SkipPred && TID.OpInfo[i].isPredicate())
551       continue;
552     MIB.addOperand(MI->getOperand(i));
553   }
554
555   DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " << *MIB);
556
557   MBB.erase(MI);
558   ++Num2Addrs;
559   return true;
560 }
561
562 bool
563 Thumb2SizeReduce::ReduceToNarrow(MachineBasicBlock &MBB, MachineInstr *MI,
564                                  const ReduceEntry &Entry,
565                                  bool LiveCPSR) {
566   if (ReduceLimit != -1 && ((int)NumNarrows >= ReduceLimit))
567     return false;
568
569   unsigned Limit = ~0U;
570   unsigned Scale = (Entry.WideOpc == ARM::t2ADDrSPi) ? 4 : 1;
571   if (Entry.Imm1Limit)
572     Limit = ((1 << Entry.Imm1Limit) - 1) * Scale;
573
574   const TargetInstrDesc &TID = MI->getDesc();
575   for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
576     if (TID.OpInfo[i].isPredicate())
577       continue;
578     const MachineOperand &MO = MI->getOperand(i);
579     if (MO.isReg()) {
580       unsigned Reg = MO.getReg();
581       if (!Reg || Reg == ARM::CPSR)
582         continue;
583       if (Entry.WideOpc == ARM::t2ADDrSPi && Reg == ARM::SP)
584         continue;
585       if (Entry.LowRegs1 && !isARMLowRegister(Reg))
586         return false;
587     } else if (MO.isImm() &&
588                !TID.OpInfo[i].isPredicate()) {
589       if (((unsigned)MO.getImm()) > Limit || (MO.getImm() & (Scale-1)) != 0)
590         return false;
591     }
592   }
593
594   // Check if it's possible / necessary to transfer the predicate.
595   const TargetInstrDesc &NewTID = TII->get(Entry.NarrowOpc1);
596   unsigned PredReg = 0;
597   ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
598   bool SkipPred = false;
599   if (Pred != ARMCC::AL) {
600     if (!NewTID.isPredicable())
601       // Can't transfer predicate, fail.
602       return false;
603   } else {
604     SkipPred = !NewTID.isPredicable();
605   }
606
607   bool HasCC = false;
608   bool CCDead = false;
609   if (TID.hasOptionalDef()) {
610     unsigned NumOps = TID.getNumOperands();
611     HasCC = (MI->getOperand(NumOps-1).getReg() == ARM::CPSR);
612     if (HasCC && MI->getOperand(NumOps-1).isDead())
613       CCDead = true;
614   }
615   if (!VerifyPredAndCC(MI, Entry, false, Pred, LiveCPSR, HasCC, CCDead))
616     return false;
617
618   // Add the 16-bit instruction.
619   DebugLoc dl = MI->getDebugLoc();
620   MachineInstrBuilder MIB = BuildMI(MBB, *MI, dl, NewTID);
621   MIB.addOperand(MI->getOperand(0));
622   if (NewTID.hasOptionalDef()) {
623     if (HasCC)
624       AddDefaultT1CC(MIB, CCDead);
625     else
626       AddNoT1CC(MIB);
627   }
628
629   // Transfer the rest of operands.
630   unsigned NumOps = TID.getNumOperands();
631   for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
632     if (i < NumOps && TID.OpInfo[i].isOptionalDef())
633       continue;
634     if ((TID.getOpcode() == ARM::t2RSBSri ||
635          TID.getOpcode() == ARM::t2RSBri) && i == 2)
636       // Skip the zero immediate operand, it's now implicit.
637       continue;
638     bool isPred = (i < NumOps && TID.OpInfo[i].isPredicate());
639     if (SkipPred && isPred)
640         continue;
641     const MachineOperand &MO = MI->getOperand(i);
642     if (Scale > 1 && !isPred && MO.isImm())
643       MIB.addImm(MO.getImm() / Scale);
644     else {
645       if (MO.isReg() && MO.isImplicit() && MO.getReg() == ARM::CPSR)
646         // Skip implicit def of CPSR. Either it's modeled as an optional
647         // def now or it's already an implicit def on the new instruction.
648         continue;
649       MIB.addOperand(MO);
650     }
651   }
652   if (!TID.isPredicable() && NewTID.isPredicable())
653     AddDefaultPred(MIB);
654
655   DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " << *MIB);
656
657   MBB.erase(MI);
658   ++NumNarrows;
659   return true;
660 }
661
662 static bool UpdateCPSRDef(MachineInstr &MI, bool LiveCPSR) {
663   bool HasDef = false;
664   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
665     const MachineOperand &MO = MI.getOperand(i);
666     if (!MO.isReg() || MO.isUndef() || MO.isUse())
667       continue;
668     if (MO.getReg() != ARM::CPSR)
669       continue;
670     if (!MO.isDead())
671       HasDef = true;
672   }
673
674   return HasDef || LiveCPSR;
675 }
676
677 static bool UpdateCPSRUse(MachineInstr &MI, bool LiveCPSR) {
678   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
679     const MachineOperand &MO = MI.getOperand(i);
680     if (!MO.isReg() || MO.isUndef() || MO.isDef())
681       continue;
682     if (MO.getReg() != ARM::CPSR)
683       continue;
684     assert(LiveCPSR && "CPSR liveness tracking is wrong!");
685     if (MO.isKill()) {
686       LiveCPSR = false;
687       break;
688     }
689   }
690
691   return LiveCPSR;
692 }
693
694 bool Thumb2SizeReduce::ReduceMBB(MachineBasicBlock &MBB) {
695   bool Modified = false;
696
697   // Yes, CPSR could be livein.
698   bool LiveCPSR = MBB.isLiveIn(ARM::CPSR);
699
700   MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
701   MachineBasicBlock::iterator NextMII;
702   for (; MII != E; MII = NextMII) {
703     NextMII = llvm::next(MII);
704
705     MachineInstr *MI = &*MII;
706     LiveCPSR = UpdateCPSRUse(*MI, LiveCPSR);
707
708     unsigned Opcode = MI->getOpcode();
709     DenseMap<unsigned, unsigned>::iterator OPI = ReduceOpcodeMap.find(Opcode);
710     if (OPI != ReduceOpcodeMap.end()) {
711       const ReduceEntry &Entry = ReduceTable[OPI->second];
712       // Ignore "special" cases for now.
713       if (Entry.Special) {
714         if (ReduceSpecial(MBB, MI, Entry, LiveCPSR)) {
715           Modified = true;
716           MachineBasicBlock::iterator I = prior(NextMII);
717           MI = &*I;
718         }
719         goto ProcessNext;
720       }
721
722       // Try to transform to a 16-bit two-address instruction.
723       if (Entry.NarrowOpc2 && ReduceTo2Addr(MBB, MI, Entry, LiveCPSR)) {
724         Modified = true;
725         MachineBasicBlock::iterator I = prior(NextMII);
726         MI = &*I;
727         goto ProcessNext;
728       }
729
730       // Try to transform to a 16-bit non-two-address instruction.
731       if (Entry.NarrowOpc1 && ReduceToNarrow(MBB, MI, Entry, LiveCPSR)) {
732         Modified = true;
733         MachineBasicBlock::iterator I = prior(NextMII);
734         MI = &*I;
735       }
736     }
737
738   ProcessNext:
739     LiveCPSR = UpdateCPSRDef(*MI, LiveCPSR);
740   }
741
742   return Modified;
743 }
744
745 bool Thumb2SizeReduce::runOnMachineFunction(MachineFunction &MF) {
746   const TargetMachine &TM = MF.getTarget();
747   TII = static_cast<const Thumb2InstrInfo*>(TM.getInstrInfo());
748
749   bool Modified = false;
750   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
751     Modified |= ReduceMBB(*I);
752   return Modified;
753 }
754
755 /// createThumb2SizeReductionPass - Returns an instance of the Thumb2 size
756 /// reduction pass.
757 FunctionPass *llvm::createThumb2SizeReductionPass() {
758   return new Thumb2SizeReduce();
759 }