Thumb2SizeReduction.cpp 40 KB

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