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