SILoadStoreOptimizer.cpp 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637
  1. //===- SILoadStoreOptimizer.cpp -------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This pass tries to fuse DS instructions with close by immediate offsets.
  10. // This will fuse operations such as
  11. // ds_read_b32 v0, v2 offset:16
  12. // ds_read_b32 v1, v2 offset:32
  13. // ==>
  14. // ds_read2_b32 v[0:1], v2, offset0:4 offset1:8
  15. //
  16. // The same is done for certain SMEM and VMEM opcodes, e.g.:
  17. // s_buffer_load_dword s4, s[0:3], 4
  18. // s_buffer_load_dword s5, s[0:3], 8
  19. // ==>
  20. // s_buffer_load_dwordx2 s[4:5], s[0:3], 4
  21. //
  22. // This pass also tries to promote constant offset to the immediate by
  23. // adjusting the base. It tries to use a base from the nearby instructions that
  24. // allows it to have a 13bit constant offset and then promotes the 13bit offset
  25. // to the immediate.
  26. // E.g.
  27. // s_movk_i32 s0, 0x1800
  28. // v_add_co_u32_e32 v0, vcc, s0, v2
  29. // v_addc_co_u32_e32 v1, vcc, 0, v6, vcc
  30. //
  31. // s_movk_i32 s0, 0x1000
  32. // v_add_co_u32_e32 v5, vcc, s0, v2
  33. // v_addc_co_u32_e32 v6, vcc, 0, v6, vcc
  34. // global_load_dwordx2 v[5:6], v[5:6], off
  35. // global_load_dwordx2 v[0:1], v[0:1], off
  36. // =>
  37. // s_movk_i32 s0, 0x1000
  38. // v_add_co_u32_e32 v5, vcc, s0, v2
  39. // v_addc_co_u32_e32 v6, vcc, 0, v6, vcc
  40. // global_load_dwordx2 v[5:6], v[5:6], off
  41. // global_load_dwordx2 v[0:1], v[5:6], off offset:2048
  42. //
  43. // Future improvements:
  44. //
  45. // - This currently relies on the scheduler to place loads and stores next to
  46. // each other, and then only merges adjacent pairs of instructions. It would
  47. // be good to be more flexible with interleaved instructions, and possibly run
  48. // before scheduling. It currently missing stores of constants because loading
  49. // the constant into the data register is placed between the stores, although
  50. // this is arguably a scheduling problem.
  51. //
  52. // - Live interval recomputing seems inefficient. This currently only matches
  53. // one pair, and recomputes live intervals and moves on to the next pair. It
  54. // would be better to compute a list of all merges that need to occur.
  55. //
  56. // - With a list of instructions to process, we can also merge more. If a
  57. // cluster of loads have offsets that are too large to fit in the 8-bit
  58. // offsets, but are close enough to fit in the 8 bits, we can add to the base
  59. // pointer and use the new reduced offsets.
  60. //
  61. //===----------------------------------------------------------------------===//
  62. #include "AMDGPU.h"
  63. #include "AMDGPUSubtarget.h"
  64. #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
  65. #include "SIInstrInfo.h"
  66. #include "SIRegisterInfo.h"
  67. #include "Utils/AMDGPUBaseInfo.h"
  68. #include "llvm/ADT/ArrayRef.h"
  69. #include "llvm/ADT/SmallVector.h"
  70. #include "llvm/ADT/StringRef.h"
  71. #include "llvm/Analysis/AliasAnalysis.h"
  72. #include "llvm/CodeGen/MachineBasicBlock.h"
  73. #include "llvm/CodeGen/MachineFunction.h"
  74. #include "llvm/CodeGen/MachineFunctionPass.h"
  75. #include "llvm/CodeGen/MachineInstr.h"
  76. #include "llvm/CodeGen/MachineInstrBuilder.h"
  77. #include "llvm/CodeGen/MachineOperand.h"
  78. #include "llvm/CodeGen/MachineRegisterInfo.h"
  79. #include "llvm/IR/DebugLoc.h"
  80. #include "llvm/Pass.h"
  81. #include "llvm/Support/Debug.h"
  82. #include "llvm/Support/MathExtras.h"
  83. #include "llvm/Support/raw_ostream.h"
  84. #include <algorithm>
  85. #include <cassert>
  86. #include <cstdlib>
  87. #include <iterator>
  88. #include <utility>
  89. using namespace llvm;
  90. #define DEBUG_TYPE "si-load-store-opt"
  91. namespace {
  92. enum InstClassEnum {
  93. UNKNOWN,
  94. DS_READ,
  95. DS_WRITE,
  96. S_BUFFER_LOAD_IMM,
  97. BUFFER_LOAD_OFFEN = AMDGPU::BUFFER_LOAD_DWORD_OFFEN,
  98. BUFFER_LOAD_OFFSET = AMDGPU::BUFFER_LOAD_DWORD_OFFSET,
  99. BUFFER_STORE_OFFEN = AMDGPU::BUFFER_STORE_DWORD_OFFEN,
  100. BUFFER_STORE_OFFSET = AMDGPU::BUFFER_STORE_DWORD_OFFSET,
  101. BUFFER_LOAD_OFFEN_exact = AMDGPU::BUFFER_LOAD_DWORD_OFFEN_exact,
  102. BUFFER_LOAD_OFFSET_exact = AMDGPU::BUFFER_LOAD_DWORD_OFFSET_exact,
  103. BUFFER_STORE_OFFEN_exact = AMDGPU::BUFFER_STORE_DWORD_OFFEN_exact,
  104. BUFFER_STORE_OFFSET_exact = AMDGPU::BUFFER_STORE_DWORD_OFFSET_exact,
  105. };
  106. enum RegisterEnum {
  107. SBASE = 0x1,
  108. SRSRC = 0x2,
  109. SOFFSET = 0x4,
  110. VADDR = 0x8,
  111. ADDR = 0x10,
  112. };
  113. class SILoadStoreOptimizer : public MachineFunctionPass {
  114. struct CombineInfo {
  115. MachineBasicBlock::iterator I;
  116. MachineBasicBlock::iterator Paired;
  117. unsigned EltSize;
  118. unsigned Offset0;
  119. unsigned Offset1;
  120. unsigned Width0;
  121. unsigned Width1;
  122. unsigned BaseOff;
  123. InstClassEnum InstClass;
  124. bool GLC0;
  125. bool GLC1;
  126. bool SLC0;
  127. bool SLC1;
  128. bool DLC0;
  129. bool DLC1;
  130. bool UseST64;
  131. SmallVector<MachineInstr *, 8> InstsToMove;
  132. int AddrIdx[5];
  133. const MachineOperand *AddrReg[5];
  134. unsigned NumAddresses;
  135. bool hasSameBaseAddress(const MachineInstr &MI) {
  136. for (unsigned i = 0; i < NumAddresses; i++) {
  137. const MachineOperand &AddrRegNext = MI.getOperand(AddrIdx[i]);
  138. if (AddrReg[i]->isImm() || AddrRegNext.isImm()) {
  139. if (AddrReg[i]->isImm() != AddrRegNext.isImm() ||
  140. AddrReg[i]->getImm() != AddrRegNext.getImm()) {
  141. return false;
  142. }
  143. continue;
  144. }
  145. // Check same base pointer. Be careful of subregisters, which can occur
  146. // with vectors of pointers.
  147. if (AddrReg[i]->getReg() != AddrRegNext.getReg() ||
  148. AddrReg[i]->getSubReg() != AddrRegNext.getSubReg()) {
  149. return false;
  150. }
  151. }
  152. return true;
  153. }
  154. void setMI(MachineBasicBlock::iterator MI, const SIInstrInfo &TII,
  155. const GCNSubtarget &STM);
  156. void setPaired(MachineBasicBlock::iterator MI, const SIInstrInfo &TII);
  157. };
  158. struct BaseRegisters {
  159. unsigned LoReg = 0;
  160. unsigned HiReg = 0;
  161. unsigned LoSubReg = 0;
  162. unsigned HiSubReg = 0;
  163. };
  164. struct MemAddress {
  165. BaseRegisters Base;
  166. int64_t Offset = 0;
  167. };
  168. using MemInfoMap = DenseMap<MachineInstr *, MemAddress>;
  169. private:
  170. const GCNSubtarget *STM = nullptr;
  171. const SIInstrInfo *TII = nullptr;
  172. const SIRegisterInfo *TRI = nullptr;
  173. MachineRegisterInfo *MRI = nullptr;
  174. AliasAnalysis *AA = nullptr;
  175. bool OptimizeAgain;
  176. static bool offsetsCanBeCombined(CombineInfo &CI);
  177. static bool widthsFit(const GCNSubtarget &STM, const CombineInfo &CI);
  178. static unsigned getNewOpcode(const CombineInfo &CI);
  179. static std::pair<unsigned, unsigned> getSubRegIdxs(const CombineInfo &CI);
  180. const TargetRegisterClass *getTargetRegisterClass(const CombineInfo &CI);
  181. bool findMatchingInst(CombineInfo &CI);
  182. unsigned read2Opcode(unsigned EltSize) const;
  183. unsigned read2ST64Opcode(unsigned EltSize) const;
  184. MachineBasicBlock::iterator mergeRead2Pair(CombineInfo &CI);
  185. unsigned write2Opcode(unsigned EltSize) const;
  186. unsigned write2ST64Opcode(unsigned EltSize) const;
  187. MachineBasicBlock::iterator mergeWrite2Pair(CombineInfo &CI);
  188. MachineBasicBlock::iterator mergeSBufferLoadImmPair(CombineInfo &CI);
  189. MachineBasicBlock::iterator mergeBufferLoadPair(CombineInfo &CI);
  190. MachineBasicBlock::iterator mergeBufferStorePair(CombineInfo &CI);
  191. void updateBaseAndOffset(MachineInstr &I, unsigned NewBase,
  192. int32_t NewOffset) const;
  193. unsigned computeBase(MachineInstr &MI, const MemAddress &Addr) const;
  194. MachineOperand createRegOrImm(int32_t Val, MachineInstr &MI) const;
  195. Optional<int32_t> extractConstOffset(const MachineOperand &Op) const;
  196. void processBaseWithConstOffset(const MachineOperand &Base, MemAddress &Addr) const;
  197. /// Promotes constant offset to the immediate by adjusting the base. It
  198. /// tries to use a base from the nearby instructions that allows it to have
  199. /// a 13bit constant offset which gets promoted to the immediate.
  200. bool promoteConstantOffsetToImm(MachineInstr &CI,
  201. MemInfoMap &Visited,
  202. SmallPtrSet<MachineInstr *, 4> &Promoted) const;
  203. public:
  204. static char ID;
  205. SILoadStoreOptimizer() : MachineFunctionPass(ID) {
  206. initializeSILoadStoreOptimizerPass(*PassRegistry::getPassRegistry());
  207. }
  208. bool optimizeBlock(MachineBasicBlock &MBB);
  209. bool runOnMachineFunction(MachineFunction &MF) override;
  210. StringRef getPassName() const override { return "SI Load Store Optimizer"; }
  211. void getAnalysisUsage(AnalysisUsage &AU) const override {
  212. AU.setPreservesCFG();
  213. AU.addRequired<AAResultsWrapperPass>();
  214. MachineFunctionPass::getAnalysisUsage(AU);
  215. }
  216. };
  217. static unsigned getOpcodeWidth(const MachineInstr &MI, const SIInstrInfo &TII) {
  218. const unsigned Opc = MI.getOpcode();
  219. if (TII.isMUBUF(Opc)) {
  220. // FIXME: Handle d16 correctly
  221. return AMDGPU::getMUBUFElements(Opc);
  222. }
  223. switch (Opc) {
  224. case AMDGPU::S_BUFFER_LOAD_DWORD_IMM:
  225. return 1;
  226. case AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM:
  227. return 2;
  228. case AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM:
  229. return 4;
  230. default:
  231. return 0;
  232. }
  233. }
  234. static InstClassEnum getInstClass(unsigned Opc, const SIInstrInfo &TII) {
  235. if (TII.isMUBUF(Opc)) {
  236. const int baseOpcode = AMDGPU::getMUBUFBaseOpcode(Opc);
  237. // If we couldn't identify the opcode, bail out.
  238. if (baseOpcode == -1) {
  239. return UNKNOWN;
  240. }
  241. switch (baseOpcode) {
  242. case AMDGPU::BUFFER_LOAD_DWORD_OFFEN:
  243. return BUFFER_LOAD_OFFEN;
  244. case AMDGPU::BUFFER_LOAD_DWORD_OFFSET:
  245. return BUFFER_LOAD_OFFSET;
  246. case AMDGPU::BUFFER_STORE_DWORD_OFFEN:
  247. return BUFFER_STORE_OFFEN;
  248. case AMDGPU::BUFFER_STORE_DWORD_OFFSET:
  249. return BUFFER_STORE_OFFSET;
  250. case AMDGPU::BUFFER_LOAD_DWORD_OFFEN_exact:
  251. return BUFFER_LOAD_OFFEN_exact;
  252. case AMDGPU::BUFFER_LOAD_DWORD_OFFSET_exact:
  253. return BUFFER_LOAD_OFFSET_exact;
  254. case AMDGPU::BUFFER_STORE_DWORD_OFFEN_exact:
  255. return BUFFER_STORE_OFFEN_exact;
  256. case AMDGPU::BUFFER_STORE_DWORD_OFFSET_exact:
  257. return BUFFER_STORE_OFFSET_exact;
  258. default:
  259. return UNKNOWN;
  260. }
  261. }
  262. switch (Opc) {
  263. case AMDGPU::S_BUFFER_LOAD_DWORD_IMM:
  264. case AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM:
  265. case AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM:
  266. return S_BUFFER_LOAD_IMM;
  267. case AMDGPU::DS_READ_B32:
  268. case AMDGPU::DS_READ_B64:
  269. case AMDGPU::DS_READ_B32_gfx9:
  270. case AMDGPU::DS_READ_B64_gfx9:
  271. return DS_READ;
  272. case AMDGPU::DS_WRITE_B32:
  273. case AMDGPU::DS_WRITE_B64:
  274. case AMDGPU::DS_WRITE_B32_gfx9:
  275. case AMDGPU::DS_WRITE_B64_gfx9:
  276. return DS_WRITE;
  277. default:
  278. return UNKNOWN;
  279. }
  280. }
  281. static unsigned getRegs(unsigned Opc, const SIInstrInfo &TII) {
  282. if (TII.isMUBUF(Opc)) {
  283. unsigned result = 0;
  284. if (AMDGPU::getMUBUFHasVAddr(Opc)) {
  285. result |= VADDR;
  286. }
  287. if (AMDGPU::getMUBUFHasSrsrc(Opc)) {
  288. result |= SRSRC;
  289. }
  290. if (AMDGPU::getMUBUFHasSoffset(Opc)) {
  291. result |= SOFFSET;
  292. }
  293. return result;
  294. }
  295. switch (Opc) {
  296. default:
  297. return 0;
  298. case AMDGPU::S_BUFFER_LOAD_DWORD_IMM:
  299. case AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM:
  300. case AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM:
  301. return SBASE;
  302. case AMDGPU::DS_READ_B32:
  303. case AMDGPU::DS_READ_B64:
  304. case AMDGPU::DS_READ_B32_gfx9:
  305. case AMDGPU::DS_READ_B64_gfx9:
  306. case AMDGPU::DS_WRITE_B32:
  307. case AMDGPU::DS_WRITE_B64:
  308. case AMDGPU::DS_WRITE_B32_gfx9:
  309. case AMDGPU::DS_WRITE_B64_gfx9:
  310. return ADDR;
  311. }
  312. }
  313. void SILoadStoreOptimizer::CombineInfo::setMI(MachineBasicBlock::iterator MI,
  314. const SIInstrInfo &TII,
  315. const GCNSubtarget &STM) {
  316. I = MI;
  317. unsigned Opc = MI->getOpcode();
  318. InstClass = getInstClass(Opc, TII);
  319. if (InstClass == UNKNOWN)
  320. return;
  321. switch (InstClass) {
  322. case DS_READ:
  323. EltSize =
  324. (Opc == AMDGPU::DS_READ_B64 || Opc == AMDGPU::DS_READ_B64_gfx9) ? 8
  325. : 4;
  326. break;
  327. case DS_WRITE:
  328. EltSize =
  329. (Opc == AMDGPU::DS_WRITE_B64 || Opc == AMDGPU::DS_WRITE_B64_gfx9) ? 8
  330. : 4;
  331. break;
  332. case S_BUFFER_LOAD_IMM:
  333. EltSize = AMDGPU::getSMRDEncodedOffset(STM, 4);
  334. break;
  335. default:
  336. EltSize = 4;
  337. break;
  338. }
  339. int OffsetIdx =
  340. AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::offset);
  341. Offset0 = I->getOperand(OffsetIdx).getImm();
  342. Width0 = getOpcodeWidth(*I, TII);
  343. if ((InstClass == DS_READ) || (InstClass == DS_WRITE)) {
  344. Offset0 &= 0xffff;
  345. } else {
  346. GLC0 = TII.getNamedOperand(*I, AMDGPU::OpName::glc)->getImm();
  347. if (InstClass != S_BUFFER_LOAD_IMM) {
  348. SLC0 = TII.getNamedOperand(*I, AMDGPU::OpName::slc)->getImm();
  349. }
  350. DLC0 = TII.getNamedOperand(*I, AMDGPU::OpName::dlc)->getImm();
  351. }
  352. unsigned AddrOpName[5] = {0};
  353. NumAddresses = 0;
  354. const unsigned Regs = getRegs(I->getOpcode(), TII);
  355. if (Regs & ADDR) {
  356. AddrOpName[NumAddresses++] = AMDGPU::OpName::addr;
  357. }
  358. if (Regs & SBASE) {
  359. AddrOpName[NumAddresses++] = AMDGPU::OpName::sbase;
  360. }
  361. if (Regs & SRSRC) {
  362. AddrOpName[NumAddresses++] = AMDGPU::OpName::srsrc;
  363. }
  364. if (Regs & SOFFSET) {
  365. AddrOpName[NumAddresses++] = AMDGPU::OpName::soffset;
  366. }
  367. if (Regs & VADDR) {
  368. AddrOpName[NumAddresses++] = AMDGPU::OpName::vaddr;
  369. }
  370. for (unsigned i = 0; i < NumAddresses; i++) {
  371. AddrIdx[i] = AMDGPU::getNamedOperandIdx(I->getOpcode(), AddrOpName[i]);
  372. AddrReg[i] = &I->getOperand(AddrIdx[i]);
  373. }
  374. }
  375. void SILoadStoreOptimizer::CombineInfo::setPaired(MachineBasicBlock::iterator MI,
  376. const SIInstrInfo &TII) {
  377. Paired = MI;
  378. assert(InstClass == getInstClass(Paired->getOpcode(), TII));
  379. int OffsetIdx =
  380. AMDGPU::getNamedOperandIdx(I->getOpcode(), AMDGPU::OpName::offset);
  381. Offset1 = Paired->getOperand(OffsetIdx).getImm();
  382. Width1 = getOpcodeWidth(*Paired, TII);
  383. if ((InstClass == DS_READ) || (InstClass == DS_WRITE)) {
  384. Offset1 &= 0xffff;
  385. } else {
  386. GLC1 = TII.getNamedOperand(*Paired, AMDGPU::OpName::glc)->getImm();
  387. if (InstClass != S_BUFFER_LOAD_IMM) {
  388. SLC1 = TII.getNamedOperand(*Paired, AMDGPU::OpName::slc)->getImm();
  389. }
  390. DLC1 = TII.getNamedOperand(*Paired, AMDGPU::OpName::dlc)->getImm();
  391. }
  392. }
  393. } // end anonymous namespace.
  394. INITIALIZE_PASS_BEGIN(SILoadStoreOptimizer, DEBUG_TYPE,
  395. "SI Load Store Optimizer", false, false)
  396. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  397. INITIALIZE_PASS_END(SILoadStoreOptimizer, DEBUG_TYPE, "SI Load Store Optimizer",
  398. false, false)
  399. char SILoadStoreOptimizer::ID = 0;
  400. char &llvm::SILoadStoreOptimizerID = SILoadStoreOptimizer::ID;
  401. FunctionPass *llvm::createSILoadStoreOptimizerPass() {
  402. return new SILoadStoreOptimizer();
  403. }
  404. static void moveInstsAfter(MachineBasicBlock::iterator I,
  405. ArrayRef<MachineInstr *> InstsToMove) {
  406. MachineBasicBlock *MBB = I->getParent();
  407. ++I;
  408. for (MachineInstr *MI : InstsToMove) {
  409. MI->removeFromParent();
  410. MBB->insert(I, MI);
  411. }
  412. }
  413. static void addDefsUsesToList(const MachineInstr &MI,
  414. DenseSet<unsigned> &RegDefs,
  415. DenseSet<unsigned> &PhysRegUses) {
  416. for (const MachineOperand &Op : MI.operands()) {
  417. if (Op.isReg()) {
  418. if (Op.isDef())
  419. RegDefs.insert(Op.getReg());
  420. else if (Op.readsReg() && Register::isPhysicalRegister(Op.getReg()))
  421. PhysRegUses.insert(Op.getReg());
  422. }
  423. }
  424. }
  425. static bool memAccessesCanBeReordered(MachineBasicBlock::iterator A,
  426. MachineBasicBlock::iterator B,
  427. AliasAnalysis *AA) {
  428. // RAW or WAR - cannot reorder
  429. // WAW - cannot reorder
  430. // RAR - safe to reorder
  431. return !(A->mayStore() || B->mayStore()) || !A->mayAlias(AA, *B, true);
  432. }
  433. // Add MI and its defs to the lists if MI reads one of the defs that are
  434. // already in the list. Returns true in that case.
  435. static bool addToListsIfDependent(MachineInstr &MI, DenseSet<unsigned> &RegDefs,
  436. DenseSet<unsigned> &PhysRegUses,
  437. SmallVectorImpl<MachineInstr *> &Insts) {
  438. for (MachineOperand &Use : MI.operands()) {
  439. // If one of the defs is read, then there is a use of Def between I and the
  440. // instruction that I will potentially be merged with. We will need to move
  441. // this instruction after the merged instructions.
  442. //
  443. // Similarly, if there is a def which is read by an instruction that is to
  444. // be moved for merging, then we need to move the def-instruction as well.
  445. // This can only happen for physical registers such as M0; virtual
  446. // registers are in SSA form.
  447. if (Use.isReg() &&
  448. ((Use.readsReg() && RegDefs.count(Use.getReg())) ||
  449. (Use.isDef() && RegDefs.count(Use.getReg())) ||
  450. (Use.isDef() && Register::isPhysicalRegister(Use.getReg()) &&
  451. PhysRegUses.count(Use.getReg())))) {
  452. Insts.push_back(&MI);
  453. addDefsUsesToList(MI, RegDefs, PhysRegUses);
  454. return true;
  455. }
  456. }
  457. return false;
  458. }
  459. static bool canMoveInstsAcrossMemOp(MachineInstr &MemOp,
  460. ArrayRef<MachineInstr *> InstsToMove,
  461. AliasAnalysis *AA) {
  462. assert(MemOp.mayLoadOrStore());
  463. for (MachineInstr *InstToMove : InstsToMove) {
  464. if (!InstToMove->mayLoadOrStore())
  465. continue;
  466. if (!memAccessesCanBeReordered(MemOp, *InstToMove, AA))
  467. return false;
  468. }
  469. return true;
  470. }
  471. // This function assumes that \p A and \p B have are identical except for
  472. // size and offset, and they referecne adjacent memory.
  473. static MachineMemOperand *combineKnownAdjacentMMOs(MachineFunction &MF,
  474. const MachineMemOperand *A,
  475. const MachineMemOperand *B) {
  476. unsigned MinOffset = std::min(A->getOffset(), B->getOffset());
  477. unsigned Size = A->getSize() + B->getSize();
  478. // This function adds the offset parameter to the existing offset for A,
  479. // so we pass 0 here as the offset and then manually set it to the correct
  480. // value after the call.
  481. MachineMemOperand *MMO = MF.getMachineMemOperand(A, 0, Size);
  482. MMO->setOffset(MinOffset);
  483. return MMO;
  484. }
  485. bool SILoadStoreOptimizer::offsetsCanBeCombined(CombineInfo &CI) {
  486. // XXX - Would the same offset be OK? Is there any reason this would happen or
  487. // be useful?
  488. if (CI.Offset0 == CI.Offset1)
  489. return false;
  490. // This won't be valid if the offset isn't aligned.
  491. if ((CI.Offset0 % CI.EltSize != 0) || (CI.Offset1 % CI.EltSize != 0))
  492. return false;
  493. unsigned EltOffset0 = CI.Offset0 / CI.EltSize;
  494. unsigned EltOffset1 = CI.Offset1 / CI.EltSize;
  495. CI.UseST64 = false;
  496. CI.BaseOff = 0;
  497. // Handle SMEM and VMEM instructions.
  498. if ((CI.InstClass != DS_READ) && (CI.InstClass != DS_WRITE)) {
  499. return (EltOffset0 + CI.Width0 == EltOffset1 ||
  500. EltOffset1 + CI.Width1 == EltOffset0) &&
  501. CI.GLC0 == CI.GLC1 && CI.DLC0 == CI.DLC1 &&
  502. (CI.InstClass == S_BUFFER_LOAD_IMM || CI.SLC0 == CI.SLC1);
  503. }
  504. // If the offset in elements doesn't fit in 8-bits, we might be able to use
  505. // the stride 64 versions.
  506. if ((EltOffset0 % 64 == 0) && (EltOffset1 % 64) == 0 &&
  507. isUInt<8>(EltOffset0 / 64) && isUInt<8>(EltOffset1 / 64)) {
  508. CI.Offset0 = EltOffset0 / 64;
  509. CI.Offset1 = EltOffset1 / 64;
  510. CI.UseST64 = true;
  511. return true;
  512. }
  513. // Check if the new offsets fit in the reduced 8-bit range.
  514. if (isUInt<8>(EltOffset0) && isUInt<8>(EltOffset1)) {
  515. CI.Offset0 = EltOffset0;
  516. CI.Offset1 = EltOffset1;
  517. return true;
  518. }
  519. // Try to shift base address to decrease offsets.
  520. unsigned OffsetDiff = std::abs((int)EltOffset1 - (int)EltOffset0);
  521. CI.BaseOff = std::min(CI.Offset0, CI.Offset1);
  522. if ((OffsetDiff % 64 == 0) && isUInt<8>(OffsetDiff / 64)) {
  523. CI.Offset0 = (EltOffset0 - CI.BaseOff / CI.EltSize) / 64;
  524. CI.Offset1 = (EltOffset1 - CI.BaseOff / CI.EltSize) / 64;
  525. CI.UseST64 = true;
  526. return true;
  527. }
  528. if (isUInt<8>(OffsetDiff)) {
  529. CI.Offset0 = EltOffset0 - CI.BaseOff / CI.EltSize;
  530. CI.Offset1 = EltOffset1 - CI.BaseOff / CI.EltSize;
  531. return true;
  532. }
  533. return false;
  534. }
  535. bool SILoadStoreOptimizer::widthsFit(const GCNSubtarget &STM,
  536. const CombineInfo &CI) {
  537. const unsigned Width = (CI.Width0 + CI.Width1);
  538. switch (CI.InstClass) {
  539. default:
  540. return (Width <= 4) && (STM.hasDwordx3LoadStores() || (Width != 3));
  541. case S_BUFFER_LOAD_IMM:
  542. switch (Width) {
  543. default:
  544. return false;
  545. case 2:
  546. case 4:
  547. return true;
  548. }
  549. }
  550. }
  551. bool SILoadStoreOptimizer::findMatchingInst(CombineInfo &CI) {
  552. MachineBasicBlock *MBB = CI.I->getParent();
  553. MachineBasicBlock::iterator E = MBB->end();
  554. MachineBasicBlock::iterator MBBI = CI.I;
  555. const unsigned Opc = CI.I->getOpcode();
  556. const InstClassEnum InstClass = getInstClass(Opc, *TII);
  557. if (InstClass == UNKNOWN) {
  558. return false;
  559. }
  560. // Do not merge VMEM buffer instructions with "swizzled" bit set.
  561. int Swizzled =
  562. AMDGPU::getNamedOperandIdx(CI.I->getOpcode(), AMDGPU::OpName::swz);
  563. if (Swizzled != -1 && CI.I->getOperand(Swizzled).getImm())
  564. return false;
  565. for (unsigned i = 0; i < CI.NumAddresses; i++) {
  566. // We only ever merge operations with the same base address register, so
  567. // don't bother scanning forward if there are no other uses.
  568. if (CI.AddrReg[i]->isReg() &&
  569. (Register::isPhysicalRegister(CI.AddrReg[i]->getReg()) ||
  570. MRI->hasOneNonDBGUse(CI.AddrReg[i]->getReg())))
  571. return false;
  572. }
  573. ++MBBI;
  574. DenseSet<unsigned> RegDefsToMove;
  575. DenseSet<unsigned> PhysRegUsesToMove;
  576. addDefsUsesToList(*CI.I, RegDefsToMove, PhysRegUsesToMove);
  577. for (; MBBI != E; ++MBBI) {
  578. const bool IsDS = (InstClass == DS_READ) || (InstClass == DS_WRITE);
  579. if ((getInstClass(MBBI->getOpcode(), *TII) != InstClass) ||
  580. (IsDS && (MBBI->getOpcode() != Opc))) {
  581. // This is not a matching DS instruction, but we can keep looking as
  582. // long as one of these conditions are met:
  583. // 1. It is safe to move I down past MBBI.
  584. // 2. It is safe to move MBBI down past the instruction that I will
  585. // be merged into.
  586. if (MBBI->hasUnmodeledSideEffects()) {
  587. // We can't re-order this instruction with respect to other memory
  588. // operations, so we fail both conditions mentioned above.
  589. return false;
  590. }
  591. if (MBBI->mayLoadOrStore() &&
  592. (!memAccessesCanBeReordered(*CI.I, *MBBI, AA) ||
  593. !canMoveInstsAcrossMemOp(*MBBI, CI.InstsToMove, AA))) {
  594. // We fail condition #1, but we may still be able to satisfy condition
  595. // #2. Add this instruction to the move list and then we will check
  596. // if condition #2 holds once we have selected the matching instruction.
  597. CI.InstsToMove.push_back(&*MBBI);
  598. addDefsUsesToList(*MBBI, RegDefsToMove, PhysRegUsesToMove);
  599. continue;
  600. }
  601. // When we match I with another DS instruction we will be moving I down
  602. // to the location of the matched instruction any uses of I will need to
  603. // be moved down as well.
  604. addToListsIfDependent(*MBBI, RegDefsToMove, PhysRegUsesToMove,
  605. CI.InstsToMove);
  606. continue;
  607. }
  608. // Don't merge volatiles.
  609. if (MBBI->hasOrderedMemoryRef())
  610. return false;
  611. // Handle a case like
  612. // DS_WRITE_B32 addr, v, idx0
  613. // w = DS_READ_B32 addr, idx0
  614. // DS_WRITE_B32 addr, f(w), idx1
  615. // where the DS_READ_B32 ends up in InstsToMove and therefore prevents
  616. // merging of the two writes.
  617. if (addToListsIfDependent(*MBBI, RegDefsToMove, PhysRegUsesToMove,
  618. CI.InstsToMove))
  619. continue;
  620. bool Match = CI.hasSameBaseAddress(*MBBI);
  621. if (Match) {
  622. CI.setPaired(MBBI, *TII);
  623. // Check both offsets fit in the reduced range.
  624. // We also need to go through the list of instructions that we plan to
  625. // move and make sure they are all safe to move down past the merged
  626. // instruction.
  627. if (widthsFit(*STM, CI) && offsetsCanBeCombined(CI))
  628. if (canMoveInstsAcrossMemOp(*MBBI, CI.InstsToMove, AA))
  629. return true;
  630. }
  631. // We've found a load/store that we couldn't merge for some reason.
  632. // We could potentially keep looking, but we'd need to make sure that
  633. // it was safe to move I and also all the instruction in InstsToMove
  634. // down past this instruction.
  635. // check if we can move I across MBBI and if we can move all I's users
  636. if (!memAccessesCanBeReordered(*CI.I, *MBBI, AA) ||
  637. !canMoveInstsAcrossMemOp(*MBBI, CI.InstsToMove, AA))
  638. break;
  639. }
  640. return false;
  641. }
  642. unsigned SILoadStoreOptimizer::read2Opcode(unsigned EltSize) const {
  643. if (STM->ldsRequiresM0Init())
  644. return (EltSize == 4) ? AMDGPU::DS_READ2_B32 : AMDGPU::DS_READ2_B64;
  645. return (EltSize == 4) ? AMDGPU::DS_READ2_B32_gfx9 : AMDGPU::DS_READ2_B64_gfx9;
  646. }
  647. unsigned SILoadStoreOptimizer::read2ST64Opcode(unsigned EltSize) const {
  648. if (STM->ldsRequiresM0Init())
  649. return (EltSize == 4) ? AMDGPU::DS_READ2ST64_B32 : AMDGPU::DS_READ2ST64_B64;
  650. return (EltSize == 4) ? AMDGPU::DS_READ2ST64_B32_gfx9
  651. : AMDGPU::DS_READ2ST64_B64_gfx9;
  652. }
  653. MachineBasicBlock::iterator
  654. SILoadStoreOptimizer::mergeRead2Pair(CombineInfo &CI) {
  655. MachineBasicBlock *MBB = CI.I->getParent();
  656. // Be careful, since the addresses could be subregisters themselves in weird
  657. // cases, like vectors of pointers.
  658. const auto *AddrReg = TII->getNamedOperand(*CI.I, AMDGPU::OpName::addr);
  659. const auto *Dest0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::vdst);
  660. const auto *Dest1 = TII->getNamedOperand(*CI.Paired, AMDGPU::OpName::vdst);
  661. unsigned NewOffset0 = CI.Offset0;
  662. unsigned NewOffset1 = CI.Offset1;
  663. unsigned Opc =
  664. CI.UseST64 ? read2ST64Opcode(CI.EltSize) : read2Opcode(CI.EltSize);
  665. unsigned SubRegIdx0 = (CI.EltSize == 4) ? AMDGPU::sub0 : AMDGPU::sub0_sub1;
  666. unsigned SubRegIdx1 = (CI.EltSize == 4) ? AMDGPU::sub1 : AMDGPU::sub2_sub3;
  667. if (NewOffset0 > NewOffset1) {
  668. // Canonicalize the merged instruction so the smaller offset comes first.
  669. std::swap(NewOffset0, NewOffset1);
  670. std::swap(SubRegIdx0, SubRegIdx1);
  671. }
  672. assert((isUInt<8>(NewOffset0) && isUInt<8>(NewOffset1)) &&
  673. (NewOffset0 != NewOffset1) && "Computed offset doesn't fit");
  674. const MCInstrDesc &Read2Desc = TII->get(Opc);
  675. const TargetRegisterClass *SuperRC =
  676. (CI.EltSize == 4) ? &AMDGPU::VReg_64RegClass : &AMDGPU::VReg_128RegClass;
  677. Register DestReg = MRI->createVirtualRegister(SuperRC);
  678. DebugLoc DL = CI.I->getDebugLoc();
  679. Register BaseReg = AddrReg->getReg();
  680. unsigned BaseSubReg = AddrReg->getSubReg();
  681. unsigned BaseRegFlags = 0;
  682. if (CI.BaseOff) {
  683. Register ImmReg = MRI->createVirtualRegister(&AMDGPU::SGPR_32RegClass);
  684. BuildMI(*MBB, CI.Paired, DL, TII->get(AMDGPU::S_MOV_B32), ImmReg)
  685. .addImm(CI.BaseOff);
  686. BaseReg = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
  687. BaseRegFlags = RegState::Kill;
  688. TII->getAddNoCarry(*MBB, CI.Paired, DL, BaseReg)
  689. .addReg(ImmReg)
  690. .addReg(AddrReg->getReg(), 0, BaseSubReg)
  691. .addImm(0); // clamp bit
  692. BaseSubReg = 0;
  693. }
  694. MachineInstrBuilder Read2 =
  695. BuildMI(*MBB, CI.Paired, DL, Read2Desc, DestReg)
  696. .addReg(BaseReg, BaseRegFlags, BaseSubReg) // addr
  697. .addImm(NewOffset0) // offset0
  698. .addImm(NewOffset1) // offset1
  699. .addImm(0) // gds
  700. .cloneMergedMemRefs({&*CI.I, &*CI.Paired});
  701. (void)Read2;
  702. const MCInstrDesc &CopyDesc = TII->get(TargetOpcode::COPY);
  703. // Copy to the old destination registers.
  704. BuildMI(*MBB, CI.Paired, DL, CopyDesc)
  705. .add(*Dest0) // Copy to same destination including flags and sub reg.
  706. .addReg(DestReg, 0, SubRegIdx0);
  707. MachineInstr *Copy1 = BuildMI(*MBB, CI.Paired, DL, CopyDesc)
  708. .add(*Dest1)
  709. .addReg(DestReg, RegState::Kill, SubRegIdx1);
  710. moveInstsAfter(Copy1, CI.InstsToMove);
  711. MachineBasicBlock::iterator Next = std::next(CI.I);
  712. CI.I->eraseFromParent();
  713. CI.Paired->eraseFromParent();
  714. LLVM_DEBUG(dbgs() << "Inserted read2: " << *Read2 << '\n');
  715. return Next;
  716. }
  717. unsigned SILoadStoreOptimizer::write2Opcode(unsigned EltSize) const {
  718. if (STM->ldsRequiresM0Init())
  719. return (EltSize == 4) ? AMDGPU::DS_WRITE2_B32 : AMDGPU::DS_WRITE2_B64;
  720. return (EltSize == 4) ? AMDGPU::DS_WRITE2_B32_gfx9
  721. : AMDGPU::DS_WRITE2_B64_gfx9;
  722. }
  723. unsigned SILoadStoreOptimizer::write2ST64Opcode(unsigned EltSize) const {
  724. if (STM->ldsRequiresM0Init())
  725. return (EltSize == 4) ? AMDGPU::DS_WRITE2ST64_B32
  726. : AMDGPU::DS_WRITE2ST64_B64;
  727. return (EltSize == 4) ? AMDGPU::DS_WRITE2ST64_B32_gfx9
  728. : AMDGPU::DS_WRITE2ST64_B64_gfx9;
  729. }
  730. MachineBasicBlock::iterator
  731. SILoadStoreOptimizer::mergeWrite2Pair(CombineInfo &CI) {
  732. MachineBasicBlock *MBB = CI.I->getParent();
  733. // Be sure to use .addOperand(), and not .addReg() with these. We want to be
  734. // sure we preserve the subregister index and any register flags set on them.
  735. const MachineOperand *AddrReg =
  736. TII->getNamedOperand(*CI.I, AMDGPU::OpName::addr);
  737. const MachineOperand *Data0 =
  738. TII->getNamedOperand(*CI.I, AMDGPU::OpName::data0);
  739. const MachineOperand *Data1 =
  740. TII->getNamedOperand(*CI.Paired, AMDGPU::OpName::data0);
  741. unsigned NewOffset0 = CI.Offset0;
  742. unsigned NewOffset1 = CI.Offset1;
  743. unsigned Opc =
  744. CI.UseST64 ? write2ST64Opcode(CI.EltSize) : write2Opcode(CI.EltSize);
  745. if (NewOffset0 > NewOffset1) {
  746. // Canonicalize the merged instruction so the smaller offset comes first.
  747. std::swap(NewOffset0, NewOffset1);
  748. std::swap(Data0, Data1);
  749. }
  750. assert((isUInt<8>(NewOffset0) && isUInt<8>(NewOffset1)) &&
  751. (NewOffset0 != NewOffset1) && "Computed offset doesn't fit");
  752. const MCInstrDesc &Write2Desc = TII->get(Opc);
  753. DebugLoc DL = CI.I->getDebugLoc();
  754. Register BaseReg = AddrReg->getReg();
  755. unsigned BaseSubReg = AddrReg->getSubReg();
  756. unsigned BaseRegFlags = 0;
  757. if (CI.BaseOff) {
  758. Register ImmReg = MRI->createVirtualRegister(&AMDGPU::SGPR_32RegClass);
  759. BuildMI(*MBB, CI.Paired, DL, TII->get(AMDGPU::S_MOV_B32), ImmReg)
  760. .addImm(CI.BaseOff);
  761. BaseReg = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
  762. BaseRegFlags = RegState::Kill;
  763. TII->getAddNoCarry(*MBB, CI.Paired, DL, BaseReg)
  764. .addReg(ImmReg)
  765. .addReg(AddrReg->getReg(), 0, BaseSubReg)
  766. .addImm(0); // clamp bit
  767. BaseSubReg = 0;
  768. }
  769. MachineInstrBuilder Write2 =
  770. BuildMI(*MBB, CI.Paired, DL, Write2Desc)
  771. .addReg(BaseReg, BaseRegFlags, BaseSubReg) // addr
  772. .add(*Data0) // data0
  773. .add(*Data1) // data1
  774. .addImm(NewOffset0) // offset0
  775. .addImm(NewOffset1) // offset1
  776. .addImm(0) // gds
  777. .cloneMergedMemRefs({&*CI.I, &*CI.Paired});
  778. moveInstsAfter(Write2, CI.InstsToMove);
  779. MachineBasicBlock::iterator Next = std::next(CI.I);
  780. CI.I->eraseFromParent();
  781. CI.Paired->eraseFromParent();
  782. LLVM_DEBUG(dbgs() << "Inserted write2 inst: " << *Write2 << '\n');
  783. return Next;
  784. }
  785. MachineBasicBlock::iterator
  786. SILoadStoreOptimizer::mergeSBufferLoadImmPair(CombineInfo &CI) {
  787. MachineBasicBlock *MBB = CI.I->getParent();
  788. DebugLoc DL = CI.I->getDebugLoc();
  789. const unsigned Opcode = getNewOpcode(CI);
  790. const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI);
  791. Register DestReg = MRI->createVirtualRegister(SuperRC);
  792. unsigned MergedOffset = std::min(CI.Offset0, CI.Offset1);
  793. // It shouldn't be possible to get this far if the two instructions
  794. // don't have a single memoperand, because MachineInstr::mayAlias()
  795. // will return true if this is the case.
  796. assert(CI.I->hasOneMemOperand() && CI.Paired->hasOneMemOperand());
  797. const MachineMemOperand *MMOa = *CI.I->memoperands_begin();
  798. const MachineMemOperand *MMOb = *CI.Paired->memoperands_begin();
  799. BuildMI(*MBB, CI.Paired, DL, TII->get(Opcode), DestReg)
  800. .add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::sbase))
  801. .addImm(MergedOffset) // offset
  802. .addImm(CI.GLC0) // glc
  803. .addImm(CI.DLC0) // dlc
  804. .addMemOperand(combineKnownAdjacentMMOs(*MBB->getParent(), MMOa, MMOb));
  805. std::pair<unsigned, unsigned> SubRegIdx = getSubRegIdxs(CI);
  806. const unsigned SubRegIdx0 = std::get<0>(SubRegIdx);
  807. const unsigned SubRegIdx1 = std::get<1>(SubRegIdx);
  808. // Copy to the old destination registers.
  809. const MCInstrDesc &CopyDesc = TII->get(TargetOpcode::COPY);
  810. const auto *Dest0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::sdst);
  811. const auto *Dest1 = TII->getNamedOperand(*CI.Paired, AMDGPU::OpName::sdst);
  812. BuildMI(*MBB, CI.Paired, DL, CopyDesc)
  813. .add(*Dest0) // Copy to same destination including flags and sub reg.
  814. .addReg(DestReg, 0, SubRegIdx0);
  815. MachineInstr *Copy1 = BuildMI(*MBB, CI.Paired, DL, CopyDesc)
  816. .add(*Dest1)
  817. .addReg(DestReg, RegState::Kill, SubRegIdx1);
  818. moveInstsAfter(Copy1, CI.InstsToMove);
  819. MachineBasicBlock::iterator Next = std::next(CI.I);
  820. CI.I->eraseFromParent();
  821. CI.Paired->eraseFromParent();
  822. return Next;
  823. }
  824. MachineBasicBlock::iterator
  825. SILoadStoreOptimizer::mergeBufferLoadPair(CombineInfo &CI) {
  826. MachineBasicBlock *MBB = CI.I->getParent();
  827. DebugLoc DL = CI.I->getDebugLoc();
  828. const unsigned Opcode = getNewOpcode(CI);
  829. const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI);
  830. // Copy to the new source register.
  831. Register DestReg = MRI->createVirtualRegister(SuperRC);
  832. unsigned MergedOffset = std::min(CI.Offset0, CI.Offset1);
  833. auto MIB = BuildMI(*MBB, CI.Paired, DL, TII->get(Opcode), DestReg);
  834. const unsigned Regs = getRegs(Opcode, *TII);
  835. if (Regs & VADDR)
  836. MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::vaddr));
  837. // It shouldn't be possible to get this far if the two instructions
  838. // don't have a single memoperand, because MachineInstr::mayAlias()
  839. // will return true if this is the case.
  840. assert(CI.I->hasOneMemOperand() && CI.Paired->hasOneMemOperand());
  841. const MachineMemOperand *MMOa = *CI.I->memoperands_begin();
  842. const MachineMemOperand *MMOb = *CI.Paired->memoperands_begin();
  843. MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::srsrc))
  844. .add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::soffset))
  845. .addImm(MergedOffset) // offset
  846. .addImm(CI.GLC0) // glc
  847. .addImm(CI.SLC0) // slc
  848. .addImm(0) // tfe
  849. .addImm(CI.DLC0) // dlc
  850. .addImm(0) // swz
  851. .addMemOperand(combineKnownAdjacentMMOs(*MBB->getParent(), MMOa, MMOb));
  852. std::pair<unsigned, unsigned> SubRegIdx = getSubRegIdxs(CI);
  853. const unsigned SubRegIdx0 = std::get<0>(SubRegIdx);
  854. const unsigned SubRegIdx1 = std::get<1>(SubRegIdx);
  855. // Copy to the old destination registers.
  856. const MCInstrDesc &CopyDesc = TII->get(TargetOpcode::COPY);
  857. const auto *Dest0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::vdata);
  858. const auto *Dest1 = TII->getNamedOperand(*CI.Paired, AMDGPU::OpName::vdata);
  859. BuildMI(*MBB, CI.Paired, DL, CopyDesc)
  860. .add(*Dest0) // Copy to same destination including flags and sub reg.
  861. .addReg(DestReg, 0, SubRegIdx0);
  862. MachineInstr *Copy1 = BuildMI(*MBB, CI.Paired, DL, CopyDesc)
  863. .add(*Dest1)
  864. .addReg(DestReg, RegState::Kill, SubRegIdx1);
  865. moveInstsAfter(Copy1, CI.InstsToMove);
  866. MachineBasicBlock::iterator Next = std::next(CI.I);
  867. CI.I->eraseFromParent();
  868. CI.Paired->eraseFromParent();
  869. return Next;
  870. }
  871. unsigned SILoadStoreOptimizer::getNewOpcode(const CombineInfo &CI) {
  872. const unsigned Width = CI.Width0 + CI.Width1;
  873. switch (CI.InstClass) {
  874. default:
  875. // FIXME: Handle d16 correctly
  876. return AMDGPU::getMUBUFOpcode(CI.InstClass, Width);
  877. case UNKNOWN:
  878. llvm_unreachable("Unknown instruction class");
  879. case S_BUFFER_LOAD_IMM:
  880. switch (Width) {
  881. default:
  882. return 0;
  883. case 2:
  884. return AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM;
  885. case 4:
  886. return AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM;
  887. }
  888. }
  889. }
  890. std::pair<unsigned, unsigned>
  891. SILoadStoreOptimizer::getSubRegIdxs(const CombineInfo &CI) {
  892. if (CI.Offset0 > CI.Offset1) {
  893. switch (CI.Width0) {
  894. default:
  895. return std::make_pair(0, 0);
  896. case 1:
  897. switch (CI.Width1) {
  898. default:
  899. return std::make_pair(0, 0);
  900. case 1:
  901. return std::make_pair(AMDGPU::sub1, AMDGPU::sub0);
  902. case 2:
  903. return std::make_pair(AMDGPU::sub2, AMDGPU::sub0_sub1);
  904. case 3:
  905. return std::make_pair(AMDGPU::sub3, AMDGPU::sub0_sub1_sub2);
  906. }
  907. case 2:
  908. switch (CI.Width1) {
  909. default:
  910. return std::make_pair(0, 0);
  911. case 1:
  912. return std::make_pair(AMDGPU::sub1_sub2, AMDGPU::sub0);
  913. case 2:
  914. return std::make_pair(AMDGPU::sub2_sub3, AMDGPU::sub0_sub1);
  915. }
  916. case 3:
  917. switch (CI.Width1) {
  918. default:
  919. return std::make_pair(0, 0);
  920. case 1:
  921. return std::make_pair(AMDGPU::sub1_sub2_sub3, AMDGPU::sub0);
  922. }
  923. }
  924. } else {
  925. switch (CI.Width0) {
  926. default:
  927. return std::make_pair(0, 0);
  928. case 1:
  929. switch (CI.Width1) {
  930. default:
  931. return std::make_pair(0, 0);
  932. case 1:
  933. return std::make_pair(AMDGPU::sub0, AMDGPU::sub1);
  934. case 2:
  935. return std::make_pair(AMDGPU::sub0, AMDGPU::sub1_sub2);
  936. case 3:
  937. return std::make_pair(AMDGPU::sub0, AMDGPU::sub1_sub2_sub3);
  938. }
  939. case 2:
  940. switch (CI.Width1) {
  941. default:
  942. return std::make_pair(0, 0);
  943. case 1:
  944. return std::make_pair(AMDGPU::sub0_sub1, AMDGPU::sub2);
  945. case 2:
  946. return std::make_pair(AMDGPU::sub0_sub1, AMDGPU::sub2_sub3);
  947. }
  948. case 3:
  949. switch (CI.Width1) {
  950. default:
  951. return std::make_pair(0, 0);
  952. case 1:
  953. return std::make_pair(AMDGPU::sub0_sub1_sub2, AMDGPU::sub3);
  954. }
  955. }
  956. }
  957. }
  958. const TargetRegisterClass *
  959. SILoadStoreOptimizer::getTargetRegisterClass(const CombineInfo &CI) {
  960. if (CI.InstClass == S_BUFFER_LOAD_IMM) {
  961. switch (CI.Width0 + CI.Width1) {
  962. default:
  963. return nullptr;
  964. case 2:
  965. return &AMDGPU::SReg_64_XEXECRegClass;
  966. case 4:
  967. return &AMDGPU::SReg_128RegClass;
  968. case 8:
  969. return &AMDGPU::SReg_256RegClass;
  970. case 16:
  971. return &AMDGPU::SReg_512RegClass;
  972. }
  973. } else {
  974. switch (CI.Width0 + CI.Width1) {
  975. default:
  976. return nullptr;
  977. case 2:
  978. return &AMDGPU::VReg_64RegClass;
  979. case 3:
  980. return &AMDGPU::VReg_96RegClass;
  981. case 4:
  982. return &AMDGPU::VReg_128RegClass;
  983. }
  984. }
  985. }
  986. MachineBasicBlock::iterator
  987. SILoadStoreOptimizer::mergeBufferStorePair(CombineInfo &CI) {
  988. MachineBasicBlock *MBB = CI.I->getParent();
  989. DebugLoc DL = CI.I->getDebugLoc();
  990. const unsigned Opcode = getNewOpcode(CI);
  991. std::pair<unsigned, unsigned> SubRegIdx = getSubRegIdxs(CI);
  992. const unsigned SubRegIdx0 = std::get<0>(SubRegIdx);
  993. const unsigned SubRegIdx1 = std::get<1>(SubRegIdx);
  994. // Copy to the new source register.
  995. const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI);
  996. Register SrcReg = MRI->createVirtualRegister(SuperRC);
  997. const auto *Src0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::vdata);
  998. const auto *Src1 = TII->getNamedOperand(*CI.Paired, AMDGPU::OpName::vdata);
  999. BuildMI(*MBB, CI.Paired, DL, TII->get(AMDGPU::REG_SEQUENCE), SrcReg)
  1000. .add(*Src0)
  1001. .addImm(SubRegIdx0)
  1002. .add(*Src1)
  1003. .addImm(SubRegIdx1);
  1004. auto MIB = BuildMI(*MBB, CI.Paired, DL, TII->get(Opcode))
  1005. .addReg(SrcReg, RegState::Kill);
  1006. const unsigned Regs = getRegs(Opcode, *TII);
  1007. if (Regs & VADDR)
  1008. MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::vaddr));
  1009. // It shouldn't be possible to get this far if the two instructions
  1010. // don't have a single memoperand, because MachineInstr::mayAlias()
  1011. // will return true if this is the case.
  1012. assert(CI.I->hasOneMemOperand() && CI.Paired->hasOneMemOperand());
  1013. const MachineMemOperand *MMOa = *CI.I->memoperands_begin();
  1014. const MachineMemOperand *MMOb = *CI.Paired->memoperands_begin();
  1015. MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::srsrc))
  1016. .add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::soffset))
  1017. .addImm(std::min(CI.Offset0, CI.Offset1)) // offset
  1018. .addImm(CI.GLC0) // glc
  1019. .addImm(CI.SLC0) // slc
  1020. .addImm(0) // tfe
  1021. .addImm(CI.DLC0) // dlc
  1022. .addImm(0) // swz
  1023. .addMemOperand(combineKnownAdjacentMMOs(*MBB->getParent(), MMOa, MMOb));
  1024. moveInstsAfter(MIB, CI.InstsToMove);
  1025. MachineBasicBlock::iterator Next = std::next(CI.I);
  1026. CI.I->eraseFromParent();
  1027. CI.Paired->eraseFromParent();
  1028. return Next;
  1029. }
  1030. MachineOperand
  1031. SILoadStoreOptimizer::createRegOrImm(int32_t Val, MachineInstr &MI) const {
  1032. APInt V(32, Val, true);
  1033. if (TII->isInlineConstant(V))
  1034. return MachineOperand::CreateImm(Val);
  1035. Register Reg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
  1036. MachineInstr *Mov =
  1037. BuildMI(*MI.getParent(), MI.getIterator(), MI.getDebugLoc(),
  1038. TII->get(AMDGPU::S_MOV_B32), Reg)
  1039. .addImm(Val);
  1040. (void)Mov;
  1041. LLVM_DEBUG(dbgs() << " "; Mov->dump());
  1042. return MachineOperand::CreateReg(Reg, false);
  1043. }
  1044. // Compute base address using Addr and return the final register.
  1045. unsigned SILoadStoreOptimizer::computeBase(MachineInstr &MI,
  1046. const MemAddress &Addr) const {
  1047. MachineBasicBlock *MBB = MI.getParent();
  1048. MachineBasicBlock::iterator MBBI = MI.getIterator();
  1049. DebugLoc DL = MI.getDebugLoc();
  1050. assert((TRI->getRegSizeInBits(Addr.Base.LoReg, *MRI) == 32 ||
  1051. Addr.Base.LoSubReg) &&
  1052. "Expected 32-bit Base-Register-Low!!");
  1053. assert((TRI->getRegSizeInBits(Addr.Base.HiReg, *MRI) == 32 ||
  1054. Addr.Base.HiSubReg) &&
  1055. "Expected 32-bit Base-Register-Hi!!");
  1056. LLVM_DEBUG(dbgs() << " Re-Computed Anchor-Base:\n");
  1057. MachineOperand OffsetLo = createRegOrImm(static_cast<int32_t>(Addr.Offset), MI);
  1058. MachineOperand OffsetHi =
  1059. createRegOrImm(static_cast<int32_t>(Addr.Offset >> 32), MI);
  1060. const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
  1061. Register CarryReg = MRI->createVirtualRegister(CarryRC);
  1062. Register DeadCarryReg = MRI->createVirtualRegister(CarryRC);
  1063. Register DestSub0 = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
  1064. Register DestSub1 = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
  1065. MachineInstr *LoHalf =
  1066. BuildMI(*MBB, MBBI, DL, TII->get(AMDGPU::V_ADD_I32_e64), DestSub0)
  1067. .addReg(CarryReg, RegState::Define)
  1068. .addReg(Addr.Base.LoReg, 0, Addr.Base.LoSubReg)
  1069. .add(OffsetLo)
  1070. .addImm(0); // clamp bit
  1071. (void)LoHalf;
  1072. LLVM_DEBUG(dbgs() << " "; LoHalf->dump(););
  1073. MachineInstr *HiHalf =
  1074. BuildMI(*MBB, MBBI, DL, TII->get(AMDGPU::V_ADDC_U32_e64), DestSub1)
  1075. .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
  1076. .addReg(Addr.Base.HiReg, 0, Addr.Base.HiSubReg)
  1077. .add(OffsetHi)
  1078. .addReg(CarryReg, RegState::Kill)
  1079. .addImm(0); // clamp bit
  1080. (void)HiHalf;
  1081. LLVM_DEBUG(dbgs() << " "; HiHalf->dump(););
  1082. Register FullDestReg = MRI->createVirtualRegister(&AMDGPU::VReg_64RegClass);
  1083. MachineInstr *FullBase =
  1084. BuildMI(*MBB, MBBI, DL, TII->get(TargetOpcode::REG_SEQUENCE), FullDestReg)
  1085. .addReg(DestSub0)
  1086. .addImm(AMDGPU::sub0)
  1087. .addReg(DestSub1)
  1088. .addImm(AMDGPU::sub1);
  1089. (void)FullBase;
  1090. LLVM_DEBUG(dbgs() << " "; FullBase->dump(); dbgs() << "\n";);
  1091. return FullDestReg;
  1092. }
  1093. // Update base and offset with the NewBase and NewOffset in MI.
  1094. void SILoadStoreOptimizer::updateBaseAndOffset(MachineInstr &MI,
  1095. unsigned NewBase,
  1096. int32_t NewOffset) const {
  1097. TII->getNamedOperand(MI, AMDGPU::OpName::vaddr)->setReg(NewBase);
  1098. TII->getNamedOperand(MI, AMDGPU::OpName::offset)->setImm(NewOffset);
  1099. }
  1100. Optional<int32_t>
  1101. SILoadStoreOptimizer::extractConstOffset(const MachineOperand &Op) const {
  1102. if (Op.isImm())
  1103. return Op.getImm();
  1104. if (!Op.isReg())
  1105. return None;
  1106. MachineInstr *Def = MRI->getUniqueVRegDef(Op.getReg());
  1107. if (!Def || Def->getOpcode() != AMDGPU::S_MOV_B32 ||
  1108. !Def->getOperand(1).isImm())
  1109. return None;
  1110. return Def->getOperand(1).getImm();
  1111. }
  1112. // Analyze Base and extracts:
  1113. // - 32bit base registers, subregisters
  1114. // - 64bit constant offset
  1115. // Expecting base computation as:
  1116. // %OFFSET0:sgpr_32 = S_MOV_B32 8000
  1117. // %LO:vgpr_32, %c:sreg_64_xexec =
  1118. // V_ADD_I32_e64 %BASE_LO:vgpr_32, %103:sgpr_32,
  1119. // %HI:vgpr_32, = V_ADDC_U32_e64 %BASE_HI:vgpr_32, 0, killed %c:sreg_64_xexec
  1120. // %Base:vreg_64 =
  1121. // REG_SEQUENCE %LO:vgpr_32, %subreg.sub0, %HI:vgpr_32, %subreg.sub1
  1122. void SILoadStoreOptimizer::processBaseWithConstOffset(const MachineOperand &Base,
  1123. MemAddress &Addr) const {
  1124. if (!Base.isReg())
  1125. return;
  1126. MachineInstr *Def = MRI->getUniqueVRegDef(Base.getReg());
  1127. if (!Def || Def->getOpcode() != AMDGPU::REG_SEQUENCE
  1128. || Def->getNumOperands() != 5)
  1129. return;
  1130. MachineOperand BaseLo = Def->getOperand(1);
  1131. MachineOperand BaseHi = Def->getOperand(3);
  1132. if (!BaseLo.isReg() || !BaseHi.isReg())
  1133. return;
  1134. MachineInstr *BaseLoDef = MRI->getUniqueVRegDef(BaseLo.getReg());
  1135. MachineInstr *BaseHiDef = MRI->getUniqueVRegDef(BaseHi.getReg());
  1136. if (!BaseLoDef || BaseLoDef->getOpcode() != AMDGPU::V_ADD_I32_e64 ||
  1137. !BaseHiDef || BaseHiDef->getOpcode() != AMDGPU::V_ADDC_U32_e64)
  1138. return;
  1139. const auto *Src0 = TII->getNamedOperand(*BaseLoDef, AMDGPU::OpName::src0);
  1140. const auto *Src1 = TII->getNamedOperand(*BaseLoDef, AMDGPU::OpName::src1);
  1141. auto Offset0P = extractConstOffset(*Src0);
  1142. if (Offset0P)
  1143. BaseLo = *Src1;
  1144. else {
  1145. if (!(Offset0P = extractConstOffset(*Src1)))
  1146. return;
  1147. BaseLo = *Src0;
  1148. }
  1149. Src0 = TII->getNamedOperand(*BaseHiDef, AMDGPU::OpName::src0);
  1150. Src1 = TII->getNamedOperand(*BaseHiDef, AMDGPU::OpName::src1);
  1151. if (Src0->isImm())
  1152. std::swap(Src0, Src1);
  1153. if (!Src1->isImm())
  1154. return;
  1155. uint64_t Offset1 = Src1->getImm();
  1156. BaseHi = *Src0;
  1157. Addr.Base.LoReg = BaseLo.getReg();
  1158. Addr.Base.HiReg = BaseHi.getReg();
  1159. Addr.Base.LoSubReg = BaseLo.getSubReg();
  1160. Addr.Base.HiSubReg = BaseHi.getSubReg();
  1161. Addr.Offset = (*Offset0P & 0x00000000ffffffff) | (Offset1 << 32);
  1162. }
  1163. bool SILoadStoreOptimizer::promoteConstantOffsetToImm(
  1164. MachineInstr &MI,
  1165. MemInfoMap &Visited,
  1166. SmallPtrSet<MachineInstr *, 4> &AnchorList) const {
  1167. if (!(MI.mayLoad() ^ MI.mayStore()))
  1168. return false;
  1169. // TODO: Support flat and scratch.
  1170. if (AMDGPU::getGlobalSaddrOp(MI.getOpcode()) < 0)
  1171. return false;
  1172. if (MI.mayLoad() && TII->getNamedOperand(MI, AMDGPU::OpName::vdata) != NULL)
  1173. return false;
  1174. if (AnchorList.count(&MI))
  1175. return false;
  1176. LLVM_DEBUG(dbgs() << "\nTryToPromoteConstantOffsetToImmFor "; MI.dump());
  1177. if (TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm()) {
  1178. LLVM_DEBUG(dbgs() << " Const-offset is already promoted.\n";);
  1179. return false;
  1180. }
  1181. // Step1: Find the base-registers and a 64bit constant offset.
  1182. MachineOperand &Base = *TII->getNamedOperand(MI, AMDGPU::OpName::vaddr);
  1183. MemAddress MAddr;
  1184. if (Visited.find(&MI) == Visited.end()) {
  1185. processBaseWithConstOffset(Base, MAddr);
  1186. Visited[&MI] = MAddr;
  1187. } else
  1188. MAddr = Visited[&MI];
  1189. if (MAddr.Offset == 0) {
  1190. LLVM_DEBUG(dbgs() << " Failed to extract constant-offset or there are no"
  1191. " constant offsets that can be promoted.\n";);
  1192. return false;
  1193. }
  1194. LLVM_DEBUG(dbgs() << " BASE: {" << MAddr.Base.HiReg << ", "
  1195. << MAddr.Base.LoReg << "} Offset: " << MAddr.Offset << "\n\n";);
  1196. // Step2: Traverse through MI's basic block and find an anchor(that has the
  1197. // same base-registers) with the highest 13bit distance from MI's offset.
  1198. // E.g. (64bit loads)
  1199. // bb:
  1200. // addr1 = &a + 4096; load1 = load(addr1, 0)
  1201. // addr2 = &a + 6144; load2 = load(addr2, 0)
  1202. // addr3 = &a + 8192; load3 = load(addr3, 0)
  1203. // addr4 = &a + 10240; load4 = load(addr4, 0)
  1204. // addr5 = &a + 12288; load5 = load(addr5, 0)
  1205. //
  1206. // Starting from the first load, the optimization will try to find a new base
  1207. // from which (&a + 4096) has 13 bit distance. Both &a + 6144 and &a + 8192
  1208. // has 13bit distance from &a + 4096. The heuristic considers &a + 8192
  1209. // as the new-base(anchor) because of the maximum distance which can
  1210. // accomodate more intermediate bases presumeably.
  1211. //
  1212. // Step3: move (&a + 8192) above load1. Compute and promote offsets from
  1213. // (&a + 8192) for load1, load2, load4.
  1214. // addr = &a + 8192
  1215. // load1 = load(addr, -4096)
  1216. // load2 = load(addr, -2048)
  1217. // load3 = load(addr, 0)
  1218. // load4 = load(addr, 2048)
  1219. // addr5 = &a + 12288; load5 = load(addr5, 0)
  1220. //
  1221. MachineInstr *AnchorInst = nullptr;
  1222. MemAddress AnchorAddr;
  1223. uint32_t MaxDist = std::numeric_limits<uint32_t>::min();
  1224. SmallVector<std::pair<MachineInstr *, int64_t>, 4> InstsWCommonBase;
  1225. MachineBasicBlock *MBB = MI.getParent();
  1226. MachineBasicBlock::iterator E = MBB->end();
  1227. MachineBasicBlock::iterator MBBI = MI.getIterator();
  1228. ++MBBI;
  1229. const SITargetLowering *TLI =
  1230. static_cast<const SITargetLowering *>(STM->getTargetLowering());
  1231. for ( ; MBBI != E; ++MBBI) {
  1232. MachineInstr &MINext = *MBBI;
  1233. // TODO: Support finding an anchor(with same base) from store addresses or
  1234. // any other load addresses where the opcodes are different.
  1235. if (MINext.getOpcode() != MI.getOpcode() ||
  1236. TII->getNamedOperand(MINext, AMDGPU::OpName::offset)->getImm())
  1237. continue;
  1238. const MachineOperand &BaseNext =
  1239. *TII->getNamedOperand(MINext, AMDGPU::OpName::vaddr);
  1240. MemAddress MAddrNext;
  1241. if (Visited.find(&MINext) == Visited.end()) {
  1242. processBaseWithConstOffset(BaseNext, MAddrNext);
  1243. Visited[&MINext] = MAddrNext;
  1244. } else
  1245. MAddrNext = Visited[&MINext];
  1246. if (MAddrNext.Base.LoReg != MAddr.Base.LoReg ||
  1247. MAddrNext.Base.HiReg != MAddr.Base.HiReg ||
  1248. MAddrNext.Base.LoSubReg != MAddr.Base.LoSubReg ||
  1249. MAddrNext.Base.HiSubReg != MAddr.Base.HiSubReg)
  1250. continue;
  1251. InstsWCommonBase.push_back(std::make_pair(&MINext, MAddrNext.Offset));
  1252. int64_t Dist = MAddr.Offset - MAddrNext.Offset;
  1253. TargetLoweringBase::AddrMode AM;
  1254. AM.HasBaseReg = true;
  1255. AM.BaseOffs = Dist;
  1256. if (TLI->isLegalGlobalAddressingMode(AM) &&
  1257. (uint32_t)std::abs(Dist) > MaxDist) {
  1258. MaxDist = std::abs(Dist);
  1259. AnchorAddr = MAddrNext;
  1260. AnchorInst = &MINext;
  1261. }
  1262. }
  1263. if (AnchorInst) {
  1264. LLVM_DEBUG(dbgs() << " Anchor-Inst(with max-distance from Offset): ";
  1265. AnchorInst->dump());
  1266. LLVM_DEBUG(dbgs() << " Anchor-Offset from BASE: "
  1267. << AnchorAddr.Offset << "\n\n");
  1268. // Instead of moving up, just re-compute anchor-instruction's base address.
  1269. unsigned Base = computeBase(MI, AnchorAddr);
  1270. updateBaseAndOffset(MI, Base, MAddr.Offset - AnchorAddr.Offset);
  1271. LLVM_DEBUG(dbgs() << " After promotion: "; MI.dump(););
  1272. for (auto P : InstsWCommonBase) {
  1273. TargetLoweringBase::AddrMode AM;
  1274. AM.HasBaseReg = true;
  1275. AM.BaseOffs = P.second - AnchorAddr.Offset;
  1276. if (TLI->isLegalGlobalAddressingMode(AM)) {
  1277. LLVM_DEBUG(dbgs() << " Promote Offset(" << P.second;
  1278. dbgs() << ")"; P.first->dump());
  1279. updateBaseAndOffset(*P.first, Base, P.second - AnchorAddr.Offset);
  1280. LLVM_DEBUG(dbgs() << " After promotion: "; P.first->dump());
  1281. }
  1282. }
  1283. AnchorList.insert(AnchorInst);
  1284. return true;
  1285. }
  1286. return false;
  1287. }
  1288. // Scan through looking for adjacent LDS operations with constant offsets from
  1289. // the same base register. We rely on the scheduler to do the hard work of
  1290. // clustering nearby loads, and assume these are all adjacent.
  1291. bool SILoadStoreOptimizer::optimizeBlock(MachineBasicBlock &MBB) {
  1292. bool Modified = false;
  1293. // Contain the list
  1294. MemInfoMap Visited;
  1295. // Contains the list of instructions for which constant offsets are being
  1296. // promoted to the IMM.
  1297. SmallPtrSet<MachineInstr *, 4> AnchorList;
  1298. for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;) {
  1299. MachineInstr &MI = *I;
  1300. if (promoteConstantOffsetToImm(MI, Visited, AnchorList))
  1301. Modified = true;
  1302. // Don't combine if volatile.
  1303. if (MI.hasOrderedMemoryRef()) {
  1304. ++I;
  1305. continue;
  1306. }
  1307. CombineInfo CI;
  1308. CI.setMI(I, *TII, *STM);
  1309. switch (CI.InstClass) {
  1310. default:
  1311. break;
  1312. case DS_READ:
  1313. if (findMatchingInst(CI)) {
  1314. Modified = true;
  1315. I = mergeRead2Pair(CI);
  1316. } else {
  1317. ++I;
  1318. }
  1319. continue;
  1320. case DS_WRITE:
  1321. if (findMatchingInst(CI)) {
  1322. Modified = true;
  1323. I = mergeWrite2Pair(CI);
  1324. } else {
  1325. ++I;
  1326. }
  1327. continue;
  1328. case S_BUFFER_LOAD_IMM:
  1329. if (findMatchingInst(CI)) {
  1330. Modified = true;
  1331. I = mergeSBufferLoadImmPair(CI);
  1332. OptimizeAgain |= (CI.Width0 + CI.Width1) < 16;
  1333. } else {
  1334. ++I;
  1335. }
  1336. continue;
  1337. case BUFFER_LOAD_OFFEN:
  1338. case BUFFER_LOAD_OFFSET:
  1339. case BUFFER_LOAD_OFFEN_exact:
  1340. case BUFFER_LOAD_OFFSET_exact:
  1341. if (findMatchingInst(CI)) {
  1342. Modified = true;
  1343. I = mergeBufferLoadPair(CI);
  1344. OptimizeAgain |= (CI.Width0 + CI.Width1) < 4;
  1345. } else {
  1346. ++I;
  1347. }
  1348. continue;
  1349. case BUFFER_STORE_OFFEN:
  1350. case BUFFER_STORE_OFFSET:
  1351. case BUFFER_STORE_OFFEN_exact:
  1352. case BUFFER_STORE_OFFSET_exact:
  1353. if (findMatchingInst(CI)) {
  1354. Modified = true;
  1355. I = mergeBufferStorePair(CI);
  1356. OptimizeAgain |= (CI.Width0 + CI.Width1) < 4;
  1357. } else {
  1358. ++I;
  1359. }
  1360. continue;
  1361. }
  1362. ++I;
  1363. }
  1364. return Modified;
  1365. }
  1366. bool SILoadStoreOptimizer::runOnMachineFunction(MachineFunction &MF) {
  1367. if (skipFunction(MF.getFunction()))
  1368. return false;
  1369. STM = &MF.getSubtarget<GCNSubtarget>();
  1370. if (!STM->loadStoreOptEnabled())
  1371. return false;
  1372. TII = STM->getInstrInfo();
  1373. TRI = &TII->getRegisterInfo();
  1374. MRI = &MF.getRegInfo();
  1375. AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  1376. assert(MRI->isSSA() && "Must be run on SSA");
  1377. LLVM_DEBUG(dbgs() << "Running SILoadStoreOptimizer\n");
  1378. bool Modified = false;
  1379. for (MachineBasicBlock &MBB : MF) {
  1380. do {
  1381. OptimizeAgain = false;
  1382. Modified |= optimizeBlock(MBB);
  1383. } while (OptimizeAgain);
  1384. }
  1385. return Modified;
  1386. }