c2d9c17cf37c2b48b83f14c2fc4bbe8ca6328af0
[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 #include "ARM.h"
11 #include "ARMBaseInstrInfo.h"
12 #include "ARMSubtarget.h"
13 #include "MCTargetDesc/ARMAddressingModes.h"
14 #include "Thumb2InstrInfo.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/PostOrderIterator.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/IR/Function.h"        // To access Function attributes
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Target/TargetMachine.h"
26 using namespace llvm;
27
28 #define DEBUG_TYPE "t2-reduce-size"
29
30 STATISTIC(NumNarrows,  "Number of 32-bit instrs reduced to 16-bit ones");
31 STATISTIC(Num2Addrs,   "Number of 32-bit instrs reduced to 2addr 16-bit ones");
32 STATISTIC(NumLdSts,    "Number of 32-bit load / store reduced to 16-bit ones");
33
34 static cl::opt<int> ReduceLimit("t2-reduce-limit",
35                                 cl::init(-1), cl::Hidden);
36 static cl::opt<int> ReduceLimit2Addr("t2-reduce-limit2",
37                                      cl::init(-1), cl::Hidden);
38 static cl::opt<int> ReduceLimitLdSt("t2-reduce-limit3",
39                                      cl::init(-1), cl::Hidden);
40
41 namespace {
42   /// ReduceTable - A static table with information on mapping from wide
43   /// opcodes to narrow
44   struct ReduceEntry {
45     uint16_t WideOpc;      // Wide opcode
46     uint16_t NarrowOpc1;   // Narrow opcode to transform to
47     uint16_t NarrowOpc2;   // Narrow opcode when it's two-address
48     uint8_t  Imm1Limit;    // Limit of immediate field (bits)
49     uint8_t  Imm2Limit;    // Limit of immediate field when it's two-address
50     unsigned LowRegs1 : 1; // Only possible if low-registers are used
51     unsigned LowRegs2 : 1; // Only possible if low-registers are used (2addr)
52     unsigned PredCC1  : 2; // 0 - If predicated, cc is on and vice versa.
53                            // 1 - No cc field.
54                            // 2 - Always set CPSR.
55     unsigned PredCC2  : 2;
56     unsigned PartFlag : 1; // 16-bit instruction does partial flag update
57     unsigned Special  : 1; // Needs to be dealt with specially
58     unsigned AvoidMovs: 1; // Avoid movs with shifter operand (for Swift)
59   };
60
61   static const ReduceEntry ReduceTable[] = {
62   // Wide,        Narrow1,      Narrow2,     imm1,imm2, lo1, lo2, P/C,PF,S,AM
63   { ARM::t2ADCrr, 0,            ARM::tADC,     0,   0,   0,   1,  0,0, 0,0,0 },
64   { ARM::t2ADDri, ARM::tADDi3,  ARM::tADDi8,   3,   8,   1,   1,  0,0, 0,1,0 },
65   { ARM::t2ADDrr, ARM::tADDrr,  ARM::tADDhirr, 0,   0,   1,   0,  0,1, 0,0,0 },
66   { ARM::t2ADDSri,ARM::tADDi3,  ARM::tADDi8,   3,   8,   1,   1,  2,2, 0,1,0 },
67   { ARM::t2ADDSrr,ARM::tADDrr,  0,             0,   0,   1,   0,  2,0, 0,1,0 },
68   { ARM::t2ANDrr, 0,            ARM::tAND,     0,   0,   0,   1,  0,0, 1,0,0 },
69   { ARM::t2ASRri, ARM::tASRri,  0,             5,   0,   1,   0,  0,0, 1,0,1 },
70   { ARM::t2ASRrr, 0,            ARM::tASRrr,   0,   0,   0,   1,  0,0, 1,0,1 },
71   { ARM::t2BICrr, 0,            ARM::tBIC,     0,   0,   0,   1,  0,0, 1,0,0 },
72   //FIXME: Disable CMN, as CCodes are backwards from compare expectations
73   //{ ARM::t2CMNrr, ARM::tCMN,  0,             0,   0,   1,   0,  2,0, 0,0,0 },
74   { ARM::t2CMNzrr, ARM::tCMNz,  0,             0,   0,   1,   0,  2,0, 0,0,0 },
75   { ARM::t2CMPri, ARM::tCMPi8,  0,             8,   0,   1,   0,  2,0, 0,0,0 },
76   { ARM::t2CMPrr, ARM::tCMPhir, 0,             0,   0,   0,   0,  2,0, 0,1,0 },
77   { ARM::t2EORrr, 0,            ARM::tEOR,     0,   0,   0,   1,  0,0, 1,0,0 },
78   // FIXME: adr.n immediate offset must be multiple of 4.
79   //{ ARM::t2LEApcrelJT,ARM::tLEApcrelJT, 0,   0,   0,   1,   0,  1,0, 0,0,0 },
80   { ARM::t2LSLri, ARM::tLSLri,  0,             5,   0,   1,   0,  0,0, 1,0,1 },
81   { ARM::t2LSLrr, 0,            ARM::tLSLrr,   0,   0,   0,   1,  0,0, 1,0,1 },
82   { ARM::t2LSRri, ARM::tLSRri,  0,             5,   0,   1,   0,  0,0, 1,0,1 },
83   { ARM::t2LSRrr, 0,            ARM::tLSRrr,   0,   0,   0,   1,  0,0, 1,0,1 },
84   { ARM::t2MOVi,  ARM::tMOVi8,  0,             8,   0,   1,   0,  0,0, 1,0,0 },
85   { ARM::t2MOVi16,ARM::tMOVi8,  0,             8,   0,   1,   0,  0,0, 1,1,0 },
86   // FIXME: Do we need the 16-bit 'S' variant?
87   { ARM::t2MOVr,ARM::tMOVr,     0,             0,   0,   0,   0,  1,0, 0,0,0 },
88   { ARM::t2MUL,   0,            ARM::tMUL,     0,   0,   0,   1,  0,0, 1,0,0 },
89   { ARM::t2MVNr,  ARM::tMVN,    0,             0,   0,   1,   0,  0,0, 0,0,0 },
90   { ARM::t2ORRrr, 0,            ARM::tORR,     0,   0,   0,   1,  0,0, 1,0,0 },
91   { ARM::t2REV,   ARM::tREV,    0,             0,   0,   1,   0,  1,0, 0,0,0 },
92   { ARM::t2REV16, ARM::tREV16,  0,             0,   0,   1,   0,  1,0, 0,0,0 },
93   { ARM::t2REVSH, ARM::tREVSH,  0,             0,   0,   1,   0,  1,0, 0,0,0 },
94   { ARM::t2RORrr, 0,            ARM::tROR,     0,   0,   0,   1,  0,0, 1,0,0 },
95   { ARM::t2RSBri, ARM::tRSB,    0,             0,   0,   1,   0,  0,0, 0,1,0 },
96   { ARM::t2RSBSri,ARM::tRSB,    0,             0,   0,   1,   0,  2,0, 0,1,0 },
97   { ARM::t2SBCrr, 0,            ARM::tSBC,     0,   0,   0,   1,  0,0, 0,0,0 },
98   { ARM::t2SUBri, ARM::tSUBi3,  ARM::tSUBi8,   3,   8,   1,   1,  0,0, 0,0,0 },
99   { ARM::t2SUBrr, ARM::tSUBrr,  0,             0,   0,   1,   0,  0,0, 0,0,0 },
100   { ARM::t2SUBSri,ARM::tSUBi3,  ARM::tSUBi8,   3,   8,   1,   1,  2,2, 0,0,0 },
101   { ARM::t2SUBSrr,ARM::tSUBrr,  0,             0,   0,   1,   0,  2,0, 0,0,0 },
102   { ARM::t2SXTB,  ARM::tSXTB,   0,             0,   0,   1,   0,  1,0, 0,1,0 },
103   { ARM::t2SXTH,  ARM::tSXTH,   0,             0,   0,   1,   0,  1,0, 0,1,0 },
104   { ARM::t2TSTrr, ARM::tTST,    0,             0,   0,   1,   0,  2,0, 0,0,0 },
105   { ARM::t2UXTB,  ARM::tUXTB,   0,             0,   0,   1,   0,  1,0, 0,1,0 },
106   { ARM::t2UXTH,  ARM::tUXTH,   0,             0,   0,   1,   0,  1,0, 0,1,0 },
107
108   // FIXME: Clean this up after splitting each Thumb load / store opcode
109   // into multiple ones.
110   { ARM::t2LDRi12,ARM::tLDRi,   ARM::tLDRspi,  5,   8,   1,   0,  0,0, 0,1,0 },
111   { ARM::t2LDRs,  ARM::tLDRr,   0,             0,   0,   1,   0,  0,0, 0,1,0 },
112   { ARM::t2LDRBi12,ARM::tLDRBi, 0,             5,   0,   1,   0,  0,0, 0,1,0 },
113   { ARM::t2LDRBs, ARM::tLDRBr,  0,             0,   0,   1,   0,  0,0, 0,1,0 },
114   { ARM::t2LDRHi12,ARM::tLDRHi, 0,             5,   0,   1,   0,  0,0, 0,1,0 },
115   { ARM::t2LDRHs, ARM::tLDRHr,  0,             0,   0,   1,   0,  0,0, 0,1,0 },
116   { ARM::t2LDRSBs,ARM::tLDRSB,  0,             0,   0,   1,   0,  0,0, 0,1,0 },
117   { ARM::t2LDRSHs,ARM::tLDRSH,  0,             0,   0,   1,   0,  0,0, 0,1,0 },
118   { ARM::t2STRi12,ARM::tSTRi,   ARM::tSTRspi,  5,   8,   1,   0,  0,0, 0,1,0 },
119   { ARM::t2STRs,  ARM::tSTRr,   0,             0,   0,   1,   0,  0,0, 0,1,0 },
120   { ARM::t2STRBi12,ARM::tSTRBi, 0,             5,   0,   1,   0,  0,0, 0,1,0 },
121   { ARM::t2STRBs, ARM::tSTRBr,  0,             0,   0,   1,   0,  0,0, 0,1,0 },
122   { ARM::t2STRHi12,ARM::tSTRHi, 0,             5,   0,   1,   0,  0,0, 0,1,0 },
123   { ARM::t2STRHs, ARM::tSTRHr,  0,             0,   0,   1,   0,  0,0, 0,1,0 },
124
125   { ARM::t2LDMIA, ARM::tLDMIA,  0,             0,   0,   1,   1,  1,1, 0,1,0 },
126   { ARM::t2LDMIA_RET,0,         ARM::tPOP_RET, 0,   0,   1,   1,  1,1, 0,1,0 },
127   { ARM::t2LDMIA_UPD,ARM::tLDMIA_UPD,ARM::tPOP,0,   0,   1,   1,  1,1, 0,1,0 },
128   // ARM::t2STMIA (with no basereg writeback) has no Thumb1 equivalent.
129   // tSTMIA_UPD is a change in semantics which can only be used if the base
130   // register is killed. This difference is correctly handled elsewhere.
131   { ARM::t2STMIA, ARM::tSTMIA_UPD, 0,          0,   0,   1,   1,  1,1, 0,1,0 },
132   { ARM::t2STMIA_UPD,ARM::tSTMIA_UPD, 0,       0,   0,   1,   1,  1,1, 0,1,0 },
133   { ARM::t2STMDB_UPD, 0,        ARM::tPUSH,    0,   0,   1,   1,  1,1, 0,1,0 }
134   };
135
136   class Thumb2SizeReduce : public MachineFunctionPass {
137   public:
138     static char ID;
139     Thumb2SizeReduce();
140
141     const Thumb2InstrInfo *TII;
142     const ARMSubtarget *STI;
143
144     bool runOnMachineFunction(MachineFunction &MF) override;
145
146     const char *getPassName() const override {
147       return "Thumb2 instruction size reduction pass";
148     }
149
150   private:
151     /// ReduceOpcodeMap - Maps wide opcode to index of entry in ReduceTable.
152     DenseMap<unsigned, unsigned> ReduceOpcodeMap;
153
154     bool canAddPseudoFlagDep(MachineInstr *Use, bool IsSelfLoop);
155
156     bool VerifyPredAndCC(MachineInstr *MI, const ReduceEntry &Entry,
157                          bool is2Addr, ARMCC::CondCodes Pred,
158                          bool LiveCPSR, bool &HasCC, bool &CCDead);
159
160     bool ReduceLoadStore(MachineBasicBlock &MBB, MachineInstr *MI,
161                          const ReduceEntry &Entry);
162
163     bool ReduceSpecial(MachineBasicBlock &MBB, MachineInstr *MI,
164                        const ReduceEntry &Entry, bool LiveCPSR, bool IsSelfLoop);
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, bool LiveCPSR,
170                        bool IsSelfLoop);
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, bool LiveCPSR,
176                         bool IsSelfLoop);
177
178     /// ReduceMI - Attempt to reduce MI, return true on success.
179     bool ReduceMI(MachineBasicBlock &MBB, MachineInstr *MI,
180                   bool LiveCPSR, bool IsSelfLoop);
181
182     /// ReduceMBB - Reduce width of instructions in the specified basic block.
183     bool ReduceMBB(MachineBasicBlock &MBB);
184
185     bool OptimizeSize;
186     bool MinimizeSize;
187
188     // Last instruction to define CPSR in the current block.
189     MachineInstr *CPSRDef;
190     // Was CPSR last defined by a high latency instruction?
191     // When CPSRDef is null, this refers to CPSR defs in predecessors.
192     bool HighLatencyCPSR;
193
194     struct MBBInfo {
195       // The flags leaving this block have high latency.
196       bool HighLatencyCPSR;
197       // Has this block been visited yet?
198       bool Visited;
199
200       MBBInfo() : HighLatencyCPSR(false), Visited(false) {}
201     };
202
203     SmallVector<MBBInfo, 8> BlockInfo;
204   };
205   char Thumb2SizeReduce::ID = 0;
206 }
207
208 Thumb2SizeReduce::Thumb2SizeReduce() : MachineFunctionPass(ID) {
209   OptimizeSize = MinimizeSize = false;
210   for (unsigned i = 0, e = array_lengthof(ReduceTable); i != e; ++i) {
211     unsigned FromOpc = ReduceTable[i].WideOpc;
212     if (!ReduceOpcodeMap.insert(std::make_pair(FromOpc, i)).second)
213       assert(false && "Duplicated entries?");
214   }
215 }
216
217 static bool HasImplicitCPSRDef(const MCInstrDesc &MCID) {
218   for (const uint16_t *Regs = MCID.getImplicitDefs(); *Regs; ++Regs)
219     if (*Regs == ARM::CPSR)
220       return true;
221   return false;
222 }
223
224 // Check for a likely high-latency flag def.
225 static bool isHighLatencyCPSR(MachineInstr *Def) {
226   switch(Def->getOpcode()) {
227   case ARM::FMSTAT:
228   case ARM::tMUL:
229     return true;
230   }
231   return false;
232 }
233
234 /// canAddPseudoFlagDep - For A9 (and other out-of-order) implementations,
235 /// the 's' 16-bit instruction partially update CPSR. Abort the
236 /// transformation to avoid adding false dependency on last CPSR setting
237 /// instruction which hurts the ability for out-of-order execution engine
238 /// to do register renaming magic.
239 /// This function checks if there is a read-of-write dependency between the
240 /// last instruction that defines the CPSR and the current instruction. If there
241 /// is, then there is no harm done since the instruction cannot be retired
242 /// before the CPSR setting instruction anyway.
243 /// Note, we are not doing full dependency analysis here for the sake of compile
244 /// time. We're not looking for cases like:
245 /// r0 = muls ...
246 /// r1 = add.w r0, ...
247 /// ...
248 ///    = mul.w r1
249 /// In this case it would have been ok to narrow the mul.w to muls since there
250 /// are indirect RAW dependency between the muls and the mul.w
251 bool
252 Thumb2SizeReduce::canAddPseudoFlagDep(MachineInstr *Use, bool FirstInSelfLoop) {
253   // Disable the check for -Oz (aka OptimizeForSizeHarder).
254   if (MinimizeSize || !STI->avoidCPSRPartialUpdate())
255     return false;
256
257   if (!CPSRDef)
258     // If this BB loops back to itself, conservatively avoid narrowing the
259     // first instruction that does partial flag update.
260     return HighLatencyCPSR || FirstInSelfLoop;
261
262   SmallSet<unsigned, 2> Defs;
263   for (const MachineOperand &MO : CPSRDef->operands()) {
264     if (!MO.isReg() || MO.isUndef() || MO.isUse())
265       continue;
266     unsigned Reg = MO.getReg();
267     if (Reg == 0 || Reg == ARM::CPSR)
268       continue;
269     Defs.insert(Reg);
270   }
271
272   for (const MachineOperand &MO : Use->operands()) {
273     if (!MO.isReg() || MO.isUndef() || MO.isDef())
274       continue;
275     unsigned Reg = MO.getReg();
276     if (Defs.count(Reg))
277       return false;
278   }
279
280   // If the current CPSR has high latency, try to avoid the false dependency.
281   if (HighLatencyCPSR)
282     return true;
283
284   // tMOVi8 usually doesn't start long dependency chains, and there are a lot
285   // of them, so always shrink them when CPSR doesn't have high latency.
286   if (Use->getOpcode() == ARM::t2MOVi ||
287       Use->getOpcode() == ARM::t2MOVi16)
288     return false;
289
290   // No read-after-write dependency. The narrowing will add false dependency.
291   return true;
292 }
293
294 bool
295 Thumb2SizeReduce::VerifyPredAndCC(MachineInstr *MI, const ReduceEntry &Entry,
296                                   bool is2Addr, ARMCC::CondCodes Pred,
297                                   bool LiveCPSR, bool &HasCC, bool &CCDead) {
298   if ((is2Addr  && Entry.PredCC2 == 0) ||
299       (!is2Addr && Entry.PredCC1 == 0)) {
300     if (Pred == ARMCC::AL) {
301       // Not predicated, must set CPSR.
302       if (!HasCC) {
303         // Original instruction was not setting CPSR, but CPSR is not
304         // currently live anyway. It's ok to set it. The CPSR def is
305         // dead though.
306         if (!LiveCPSR) {
307           HasCC = true;
308           CCDead = true;
309           return true;
310         }
311         return false;
312       }
313     } else {
314       // Predicated, must not set CPSR.
315       if (HasCC)
316         return false;
317     }
318   } else if ((is2Addr  && Entry.PredCC2 == 2) ||
319              (!is2Addr && Entry.PredCC1 == 2)) {
320     /// Old opcode has an optional def of CPSR.
321     if (HasCC)
322       return true;
323     // If old opcode does not implicitly define CPSR, then it's not ok since
324     // these new opcodes' CPSR def is not meant to be thrown away. e.g. CMP.
325     if (!HasImplicitCPSRDef(MI->getDesc()))
326       return false;
327     HasCC = true;
328   } else {
329     // 16-bit instruction does not set CPSR.
330     if (HasCC)
331       return false;
332   }
333
334   return true;
335 }
336
337 static bool VerifyLowRegs(MachineInstr *MI) {
338   unsigned Opc = MI->getOpcode();
339   bool isPCOk = (Opc == ARM::t2LDMIA_RET || Opc == ARM::t2LDMIA_UPD);
340   bool isLROk = (Opc == ARM::t2STMDB_UPD);
341   bool isSPOk = isPCOk || isLROk;
342   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
343     const MachineOperand &MO = MI->getOperand(i);
344     if (!MO.isReg() || MO.isImplicit())
345       continue;
346     unsigned Reg = MO.getReg();
347     if (Reg == 0 || Reg == ARM::CPSR)
348       continue;
349     if (isPCOk && Reg == ARM::PC)
350       continue;
351     if (isLROk && Reg == ARM::LR)
352       continue;
353     if (Reg == ARM::SP) {
354       if (isSPOk)
355         continue;
356       if (i == 1 && (Opc == ARM::t2LDRi12 || Opc == ARM::t2STRi12))
357         // Special case for these ldr / str with sp as base register.
358         continue;
359     }
360     if (!isARMLowRegister(Reg))
361       return false;
362   }
363   return true;
364 }
365
366 bool
367 Thumb2SizeReduce::ReduceLoadStore(MachineBasicBlock &MBB, MachineInstr *MI,
368                                   const ReduceEntry &Entry) {
369   if (ReduceLimitLdSt != -1 && ((int)NumLdSts >= ReduceLimitLdSt))
370     return false;
371
372   unsigned Scale = 1;
373   bool HasImmOffset = false;
374   bool HasShift = false;
375   bool HasOffReg = true;
376   bool isLdStMul = false;
377   unsigned Opc = Entry.NarrowOpc1;
378   unsigned OpNum = 3; // First 'rest' of operands.
379   uint8_t  ImmLimit = Entry.Imm1Limit;
380
381   switch (Entry.WideOpc) {
382   default:
383     llvm_unreachable("Unexpected Thumb2 load / store opcode!");
384   case ARM::t2LDRi12:
385   case ARM::t2STRi12:
386     if (MI->getOperand(1).getReg() == ARM::SP) {
387       Opc = Entry.NarrowOpc2;
388       ImmLimit = Entry.Imm2Limit;
389     }
390
391     Scale = 4;
392     HasImmOffset = true;
393     HasOffReg = false;
394     break;
395   case ARM::t2LDRBi12:
396   case ARM::t2STRBi12:
397     HasImmOffset = true;
398     HasOffReg = false;
399     break;
400   case ARM::t2LDRHi12:
401   case ARM::t2STRHi12:
402     Scale = 2;
403     HasImmOffset = true;
404     HasOffReg = false;
405     break;
406   case ARM::t2LDRs:
407   case ARM::t2LDRBs:
408   case ARM::t2LDRHs:
409   case ARM::t2LDRSBs:
410   case ARM::t2LDRSHs:
411   case ARM::t2STRs:
412   case ARM::t2STRBs:
413   case ARM::t2STRHs:
414     HasShift = true;
415     OpNum = 4;
416     break;
417   case ARM::t2LDMIA: {
418     unsigned BaseReg = MI->getOperand(0).getReg();
419     assert(isARMLowRegister(BaseReg));
420
421     // For the non-writeback version (this one), the base register must be
422     // one of the registers being loaded.
423     bool isOK = false;
424     for (unsigned i = 3; i < MI->getNumOperands(); ++i) {
425       if (MI->getOperand(i).getReg() == BaseReg) {
426         isOK = true;
427         break;
428       }
429     }
430
431     if (!isOK)
432       return false;
433
434     OpNum = 0;
435     isLdStMul = true;
436     break;
437   }
438   case ARM::t2STMIA: {
439     // If the base register is killed, we don't care what its value is after the
440     // instruction, so we can use an updating STMIA.
441     if (!MI->getOperand(0).isKill())
442       return false;
443
444     break;
445   }
446   case ARM::t2LDMIA_RET: {
447     unsigned BaseReg = MI->getOperand(1).getReg();
448     if (BaseReg != ARM::SP)
449       return false;
450     Opc = Entry.NarrowOpc2; // tPOP_RET
451     OpNum = 2;
452     isLdStMul = true;
453     break;
454   }
455   case ARM::t2LDMIA_UPD:
456   case ARM::t2STMIA_UPD:
457   case ARM::t2STMDB_UPD: {
458     OpNum = 0;
459
460     unsigned BaseReg = MI->getOperand(1).getReg();
461     if (BaseReg == ARM::SP &&
462         (Entry.WideOpc == ARM::t2LDMIA_UPD ||
463          Entry.WideOpc == ARM::t2STMDB_UPD)) {
464       Opc = Entry.NarrowOpc2; // tPOP or tPUSH
465       OpNum = 2;
466     } else if (!isARMLowRegister(BaseReg) ||
467                (Entry.WideOpc != ARM::t2LDMIA_UPD &&
468                 Entry.WideOpc != ARM::t2STMIA_UPD)) {
469       return false;
470     }
471
472     isLdStMul = true;
473     break;
474   }
475   }
476
477   unsigned OffsetReg = 0;
478   bool OffsetKill = false;
479   bool OffsetInternal = false;
480   if (HasShift) {
481     OffsetReg  = MI->getOperand(2).getReg();
482     OffsetKill = MI->getOperand(2).isKill();
483     OffsetInternal = MI->getOperand(2).isInternalRead();
484
485     if (MI->getOperand(3).getImm())
486       // Thumb1 addressing mode doesn't support shift.
487       return false;
488   }
489
490   unsigned OffsetImm = 0;
491   if (HasImmOffset) {
492     OffsetImm = MI->getOperand(2).getImm();
493     unsigned MaxOffset = ((1 << ImmLimit) - 1) * Scale;
494
495     if ((OffsetImm & (Scale - 1)) || OffsetImm > MaxOffset)
496       // Make sure the immediate field fits.
497       return false;
498   }
499
500   // Add the 16-bit load / store instruction.
501   DebugLoc dl = MI->getDebugLoc();
502   MachineInstrBuilder MIB = BuildMI(MBB, MI, dl, TII->get(Opc));
503
504   // tSTMIA_UPD takes a defining register operand. We've already checked that
505   // the register is killed, so mark it as dead here.
506   if (Entry.WideOpc == ARM::t2STMIA)
507     MIB.addReg(MI->getOperand(0).getReg(), RegState::Define | RegState::Dead);
508
509   if (!isLdStMul) {
510     MIB.addOperand(MI->getOperand(0));
511     MIB.addOperand(MI->getOperand(1));
512
513     if (HasImmOffset)
514       MIB.addImm(OffsetImm / Scale);
515
516     assert((!HasShift || OffsetReg) && "Invalid so_reg load / store address!");
517
518     if (HasOffReg)
519       MIB.addReg(OffsetReg, getKillRegState(OffsetKill) |
520                             getInternalReadRegState(OffsetInternal));
521   }
522
523   // Transfer the rest of operands.
524   for (unsigned e = MI->getNumOperands(); OpNum != e; ++OpNum)
525     MIB.addOperand(MI->getOperand(OpNum));
526
527   // Transfer memoperands.
528   MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
529
530   // Transfer MI flags.
531   MIB.setMIFlags(MI->getFlags());
532
533   DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " << *MIB);
534
535   MBB.erase_instr(MI);
536   ++NumLdSts;
537   return true;
538 }
539
540 bool
541 Thumb2SizeReduce::ReduceSpecial(MachineBasicBlock &MBB, MachineInstr *MI,
542                                 const ReduceEntry &Entry,
543                                 bool LiveCPSR, bool IsSelfLoop) {
544   unsigned Opc = MI->getOpcode();
545   if (Opc == ARM::t2ADDri) {
546     // If the source register is SP, try to reduce to tADDrSPi, otherwise
547     // it's a normal reduce.
548     if (MI->getOperand(1).getReg() != ARM::SP) {
549       if (ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, IsSelfLoop))
550         return true;
551       return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
552     }
553     // Try to reduce to tADDrSPi.
554     unsigned Imm = MI->getOperand(2).getImm();
555     // The immediate must be in range, the destination register must be a low
556     // reg, the predicate must be "always" and the condition flags must not
557     // be being set.
558     if (Imm & 3 || Imm > 1020)
559       return false;
560     if (!isARMLowRegister(MI->getOperand(0).getReg()))
561       return false;
562     if (MI->getOperand(3).getImm() != ARMCC::AL)
563       return false;
564     const MCInstrDesc &MCID = MI->getDesc();
565     if (MCID.hasOptionalDef() &&
566         MI->getOperand(MCID.getNumOperands()-1).getReg() == ARM::CPSR)
567       return false;
568
569     MachineInstrBuilder MIB = BuildMI(MBB, MI, MI->getDebugLoc(),
570                                       TII->get(ARM::tADDrSPi))
571       .addOperand(MI->getOperand(0))
572       .addOperand(MI->getOperand(1))
573       .addImm(Imm / 4); // The tADDrSPi has an implied scale by four.
574     AddDefaultPred(MIB);
575
576     // Transfer MI flags.
577     MIB.setMIFlags(MI->getFlags());
578
579     DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " <<*MIB);
580
581     MBB.erase_instr(MI);
582     ++NumNarrows;
583     return true;
584   }
585
586   if (Entry.LowRegs1 && !VerifyLowRegs(MI))
587     return false;
588
589   if (MI->mayLoadOrStore())
590     return ReduceLoadStore(MBB, MI, Entry);
591
592   switch (Opc) {
593   default: break;
594   case ARM::t2ADDSri:
595   case ARM::t2ADDSrr: {
596     unsigned PredReg = 0;
597     if (getInstrPredicate(MI, PredReg) == ARMCC::AL) {
598       switch (Opc) {
599       default: break;
600       case ARM::t2ADDSri: {
601         if (ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, IsSelfLoop))
602           return true;
603         // fallthrough
604       }
605       case ARM::t2ADDSrr:
606         return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
607       }
608     }
609     break;
610   }
611   case ARM::t2RSBri:
612   case ARM::t2RSBSri:
613   case ARM::t2SXTB:
614   case ARM::t2SXTH:
615   case ARM::t2UXTB:
616   case ARM::t2UXTH:
617     if (MI->getOperand(2).getImm() == 0)
618       return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
619     break;
620   case ARM::t2MOVi16:
621     // Can convert only 'pure' immediate operands, not immediates obtained as
622     // globals' addresses.
623     if (MI->getOperand(1).isImm())
624       return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
625     break;
626   case ARM::t2CMPrr: {
627     // Try to reduce to the lo-reg only version first. Why there are two
628     // versions of the instruction is a mystery.
629     // It would be nice to just have two entries in the master table that
630     // are prioritized, but the table assumes a unique entry for each
631     // source insn opcode. So for now, we hack a local entry record to use.
632     static const ReduceEntry NarrowEntry =
633       { ARM::t2CMPrr,ARM::tCMPr, 0, 0, 0, 1, 1,2, 0, 0,1,0 };
634     if (ReduceToNarrow(MBB, MI, NarrowEntry, LiveCPSR, IsSelfLoop))
635       return true;
636     return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
637   }
638   }
639   return false;
640 }
641
642 bool
643 Thumb2SizeReduce::ReduceTo2Addr(MachineBasicBlock &MBB, MachineInstr *MI,
644                                 const ReduceEntry &Entry,
645                                 bool LiveCPSR, bool IsSelfLoop) {
646
647   if (ReduceLimit2Addr != -1 && ((int)Num2Addrs >= ReduceLimit2Addr))
648     return false;
649
650   if (!MinimizeSize && !OptimizeSize && Entry.AvoidMovs &&
651       STI->avoidMOVsShifterOperand())
652     // Don't issue movs with shifter operand for some CPUs unless we
653     // are optimizing / minimizing for size.
654     return false;
655
656   unsigned Reg0 = MI->getOperand(0).getReg();
657   unsigned Reg1 = MI->getOperand(1).getReg();
658   // t2MUL is "special". The tied source operand is second, not first.
659   if (MI->getOpcode() == ARM::t2MUL) {
660     unsigned Reg2 = MI->getOperand(2).getReg();
661     // Early exit if the regs aren't all low regs.
662     if (!isARMLowRegister(Reg0) || !isARMLowRegister(Reg1)
663         || !isARMLowRegister(Reg2))
664       return false;
665     if (Reg0 != Reg2) {
666       // If the other operand also isn't the same as the destination, we
667       // can't reduce.
668       if (Reg1 != Reg0)
669         return false;
670       // Try to commute the operands to make it a 2-address instruction.
671       MachineInstr *CommutedMI = TII->commuteInstruction(MI);
672       if (!CommutedMI)
673         return false;
674     }
675   } else if (Reg0 != Reg1) {
676     // Try to commute the operands to make it a 2-address instruction.
677     unsigned CommOpIdx1, CommOpIdx2;
678     if (!TII->findCommutedOpIndices(MI, CommOpIdx1, CommOpIdx2) ||
679         CommOpIdx1 != 1 || MI->getOperand(CommOpIdx2).getReg() != Reg0)
680       return false;
681     MachineInstr *CommutedMI = TII->commuteInstruction(MI);
682     if (!CommutedMI)
683       return false;
684   }
685   if (Entry.LowRegs2 && !isARMLowRegister(Reg0))
686     return false;
687   if (Entry.Imm2Limit) {
688     unsigned Imm = MI->getOperand(2).getImm();
689     unsigned Limit = (1 << Entry.Imm2Limit) - 1;
690     if (Imm > Limit)
691       return false;
692   } else {
693     unsigned Reg2 = MI->getOperand(2).getReg();
694     if (Entry.LowRegs2 && !isARMLowRegister(Reg2))
695       return false;
696   }
697
698   // Check if it's possible / necessary to transfer the predicate.
699   const MCInstrDesc &NewMCID = TII->get(Entry.NarrowOpc2);
700   unsigned PredReg = 0;
701   ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
702   bool SkipPred = false;
703   if (Pred != ARMCC::AL) {
704     if (!NewMCID.isPredicable())
705       // Can't transfer predicate, fail.
706       return false;
707   } else {
708     SkipPred = !NewMCID.isPredicable();
709   }
710
711   bool HasCC = false;
712   bool CCDead = false;
713   const MCInstrDesc &MCID = MI->getDesc();
714   if (MCID.hasOptionalDef()) {
715     unsigned NumOps = MCID.getNumOperands();
716     HasCC = (MI->getOperand(NumOps-1).getReg() == ARM::CPSR);
717     if (HasCC && MI->getOperand(NumOps-1).isDead())
718       CCDead = true;
719   }
720   if (!VerifyPredAndCC(MI, Entry, true, Pred, LiveCPSR, HasCC, CCDead))
721     return false;
722
723   // Avoid adding a false dependency on partial flag update by some 16-bit
724   // instructions which has the 's' bit set.
725   if (Entry.PartFlag && NewMCID.hasOptionalDef() && HasCC &&
726       canAddPseudoFlagDep(MI, IsSelfLoop))
727     return false;
728
729   // Add the 16-bit instruction.
730   DebugLoc dl = MI->getDebugLoc();
731   MachineInstrBuilder MIB = BuildMI(MBB, MI, dl, NewMCID);
732   MIB.addOperand(MI->getOperand(0));
733   if (NewMCID.hasOptionalDef()) {
734     if (HasCC)
735       AddDefaultT1CC(MIB, CCDead);
736     else
737       AddNoT1CC(MIB);
738   }
739
740   // Transfer the rest of operands.
741   unsigned NumOps = MCID.getNumOperands();
742   for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
743     if (i < NumOps && MCID.OpInfo[i].isOptionalDef())
744       continue;
745     if (SkipPred && MCID.OpInfo[i].isPredicate())
746       continue;
747     MIB.addOperand(MI->getOperand(i));
748   }
749
750   // Transfer MI flags.
751   MIB.setMIFlags(MI->getFlags());
752
753   DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " << *MIB);
754
755   MBB.erase_instr(MI);
756   ++Num2Addrs;
757   return true;
758 }
759
760 bool
761 Thumb2SizeReduce::ReduceToNarrow(MachineBasicBlock &MBB, MachineInstr *MI,
762                                  const ReduceEntry &Entry,
763                                  bool LiveCPSR, bool IsSelfLoop) {
764   if (ReduceLimit != -1 && ((int)NumNarrows >= ReduceLimit))
765     return false;
766
767   if (!MinimizeSize && !OptimizeSize && Entry.AvoidMovs &&
768       STI->avoidMOVsShifterOperand())
769     // Don't issue movs with shifter operand for some CPUs unless we
770     // are optimizing / minimizing for size.
771     return false;
772
773   unsigned Limit = ~0U;
774   if (Entry.Imm1Limit)
775     Limit = (1 << Entry.Imm1Limit) - 1;
776
777   const MCInstrDesc &MCID = MI->getDesc();
778   for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
779     if (MCID.OpInfo[i].isPredicate())
780       continue;
781     const MachineOperand &MO = MI->getOperand(i);
782     if (MO.isReg()) {
783       unsigned Reg = MO.getReg();
784       if (!Reg || Reg == ARM::CPSR)
785         continue;
786       if (Entry.LowRegs1 && !isARMLowRegister(Reg))
787         return false;
788     } else if (MO.isImm() &&
789                !MCID.OpInfo[i].isPredicate()) {
790       if (((unsigned)MO.getImm()) > Limit)
791         return false;
792     }
793   }
794
795   // Check if it's possible / necessary to transfer the predicate.
796   const MCInstrDesc &NewMCID = TII->get(Entry.NarrowOpc1);
797   unsigned PredReg = 0;
798   ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
799   bool SkipPred = false;
800   if (Pred != ARMCC::AL) {
801     if (!NewMCID.isPredicable())
802       // Can't transfer predicate, fail.
803       return false;
804   } else {
805     SkipPred = !NewMCID.isPredicable();
806   }
807
808   bool HasCC = false;
809   bool CCDead = false;
810   if (MCID.hasOptionalDef()) {
811     unsigned NumOps = MCID.getNumOperands();
812     HasCC = (MI->getOperand(NumOps-1).getReg() == ARM::CPSR);
813     if (HasCC && MI->getOperand(NumOps-1).isDead())
814       CCDead = true;
815   }
816   if (!VerifyPredAndCC(MI, Entry, false, Pred, LiveCPSR, HasCC, CCDead))
817     return false;
818
819   // Avoid adding a false dependency on partial flag update by some 16-bit
820   // instructions which has the 's' bit set.
821   if (Entry.PartFlag && NewMCID.hasOptionalDef() && HasCC &&
822       canAddPseudoFlagDep(MI, IsSelfLoop))
823     return false;
824
825   // Add the 16-bit instruction.
826   DebugLoc dl = MI->getDebugLoc();
827   MachineInstrBuilder MIB = BuildMI(MBB, MI, dl, NewMCID);
828   MIB.addOperand(MI->getOperand(0));
829   if (NewMCID.hasOptionalDef()) {
830     if (HasCC)
831       AddDefaultT1CC(MIB, CCDead);
832     else
833       AddNoT1CC(MIB);
834   }
835
836   // Transfer the rest of operands.
837   unsigned NumOps = MCID.getNumOperands();
838   for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
839     if (i < NumOps && MCID.OpInfo[i].isOptionalDef())
840       continue;
841     if ((MCID.getOpcode() == ARM::t2RSBSri ||
842          MCID.getOpcode() == ARM::t2RSBri ||
843          MCID.getOpcode() == ARM::t2SXTB ||
844          MCID.getOpcode() == ARM::t2SXTH ||
845          MCID.getOpcode() == ARM::t2UXTB ||
846          MCID.getOpcode() == ARM::t2UXTH) && i == 2)
847       // Skip the zero immediate operand, it's now implicit.
848       continue;
849     bool isPred = (i < NumOps && MCID.OpInfo[i].isPredicate());
850     if (SkipPred && isPred)
851         continue;
852     const MachineOperand &MO = MI->getOperand(i);
853     if (MO.isReg() && MO.isImplicit() && MO.getReg() == ARM::CPSR)
854       // Skip implicit def of CPSR. Either it's modeled as an optional
855       // def now or it's already an implicit def on the new instruction.
856       continue;
857     MIB.addOperand(MO);
858   }
859   if (!MCID.isPredicable() && NewMCID.isPredicable())
860     AddDefaultPred(MIB);
861
862   // Transfer MI flags.
863   MIB.setMIFlags(MI->getFlags());
864
865   DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " << *MIB);
866
867   MBB.erase_instr(MI);
868   ++NumNarrows;
869   return true;
870 }
871
872 static bool UpdateCPSRDef(MachineInstr &MI, bool LiveCPSR, bool &DefCPSR) {
873   bool HasDef = false;
874   for (const MachineOperand &MO : MI.operands()) {
875     if (!MO.isReg() || MO.isUndef() || MO.isUse())
876       continue;
877     if (MO.getReg() != ARM::CPSR)
878       continue;
879
880     DefCPSR = true;
881     if (!MO.isDead())
882       HasDef = true;
883   }
884
885   return HasDef || LiveCPSR;
886 }
887
888 static bool UpdateCPSRUse(MachineInstr &MI, bool LiveCPSR) {
889   for (const MachineOperand &MO : MI.operands()) {
890     if (!MO.isReg() || MO.isUndef() || MO.isDef())
891       continue;
892     if (MO.getReg() != ARM::CPSR)
893       continue;
894     assert(LiveCPSR && "CPSR liveness tracking is wrong!");
895     if (MO.isKill()) {
896       LiveCPSR = false;
897       break;
898     }
899   }
900
901   return LiveCPSR;
902 }
903
904 bool Thumb2SizeReduce::ReduceMI(MachineBasicBlock &MBB, MachineInstr *MI,
905                                 bool LiveCPSR, bool IsSelfLoop) {
906   unsigned Opcode = MI->getOpcode();
907   DenseMap<unsigned, unsigned>::iterator OPI = ReduceOpcodeMap.find(Opcode);
908   if (OPI == ReduceOpcodeMap.end())
909     return false;
910   const ReduceEntry &Entry = ReduceTable[OPI->second];
911
912   // Don't attempt normal reductions on "special" cases for now.
913   if (Entry.Special)
914     return ReduceSpecial(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
915
916   // Try to transform to a 16-bit two-address instruction.
917   if (Entry.NarrowOpc2 &&
918       ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, IsSelfLoop))
919     return true;
920
921   // Try to transform to a 16-bit non-two-address instruction.
922   if (Entry.NarrowOpc1 &&
923       ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop))
924     return true;
925
926   return false;
927 }
928
929 bool Thumb2SizeReduce::ReduceMBB(MachineBasicBlock &MBB) {
930   bool Modified = false;
931
932   // Yes, CPSR could be livein.
933   bool LiveCPSR = MBB.isLiveIn(ARM::CPSR);
934   MachineInstr *BundleMI = nullptr;
935
936   CPSRDef = nullptr;
937   HighLatencyCPSR = false;
938
939   // Check predecessors for the latest CPSRDef.
940   for (auto *Pred : MBB.predecessors()) {
941     const MBBInfo &PInfo = BlockInfo[Pred->getNumber()];
942     if (!PInfo.Visited) {
943       // Since blocks are visited in RPO, this must be a back-edge.
944       continue;
945     }
946     if (PInfo.HighLatencyCPSR) {
947       HighLatencyCPSR = true;
948       break;
949     }
950   }
951
952   // If this BB loops back to itself, conservatively avoid narrowing the
953   // first instruction that does partial flag update.
954   bool IsSelfLoop = MBB.isSuccessor(&MBB);
955   MachineBasicBlock::instr_iterator MII = MBB.instr_begin(),E = MBB.instr_end();
956   MachineBasicBlock::instr_iterator NextMII;
957   for (; MII != E; MII = NextMII) {
958     NextMII = std::next(MII);
959
960     MachineInstr *MI = &*MII;
961     if (MI->isBundle()) {
962       BundleMI = MI;
963       continue;
964     }
965     if (MI->isDebugValue())
966       continue;
967
968     LiveCPSR = UpdateCPSRUse(*MI, LiveCPSR);
969
970     // Does NextMII belong to the same bundle as MI?
971     bool NextInSameBundle = NextMII != E && NextMII->isBundledWithPred();
972
973     if (ReduceMI(MBB, MI, LiveCPSR, IsSelfLoop)) {
974       Modified = true;
975       MachineBasicBlock::instr_iterator I = std::prev(NextMII);
976       MI = &*I;
977       // Removing and reinserting the first instruction in a bundle will break
978       // up the bundle. Fix the bundling if it was broken.
979       if (NextInSameBundle && !NextMII->isBundledWithPred())
980         NextMII->bundleWithPred();
981     }
982
983     if (!NextInSameBundle && MI->isInsideBundle()) {
984       // FIXME: Since post-ra scheduler operates on bundles, the CPSR kill
985       // marker is only on the BUNDLE instruction. Process the BUNDLE
986       // instruction as we finish with the bundled instruction to work around
987       // the inconsistency.
988       if (BundleMI->killsRegister(ARM::CPSR))
989         LiveCPSR = false;
990       MachineOperand *MO = BundleMI->findRegisterDefOperand(ARM::CPSR);
991       if (MO && !MO->isDead())
992         LiveCPSR = true;
993       MO = BundleMI->findRegisterUseOperand(ARM::CPSR);
994       if (MO && !MO->isKill())
995         LiveCPSR = true;
996     }
997
998     bool DefCPSR = false;
999     LiveCPSR = UpdateCPSRDef(*MI, LiveCPSR, DefCPSR);
1000     if (MI->isCall()) {
1001       // Calls don't really set CPSR.
1002       CPSRDef = nullptr;
1003       HighLatencyCPSR = false;
1004       IsSelfLoop = false;
1005     } else if (DefCPSR) {
1006       // This is the last CPSR defining instruction.
1007       CPSRDef = MI;
1008       HighLatencyCPSR = isHighLatencyCPSR(CPSRDef);
1009       IsSelfLoop = false;
1010     }
1011   }
1012
1013   MBBInfo &Info = BlockInfo[MBB.getNumber()];
1014   Info.HighLatencyCPSR = HighLatencyCPSR;
1015   Info.Visited = true;
1016   return Modified;
1017 }
1018
1019 bool Thumb2SizeReduce::runOnMachineFunction(MachineFunction &MF) {
1020   STI = &static_cast<const ARMSubtarget &>(MF.getSubtarget());
1021   if (STI->isThumb1Only() || STI->prefers32BitThumb())
1022     return false;
1023
1024   TII = static_cast<const Thumb2InstrInfo *>(STI->getInstrInfo());
1025
1026   // Optimizing / minimizing size?
1027   OptimizeSize = MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
1028   MinimizeSize = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1029
1030   BlockInfo.clear();
1031   BlockInfo.resize(MF.getNumBlockIDs());
1032
1033   // Visit blocks in reverse post-order so LastCPSRDef is known for all
1034   // predecessors.
1035   ReversePostOrderTraversal<MachineFunction*> RPOT(&MF);
1036   bool Modified = false;
1037   for (ReversePostOrderTraversal<MachineFunction*>::rpo_iterator
1038        I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
1039     Modified |= ReduceMBB(**I);
1040   return Modified;
1041 }
1042
1043 /// createThumb2SizeReductionPass - Returns an instance of the Thumb2 size
1044 /// reduction pass.
1045 FunctionPass *llvm::createThumb2SizeReductionPass() {
1046   return new Thumb2SizeReduce();
1047 }