1 //=- AArch64LoadStoreOptimizer.cpp - AArch64 load/store opt. pass -*- C++ -*-=// 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 // This file contains a pass that performs load / store related peephole 11 // optimizations. This pass should be run after register allocation. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "AArch64InstrInfo.h" 16 #include "AArch64Subtarget.h" 17 #include "MCTargetDesc/AArch64AddressingModes.h" 18 #include "llvm/ADT/BitVector.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/CodeGen/MachineBasicBlock.h" 22 #include "llvm/CodeGen/MachineFunctionPass.h" 23 #include "llvm/CodeGen/MachineInstr.h" 24 #include "llvm/CodeGen/MachineInstrBuilder.h" 25 #include "llvm/Support/CommandLine.h" 26 #include "llvm/Support/Debug.h" 27 #include "llvm/Support/ErrorHandling.h" 28 #include "llvm/Support/raw_ostream.h" 29 #include "llvm/Target/TargetInstrInfo.h" 30 #include "llvm/Target/TargetMachine.h" 31 #include "llvm/Target/TargetRegisterInfo.h" 32 using namespace llvm; 33 34 #define DEBUG_TYPE "aarch64-ldst-opt" 35 36 STATISTIC(NumPairCreated, "Number of load/store pair instructions generated"); 37 STATISTIC(NumPostFolded, "Number of post-index updates folded"); 38 STATISTIC(NumPreFolded, "Number of pre-index updates folded"); 39 STATISTIC(NumUnscaledPairCreated, 40 "Number of load/store from unscaled generated"); 41 STATISTIC(NumZeroStoresPromoted, "Number of narrow zero stores promoted"); 42 STATISTIC(NumLoadsFromStoresPromoted, "Number of loads from stores promoted"); 43 44 // The LdStLimit limits how far we search for load/store pairs. 45 static cl::opt<unsigned> LdStLimit("aarch64-load-store-scan-limit", 46 cl::init(20), cl::Hidden); 47 48 // The UpdateLimit limits how far we search for update instructions when we form 49 // pre-/post-index instructions. 50 static cl::opt<unsigned> UpdateLimit("aarch64-update-scan-limit", cl::init(100), 51 cl::Hidden); 52 53 #define AARCH64_LOAD_STORE_OPT_NAME "AArch64 load / store optimization pass" 54 55 namespace { 56 57 typedef struct LdStPairFlags { 58 // If a matching instruction is found, MergeForward is set to true if the 59 // merge is to remove the first instruction and replace the second with 60 // a pair-wise insn, and false if the reverse is true. 61 bool MergeForward; 62 63 // SExtIdx gives the index of the result of the load pair that must be 64 // extended. The value of SExtIdx assumes that the paired load produces the 65 // value in this order: (I, returned iterator), i.e., -1 means no value has 66 // to be extended, 0 means I, and 1 means the returned iterator. 67 int SExtIdx; 68 69 LdStPairFlags() : MergeForward(false), SExtIdx(-1) {} 70 71 void setMergeForward(bool V = true) { MergeForward = V; } 72 bool getMergeForward() const { return MergeForward; } 73 74 void setSExtIdx(int V) { SExtIdx = V; } 75 int getSExtIdx() const { return SExtIdx; } 76 77 } LdStPairFlags; 78 79 struct AArch64LoadStoreOpt : public MachineFunctionPass { 80 static char ID; 81 AArch64LoadStoreOpt() : MachineFunctionPass(ID) { 82 initializeAArch64LoadStoreOptPass(*PassRegistry::getPassRegistry()); 83 } 84 85 const AArch64InstrInfo *TII; 86 const TargetRegisterInfo *TRI; 87 const AArch64Subtarget *Subtarget; 88 89 // Track which registers have been modified and used. 90 BitVector ModifiedRegs, UsedRegs; 91 92 // Scan the instructions looking for a load/store that can be combined 93 // with the current instruction into a load/store pair. 94 // Return the matching instruction if one is found, else MBB->end(). 95 MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I, 96 LdStPairFlags &Flags, 97 unsigned Limit, 98 bool FindNarrowMerge); 99 100 // Scan the instructions looking for a store that writes to the address from 101 // which the current load instruction reads. Return true if one is found. 102 bool findMatchingStore(MachineBasicBlock::iterator I, unsigned Limit, 103 MachineBasicBlock::iterator &StoreI); 104 105 // Merge the two instructions indicated into a wider narrow store instruction. 106 MachineBasicBlock::iterator 107 mergeNarrowZeroStores(MachineBasicBlock::iterator I, 108 MachineBasicBlock::iterator MergeMI, 109 const LdStPairFlags &Flags); 110 111 // Merge the two instructions indicated into a single pair-wise instruction. 112 MachineBasicBlock::iterator 113 mergePairedInsns(MachineBasicBlock::iterator I, 114 MachineBasicBlock::iterator Paired, 115 const LdStPairFlags &Flags); 116 117 // Promote the load that reads directly from the address stored to. 118 MachineBasicBlock::iterator 119 promoteLoadFromStore(MachineBasicBlock::iterator LoadI, 120 MachineBasicBlock::iterator StoreI); 121 122 // Scan the instruction list to find a base register update that can 123 // be combined with the current instruction (a load or store) using 124 // pre or post indexed addressing with writeback. Scan forwards. 125 MachineBasicBlock::iterator 126 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I, 127 int UnscaledOffset, unsigned Limit); 128 129 // Scan the instruction list to find a base register update that can 130 // be combined with the current instruction (a load or store) using 131 // pre or post indexed addressing with writeback. Scan backwards. 132 MachineBasicBlock::iterator 133 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit); 134 135 // Find an instruction that updates the base register of the ld/st 136 // instruction. 137 bool isMatchingUpdateInsn(MachineInstr &MemMI, MachineInstr &MI, 138 unsigned BaseReg, int Offset); 139 140 // Merge a pre- or post-index base register update into a ld/st instruction. 141 MachineBasicBlock::iterator 142 mergeUpdateInsn(MachineBasicBlock::iterator I, 143 MachineBasicBlock::iterator Update, bool IsPreIdx); 144 145 // Find and merge zero store instructions. 146 bool tryToMergeZeroStInst(MachineBasicBlock::iterator &MBBI); 147 148 // Find and pair ldr/str instructions. 149 bool tryToPairLdStInst(MachineBasicBlock::iterator &MBBI); 150 151 // Find and promote load instructions which read directly from store. 152 bool tryToPromoteLoadFromStore(MachineBasicBlock::iterator &MBBI); 153 154 bool optimizeBlock(MachineBasicBlock &MBB, bool EnableNarrowZeroStOpt); 155 156 bool runOnMachineFunction(MachineFunction &Fn) override; 157 158 MachineFunctionProperties getRequiredProperties() const override { 159 return MachineFunctionProperties().set( 160 MachineFunctionProperties::Property::NoVRegs); 161 } 162 163 StringRef getPassName() const override { return AARCH64_LOAD_STORE_OPT_NAME; } 164 }; 165 char AArch64LoadStoreOpt::ID = 0; 166 } // namespace 167 168 INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt", 169 AARCH64_LOAD_STORE_OPT_NAME, false, false) 170 171 static bool isNarrowStore(unsigned Opc) { 172 switch (Opc) { 173 default: 174 return false; 175 case AArch64::STRBBui: 176 case AArch64::STURBBi: 177 case AArch64::STRHHui: 178 case AArch64::STURHHi: 179 return true; 180 } 181 } 182 183 // Scaling factor for unscaled load or store. 184 static int getMemScale(MachineInstr &MI) { 185 switch (MI.getOpcode()) { 186 default: 187 llvm_unreachable("Opcode has unknown scale!"); 188 case AArch64::LDRBBui: 189 case AArch64::LDURBBi: 190 case AArch64::LDRSBWui: 191 case AArch64::LDURSBWi: 192 case AArch64::STRBBui: 193 case AArch64::STURBBi: 194 return 1; 195 case AArch64::LDRHHui: 196 case AArch64::LDURHHi: 197 case AArch64::LDRSHWui: 198 case AArch64::LDURSHWi: 199 case AArch64::STRHHui: 200 case AArch64::STURHHi: 201 return 2; 202 case AArch64::LDRSui: 203 case AArch64::LDURSi: 204 case AArch64::LDRSWui: 205 case AArch64::LDURSWi: 206 case AArch64::LDRWui: 207 case AArch64::LDURWi: 208 case AArch64::STRSui: 209 case AArch64::STURSi: 210 case AArch64::STRWui: 211 case AArch64::STURWi: 212 case AArch64::LDPSi: 213 case AArch64::LDPSWi: 214 case AArch64::LDPWi: 215 case AArch64::STPSi: 216 case AArch64::STPWi: 217 return 4; 218 case AArch64::LDRDui: 219 case AArch64::LDURDi: 220 case AArch64::LDRXui: 221 case AArch64::LDURXi: 222 case AArch64::STRDui: 223 case AArch64::STURDi: 224 case AArch64::STRXui: 225 case AArch64::STURXi: 226 case AArch64::LDPDi: 227 case AArch64::LDPXi: 228 case AArch64::STPDi: 229 case AArch64::STPXi: 230 return 8; 231 case AArch64::LDRQui: 232 case AArch64::LDURQi: 233 case AArch64::STRQui: 234 case AArch64::STURQi: 235 case AArch64::LDPQi: 236 case AArch64::STPQi: 237 return 16; 238 } 239 } 240 241 static unsigned getMatchingNonSExtOpcode(unsigned Opc, 242 bool *IsValidLdStrOpc = nullptr) { 243 if (IsValidLdStrOpc) 244 *IsValidLdStrOpc = true; 245 switch (Opc) { 246 default: 247 if (IsValidLdStrOpc) 248 *IsValidLdStrOpc = false; 249 return UINT_MAX; 250 case AArch64::STRDui: 251 case AArch64::STURDi: 252 case AArch64::STRQui: 253 case AArch64::STURQi: 254 case AArch64::STRBBui: 255 case AArch64::STURBBi: 256 case AArch64::STRHHui: 257 case AArch64::STURHHi: 258 case AArch64::STRWui: 259 case AArch64::STURWi: 260 case AArch64::STRXui: 261 case AArch64::STURXi: 262 case AArch64::LDRDui: 263 case AArch64::LDURDi: 264 case AArch64::LDRQui: 265 case AArch64::LDURQi: 266 case AArch64::LDRWui: 267 case AArch64::LDURWi: 268 case AArch64::LDRXui: 269 case AArch64::LDURXi: 270 case AArch64::STRSui: 271 case AArch64::STURSi: 272 case AArch64::LDRSui: 273 case AArch64::LDURSi: 274 return Opc; 275 case AArch64::LDRSWui: 276 return AArch64::LDRWui; 277 case AArch64::LDURSWi: 278 return AArch64::LDURWi; 279 } 280 } 281 282 static unsigned getMatchingWideOpcode(unsigned Opc) { 283 switch (Opc) { 284 default: 285 llvm_unreachable("Opcode has no wide equivalent!"); 286 case AArch64::STRBBui: 287 return AArch64::STRHHui; 288 case AArch64::STRHHui: 289 return AArch64::STRWui; 290 case AArch64::STURBBi: 291 return AArch64::STURHHi; 292 case AArch64::STURHHi: 293 return AArch64::STURWi; 294 case AArch64::STURWi: 295 return AArch64::STURXi; 296 case AArch64::STRWui: 297 return AArch64::STRXui; 298 } 299 } 300 301 static unsigned getMatchingPairOpcode(unsigned Opc) { 302 switch (Opc) { 303 default: 304 llvm_unreachable("Opcode has no pairwise equivalent!"); 305 case AArch64::STRSui: 306 case AArch64::STURSi: 307 return AArch64::STPSi; 308 case AArch64::STRDui: 309 case AArch64::STURDi: 310 return AArch64::STPDi; 311 case AArch64::STRQui: 312 case AArch64::STURQi: 313 return AArch64::STPQi; 314 case AArch64::STRWui: 315 case AArch64::STURWi: 316 return AArch64::STPWi; 317 case AArch64::STRXui: 318 case AArch64::STURXi: 319 return AArch64::STPXi; 320 case AArch64::LDRSui: 321 case AArch64::LDURSi: 322 return AArch64::LDPSi; 323 case AArch64::LDRDui: 324 case AArch64::LDURDi: 325 return AArch64::LDPDi; 326 case AArch64::LDRQui: 327 case AArch64::LDURQi: 328 return AArch64::LDPQi; 329 case AArch64::LDRWui: 330 case AArch64::LDURWi: 331 return AArch64::LDPWi; 332 case AArch64::LDRXui: 333 case AArch64::LDURXi: 334 return AArch64::LDPXi; 335 case AArch64::LDRSWui: 336 case AArch64::LDURSWi: 337 return AArch64::LDPSWi; 338 } 339 } 340 341 static unsigned isMatchingStore(MachineInstr &LoadInst, 342 MachineInstr &StoreInst) { 343 unsigned LdOpc = LoadInst.getOpcode(); 344 unsigned StOpc = StoreInst.getOpcode(); 345 switch (LdOpc) { 346 default: 347 llvm_unreachable("Unsupported load instruction!"); 348 case AArch64::LDRBBui: 349 return StOpc == AArch64::STRBBui || StOpc == AArch64::STRHHui || 350 StOpc == AArch64::STRWui || StOpc == AArch64::STRXui; 351 case AArch64::LDURBBi: 352 return StOpc == AArch64::STURBBi || StOpc == AArch64::STURHHi || 353 StOpc == AArch64::STURWi || StOpc == AArch64::STURXi; 354 case AArch64::LDRHHui: 355 return StOpc == AArch64::STRHHui || StOpc == AArch64::STRWui || 356 StOpc == AArch64::STRXui; 357 case AArch64::LDURHHi: 358 return StOpc == AArch64::STURHHi || StOpc == AArch64::STURWi || 359 StOpc == AArch64::STURXi; 360 case AArch64::LDRWui: 361 return StOpc == AArch64::STRWui || StOpc == AArch64::STRXui; 362 case AArch64::LDURWi: 363 return StOpc == AArch64::STURWi || StOpc == AArch64::STURXi; 364 case AArch64::LDRXui: 365 return StOpc == AArch64::STRXui; 366 case AArch64::LDURXi: 367 return StOpc == AArch64::STURXi; 368 } 369 } 370 371 static unsigned getPreIndexedOpcode(unsigned Opc) { 372 switch (Opc) { 373 default: 374 llvm_unreachable("Opcode has no pre-indexed equivalent!"); 375 case AArch64::STRSui: 376 return AArch64::STRSpre; 377 case AArch64::STRDui: 378 return AArch64::STRDpre; 379 case AArch64::STRQui: 380 return AArch64::STRQpre; 381 case AArch64::STRBBui: 382 return AArch64::STRBBpre; 383 case AArch64::STRHHui: 384 return AArch64::STRHHpre; 385 case AArch64::STRWui: 386 return AArch64::STRWpre; 387 case AArch64::STRXui: 388 return AArch64::STRXpre; 389 case AArch64::LDRSui: 390 return AArch64::LDRSpre; 391 case AArch64::LDRDui: 392 return AArch64::LDRDpre; 393 case AArch64::LDRQui: 394 return AArch64::LDRQpre; 395 case AArch64::LDRBBui: 396 return AArch64::LDRBBpre; 397 case AArch64::LDRHHui: 398 return AArch64::LDRHHpre; 399 case AArch64::LDRWui: 400 return AArch64::LDRWpre; 401 case AArch64::LDRXui: 402 return AArch64::LDRXpre; 403 case AArch64::LDRSWui: 404 return AArch64::LDRSWpre; 405 case AArch64::LDPSi: 406 return AArch64::LDPSpre; 407 case AArch64::LDPSWi: 408 return AArch64::LDPSWpre; 409 case AArch64::LDPDi: 410 return AArch64::LDPDpre; 411 case AArch64::LDPQi: 412 return AArch64::LDPQpre; 413 case AArch64::LDPWi: 414 return AArch64::LDPWpre; 415 case AArch64::LDPXi: 416 return AArch64::LDPXpre; 417 case AArch64::STPSi: 418 return AArch64::STPSpre; 419 case AArch64::STPDi: 420 return AArch64::STPDpre; 421 case AArch64::STPQi: 422 return AArch64::STPQpre; 423 case AArch64::STPWi: 424 return AArch64::STPWpre; 425 case AArch64::STPXi: 426 return AArch64::STPXpre; 427 } 428 } 429 430 static unsigned getPostIndexedOpcode(unsigned Opc) { 431 switch (Opc) { 432 default: 433 llvm_unreachable("Opcode has no post-indexed wise equivalent!"); 434 case AArch64::STRSui: 435 return AArch64::STRSpost; 436 case AArch64::STRDui: 437 return AArch64::STRDpost; 438 case AArch64::STRQui: 439 return AArch64::STRQpost; 440 case AArch64::STRBBui: 441 return AArch64::STRBBpost; 442 case AArch64::STRHHui: 443 return AArch64::STRHHpost; 444 case AArch64::STRWui: 445 return AArch64::STRWpost; 446 case AArch64::STRXui: 447 return AArch64::STRXpost; 448 case AArch64::LDRSui: 449 return AArch64::LDRSpost; 450 case AArch64::LDRDui: 451 return AArch64::LDRDpost; 452 case AArch64::LDRQui: 453 return AArch64::LDRQpost; 454 case AArch64::LDRBBui: 455 return AArch64::LDRBBpost; 456 case AArch64::LDRHHui: 457 return AArch64::LDRHHpost; 458 case AArch64::LDRWui: 459 return AArch64::LDRWpost; 460 case AArch64::LDRXui: 461 return AArch64::LDRXpost; 462 case AArch64::LDRSWui: 463 return AArch64::LDRSWpost; 464 case AArch64::LDPSi: 465 return AArch64::LDPSpost; 466 case AArch64::LDPSWi: 467 return AArch64::LDPSWpost; 468 case AArch64::LDPDi: 469 return AArch64::LDPDpost; 470 case AArch64::LDPQi: 471 return AArch64::LDPQpost; 472 case AArch64::LDPWi: 473 return AArch64::LDPWpost; 474 case AArch64::LDPXi: 475 return AArch64::LDPXpost; 476 case AArch64::STPSi: 477 return AArch64::STPSpost; 478 case AArch64::STPDi: 479 return AArch64::STPDpost; 480 case AArch64::STPQi: 481 return AArch64::STPQpost; 482 case AArch64::STPWi: 483 return AArch64::STPWpost; 484 case AArch64::STPXi: 485 return AArch64::STPXpost; 486 } 487 } 488 489 static bool isPairedLdSt(const MachineInstr &MI) { 490 switch (MI.getOpcode()) { 491 default: 492 return false; 493 case AArch64::LDPSi: 494 case AArch64::LDPSWi: 495 case AArch64::LDPDi: 496 case AArch64::LDPQi: 497 case AArch64::LDPWi: 498 case AArch64::LDPXi: 499 case AArch64::STPSi: 500 case AArch64::STPDi: 501 case AArch64::STPQi: 502 case AArch64::STPWi: 503 case AArch64::STPXi: 504 return true; 505 } 506 } 507 508 static const MachineOperand &getLdStRegOp(const MachineInstr &MI, 509 unsigned PairedRegOp = 0) { 510 assert(PairedRegOp < 2 && "Unexpected register operand idx."); 511 unsigned Idx = isPairedLdSt(MI) ? PairedRegOp : 0; 512 return MI.getOperand(Idx); 513 } 514 515 static const MachineOperand &getLdStBaseOp(const MachineInstr &MI) { 516 unsigned Idx = isPairedLdSt(MI) ? 2 : 1; 517 return MI.getOperand(Idx); 518 } 519 520 static const MachineOperand &getLdStOffsetOp(const MachineInstr &MI) { 521 unsigned Idx = isPairedLdSt(MI) ? 3 : 2; 522 return MI.getOperand(Idx); 523 } 524 525 static bool isLdOffsetInRangeOfSt(MachineInstr &LoadInst, 526 MachineInstr &StoreInst, 527 const AArch64InstrInfo *TII) { 528 assert(isMatchingStore(LoadInst, StoreInst) && "Expect only matched ld/st."); 529 int LoadSize = getMemScale(LoadInst); 530 int StoreSize = getMemScale(StoreInst); 531 int UnscaledStOffset = TII->isUnscaledLdSt(StoreInst) 532 ? getLdStOffsetOp(StoreInst).getImm() 533 : getLdStOffsetOp(StoreInst).getImm() * StoreSize; 534 int UnscaledLdOffset = TII->isUnscaledLdSt(LoadInst) 535 ? getLdStOffsetOp(LoadInst).getImm() 536 : getLdStOffsetOp(LoadInst).getImm() * LoadSize; 537 return (UnscaledStOffset <= UnscaledLdOffset) && 538 (UnscaledLdOffset + LoadSize <= (UnscaledStOffset + StoreSize)); 539 } 540 541 static bool isPromotableZeroStoreInst(MachineInstr &MI) { 542 unsigned Opc = MI.getOpcode(); 543 return (Opc == AArch64::STRWui || Opc == AArch64::STURWi || 544 isNarrowStore(Opc)) && 545 getLdStRegOp(MI).getReg() == AArch64::WZR; 546 } 547 548 MachineBasicBlock::iterator 549 AArch64LoadStoreOpt::mergeNarrowZeroStores(MachineBasicBlock::iterator I, 550 MachineBasicBlock::iterator MergeMI, 551 const LdStPairFlags &Flags) { 552 assert(isPromotableZeroStoreInst(*I) && isPromotableZeroStoreInst(*MergeMI) && 553 "Expected promotable zero stores."); 554 555 MachineBasicBlock::iterator NextI = I; 556 ++NextI; 557 // If NextI is the second of the two instructions to be merged, we need 558 // to skip one further. Either way we merge will invalidate the iterator, 559 // and we don't need to scan the new instruction, as it's a pairwise 560 // instruction, which we're not considering for further action anyway. 561 if (NextI == MergeMI) 562 ++NextI; 563 564 unsigned Opc = I->getOpcode(); 565 bool IsScaled = !TII->isUnscaledLdSt(Opc); 566 int OffsetStride = IsScaled ? 1 : getMemScale(*I); 567 568 bool MergeForward = Flags.getMergeForward(); 569 // Insert our new paired instruction after whichever of the paired 570 // instructions MergeForward indicates. 571 MachineBasicBlock::iterator InsertionPoint = MergeForward ? MergeMI : I; 572 // Also based on MergeForward is from where we copy the base register operand 573 // so we get the flags compatible with the input code. 574 const MachineOperand &BaseRegOp = 575 MergeForward ? getLdStBaseOp(*MergeMI) : getLdStBaseOp(*I); 576 577 // Which register is Rt and which is Rt2 depends on the offset order. 578 MachineInstr *RtMI; 579 if (getLdStOffsetOp(*I).getImm() == 580 getLdStOffsetOp(*MergeMI).getImm() + OffsetStride) 581 RtMI = &*MergeMI; 582 else 583 RtMI = &*I; 584 585 int OffsetImm = getLdStOffsetOp(*RtMI).getImm(); 586 // Change the scaled offset from small to large type. 587 if (IsScaled) { 588 assert(((OffsetImm & 1) == 0) && "Unexpected offset to merge"); 589 OffsetImm /= 2; 590 } 591 592 // Construct the new instruction. 593 DebugLoc DL = I->getDebugLoc(); 594 MachineBasicBlock *MBB = I->getParent(); 595 MachineInstrBuilder MIB; 596 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc))) 597 .addReg(isNarrowStore(Opc) ? AArch64::WZR : AArch64::XZR) 598 .addOperand(BaseRegOp) 599 .addImm(OffsetImm) 600 .setMemRefs(I->mergeMemRefsWith(*MergeMI)); 601 (void)MIB; 602 603 DEBUG(dbgs() << "Creating wider store. Replacing instructions:\n "); 604 DEBUG(I->print(dbgs())); 605 DEBUG(dbgs() << " "); 606 DEBUG(MergeMI->print(dbgs())); 607 DEBUG(dbgs() << " with instruction:\n "); 608 DEBUG(((MachineInstr *)MIB)->print(dbgs())); 609 DEBUG(dbgs() << "\n"); 610 611 // Erase the old instructions. 612 I->eraseFromParent(); 613 MergeMI->eraseFromParent(); 614 return NextI; 615 } 616 617 MachineBasicBlock::iterator 618 AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I, 619 MachineBasicBlock::iterator Paired, 620 const LdStPairFlags &Flags) { 621 MachineBasicBlock::iterator NextI = I; 622 ++NextI; 623 // If NextI is the second of the two instructions to be merged, we need 624 // to skip one further. Either way we merge will invalidate the iterator, 625 // and we don't need to scan the new instruction, as it's a pairwise 626 // instruction, which we're not considering for further action anyway. 627 if (NextI == Paired) 628 ++NextI; 629 630 int SExtIdx = Flags.getSExtIdx(); 631 unsigned Opc = 632 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode()); 633 bool IsUnscaled = TII->isUnscaledLdSt(Opc); 634 int OffsetStride = IsUnscaled ? getMemScale(*I) : 1; 635 636 bool MergeForward = Flags.getMergeForward(); 637 // Insert our new paired instruction after whichever of the paired 638 // instructions MergeForward indicates. 639 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I; 640 // Also based on MergeForward is from where we copy the base register operand 641 // so we get the flags compatible with the input code. 642 const MachineOperand &BaseRegOp = 643 MergeForward ? getLdStBaseOp(*Paired) : getLdStBaseOp(*I); 644 645 int Offset = getLdStOffsetOp(*I).getImm(); 646 int PairedOffset = getLdStOffsetOp(*Paired).getImm(); 647 bool PairedIsUnscaled = TII->isUnscaledLdSt(Paired->getOpcode()); 648 if (IsUnscaled != PairedIsUnscaled) { 649 // We're trying to pair instructions that differ in how they are scaled. If 650 // I is scaled then scale the offset of Paired accordingly. Otherwise, do 651 // the opposite (i.e., make Paired's offset unscaled). 652 int MemSize = getMemScale(*Paired); 653 if (PairedIsUnscaled) { 654 // If the unscaled offset isn't a multiple of the MemSize, we can't 655 // pair the operations together. 656 assert(!(PairedOffset % getMemScale(*Paired)) && 657 "Offset should be a multiple of the stride!"); 658 PairedOffset /= MemSize; 659 } else { 660 PairedOffset *= MemSize; 661 } 662 } 663 664 // Which register is Rt and which is Rt2 depends on the offset order. 665 MachineInstr *RtMI, *Rt2MI; 666 if (Offset == PairedOffset + OffsetStride) { 667 RtMI = &*Paired; 668 Rt2MI = &*I; 669 // Here we swapped the assumption made for SExtIdx. 670 // I.e., we turn ldp I, Paired into ldp Paired, I. 671 // Update the index accordingly. 672 if (SExtIdx != -1) 673 SExtIdx = (SExtIdx + 1) % 2; 674 } else { 675 RtMI = &*I; 676 Rt2MI = &*Paired; 677 } 678 int OffsetImm = getLdStOffsetOp(*RtMI).getImm(); 679 // Scale the immediate offset, if necessary. 680 if (TII->isUnscaledLdSt(RtMI->getOpcode())) { 681 assert(!(OffsetImm % getMemScale(*RtMI)) && 682 "Unscaled offset cannot be scaled."); 683 OffsetImm /= getMemScale(*RtMI); 684 } 685 686 // Construct the new instruction. 687 MachineInstrBuilder MIB; 688 DebugLoc DL = I->getDebugLoc(); 689 MachineBasicBlock *MBB = I->getParent(); 690 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingPairOpcode(Opc))) 691 .addOperand(getLdStRegOp(*RtMI)) 692 .addOperand(getLdStRegOp(*Rt2MI)) 693 .addOperand(BaseRegOp) 694 .addImm(OffsetImm) 695 .setMemRefs(I->mergeMemRefsWith(*Paired)); 696 697 (void)MIB; 698 699 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n "); 700 DEBUG(I->print(dbgs())); 701 DEBUG(dbgs() << " "); 702 DEBUG(Paired->print(dbgs())); 703 DEBUG(dbgs() << " with instruction:\n "); 704 if (SExtIdx != -1) { 705 // Generate the sign extension for the proper result of the ldp. 706 // I.e., with X1, that would be: 707 // %W1<def> = KILL %W1, %X1<imp-def> 708 // %X1<def> = SBFMXri %X1<kill>, 0, 31 709 MachineOperand &DstMO = MIB->getOperand(SExtIdx); 710 // Right now, DstMO has the extended register, since it comes from an 711 // extended opcode. 712 unsigned DstRegX = DstMO.getReg(); 713 // Get the W variant of that register. 714 unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32); 715 // Update the result of LDP to use the W instead of the X variant. 716 DstMO.setReg(DstRegW); 717 DEBUG(((MachineInstr *)MIB)->print(dbgs())); 718 DEBUG(dbgs() << "\n"); 719 // Make the machine verifier happy by providing a definition for 720 // the X register. 721 // Insert this definition right after the generated LDP, i.e., before 722 // InsertionPoint. 723 MachineInstrBuilder MIBKill = 724 BuildMI(*MBB, InsertionPoint, DL, TII->get(TargetOpcode::KILL), DstRegW) 725 .addReg(DstRegW) 726 .addReg(DstRegX, RegState::Define); 727 MIBKill->getOperand(2).setImplicit(); 728 // Create the sign extension. 729 MachineInstrBuilder MIBSXTW = 730 BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::SBFMXri), DstRegX) 731 .addReg(DstRegX) 732 .addImm(0) 733 .addImm(31); 734 (void)MIBSXTW; 735 DEBUG(dbgs() << " Extend operand:\n "); 736 DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs())); 737 } else { 738 DEBUG(((MachineInstr *)MIB)->print(dbgs())); 739 } 740 DEBUG(dbgs() << "\n"); 741 742 // Erase the old instructions. 743 I->eraseFromParent(); 744 Paired->eraseFromParent(); 745 746 return NextI; 747 } 748 749 MachineBasicBlock::iterator 750 AArch64LoadStoreOpt::promoteLoadFromStore(MachineBasicBlock::iterator LoadI, 751 MachineBasicBlock::iterator StoreI) { 752 MachineBasicBlock::iterator NextI = LoadI; 753 ++NextI; 754 755 int LoadSize = getMemScale(*LoadI); 756 int StoreSize = getMemScale(*StoreI); 757 unsigned LdRt = getLdStRegOp(*LoadI).getReg(); 758 unsigned StRt = getLdStRegOp(*StoreI).getReg(); 759 bool IsStoreXReg = TRI->getRegClass(AArch64::GPR64RegClassID)->contains(StRt); 760 761 assert((IsStoreXReg || 762 TRI->getRegClass(AArch64::GPR32RegClassID)->contains(StRt)) && 763 "Unexpected RegClass"); 764 765 MachineInstr *BitExtMI; 766 if (LoadSize == StoreSize && (LoadSize == 4 || LoadSize == 8)) { 767 // Remove the load, if the destination register of the loads is the same 768 // register for stored value. 769 if (StRt == LdRt && LoadSize == 8) { 770 DEBUG(dbgs() << "Remove load instruction:\n "); 771 DEBUG(LoadI->print(dbgs())); 772 DEBUG(dbgs() << "\n"); 773 LoadI->eraseFromParent(); 774 return NextI; 775 } 776 // Replace the load with a mov if the load and store are in the same size. 777 BitExtMI = 778 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(), 779 TII->get(IsStoreXReg ? AArch64::ORRXrs : AArch64::ORRWrs), LdRt) 780 .addReg(IsStoreXReg ? AArch64::XZR : AArch64::WZR) 781 .addReg(StRt) 782 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0)); 783 } else { 784 // FIXME: Currently we disable this transformation in big-endian targets as 785 // performance and correctness are verified only in little-endian. 786 if (!Subtarget->isLittleEndian()) 787 return NextI; 788 bool IsUnscaled = TII->isUnscaledLdSt(*LoadI); 789 assert(IsUnscaled == TII->isUnscaledLdSt(*StoreI) && 790 "Unsupported ld/st match"); 791 assert(LoadSize <= StoreSize && "Invalid load size"); 792 int UnscaledLdOffset = IsUnscaled 793 ? getLdStOffsetOp(*LoadI).getImm() 794 : getLdStOffsetOp(*LoadI).getImm() * LoadSize; 795 int UnscaledStOffset = IsUnscaled 796 ? getLdStOffsetOp(*StoreI).getImm() 797 : getLdStOffsetOp(*StoreI).getImm() * StoreSize; 798 int Width = LoadSize * 8; 799 int Immr = 8 * (UnscaledLdOffset - UnscaledStOffset); 800 int Imms = Immr + Width - 1; 801 unsigned DestReg = IsStoreXReg 802 ? TRI->getMatchingSuperReg(LdRt, AArch64::sub_32, 803 &AArch64::GPR64RegClass) 804 : LdRt; 805 806 assert((UnscaledLdOffset >= UnscaledStOffset && 807 (UnscaledLdOffset + LoadSize) <= UnscaledStOffset + StoreSize) && 808 "Invalid offset"); 809 810 Immr = 8 * (UnscaledLdOffset - UnscaledStOffset); 811 Imms = Immr + Width - 1; 812 if (UnscaledLdOffset == UnscaledStOffset) { 813 uint32_t AndMaskEncoded = ((IsStoreXReg ? 1 : 0) << 12) // N 814 | ((Immr) << 6) // immr 815 | ((Imms) << 0) // imms 816 ; 817 818 BitExtMI = 819 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(), 820 TII->get(IsStoreXReg ? AArch64::ANDXri : AArch64::ANDWri), 821 DestReg) 822 .addReg(StRt) 823 .addImm(AndMaskEncoded); 824 } else { 825 BitExtMI = 826 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(), 827 TII->get(IsStoreXReg ? AArch64::UBFMXri : AArch64::UBFMWri), 828 DestReg) 829 .addReg(StRt) 830 .addImm(Immr) 831 .addImm(Imms); 832 } 833 } 834 (void)BitExtMI; 835 836 DEBUG(dbgs() << "Promoting load by replacing :\n "); 837 DEBUG(StoreI->print(dbgs())); 838 DEBUG(dbgs() << " "); 839 DEBUG(LoadI->print(dbgs())); 840 DEBUG(dbgs() << " with instructions:\n "); 841 DEBUG(StoreI->print(dbgs())); 842 DEBUG(dbgs() << " "); 843 DEBUG((BitExtMI)->print(dbgs())); 844 DEBUG(dbgs() << "\n"); 845 846 // Erase the old instructions. 847 LoadI->eraseFromParent(); 848 return NextI; 849 } 850 851 /// trackRegDefsUses - Remember what registers the specified instruction uses 852 /// and modifies. 853 static void trackRegDefsUses(const MachineInstr &MI, BitVector &ModifiedRegs, 854 BitVector &UsedRegs, 855 const TargetRegisterInfo *TRI) { 856 for (const MachineOperand &MO : MI.operands()) { 857 if (MO.isRegMask()) 858 ModifiedRegs.setBitsNotInMask(MO.getRegMask()); 859 860 if (!MO.isReg()) 861 continue; 862 unsigned Reg = MO.getReg(); 863 if (!Reg) 864 continue; 865 if (MO.isDef()) { 866 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) 867 ModifiedRegs.set(*AI); 868 } else { 869 assert(MO.isUse() && "Reg operand not a def and not a use?!?"); 870 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) 871 UsedRegs.set(*AI); 872 } 873 } 874 } 875 876 static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) { 877 // Convert the byte-offset used by unscaled into an "element" offset used 878 // by the scaled pair load/store instructions. 879 if (IsUnscaled) { 880 // If the byte-offset isn't a multiple of the stride, there's no point 881 // trying to match it. 882 if (Offset % OffsetStride) 883 return false; 884 Offset /= OffsetStride; 885 } 886 return Offset <= 63 && Offset >= -64; 887 } 888 889 // Do alignment, specialized to power of 2 and for signed ints, 890 // avoiding having to do a C-style cast from uint_64t to int when 891 // using alignTo from include/llvm/Support/MathExtras.h. 892 // FIXME: Move this function to include/MathExtras.h? 893 static int alignTo(int Num, int PowOf2) { 894 return (Num + PowOf2 - 1) & ~(PowOf2 - 1); 895 } 896 897 static bool mayAlias(MachineInstr &MIa, MachineInstr &MIb, 898 const AArch64InstrInfo *TII) { 899 // One of the instructions must modify memory. 900 if (!MIa.mayStore() && !MIb.mayStore()) 901 return false; 902 903 // Both instructions must be memory operations. 904 if (!MIa.mayLoadOrStore() && !MIb.mayLoadOrStore()) 905 return false; 906 907 return !TII->areMemAccessesTriviallyDisjoint(MIa, MIb); 908 } 909 910 static bool mayAlias(MachineInstr &MIa, 911 SmallVectorImpl<MachineInstr *> &MemInsns, 912 const AArch64InstrInfo *TII) { 913 for (MachineInstr *MIb : MemInsns) 914 if (mayAlias(MIa, *MIb, TII)) 915 return true; 916 917 return false; 918 } 919 920 bool AArch64LoadStoreOpt::findMatchingStore( 921 MachineBasicBlock::iterator I, unsigned Limit, 922 MachineBasicBlock::iterator &StoreI) { 923 MachineBasicBlock::iterator B = I->getParent()->begin(); 924 MachineBasicBlock::iterator MBBI = I; 925 MachineInstr &LoadMI = *I; 926 unsigned BaseReg = getLdStBaseOp(LoadMI).getReg(); 927 928 // If the load is the first instruction in the block, there's obviously 929 // not any matching store. 930 if (MBBI == B) 931 return false; 932 933 // Track which registers have been modified and used between the first insn 934 // and the second insn. 935 ModifiedRegs.reset(); 936 UsedRegs.reset(); 937 938 unsigned Count = 0; 939 do { 940 --MBBI; 941 MachineInstr &MI = *MBBI; 942 943 // Don't count transient instructions towards the search limit since there 944 // may be different numbers of them if e.g. debug information is present. 945 if (!MI.isTransient()) 946 ++Count; 947 948 // If the load instruction reads directly from the address to which the 949 // store instruction writes and the stored value is not modified, we can 950 // promote the load. Since we do not handle stores with pre-/post-index, 951 // it's unnecessary to check if BaseReg is modified by the store itself. 952 if (MI.mayStore() && isMatchingStore(LoadMI, MI) && 953 BaseReg == getLdStBaseOp(MI).getReg() && 954 isLdOffsetInRangeOfSt(LoadMI, MI, TII) && 955 !ModifiedRegs[getLdStRegOp(MI).getReg()]) { 956 StoreI = MBBI; 957 return true; 958 } 959 960 if (MI.isCall()) 961 return false; 962 963 // Update modified / uses register lists. 964 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI); 965 966 // Otherwise, if the base register is modified, we have no match, so 967 // return early. 968 if (ModifiedRegs[BaseReg]) 969 return false; 970 971 // If we encounter a store aliased with the load, return early. 972 if (MI.mayStore() && mayAlias(LoadMI, MI, TII)) 973 return false; 974 } while (MBBI != B && Count < Limit); 975 return false; 976 } 977 978 // Returns true if FirstMI and MI are candidates for merging or pairing. 979 // Otherwise, returns false. 980 static bool areCandidatesToMergeOrPair(MachineInstr &FirstMI, MachineInstr &MI, 981 LdStPairFlags &Flags, 982 const AArch64InstrInfo *TII) { 983 // If this is volatile or if pairing is suppressed, not a candidate. 984 if (MI.hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI)) 985 return false; 986 987 // We should have already checked FirstMI for pair suppression and volatility. 988 assert(!FirstMI.hasOrderedMemoryRef() && 989 !TII->isLdStPairSuppressed(FirstMI) && 990 "FirstMI shouldn't get here if either of these checks are true."); 991 992 unsigned OpcA = FirstMI.getOpcode(); 993 unsigned OpcB = MI.getOpcode(); 994 995 // Opcodes match: nothing more to check. 996 if (OpcA == OpcB) 997 return true; 998 999 // Try to match a sign-extended load/store with a zero-extended load/store. 1000 bool IsValidLdStrOpc, PairIsValidLdStrOpc; 1001 unsigned NonSExtOpc = getMatchingNonSExtOpcode(OpcA, &IsValidLdStrOpc); 1002 assert(IsValidLdStrOpc && 1003 "Given Opc should be a Load or Store with an immediate"); 1004 // OpcA will be the first instruction in the pair. 1005 if (NonSExtOpc == getMatchingNonSExtOpcode(OpcB, &PairIsValidLdStrOpc)) { 1006 Flags.setSExtIdx(NonSExtOpc == (unsigned)OpcA ? 1 : 0); 1007 return true; 1008 } 1009 1010 // If the second instruction isn't even a mergable/pairable load/store, bail 1011 // out. 1012 if (!PairIsValidLdStrOpc) 1013 return false; 1014 1015 // FIXME: We don't support merging narrow stores with mixed scaled/unscaled 1016 // offsets. 1017 if (isNarrowStore(OpcA) || isNarrowStore(OpcB)) 1018 return false; 1019 1020 // Try to match an unscaled load/store with a scaled load/store. 1021 return TII->isUnscaledLdSt(OpcA) != TII->isUnscaledLdSt(OpcB) && 1022 getMatchingPairOpcode(OpcA) == getMatchingPairOpcode(OpcB); 1023 1024 // FIXME: Can we also match a mixed sext/zext unscaled/scaled pair? 1025 } 1026 1027 /// Scan the instructions looking for a load/store that can be combined with the 1028 /// current instruction into a wider equivalent or a load/store pair. 1029 MachineBasicBlock::iterator 1030 AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I, 1031 LdStPairFlags &Flags, unsigned Limit, 1032 bool FindNarrowMerge) { 1033 MachineBasicBlock::iterator E = I->getParent()->end(); 1034 MachineBasicBlock::iterator MBBI = I; 1035 MachineInstr &FirstMI = *I; 1036 ++MBBI; 1037 1038 bool MayLoad = FirstMI.mayLoad(); 1039 bool IsUnscaled = TII->isUnscaledLdSt(FirstMI); 1040 unsigned Reg = getLdStRegOp(FirstMI).getReg(); 1041 unsigned BaseReg = getLdStBaseOp(FirstMI).getReg(); 1042 int Offset = getLdStOffsetOp(FirstMI).getImm(); 1043 int OffsetStride = IsUnscaled ? getMemScale(FirstMI) : 1; 1044 bool IsPromotableZeroStore = isPromotableZeroStoreInst(FirstMI); 1045 1046 // Track which registers have been modified and used between the first insn 1047 // (inclusive) and the second insn. 1048 ModifiedRegs.reset(); 1049 UsedRegs.reset(); 1050 1051 // Remember any instructions that read/write memory between FirstMI and MI. 1052 SmallVector<MachineInstr *, 4> MemInsns; 1053 1054 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) { 1055 MachineInstr &MI = *MBBI; 1056 1057 // Don't count transient instructions towards the search limit since there 1058 // may be different numbers of them if e.g. debug information is present. 1059 if (!MI.isTransient()) 1060 ++Count; 1061 1062 Flags.setSExtIdx(-1); 1063 if (areCandidatesToMergeOrPair(FirstMI, MI, Flags, TII) && 1064 getLdStOffsetOp(MI).isImm()) { 1065 assert(MI.mayLoadOrStore() && "Expected memory operation."); 1066 // If we've found another instruction with the same opcode, check to see 1067 // if the base and offset are compatible with our starting instruction. 1068 // These instructions all have scaled immediate operands, so we just 1069 // check for +1/-1. Make sure to check the new instruction offset is 1070 // actually an immediate and not a symbolic reference destined for 1071 // a relocation. 1072 unsigned MIBaseReg = getLdStBaseOp(MI).getReg(); 1073 int MIOffset = getLdStOffsetOp(MI).getImm(); 1074 bool MIIsUnscaled = TII->isUnscaledLdSt(MI); 1075 if (IsUnscaled != MIIsUnscaled) { 1076 // We're trying to pair instructions that differ in how they are scaled. 1077 // If FirstMI is scaled then scale the offset of MI accordingly. 1078 // Otherwise, do the opposite (i.e., make MI's offset unscaled). 1079 int MemSize = getMemScale(MI); 1080 if (MIIsUnscaled) { 1081 // If the unscaled offset isn't a multiple of the MemSize, we can't 1082 // pair the operations together: bail and keep looking. 1083 if (MIOffset % MemSize) { 1084 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI); 1085 MemInsns.push_back(&MI); 1086 continue; 1087 } 1088 MIOffset /= MemSize; 1089 } else { 1090 MIOffset *= MemSize; 1091 } 1092 } 1093 1094 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) || 1095 (Offset + OffsetStride == MIOffset))) { 1096 int MinOffset = Offset < MIOffset ? Offset : MIOffset; 1097 if (FindNarrowMerge) { 1098 // If the alignment requirements of the scaled wide load/store 1099 // instruction can't express the offset of the scaled narrow input, 1100 // bail and keep looking. For promotable zero stores, allow only when 1101 // the stored value is the same (i.e., WZR). 1102 if ((!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) || 1103 (IsPromotableZeroStore && Reg != getLdStRegOp(MI).getReg())) { 1104 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI); 1105 MemInsns.push_back(&MI); 1106 continue; 1107 } 1108 } else { 1109 // Pairwise instructions have a 7-bit signed offset field. Single 1110 // insns have a 12-bit unsigned offset field. If the resultant 1111 // immediate offset of merging these instructions is out of range for 1112 // a pairwise instruction, bail and keep looking. 1113 if (!inBoundsForPair(IsUnscaled, MinOffset, OffsetStride)) { 1114 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI); 1115 MemInsns.push_back(&MI); 1116 continue; 1117 } 1118 // If the alignment requirements of the paired (scaled) instruction 1119 // can't express the offset of the unscaled input, bail and keep 1120 // looking. 1121 if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) { 1122 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI); 1123 MemInsns.push_back(&MI); 1124 continue; 1125 } 1126 } 1127 // If the destination register of the loads is the same register, bail 1128 // and keep looking. A load-pair instruction with both destination 1129 // registers the same is UNPREDICTABLE and will result in an exception. 1130 if (MayLoad && Reg == getLdStRegOp(MI).getReg()) { 1131 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI); 1132 MemInsns.push_back(&MI); 1133 continue; 1134 } 1135 1136 // If the Rt of the second instruction was not modified or used between 1137 // the two instructions and none of the instructions between the second 1138 // and first alias with the second, we can combine the second into the 1139 // first. 1140 if (!ModifiedRegs[getLdStRegOp(MI).getReg()] && 1141 !(MI.mayLoad() && UsedRegs[getLdStRegOp(MI).getReg()]) && 1142 !mayAlias(MI, MemInsns, TII)) { 1143 Flags.setMergeForward(false); 1144 return MBBI; 1145 } 1146 1147 // Likewise, if the Rt of the first instruction is not modified or used 1148 // between the two instructions and none of the instructions between the 1149 // first and the second alias with the first, we can combine the first 1150 // into the second. 1151 if (!ModifiedRegs[getLdStRegOp(FirstMI).getReg()] && 1152 !(MayLoad && UsedRegs[getLdStRegOp(FirstMI).getReg()]) && 1153 !mayAlias(FirstMI, MemInsns, TII)) { 1154 Flags.setMergeForward(true); 1155 return MBBI; 1156 } 1157 // Unable to combine these instructions due to interference in between. 1158 // Keep looking. 1159 } 1160 } 1161 1162 // If the instruction wasn't a matching load or store. Stop searching if we 1163 // encounter a call instruction that might modify memory. 1164 if (MI.isCall()) 1165 return E; 1166 1167 // Update modified / uses register lists. 1168 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI); 1169 1170 // Otherwise, if the base register is modified, we have no match, so 1171 // return early. 1172 if (ModifiedRegs[BaseReg]) 1173 return E; 1174 1175 // Update list of instructions that read/write memory. 1176 if (MI.mayLoadOrStore()) 1177 MemInsns.push_back(&MI); 1178 } 1179 return E; 1180 } 1181 1182 MachineBasicBlock::iterator 1183 AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I, 1184 MachineBasicBlock::iterator Update, 1185 bool IsPreIdx) { 1186 assert((Update->getOpcode() == AArch64::ADDXri || 1187 Update->getOpcode() == AArch64::SUBXri) && 1188 "Unexpected base register update instruction to merge!"); 1189 MachineBasicBlock::iterator NextI = I; 1190 // Return the instruction following the merged instruction, which is 1191 // the instruction following our unmerged load. Unless that's the add/sub 1192 // instruction we're merging, in which case it's the one after that. 1193 if (++NextI == Update) 1194 ++NextI; 1195 1196 int Value = Update->getOperand(2).getImm(); 1197 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 && 1198 "Can't merge 1 << 12 offset into pre-/post-indexed load / store"); 1199 if (Update->getOpcode() == AArch64::SUBXri) 1200 Value = -Value; 1201 1202 unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode()) 1203 : getPostIndexedOpcode(I->getOpcode()); 1204 MachineInstrBuilder MIB; 1205 if (!isPairedLdSt(*I)) { 1206 // Non-paired instruction. 1207 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc)) 1208 .addOperand(getLdStRegOp(*Update)) 1209 .addOperand(getLdStRegOp(*I)) 1210 .addOperand(getLdStBaseOp(*I)) 1211 .addImm(Value) 1212 .setMemRefs(I->memoperands_begin(), I->memoperands_end()); 1213 } else { 1214 // Paired instruction. 1215 int Scale = getMemScale(*I); 1216 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc)) 1217 .addOperand(getLdStRegOp(*Update)) 1218 .addOperand(getLdStRegOp(*I, 0)) 1219 .addOperand(getLdStRegOp(*I, 1)) 1220 .addOperand(getLdStBaseOp(*I)) 1221 .addImm(Value / Scale) 1222 .setMemRefs(I->memoperands_begin(), I->memoperands_end()); 1223 } 1224 (void)MIB; 1225 1226 if (IsPreIdx) 1227 DEBUG(dbgs() << "Creating pre-indexed load/store."); 1228 else 1229 DEBUG(dbgs() << "Creating post-indexed load/store."); 1230 DEBUG(dbgs() << " Replacing instructions:\n "); 1231 DEBUG(I->print(dbgs())); 1232 DEBUG(dbgs() << " "); 1233 DEBUG(Update->print(dbgs())); 1234 DEBUG(dbgs() << " with instruction:\n "); 1235 DEBUG(((MachineInstr *)MIB)->print(dbgs())); 1236 DEBUG(dbgs() << "\n"); 1237 1238 // Erase the old instructions for the block. 1239 I->eraseFromParent(); 1240 Update->eraseFromParent(); 1241 1242 return NextI; 1243 } 1244 1245 bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr &MemMI, 1246 MachineInstr &MI, 1247 unsigned BaseReg, int Offset) { 1248 switch (MI.getOpcode()) { 1249 default: 1250 break; 1251 case AArch64::SUBXri: 1252 case AArch64::ADDXri: 1253 // Make sure it's a vanilla immediate operand, not a relocation or 1254 // anything else we can't handle. 1255 if (!MI.getOperand(2).isImm()) 1256 break; 1257 // Watch out for 1 << 12 shifted value. 1258 if (AArch64_AM::getShiftValue(MI.getOperand(3).getImm())) 1259 break; 1260 1261 // The update instruction source and destination register must be the 1262 // same as the load/store base register. 1263 if (MI.getOperand(0).getReg() != BaseReg || 1264 MI.getOperand(1).getReg() != BaseReg) 1265 break; 1266 1267 bool IsPairedInsn = isPairedLdSt(MemMI); 1268 int UpdateOffset = MI.getOperand(2).getImm(); 1269 if (MI.getOpcode() == AArch64::SUBXri) 1270 UpdateOffset = -UpdateOffset; 1271 1272 // For non-paired load/store instructions, the immediate must fit in a 1273 // signed 9-bit integer. 1274 if (!IsPairedInsn && (UpdateOffset > 255 || UpdateOffset < -256)) 1275 break; 1276 1277 // For paired load/store instructions, the immediate must be a multiple of 1278 // the scaling factor. The scaled offset must also fit into a signed 7-bit 1279 // integer. 1280 if (IsPairedInsn) { 1281 int Scale = getMemScale(MemMI); 1282 if (UpdateOffset % Scale != 0) 1283 break; 1284 1285 int ScaledOffset = UpdateOffset / Scale; 1286 if (ScaledOffset > 63 || ScaledOffset < -64) 1287 break; 1288 } 1289 1290 // If we have a non-zero Offset, we check that it matches the amount 1291 // we're adding to the register. 1292 if (!Offset || Offset == UpdateOffset) 1293 return true; 1294 break; 1295 } 1296 return false; 1297 } 1298 1299 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward( 1300 MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) { 1301 MachineBasicBlock::iterator E = I->getParent()->end(); 1302 MachineInstr &MemMI = *I; 1303 MachineBasicBlock::iterator MBBI = I; 1304 1305 unsigned BaseReg = getLdStBaseOp(MemMI).getReg(); 1306 int MIUnscaledOffset = getLdStOffsetOp(MemMI).getImm() * getMemScale(MemMI); 1307 1308 // Scan forward looking for post-index opportunities. Updating instructions 1309 // can't be formed if the memory instruction doesn't have the offset we're 1310 // looking for. 1311 if (MIUnscaledOffset != UnscaledOffset) 1312 return E; 1313 1314 // If the base register overlaps a destination register, we can't 1315 // merge the update. 1316 bool IsPairedInsn = isPairedLdSt(MemMI); 1317 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) { 1318 unsigned DestReg = getLdStRegOp(MemMI, i).getReg(); 1319 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg)) 1320 return E; 1321 } 1322 1323 // Track which registers have been modified and used between the first insn 1324 // (inclusive) and the second insn. 1325 ModifiedRegs.reset(); 1326 UsedRegs.reset(); 1327 ++MBBI; 1328 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) { 1329 MachineInstr &MI = *MBBI; 1330 1331 // Don't count transient instructions towards the search limit since there 1332 // may be different numbers of them if e.g. debug information is present. 1333 if (!MI.isTransient()) 1334 ++Count; 1335 1336 // If we found a match, return it. 1337 if (isMatchingUpdateInsn(*I, MI, BaseReg, UnscaledOffset)) 1338 return MBBI; 1339 1340 // Update the status of what the instruction clobbered and used. 1341 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI); 1342 1343 // Otherwise, if the base register is used or modified, we have no match, so 1344 // return early. 1345 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg]) 1346 return E; 1347 } 1348 return E; 1349 } 1350 1351 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward( 1352 MachineBasicBlock::iterator I, unsigned Limit) { 1353 MachineBasicBlock::iterator B = I->getParent()->begin(); 1354 MachineBasicBlock::iterator E = I->getParent()->end(); 1355 MachineInstr &MemMI = *I; 1356 MachineBasicBlock::iterator MBBI = I; 1357 1358 unsigned BaseReg = getLdStBaseOp(MemMI).getReg(); 1359 int Offset = getLdStOffsetOp(MemMI).getImm(); 1360 1361 // If the load/store is the first instruction in the block, there's obviously 1362 // not any matching update. Ditto if the memory offset isn't zero. 1363 if (MBBI == B || Offset != 0) 1364 return E; 1365 // If the base register overlaps a destination register, we can't 1366 // merge the update. 1367 bool IsPairedInsn = isPairedLdSt(MemMI); 1368 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) { 1369 unsigned DestReg = getLdStRegOp(MemMI, i).getReg(); 1370 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg)) 1371 return E; 1372 } 1373 1374 // Track which registers have been modified and used between the first insn 1375 // (inclusive) and the second insn. 1376 ModifiedRegs.reset(); 1377 UsedRegs.reset(); 1378 unsigned Count = 0; 1379 do { 1380 --MBBI; 1381 MachineInstr &MI = *MBBI; 1382 1383 // Don't count transient instructions towards the search limit since there 1384 // may be different numbers of them if e.g. debug information is present. 1385 if (!MI.isTransient()) 1386 ++Count; 1387 1388 // If we found a match, return it. 1389 if (isMatchingUpdateInsn(*I, MI, BaseReg, Offset)) 1390 return MBBI; 1391 1392 // Update the status of what the instruction clobbered and used. 1393 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI); 1394 1395 // Otherwise, if the base register is used or modified, we have no match, so 1396 // return early. 1397 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg]) 1398 return E; 1399 } while (MBBI != B && Count < Limit); 1400 return E; 1401 } 1402 1403 bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore( 1404 MachineBasicBlock::iterator &MBBI) { 1405 MachineInstr &MI = *MBBI; 1406 // If this is a volatile load, don't mess with it. 1407 if (MI.hasOrderedMemoryRef()) 1408 return false; 1409 1410 // Make sure this is a reg+imm. 1411 // FIXME: It is possible to extend it to handle reg+reg cases. 1412 if (!getLdStOffsetOp(MI).isImm()) 1413 return false; 1414 1415 // Look backward up to LdStLimit instructions. 1416 MachineBasicBlock::iterator StoreI; 1417 if (findMatchingStore(MBBI, LdStLimit, StoreI)) { 1418 ++NumLoadsFromStoresPromoted; 1419 // Promote the load. Keeping the iterator straight is a 1420 // pain, so we let the merge routine tell us what the next instruction 1421 // is after it's done mucking about. 1422 MBBI = promoteLoadFromStore(MBBI, StoreI); 1423 return true; 1424 } 1425 return false; 1426 } 1427 1428 // Merge adjacent zero stores into a wider store. 1429 bool AArch64LoadStoreOpt::tryToMergeZeroStInst( 1430 MachineBasicBlock::iterator &MBBI) { 1431 assert(isPromotableZeroStoreInst(*MBBI) && "Expected narrow store."); 1432 MachineInstr &MI = *MBBI; 1433 MachineBasicBlock::iterator E = MI.getParent()->end(); 1434 1435 if (!TII->isCandidateToMergeOrPair(MI)) 1436 return false; 1437 1438 // Look ahead up to LdStLimit instructions for a mergable instruction. 1439 LdStPairFlags Flags; 1440 MachineBasicBlock::iterator MergeMI = 1441 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ true); 1442 if (MergeMI != E) { 1443 ++NumZeroStoresPromoted; 1444 1445 // Keeping the iterator straight is a pain, so we let the merge routine tell 1446 // us what the next instruction is after it's done mucking about. 1447 MBBI = mergeNarrowZeroStores(MBBI, MergeMI, Flags); 1448 return true; 1449 } 1450 return false; 1451 } 1452 1453 // Find loads and stores that can be merged into a single load or store pair 1454 // instruction. 1455 bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) { 1456 MachineInstr &MI = *MBBI; 1457 MachineBasicBlock::iterator E = MI.getParent()->end(); 1458 1459 if (!TII->isCandidateToMergeOrPair(MI)) 1460 return false; 1461 1462 // Early exit if the offset is not possible to match. (6 bits of positive 1463 // range, plus allow an extra one in case we find a later insn that matches 1464 // with Offset-1) 1465 bool IsUnscaled = TII->isUnscaledLdSt(MI); 1466 int Offset = getLdStOffsetOp(MI).getImm(); 1467 int OffsetStride = IsUnscaled ? getMemScale(MI) : 1; 1468 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride)) 1469 return false; 1470 1471 // Look ahead up to LdStLimit instructions for a pairable instruction. 1472 LdStPairFlags Flags; 1473 MachineBasicBlock::iterator Paired = 1474 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ false); 1475 if (Paired != E) { 1476 ++NumPairCreated; 1477 if (TII->isUnscaledLdSt(MI)) 1478 ++NumUnscaledPairCreated; 1479 // Keeping the iterator straight is a pain, so we let the merge routine tell 1480 // us what the next instruction is after it's done mucking about. 1481 MBBI = mergePairedInsns(MBBI, Paired, Flags); 1482 return true; 1483 } 1484 return false; 1485 } 1486 1487 bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB, 1488 bool EnableNarrowZeroStOpt) { 1489 bool Modified = false; 1490 // Four tranformations to do here: 1491 // 1) Find loads that directly read from stores and promote them by 1492 // replacing with mov instructions. If the store is wider than the load, 1493 // the load will be replaced with a bitfield extract. 1494 // e.g., 1495 // str w1, [x0, #4] 1496 // ldrh w2, [x0, #6] 1497 // ; becomes 1498 // str w1, [x0, #4] 1499 // lsr w2, w1, #16 1500 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end(); 1501 MBBI != E;) { 1502 MachineInstr &MI = *MBBI; 1503 switch (MI.getOpcode()) { 1504 default: 1505 // Just move on to the next instruction. 1506 ++MBBI; 1507 break; 1508 // Scaled instructions. 1509 case AArch64::LDRBBui: 1510 case AArch64::LDRHHui: 1511 case AArch64::LDRWui: 1512 case AArch64::LDRXui: 1513 // Unscaled instructions. 1514 case AArch64::LDURBBi: 1515 case AArch64::LDURHHi: 1516 case AArch64::LDURWi: 1517 case AArch64::LDURXi: { 1518 if (tryToPromoteLoadFromStore(MBBI)) { 1519 Modified = true; 1520 break; 1521 } 1522 ++MBBI; 1523 break; 1524 } 1525 } 1526 } 1527 // 2) Merge adjacent zero stores into a wider store. 1528 // e.g., 1529 // strh wzr, [x0] 1530 // strh wzr, [x0, #2] 1531 // ; becomes 1532 // str wzr, [x0] 1533 // e.g., 1534 // str wzr, [x0] 1535 // str wzr, [x0, #4] 1536 // ; becomes 1537 // str xzr, [x0] 1538 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end(); 1539 EnableNarrowZeroStOpt && MBBI != E;) { 1540 if (isPromotableZeroStoreInst(*MBBI)) { 1541 if (tryToMergeZeroStInst(MBBI)) { 1542 Modified = true; 1543 } else 1544 ++MBBI; 1545 } else 1546 ++MBBI; 1547 } 1548 1549 // 3) Find loads and stores that can be merged into a single load or store 1550 // pair instruction. 1551 // e.g., 1552 // ldr x0, [x2] 1553 // ldr x1, [x2, #8] 1554 // ; becomes 1555 // ldp x0, x1, [x2] 1556 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end(); 1557 MBBI != E;) { 1558 if (TII->isPairableLdStInst(*MBBI) && tryToPairLdStInst(MBBI)) 1559 Modified = true; 1560 else 1561 ++MBBI; 1562 } 1563 // 4) Find base register updates that can be merged into the load or store 1564 // as a base-reg writeback. 1565 // e.g., 1566 // ldr x0, [x2] 1567 // add x2, x2, #4 1568 // ; becomes 1569 // ldr x0, [x2], #4 1570 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end(); 1571 MBBI != E;) { 1572 MachineInstr &MI = *MBBI; 1573 // Do update merging. It's simpler to keep this separate from the above 1574 // switchs, though not strictly necessary. 1575 unsigned Opc = MI.getOpcode(); 1576 switch (Opc) { 1577 default: 1578 // Just move on to the next instruction. 1579 ++MBBI; 1580 break; 1581 // Scaled instructions. 1582 case AArch64::STRSui: 1583 case AArch64::STRDui: 1584 case AArch64::STRQui: 1585 case AArch64::STRXui: 1586 case AArch64::STRWui: 1587 case AArch64::STRHHui: 1588 case AArch64::STRBBui: 1589 case AArch64::LDRSui: 1590 case AArch64::LDRDui: 1591 case AArch64::LDRQui: 1592 case AArch64::LDRXui: 1593 case AArch64::LDRWui: 1594 case AArch64::LDRHHui: 1595 case AArch64::LDRBBui: 1596 // Unscaled instructions. 1597 case AArch64::STURSi: 1598 case AArch64::STURDi: 1599 case AArch64::STURQi: 1600 case AArch64::STURWi: 1601 case AArch64::STURXi: 1602 case AArch64::LDURSi: 1603 case AArch64::LDURDi: 1604 case AArch64::LDURQi: 1605 case AArch64::LDURWi: 1606 case AArch64::LDURXi: 1607 // Paired instructions. 1608 case AArch64::LDPSi: 1609 case AArch64::LDPSWi: 1610 case AArch64::LDPDi: 1611 case AArch64::LDPQi: 1612 case AArch64::LDPWi: 1613 case AArch64::LDPXi: 1614 case AArch64::STPSi: 1615 case AArch64::STPDi: 1616 case AArch64::STPQi: 1617 case AArch64::STPWi: 1618 case AArch64::STPXi: { 1619 // Make sure this is a reg+imm (as opposed to an address reloc). 1620 if (!getLdStOffsetOp(MI).isImm()) { 1621 ++MBBI; 1622 break; 1623 } 1624 // Look forward to try to form a post-index instruction. For example, 1625 // ldr x0, [x20] 1626 // add x20, x20, #32 1627 // merged into: 1628 // ldr x0, [x20], #32 1629 MachineBasicBlock::iterator Update = 1630 findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit); 1631 if (Update != E) { 1632 // Merge the update into the ld/st. 1633 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false); 1634 Modified = true; 1635 ++NumPostFolded; 1636 break; 1637 } 1638 // Don't know how to handle pre/post-index versions, so move to the next 1639 // instruction. 1640 if (TII->isUnscaledLdSt(Opc)) { 1641 ++MBBI; 1642 break; 1643 } 1644 1645 // Look back to try to find a pre-index instruction. For example, 1646 // add x0, x0, #8 1647 // ldr x1, [x0] 1648 // merged into: 1649 // ldr x1, [x0, #8]! 1650 Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit); 1651 if (Update != E) { 1652 // Merge the update into the ld/st. 1653 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true); 1654 Modified = true; 1655 ++NumPreFolded; 1656 break; 1657 } 1658 // The immediate in the load/store is scaled by the size of the memory 1659 // operation. The immediate in the add we're looking for, 1660 // however, is not, so adjust here. 1661 int UnscaledOffset = getLdStOffsetOp(MI).getImm() * getMemScale(MI); 1662 1663 // Look forward to try to find a post-index instruction. For example, 1664 // ldr x1, [x0, #64] 1665 // add x0, x0, #64 1666 // merged into: 1667 // ldr x1, [x0, #64]! 1668 Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit); 1669 if (Update != E) { 1670 // Merge the update into the ld/st. 1671 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true); 1672 Modified = true; 1673 ++NumPreFolded; 1674 break; 1675 } 1676 1677 // Nothing found. Just move to the next instruction. 1678 ++MBBI; 1679 break; 1680 } 1681 } 1682 } 1683 1684 return Modified; 1685 } 1686 1687 bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) { 1688 if (skipFunction(*Fn.getFunction())) 1689 return false; 1690 1691 Subtarget = &static_cast<const AArch64Subtarget &>(Fn.getSubtarget()); 1692 TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo()); 1693 TRI = Subtarget->getRegisterInfo(); 1694 1695 // Resize the modified and used register bitfield trackers. We do this once 1696 // per function and then clear the bitfield each time we optimize a load or 1697 // store. 1698 ModifiedRegs.resize(TRI->getNumRegs()); 1699 UsedRegs.resize(TRI->getNumRegs()); 1700 1701 bool Modified = false; 1702 bool enableNarrowZeroStOpt = !Subtarget->requiresStrictAlign(); 1703 for (auto &MBB : Fn) 1704 Modified |= optimizeBlock(MBB, enableNarrowZeroStOpt); 1705 1706 return Modified; 1707 } 1708 1709 // FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep loads and 1710 // stores near one another? Note: The pre-RA instruction scheduler already has 1711 // hooks to try and schedule pairable loads/stores together to improve pairing 1712 // opportunities. Thus, pre-RA pairing pass may not be worth the effort. 1713 1714 // FIXME: When pairing store instructions it's very possible for this pass to 1715 // hoist a store with a KILL marker above another use (without a KILL marker). 1716 // The resulting IR is invalid, but nothing uses the KILL markers after this 1717 // pass, so it's never caused a problem in practice. 1718 1719 /// createAArch64LoadStoreOptimizationPass - returns an instance of the 1720 /// load / store optimization pass. 1721 FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() { 1722 return new AArch64LoadStoreOpt(); 1723 } 1724