ARMLoadStoreOptimizer.cpp 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379
  1. //===-- ARMLoadStoreOptimizer.cpp - ARM load / store opt. pass ------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. /// \file This file contains a pass that performs load / store related peephole
  11. /// optimizations. This pass should be run after register allocation.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "ARM.h"
  15. #include "ARMBaseInstrInfo.h"
  16. #include "ARMBaseRegisterInfo.h"
  17. #include "ARMISelLowering.h"
  18. #include "ARMMachineFunctionInfo.h"
  19. #include "ARMSubtarget.h"
  20. #include "MCTargetDesc/ARMAddressingModes.h"
  21. #include "ThumbRegisterInfo.h"
  22. #include "llvm/ADT/DenseMap.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. #include "llvm/ADT/SmallPtrSet.h"
  25. #include "llvm/ADT/SmallSet.h"
  26. #include "llvm/ADT/SmallVector.h"
  27. #include "llvm/ADT/Statistic.h"
  28. #include "llvm/CodeGen/MachineBasicBlock.h"
  29. #include "llvm/CodeGen/MachineFunctionPass.h"
  30. #include "llvm/CodeGen/MachineInstr.h"
  31. #include "llvm/CodeGen/MachineInstrBuilder.h"
  32. #include "llvm/CodeGen/MachineRegisterInfo.h"
  33. #include "llvm/CodeGen/RegisterClassInfo.h"
  34. #include "llvm/CodeGen/SelectionDAGNodes.h"
  35. #include "llvm/CodeGen/LivePhysRegs.h"
  36. #include "llvm/IR/DataLayout.h"
  37. #include "llvm/IR/DerivedTypes.h"
  38. #include "llvm/IR/Function.h"
  39. #include "llvm/Support/Allocator.h"
  40. #include "llvm/Support/Debug.h"
  41. #include "llvm/Support/ErrorHandling.h"
  42. #include "llvm/Support/raw_ostream.h"
  43. #include "llvm/Target/TargetInstrInfo.h"
  44. #include "llvm/Target/TargetMachine.h"
  45. #include "llvm/Target/TargetRegisterInfo.h"
  46. using namespace llvm;
  47. #define DEBUG_TYPE "arm-ldst-opt"
  48. STATISTIC(NumLDMGened , "Number of ldm instructions generated");
  49. STATISTIC(NumSTMGened , "Number of stm instructions generated");
  50. STATISTIC(NumVLDMGened, "Number of vldm instructions generated");
  51. STATISTIC(NumVSTMGened, "Number of vstm instructions generated");
  52. STATISTIC(NumLdStMoved, "Number of load / store instructions moved");
  53. STATISTIC(NumLDRDFormed,"Number of ldrd created before allocation");
  54. STATISTIC(NumSTRDFormed,"Number of strd created before allocation");
  55. STATISTIC(NumLDRD2LDM, "Number of ldrd instructions turned back into ldm");
  56. STATISTIC(NumSTRD2STM, "Number of strd instructions turned back into stm");
  57. STATISTIC(NumLDRD2LDR, "Number of ldrd instructions turned back into ldr's");
  58. STATISTIC(NumSTRD2STR, "Number of strd instructions turned back into str's");
  59. /// This switch disables formation of double/multi instructions that could
  60. /// potentially lead to (new) alignment traps even with CCR.UNALIGN_TRP
  61. /// disabled. This can be used to create libraries that are robust even when
  62. /// users provoke undefined behaviour by supplying misaligned pointers.
  63. /// \see mayCombineMisaligned()
  64. static cl::opt<bool>
  65. AssumeMisalignedLoadStores("arm-assume-misaligned-load-store", cl::Hidden,
  66. cl::init(false), cl::desc("Be more conservative in ARM load/store opt"));
  67. namespace llvm {
  68. void initializeARMLoadStoreOptPass(PassRegistry &);
  69. }
  70. #define ARM_LOAD_STORE_OPT_NAME "ARM load / store optimization pass"
  71. namespace {
  72. /// Post- register allocation pass the combine load / store instructions to
  73. /// form ldm / stm instructions.
  74. struct ARMLoadStoreOpt : public MachineFunctionPass {
  75. static char ID;
  76. ARMLoadStoreOpt() : MachineFunctionPass(ID) {
  77. initializeARMLoadStoreOptPass(*PassRegistry::getPassRegistry());
  78. }
  79. const MachineFunction *MF;
  80. const TargetInstrInfo *TII;
  81. const TargetRegisterInfo *TRI;
  82. const ARMSubtarget *STI;
  83. const TargetLowering *TL;
  84. ARMFunctionInfo *AFI;
  85. LivePhysRegs LiveRegs;
  86. RegisterClassInfo RegClassInfo;
  87. MachineBasicBlock::const_iterator LiveRegPos;
  88. bool LiveRegsValid;
  89. bool RegClassInfoValid;
  90. bool isThumb1, isThumb2;
  91. bool runOnMachineFunction(MachineFunction &Fn) override;
  92. MachineFunctionProperties getRequiredProperties() const override {
  93. return MachineFunctionProperties().set(
  94. MachineFunctionProperties::Property::AllVRegsAllocated);
  95. }
  96. const char *getPassName() const override {
  97. return ARM_LOAD_STORE_OPT_NAME;
  98. }
  99. private:
  100. /// A set of load/store MachineInstrs with same base register sorted by
  101. /// offset.
  102. struct MemOpQueueEntry {
  103. MachineInstr *MI;
  104. int Offset; ///< Load/Store offset.
  105. unsigned Position; ///< Position as counted from end of basic block.
  106. MemOpQueueEntry(MachineInstr *MI, int Offset, unsigned Position)
  107. : MI(MI), Offset(Offset), Position(Position) {}
  108. };
  109. typedef SmallVector<MemOpQueueEntry,8> MemOpQueue;
  110. /// A set of MachineInstrs that fulfill (nearly all) conditions to get
  111. /// merged into a LDM/STM.
  112. struct MergeCandidate {
  113. /// List of instructions ordered by load/store offset.
  114. SmallVector<MachineInstr*, 4> Instrs;
  115. /// Index in Instrs of the instruction being latest in the schedule.
  116. unsigned LatestMIIdx;
  117. /// Index in Instrs of the instruction being earliest in the schedule.
  118. unsigned EarliestMIIdx;
  119. /// Index into the basic block where the merged instruction will be
  120. /// inserted. (See MemOpQueueEntry.Position)
  121. unsigned InsertPos;
  122. /// Whether the instructions can be merged into a ldm/stm instruction.
  123. bool CanMergeToLSMulti;
  124. /// Whether the instructions can be merged into a ldrd/strd instruction.
  125. bool CanMergeToLSDouble;
  126. };
  127. SpecificBumpPtrAllocator<MergeCandidate> Allocator;
  128. SmallVector<const MergeCandidate*,4> Candidates;
  129. SmallVector<MachineInstr*,4> MergeBaseCandidates;
  130. void moveLiveRegsBefore(const MachineBasicBlock &MBB,
  131. MachineBasicBlock::const_iterator Before);
  132. unsigned findFreeReg(const TargetRegisterClass &RegClass);
  133. void UpdateBaseRegUses(MachineBasicBlock &MBB,
  134. MachineBasicBlock::iterator MBBI,
  135. DebugLoc DL, unsigned Base, unsigned WordOffset,
  136. ARMCC::CondCodes Pred, unsigned PredReg);
  137. MachineInstr *CreateLoadStoreMulti(MachineBasicBlock &MBB,
  138. MachineBasicBlock::iterator InsertBefore, int Offset, unsigned Base,
  139. bool BaseKill, unsigned Opcode, ARMCC::CondCodes Pred, unsigned PredReg,
  140. DebugLoc DL, ArrayRef<std::pair<unsigned, bool>> Regs);
  141. MachineInstr *CreateLoadStoreDouble(MachineBasicBlock &MBB,
  142. MachineBasicBlock::iterator InsertBefore, int Offset, unsigned Base,
  143. bool BaseKill, unsigned Opcode, ARMCC::CondCodes Pred, unsigned PredReg,
  144. DebugLoc DL, ArrayRef<std::pair<unsigned, bool>> Regs) const;
  145. void FormCandidates(const MemOpQueue &MemOps);
  146. MachineInstr *MergeOpsUpdate(const MergeCandidate &Cand);
  147. bool FixInvalidRegPairOp(MachineBasicBlock &MBB,
  148. MachineBasicBlock::iterator &MBBI);
  149. bool MergeBaseUpdateLoadStore(MachineInstr *MI);
  150. bool MergeBaseUpdateLSMultiple(MachineInstr *MI);
  151. bool MergeBaseUpdateLSDouble(MachineInstr &MI) const;
  152. bool LoadStoreMultipleOpti(MachineBasicBlock &MBB);
  153. bool MergeReturnIntoLDM(MachineBasicBlock &MBB);
  154. bool CombineMovBx(MachineBasicBlock &MBB);
  155. };
  156. char ARMLoadStoreOpt::ID = 0;
  157. }
  158. INITIALIZE_PASS(ARMLoadStoreOpt, "arm-load-store-opt", ARM_LOAD_STORE_OPT_NAME, false, false)
  159. static bool definesCPSR(const MachineInstr *MI) {
  160. for (const auto &MO : MI->operands()) {
  161. if (!MO.isReg())
  162. continue;
  163. if (MO.isDef() && MO.getReg() == ARM::CPSR && !MO.isDead())
  164. // If the instruction has live CPSR def, then it's not safe to fold it
  165. // into load / store.
  166. return true;
  167. }
  168. return false;
  169. }
  170. static int getMemoryOpOffset(const MachineInstr *MI) {
  171. unsigned Opcode = MI->getOpcode();
  172. bool isAM3 = Opcode == ARM::LDRD || Opcode == ARM::STRD;
  173. unsigned NumOperands = MI->getDesc().getNumOperands();
  174. unsigned OffField = MI->getOperand(NumOperands-3).getImm();
  175. if (Opcode == ARM::t2LDRi12 || Opcode == ARM::t2LDRi8 ||
  176. Opcode == ARM::t2STRi12 || Opcode == ARM::t2STRi8 ||
  177. Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8 ||
  178. Opcode == ARM::LDRi12 || Opcode == ARM::STRi12)
  179. return OffField;
  180. // Thumb1 immediate offsets are scaled by 4
  181. if (Opcode == ARM::tLDRi || Opcode == ARM::tSTRi ||
  182. Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi)
  183. return OffField * 4;
  184. int Offset = isAM3 ? ARM_AM::getAM3Offset(OffField)
  185. : ARM_AM::getAM5Offset(OffField) * 4;
  186. ARM_AM::AddrOpc Op = isAM3 ? ARM_AM::getAM3Op(OffField)
  187. : ARM_AM::getAM5Op(OffField);
  188. if (Op == ARM_AM::sub)
  189. return -Offset;
  190. return Offset;
  191. }
  192. static const MachineOperand &getLoadStoreBaseOp(const MachineInstr &MI) {
  193. return MI.getOperand(1);
  194. }
  195. static const MachineOperand &getLoadStoreRegOp(const MachineInstr &MI) {
  196. return MI.getOperand(0);
  197. }
  198. static int getLoadStoreMultipleOpcode(unsigned Opcode, ARM_AM::AMSubMode Mode) {
  199. switch (Opcode) {
  200. default: llvm_unreachable("Unhandled opcode!");
  201. case ARM::LDRi12:
  202. ++NumLDMGened;
  203. switch (Mode) {
  204. default: llvm_unreachable("Unhandled submode!");
  205. case ARM_AM::ia: return ARM::LDMIA;
  206. case ARM_AM::da: return ARM::LDMDA;
  207. case ARM_AM::db: return ARM::LDMDB;
  208. case ARM_AM::ib: return ARM::LDMIB;
  209. }
  210. case ARM::STRi12:
  211. ++NumSTMGened;
  212. switch (Mode) {
  213. default: llvm_unreachable("Unhandled submode!");
  214. case ARM_AM::ia: return ARM::STMIA;
  215. case ARM_AM::da: return ARM::STMDA;
  216. case ARM_AM::db: return ARM::STMDB;
  217. case ARM_AM::ib: return ARM::STMIB;
  218. }
  219. case ARM::tLDRi:
  220. case ARM::tLDRspi:
  221. // tLDMIA is writeback-only - unless the base register is in the input
  222. // reglist.
  223. ++NumLDMGened;
  224. switch (Mode) {
  225. default: llvm_unreachable("Unhandled submode!");
  226. case ARM_AM::ia: return ARM::tLDMIA;
  227. }
  228. case ARM::tSTRi:
  229. case ARM::tSTRspi:
  230. // There is no non-writeback tSTMIA either.
  231. ++NumSTMGened;
  232. switch (Mode) {
  233. default: llvm_unreachable("Unhandled submode!");
  234. case ARM_AM::ia: return ARM::tSTMIA_UPD;
  235. }
  236. case ARM::t2LDRi8:
  237. case ARM::t2LDRi12:
  238. ++NumLDMGened;
  239. switch (Mode) {
  240. default: llvm_unreachable("Unhandled submode!");
  241. case ARM_AM::ia: return ARM::t2LDMIA;
  242. case ARM_AM::db: return ARM::t2LDMDB;
  243. }
  244. case ARM::t2STRi8:
  245. case ARM::t2STRi12:
  246. ++NumSTMGened;
  247. switch (Mode) {
  248. default: llvm_unreachable("Unhandled submode!");
  249. case ARM_AM::ia: return ARM::t2STMIA;
  250. case ARM_AM::db: return ARM::t2STMDB;
  251. }
  252. case ARM::VLDRS:
  253. ++NumVLDMGened;
  254. switch (Mode) {
  255. default: llvm_unreachable("Unhandled submode!");
  256. case ARM_AM::ia: return ARM::VLDMSIA;
  257. case ARM_AM::db: return 0; // Only VLDMSDB_UPD exists.
  258. }
  259. case ARM::VSTRS:
  260. ++NumVSTMGened;
  261. switch (Mode) {
  262. default: llvm_unreachable("Unhandled submode!");
  263. case ARM_AM::ia: return ARM::VSTMSIA;
  264. case ARM_AM::db: return 0; // Only VSTMSDB_UPD exists.
  265. }
  266. case ARM::VLDRD:
  267. ++NumVLDMGened;
  268. switch (Mode) {
  269. default: llvm_unreachable("Unhandled submode!");
  270. case ARM_AM::ia: return ARM::VLDMDIA;
  271. case ARM_AM::db: return 0; // Only VLDMDDB_UPD exists.
  272. }
  273. case ARM::VSTRD:
  274. ++NumVSTMGened;
  275. switch (Mode) {
  276. default: llvm_unreachable("Unhandled submode!");
  277. case ARM_AM::ia: return ARM::VSTMDIA;
  278. case ARM_AM::db: return 0; // Only VSTMDDB_UPD exists.
  279. }
  280. }
  281. }
  282. static ARM_AM::AMSubMode getLoadStoreMultipleSubMode(unsigned Opcode) {
  283. switch (Opcode) {
  284. default: llvm_unreachable("Unhandled opcode!");
  285. case ARM::LDMIA_RET:
  286. case ARM::LDMIA:
  287. case ARM::LDMIA_UPD:
  288. case ARM::STMIA:
  289. case ARM::STMIA_UPD:
  290. case ARM::tLDMIA:
  291. case ARM::tLDMIA_UPD:
  292. case ARM::tSTMIA_UPD:
  293. case ARM::t2LDMIA_RET:
  294. case ARM::t2LDMIA:
  295. case ARM::t2LDMIA_UPD:
  296. case ARM::t2STMIA:
  297. case ARM::t2STMIA_UPD:
  298. case ARM::VLDMSIA:
  299. case ARM::VLDMSIA_UPD:
  300. case ARM::VSTMSIA:
  301. case ARM::VSTMSIA_UPD:
  302. case ARM::VLDMDIA:
  303. case ARM::VLDMDIA_UPD:
  304. case ARM::VSTMDIA:
  305. case ARM::VSTMDIA_UPD:
  306. return ARM_AM::ia;
  307. case ARM::LDMDA:
  308. case ARM::LDMDA_UPD:
  309. case ARM::STMDA:
  310. case ARM::STMDA_UPD:
  311. return ARM_AM::da;
  312. case ARM::LDMDB:
  313. case ARM::LDMDB_UPD:
  314. case ARM::STMDB:
  315. case ARM::STMDB_UPD:
  316. case ARM::t2LDMDB:
  317. case ARM::t2LDMDB_UPD:
  318. case ARM::t2STMDB:
  319. case ARM::t2STMDB_UPD:
  320. case ARM::VLDMSDB_UPD:
  321. case ARM::VSTMSDB_UPD:
  322. case ARM::VLDMDDB_UPD:
  323. case ARM::VSTMDDB_UPD:
  324. return ARM_AM::db;
  325. case ARM::LDMIB:
  326. case ARM::LDMIB_UPD:
  327. case ARM::STMIB:
  328. case ARM::STMIB_UPD:
  329. return ARM_AM::ib;
  330. }
  331. }
  332. static bool isT1i32Load(unsigned Opc) {
  333. return Opc == ARM::tLDRi || Opc == ARM::tLDRspi;
  334. }
  335. static bool isT2i32Load(unsigned Opc) {
  336. return Opc == ARM::t2LDRi12 || Opc == ARM::t2LDRi8;
  337. }
  338. static bool isi32Load(unsigned Opc) {
  339. return Opc == ARM::LDRi12 || isT1i32Load(Opc) || isT2i32Load(Opc) ;
  340. }
  341. static bool isT1i32Store(unsigned Opc) {
  342. return Opc == ARM::tSTRi || Opc == ARM::tSTRspi;
  343. }
  344. static bool isT2i32Store(unsigned Opc) {
  345. return Opc == ARM::t2STRi12 || Opc == ARM::t2STRi8;
  346. }
  347. static bool isi32Store(unsigned Opc) {
  348. return Opc == ARM::STRi12 || isT1i32Store(Opc) || isT2i32Store(Opc);
  349. }
  350. static bool isLoadSingle(unsigned Opc) {
  351. return isi32Load(Opc) || Opc == ARM::VLDRS || Opc == ARM::VLDRD;
  352. }
  353. static unsigned getImmScale(unsigned Opc) {
  354. switch (Opc) {
  355. default: llvm_unreachable("Unhandled opcode!");
  356. case ARM::tLDRi:
  357. case ARM::tSTRi:
  358. case ARM::tLDRspi:
  359. case ARM::tSTRspi:
  360. return 1;
  361. case ARM::tLDRHi:
  362. case ARM::tSTRHi:
  363. return 2;
  364. case ARM::tLDRBi:
  365. case ARM::tSTRBi:
  366. return 4;
  367. }
  368. }
  369. static unsigned getLSMultipleTransferSize(const MachineInstr *MI) {
  370. switch (MI->getOpcode()) {
  371. default: return 0;
  372. case ARM::LDRi12:
  373. case ARM::STRi12:
  374. case ARM::tLDRi:
  375. case ARM::tSTRi:
  376. case ARM::tLDRspi:
  377. case ARM::tSTRspi:
  378. case ARM::t2LDRi8:
  379. case ARM::t2LDRi12:
  380. case ARM::t2STRi8:
  381. case ARM::t2STRi12:
  382. case ARM::VLDRS:
  383. case ARM::VSTRS:
  384. return 4;
  385. case ARM::VLDRD:
  386. case ARM::VSTRD:
  387. return 8;
  388. case ARM::LDMIA:
  389. case ARM::LDMDA:
  390. case ARM::LDMDB:
  391. case ARM::LDMIB:
  392. case ARM::STMIA:
  393. case ARM::STMDA:
  394. case ARM::STMDB:
  395. case ARM::STMIB:
  396. case ARM::tLDMIA:
  397. case ARM::tLDMIA_UPD:
  398. case ARM::tSTMIA_UPD:
  399. case ARM::t2LDMIA:
  400. case ARM::t2LDMDB:
  401. case ARM::t2STMIA:
  402. case ARM::t2STMDB:
  403. case ARM::VLDMSIA:
  404. case ARM::VSTMSIA:
  405. return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 4;
  406. case ARM::VLDMDIA:
  407. case ARM::VSTMDIA:
  408. return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 8;
  409. }
  410. }
  411. /// Update future uses of the base register with the offset introduced
  412. /// due to writeback. This function only works on Thumb1.
  413. void
  414. ARMLoadStoreOpt::UpdateBaseRegUses(MachineBasicBlock &MBB,
  415. MachineBasicBlock::iterator MBBI,
  416. DebugLoc DL, unsigned Base,
  417. unsigned WordOffset,
  418. ARMCC::CondCodes Pred, unsigned PredReg) {
  419. assert(isThumb1 && "Can only update base register uses for Thumb1!");
  420. // Start updating any instructions with immediate offsets. Insert a SUB before
  421. // the first non-updateable instruction (if any).
  422. for (; MBBI != MBB.end(); ++MBBI) {
  423. bool InsertSub = false;
  424. unsigned Opc = MBBI->getOpcode();
  425. if (MBBI->readsRegister(Base)) {
  426. int Offset;
  427. bool IsLoad =
  428. Opc == ARM::tLDRi || Opc == ARM::tLDRHi || Opc == ARM::tLDRBi;
  429. bool IsStore =
  430. Opc == ARM::tSTRi || Opc == ARM::tSTRHi || Opc == ARM::tSTRBi;
  431. if (IsLoad || IsStore) {
  432. // Loads and stores with immediate offsets can be updated, but only if
  433. // the new offset isn't negative.
  434. // The MachineOperand containing the offset immediate is the last one
  435. // before predicates.
  436. MachineOperand &MO =
  437. MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3);
  438. // The offsets are scaled by 1, 2 or 4 depending on the Opcode.
  439. Offset = MO.getImm() - WordOffset * getImmScale(Opc);
  440. // If storing the base register, it needs to be reset first.
  441. unsigned InstrSrcReg = getLoadStoreRegOp(*MBBI).getReg();
  442. if (Offset >= 0 && !(IsStore && InstrSrcReg == Base))
  443. MO.setImm(Offset);
  444. else
  445. InsertSub = true;
  446. } else if ((Opc == ARM::tSUBi8 || Opc == ARM::tADDi8) &&
  447. !definesCPSR(MBBI)) {
  448. // SUBS/ADDS using this register, with a dead def of the CPSR.
  449. // Merge it with the update; if the merged offset is too large,
  450. // insert a new sub instead.
  451. MachineOperand &MO =
  452. MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3);
  453. Offset = (Opc == ARM::tSUBi8) ?
  454. MO.getImm() + WordOffset * 4 :
  455. MO.getImm() - WordOffset * 4 ;
  456. if (Offset >= 0 && TL->isLegalAddImmediate(Offset)) {
  457. // FIXME: Swap ADDS<->SUBS if Offset < 0, erase instruction if
  458. // Offset == 0.
  459. MO.setImm(Offset);
  460. // The base register has now been reset, so exit early.
  461. return;
  462. } else {
  463. InsertSub = true;
  464. }
  465. } else {
  466. // Can't update the instruction.
  467. InsertSub = true;
  468. }
  469. } else if (definesCPSR(MBBI) || MBBI->isCall() || MBBI->isBranch()) {
  470. // Since SUBS sets the condition flags, we can't place the base reset
  471. // after an instruction that has a live CPSR def.
  472. // The base register might also contain an argument for a function call.
  473. InsertSub = true;
  474. }
  475. if (InsertSub) {
  476. // An instruction above couldn't be updated, so insert a sub.
  477. AddDefaultT1CC(BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base), true)
  478. .addReg(Base).addImm(WordOffset * 4).addImm(Pred).addReg(PredReg);
  479. return;
  480. }
  481. if (MBBI->killsRegister(Base) || MBBI->definesRegister(Base))
  482. // Register got killed. Stop updating.
  483. return;
  484. }
  485. // End of block was reached.
  486. if (MBB.succ_size() > 0) {
  487. // FIXME: Because of a bug, live registers are sometimes missing from
  488. // the successor blocks' live-in sets. This means we can't trust that
  489. // information and *always* have to reset at the end of a block.
  490. // See PR21029.
  491. if (MBBI != MBB.end()) --MBBI;
  492. AddDefaultT1CC(
  493. BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base), true)
  494. .addReg(Base).addImm(WordOffset * 4).addImm(Pred).addReg(PredReg);
  495. }
  496. }
  497. /// Return the first register of class \p RegClass that is not in \p Regs.
  498. unsigned ARMLoadStoreOpt::findFreeReg(const TargetRegisterClass &RegClass) {
  499. if (!RegClassInfoValid) {
  500. RegClassInfo.runOnMachineFunction(*MF);
  501. RegClassInfoValid = true;
  502. }
  503. for (unsigned Reg : RegClassInfo.getOrder(&RegClass))
  504. if (!LiveRegs.contains(Reg))
  505. return Reg;
  506. return 0;
  507. }
  508. /// Compute live registers just before instruction \p Before (in normal schedule
  509. /// direction). Computes backwards so multiple queries in the same block must
  510. /// come in reverse order.
  511. void ARMLoadStoreOpt::moveLiveRegsBefore(const MachineBasicBlock &MBB,
  512. MachineBasicBlock::const_iterator Before) {
  513. // Initialize if we never queried in this block.
  514. if (!LiveRegsValid) {
  515. LiveRegs.init(TRI);
  516. LiveRegs.addLiveOuts(MBB);
  517. LiveRegPos = MBB.end();
  518. LiveRegsValid = true;
  519. }
  520. // Move backward just before the "Before" position.
  521. while (LiveRegPos != Before) {
  522. --LiveRegPos;
  523. LiveRegs.stepBackward(*LiveRegPos);
  524. }
  525. }
  526. static bool ContainsReg(const ArrayRef<std::pair<unsigned, bool>> &Regs,
  527. unsigned Reg) {
  528. for (const std::pair<unsigned, bool> &R : Regs)
  529. if (R.first == Reg)
  530. return true;
  531. return false;
  532. }
  533. /// Create and insert a LDM or STM with Base as base register and registers in
  534. /// Regs as the register operands that would be loaded / stored. It returns
  535. /// true if the transformation is done.
  536. MachineInstr *ARMLoadStoreOpt::CreateLoadStoreMulti(MachineBasicBlock &MBB,
  537. MachineBasicBlock::iterator InsertBefore, int Offset, unsigned Base,
  538. bool BaseKill, unsigned Opcode, ARMCC::CondCodes Pred, unsigned PredReg,
  539. DebugLoc DL, ArrayRef<std::pair<unsigned, bool>> Regs) {
  540. unsigned NumRegs = Regs.size();
  541. assert(NumRegs > 1);
  542. // For Thumb1 targets, it might be necessary to clobber the CPSR to merge.
  543. // Compute liveness information for that register to make the decision.
  544. bool SafeToClobberCPSR = !isThumb1 ||
  545. (MBB.computeRegisterLiveness(TRI, ARM::CPSR, InsertBefore, 20) ==
  546. MachineBasicBlock::LQR_Dead);
  547. bool Writeback = isThumb1; // Thumb1 LDM/STM have base reg writeback.
  548. // Exception: If the base register is in the input reglist, Thumb1 LDM is
  549. // non-writeback.
  550. // It's also not possible to merge an STR of the base register in Thumb1.
  551. if (isThumb1 && isi32Load(Opcode) && ContainsReg(Regs, Base)) {
  552. assert(Base != ARM::SP && "Thumb1 does not allow SP in register list");
  553. if (Opcode == ARM::tLDRi) {
  554. Writeback = false;
  555. } else if (Opcode == ARM::tSTRi) {
  556. return nullptr;
  557. }
  558. }
  559. ARM_AM::AMSubMode Mode = ARM_AM::ia;
  560. // VFP and Thumb2 do not support IB or DA modes. Thumb1 only supports IA.
  561. bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);
  562. bool haveIBAndDA = isNotVFP && !isThumb2 && !isThumb1;
  563. if (Offset == 4 && haveIBAndDA) {
  564. Mode = ARM_AM::ib;
  565. } else if (Offset == -4 * (int)NumRegs + 4 && haveIBAndDA) {
  566. Mode = ARM_AM::da;
  567. } else if (Offset == -4 * (int)NumRegs && isNotVFP && !isThumb1) {
  568. // VLDM/VSTM do not support DB mode without also updating the base reg.
  569. Mode = ARM_AM::db;
  570. } else if (Offset != 0 || Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi) {
  571. // Check if this is a supported opcode before inserting instructions to
  572. // calculate a new base register.
  573. if (!getLoadStoreMultipleOpcode(Opcode, Mode)) return nullptr;
  574. // If starting offset isn't zero, insert a MI to materialize a new base.
  575. // But only do so if it is cost effective, i.e. merging more than two
  576. // loads / stores.
  577. if (NumRegs <= 2)
  578. return nullptr;
  579. // On Thumb1, it's not worth materializing a new base register without
  580. // clobbering the CPSR (i.e. not using ADDS/SUBS).
  581. if (!SafeToClobberCPSR)
  582. return nullptr;
  583. unsigned NewBase;
  584. if (isi32Load(Opcode)) {
  585. // If it is a load, then just use one of the destination registers
  586. // as the new base. Will no longer be writeback in Thumb1.
  587. NewBase = Regs[NumRegs-1].first;
  588. Writeback = false;
  589. } else {
  590. // Find a free register that we can use as scratch register.
  591. moveLiveRegsBefore(MBB, InsertBefore);
  592. // The merged instruction does not exist yet but will use several Regs if
  593. // it is a Store.
  594. if (!isLoadSingle(Opcode))
  595. for (const std::pair<unsigned, bool> &R : Regs)
  596. LiveRegs.addReg(R.first);
  597. NewBase = findFreeReg(isThumb1 ? ARM::tGPRRegClass : ARM::GPRRegClass);
  598. if (NewBase == 0)
  599. return nullptr;
  600. }
  601. int BaseOpc =
  602. isThumb2 ? ARM::t2ADDri :
  603. (isThumb1 && Base == ARM::SP) ? ARM::tADDrSPi :
  604. (isThumb1 && Offset < 8) ? ARM::tADDi3 :
  605. isThumb1 ? ARM::tADDi8 : ARM::ADDri;
  606. if (Offset < 0) {
  607. Offset = - Offset;
  608. BaseOpc =
  609. isThumb2 ? ARM::t2SUBri :
  610. (isThumb1 && Offset < 8 && Base != ARM::SP) ? ARM::tSUBi3 :
  611. isThumb1 ? ARM::tSUBi8 : ARM::SUBri;
  612. }
  613. if (!TL->isLegalAddImmediate(Offset))
  614. // FIXME: Try add with register operand?
  615. return nullptr; // Probably not worth it then.
  616. // We can only append a kill flag to the add/sub input if the value is not
  617. // used in the register list of the stm as well.
  618. bool KillOldBase = BaseKill &&
  619. (!isi32Store(Opcode) || !ContainsReg(Regs, Base));
  620. if (isThumb1) {
  621. // Thumb1: depending on immediate size, use either
  622. // ADDS NewBase, Base, #imm3
  623. // or
  624. // MOV NewBase, Base
  625. // ADDS NewBase, #imm8.
  626. if (Base != NewBase &&
  627. (BaseOpc == ARM::tADDi8 || BaseOpc == ARM::tSUBi8)) {
  628. // Need to insert a MOV to the new base first.
  629. if (isARMLowRegister(NewBase) && isARMLowRegister(Base) &&
  630. !STI->hasV6Ops()) {
  631. // thumbv4t doesn't have lo->lo copies, and we can't predicate tMOVSr
  632. if (Pred != ARMCC::AL)
  633. return nullptr;
  634. BuildMI(MBB, InsertBefore, DL, TII->get(ARM::tMOVSr), NewBase)
  635. .addReg(Base, getKillRegState(KillOldBase));
  636. } else
  637. BuildMI(MBB, InsertBefore, DL, TII->get(ARM::tMOVr), NewBase)
  638. .addReg(Base, getKillRegState(KillOldBase))
  639. .addImm(Pred).addReg(PredReg);
  640. // The following ADDS/SUBS becomes an update.
  641. Base = NewBase;
  642. KillOldBase = true;
  643. }
  644. if (BaseOpc == ARM::tADDrSPi) {
  645. assert(Offset % 4 == 0 && "tADDrSPi offset is scaled by 4");
  646. BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
  647. .addReg(Base, getKillRegState(KillOldBase)).addImm(Offset/4)
  648. .addImm(Pred).addReg(PredReg);
  649. } else
  650. AddDefaultT1CC(
  651. BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase), true)
  652. .addReg(Base, getKillRegState(KillOldBase)).addImm(Offset)
  653. .addImm(Pred).addReg(PredReg);
  654. } else {
  655. BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
  656. .addReg(Base, getKillRegState(KillOldBase)).addImm(Offset)
  657. .addImm(Pred).addReg(PredReg).addReg(0);
  658. }
  659. Base = NewBase;
  660. BaseKill = true; // New base is always killed straight away.
  661. }
  662. bool isDef = isLoadSingle(Opcode);
  663. // Get LS multiple opcode. Note that for Thumb1 this might be an opcode with
  664. // base register writeback.
  665. Opcode = getLoadStoreMultipleOpcode(Opcode, Mode);
  666. if (!Opcode)
  667. return nullptr;
  668. // Check if a Thumb1 LDM/STM merge is safe. This is the case if:
  669. // - There is no writeback (LDM of base register),
  670. // - the base register is killed by the merged instruction,
  671. // - or it's safe to overwrite the condition flags, i.e. to insert a SUBS
  672. // to reset the base register.
  673. // Otherwise, don't merge.
  674. // It's safe to return here since the code to materialize a new base register
  675. // above is also conditional on SafeToClobberCPSR.
  676. if (isThumb1 && !SafeToClobberCPSR && Writeback && !BaseKill)
  677. return nullptr;
  678. MachineInstrBuilder MIB;
  679. if (Writeback) {
  680. assert(isThumb1 && "expected Writeback only inThumb1");
  681. if (Opcode == ARM::tLDMIA) {
  682. assert(!(ContainsReg(Regs, Base)) && "Thumb1 can't LDM ! with Base in Regs");
  683. // Update tLDMIA with writeback if necessary.
  684. Opcode = ARM::tLDMIA_UPD;
  685. }
  686. MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode));
  687. // Thumb1: we might need to set base writeback when building the MI.
  688. MIB.addReg(Base, getDefRegState(true))
  689. .addReg(Base, getKillRegState(BaseKill));
  690. // The base isn't dead after a merged instruction with writeback.
  691. // Insert a sub instruction after the newly formed instruction to reset.
  692. if (!BaseKill)
  693. UpdateBaseRegUses(MBB, InsertBefore, DL, Base, NumRegs, Pred, PredReg);
  694. } else {
  695. // No writeback, simply build the MachineInstr.
  696. MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode));
  697. MIB.addReg(Base, getKillRegState(BaseKill));
  698. }
  699. MIB.addImm(Pred).addReg(PredReg);
  700. for (const std::pair<unsigned, bool> &R : Regs)
  701. MIB.addReg(R.first, getDefRegState(isDef) | getKillRegState(R.second));
  702. return MIB.getInstr();
  703. }
  704. MachineInstr *ARMLoadStoreOpt::CreateLoadStoreDouble(MachineBasicBlock &MBB,
  705. MachineBasicBlock::iterator InsertBefore, int Offset, unsigned Base,
  706. bool BaseKill, unsigned Opcode, ARMCC::CondCodes Pred, unsigned PredReg,
  707. DebugLoc DL, ArrayRef<std::pair<unsigned, bool>> Regs) const {
  708. bool IsLoad = isi32Load(Opcode);
  709. assert((IsLoad || isi32Store(Opcode)) && "Must have integer load or store");
  710. unsigned LoadStoreOpcode = IsLoad ? ARM::t2LDRDi8 : ARM::t2STRDi8;
  711. assert(Regs.size() == 2);
  712. MachineInstrBuilder MIB = BuildMI(MBB, InsertBefore, DL,
  713. TII->get(LoadStoreOpcode));
  714. if (IsLoad) {
  715. MIB.addReg(Regs[0].first, RegState::Define)
  716. .addReg(Regs[1].first, RegState::Define);
  717. } else {
  718. MIB.addReg(Regs[0].first, getKillRegState(Regs[0].second))
  719. .addReg(Regs[1].first, getKillRegState(Regs[1].second));
  720. }
  721. MIB.addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
  722. return MIB.getInstr();
  723. }
  724. /// Call MergeOps and update MemOps and merges accordingly on success.
  725. MachineInstr *ARMLoadStoreOpt::MergeOpsUpdate(const MergeCandidate &Cand) {
  726. const MachineInstr *First = Cand.Instrs.front();
  727. unsigned Opcode = First->getOpcode();
  728. bool IsLoad = isLoadSingle(Opcode);
  729. SmallVector<std::pair<unsigned, bool>, 8> Regs;
  730. SmallVector<unsigned, 4> ImpDefs;
  731. DenseSet<unsigned> KilledRegs;
  732. DenseSet<unsigned> UsedRegs;
  733. // Determine list of registers and list of implicit super-register defs.
  734. for (const MachineInstr *MI : Cand.Instrs) {
  735. const MachineOperand &MO = getLoadStoreRegOp(*MI);
  736. unsigned Reg = MO.getReg();
  737. bool IsKill = MO.isKill();
  738. if (IsKill)
  739. KilledRegs.insert(Reg);
  740. Regs.push_back(std::make_pair(Reg, IsKill));
  741. UsedRegs.insert(Reg);
  742. if (IsLoad) {
  743. // Collect any implicit defs of super-registers, after merging we can't
  744. // be sure anymore that we properly preserved these live ranges and must
  745. // removed these implicit operands.
  746. for (const MachineOperand &MO : MI->implicit_operands()) {
  747. if (!MO.isReg() || !MO.isDef() || MO.isDead())
  748. continue;
  749. assert(MO.isImplicit());
  750. unsigned DefReg = MO.getReg();
  751. if (std::find(ImpDefs.begin(), ImpDefs.end(), DefReg) != ImpDefs.end())
  752. continue;
  753. // We can ignore cases where the super-reg is read and written.
  754. if (MI->readsRegister(DefReg))
  755. continue;
  756. ImpDefs.push_back(DefReg);
  757. }
  758. }
  759. }
  760. // Attempt the merge.
  761. typedef MachineBasicBlock::iterator iterator;
  762. MachineInstr *LatestMI = Cand.Instrs[Cand.LatestMIIdx];
  763. iterator InsertBefore = std::next(iterator(LatestMI));
  764. MachineBasicBlock &MBB = *LatestMI->getParent();
  765. unsigned Offset = getMemoryOpOffset(First);
  766. unsigned Base = getLoadStoreBaseOp(*First).getReg();
  767. bool BaseKill = LatestMI->killsRegister(Base);
  768. unsigned PredReg = 0;
  769. ARMCC::CondCodes Pred = getInstrPredicate(*First, PredReg);
  770. DebugLoc DL = First->getDebugLoc();
  771. MachineInstr *Merged = nullptr;
  772. if (Cand.CanMergeToLSDouble)
  773. Merged = CreateLoadStoreDouble(MBB, InsertBefore, Offset, Base, BaseKill,
  774. Opcode, Pred, PredReg, DL, Regs);
  775. if (!Merged && Cand.CanMergeToLSMulti)
  776. Merged = CreateLoadStoreMulti(MBB, InsertBefore, Offset, Base, BaseKill,
  777. Opcode, Pred, PredReg, DL, Regs);
  778. if (!Merged)
  779. return nullptr;
  780. // Determine earliest instruction that will get removed. We then keep an
  781. // iterator just above it so the following erases don't invalidated it.
  782. iterator EarliestI(Cand.Instrs[Cand.EarliestMIIdx]);
  783. bool EarliestAtBegin = false;
  784. if (EarliestI == MBB.begin()) {
  785. EarliestAtBegin = true;
  786. } else {
  787. EarliestI = std::prev(EarliestI);
  788. }
  789. // Remove instructions which have been merged.
  790. for (MachineInstr *MI : Cand.Instrs)
  791. MBB.erase(MI);
  792. // Determine range between the earliest removed instruction and the new one.
  793. if (EarliestAtBegin)
  794. EarliestI = MBB.begin();
  795. else
  796. EarliestI = std::next(EarliestI);
  797. auto FixupRange = make_range(EarliestI, iterator(Merged));
  798. if (isLoadSingle(Opcode)) {
  799. // If the previous loads defined a super-reg, then we have to mark earlier
  800. // operands undef; Replicate the super-reg def on the merged instruction.
  801. for (MachineInstr &MI : FixupRange) {
  802. for (unsigned &ImpDefReg : ImpDefs) {
  803. for (MachineOperand &MO : MI.implicit_operands()) {
  804. if (!MO.isReg() || MO.getReg() != ImpDefReg)
  805. continue;
  806. if (MO.readsReg())
  807. MO.setIsUndef();
  808. else if (MO.isDef())
  809. ImpDefReg = 0;
  810. }
  811. }
  812. }
  813. MachineInstrBuilder MIB(*Merged->getParent()->getParent(), Merged);
  814. for (unsigned ImpDef : ImpDefs)
  815. MIB.addReg(ImpDef, RegState::ImplicitDefine);
  816. } else {
  817. // Remove kill flags: We are possibly storing the values later now.
  818. assert(isi32Store(Opcode) || Opcode == ARM::VSTRS || Opcode == ARM::VSTRD);
  819. for (MachineInstr &MI : FixupRange) {
  820. for (MachineOperand &MO : MI.uses()) {
  821. if (!MO.isReg() || !MO.isKill())
  822. continue;
  823. if (UsedRegs.count(MO.getReg()))
  824. MO.setIsKill(false);
  825. }
  826. }
  827. assert(ImpDefs.empty());
  828. }
  829. return Merged;
  830. }
  831. static bool isValidLSDoubleOffset(int Offset) {
  832. unsigned Value = abs(Offset);
  833. // t2LDRDi8/t2STRDi8 supports an 8 bit immediate which is internally
  834. // multiplied by 4.
  835. return (Value % 4) == 0 && Value < 1024;
  836. }
  837. /// Return true for loads/stores that can be combined to a double/multi
  838. /// operation without increasing the requirements for alignment.
  839. static bool mayCombineMisaligned(const TargetSubtargetInfo &STI,
  840. const MachineInstr &MI) {
  841. // vldr/vstr trap on misaligned pointers anyway, forming vldm makes no
  842. // difference.
  843. unsigned Opcode = MI.getOpcode();
  844. if (!isi32Load(Opcode) && !isi32Store(Opcode))
  845. return true;
  846. // Stack pointer alignment is out of the programmers control so we can trust
  847. // SP-relative loads/stores.
  848. if (getLoadStoreBaseOp(MI).getReg() == ARM::SP &&
  849. STI.getFrameLowering()->getTransientStackAlignment() >= 4)
  850. return true;
  851. return false;
  852. }
  853. /// Find candidates for load/store multiple merge in list of MemOpQueueEntries.
  854. void ARMLoadStoreOpt::FormCandidates(const MemOpQueue &MemOps) {
  855. const MachineInstr *FirstMI = MemOps[0].MI;
  856. unsigned Opcode = FirstMI->getOpcode();
  857. bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);
  858. unsigned Size = getLSMultipleTransferSize(FirstMI);
  859. unsigned SIndex = 0;
  860. unsigned EIndex = MemOps.size();
  861. do {
  862. // Look at the first instruction.
  863. const MachineInstr *MI = MemOps[SIndex].MI;
  864. int Offset = MemOps[SIndex].Offset;
  865. const MachineOperand &PMO = getLoadStoreRegOp(*MI);
  866. unsigned PReg = PMO.getReg();
  867. unsigned PRegNum = PMO.isUndef() ? UINT_MAX : TRI->getEncodingValue(PReg);
  868. unsigned Latest = SIndex;
  869. unsigned Earliest = SIndex;
  870. unsigned Count = 1;
  871. bool CanMergeToLSDouble =
  872. STI->isThumb2() && isNotVFP && isValidLSDoubleOffset(Offset);
  873. // ARM errata 602117: LDRD with base in list may result in incorrect base
  874. // register when interrupted or faulted.
  875. if (STI->isCortexM3() && isi32Load(Opcode) &&
  876. PReg == getLoadStoreBaseOp(*MI).getReg())
  877. CanMergeToLSDouble = false;
  878. bool CanMergeToLSMulti = true;
  879. // On swift vldm/vstm starting with an odd register number as that needs
  880. // more uops than single vldrs.
  881. if (STI->isSwift() && !isNotVFP && (PRegNum % 2) == 1)
  882. CanMergeToLSMulti = false;
  883. // LDRD/STRD do not allow SP/PC. LDM/STM do not support it or have it
  884. // deprecated; LDM to PC is fine but cannot happen here.
  885. if (PReg == ARM::SP || PReg == ARM::PC)
  886. CanMergeToLSMulti = CanMergeToLSDouble = false;
  887. // Should we be conservative?
  888. if (AssumeMisalignedLoadStores && !mayCombineMisaligned(*STI, *MI))
  889. CanMergeToLSMulti = CanMergeToLSDouble = false;
  890. // Merge following instructions where possible.
  891. for (unsigned I = SIndex+1; I < EIndex; ++I, ++Count) {
  892. int NewOffset = MemOps[I].Offset;
  893. if (NewOffset != Offset + (int)Size)
  894. break;
  895. const MachineOperand &MO = getLoadStoreRegOp(*MemOps[I].MI);
  896. unsigned Reg = MO.getReg();
  897. if (Reg == ARM::SP || Reg == ARM::PC)
  898. break;
  899. // See if the current load/store may be part of a multi load/store.
  900. unsigned RegNum = MO.isUndef() ? UINT_MAX : TRI->getEncodingValue(Reg);
  901. bool PartOfLSMulti = CanMergeToLSMulti;
  902. if (PartOfLSMulti) {
  903. // Register numbers must be in ascending order.
  904. if (RegNum <= PRegNum)
  905. PartOfLSMulti = false;
  906. // For VFP / NEON load/store multiples, the registers must be
  907. // consecutive and within the limit on the number of registers per
  908. // instruction.
  909. else if (!isNotVFP && RegNum != PRegNum+1)
  910. PartOfLSMulti = false;
  911. }
  912. // See if the current load/store may be part of a double load/store.
  913. bool PartOfLSDouble = CanMergeToLSDouble && Count <= 1;
  914. if (!PartOfLSMulti && !PartOfLSDouble)
  915. break;
  916. CanMergeToLSMulti &= PartOfLSMulti;
  917. CanMergeToLSDouble &= PartOfLSDouble;
  918. // Track MemOp with latest and earliest position (Positions are
  919. // counted in reverse).
  920. unsigned Position = MemOps[I].Position;
  921. if (Position < MemOps[Latest].Position)
  922. Latest = I;
  923. else if (Position > MemOps[Earliest].Position)
  924. Earliest = I;
  925. // Prepare for next MemOp.
  926. Offset += Size;
  927. PRegNum = RegNum;
  928. }
  929. // Form a candidate from the Ops collected so far.
  930. MergeCandidate *Candidate = new(Allocator.Allocate()) MergeCandidate;
  931. for (unsigned C = SIndex, CE = SIndex + Count; C < CE; ++C)
  932. Candidate->Instrs.push_back(MemOps[C].MI);
  933. Candidate->LatestMIIdx = Latest - SIndex;
  934. Candidate->EarliestMIIdx = Earliest - SIndex;
  935. Candidate->InsertPos = MemOps[Latest].Position;
  936. if (Count == 1)
  937. CanMergeToLSMulti = CanMergeToLSDouble = false;
  938. Candidate->CanMergeToLSMulti = CanMergeToLSMulti;
  939. Candidate->CanMergeToLSDouble = CanMergeToLSDouble;
  940. Candidates.push_back(Candidate);
  941. // Continue after the chain.
  942. SIndex += Count;
  943. } while (SIndex < EIndex);
  944. }
  945. static unsigned getUpdatingLSMultipleOpcode(unsigned Opc,
  946. ARM_AM::AMSubMode Mode) {
  947. switch (Opc) {
  948. default: llvm_unreachable("Unhandled opcode!");
  949. case ARM::LDMIA:
  950. case ARM::LDMDA:
  951. case ARM::LDMDB:
  952. case ARM::LDMIB:
  953. switch (Mode) {
  954. default: llvm_unreachable("Unhandled submode!");
  955. case ARM_AM::ia: return ARM::LDMIA_UPD;
  956. case ARM_AM::ib: return ARM::LDMIB_UPD;
  957. case ARM_AM::da: return ARM::LDMDA_UPD;
  958. case ARM_AM::db: return ARM::LDMDB_UPD;
  959. }
  960. case ARM::STMIA:
  961. case ARM::STMDA:
  962. case ARM::STMDB:
  963. case ARM::STMIB:
  964. switch (Mode) {
  965. default: llvm_unreachable("Unhandled submode!");
  966. case ARM_AM::ia: return ARM::STMIA_UPD;
  967. case ARM_AM::ib: return ARM::STMIB_UPD;
  968. case ARM_AM::da: return ARM::STMDA_UPD;
  969. case ARM_AM::db: return ARM::STMDB_UPD;
  970. }
  971. case ARM::t2LDMIA:
  972. case ARM::t2LDMDB:
  973. switch (Mode) {
  974. default: llvm_unreachable("Unhandled submode!");
  975. case ARM_AM::ia: return ARM::t2LDMIA_UPD;
  976. case ARM_AM::db: return ARM::t2LDMDB_UPD;
  977. }
  978. case ARM::t2STMIA:
  979. case ARM::t2STMDB:
  980. switch (Mode) {
  981. default: llvm_unreachable("Unhandled submode!");
  982. case ARM_AM::ia: return ARM::t2STMIA_UPD;
  983. case ARM_AM::db: return ARM::t2STMDB_UPD;
  984. }
  985. case ARM::VLDMSIA:
  986. switch (Mode) {
  987. default: llvm_unreachable("Unhandled submode!");
  988. case ARM_AM::ia: return ARM::VLDMSIA_UPD;
  989. case ARM_AM::db: return ARM::VLDMSDB_UPD;
  990. }
  991. case ARM::VLDMDIA:
  992. switch (Mode) {
  993. default: llvm_unreachable("Unhandled submode!");
  994. case ARM_AM::ia: return ARM::VLDMDIA_UPD;
  995. case ARM_AM::db: return ARM::VLDMDDB_UPD;
  996. }
  997. case ARM::VSTMSIA:
  998. switch (Mode) {
  999. default: llvm_unreachable("Unhandled submode!");
  1000. case ARM_AM::ia: return ARM::VSTMSIA_UPD;
  1001. case ARM_AM::db: return ARM::VSTMSDB_UPD;
  1002. }
  1003. case ARM::VSTMDIA:
  1004. switch (Mode) {
  1005. default: llvm_unreachable("Unhandled submode!");
  1006. case ARM_AM::ia: return ARM::VSTMDIA_UPD;
  1007. case ARM_AM::db: return ARM::VSTMDDB_UPD;
  1008. }
  1009. }
  1010. }
  1011. /// Check if the given instruction increments or decrements a register and
  1012. /// return the amount it is incremented/decremented. Returns 0 if the CPSR flags
  1013. /// generated by the instruction are possibly read as well.
  1014. static int isIncrementOrDecrement(const MachineInstr &MI, unsigned Reg,
  1015. ARMCC::CondCodes Pred, unsigned PredReg) {
  1016. bool CheckCPSRDef;
  1017. int Scale;
  1018. switch (MI.getOpcode()) {
  1019. case ARM::tADDi8: Scale = 4; CheckCPSRDef = true; break;
  1020. case ARM::tSUBi8: Scale = -4; CheckCPSRDef = true; break;
  1021. case ARM::t2SUBri:
  1022. case ARM::SUBri: Scale = -1; CheckCPSRDef = true; break;
  1023. case ARM::t2ADDri:
  1024. case ARM::ADDri: Scale = 1; CheckCPSRDef = true; break;
  1025. case ARM::tADDspi: Scale = 4; CheckCPSRDef = false; break;
  1026. case ARM::tSUBspi: Scale = -4; CheckCPSRDef = false; break;
  1027. default: return 0;
  1028. }
  1029. unsigned MIPredReg;
  1030. if (MI.getOperand(0).getReg() != Reg ||
  1031. MI.getOperand(1).getReg() != Reg ||
  1032. getInstrPredicate(MI, MIPredReg) != Pred ||
  1033. MIPredReg != PredReg)
  1034. return 0;
  1035. if (CheckCPSRDef && definesCPSR(&MI))
  1036. return 0;
  1037. return MI.getOperand(2).getImm() * Scale;
  1038. }
  1039. /// Searches for an increment or decrement of \p Reg before \p MBBI.
  1040. static MachineBasicBlock::iterator
  1041. findIncDecBefore(MachineBasicBlock::iterator MBBI, unsigned Reg,
  1042. ARMCC::CondCodes Pred, unsigned PredReg, int &Offset) {
  1043. Offset = 0;
  1044. MachineBasicBlock &MBB = *MBBI->getParent();
  1045. MachineBasicBlock::iterator BeginMBBI = MBB.begin();
  1046. MachineBasicBlock::iterator EndMBBI = MBB.end();
  1047. if (MBBI == BeginMBBI)
  1048. return EndMBBI;
  1049. // Skip debug values.
  1050. MachineBasicBlock::iterator PrevMBBI = std::prev(MBBI);
  1051. while (PrevMBBI->isDebugValue() && PrevMBBI != BeginMBBI)
  1052. --PrevMBBI;
  1053. Offset = isIncrementOrDecrement(*PrevMBBI, Reg, Pred, PredReg);
  1054. return Offset == 0 ? EndMBBI : PrevMBBI;
  1055. }
  1056. /// Searches for a increment or decrement of \p Reg after \p MBBI.
  1057. static MachineBasicBlock::iterator
  1058. findIncDecAfter(MachineBasicBlock::iterator MBBI, unsigned Reg,
  1059. ARMCC::CondCodes Pred, unsigned PredReg, int &Offset) {
  1060. Offset = 0;
  1061. MachineBasicBlock &MBB = *MBBI->getParent();
  1062. MachineBasicBlock::iterator EndMBBI = MBB.end();
  1063. MachineBasicBlock::iterator NextMBBI = std::next(MBBI);
  1064. // Skip debug values.
  1065. while (NextMBBI != EndMBBI && NextMBBI->isDebugValue())
  1066. ++NextMBBI;
  1067. if (NextMBBI == EndMBBI)
  1068. return EndMBBI;
  1069. Offset = isIncrementOrDecrement(*NextMBBI, Reg, Pred, PredReg);
  1070. return Offset == 0 ? EndMBBI : NextMBBI;
  1071. }
  1072. /// Fold proceeding/trailing inc/dec of base register into the
  1073. /// LDM/STM/VLDM{D|S}/VSTM{D|S} op when possible:
  1074. ///
  1075. /// stmia rn, <ra, rb, rc>
  1076. /// rn := rn + 4 * 3;
  1077. /// =>
  1078. /// stmia rn!, <ra, rb, rc>
  1079. ///
  1080. /// rn := rn - 4 * 3;
  1081. /// ldmia rn, <ra, rb, rc>
  1082. /// =>
  1083. /// ldmdb rn!, <ra, rb, rc>
  1084. bool ARMLoadStoreOpt::MergeBaseUpdateLSMultiple(MachineInstr *MI) {
  1085. // Thumb1 is already using updating loads/stores.
  1086. if (isThumb1) return false;
  1087. const MachineOperand &BaseOP = MI->getOperand(0);
  1088. unsigned Base = BaseOP.getReg();
  1089. bool BaseKill = BaseOP.isKill();
  1090. unsigned PredReg = 0;
  1091. ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
  1092. unsigned Opcode = MI->getOpcode();
  1093. DebugLoc DL = MI->getDebugLoc();
  1094. // Can't use an updating ld/st if the base register is also a dest
  1095. // register. e.g. ldmdb r0!, {r0, r1, r2}. The behavior is undefined.
  1096. for (unsigned i = 2, e = MI->getNumOperands(); i != e; ++i)
  1097. if (MI->getOperand(i).getReg() == Base)
  1098. return false;
  1099. int Bytes = getLSMultipleTransferSize(MI);
  1100. MachineBasicBlock &MBB = *MI->getParent();
  1101. MachineBasicBlock::iterator MBBI(MI);
  1102. int Offset;
  1103. MachineBasicBlock::iterator MergeInstr
  1104. = findIncDecBefore(MBBI, Base, Pred, PredReg, Offset);
  1105. ARM_AM::AMSubMode Mode = getLoadStoreMultipleSubMode(Opcode);
  1106. if (Mode == ARM_AM::ia && Offset == -Bytes) {
  1107. Mode = ARM_AM::db;
  1108. } else if (Mode == ARM_AM::ib && Offset == -Bytes) {
  1109. Mode = ARM_AM::da;
  1110. } else {
  1111. MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset);
  1112. if (((Mode != ARM_AM::ia && Mode != ARM_AM::ib) || Offset != Bytes) &&
  1113. ((Mode != ARM_AM::da && Mode != ARM_AM::db) || Offset != -Bytes))
  1114. return false;
  1115. }
  1116. MBB.erase(MergeInstr);
  1117. unsigned NewOpc = getUpdatingLSMultipleOpcode(Opcode, Mode);
  1118. MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
  1119. .addReg(Base, getDefRegState(true)) // WB base register
  1120. .addReg(Base, getKillRegState(BaseKill))
  1121. .addImm(Pred).addReg(PredReg);
  1122. // Transfer the rest of operands.
  1123. for (unsigned OpNum = 3, e = MI->getNumOperands(); OpNum != e; ++OpNum)
  1124. MIB.addOperand(MI->getOperand(OpNum));
  1125. // Transfer memoperands.
  1126. MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
  1127. MBB.erase(MBBI);
  1128. return true;
  1129. }
  1130. static unsigned getPreIndexedLoadStoreOpcode(unsigned Opc,
  1131. ARM_AM::AddrOpc Mode) {
  1132. switch (Opc) {
  1133. case ARM::LDRi12:
  1134. return ARM::LDR_PRE_IMM;
  1135. case ARM::STRi12:
  1136. return ARM::STR_PRE_IMM;
  1137. case ARM::VLDRS:
  1138. return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;
  1139. case ARM::VLDRD:
  1140. return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;
  1141. case ARM::VSTRS:
  1142. return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;
  1143. case ARM::VSTRD:
  1144. return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;
  1145. case ARM::t2LDRi8:
  1146. case ARM::t2LDRi12:
  1147. return ARM::t2LDR_PRE;
  1148. case ARM::t2STRi8:
  1149. case ARM::t2STRi12:
  1150. return ARM::t2STR_PRE;
  1151. default: llvm_unreachable("Unhandled opcode!");
  1152. }
  1153. }
  1154. static unsigned getPostIndexedLoadStoreOpcode(unsigned Opc,
  1155. ARM_AM::AddrOpc Mode) {
  1156. switch (Opc) {
  1157. case ARM::LDRi12:
  1158. return ARM::LDR_POST_IMM;
  1159. case ARM::STRi12:
  1160. return ARM::STR_POST_IMM;
  1161. case ARM::VLDRS:
  1162. return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;
  1163. case ARM::VLDRD:
  1164. return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;
  1165. case ARM::VSTRS:
  1166. return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;
  1167. case ARM::VSTRD:
  1168. return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;
  1169. case ARM::t2LDRi8:
  1170. case ARM::t2LDRi12:
  1171. return ARM::t2LDR_POST;
  1172. case ARM::t2STRi8:
  1173. case ARM::t2STRi12:
  1174. return ARM::t2STR_POST;
  1175. default: llvm_unreachable("Unhandled opcode!");
  1176. }
  1177. }
  1178. /// Fold proceeding/trailing inc/dec of base register into the
  1179. /// LDR/STR/FLD{D|S}/FST{D|S} op when possible:
  1180. bool ARMLoadStoreOpt::MergeBaseUpdateLoadStore(MachineInstr *MI) {
  1181. // Thumb1 doesn't have updating LDR/STR.
  1182. // FIXME: Use LDM/STM with single register instead.
  1183. if (isThumb1) return false;
  1184. unsigned Base = getLoadStoreBaseOp(*MI).getReg();
  1185. bool BaseKill = getLoadStoreBaseOp(*MI).isKill();
  1186. unsigned Opcode = MI->getOpcode();
  1187. DebugLoc DL = MI->getDebugLoc();
  1188. bool isAM5 = (Opcode == ARM::VLDRD || Opcode == ARM::VLDRS ||
  1189. Opcode == ARM::VSTRD || Opcode == ARM::VSTRS);
  1190. bool isAM2 = (Opcode == ARM::LDRi12 || Opcode == ARM::STRi12);
  1191. if (isi32Load(Opcode) || isi32Store(Opcode))
  1192. if (MI->getOperand(2).getImm() != 0)
  1193. return false;
  1194. if (isAM5 && ARM_AM::getAM5Offset(MI->getOperand(2).getImm()) != 0)
  1195. return false;
  1196. // Can't do the merge if the destination register is the same as the would-be
  1197. // writeback register.
  1198. if (MI->getOperand(0).getReg() == Base)
  1199. return false;
  1200. unsigned PredReg = 0;
  1201. ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
  1202. int Bytes = getLSMultipleTransferSize(MI);
  1203. MachineBasicBlock &MBB = *MI->getParent();
  1204. MachineBasicBlock::iterator MBBI(MI);
  1205. int Offset;
  1206. MachineBasicBlock::iterator MergeInstr
  1207. = findIncDecBefore(MBBI, Base, Pred, PredReg, Offset);
  1208. unsigned NewOpc;
  1209. if (!isAM5 && Offset == Bytes) {
  1210. NewOpc = getPreIndexedLoadStoreOpcode(Opcode, ARM_AM::add);
  1211. } else if (Offset == -Bytes) {
  1212. NewOpc = getPreIndexedLoadStoreOpcode(Opcode, ARM_AM::sub);
  1213. } else {
  1214. MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset);
  1215. if (Offset == Bytes) {
  1216. NewOpc = getPostIndexedLoadStoreOpcode(Opcode, ARM_AM::add);
  1217. } else if (!isAM5 && Offset == -Bytes) {
  1218. NewOpc = getPostIndexedLoadStoreOpcode(Opcode, ARM_AM::sub);
  1219. } else
  1220. return false;
  1221. }
  1222. MBB.erase(MergeInstr);
  1223. ARM_AM::AddrOpc AddSub = Offset < 0 ? ARM_AM::sub : ARM_AM::add;
  1224. bool isLd = isLoadSingle(Opcode);
  1225. if (isAM5) {
  1226. // VLDM[SD]_UPD, VSTM[SD]_UPD
  1227. // (There are no base-updating versions of VLDR/VSTR instructions, but the
  1228. // updating load/store-multiple instructions can be used with only one
  1229. // register.)
  1230. MachineOperand &MO = MI->getOperand(0);
  1231. BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
  1232. .addReg(Base, getDefRegState(true)) // WB base register
  1233. .addReg(Base, getKillRegState(isLd ? BaseKill : false))
  1234. .addImm(Pred).addReg(PredReg)
  1235. .addReg(MO.getReg(), (isLd ? getDefRegState(true) :
  1236. getKillRegState(MO.isKill())));
  1237. } else if (isLd) {
  1238. if (isAM2) {
  1239. // LDR_PRE, LDR_POST
  1240. if (NewOpc == ARM::LDR_PRE_IMM || NewOpc == ARM::LDRB_PRE_IMM) {
  1241. BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
  1242. .addReg(Base, RegState::Define)
  1243. .addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
  1244. } else {
  1245. int Imm = ARM_AM::getAM2Opc(AddSub, Bytes, ARM_AM::no_shift);
  1246. BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
  1247. .addReg(Base, RegState::Define)
  1248. .addReg(Base).addReg(0).addImm(Imm).addImm(Pred).addReg(PredReg);
  1249. }
  1250. } else {
  1251. // t2LDR_PRE, t2LDR_POST
  1252. BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
  1253. .addReg(Base, RegState::Define)
  1254. .addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
  1255. }
  1256. } else {
  1257. MachineOperand &MO = MI->getOperand(0);
  1258. // FIXME: post-indexed stores use am2offset_imm, which still encodes
  1259. // the vestigal zero-reg offset register. When that's fixed, this clause
  1260. // can be removed entirely.
  1261. if (isAM2 && NewOpc == ARM::STR_POST_IMM) {
  1262. int Imm = ARM_AM::getAM2Opc(AddSub, Bytes, ARM_AM::no_shift);
  1263. // STR_PRE, STR_POST
  1264. BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base)
  1265. .addReg(MO.getReg(), getKillRegState(MO.isKill()))
  1266. .addReg(Base).addReg(0).addImm(Imm).addImm(Pred).addReg(PredReg);
  1267. } else {
  1268. // t2STR_PRE, t2STR_POST
  1269. BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base)
  1270. .addReg(MO.getReg(), getKillRegState(MO.isKill()))
  1271. .addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
  1272. }
  1273. }
  1274. MBB.erase(MBBI);
  1275. return true;
  1276. }
  1277. bool ARMLoadStoreOpt::MergeBaseUpdateLSDouble(MachineInstr &MI) const {
  1278. unsigned Opcode = MI.getOpcode();
  1279. assert((Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8) &&
  1280. "Must have t2STRDi8 or t2LDRDi8");
  1281. if (MI.getOperand(3).getImm() != 0)
  1282. return false;
  1283. // Behaviour for writeback is undefined if base register is the same as one
  1284. // of the others.
  1285. const MachineOperand &BaseOp = MI.getOperand(2);
  1286. unsigned Base = BaseOp.getReg();
  1287. const MachineOperand &Reg0Op = MI.getOperand(0);
  1288. const MachineOperand &Reg1Op = MI.getOperand(1);
  1289. if (Reg0Op.getReg() == Base || Reg1Op.getReg() == Base)
  1290. return false;
  1291. unsigned PredReg;
  1292. ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
  1293. MachineBasicBlock::iterator MBBI(MI);
  1294. MachineBasicBlock &MBB = *MI.getParent();
  1295. int Offset;
  1296. MachineBasicBlock::iterator MergeInstr = findIncDecBefore(MBBI, Base, Pred,
  1297. PredReg, Offset);
  1298. unsigned NewOpc;
  1299. if (Offset == 8 || Offset == -8) {
  1300. NewOpc = Opcode == ARM::t2LDRDi8 ? ARM::t2LDRD_PRE : ARM::t2STRD_PRE;
  1301. } else {
  1302. MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset);
  1303. if (Offset == 8 || Offset == -8) {
  1304. NewOpc = Opcode == ARM::t2LDRDi8 ? ARM::t2LDRD_POST : ARM::t2STRD_POST;
  1305. } else
  1306. return false;
  1307. }
  1308. MBB.erase(MergeInstr);
  1309. DebugLoc DL = MI.getDebugLoc();
  1310. MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
  1311. if (NewOpc == ARM::t2LDRD_PRE || NewOpc == ARM::t2LDRD_POST) {
  1312. MIB.addOperand(Reg0Op).addOperand(Reg1Op)
  1313. .addReg(BaseOp.getReg(), RegState::Define);
  1314. } else {
  1315. assert(NewOpc == ARM::t2STRD_PRE || NewOpc == ARM::t2STRD_POST);
  1316. MIB.addReg(BaseOp.getReg(), RegState::Define)
  1317. .addOperand(Reg0Op).addOperand(Reg1Op);
  1318. }
  1319. MIB.addReg(BaseOp.getReg(), RegState::Kill)
  1320. .addImm(Offset).addImm(Pred).addReg(PredReg);
  1321. assert(TII->get(Opcode).getNumOperands() == 6 &&
  1322. TII->get(NewOpc).getNumOperands() == 7 &&
  1323. "Unexpected number of operands in Opcode specification.");
  1324. // Transfer implicit operands.
  1325. for (const MachineOperand &MO : MI.implicit_operands())
  1326. MIB.addOperand(MO);
  1327. MIB->setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
  1328. MBB.erase(MBBI);
  1329. return true;
  1330. }
  1331. /// Returns true if instruction is a memory operation that this pass is capable
  1332. /// of operating on.
  1333. static bool isMemoryOp(const MachineInstr &MI) {
  1334. unsigned Opcode = MI.getOpcode();
  1335. switch (Opcode) {
  1336. case ARM::VLDRS:
  1337. case ARM::VSTRS:
  1338. case ARM::VLDRD:
  1339. case ARM::VSTRD:
  1340. case ARM::LDRi12:
  1341. case ARM::STRi12:
  1342. case ARM::tLDRi:
  1343. case ARM::tSTRi:
  1344. case ARM::tLDRspi:
  1345. case ARM::tSTRspi:
  1346. case ARM::t2LDRi8:
  1347. case ARM::t2LDRi12:
  1348. case ARM::t2STRi8:
  1349. case ARM::t2STRi12:
  1350. break;
  1351. default:
  1352. return false;
  1353. }
  1354. if (!MI.getOperand(1).isReg())
  1355. return false;
  1356. // When no memory operands are present, conservatively assume unaligned,
  1357. // volatile, unfoldable.
  1358. if (!MI.hasOneMemOperand())
  1359. return false;
  1360. const MachineMemOperand &MMO = **MI.memoperands_begin();
  1361. // Don't touch volatile memory accesses - we may be changing their order.
  1362. if (MMO.isVolatile())
  1363. return false;
  1364. // Unaligned ldr/str is emulated by some kernels, but unaligned ldm/stm is
  1365. // not.
  1366. if (MMO.getAlignment() < 4)
  1367. return false;
  1368. // str <undef> could probably be eliminated entirely, but for now we just want
  1369. // to avoid making a mess of it.
  1370. // FIXME: Use str <undef> as a wildcard to enable better stm folding.
  1371. if (MI.getOperand(0).isReg() && MI.getOperand(0).isUndef())
  1372. return false;
  1373. // Likewise don't mess with references to undefined addresses.
  1374. if (MI.getOperand(1).isUndef())
  1375. return false;
  1376. return true;
  1377. }
  1378. static void InsertLDR_STR(MachineBasicBlock &MBB,
  1379. MachineBasicBlock::iterator &MBBI,
  1380. int Offset, bool isDef,
  1381. DebugLoc DL, unsigned NewOpc,
  1382. unsigned Reg, bool RegDeadKill, bool RegUndef,
  1383. unsigned BaseReg, bool BaseKill, bool BaseUndef,
  1384. bool OffKill, bool OffUndef,
  1385. ARMCC::CondCodes Pred, unsigned PredReg,
  1386. const TargetInstrInfo *TII, bool isT2) {
  1387. if (isDef) {
  1388. MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(),
  1389. TII->get(NewOpc))
  1390. .addReg(Reg, getDefRegState(true) | getDeadRegState(RegDeadKill))
  1391. .addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef));
  1392. MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
  1393. } else {
  1394. MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(),
  1395. TII->get(NewOpc))
  1396. .addReg(Reg, getKillRegState(RegDeadKill) | getUndefRegState(RegUndef))
  1397. .addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef));
  1398. MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
  1399. }
  1400. }
  1401. bool ARMLoadStoreOpt::FixInvalidRegPairOp(MachineBasicBlock &MBB,
  1402. MachineBasicBlock::iterator &MBBI) {
  1403. MachineInstr *MI = &*MBBI;
  1404. unsigned Opcode = MI->getOpcode();
  1405. if (Opcode != ARM::LDRD && Opcode != ARM::STRD && Opcode != ARM::t2LDRDi8)
  1406. return false;
  1407. const MachineOperand &BaseOp = MI->getOperand(2);
  1408. unsigned BaseReg = BaseOp.getReg();
  1409. unsigned EvenReg = MI->getOperand(0).getReg();
  1410. unsigned OddReg = MI->getOperand(1).getReg();
  1411. unsigned EvenRegNum = TRI->getDwarfRegNum(EvenReg, false);
  1412. unsigned OddRegNum = TRI->getDwarfRegNum(OddReg, false);
  1413. // ARM errata 602117: LDRD with base in list may result in incorrect base
  1414. // register when interrupted or faulted.
  1415. bool Errata602117 = EvenReg == BaseReg &&
  1416. (Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8) && STI->isCortexM3();
  1417. // ARM LDRD/STRD needs consecutive registers.
  1418. bool NonConsecutiveRegs = (Opcode == ARM::LDRD || Opcode == ARM::STRD) &&
  1419. (EvenRegNum % 2 != 0 || EvenRegNum + 1 != OddRegNum);
  1420. if (!Errata602117 && !NonConsecutiveRegs)
  1421. return false;
  1422. bool isT2 = Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8;
  1423. bool isLd = Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8;
  1424. bool EvenDeadKill = isLd ?
  1425. MI->getOperand(0).isDead() : MI->getOperand(0).isKill();
  1426. bool EvenUndef = MI->getOperand(0).isUndef();
  1427. bool OddDeadKill = isLd ?
  1428. MI->getOperand(1).isDead() : MI->getOperand(1).isKill();
  1429. bool OddUndef = MI->getOperand(1).isUndef();
  1430. bool BaseKill = BaseOp.isKill();
  1431. bool BaseUndef = BaseOp.isUndef();
  1432. bool OffKill = isT2 ? false : MI->getOperand(3).isKill();
  1433. bool OffUndef = isT2 ? false : MI->getOperand(3).isUndef();
  1434. int OffImm = getMemoryOpOffset(MI);
  1435. unsigned PredReg = 0;
  1436. ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
  1437. if (OddRegNum > EvenRegNum && OffImm == 0) {
  1438. // Ascending register numbers and no offset. It's safe to change it to a
  1439. // ldm or stm.
  1440. unsigned NewOpc = (isLd)
  1441. ? (isT2 ? ARM::t2LDMIA : ARM::LDMIA)
  1442. : (isT2 ? ARM::t2STMIA : ARM::STMIA);
  1443. if (isLd) {
  1444. BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc))
  1445. .addReg(BaseReg, getKillRegState(BaseKill))
  1446. .addImm(Pred).addReg(PredReg)
  1447. .addReg(EvenReg, getDefRegState(isLd) | getDeadRegState(EvenDeadKill))
  1448. .addReg(OddReg, getDefRegState(isLd) | getDeadRegState(OddDeadKill));
  1449. ++NumLDRD2LDM;
  1450. } else {
  1451. BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc))
  1452. .addReg(BaseReg, getKillRegState(BaseKill))
  1453. .addImm(Pred).addReg(PredReg)
  1454. .addReg(EvenReg,
  1455. getKillRegState(EvenDeadKill) | getUndefRegState(EvenUndef))
  1456. .addReg(OddReg,
  1457. getKillRegState(OddDeadKill) | getUndefRegState(OddUndef));
  1458. ++NumSTRD2STM;
  1459. }
  1460. } else {
  1461. // Split into two instructions.
  1462. unsigned NewOpc = (isLd)
  1463. ? (isT2 ? (OffImm < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12)
  1464. : (isT2 ? (OffImm < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12);
  1465. // Be extra careful for thumb2. t2LDRi8 can't reference a zero offset,
  1466. // so adjust and use t2LDRi12 here for that.
  1467. unsigned NewOpc2 = (isLd)
  1468. ? (isT2 ? (OffImm+4 < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12)
  1469. : (isT2 ? (OffImm+4 < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12);
  1470. DebugLoc dl = MBBI->getDebugLoc();
  1471. // If this is a load and base register is killed, it may have been
  1472. // re-defed by the load, make sure the first load does not clobber it.
  1473. if (isLd &&
  1474. (BaseKill || OffKill) &&
  1475. (TRI->regsOverlap(EvenReg, BaseReg))) {
  1476. assert(!TRI->regsOverlap(OddReg, BaseReg));
  1477. InsertLDR_STR(MBB, MBBI, OffImm+4, isLd, dl, NewOpc2,
  1478. OddReg, OddDeadKill, false,
  1479. BaseReg, false, BaseUndef, false, OffUndef,
  1480. Pred, PredReg, TII, isT2);
  1481. InsertLDR_STR(MBB, MBBI, OffImm, isLd, dl, NewOpc,
  1482. EvenReg, EvenDeadKill, false,
  1483. BaseReg, BaseKill, BaseUndef, OffKill, OffUndef,
  1484. Pred, PredReg, TII, isT2);
  1485. } else {
  1486. if (OddReg == EvenReg && EvenDeadKill) {
  1487. // If the two source operands are the same, the kill marker is
  1488. // probably on the first one. e.g.
  1489. // t2STRDi8 %R5<kill>, %R5, %R9<kill>, 0, 14, %reg0
  1490. EvenDeadKill = false;
  1491. OddDeadKill = true;
  1492. }
  1493. // Never kill the base register in the first instruction.
  1494. if (EvenReg == BaseReg)
  1495. EvenDeadKill = false;
  1496. InsertLDR_STR(MBB, MBBI, OffImm, isLd, dl, NewOpc,
  1497. EvenReg, EvenDeadKill, EvenUndef,
  1498. BaseReg, false, BaseUndef, false, OffUndef,
  1499. Pred, PredReg, TII, isT2);
  1500. InsertLDR_STR(MBB, MBBI, OffImm+4, isLd, dl, NewOpc2,
  1501. OddReg, OddDeadKill, OddUndef,
  1502. BaseReg, BaseKill, BaseUndef, OffKill, OffUndef,
  1503. Pred, PredReg, TII, isT2);
  1504. }
  1505. if (isLd)
  1506. ++NumLDRD2LDR;
  1507. else
  1508. ++NumSTRD2STR;
  1509. }
  1510. MBBI = MBB.erase(MBBI);
  1511. return true;
  1512. }
  1513. /// An optimization pass to turn multiple LDR / STR ops of the same base and
  1514. /// incrementing offset into LDM / STM ops.
  1515. bool ARMLoadStoreOpt::LoadStoreMultipleOpti(MachineBasicBlock &MBB) {
  1516. MemOpQueue MemOps;
  1517. unsigned CurrBase = 0;
  1518. unsigned CurrOpc = ~0u;
  1519. ARMCC::CondCodes CurrPred = ARMCC::AL;
  1520. unsigned Position = 0;
  1521. assert(Candidates.size() == 0);
  1522. assert(MergeBaseCandidates.size() == 0);
  1523. LiveRegsValid = false;
  1524. for (MachineBasicBlock::iterator I = MBB.end(), MBBI; I != MBB.begin();
  1525. I = MBBI) {
  1526. // The instruction in front of the iterator is the one we look at.
  1527. MBBI = std::prev(I);
  1528. if (FixInvalidRegPairOp(MBB, MBBI))
  1529. continue;
  1530. ++Position;
  1531. if (isMemoryOp(*MBBI)) {
  1532. unsigned Opcode = MBBI->getOpcode();
  1533. const MachineOperand &MO = MBBI->getOperand(0);
  1534. unsigned Reg = MO.getReg();
  1535. unsigned Base = getLoadStoreBaseOp(*MBBI).getReg();
  1536. unsigned PredReg = 0;
  1537. ARMCC::CondCodes Pred = getInstrPredicate(*MBBI, PredReg);
  1538. int Offset = getMemoryOpOffset(MBBI);
  1539. if (CurrBase == 0) {
  1540. // Start of a new chain.
  1541. CurrBase = Base;
  1542. CurrOpc = Opcode;
  1543. CurrPred = Pred;
  1544. MemOps.push_back(MemOpQueueEntry(MBBI, Offset, Position));
  1545. continue;
  1546. }
  1547. // Note: No need to match PredReg in the next if.
  1548. if (CurrOpc == Opcode && CurrBase == Base && CurrPred == Pred) {
  1549. // Watch out for:
  1550. // r4 := ldr [r0, #8]
  1551. // r4 := ldr [r0, #4]
  1552. // or
  1553. // r0 := ldr [r0]
  1554. // If a load overrides the base register or a register loaded by
  1555. // another load in our chain, we cannot take this instruction.
  1556. bool Overlap = false;
  1557. if (isLoadSingle(Opcode)) {
  1558. Overlap = (Base == Reg);
  1559. if (!Overlap) {
  1560. for (const MemOpQueueEntry &E : MemOps) {
  1561. if (TRI->regsOverlap(Reg, E.MI->getOperand(0).getReg())) {
  1562. Overlap = true;
  1563. break;
  1564. }
  1565. }
  1566. }
  1567. }
  1568. if (!Overlap) {
  1569. // Check offset and sort memory operation into the current chain.
  1570. if (Offset > MemOps.back().Offset) {
  1571. MemOps.push_back(MemOpQueueEntry(MBBI, Offset, Position));
  1572. continue;
  1573. } else {
  1574. MemOpQueue::iterator MI, ME;
  1575. for (MI = MemOps.begin(), ME = MemOps.end(); MI != ME; ++MI) {
  1576. if (Offset < MI->Offset) {
  1577. // Found a place to insert.
  1578. break;
  1579. }
  1580. if (Offset == MI->Offset) {
  1581. // Collision, abort.
  1582. MI = ME;
  1583. break;
  1584. }
  1585. }
  1586. if (MI != MemOps.end()) {
  1587. MemOps.insert(MI, MemOpQueueEntry(MBBI, Offset, Position));
  1588. continue;
  1589. }
  1590. }
  1591. }
  1592. }
  1593. // Don't advance the iterator; The op will start a new chain next.
  1594. MBBI = I;
  1595. --Position;
  1596. // Fallthrough to look into existing chain.
  1597. } else if (MBBI->isDebugValue()) {
  1598. continue;
  1599. } else if (MBBI->getOpcode() == ARM::t2LDRDi8 ||
  1600. MBBI->getOpcode() == ARM::t2STRDi8) {
  1601. // ARMPreAllocLoadStoreOpt has already formed some LDRD/STRD instructions
  1602. // remember them because we may still be able to merge add/sub into them.
  1603. MergeBaseCandidates.push_back(MBBI);
  1604. }
  1605. // If we are here then the chain is broken; Extract candidates for a merge.
  1606. if (MemOps.size() > 0) {
  1607. FormCandidates(MemOps);
  1608. // Reset for the next chain.
  1609. CurrBase = 0;
  1610. CurrOpc = ~0u;
  1611. CurrPred = ARMCC::AL;
  1612. MemOps.clear();
  1613. }
  1614. }
  1615. if (MemOps.size() > 0)
  1616. FormCandidates(MemOps);
  1617. // Sort candidates so they get processed from end to begin of the basic
  1618. // block later; This is necessary for liveness calculation.
  1619. auto LessThan = [](const MergeCandidate* M0, const MergeCandidate *M1) {
  1620. return M0->InsertPos < M1->InsertPos;
  1621. };
  1622. std::sort(Candidates.begin(), Candidates.end(), LessThan);
  1623. // Go through list of candidates and merge.
  1624. bool Changed = false;
  1625. for (const MergeCandidate *Candidate : Candidates) {
  1626. if (Candidate->CanMergeToLSMulti || Candidate->CanMergeToLSDouble) {
  1627. MachineInstr *Merged = MergeOpsUpdate(*Candidate);
  1628. // Merge preceding/trailing base inc/dec into the merged op.
  1629. if (Merged) {
  1630. Changed = true;
  1631. unsigned Opcode = Merged->getOpcode();
  1632. if (Opcode == ARM::t2STRDi8 || Opcode == ARM::t2LDRDi8)
  1633. MergeBaseUpdateLSDouble(*Merged);
  1634. else
  1635. MergeBaseUpdateLSMultiple(Merged);
  1636. } else {
  1637. for (MachineInstr *MI : Candidate->Instrs) {
  1638. if (MergeBaseUpdateLoadStore(MI))
  1639. Changed = true;
  1640. }
  1641. }
  1642. } else {
  1643. assert(Candidate->Instrs.size() == 1);
  1644. if (MergeBaseUpdateLoadStore(Candidate->Instrs.front()))
  1645. Changed = true;
  1646. }
  1647. }
  1648. Candidates.clear();
  1649. // Try to fold add/sub into the LDRD/STRD formed by ARMPreAllocLoadStoreOpt.
  1650. for (MachineInstr *MI : MergeBaseCandidates)
  1651. MergeBaseUpdateLSDouble(*MI);
  1652. MergeBaseCandidates.clear();
  1653. return Changed;
  1654. }
  1655. /// If this is a exit BB, try merging the return ops ("bx lr" and "mov pc, lr")
  1656. /// into the preceding stack restore so it directly restore the value of LR
  1657. /// into pc.
  1658. /// ldmfd sp!, {..., lr}
  1659. /// bx lr
  1660. /// or
  1661. /// ldmfd sp!, {..., lr}
  1662. /// mov pc, lr
  1663. /// =>
  1664. /// ldmfd sp!, {..., pc}
  1665. bool ARMLoadStoreOpt::MergeReturnIntoLDM(MachineBasicBlock &MBB) {
  1666. // Thumb1 LDM doesn't allow high registers.
  1667. if (isThumb1) return false;
  1668. if (MBB.empty()) return false;
  1669. MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
  1670. if (MBBI != MBB.begin() &&
  1671. (MBBI->getOpcode() == ARM::BX_RET ||
  1672. MBBI->getOpcode() == ARM::tBX_RET ||
  1673. MBBI->getOpcode() == ARM::MOVPCLR)) {
  1674. MachineBasicBlock::iterator PrevI = std::prev(MBBI);
  1675. // Ignore any DBG_VALUE instructions.
  1676. while (PrevI->isDebugValue() && PrevI != MBB.begin())
  1677. --PrevI;
  1678. MachineInstr *PrevMI = PrevI;
  1679. unsigned Opcode = PrevMI->getOpcode();
  1680. if (Opcode == ARM::LDMIA_UPD || Opcode == ARM::LDMDA_UPD ||
  1681. Opcode == ARM::LDMDB_UPD || Opcode == ARM::LDMIB_UPD ||
  1682. Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
  1683. MachineOperand &MO = PrevMI->getOperand(PrevMI->getNumOperands()-1);
  1684. if (MO.getReg() != ARM::LR)
  1685. return false;
  1686. unsigned NewOpc = (isThumb2 ? ARM::t2LDMIA_RET : ARM::LDMIA_RET);
  1687. assert(((isThumb2 && Opcode == ARM::t2LDMIA_UPD) ||
  1688. Opcode == ARM::LDMIA_UPD) && "Unsupported multiple load-return!");
  1689. PrevMI->setDesc(TII->get(NewOpc));
  1690. MO.setReg(ARM::PC);
  1691. PrevMI->copyImplicitOps(*MBB.getParent(), *MBBI);
  1692. MBB.erase(MBBI);
  1693. return true;
  1694. }
  1695. }
  1696. return false;
  1697. }
  1698. bool ARMLoadStoreOpt::CombineMovBx(MachineBasicBlock &MBB) {
  1699. MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
  1700. if (MBBI == MBB.begin() || MBBI == MBB.end() ||
  1701. MBBI->getOpcode() != ARM::tBX_RET)
  1702. return false;
  1703. MachineBasicBlock::iterator Prev = MBBI;
  1704. --Prev;
  1705. if (Prev->getOpcode() != ARM::tMOVr || !Prev->definesRegister(ARM::LR))
  1706. return false;
  1707. for (auto Use : Prev->uses())
  1708. if (Use.isKill()) {
  1709. AddDefaultPred(BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(ARM::tBX))
  1710. .addReg(Use.getReg(), RegState::Kill))
  1711. .copyImplicitOps(*MBBI);
  1712. MBB.erase(MBBI);
  1713. MBB.erase(Prev);
  1714. return true;
  1715. }
  1716. llvm_unreachable("tMOVr doesn't kill a reg before tBX_RET?");
  1717. }
  1718. bool ARMLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
  1719. if (skipFunction(*Fn.getFunction()))
  1720. return false;
  1721. MF = &Fn;
  1722. STI = &static_cast<const ARMSubtarget &>(Fn.getSubtarget());
  1723. TL = STI->getTargetLowering();
  1724. AFI = Fn.getInfo<ARMFunctionInfo>();
  1725. TII = STI->getInstrInfo();
  1726. TRI = STI->getRegisterInfo();
  1727. RegClassInfoValid = false;
  1728. isThumb2 = AFI->isThumb2Function();
  1729. isThumb1 = AFI->isThumbFunction() && !isThumb2;
  1730. bool Modified = false;
  1731. for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
  1732. ++MFI) {
  1733. MachineBasicBlock &MBB = *MFI;
  1734. Modified |= LoadStoreMultipleOpti(MBB);
  1735. if (STI->hasV5TOps())
  1736. Modified |= MergeReturnIntoLDM(MBB);
  1737. if (isThumb1)
  1738. Modified |= CombineMovBx(MBB);
  1739. }
  1740. Allocator.DestroyAll();
  1741. return Modified;
  1742. }
  1743. namespace llvm {
  1744. void initializeARMPreAllocLoadStoreOptPass(PassRegistry &);
  1745. }
  1746. #define ARM_PREALLOC_LOAD_STORE_OPT_NAME \
  1747. "ARM pre- register allocation load / store optimization pass"
  1748. namespace {
  1749. /// Pre- register allocation pass that move load / stores from consecutive
  1750. /// locations close to make it more likely they will be combined later.
  1751. struct ARMPreAllocLoadStoreOpt : public MachineFunctionPass{
  1752. static char ID;
  1753. ARMPreAllocLoadStoreOpt() : MachineFunctionPass(ID) {
  1754. initializeARMPreAllocLoadStoreOptPass(*PassRegistry::getPassRegistry());
  1755. }
  1756. const DataLayout *TD;
  1757. const TargetInstrInfo *TII;
  1758. const TargetRegisterInfo *TRI;
  1759. const ARMSubtarget *STI;
  1760. MachineRegisterInfo *MRI;
  1761. MachineFunction *MF;
  1762. bool runOnMachineFunction(MachineFunction &Fn) override;
  1763. const char *getPassName() const override {
  1764. return ARM_PREALLOC_LOAD_STORE_OPT_NAME;
  1765. }
  1766. private:
  1767. bool CanFormLdStDWord(MachineInstr *Op0, MachineInstr *Op1, DebugLoc &dl,
  1768. unsigned &NewOpc, unsigned &EvenReg,
  1769. unsigned &OddReg, unsigned &BaseReg,
  1770. int &Offset,
  1771. unsigned &PredReg, ARMCC::CondCodes &Pred,
  1772. bool &isT2);
  1773. bool RescheduleOps(MachineBasicBlock *MBB,
  1774. SmallVectorImpl<MachineInstr *> &Ops,
  1775. unsigned Base, bool isLd,
  1776. DenseMap<MachineInstr*, unsigned> &MI2LocMap);
  1777. bool RescheduleLoadStoreInstrs(MachineBasicBlock *MBB);
  1778. };
  1779. char ARMPreAllocLoadStoreOpt::ID = 0;
  1780. }
  1781. INITIALIZE_PASS(ARMPreAllocLoadStoreOpt, "arm-prera-load-store-opt",
  1782. ARM_PREALLOC_LOAD_STORE_OPT_NAME, false, false)
  1783. bool ARMPreAllocLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
  1784. if (AssumeMisalignedLoadStores || skipFunction(*Fn.getFunction()))
  1785. return false;
  1786. TD = &Fn.getDataLayout();
  1787. STI = &static_cast<const ARMSubtarget &>(Fn.getSubtarget());
  1788. TII = STI->getInstrInfo();
  1789. TRI = STI->getRegisterInfo();
  1790. MRI = &Fn.getRegInfo();
  1791. MF = &Fn;
  1792. bool Modified = false;
  1793. for (MachineBasicBlock &MFI : Fn)
  1794. Modified |= RescheduleLoadStoreInstrs(&MFI);
  1795. return Modified;
  1796. }
  1797. static bool IsSafeAndProfitableToMove(bool isLd, unsigned Base,
  1798. MachineBasicBlock::iterator I,
  1799. MachineBasicBlock::iterator E,
  1800. SmallPtrSetImpl<MachineInstr*> &MemOps,
  1801. SmallSet<unsigned, 4> &MemRegs,
  1802. const TargetRegisterInfo *TRI) {
  1803. // Are there stores / loads / calls between them?
  1804. // FIXME: This is overly conservative. We should make use of alias information
  1805. // some day.
  1806. SmallSet<unsigned, 4> AddedRegPressure;
  1807. while (++I != E) {
  1808. if (I->isDebugValue() || MemOps.count(&*I))
  1809. continue;
  1810. if (I->isCall() || I->isTerminator() || I->hasUnmodeledSideEffects())
  1811. return false;
  1812. if (isLd && I->mayStore())
  1813. return false;
  1814. if (!isLd) {
  1815. if (I->mayLoad())
  1816. return false;
  1817. // It's not safe to move the first 'str' down.
  1818. // str r1, [r0]
  1819. // strh r5, [r0]
  1820. // str r4, [r0, #+4]
  1821. if (I->mayStore())
  1822. return false;
  1823. }
  1824. for (unsigned j = 0, NumOps = I->getNumOperands(); j != NumOps; ++j) {
  1825. MachineOperand &MO = I->getOperand(j);
  1826. if (!MO.isReg())
  1827. continue;
  1828. unsigned Reg = MO.getReg();
  1829. if (MO.isDef() && TRI->regsOverlap(Reg, Base))
  1830. return false;
  1831. if (Reg != Base && !MemRegs.count(Reg))
  1832. AddedRegPressure.insert(Reg);
  1833. }
  1834. }
  1835. // Estimate register pressure increase due to the transformation.
  1836. if (MemRegs.size() <= 4)
  1837. // Ok if we are moving small number of instructions.
  1838. return true;
  1839. return AddedRegPressure.size() <= MemRegs.size() * 2;
  1840. }
  1841. bool
  1842. ARMPreAllocLoadStoreOpt::CanFormLdStDWord(MachineInstr *Op0, MachineInstr *Op1,
  1843. DebugLoc &dl, unsigned &NewOpc,
  1844. unsigned &FirstReg,
  1845. unsigned &SecondReg,
  1846. unsigned &BaseReg, int &Offset,
  1847. unsigned &PredReg,
  1848. ARMCC::CondCodes &Pred,
  1849. bool &isT2) {
  1850. // Make sure we're allowed to generate LDRD/STRD.
  1851. if (!STI->hasV5TEOps())
  1852. return false;
  1853. // FIXME: VLDRS / VSTRS -> VLDRD / VSTRD
  1854. unsigned Scale = 1;
  1855. unsigned Opcode = Op0->getOpcode();
  1856. if (Opcode == ARM::LDRi12) {
  1857. NewOpc = ARM::LDRD;
  1858. } else if (Opcode == ARM::STRi12) {
  1859. NewOpc = ARM::STRD;
  1860. } else if (Opcode == ARM::t2LDRi8 || Opcode == ARM::t2LDRi12) {
  1861. NewOpc = ARM::t2LDRDi8;
  1862. Scale = 4;
  1863. isT2 = true;
  1864. } else if (Opcode == ARM::t2STRi8 || Opcode == ARM::t2STRi12) {
  1865. NewOpc = ARM::t2STRDi8;
  1866. Scale = 4;
  1867. isT2 = true;
  1868. } else {
  1869. return false;
  1870. }
  1871. // Make sure the base address satisfies i64 ld / st alignment requirement.
  1872. // At the moment, we ignore the memoryoperand's value.
  1873. // If we want to use AliasAnalysis, we should check it accordingly.
  1874. if (!Op0->hasOneMemOperand() ||
  1875. (*Op0->memoperands_begin())->isVolatile())
  1876. return false;
  1877. unsigned Align = (*Op0->memoperands_begin())->getAlignment();
  1878. const Function *Func = MF->getFunction();
  1879. unsigned ReqAlign = STI->hasV6Ops()
  1880. ? TD->getABITypeAlignment(Type::getInt64Ty(Func->getContext()))
  1881. : 8; // Pre-v6 need 8-byte align
  1882. if (Align < ReqAlign)
  1883. return false;
  1884. // Then make sure the immediate offset fits.
  1885. int OffImm = getMemoryOpOffset(Op0);
  1886. if (isT2) {
  1887. int Limit = (1 << 8) * Scale;
  1888. if (OffImm >= Limit || (OffImm <= -Limit) || (OffImm & (Scale-1)))
  1889. return false;
  1890. Offset = OffImm;
  1891. } else {
  1892. ARM_AM::AddrOpc AddSub = ARM_AM::add;
  1893. if (OffImm < 0) {
  1894. AddSub = ARM_AM::sub;
  1895. OffImm = - OffImm;
  1896. }
  1897. int Limit = (1 << 8) * Scale;
  1898. if (OffImm >= Limit || (OffImm & (Scale-1)))
  1899. return false;
  1900. Offset = ARM_AM::getAM3Opc(AddSub, OffImm);
  1901. }
  1902. FirstReg = Op0->getOperand(0).getReg();
  1903. SecondReg = Op1->getOperand(0).getReg();
  1904. if (FirstReg == SecondReg)
  1905. return false;
  1906. BaseReg = Op0->getOperand(1).getReg();
  1907. Pred = getInstrPredicate(*Op0, PredReg);
  1908. dl = Op0->getDebugLoc();
  1909. return true;
  1910. }
  1911. bool ARMPreAllocLoadStoreOpt::RescheduleOps(MachineBasicBlock *MBB,
  1912. SmallVectorImpl<MachineInstr *> &Ops,
  1913. unsigned Base, bool isLd,
  1914. DenseMap<MachineInstr*, unsigned> &MI2LocMap) {
  1915. bool RetVal = false;
  1916. // Sort by offset (in reverse order).
  1917. std::sort(Ops.begin(), Ops.end(),
  1918. [](const MachineInstr *LHS, const MachineInstr *RHS) {
  1919. int LOffset = getMemoryOpOffset(LHS);
  1920. int ROffset = getMemoryOpOffset(RHS);
  1921. assert(LHS == RHS || LOffset != ROffset);
  1922. return LOffset > ROffset;
  1923. });
  1924. // The loads / stores of the same base are in order. Scan them from first to
  1925. // last and check for the following:
  1926. // 1. Any def of base.
  1927. // 2. Any gaps.
  1928. while (Ops.size() > 1) {
  1929. unsigned FirstLoc = ~0U;
  1930. unsigned LastLoc = 0;
  1931. MachineInstr *FirstOp = nullptr;
  1932. MachineInstr *LastOp = nullptr;
  1933. int LastOffset = 0;
  1934. unsigned LastOpcode = 0;
  1935. unsigned LastBytes = 0;
  1936. unsigned NumMove = 0;
  1937. for (int i = Ops.size() - 1; i >= 0; --i) {
  1938. MachineInstr *Op = Ops[i];
  1939. unsigned Loc = MI2LocMap[Op];
  1940. if (Loc <= FirstLoc) {
  1941. FirstLoc = Loc;
  1942. FirstOp = Op;
  1943. }
  1944. if (Loc >= LastLoc) {
  1945. LastLoc = Loc;
  1946. LastOp = Op;
  1947. }
  1948. unsigned LSMOpcode
  1949. = getLoadStoreMultipleOpcode(Op->getOpcode(), ARM_AM::ia);
  1950. if (LastOpcode && LSMOpcode != LastOpcode)
  1951. break;
  1952. int Offset = getMemoryOpOffset(Op);
  1953. unsigned Bytes = getLSMultipleTransferSize(Op);
  1954. if (LastBytes) {
  1955. if (Bytes != LastBytes || Offset != (LastOffset + (int)Bytes))
  1956. break;
  1957. }
  1958. LastOffset = Offset;
  1959. LastBytes = Bytes;
  1960. LastOpcode = LSMOpcode;
  1961. if (++NumMove == 8) // FIXME: Tune this limit.
  1962. break;
  1963. }
  1964. if (NumMove <= 1)
  1965. Ops.pop_back();
  1966. else {
  1967. SmallPtrSet<MachineInstr*, 4> MemOps;
  1968. SmallSet<unsigned, 4> MemRegs;
  1969. for (int i = NumMove-1; i >= 0; --i) {
  1970. MemOps.insert(Ops[i]);
  1971. MemRegs.insert(Ops[i]->getOperand(0).getReg());
  1972. }
  1973. // Be conservative, if the instructions are too far apart, don't
  1974. // move them. We want to limit the increase of register pressure.
  1975. bool DoMove = (LastLoc - FirstLoc) <= NumMove*4; // FIXME: Tune this.
  1976. if (DoMove)
  1977. DoMove = IsSafeAndProfitableToMove(isLd, Base, FirstOp, LastOp,
  1978. MemOps, MemRegs, TRI);
  1979. if (!DoMove) {
  1980. for (unsigned i = 0; i != NumMove; ++i)
  1981. Ops.pop_back();
  1982. } else {
  1983. // This is the new location for the loads / stores.
  1984. MachineBasicBlock::iterator InsertPos = isLd ? FirstOp : LastOp;
  1985. while (InsertPos != MBB->end()
  1986. && (MemOps.count(InsertPos) || InsertPos->isDebugValue()))
  1987. ++InsertPos;
  1988. // If we are moving a pair of loads / stores, see if it makes sense
  1989. // to try to allocate a pair of registers that can form register pairs.
  1990. MachineInstr *Op0 = Ops.back();
  1991. MachineInstr *Op1 = Ops[Ops.size()-2];
  1992. unsigned FirstReg = 0, SecondReg = 0;
  1993. unsigned BaseReg = 0, PredReg = 0;
  1994. ARMCC::CondCodes Pred = ARMCC::AL;
  1995. bool isT2 = false;
  1996. unsigned NewOpc = 0;
  1997. int Offset = 0;
  1998. DebugLoc dl;
  1999. if (NumMove == 2 && CanFormLdStDWord(Op0, Op1, dl, NewOpc,
  2000. FirstReg, SecondReg, BaseReg,
  2001. Offset, PredReg, Pred, isT2)) {
  2002. Ops.pop_back();
  2003. Ops.pop_back();
  2004. const MCInstrDesc &MCID = TII->get(NewOpc);
  2005. const TargetRegisterClass *TRC = TII->getRegClass(MCID, 0, TRI, *MF);
  2006. MRI->constrainRegClass(FirstReg, TRC);
  2007. MRI->constrainRegClass(SecondReg, TRC);
  2008. // Form the pair instruction.
  2009. if (isLd) {
  2010. MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)
  2011. .addReg(FirstReg, RegState::Define)
  2012. .addReg(SecondReg, RegState::Define)
  2013. .addReg(BaseReg);
  2014. // FIXME: We're converting from LDRi12 to an insn that still
  2015. // uses addrmode2, so we need an explicit offset reg. It should
  2016. // always by reg0 since we're transforming LDRi12s.
  2017. if (!isT2)
  2018. MIB.addReg(0);
  2019. MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
  2020. MIB.setMemRefs(Op0->mergeMemRefsWith(*Op1));
  2021. DEBUG(dbgs() << "Formed " << *MIB << "\n");
  2022. ++NumLDRDFormed;
  2023. } else {
  2024. MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)
  2025. .addReg(FirstReg)
  2026. .addReg(SecondReg)
  2027. .addReg(BaseReg);
  2028. // FIXME: We're converting from LDRi12 to an insn that still
  2029. // uses addrmode2, so we need an explicit offset reg. It should
  2030. // always by reg0 since we're transforming STRi12s.
  2031. if (!isT2)
  2032. MIB.addReg(0);
  2033. MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
  2034. MIB.setMemRefs(Op0->mergeMemRefsWith(*Op1));
  2035. DEBUG(dbgs() << "Formed " << *MIB << "\n");
  2036. ++NumSTRDFormed;
  2037. }
  2038. MBB->erase(Op0);
  2039. MBB->erase(Op1);
  2040. if (!isT2) {
  2041. // Add register allocation hints to form register pairs.
  2042. MRI->setRegAllocationHint(FirstReg, ARMRI::RegPairEven, SecondReg);
  2043. MRI->setRegAllocationHint(SecondReg, ARMRI::RegPairOdd, FirstReg);
  2044. }
  2045. } else {
  2046. for (unsigned i = 0; i != NumMove; ++i) {
  2047. MachineInstr *Op = Ops.back();
  2048. Ops.pop_back();
  2049. MBB->splice(InsertPos, MBB, Op);
  2050. }
  2051. }
  2052. NumLdStMoved += NumMove;
  2053. RetVal = true;
  2054. }
  2055. }
  2056. }
  2057. return RetVal;
  2058. }
  2059. bool
  2060. ARMPreAllocLoadStoreOpt::RescheduleLoadStoreInstrs(MachineBasicBlock *MBB) {
  2061. bool RetVal = false;
  2062. DenseMap<MachineInstr*, unsigned> MI2LocMap;
  2063. DenseMap<unsigned, SmallVector<MachineInstr*, 4> > Base2LdsMap;
  2064. DenseMap<unsigned, SmallVector<MachineInstr*, 4> > Base2StsMap;
  2065. SmallVector<unsigned, 4> LdBases;
  2066. SmallVector<unsigned, 4> StBases;
  2067. unsigned Loc = 0;
  2068. MachineBasicBlock::iterator MBBI = MBB->begin();
  2069. MachineBasicBlock::iterator E = MBB->end();
  2070. while (MBBI != E) {
  2071. for (; MBBI != E; ++MBBI) {
  2072. MachineInstr *MI = MBBI;
  2073. if (MI->isCall() || MI->isTerminator()) {
  2074. // Stop at barriers.
  2075. ++MBBI;
  2076. break;
  2077. }
  2078. if (!MI->isDebugValue())
  2079. MI2LocMap[MI] = ++Loc;
  2080. if (!isMemoryOp(*MI))
  2081. continue;
  2082. unsigned PredReg = 0;
  2083. if (getInstrPredicate(*MI, PredReg) != ARMCC::AL)
  2084. continue;
  2085. int Opc = MI->getOpcode();
  2086. bool isLd = isLoadSingle(Opc);
  2087. unsigned Base = MI->getOperand(1).getReg();
  2088. int Offset = getMemoryOpOffset(MI);
  2089. bool StopHere = false;
  2090. if (isLd) {
  2091. DenseMap<unsigned, SmallVector<MachineInstr*, 4> >::iterator BI =
  2092. Base2LdsMap.find(Base);
  2093. if (BI != Base2LdsMap.end()) {
  2094. for (unsigned i = 0, e = BI->second.size(); i != e; ++i) {
  2095. if (Offset == getMemoryOpOffset(BI->second[i])) {
  2096. StopHere = true;
  2097. break;
  2098. }
  2099. }
  2100. if (!StopHere)
  2101. BI->second.push_back(MI);
  2102. } else {
  2103. Base2LdsMap[Base].push_back(MI);
  2104. LdBases.push_back(Base);
  2105. }
  2106. } else {
  2107. DenseMap<unsigned, SmallVector<MachineInstr*, 4> >::iterator BI =
  2108. Base2StsMap.find(Base);
  2109. if (BI != Base2StsMap.end()) {
  2110. for (unsigned i = 0, e = BI->second.size(); i != e; ++i) {
  2111. if (Offset == getMemoryOpOffset(BI->second[i])) {
  2112. StopHere = true;
  2113. break;
  2114. }
  2115. }
  2116. if (!StopHere)
  2117. BI->second.push_back(MI);
  2118. } else {
  2119. Base2StsMap[Base].push_back(MI);
  2120. StBases.push_back(Base);
  2121. }
  2122. }
  2123. if (StopHere) {
  2124. // Found a duplicate (a base+offset combination that's seen earlier).
  2125. // Backtrack.
  2126. --Loc;
  2127. break;
  2128. }
  2129. }
  2130. // Re-schedule loads.
  2131. for (unsigned i = 0, e = LdBases.size(); i != e; ++i) {
  2132. unsigned Base = LdBases[i];
  2133. SmallVectorImpl<MachineInstr *> &Lds = Base2LdsMap[Base];
  2134. if (Lds.size() > 1)
  2135. RetVal |= RescheduleOps(MBB, Lds, Base, true, MI2LocMap);
  2136. }
  2137. // Re-schedule stores.
  2138. for (unsigned i = 0, e = StBases.size(); i != e; ++i) {
  2139. unsigned Base = StBases[i];
  2140. SmallVectorImpl<MachineInstr *> &Sts = Base2StsMap[Base];
  2141. if (Sts.size() > 1)
  2142. RetVal |= RescheduleOps(MBB, Sts, Base, false, MI2LocMap);
  2143. }
  2144. if (MBBI != E) {
  2145. Base2LdsMap.clear();
  2146. Base2StsMap.clear();
  2147. LdBases.clear();
  2148. StBases.clear();
  2149. }
  2150. }
  2151. return RetVal;
  2152. }
  2153. /// Returns an instance of the load / store optimization pass.
  2154. FunctionPass *llvm::createARMLoadStoreOptimizationPass(bool PreAlloc) {
  2155. if (PreAlloc)
  2156. return new ARMPreAllocLoadStoreOpt();
  2157. return new ARMLoadStoreOpt();
  2158. }