xref: /openbsd-src/gnu/llvm/llvm/lib/Target/ARM/Thumb2SizeReduction.cpp (revision d415bd752c734aee168c4ee86ff32e8cc249eb16)
109467b48Spatrick //===-- Thumb2SizeReduction.cpp - Thumb2 code size reduction pass -*- C++ -*-=//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick 
909467b48Spatrick #include "ARM.h"
1009467b48Spatrick #include "ARMBaseInstrInfo.h"
1109467b48Spatrick #include "ARMSubtarget.h"
1209467b48Spatrick #include "MCTargetDesc/ARMBaseInfo.h"
1309467b48Spatrick #include "Thumb2InstrInfo.h"
1409467b48Spatrick #include "llvm/ADT/DenseMap.h"
1509467b48Spatrick #include "llvm/ADT/PostOrderIterator.h"
1609467b48Spatrick #include "llvm/ADT/STLExtras.h"
1709467b48Spatrick #include "llvm/ADT/SmallSet.h"
1809467b48Spatrick #include "llvm/ADT/SmallVector.h"
1909467b48Spatrick #include "llvm/ADT/Statistic.h"
2009467b48Spatrick #include "llvm/ADT/StringRef.h"
2109467b48Spatrick #include "llvm/CodeGen/MachineBasicBlock.h"
2209467b48Spatrick #include "llvm/CodeGen/MachineFunction.h"
2309467b48Spatrick #include "llvm/CodeGen/MachineFunctionPass.h"
2409467b48Spatrick #include "llvm/CodeGen/MachineInstr.h"
2509467b48Spatrick #include "llvm/CodeGen/MachineInstrBuilder.h"
2609467b48Spatrick #include "llvm/CodeGen/MachineOperand.h"
2709467b48Spatrick #include "llvm/CodeGen/TargetInstrInfo.h"
2809467b48Spatrick #include "llvm/IR/DebugLoc.h"
2909467b48Spatrick #include "llvm/IR/Function.h"
30*d415bd75Srobert #include "llvm/MC/MCAsmInfo.h"
3109467b48Spatrick #include "llvm/MC/MCInstrDesc.h"
3209467b48Spatrick #include "llvm/MC/MCRegisterInfo.h"
3309467b48Spatrick #include "llvm/Support/CommandLine.h"
3409467b48Spatrick #include "llvm/Support/Compiler.h"
3509467b48Spatrick #include "llvm/Support/Debug.h"
3609467b48Spatrick #include "llvm/Support/ErrorHandling.h"
3709467b48Spatrick #include "llvm/Support/raw_ostream.h"
3809467b48Spatrick #include <algorithm>
3909467b48Spatrick #include <cassert>
4009467b48Spatrick #include <cstdint>
4109467b48Spatrick #include <functional>
4209467b48Spatrick #include <iterator>
4309467b48Spatrick #include <utility>
4409467b48Spatrick 
4509467b48Spatrick using namespace llvm;
4609467b48Spatrick 
4773471bf0Spatrick #define DEBUG_TYPE "thumb2-reduce-size"
4809467b48Spatrick #define THUMB2_SIZE_REDUCE_NAME "Thumb2 instruction size reduce pass"
4909467b48Spatrick 
5009467b48Spatrick STATISTIC(NumNarrows,  "Number of 32-bit instrs reduced to 16-bit ones");
5109467b48Spatrick STATISTIC(Num2Addrs,   "Number of 32-bit instrs reduced to 2addr 16-bit ones");
5209467b48Spatrick STATISTIC(NumLdSts,    "Number of 32-bit load / store reduced to 16-bit ones");
5309467b48Spatrick 
5409467b48Spatrick static cl::opt<int> ReduceLimit("t2-reduce-limit",
5509467b48Spatrick                                 cl::init(-1), cl::Hidden);
5609467b48Spatrick static cl::opt<int> ReduceLimit2Addr("t2-reduce-limit2",
5709467b48Spatrick                                      cl::init(-1), cl::Hidden);
5809467b48Spatrick static cl::opt<int> ReduceLimitLdSt("t2-reduce-limit3",
5909467b48Spatrick                                      cl::init(-1), cl::Hidden);
6009467b48Spatrick 
6109467b48Spatrick namespace {
6209467b48Spatrick 
6309467b48Spatrick   /// ReduceTable - A static table with information on mapping from wide
6409467b48Spatrick   /// opcodes to narrow
6509467b48Spatrick   struct ReduceEntry {
6609467b48Spatrick     uint16_t WideOpc;      // Wide opcode
6709467b48Spatrick     uint16_t NarrowOpc1;   // Narrow opcode to transform to
6809467b48Spatrick     uint16_t NarrowOpc2;   // Narrow opcode when it's two-address
6909467b48Spatrick     uint8_t  Imm1Limit;    // Limit of immediate field (bits)
7009467b48Spatrick     uint8_t  Imm2Limit;    // Limit of immediate field when it's two-address
7109467b48Spatrick     unsigned LowRegs1 : 1; // Only possible if low-registers are used
7209467b48Spatrick     unsigned LowRegs2 : 1; // Only possible if low-registers are used (2addr)
7309467b48Spatrick     unsigned PredCC1  : 2; // 0 - If predicated, cc is on and vice versa.
7409467b48Spatrick                            // 1 - No cc field.
7509467b48Spatrick                            // 2 - Always set CPSR.
7609467b48Spatrick     unsigned PredCC2  : 2;
7709467b48Spatrick     unsigned PartFlag : 1; // 16-bit instruction does partial flag update
7809467b48Spatrick     unsigned Special  : 1; // Needs to be dealt with specially
7909467b48Spatrick     unsigned AvoidMovs: 1; // Avoid movs with shifter operand (for Swift)
8009467b48Spatrick   };
8109467b48Spatrick 
8209467b48Spatrick   static const ReduceEntry ReduceTable[] = {
8309467b48Spatrick   // Wide,        Narrow1,      Narrow2,     imm1,imm2, lo1, lo2, P/C,PF,S,AM
8409467b48Spatrick   { ARM::t2ADCrr, 0,            ARM::tADC,     0,   0,   0,   1,  0,0, 0,0,0 },
8509467b48Spatrick   { ARM::t2ADDri, ARM::tADDi3,  ARM::tADDi8,   3,   8,   1,   1,  0,0, 0,1,0 },
8609467b48Spatrick   { ARM::t2ADDrr, ARM::tADDrr,  ARM::tADDhirr, 0,   0,   1,   0,  0,1, 0,0,0 },
8709467b48Spatrick   { ARM::t2ADDSri,ARM::tADDi3,  ARM::tADDi8,   3,   8,   1,   1,  2,2, 0,1,0 },
8809467b48Spatrick   { ARM::t2ADDSrr,ARM::tADDrr,  0,             0,   0,   1,   0,  2,0, 0,1,0 },
8909467b48Spatrick   { ARM::t2ANDrr, 0,            ARM::tAND,     0,   0,   0,   1,  0,0, 1,0,0 },
9009467b48Spatrick   { ARM::t2ASRri, ARM::tASRri,  0,             5,   0,   1,   0,  0,0, 1,0,1 },
9109467b48Spatrick   { ARM::t2ASRrr, 0,            ARM::tASRrr,   0,   0,   0,   1,  0,0, 1,0,1 },
9209467b48Spatrick   { ARM::t2BICrr, 0,            ARM::tBIC,     0,   0,   0,   1,  0,0, 1,0,0 },
9309467b48Spatrick   //FIXME: Disable CMN, as CCodes are backwards from compare expectations
9409467b48Spatrick   //{ ARM::t2CMNrr, ARM::tCMN,  0,             0,   0,   1,   0,  2,0, 0,0,0 },
9509467b48Spatrick   { ARM::t2CMNzrr, ARM::tCMNz,  0,             0,   0,   1,   0,  2,0, 0,0,0 },
9609467b48Spatrick   { ARM::t2CMPri, ARM::tCMPi8,  0,             8,   0,   1,   0,  2,0, 0,0,0 },
9709467b48Spatrick   { ARM::t2CMPrr, ARM::tCMPhir, 0,             0,   0,   0,   0,  2,0, 0,1,0 },
9809467b48Spatrick   { ARM::t2EORrr, 0,            ARM::tEOR,     0,   0,   0,   1,  0,0, 1,0,0 },
9909467b48Spatrick   // FIXME: adr.n immediate offset must be multiple of 4.
10009467b48Spatrick   //{ ARM::t2LEApcrelJT,ARM::tLEApcrelJT, 0,   0,   0,   1,   0,  1,0, 0,0,0 },
10109467b48Spatrick   { ARM::t2LSLri, ARM::tLSLri,  0,             5,   0,   1,   0,  0,0, 1,0,1 },
10209467b48Spatrick   { ARM::t2LSLrr, 0,            ARM::tLSLrr,   0,   0,   0,   1,  0,0, 1,0,1 },
10309467b48Spatrick   { ARM::t2LSRri, ARM::tLSRri,  0,             5,   0,   1,   0,  0,0, 1,0,1 },
10409467b48Spatrick   { ARM::t2LSRrr, 0,            ARM::tLSRrr,   0,   0,   0,   1,  0,0, 1,0,1 },
10509467b48Spatrick   { ARM::t2MOVi,  ARM::tMOVi8,  0,             8,   0,   1,   0,  0,0, 1,0,0 },
10609467b48Spatrick   { ARM::t2MOVi16,ARM::tMOVi8,  0,             8,   0,   1,   0,  0,0, 1,1,0 },
10709467b48Spatrick   // FIXME: Do we need the 16-bit 'S' variant?
10809467b48Spatrick   { ARM::t2MOVr,ARM::tMOVr,     0,             0,   0,   0,   0,  1,0, 0,0,0 },
10909467b48Spatrick   { ARM::t2MUL,   0,            ARM::tMUL,     0,   0,   0,   1,  0,0, 1,0,0 },
11009467b48Spatrick   { ARM::t2MVNr,  ARM::tMVN,    0,             0,   0,   1,   0,  0,0, 0,0,0 },
11109467b48Spatrick   { ARM::t2ORRrr, 0,            ARM::tORR,     0,   0,   0,   1,  0,0, 1,0,0 },
11209467b48Spatrick   { ARM::t2REV,   ARM::tREV,    0,             0,   0,   1,   0,  1,0, 0,0,0 },
11309467b48Spatrick   { ARM::t2REV16, ARM::tREV16,  0,             0,   0,   1,   0,  1,0, 0,0,0 },
11409467b48Spatrick   { ARM::t2REVSH, ARM::tREVSH,  0,             0,   0,   1,   0,  1,0, 0,0,0 },
11509467b48Spatrick   { ARM::t2RORrr, 0,            ARM::tROR,     0,   0,   0,   1,  0,0, 1,0,0 },
11609467b48Spatrick   { ARM::t2RSBri, ARM::tRSB,    0,             0,   0,   1,   0,  0,0, 0,1,0 },
11709467b48Spatrick   { ARM::t2RSBSri,ARM::tRSB,    0,             0,   0,   1,   0,  2,0, 0,1,0 },
11809467b48Spatrick   { ARM::t2SBCrr, 0,            ARM::tSBC,     0,   0,   0,   1,  0,0, 0,0,0 },
11909467b48Spatrick   { ARM::t2SUBri, ARM::tSUBi3,  ARM::tSUBi8,   3,   8,   1,   1,  0,0, 0,0,0 },
12009467b48Spatrick   { ARM::t2SUBrr, ARM::tSUBrr,  0,             0,   0,   1,   0,  0,0, 0,0,0 },
12109467b48Spatrick   { ARM::t2SUBSri,ARM::tSUBi3,  ARM::tSUBi8,   3,   8,   1,   1,  2,2, 0,0,0 },
12209467b48Spatrick   { ARM::t2SUBSrr,ARM::tSUBrr,  0,             0,   0,   1,   0,  2,0, 0,0,0 },
12309467b48Spatrick   { ARM::t2SXTB,  ARM::tSXTB,   0,             0,   0,   1,   0,  1,0, 0,1,0 },
12409467b48Spatrick   { ARM::t2SXTH,  ARM::tSXTH,   0,             0,   0,   1,   0,  1,0, 0,1,0 },
12509467b48Spatrick   { ARM::t2TEQrr, ARM::tEOR,    0,             0,   0,   1,   0,  2,0, 0,1,0 },
12609467b48Spatrick   { ARM::t2TSTrr, ARM::tTST,    0,             0,   0,   1,   0,  2,0, 0,0,0 },
12709467b48Spatrick   { ARM::t2UXTB,  ARM::tUXTB,   0,             0,   0,   1,   0,  1,0, 0,1,0 },
12809467b48Spatrick   { ARM::t2UXTH,  ARM::tUXTH,   0,             0,   0,   1,   0,  1,0, 0,1,0 },
12909467b48Spatrick 
13009467b48Spatrick   // FIXME: Clean this up after splitting each Thumb load / store opcode
13109467b48Spatrick   // into multiple ones.
13209467b48Spatrick   { ARM::t2LDRi12,ARM::tLDRi,   ARM::tLDRspi,  5,   8,   1,   0,  0,0, 0,1,0 },
13309467b48Spatrick   { ARM::t2LDRs,  ARM::tLDRr,   0,             0,   0,   1,   0,  0,0, 0,1,0 },
13409467b48Spatrick   { ARM::t2LDRBi12,ARM::tLDRBi, 0,             5,   0,   1,   0,  0,0, 0,1,0 },
13509467b48Spatrick   { ARM::t2LDRBs, ARM::tLDRBr,  0,             0,   0,   1,   0,  0,0, 0,1,0 },
13609467b48Spatrick   { ARM::t2LDRHi12,ARM::tLDRHi, 0,             5,   0,   1,   0,  0,0, 0,1,0 },
13709467b48Spatrick   { ARM::t2LDRHs, ARM::tLDRHr,  0,             0,   0,   1,   0,  0,0, 0,1,0 },
13809467b48Spatrick   { ARM::t2LDRSBs,ARM::tLDRSB,  0,             0,   0,   1,   0,  0,0, 0,1,0 },
13909467b48Spatrick   { ARM::t2LDRSHs,ARM::tLDRSH,  0,             0,   0,   1,   0,  0,0, 0,1,0 },
14009467b48Spatrick   { ARM::t2LDR_POST,ARM::tLDMIA_UPD,0,         0,   0,   1,   0,  0,0, 0,1,0 },
14109467b48Spatrick   { ARM::t2STRi12,ARM::tSTRi,   ARM::tSTRspi,  5,   8,   1,   0,  0,0, 0,1,0 },
14209467b48Spatrick   { ARM::t2STRs,  ARM::tSTRr,   0,             0,   0,   1,   0,  0,0, 0,1,0 },
14309467b48Spatrick   { ARM::t2STRBi12,ARM::tSTRBi, 0,             5,   0,   1,   0,  0,0, 0,1,0 },
14409467b48Spatrick   { ARM::t2STRBs, ARM::tSTRBr,  0,             0,   0,   1,   0,  0,0, 0,1,0 },
14509467b48Spatrick   { ARM::t2STRHi12,ARM::tSTRHi, 0,             5,   0,   1,   0,  0,0, 0,1,0 },
14609467b48Spatrick   { ARM::t2STRHs, ARM::tSTRHr,  0,             0,   0,   1,   0,  0,0, 0,1,0 },
14709467b48Spatrick   { ARM::t2STR_POST,ARM::tSTMIA_UPD,0,         0,   0,   1,   0,  0,0, 0,1,0 },
14809467b48Spatrick 
14909467b48Spatrick   { ARM::t2LDMIA, ARM::tLDMIA,  0,             0,   0,   1,   1,  1,1, 0,1,0 },
15009467b48Spatrick   { ARM::t2LDMIA_RET,0,         ARM::tPOP_RET, 0,   0,   1,   1,  1,1, 0,1,0 },
15109467b48Spatrick   { ARM::t2LDMIA_UPD,ARM::tLDMIA_UPD,ARM::tPOP,0,   0,   1,   1,  1,1, 0,1,0 },
15209467b48Spatrick   // ARM::t2STMIA (with no basereg writeback) has no Thumb1 equivalent.
15309467b48Spatrick   // tSTMIA_UPD is a change in semantics which can only be used if the base
15409467b48Spatrick   // register is killed. This difference is correctly handled elsewhere.
15509467b48Spatrick   { ARM::t2STMIA, ARM::tSTMIA_UPD, 0,          0,   0,   1,   1,  1,1, 0,1,0 },
15609467b48Spatrick   { ARM::t2STMIA_UPD,ARM::tSTMIA_UPD, 0,       0,   0,   1,   1,  1,1, 0,1,0 },
15709467b48Spatrick   { ARM::t2STMDB_UPD, 0,        ARM::tPUSH,    0,   0,   1,   1,  1,1, 0,1,0 }
15809467b48Spatrick   };
15909467b48Spatrick 
16009467b48Spatrick   class Thumb2SizeReduce : public MachineFunctionPass {
16109467b48Spatrick   public:
16209467b48Spatrick     static char ID;
16309467b48Spatrick 
16409467b48Spatrick     const Thumb2InstrInfo *TII;
16509467b48Spatrick     const ARMSubtarget *STI;
16609467b48Spatrick 
16709467b48Spatrick     Thumb2SizeReduce(std::function<bool(const Function &)> Ftor = nullptr);
16809467b48Spatrick 
16909467b48Spatrick     bool runOnMachineFunction(MachineFunction &MF) override;
17009467b48Spatrick 
getRequiredProperties() const17109467b48Spatrick     MachineFunctionProperties getRequiredProperties() const override {
17209467b48Spatrick       return MachineFunctionProperties().set(
17309467b48Spatrick           MachineFunctionProperties::Property::NoVRegs);
17409467b48Spatrick     }
17509467b48Spatrick 
getPassName() const17609467b48Spatrick     StringRef getPassName() const override {
17709467b48Spatrick       return THUMB2_SIZE_REDUCE_NAME;
17809467b48Spatrick     }
17909467b48Spatrick 
18009467b48Spatrick   private:
18109467b48Spatrick     /// ReduceOpcodeMap - Maps wide opcode to index of entry in ReduceTable.
18209467b48Spatrick     DenseMap<unsigned, unsigned> ReduceOpcodeMap;
18309467b48Spatrick 
18409467b48Spatrick     bool canAddPseudoFlagDep(MachineInstr *Use, bool IsSelfLoop);
18509467b48Spatrick 
18609467b48Spatrick     bool VerifyPredAndCC(MachineInstr *MI, const ReduceEntry &Entry,
18709467b48Spatrick                          bool is2Addr, ARMCC::CondCodes Pred,
18809467b48Spatrick                          bool LiveCPSR, bool &HasCC, bool &CCDead);
18909467b48Spatrick 
19009467b48Spatrick     bool ReduceLoadStore(MachineBasicBlock &MBB, MachineInstr *MI,
19109467b48Spatrick                          const ReduceEntry &Entry);
19209467b48Spatrick 
19309467b48Spatrick     bool ReduceSpecial(MachineBasicBlock &MBB, MachineInstr *MI,
19409467b48Spatrick                        const ReduceEntry &Entry, bool LiveCPSR, bool IsSelfLoop);
19509467b48Spatrick 
19609467b48Spatrick     /// ReduceTo2Addr - Reduce a 32-bit instruction to a 16-bit two-address
19709467b48Spatrick     /// instruction.
19809467b48Spatrick     bool ReduceTo2Addr(MachineBasicBlock &MBB, MachineInstr *MI,
19909467b48Spatrick                        const ReduceEntry &Entry, bool LiveCPSR,
20009467b48Spatrick                        bool IsSelfLoop);
20109467b48Spatrick 
20209467b48Spatrick     /// ReduceToNarrow - Reduce a 32-bit instruction to a 16-bit
20309467b48Spatrick     /// non-two-address instruction.
20409467b48Spatrick     bool ReduceToNarrow(MachineBasicBlock &MBB, MachineInstr *MI,
20509467b48Spatrick                         const ReduceEntry &Entry, bool LiveCPSR,
20609467b48Spatrick                         bool IsSelfLoop);
20709467b48Spatrick 
20809467b48Spatrick     /// ReduceMI - Attempt to reduce MI, return true on success.
209*d415bd75Srobert     bool ReduceMI(MachineBasicBlock &MBB, MachineInstr *MI, bool LiveCPSR,
210*d415bd75Srobert                   bool IsSelfLoop, bool SkipPrologueEpilogue);
21109467b48Spatrick 
21209467b48Spatrick     /// ReduceMBB - Reduce width of instructions in the specified basic block.
213*d415bd75Srobert     bool ReduceMBB(MachineBasicBlock &MBB, bool SkipPrologueEpilogue);
21409467b48Spatrick 
21509467b48Spatrick     bool OptimizeSize;
21609467b48Spatrick     bool MinimizeSize;
21709467b48Spatrick 
21809467b48Spatrick     // Last instruction to define CPSR in the current block.
21909467b48Spatrick     MachineInstr *CPSRDef;
22009467b48Spatrick     // Was CPSR last defined by a high latency instruction?
22109467b48Spatrick     // When CPSRDef is null, this refers to CPSR defs in predecessors.
22209467b48Spatrick     bool HighLatencyCPSR;
22309467b48Spatrick 
22409467b48Spatrick     struct MBBInfo {
22509467b48Spatrick       // The flags leaving this block have high latency.
22609467b48Spatrick       bool HighLatencyCPSR = false;
22709467b48Spatrick       // Has this block been visited yet?
22809467b48Spatrick       bool Visited = false;
22909467b48Spatrick 
23009467b48Spatrick       MBBInfo() = default;
23109467b48Spatrick     };
23209467b48Spatrick 
23309467b48Spatrick     SmallVector<MBBInfo, 8> BlockInfo;
23409467b48Spatrick 
23509467b48Spatrick     std::function<bool(const Function &)> PredicateFtor;
23609467b48Spatrick   };
23709467b48Spatrick 
23809467b48Spatrick   char Thumb2SizeReduce::ID = 0;
23909467b48Spatrick 
24009467b48Spatrick } // end anonymous namespace
24109467b48Spatrick 
INITIALIZE_PASS(Thumb2SizeReduce,DEBUG_TYPE,THUMB2_SIZE_REDUCE_NAME,false,false)24209467b48Spatrick INITIALIZE_PASS(Thumb2SizeReduce, DEBUG_TYPE, THUMB2_SIZE_REDUCE_NAME, false,
24309467b48Spatrick                 false)
24409467b48Spatrick 
24509467b48Spatrick Thumb2SizeReduce::Thumb2SizeReduce(std::function<bool(const Function &)> Ftor)
24609467b48Spatrick     : MachineFunctionPass(ID), PredicateFtor(std::move(Ftor)) {
24709467b48Spatrick   OptimizeSize = MinimizeSize = false;
248*d415bd75Srobert   for (unsigned i = 0, e = std::size(ReduceTable); i != e; ++i) {
24909467b48Spatrick     unsigned FromOpc = ReduceTable[i].WideOpc;
25009467b48Spatrick     if (!ReduceOpcodeMap.insert(std::make_pair(FromOpc, i)).second)
25109467b48Spatrick       llvm_unreachable("Duplicated entries?");
25209467b48Spatrick   }
25309467b48Spatrick }
25409467b48Spatrick 
HasImplicitCPSRDef(const MCInstrDesc & MCID)25509467b48Spatrick static bool HasImplicitCPSRDef(const MCInstrDesc &MCID) {
256*d415bd75Srobert   return is_contained(MCID.implicit_defs(), ARM::CPSR);
25709467b48Spatrick }
25809467b48Spatrick 
25909467b48Spatrick // Check for a likely high-latency flag def.
isHighLatencyCPSR(MachineInstr * Def)26009467b48Spatrick static bool isHighLatencyCPSR(MachineInstr *Def) {
26109467b48Spatrick   switch(Def->getOpcode()) {
26209467b48Spatrick   case ARM::FMSTAT:
26309467b48Spatrick   case ARM::tMUL:
26409467b48Spatrick     return true;
26509467b48Spatrick   }
26609467b48Spatrick   return false;
26709467b48Spatrick }
26809467b48Spatrick 
26909467b48Spatrick /// canAddPseudoFlagDep - For A9 (and other out-of-order) implementations,
27009467b48Spatrick /// the 's' 16-bit instruction partially update CPSR. Abort the
27109467b48Spatrick /// transformation to avoid adding false dependency on last CPSR setting
27209467b48Spatrick /// instruction which hurts the ability for out-of-order execution engine
27309467b48Spatrick /// to do register renaming magic.
27409467b48Spatrick /// This function checks if there is a read-of-write dependency between the
27509467b48Spatrick /// last instruction that defines the CPSR and the current instruction. If there
27609467b48Spatrick /// is, then there is no harm done since the instruction cannot be retired
27709467b48Spatrick /// before the CPSR setting instruction anyway.
27809467b48Spatrick /// Note, we are not doing full dependency analysis here for the sake of compile
27909467b48Spatrick /// time. We're not looking for cases like:
28009467b48Spatrick /// r0 = muls ...
28109467b48Spatrick /// r1 = add.w r0, ...
28209467b48Spatrick /// ...
28309467b48Spatrick ///    = mul.w r1
28409467b48Spatrick /// In this case it would have been ok to narrow the mul.w to muls since there
28509467b48Spatrick /// are indirect RAW dependency between the muls and the mul.w
28609467b48Spatrick bool
canAddPseudoFlagDep(MachineInstr * Use,bool FirstInSelfLoop)28709467b48Spatrick Thumb2SizeReduce::canAddPseudoFlagDep(MachineInstr *Use, bool FirstInSelfLoop) {
28809467b48Spatrick   // Disable the check for -Oz (aka OptimizeForSizeHarder).
28909467b48Spatrick   if (MinimizeSize || !STI->avoidCPSRPartialUpdate())
29009467b48Spatrick     return false;
29109467b48Spatrick 
29209467b48Spatrick   if (!CPSRDef)
29309467b48Spatrick     // If this BB loops back to itself, conservatively avoid narrowing the
29409467b48Spatrick     // first instruction that does partial flag update.
29509467b48Spatrick     return HighLatencyCPSR || FirstInSelfLoop;
29609467b48Spatrick 
29709467b48Spatrick   SmallSet<unsigned, 2> Defs;
29809467b48Spatrick   for (const MachineOperand &MO : CPSRDef->operands()) {
29909467b48Spatrick     if (!MO.isReg() || MO.isUndef() || MO.isUse())
30009467b48Spatrick       continue;
30109467b48Spatrick     Register Reg = MO.getReg();
30209467b48Spatrick     if (Reg == 0 || Reg == ARM::CPSR)
30309467b48Spatrick       continue;
30409467b48Spatrick     Defs.insert(Reg);
30509467b48Spatrick   }
30609467b48Spatrick 
30709467b48Spatrick   for (const MachineOperand &MO : Use->operands()) {
30809467b48Spatrick     if (!MO.isReg() || MO.isUndef() || MO.isDef())
30909467b48Spatrick       continue;
31009467b48Spatrick     Register Reg = MO.getReg();
31109467b48Spatrick     if (Defs.count(Reg))
31209467b48Spatrick       return false;
31309467b48Spatrick   }
31409467b48Spatrick 
31509467b48Spatrick   // If the current CPSR has high latency, try to avoid the false dependency.
31609467b48Spatrick   if (HighLatencyCPSR)
31709467b48Spatrick     return true;
31809467b48Spatrick 
31909467b48Spatrick   // tMOVi8 usually doesn't start long dependency chains, and there are a lot
32009467b48Spatrick   // of them, so always shrink them when CPSR doesn't have high latency.
32109467b48Spatrick   if (Use->getOpcode() == ARM::t2MOVi ||
32209467b48Spatrick       Use->getOpcode() == ARM::t2MOVi16)
32309467b48Spatrick     return false;
32409467b48Spatrick 
32509467b48Spatrick   // No read-after-write dependency. The narrowing will add false dependency.
32609467b48Spatrick   return true;
32709467b48Spatrick }
32809467b48Spatrick 
32909467b48Spatrick bool
VerifyPredAndCC(MachineInstr * MI,const ReduceEntry & Entry,bool is2Addr,ARMCC::CondCodes Pred,bool LiveCPSR,bool & HasCC,bool & CCDead)33009467b48Spatrick Thumb2SizeReduce::VerifyPredAndCC(MachineInstr *MI, const ReduceEntry &Entry,
33109467b48Spatrick                                   bool is2Addr, ARMCC::CondCodes Pred,
33209467b48Spatrick                                   bool LiveCPSR, bool &HasCC, bool &CCDead) {
33309467b48Spatrick   if ((is2Addr  && Entry.PredCC2 == 0) ||
33409467b48Spatrick       (!is2Addr && Entry.PredCC1 == 0)) {
33509467b48Spatrick     if (Pred == ARMCC::AL) {
33609467b48Spatrick       // Not predicated, must set CPSR.
33709467b48Spatrick       if (!HasCC) {
33809467b48Spatrick         // Original instruction was not setting CPSR, but CPSR is not
33909467b48Spatrick         // currently live anyway. It's ok to set it. The CPSR def is
34009467b48Spatrick         // dead though.
34109467b48Spatrick         if (!LiveCPSR) {
34209467b48Spatrick           HasCC = true;
34309467b48Spatrick           CCDead = true;
34409467b48Spatrick           return true;
34509467b48Spatrick         }
34609467b48Spatrick         return false;
34709467b48Spatrick       }
34809467b48Spatrick     } else {
34909467b48Spatrick       // Predicated, must not set CPSR.
35009467b48Spatrick       if (HasCC)
35109467b48Spatrick         return false;
35209467b48Spatrick     }
35309467b48Spatrick   } else if ((is2Addr  && Entry.PredCC2 == 2) ||
35409467b48Spatrick              (!is2Addr && Entry.PredCC1 == 2)) {
35509467b48Spatrick     /// Old opcode has an optional def of CPSR.
35609467b48Spatrick     if (HasCC)
35709467b48Spatrick       return true;
35809467b48Spatrick     // If old opcode does not implicitly define CPSR, then it's not ok since
35909467b48Spatrick     // these new opcodes' CPSR def is not meant to be thrown away. e.g. CMP.
36009467b48Spatrick     if (!HasImplicitCPSRDef(MI->getDesc()))
36109467b48Spatrick       return false;
36209467b48Spatrick     HasCC = true;
36309467b48Spatrick   } else {
36409467b48Spatrick     // 16-bit instruction does not set CPSR.
36509467b48Spatrick     if (HasCC)
36609467b48Spatrick       return false;
36709467b48Spatrick   }
36809467b48Spatrick 
36909467b48Spatrick   return true;
37009467b48Spatrick }
37109467b48Spatrick 
VerifyLowRegs(MachineInstr * MI)37209467b48Spatrick static bool VerifyLowRegs(MachineInstr *MI) {
37309467b48Spatrick   unsigned Opc = MI->getOpcode();
37409467b48Spatrick   bool isPCOk = (Opc == ARM::t2LDMIA_RET || Opc == ARM::t2LDMIA_UPD);
37509467b48Spatrick   bool isLROk = (Opc == ARM::t2STMDB_UPD);
37609467b48Spatrick   bool isSPOk = isPCOk || isLROk;
37709467b48Spatrick   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
37809467b48Spatrick     const MachineOperand &MO = MI->getOperand(i);
37909467b48Spatrick     if (!MO.isReg() || MO.isImplicit())
38009467b48Spatrick       continue;
38109467b48Spatrick     Register Reg = MO.getReg();
38209467b48Spatrick     if (Reg == 0 || Reg == ARM::CPSR)
38309467b48Spatrick       continue;
38409467b48Spatrick     if (isPCOk && Reg == ARM::PC)
38509467b48Spatrick       continue;
38609467b48Spatrick     if (isLROk && Reg == ARM::LR)
38709467b48Spatrick       continue;
38809467b48Spatrick     if (Reg == ARM::SP) {
38909467b48Spatrick       if (isSPOk)
39009467b48Spatrick         continue;
39109467b48Spatrick       if (i == 1 && (Opc == ARM::t2LDRi12 || Opc == ARM::t2STRi12))
39209467b48Spatrick         // Special case for these ldr / str with sp as base register.
39309467b48Spatrick         continue;
39409467b48Spatrick     }
39509467b48Spatrick     if (!isARMLowRegister(Reg))
39609467b48Spatrick       return false;
39709467b48Spatrick   }
39809467b48Spatrick   return true;
39909467b48Spatrick }
40009467b48Spatrick 
40109467b48Spatrick bool
ReduceLoadStore(MachineBasicBlock & MBB,MachineInstr * MI,const ReduceEntry & Entry)40209467b48Spatrick Thumb2SizeReduce::ReduceLoadStore(MachineBasicBlock &MBB, MachineInstr *MI,
40309467b48Spatrick                                   const ReduceEntry &Entry) {
40409467b48Spatrick   if (ReduceLimitLdSt != -1 && ((int)NumLdSts >= ReduceLimitLdSt))
40509467b48Spatrick     return false;
40609467b48Spatrick 
40709467b48Spatrick   unsigned Scale = 1;
40809467b48Spatrick   bool HasImmOffset = false;
40909467b48Spatrick   bool HasShift = false;
41009467b48Spatrick   bool HasOffReg = true;
41109467b48Spatrick   bool isLdStMul = false;
41209467b48Spatrick   unsigned Opc = Entry.NarrowOpc1;
41309467b48Spatrick   unsigned OpNum = 3; // First 'rest' of operands.
41409467b48Spatrick   uint8_t  ImmLimit = Entry.Imm1Limit;
41509467b48Spatrick 
41609467b48Spatrick   switch (Entry.WideOpc) {
41709467b48Spatrick   default:
41809467b48Spatrick     llvm_unreachable("Unexpected Thumb2 load / store opcode!");
41909467b48Spatrick   case ARM::t2LDRi12:
42009467b48Spatrick   case ARM::t2STRi12:
42109467b48Spatrick     if (MI->getOperand(1).getReg() == ARM::SP) {
42209467b48Spatrick       Opc = Entry.NarrowOpc2;
42309467b48Spatrick       ImmLimit = Entry.Imm2Limit;
42409467b48Spatrick     }
42509467b48Spatrick 
42609467b48Spatrick     Scale = 4;
42709467b48Spatrick     HasImmOffset = true;
42809467b48Spatrick     HasOffReg = false;
42909467b48Spatrick     break;
43009467b48Spatrick   case ARM::t2LDRBi12:
43109467b48Spatrick   case ARM::t2STRBi12:
43209467b48Spatrick     HasImmOffset = true;
43309467b48Spatrick     HasOffReg = false;
43409467b48Spatrick     break;
43509467b48Spatrick   case ARM::t2LDRHi12:
43609467b48Spatrick   case ARM::t2STRHi12:
43709467b48Spatrick     Scale = 2;
43809467b48Spatrick     HasImmOffset = true;
43909467b48Spatrick     HasOffReg = false;
44009467b48Spatrick     break;
44109467b48Spatrick   case ARM::t2LDRs:
44209467b48Spatrick   case ARM::t2LDRBs:
44309467b48Spatrick   case ARM::t2LDRHs:
44409467b48Spatrick   case ARM::t2LDRSBs:
44509467b48Spatrick   case ARM::t2LDRSHs:
44609467b48Spatrick   case ARM::t2STRs:
44709467b48Spatrick   case ARM::t2STRBs:
44809467b48Spatrick   case ARM::t2STRHs:
44909467b48Spatrick     HasShift = true;
45009467b48Spatrick     OpNum = 4;
45109467b48Spatrick     break;
45209467b48Spatrick   case ARM::t2LDR_POST:
45309467b48Spatrick   case ARM::t2STR_POST: {
45409467b48Spatrick     if (!MinimizeSize)
45509467b48Spatrick       return false;
45609467b48Spatrick 
45709467b48Spatrick     if (!MI->hasOneMemOperand() ||
458097a140dSpatrick         (*MI->memoperands_begin())->getAlign() < Align(4))
45909467b48Spatrick       return false;
46009467b48Spatrick 
46109467b48Spatrick     // We're creating a completely different type of load/store - LDM from LDR.
46209467b48Spatrick     // For this reason we can't reuse the logic at the end of this function; we
46309467b48Spatrick     // have to implement the MI building here.
46409467b48Spatrick     bool IsStore = Entry.WideOpc == ARM::t2STR_POST;
46509467b48Spatrick     Register Rt = MI->getOperand(IsStore ? 1 : 0).getReg();
46609467b48Spatrick     Register Rn = MI->getOperand(IsStore ? 0 : 1).getReg();
46709467b48Spatrick     unsigned Offset = MI->getOperand(3).getImm();
46809467b48Spatrick     unsigned PredImm = MI->getOperand(4).getImm();
46909467b48Spatrick     Register PredReg = MI->getOperand(5).getReg();
47009467b48Spatrick     assert(isARMLowRegister(Rt));
47109467b48Spatrick     assert(isARMLowRegister(Rn));
47209467b48Spatrick 
47309467b48Spatrick     if (Offset != 4)
47409467b48Spatrick       return false;
47509467b48Spatrick 
47609467b48Spatrick     // Add the 16-bit load / store instruction.
47709467b48Spatrick     DebugLoc dl = MI->getDebugLoc();
47809467b48Spatrick     auto MIB = BuildMI(MBB, MI, dl, TII->get(Entry.NarrowOpc1))
47909467b48Spatrick                    .addReg(Rn, RegState::Define)
48009467b48Spatrick                    .addReg(Rn)
48109467b48Spatrick                    .addImm(PredImm)
48209467b48Spatrick                    .addReg(PredReg)
48309467b48Spatrick                    .addReg(Rt, IsStore ? 0 : RegState::Define);
48409467b48Spatrick 
48509467b48Spatrick     // Transfer memoperands.
48609467b48Spatrick     MIB.setMemRefs(MI->memoperands());
48709467b48Spatrick 
48809467b48Spatrick     // Transfer MI flags.
48909467b48Spatrick     MIB.setMIFlags(MI->getFlags());
49009467b48Spatrick 
49109467b48Spatrick     // Kill the old instruction.
49209467b48Spatrick     MI->eraseFromBundle();
49309467b48Spatrick     ++NumLdSts;
49409467b48Spatrick     return true;
49509467b48Spatrick   }
49609467b48Spatrick   case ARM::t2LDMIA: {
49709467b48Spatrick     Register BaseReg = MI->getOperand(0).getReg();
49809467b48Spatrick     assert(isARMLowRegister(BaseReg));
49909467b48Spatrick 
50009467b48Spatrick     // For the non-writeback version (this one), the base register must be
50109467b48Spatrick     // one of the registers being loaded.
50209467b48Spatrick     bool isOK = false;
503*d415bd75Srobert     for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 3)) {
504*d415bd75Srobert       if (MO.getReg() == BaseReg) {
50509467b48Spatrick         isOK = true;
50609467b48Spatrick         break;
50709467b48Spatrick       }
50809467b48Spatrick     }
50909467b48Spatrick 
51009467b48Spatrick     if (!isOK)
51109467b48Spatrick       return false;
51209467b48Spatrick 
51309467b48Spatrick     OpNum = 0;
51409467b48Spatrick     isLdStMul = true;
51509467b48Spatrick     break;
51609467b48Spatrick   }
517097a140dSpatrick   case ARM::t2STMIA: {
518097a140dSpatrick     // t2STMIA is reduced to tSTMIA_UPD which has writeback. We can only do this
519097a140dSpatrick     // if the base register is killed, as then it doesn't matter what its value
520097a140dSpatrick     // is after the instruction.
52109467b48Spatrick     if (!MI->getOperand(0).isKill())
52209467b48Spatrick       return false;
52309467b48Spatrick 
524097a140dSpatrick     // If the base register is in the register list and isn't the lowest
525097a140dSpatrick     // numbered register (i.e. it's in operand 4 onwards) then with writeback
526097a140dSpatrick     // the stored value is unknown, so we can't convert to tSTMIA_UPD.
527097a140dSpatrick     Register BaseReg = MI->getOperand(0).getReg();
528*d415bd75Srobert     for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 4))
529*d415bd75Srobert       if (MO.getReg() == BaseReg)
530097a140dSpatrick         return false;
531097a140dSpatrick 
53209467b48Spatrick     break;
533097a140dSpatrick   }
53409467b48Spatrick   case ARM::t2LDMIA_RET: {
53509467b48Spatrick     Register BaseReg = MI->getOperand(1).getReg();
53609467b48Spatrick     if (BaseReg != ARM::SP)
53709467b48Spatrick       return false;
53809467b48Spatrick     Opc = Entry.NarrowOpc2; // tPOP_RET
53909467b48Spatrick     OpNum = 2;
54009467b48Spatrick     isLdStMul = true;
54109467b48Spatrick     break;
54209467b48Spatrick   }
54309467b48Spatrick   case ARM::t2LDMIA_UPD:
54409467b48Spatrick   case ARM::t2STMIA_UPD:
54509467b48Spatrick   case ARM::t2STMDB_UPD: {
54609467b48Spatrick     OpNum = 0;
54709467b48Spatrick 
54809467b48Spatrick     Register BaseReg = MI->getOperand(1).getReg();
54909467b48Spatrick     if (BaseReg == ARM::SP &&
55009467b48Spatrick         (Entry.WideOpc == ARM::t2LDMIA_UPD ||
55109467b48Spatrick          Entry.WideOpc == ARM::t2STMDB_UPD)) {
55209467b48Spatrick       Opc = Entry.NarrowOpc2; // tPOP or tPUSH
55309467b48Spatrick       OpNum = 2;
55409467b48Spatrick     } else if (!isARMLowRegister(BaseReg) ||
55509467b48Spatrick                (Entry.WideOpc != ARM::t2LDMIA_UPD &&
55609467b48Spatrick                 Entry.WideOpc != ARM::t2STMIA_UPD)) {
55709467b48Spatrick       return false;
55809467b48Spatrick     }
55909467b48Spatrick 
56009467b48Spatrick     isLdStMul = true;
56109467b48Spatrick     break;
56209467b48Spatrick   }
56309467b48Spatrick   }
56409467b48Spatrick 
56509467b48Spatrick   unsigned OffsetReg = 0;
56609467b48Spatrick   bool OffsetKill = false;
56709467b48Spatrick   bool OffsetInternal = false;
56809467b48Spatrick   if (HasShift) {
56909467b48Spatrick     OffsetReg  = MI->getOperand(2).getReg();
57009467b48Spatrick     OffsetKill = MI->getOperand(2).isKill();
57109467b48Spatrick     OffsetInternal = MI->getOperand(2).isInternalRead();
57209467b48Spatrick 
57309467b48Spatrick     if (MI->getOperand(3).getImm())
57409467b48Spatrick       // Thumb1 addressing mode doesn't support shift.
57509467b48Spatrick       return false;
57609467b48Spatrick   }
57709467b48Spatrick 
57809467b48Spatrick   unsigned OffsetImm = 0;
57909467b48Spatrick   if (HasImmOffset) {
58009467b48Spatrick     OffsetImm = MI->getOperand(2).getImm();
58109467b48Spatrick     unsigned MaxOffset = ((1 << ImmLimit) - 1) * Scale;
58209467b48Spatrick 
58309467b48Spatrick     if ((OffsetImm & (Scale - 1)) || OffsetImm > MaxOffset)
58409467b48Spatrick       // Make sure the immediate field fits.
58509467b48Spatrick       return false;
58609467b48Spatrick   }
58709467b48Spatrick 
58809467b48Spatrick   // Add the 16-bit load / store instruction.
58909467b48Spatrick   DebugLoc dl = MI->getDebugLoc();
59009467b48Spatrick   MachineInstrBuilder MIB = BuildMI(MBB, MI, dl, TII->get(Opc));
59109467b48Spatrick 
59209467b48Spatrick   // tSTMIA_UPD takes a defining register operand. We've already checked that
59309467b48Spatrick   // the register is killed, so mark it as dead here.
59409467b48Spatrick   if (Entry.WideOpc == ARM::t2STMIA)
59509467b48Spatrick     MIB.addReg(MI->getOperand(0).getReg(), RegState::Define | RegState::Dead);
59609467b48Spatrick 
59709467b48Spatrick   if (!isLdStMul) {
59809467b48Spatrick     MIB.add(MI->getOperand(0));
59909467b48Spatrick     MIB.add(MI->getOperand(1));
60009467b48Spatrick 
60109467b48Spatrick     if (HasImmOffset)
60209467b48Spatrick       MIB.addImm(OffsetImm / Scale);
60309467b48Spatrick 
60409467b48Spatrick     assert((!HasShift || OffsetReg) && "Invalid so_reg load / store address!");
60509467b48Spatrick 
60609467b48Spatrick     if (HasOffReg)
60709467b48Spatrick       MIB.addReg(OffsetReg, getKillRegState(OffsetKill) |
60809467b48Spatrick                             getInternalReadRegState(OffsetInternal));
60909467b48Spatrick   }
61009467b48Spatrick 
61109467b48Spatrick   // Transfer the rest of operands.
612*d415bd75Srobert   for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), OpNum))
613*d415bd75Srobert     MIB.add(MO);
61409467b48Spatrick 
61509467b48Spatrick   // Transfer memoperands.
61609467b48Spatrick   MIB.setMemRefs(MI->memoperands());
61709467b48Spatrick 
61809467b48Spatrick   // Transfer MI flags.
61909467b48Spatrick   MIB.setMIFlags(MI->getFlags());
62009467b48Spatrick 
621*d415bd75Srobert   LLVM_DEBUG(dbgs() << "Converted 32-bit: " << *MI
62209467b48Spatrick                     << "       to 16-bit: " << *MIB);
62309467b48Spatrick 
62409467b48Spatrick   MBB.erase_instr(MI);
62509467b48Spatrick   ++NumLdSts;
62609467b48Spatrick   return true;
62709467b48Spatrick }
62809467b48Spatrick 
62909467b48Spatrick bool
ReduceSpecial(MachineBasicBlock & MBB,MachineInstr * MI,const ReduceEntry & Entry,bool LiveCPSR,bool IsSelfLoop)63009467b48Spatrick Thumb2SizeReduce::ReduceSpecial(MachineBasicBlock &MBB, MachineInstr *MI,
63109467b48Spatrick                                 const ReduceEntry &Entry,
63209467b48Spatrick                                 bool LiveCPSR, bool IsSelfLoop) {
63309467b48Spatrick   unsigned Opc = MI->getOpcode();
63409467b48Spatrick   if (Opc == ARM::t2ADDri) {
63509467b48Spatrick     // If the source register is SP, try to reduce to tADDrSPi, otherwise
63609467b48Spatrick     // it's a normal reduce.
63709467b48Spatrick     if (MI->getOperand(1).getReg() != ARM::SP) {
63809467b48Spatrick       if (ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, IsSelfLoop))
63909467b48Spatrick         return true;
64009467b48Spatrick       return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
64109467b48Spatrick     }
64209467b48Spatrick     // Try to reduce to tADDrSPi.
64309467b48Spatrick     unsigned Imm = MI->getOperand(2).getImm();
64409467b48Spatrick     // The immediate must be in range, the destination register must be a low
64509467b48Spatrick     // reg, the predicate must be "always" and the condition flags must not
64609467b48Spatrick     // be being set.
64709467b48Spatrick     if (Imm & 3 || Imm > 1020)
64809467b48Spatrick       return false;
64909467b48Spatrick     if (!isARMLowRegister(MI->getOperand(0).getReg()))
65009467b48Spatrick       return false;
65109467b48Spatrick     if (MI->getOperand(3).getImm() != ARMCC::AL)
65209467b48Spatrick       return false;
65309467b48Spatrick     const MCInstrDesc &MCID = MI->getDesc();
65409467b48Spatrick     if (MCID.hasOptionalDef() &&
65509467b48Spatrick         MI->getOperand(MCID.getNumOperands()-1).getReg() == ARM::CPSR)
65609467b48Spatrick       return false;
65709467b48Spatrick 
65809467b48Spatrick     MachineInstrBuilder MIB =
65909467b48Spatrick         BuildMI(MBB, MI, MI->getDebugLoc(),
66009467b48Spatrick                 TII->get(ARM::tADDrSPi))
66109467b48Spatrick             .add(MI->getOperand(0))
66209467b48Spatrick             .add(MI->getOperand(1))
66309467b48Spatrick             .addImm(Imm / 4) // The tADDrSPi has an implied scale by four.
66409467b48Spatrick             .add(predOps(ARMCC::AL));
66509467b48Spatrick 
66609467b48Spatrick     // Transfer MI flags.
66709467b48Spatrick     MIB.setMIFlags(MI->getFlags());
66809467b48Spatrick 
669*d415bd75Srobert     LLVM_DEBUG(dbgs() << "Converted 32-bit: " << *MI
67009467b48Spatrick                       << "       to 16-bit: " << *MIB);
67109467b48Spatrick 
67209467b48Spatrick     MBB.erase_instr(MI);
67309467b48Spatrick     ++NumNarrows;
67409467b48Spatrick     return true;
67509467b48Spatrick   }
67609467b48Spatrick 
67709467b48Spatrick   if (Entry.LowRegs1 && !VerifyLowRegs(MI))
67809467b48Spatrick     return false;
67909467b48Spatrick 
68009467b48Spatrick   if (MI->mayLoadOrStore())
68109467b48Spatrick     return ReduceLoadStore(MBB, MI, Entry);
68209467b48Spatrick 
68309467b48Spatrick   switch (Opc) {
68409467b48Spatrick   default: break;
68509467b48Spatrick   case ARM::t2ADDSri:
68609467b48Spatrick   case ARM::t2ADDSrr: {
687097a140dSpatrick     Register PredReg;
68809467b48Spatrick     if (getInstrPredicate(*MI, PredReg) == ARMCC::AL) {
68909467b48Spatrick       switch (Opc) {
69009467b48Spatrick       default: break;
69109467b48Spatrick       case ARM::t2ADDSri:
69209467b48Spatrick         if (ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, IsSelfLoop))
69309467b48Spatrick           return true;
694*d415bd75Srobert         [[fallthrough]];
69509467b48Spatrick       case ARM::t2ADDSrr:
69609467b48Spatrick         return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
69709467b48Spatrick       }
69809467b48Spatrick     }
69909467b48Spatrick     break;
70009467b48Spatrick   }
70109467b48Spatrick   case ARM::t2RSBri:
70209467b48Spatrick   case ARM::t2RSBSri:
70309467b48Spatrick   case ARM::t2SXTB:
70409467b48Spatrick   case ARM::t2SXTH:
70509467b48Spatrick   case ARM::t2UXTB:
70609467b48Spatrick   case ARM::t2UXTH:
70709467b48Spatrick     if (MI->getOperand(2).getImm() == 0)
70809467b48Spatrick       return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
70909467b48Spatrick     break;
71009467b48Spatrick   case ARM::t2MOVi16:
71109467b48Spatrick     // Can convert only 'pure' immediate operands, not immediates obtained as
71209467b48Spatrick     // globals' addresses.
71309467b48Spatrick     if (MI->getOperand(1).isImm())
71409467b48Spatrick       return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
71509467b48Spatrick     break;
71609467b48Spatrick   case ARM::t2CMPrr: {
71709467b48Spatrick     // Try to reduce to the lo-reg only version first. Why there are two
71809467b48Spatrick     // versions of the instruction is a mystery.
719*d415bd75Srobert     // It would be nice to just have two entries in the main table that
72009467b48Spatrick     // are prioritized, but the table assumes a unique entry for each
72109467b48Spatrick     // source insn opcode. So for now, we hack a local entry record to use.
72209467b48Spatrick     static const ReduceEntry NarrowEntry =
72309467b48Spatrick       { ARM::t2CMPrr,ARM::tCMPr, 0, 0, 0, 1, 1,2, 0, 0,1,0 };
72409467b48Spatrick     if (ReduceToNarrow(MBB, MI, NarrowEntry, LiveCPSR, IsSelfLoop))
72509467b48Spatrick       return true;
72609467b48Spatrick     return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
72709467b48Spatrick   }
72809467b48Spatrick   case ARM::t2TEQrr: {
729097a140dSpatrick     Register PredReg;
73009467b48Spatrick     // Can only convert to eors if we're not in an IT block.
73109467b48Spatrick     if (getInstrPredicate(*MI, PredReg) != ARMCC::AL)
73209467b48Spatrick       break;
73309467b48Spatrick     // TODO if Operand 0 is not killed but Operand 1 is, then we could write
73409467b48Spatrick     // to Op1 instead.
73509467b48Spatrick     if (MI->getOperand(0).isKill())
73609467b48Spatrick       return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
73709467b48Spatrick   }
73809467b48Spatrick   }
73909467b48Spatrick   return false;
74009467b48Spatrick }
74109467b48Spatrick 
74209467b48Spatrick bool
ReduceTo2Addr(MachineBasicBlock & MBB,MachineInstr * MI,const ReduceEntry & Entry,bool LiveCPSR,bool IsSelfLoop)74309467b48Spatrick Thumb2SizeReduce::ReduceTo2Addr(MachineBasicBlock &MBB, MachineInstr *MI,
74409467b48Spatrick                                 const ReduceEntry &Entry,
74509467b48Spatrick                                 bool LiveCPSR, bool IsSelfLoop) {
74609467b48Spatrick   if (ReduceLimit2Addr != -1 && ((int)Num2Addrs >= ReduceLimit2Addr))
74709467b48Spatrick     return false;
74809467b48Spatrick 
74909467b48Spatrick   if (!OptimizeSize && Entry.AvoidMovs && STI->avoidMOVsShifterOperand())
75009467b48Spatrick     // Don't issue movs with shifter operand for some CPUs unless we
75109467b48Spatrick     // are optimizing for size.
75209467b48Spatrick     return false;
75309467b48Spatrick 
75409467b48Spatrick   Register Reg0 = MI->getOperand(0).getReg();
75509467b48Spatrick   Register Reg1 = MI->getOperand(1).getReg();
75609467b48Spatrick   // t2MUL is "special". The tied source operand is second, not first.
75709467b48Spatrick   if (MI->getOpcode() == ARM::t2MUL) {
75809467b48Spatrick     Register Reg2 = MI->getOperand(2).getReg();
75909467b48Spatrick     // Early exit if the regs aren't all low regs.
76009467b48Spatrick     if (!isARMLowRegister(Reg0) || !isARMLowRegister(Reg1)
76109467b48Spatrick         || !isARMLowRegister(Reg2))
76209467b48Spatrick       return false;
76309467b48Spatrick     if (Reg0 != Reg2) {
76409467b48Spatrick       // If the other operand also isn't the same as the destination, we
76509467b48Spatrick       // can't reduce.
76609467b48Spatrick       if (Reg1 != Reg0)
76709467b48Spatrick         return false;
76809467b48Spatrick       // Try to commute the operands to make it a 2-address instruction.
76909467b48Spatrick       MachineInstr *CommutedMI = TII->commuteInstruction(*MI);
77009467b48Spatrick       if (!CommutedMI)
77109467b48Spatrick         return false;
77209467b48Spatrick     }
77309467b48Spatrick   } else if (Reg0 != Reg1) {
77409467b48Spatrick     // Try to commute the operands to make it a 2-address instruction.
77509467b48Spatrick     unsigned CommOpIdx1 = 1;
77609467b48Spatrick     unsigned CommOpIdx2 = TargetInstrInfo::CommuteAnyOperandIndex;
77709467b48Spatrick     if (!TII->findCommutedOpIndices(*MI, CommOpIdx1, CommOpIdx2) ||
77809467b48Spatrick         MI->getOperand(CommOpIdx2).getReg() != Reg0)
77909467b48Spatrick       return false;
78009467b48Spatrick     MachineInstr *CommutedMI =
78109467b48Spatrick         TII->commuteInstruction(*MI, false, CommOpIdx1, CommOpIdx2);
78209467b48Spatrick     if (!CommutedMI)
78309467b48Spatrick       return false;
78409467b48Spatrick   }
78509467b48Spatrick   if (Entry.LowRegs2 && !isARMLowRegister(Reg0))
78609467b48Spatrick     return false;
78709467b48Spatrick   if (Entry.Imm2Limit) {
78809467b48Spatrick     unsigned Imm = MI->getOperand(2).getImm();
78909467b48Spatrick     unsigned Limit = (1 << Entry.Imm2Limit) - 1;
79009467b48Spatrick     if (Imm > Limit)
79109467b48Spatrick       return false;
79209467b48Spatrick   } else {
79309467b48Spatrick     Register Reg2 = MI->getOperand(2).getReg();
79409467b48Spatrick     if (Entry.LowRegs2 && !isARMLowRegister(Reg2))
79509467b48Spatrick       return false;
79609467b48Spatrick   }
79709467b48Spatrick 
79809467b48Spatrick   // Check if it's possible / necessary to transfer the predicate.
79909467b48Spatrick   const MCInstrDesc &NewMCID = TII->get(Entry.NarrowOpc2);
800097a140dSpatrick   Register PredReg;
80109467b48Spatrick   ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
80209467b48Spatrick   bool SkipPred = false;
80309467b48Spatrick   if (Pred != ARMCC::AL) {
80409467b48Spatrick     if (!NewMCID.isPredicable())
80509467b48Spatrick       // Can't transfer predicate, fail.
80609467b48Spatrick       return false;
80709467b48Spatrick   } else {
80809467b48Spatrick     SkipPred = !NewMCID.isPredicable();
80909467b48Spatrick   }
81009467b48Spatrick 
81109467b48Spatrick   bool HasCC = false;
81209467b48Spatrick   bool CCDead = false;
81309467b48Spatrick   const MCInstrDesc &MCID = MI->getDesc();
81409467b48Spatrick   if (MCID.hasOptionalDef()) {
81509467b48Spatrick     unsigned NumOps = MCID.getNumOperands();
81609467b48Spatrick     HasCC = (MI->getOperand(NumOps-1).getReg() == ARM::CPSR);
81709467b48Spatrick     if (HasCC && MI->getOperand(NumOps-1).isDead())
81809467b48Spatrick       CCDead = true;
81909467b48Spatrick   }
82009467b48Spatrick   if (!VerifyPredAndCC(MI, Entry, true, Pred, LiveCPSR, HasCC, CCDead))
82109467b48Spatrick     return false;
82209467b48Spatrick 
82309467b48Spatrick   // Avoid adding a false dependency on partial flag update by some 16-bit
82409467b48Spatrick   // instructions which has the 's' bit set.
82509467b48Spatrick   if (Entry.PartFlag && NewMCID.hasOptionalDef() && HasCC &&
82609467b48Spatrick       canAddPseudoFlagDep(MI, IsSelfLoop))
82709467b48Spatrick     return false;
82809467b48Spatrick 
82909467b48Spatrick   // Add the 16-bit instruction.
83009467b48Spatrick   DebugLoc dl = MI->getDebugLoc();
83109467b48Spatrick   MachineInstrBuilder MIB = BuildMI(MBB, MI, dl, NewMCID);
83209467b48Spatrick   MIB.add(MI->getOperand(0));
83309467b48Spatrick   if (NewMCID.hasOptionalDef())
83409467b48Spatrick     MIB.add(HasCC ? t1CondCodeOp(CCDead) : condCodeOp());
83509467b48Spatrick 
83609467b48Spatrick   // Transfer the rest of operands.
83709467b48Spatrick   unsigned NumOps = MCID.getNumOperands();
83809467b48Spatrick   for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
839*d415bd75Srobert     if (i < NumOps && MCID.operands()[i].isOptionalDef())
84009467b48Spatrick       continue;
841*d415bd75Srobert     if (SkipPred && MCID.operands()[i].isPredicate())
84209467b48Spatrick       continue;
84309467b48Spatrick     MIB.add(MI->getOperand(i));
84409467b48Spatrick   }
84509467b48Spatrick 
84609467b48Spatrick   // Transfer MI flags.
84709467b48Spatrick   MIB.setMIFlags(MI->getFlags());
84809467b48Spatrick 
849*d415bd75Srobert   LLVM_DEBUG(dbgs() << "Converted 32-bit: " << *MI
85009467b48Spatrick                     << "       to 16-bit: " << *MIB);
85109467b48Spatrick 
85209467b48Spatrick   MBB.erase_instr(MI);
85309467b48Spatrick   ++Num2Addrs;
85409467b48Spatrick   return true;
85509467b48Spatrick }
85609467b48Spatrick 
85709467b48Spatrick bool
ReduceToNarrow(MachineBasicBlock & MBB,MachineInstr * MI,const ReduceEntry & Entry,bool LiveCPSR,bool IsSelfLoop)85809467b48Spatrick Thumb2SizeReduce::ReduceToNarrow(MachineBasicBlock &MBB, MachineInstr *MI,
85909467b48Spatrick                                  const ReduceEntry &Entry,
86009467b48Spatrick                                  bool LiveCPSR, bool IsSelfLoop) {
86109467b48Spatrick   if (ReduceLimit != -1 && ((int)NumNarrows >= ReduceLimit))
86209467b48Spatrick     return false;
86309467b48Spatrick 
86409467b48Spatrick   if (!OptimizeSize && Entry.AvoidMovs && STI->avoidMOVsShifterOperand())
86509467b48Spatrick     // Don't issue movs with shifter operand for some CPUs unless we
86609467b48Spatrick     // are optimizing for size.
86709467b48Spatrick     return false;
86809467b48Spatrick 
86909467b48Spatrick   unsigned Limit = ~0U;
87009467b48Spatrick   if (Entry.Imm1Limit)
87109467b48Spatrick     Limit = (1 << Entry.Imm1Limit) - 1;
87209467b48Spatrick 
87309467b48Spatrick   const MCInstrDesc &MCID = MI->getDesc();
87409467b48Spatrick   for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
875*d415bd75Srobert     if (MCID.operands()[i].isPredicate())
87609467b48Spatrick       continue;
87709467b48Spatrick     const MachineOperand &MO = MI->getOperand(i);
87809467b48Spatrick     if (MO.isReg()) {
87909467b48Spatrick       Register Reg = MO.getReg();
88009467b48Spatrick       if (!Reg || Reg == ARM::CPSR)
88109467b48Spatrick         continue;
88209467b48Spatrick       if (Entry.LowRegs1 && !isARMLowRegister(Reg))
88309467b48Spatrick         return false;
884*d415bd75Srobert     } else if (MO.isImm() && !MCID.operands()[i].isPredicate()) {
88509467b48Spatrick       if (((unsigned)MO.getImm()) > Limit)
88609467b48Spatrick         return false;
88709467b48Spatrick     }
88809467b48Spatrick   }
88909467b48Spatrick 
89009467b48Spatrick   // Check if it's possible / necessary to transfer the predicate.
89109467b48Spatrick   const MCInstrDesc &NewMCID = TII->get(Entry.NarrowOpc1);
892097a140dSpatrick   Register PredReg;
89309467b48Spatrick   ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
89409467b48Spatrick   bool SkipPred = false;
89509467b48Spatrick   if (Pred != ARMCC::AL) {
89609467b48Spatrick     if (!NewMCID.isPredicable())
89709467b48Spatrick       // Can't transfer predicate, fail.
89809467b48Spatrick       return false;
89909467b48Spatrick   } else {
90009467b48Spatrick     SkipPred = !NewMCID.isPredicable();
90109467b48Spatrick   }
90209467b48Spatrick 
90309467b48Spatrick   bool HasCC = false;
90409467b48Spatrick   bool CCDead = false;
90509467b48Spatrick   if (MCID.hasOptionalDef()) {
90609467b48Spatrick     unsigned NumOps = MCID.getNumOperands();
90709467b48Spatrick     HasCC = (MI->getOperand(NumOps-1).getReg() == ARM::CPSR);
90809467b48Spatrick     if (HasCC && MI->getOperand(NumOps-1).isDead())
90909467b48Spatrick       CCDead = true;
91009467b48Spatrick   }
91109467b48Spatrick   if (!VerifyPredAndCC(MI, Entry, false, Pred, LiveCPSR, HasCC, CCDead))
91209467b48Spatrick     return false;
91309467b48Spatrick 
91409467b48Spatrick   // Avoid adding a false dependency on partial flag update by some 16-bit
91509467b48Spatrick   // instructions which has the 's' bit set.
91609467b48Spatrick   if (Entry.PartFlag && NewMCID.hasOptionalDef() && HasCC &&
91709467b48Spatrick       canAddPseudoFlagDep(MI, IsSelfLoop))
91809467b48Spatrick     return false;
91909467b48Spatrick 
92009467b48Spatrick   // Add the 16-bit instruction.
92109467b48Spatrick   DebugLoc dl = MI->getDebugLoc();
92209467b48Spatrick   MachineInstrBuilder MIB = BuildMI(MBB, MI, dl, NewMCID);
92309467b48Spatrick 
92409467b48Spatrick   // TEQ is special in that it doesn't define a register but we're converting
92509467b48Spatrick   // it into an EOR which does. So add the first operand as a def and then
92609467b48Spatrick   // again as a use.
92709467b48Spatrick   if (MCID.getOpcode() == ARM::t2TEQrr) {
92809467b48Spatrick     MIB.add(MI->getOperand(0));
92909467b48Spatrick     MIB->getOperand(0).setIsKill(false);
93009467b48Spatrick     MIB->getOperand(0).setIsDef(true);
93109467b48Spatrick     MIB->getOperand(0).setIsDead(true);
93209467b48Spatrick 
93309467b48Spatrick     if (NewMCID.hasOptionalDef())
93409467b48Spatrick       MIB.add(HasCC ? t1CondCodeOp(CCDead) : condCodeOp());
93509467b48Spatrick     MIB.add(MI->getOperand(0));
93609467b48Spatrick   } else {
93709467b48Spatrick     MIB.add(MI->getOperand(0));
93809467b48Spatrick     if (NewMCID.hasOptionalDef())
93909467b48Spatrick       MIB.add(HasCC ? t1CondCodeOp(CCDead) : condCodeOp());
94009467b48Spatrick   }
94109467b48Spatrick 
94209467b48Spatrick   // Transfer the rest of operands.
94309467b48Spatrick   unsigned NumOps = MCID.getNumOperands();
94409467b48Spatrick   for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
945*d415bd75Srobert     if (i < NumOps && MCID.operands()[i].isOptionalDef())
94609467b48Spatrick       continue;
94709467b48Spatrick     if ((MCID.getOpcode() == ARM::t2RSBSri ||
94809467b48Spatrick          MCID.getOpcode() == ARM::t2RSBri ||
94909467b48Spatrick          MCID.getOpcode() == ARM::t2SXTB ||
95009467b48Spatrick          MCID.getOpcode() == ARM::t2SXTH ||
95109467b48Spatrick          MCID.getOpcode() == ARM::t2UXTB ||
95209467b48Spatrick          MCID.getOpcode() == ARM::t2UXTH) && i == 2)
95309467b48Spatrick       // Skip the zero immediate operand, it's now implicit.
95409467b48Spatrick       continue;
955*d415bd75Srobert     bool isPred = (i < NumOps && MCID.operands()[i].isPredicate());
95609467b48Spatrick     if (SkipPred && isPred)
95709467b48Spatrick         continue;
95809467b48Spatrick     const MachineOperand &MO = MI->getOperand(i);
95909467b48Spatrick     if (MO.isReg() && MO.isImplicit() && MO.getReg() == ARM::CPSR)
96009467b48Spatrick       // Skip implicit def of CPSR. Either it's modeled as an optional
96109467b48Spatrick       // def now or it's already an implicit def on the new instruction.
96209467b48Spatrick       continue;
96309467b48Spatrick     MIB.add(MO);
96409467b48Spatrick   }
96509467b48Spatrick   if (!MCID.isPredicable() && NewMCID.isPredicable())
96609467b48Spatrick     MIB.add(predOps(ARMCC::AL));
96709467b48Spatrick 
96809467b48Spatrick   // Transfer MI flags.
96909467b48Spatrick   MIB.setMIFlags(MI->getFlags());
97009467b48Spatrick 
971*d415bd75Srobert   LLVM_DEBUG(dbgs() << "Converted 32-bit: " << *MI
97209467b48Spatrick                     << "       to 16-bit: " << *MIB);
97309467b48Spatrick 
97409467b48Spatrick   MBB.erase_instr(MI);
97509467b48Spatrick   ++NumNarrows;
97609467b48Spatrick   return true;
97709467b48Spatrick }
97809467b48Spatrick 
UpdateCPSRDef(MachineInstr & MI,bool LiveCPSR,bool & DefCPSR)97909467b48Spatrick static bool UpdateCPSRDef(MachineInstr &MI, bool LiveCPSR, bool &DefCPSR) {
98009467b48Spatrick   bool HasDef = false;
98109467b48Spatrick   for (const MachineOperand &MO : MI.operands()) {
98209467b48Spatrick     if (!MO.isReg() || MO.isUndef() || MO.isUse())
98309467b48Spatrick       continue;
98409467b48Spatrick     if (MO.getReg() != ARM::CPSR)
98509467b48Spatrick       continue;
98609467b48Spatrick 
98709467b48Spatrick     DefCPSR = true;
98809467b48Spatrick     if (!MO.isDead())
98909467b48Spatrick       HasDef = true;
99009467b48Spatrick   }
99109467b48Spatrick 
99209467b48Spatrick   return HasDef || LiveCPSR;
99309467b48Spatrick }
99409467b48Spatrick 
UpdateCPSRUse(MachineInstr & MI,bool LiveCPSR)99509467b48Spatrick static bool UpdateCPSRUse(MachineInstr &MI, bool LiveCPSR) {
99609467b48Spatrick   for (const MachineOperand &MO : MI.operands()) {
99709467b48Spatrick     if (!MO.isReg() || MO.isUndef() || MO.isDef())
99809467b48Spatrick       continue;
99909467b48Spatrick     if (MO.getReg() != ARM::CPSR)
100009467b48Spatrick       continue;
100109467b48Spatrick     assert(LiveCPSR && "CPSR liveness tracking is wrong!");
100209467b48Spatrick     if (MO.isKill()) {
100309467b48Spatrick       LiveCPSR = false;
100409467b48Spatrick       break;
100509467b48Spatrick     }
100609467b48Spatrick   }
100709467b48Spatrick 
100809467b48Spatrick   return LiveCPSR;
100909467b48Spatrick }
101009467b48Spatrick 
ReduceMI(MachineBasicBlock & MBB,MachineInstr * MI,bool LiveCPSR,bool IsSelfLoop,bool SkipPrologueEpilogue)101109467b48Spatrick bool Thumb2SizeReduce::ReduceMI(MachineBasicBlock &MBB, MachineInstr *MI,
1012*d415bd75Srobert                                 bool LiveCPSR, bool IsSelfLoop,
1013*d415bd75Srobert                                 bool SkipPrologueEpilogue) {
101409467b48Spatrick   unsigned Opcode = MI->getOpcode();
101509467b48Spatrick   DenseMap<unsigned, unsigned>::iterator OPI = ReduceOpcodeMap.find(Opcode);
101609467b48Spatrick   if (OPI == ReduceOpcodeMap.end())
101709467b48Spatrick     return false;
1018*d415bd75Srobert   if (SkipPrologueEpilogue && (MI->getFlag(MachineInstr::FrameSetup) ||
1019*d415bd75Srobert                                MI->getFlag(MachineInstr::FrameDestroy)))
1020*d415bd75Srobert     return false;
102109467b48Spatrick   const ReduceEntry &Entry = ReduceTable[OPI->second];
102209467b48Spatrick 
102309467b48Spatrick   // Don't attempt normal reductions on "special" cases for now.
102409467b48Spatrick   if (Entry.Special)
102509467b48Spatrick     return ReduceSpecial(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
102609467b48Spatrick 
102709467b48Spatrick   // Try to transform to a 16-bit two-address instruction.
102809467b48Spatrick   if (Entry.NarrowOpc2 &&
102909467b48Spatrick       ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, IsSelfLoop))
103009467b48Spatrick     return true;
103109467b48Spatrick 
103209467b48Spatrick   // Try to transform to a 16-bit non-two-address instruction.
103309467b48Spatrick   if (Entry.NarrowOpc1 &&
103409467b48Spatrick       ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop))
103509467b48Spatrick     return true;
103609467b48Spatrick 
103709467b48Spatrick   return false;
103809467b48Spatrick }
103909467b48Spatrick 
ReduceMBB(MachineBasicBlock & MBB,bool SkipPrologueEpilogue)1040*d415bd75Srobert bool Thumb2SizeReduce::ReduceMBB(MachineBasicBlock &MBB,
1041*d415bd75Srobert                                  bool SkipPrologueEpilogue) {
104209467b48Spatrick   bool Modified = false;
104309467b48Spatrick 
104409467b48Spatrick   // Yes, CPSR could be livein.
104509467b48Spatrick   bool LiveCPSR = MBB.isLiveIn(ARM::CPSR);
104609467b48Spatrick   MachineInstr *BundleMI = nullptr;
104709467b48Spatrick 
104809467b48Spatrick   CPSRDef = nullptr;
104909467b48Spatrick   HighLatencyCPSR = false;
105009467b48Spatrick 
105109467b48Spatrick   // Check predecessors for the latest CPSRDef.
105209467b48Spatrick   for (auto *Pred : MBB.predecessors()) {
105309467b48Spatrick     const MBBInfo &PInfo = BlockInfo[Pred->getNumber()];
105409467b48Spatrick     if (!PInfo.Visited) {
105509467b48Spatrick       // Since blocks are visited in RPO, this must be a back-edge.
105609467b48Spatrick       continue;
105709467b48Spatrick     }
105809467b48Spatrick     if (PInfo.HighLatencyCPSR) {
105909467b48Spatrick       HighLatencyCPSR = true;
106009467b48Spatrick       break;
106109467b48Spatrick     }
106209467b48Spatrick   }
106309467b48Spatrick 
106409467b48Spatrick   // If this BB loops back to itself, conservatively avoid narrowing the
106509467b48Spatrick   // first instruction that does partial flag update.
106609467b48Spatrick   bool IsSelfLoop = MBB.isSuccessor(&MBB);
106709467b48Spatrick   MachineBasicBlock::instr_iterator MII = MBB.instr_begin(),E = MBB.instr_end();
106809467b48Spatrick   MachineBasicBlock::instr_iterator NextMII;
106909467b48Spatrick   for (; MII != E; MII = NextMII) {
107009467b48Spatrick     NextMII = std::next(MII);
107109467b48Spatrick 
107209467b48Spatrick     MachineInstr *MI = &*MII;
107309467b48Spatrick     if (MI->isBundle()) {
107409467b48Spatrick       BundleMI = MI;
107509467b48Spatrick       continue;
107609467b48Spatrick     }
107709467b48Spatrick     if (MI->isDebugInstr())
107809467b48Spatrick       continue;
107909467b48Spatrick 
108009467b48Spatrick     LiveCPSR = UpdateCPSRUse(*MI, LiveCPSR);
108109467b48Spatrick 
108209467b48Spatrick     // Does NextMII belong to the same bundle as MI?
108309467b48Spatrick     bool NextInSameBundle = NextMII != E && NextMII->isBundledWithPred();
108409467b48Spatrick 
1085*d415bd75Srobert     if (ReduceMI(MBB, MI, LiveCPSR, IsSelfLoop, SkipPrologueEpilogue)) {
108609467b48Spatrick       Modified = true;
108709467b48Spatrick       MachineBasicBlock::instr_iterator I = std::prev(NextMII);
108809467b48Spatrick       MI = &*I;
108909467b48Spatrick       // Removing and reinserting the first instruction in a bundle will break
109009467b48Spatrick       // up the bundle. Fix the bundling if it was broken.
109109467b48Spatrick       if (NextInSameBundle && !NextMII->isBundledWithPred())
109209467b48Spatrick         NextMII->bundleWithPred();
109309467b48Spatrick     }
109409467b48Spatrick 
109509467b48Spatrick     if (BundleMI && !NextInSameBundle && MI->isInsideBundle()) {
109609467b48Spatrick       // FIXME: Since post-ra scheduler operates on bundles, the CPSR kill
109709467b48Spatrick       // marker is only on the BUNDLE instruction. Process the BUNDLE
109809467b48Spatrick       // instruction as we finish with the bundled instruction to work around
109909467b48Spatrick       // the inconsistency.
110009467b48Spatrick       if (BundleMI->killsRegister(ARM::CPSR))
110109467b48Spatrick         LiveCPSR = false;
110209467b48Spatrick       MachineOperand *MO = BundleMI->findRegisterDefOperand(ARM::CPSR);
110309467b48Spatrick       if (MO && !MO->isDead())
110409467b48Spatrick         LiveCPSR = true;
110509467b48Spatrick       MO = BundleMI->findRegisterUseOperand(ARM::CPSR);
110609467b48Spatrick       if (MO && !MO->isKill())
110709467b48Spatrick         LiveCPSR = true;
110809467b48Spatrick     }
110909467b48Spatrick 
111009467b48Spatrick     bool DefCPSR = false;
111109467b48Spatrick     LiveCPSR = UpdateCPSRDef(*MI, LiveCPSR, DefCPSR);
111209467b48Spatrick     if (MI->isCall()) {
111309467b48Spatrick       // Calls don't really set CPSR.
111409467b48Spatrick       CPSRDef = nullptr;
111509467b48Spatrick       HighLatencyCPSR = false;
111609467b48Spatrick       IsSelfLoop = false;
111709467b48Spatrick     } else if (DefCPSR) {
111809467b48Spatrick       // This is the last CPSR defining instruction.
111909467b48Spatrick       CPSRDef = MI;
112009467b48Spatrick       HighLatencyCPSR = isHighLatencyCPSR(CPSRDef);
112109467b48Spatrick       IsSelfLoop = false;
112209467b48Spatrick     }
112309467b48Spatrick   }
112409467b48Spatrick 
112509467b48Spatrick   MBBInfo &Info = BlockInfo[MBB.getNumber()];
112609467b48Spatrick   Info.HighLatencyCPSR = HighLatencyCPSR;
112709467b48Spatrick   Info.Visited = true;
112809467b48Spatrick   return Modified;
112909467b48Spatrick }
113009467b48Spatrick 
runOnMachineFunction(MachineFunction & MF)113109467b48Spatrick bool Thumb2SizeReduce::runOnMachineFunction(MachineFunction &MF) {
113209467b48Spatrick   if (PredicateFtor && !PredicateFtor(MF.getFunction()))
113309467b48Spatrick     return false;
113409467b48Spatrick 
1135*d415bd75Srobert   STI = &MF.getSubtarget<ARMSubtarget>();
113609467b48Spatrick   if (STI->isThumb1Only() || STI->prefers32BitThumb())
113709467b48Spatrick     return false;
113809467b48Spatrick 
113909467b48Spatrick   TII = static_cast<const Thumb2InstrInfo *>(STI->getInstrInfo());
114009467b48Spatrick 
114109467b48Spatrick   // Optimizing / minimizing size? Minimizing size implies optimizing for size.
114209467b48Spatrick   OptimizeSize = MF.getFunction().hasOptSize();
114309467b48Spatrick   MinimizeSize = STI->hasMinSize();
114409467b48Spatrick 
114509467b48Spatrick   BlockInfo.clear();
114609467b48Spatrick   BlockInfo.resize(MF.getNumBlockIDs());
114709467b48Spatrick 
114809467b48Spatrick   // Visit blocks in reverse post-order so LastCPSRDef is known for all
114909467b48Spatrick   // predecessors.
115009467b48Spatrick   ReversePostOrderTraversal<MachineFunction*> RPOT(&MF);
115109467b48Spatrick   bool Modified = false;
1152*d415bd75Srobert   bool NeedsWinCFI = MF.getTarget().getMCAsmInfo()->usesWindowsCFI() &&
1153*d415bd75Srobert                      MF.getFunction().needsUnwindTableEntry();
1154*d415bd75Srobert   for (MachineBasicBlock *MBB : RPOT)
1155*d415bd75Srobert     Modified |= ReduceMBB(*MBB, /*SkipPrologueEpilogue=*/NeedsWinCFI);
115609467b48Spatrick   return Modified;
115709467b48Spatrick }
115809467b48Spatrick 
115909467b48Spatrick /// createThumb2SizeReductionPass - Returns an instance of the Thumb2 size
116009467b48Spatrick /// reduction pass.
createThumb2SizeReductionPass(std::function<bool (const Function &)> Ftor)116109467b48Spatrick FunctionPass *llvm::createThumb2SizeReductionPass(
116209467b48Spatrick     std::function<bool(const Function &)> Ftor) {
116309467b48Spatrick   return new Thumb2SizeReduce(std::move(Ftor));
116409467b48Spatrick }
1165