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