1 //=- AArch64LoadStoreOptimizer.cpp - AArch64 load/store opt. pass -*- C++ -*-=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a pass that performs load / store related peephole
11 // optimizations. This pass should be run after register allocation.
13 //===----------------------------------------------------------------------===//
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/ADT/StringRef.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineOperand.h"
29 #include "llvm/IR/DebugLoc.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetRegisterInfo.h"
44 #define DEBUG_TYPE "aarch64-ldst-opt"
46 STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
47 STATISTIC(NumPostFolded, "Number of post-index updates folded");
48 STATISTIC(NumPreFolded, "Number of pre-index updates folded");
49 STATISTIC(NumUnscaledPairCreated,
50 "Number of load/store from unscaled generated");
51 STATISTIC(NumZeroStoresPromoted, "Number of narrow zero stores promoted");
52 STATISTIC(NumLoadsFromStoresPromoted, "Number of loads from stores promoted");
54 // The LdStLimit limits how far we search for load/store pairs.
55 static cl::opt<unsigned> LdStLimit("aarch64-load-store-scan-limit",
56 cl::init(20), cl::Hidden);
58 // The UpdateLimit limits how far we search for update instructions when we form
59 // pre-/post-index instructions.
60 static cl::opt<unsigned> UpdateLimit("aarch64-update-scan-limit", cl::init(100),
63 #define AARCH64_LOAD_STORE_OPT_NAME "AArch64 load / store optimization pass"
67 typedef struct LdStPairFlags {
68 // If a matching instruction is found, MergeForward is set to true if the
69 // merge is to remove the first instruction and replace the second with
70 // a pair-wise insn, and false if the reverse is true.
71 bool MergeForward = false;
73 // SExtIdx gives the index of the result of the load pair that must be
74 // extended. The value of SExtIdx assumes that the paired load produces the
75 // value in this order: (I, returned iterator), i.e., -1 means no value has
76 // to be extended, 0 means I, and 1 means the returned iterator.
79 LdStPairFlags() = default;
81 void setMergeForward(bool V = true) { MergeForward = V; }
82 bool getMergeForward() const { return MergeForward; }
84 void setSExtIdx(int V) { SExtIdx = V; }
85 int getSExtIdx() const { return SExtIdx; }
89 struct AArch64LoadStoreOpt : public MachineFunctionPass {
92 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {
93 initializeAArch64LoadStoreOptPass(*PassRegistry::getPassRegistry());
97 const AArch64InstrInfo *TII;
98 const TargetRegisterInfo *TRI;
99 const AArch64Subtarget *Subtarget;
101 // Track which registers have been modified and used.
102 BitVector ModifiedRegs, UsedRegs;
104 virtual void getAnalysisUsage(AnalysisUsage &AU) const override {
105 AU.addRequired<AAResultsWrapperPass>();
106 MachineFunctionPass::getAnalysisUsage(AU);
109 // Scan the instructions looking for a load/store that can be combined
110 // with the current instruction into a load/store pair.
111 // Return the matching instruction if one is found, else MBB->end().
112 MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
113 LdStPairFlags &Flags,
115 bool FindNarrowMerge);
117 // Scan the instructions looking for a store that writes to the address from
118 // which the current load instruction reads. Return true if one is found.
119 bool findMatchingStore(MachineBasicBlock::iterator I, unsigned Limit,
120 MachineBasicBlock::iterator &StoreI);
122 // Merge the two instructions indicated into a wider narrow store instruction.
123 MachineBasicBlock::iterator
124 mergeNarrowZeroStores(MachineBasicBlock::iterator I,
125 MachineBasicBlock::iterator MergeMI,
126 const LdStPairFlags &Flags);
128 // Merge the two instructions indicated into a single pair-wise instruction.
129 MachineBasicBlock::iterator
130 mergePairedInsns(MachineBasicBlock::iterator I,
131 MachineBasicBlock::iterator Paired,
132 const LdStPairFlags &Flags);
134 // Promote the load that reads directly from the address stored to.
135 MachineBasicBlock::iterator
136 promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
137 MachineBasicBlock::iterator StoreI);
139 // Scan the instruction list to find a base register update that can
140 // be combined with the current instruction (a load or store) using
141 // pre or post indexed addressing with writeback. Scan forwards.
142 MachineBasicBlock::iterator
143 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I,
144 int UnscaledOffset, unsigned Limit);
146 // Scan the instruction list to find a base register update that can
147 // be combined with the current instruction (a load or store) using
148 // pre or post indexed addressing with writeback. Scan backwards.
149 MachineBasicBlock::iterator
150 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
152 // Find an instruction that updates the base register of the ld/st
154 bool isMatchingUpdateInsn(MachineInstr &MemMI, MachineInstr &MI,
155 unsigned BaseReg, int Offset);
157 // Merge a pre- or post-index base register update into a ld/st instruction.
158 MachineBasicBlock::iterator
159 mergeUpdateInsn(MachineBasicBlock::iterator I,
160 MachineBasicBlock::iterator Update, bool IsPreIdx);
162 // Find and merge zero store instructions.
163 bool tryToMergeZeroStInst(MachineBasicBlock::iterator &MBBI);
165 // Find and pair ldr/str instructions.
166 bool tryToPairLdStInst(MachineBasicBlock::iterator &MBBI);
168 // Find and promote load instructions which read directly from store.
169 bool tryToPromoteLoadFromStore(MachineBasicBlock::iterator &MBBI);
171 bool optimizeBlock(MachineBasicBlock &MBB, bool EnableNarrowZeroStOpt);
173 bool runOnMachineFunction(MachineFunction &Fn) override;
175 MachineFunctionProperties getRequiredProperties() const override {
176 return MachineFunctionProperties().set(
177 MachineFunctionProperties::Property::NoVRegs);
180 StringRef getPassName() const override { return AARCH64_LOAD_STORE_OPT_NAME; }
183 char AArch64LoadStoreOpt::ID = 0;
185 } // end anonymous namespace
187 INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
188 AARCH64_LOAD_STORE_OPT_NAME, false, false)
190 static bool isNarrowStore(unsigned Opc) {
194 case AArch64::STRBBui:
195 case AArch64::STURBBi:
196 case AArch64::STRHHui:
197 case AArch64::STURHHi:
202 // Scaling factor for unscaled load or store.
203 static int getMemScale(MachineInstr &MI) {
204 switch (MI.getOpcode()) {
206 llvm_unreachable("Opcode has unknown scale!");
207 case AArch64::LDRBBui:
208 case AArch64::LDURBBi:
209 case AArch64::LDRSBWui:
210 case AArch64::LDURSBWi:
211 case AArch64::STRBBui:
212 case AArch64::STURBBi:
214 case AArch64::LDRHHui:
215 case AArch64::LDURHHi:
216 case AArch64::LDRSHWui:
217 case AArch64::LDURSHWi:
218 case AArch64::STRHHui:
219 case AArch64::STURHHi:
221 case AArch64::LDRSui:
222 case AArch64::LDURSi:
223 case AArch64::LDRSWui:
224 case AArch64::LDURSWi:
225 case AArch64::LDRWui:
226 case AArch64::LDURWi:
227 case AArch64::STRSui:
228 case AArch64::STURSi:
229 case AArch64::STRWui:
230 case AArch64::STURWi:
232 case AArch64::LDPSWi:
237 case AArch64::LDRDui:
238 case AArch64::LDURDi:
239 case AArch64::LDRXui:
240 case AArch64::LDURXi:
241 case AArch64::STRDui:
242 case AArch64::STURDi:
243 case AArch64::STRXui:
244 case AArch64::STURXi:
250 case AArch64::LDRQui:
251 case AArch64::LDURQi:
252 case AArch64::STRQui:
253 case AArch64::STURQi:
260 static unsigned getMatchingNonSExtOpcode(unsigned Opc,
261 bool *IsValidLdStrOpc = nullptr) {
263 *IsValidLdStrOpc = true;
267 *IsValidLdStrOpc = false;
268 return std::numeric_limits<unsigned>::max();
269 case AArch64::STRDui:
270 case AArch64::STURDi:
271 case AArch64::STRQui:
272 case AArch64::STURQi:
273 case AArch64::STRBBui:
274 case AArch64::STURBBi:
275 case AArch64::STRHHui:
276 case AArch64::STURHHi:
277 case AArch64::STRWui:
278 case AArch64::STURWi:
279 case AArch64::STRXui:
280 case AArch64::STURXi:
281 case AArch64::LDRDui:
282 case AArch64::LDURDi:
283 case AArch64::LDRQui:
284 case AArch64::LDURQi:
285 case AArch64::LDRWui:
286 case AArch64::LDURWi:
287 case AArch64::LDRXui:
288 case AArch64::LDURXi:
289 case AArch64::STRSui:
290 case AArch64::STURSi:
291 case AArch64::LDRSui:
292 case AArch64::LDURSi:
294 case AArch64::LDRSWui:
295 return AArch64::LDRWui;
296 case AArch64::LDURSWi:
297 return AArch64::LDURWi;
301 static unsigned getMatchingWideOpcode(unsigned Opc) {
304 llvm_unreachable("Opcode has no wide equivalent!");
305 case AArch64::STRBBui:
306 return AArch64::STRHHui;
307 case AArch64::STRHHui:
308 return AArch64::STRWui;
309 case AArch64::STURBBi:
310 return AArch64::STURHHi;
311 case AArch64::STURHHi:
312 return AArch64::STURWi;
313 case AArch64::STURWi:
314 return AArch64::STURXi;
315 case AArch64::STRWui:
316 return AArch64::STRXui;
320 static unsigned getMatchingPairOpcode(unsigned Opc) {
323 llvm_unreachable("Opcode has no pairwise equivalent!");
324 case AArch64::STRSui:
325 case AArch64::STURSi:
326 return AArch64::STPSi;
327 case AArch64::STRDui:
328 case AArch64::STURDi:
329 return AArch64::STPDi;
330 case AArch64::STRQui:
331 case AArch64::STURQi:
332 return AArch64::STPQi;
333 case AArch64::STRWui:
334 case AArch64::STURWi:
335 return AArch64::STPWi;
336 case AArch64::STRXui:
337 case AArch64::STURXi:
338 return AArch64::STPXi;
339 case AArch64::LDRSui:
340 case AArch64::LDURSi:
341 return AArch64::LDPSi;
342 case AArch64::LDRDui:
343 case AArch64::LDURDi:
344 return AArch64::LDPDi;
345 case AArch64::LDRQui:
346 case AArch64::LDURQi:
347 return AArch64::LDPQi;
348 case AArch64::LDRWui:
349 case AArch64::LDURWi:
350 return AArch64::LDPWi;
351 case AArch64::LDRXui:
352 case AArch64::LDURXi:
353 return AArch64::LDPXi;
354 case AArch64::LDRSWui:
355 case AArch64::LDURSWi:
356 return AArch64::LDPSWi;
360 static unsigned isMatchingStore(MachineInstr &LoadInst,
361 MachineInstr &StoreInst) {
362 unsigned LdOpc = LoadInst.getOpcode();
363 unsigned StOpc = StoreInst.getOpcode();
366 llvm_unreachable("Unsupported load instruction!");
367 case AArch64::LDRBBui:
368 return StOpc == AArch64::STRBBui || StOpc == AArch64::STRHHui ||
369 StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
370 case AArch64::LDURBBi:
371 return StOpc == AArch64::STURBBi || StOpc == AArch64::STURHHi ||
372 StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
373 case AArch64::LDRHHui:
374 return StOpc == AArch64::STRHHui || StOpc == AArch64::STRWui ||
375 StOpc == AArch64::STRXui;
376 case AArch64::LDURHHi:
377 return StOpc == AArch64::STURHHi || StOpc == AArch64::STURWi ||
378 StOpc == AArch64::STURXi;
379 case AArch64::LDRWui:
380 return StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
381 case AArch64::LDURWi:
382 return StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
383 case AArch64::LDRXui:
384 return StOpc == AArch64::STRXui;
385 case AArch64::LDURXi:
386 return StOpc == AArch64::STURXi;
390 static unsigned getPreIndexedOpcode(unsigned Opc) {
391 // FIXME: We don't currently support creating pre-indexed loads/stores when
392 // the load or store is the unscaled version. If we decide to perform such an
393 // optimization in the future the cases for the unscaled loads/stores will
394 // need to be added here.
397 llvm_unreachable("Opcode has no pre-indexed equivalent!");
398 case AArch64::STRSui:
399 return AArch64::STRSpre;
400 case AArch64::STRDui:
401 return AArch64::STRDpre;
402 case AArch64::STRQui:
403 return AArch64::STRQpre;
404 case AArch64::STRBBui:
405 return AArch64::STRBBpre;
406 case AArch64::STRHHui:
407 return AArch64::STRHHpre;
408 case AArch64::STRWui:
409 return AArch64::STRWpre;
410 case AArch64::STRXui:
411 return AArch64::STRXpre;
412 case AArch64::LDRSui:
413 return AArch64::LDRSpre;
414 case AArch64::LDRDui:
415 return AArch64::LDRDpre;
416 case AArch64::LDRQui:
417 return AArch64::LDRQpre;
418 case AArch64::LDRBBui:
419 return AArch64::LDRBBpre;
420 case AArch64::LDRHHui:
421 return AArch64::LDRHHpre;
422 case AArch64::LDRWui:
423 return AArch64::LDRWpre;
424 case AArch64::LDRXui:
425 return AArch64::LDRXpre;
426 case AArch64::LDRSWui:
427 return AArch64::LDRSWpre;
429 return AArch64::LDPSpre;
430 case AArch64::LDPSWi:
431 return AArch64::LDPSWpre;
433 return AArch64::LDPDpre;
435 return AArch64::LDPQpre;
437 return AArch64::LDPWpre;
439 return AArch64::LDPXpre;
441 return AArch64::STPSpre;
443 return AArch64::STPDpre;
445 return AArch64::STPQpre;
447 return AArch64::STPWpre;
449 return AArch64::STPXpre;
453 static unsigned getPostIndexedOpcode(unsigned Opc) {
456 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
457 case AArch64::STRSui:
458 case AArch64::STURSi:
459 return AArch64::STRSpost;
460 case AArch64::STRDui:
461 case AArch64::STURDi:
462 return AArch64::STRDpost;
463 case AArch64::STRQui:
464 case AArch64::STURQi:
465 return AArch64::STRQpost;
466 case AArch64::STRBBui:
467 return AArch64::STRBBpost;
468 case AArch64::STRHHui:
469 return AArch64::STRHHpost;
470 case AArch64::STRWui:
471 case AArch64::STURWi:
472 return AArch64::STRWpost;
473 case AArch64::STRXui:
474 case AArch64::STURXi:
475 return AArch64::STRXpost;
476 case AArch64::LDRSui:
477 case AArch64::LDURSi:
478 return AArch64::LDRSpost;
479 case AArch64::LDRDui:
480 case AArch64::LDURDi:
481 return AArch64::LDRDpost;
482 case AArch64::LDRQui:
483 case AArch64::LDURQi:
484 return AArch64::LDRQpost;
485 case AArch64::LDRBBui:
486 return AArch64::LDRBBpost;
487 case AArch64::LDRHHui:
488 return AArch64::LDRHHpost;
489 case AArch64::LDRWui:
490 case AArch64::LDURWi:
491 return AArch64::LDRWpost;
492 case AArch64::LDRXui:
493 case AArch64::LDURXi:
494 return AArch64::LDRXpost;
495 case AArch64::LDRSWui:
496 return AArch64::LDRSWpost;
498 return AArch64::LDPSpost;
499 case AArch64::LDPSWi:
500 return AArch64::LDPSWpost;
502 return AArch64::LDPDpost;
504 return AArch64::LDPQpost;
506 return AArch64::LDPWpost;
508 return AArch64::LDPXpost;
510 return AArch64::STPSpost;
512 return AArch64::STPDpost;
514 return AArch64::STPQpost;
516 return AArch64::STPWpost;
518 return AArch64::STPXpost;
522 static bool isPairedLdSt(const MachineInstr &MI) {
523 switch (MI.getOpcode()) {
527 case AArch64::LDPSWi:
541 static const MachineOperand &getLdStRegOp(const MachineInstr &MI,
542 unsigned PairedRegOp = 0) {
543 assert(PairedRegOp < 2 && "Unexpected register operand idx.");
544 unsigned Idx = isPairedLdSt(MI) ? PairedRegOp : 0;
545 return MI.getOperand(Idx);
548 static const MachineOperand &getLdStBaseOp(const MachineInstr &MI) {
549 unsigned Idx = isPairedLdSt(MI) ? 2 : 1;
550 return MI.getOperand(Idx);
553 static const MachineOperand &getLdStOffsetOp(const MachineInstr &MI) {
554 unsigned Idx = isPairedLdSt(MI) ? 3 : 2;
555 return MI.getOperand(Idx);
558 static bool isLdOffsetInRangeOfSt(MachineInstr &LoadInst,
559 MachineInstr &StoreInst,
560 const AArch64InstrInfo *TII) {
561 assert(isMatchingStore(LoadInst, StoreInst) && "Expect only matched ld/st.");
562 int LoadSize = getMemScale(LoadInst);
563 int StoreSize = getMemScale(StoreInst);
564 int UnscaledStOffset = TII->isUnscaledLdSt(StoreInst)
565 ? getLdStOffsetOp(StoreInst).getImm()
566 : getLdStOffsetOp(StoreInst).getImm() * StoreSize;
567 int UnscaledLdOffset = TII->isUnscaledLdSt(LoadInst)
568 ? getLdStOffsetOp(LoadInst).getImm()
569 : getLdStOffsetOp(LoadInst).getImm() * LoadSize;
570 return (UnscaledStOffset <= UnscaledLdOffset) &&
571 (UnscaledLdOffset + LoadSize <= (UnscaledStOffset + StoreSize));
574 static bool isPromotableZeroStoreInst(MachineInstr &MI) {
575 unsigned Opc = MI.getOpcode();
576 return (Opc == AArch64::STRWui || Opc == AArch64::STURWi ||
577 isNarrowStore(Opc)) &&
578 getLdStRegOp(MI).getReg() == AArch64::WZR;
581 MachineBasicBlock::iterator
582 AArch64LoadStoreOpt::mergeNarrowZeroStores(MachineBasicBlock::iterator I,
583 MachineBasicBlock::iterator MergeMI,
584 const LdStPairFlags &Flags) {
585 assert(isPromotableZeroStoreInst(*I) && isPromotableZeroStoreInst(*MergeMI) &&
586 "Expected promotable zero stores.");
588 MachineBasicBlock::iterator NextI = I;
590 // If NextI is the second of the two instructions to be merged, we need
591 // to skip one further. Either way we merge will invalidate the iterator,
592 // and we don't need to scan the new instruction, as it's a pairwise
593 // instruction, which we're not considering for further action anyway.
594 if (NextI == MergeMI)
597 unsigned Opc = I->getOpcode();
598 bool IsScaled = !TII->isUnscaledLdSt(Opc);
599 int OffsetStride = IsScaled ? 1 : getMemScale(*I);
601 bool MergeForward = Flags.getMergeForward();
602 // Insert our new paired instruction after whichever of the paired
603 // instructions MergeForward indicates.
604 MachineBasicBlock::iterator InsertionPoint = MergeForward ? MergeMI : I;
605 // Also based on MergeForward is from where we copy the base register operand
606 // so we get the flags compatible with the input code.
607 const MachineOperand &BaseRegOp =
608 MergeForward ? getLdStBaseOp(*MergeMI) : getLdStBaseOp(*I);
610 // Which register is Rt and which is Rt2 depends on the offset order.
612 if (getLdStOffsetOp(*I).getImm() ==
613 getLdStOffsetOp(*MergeMI).getImm() + OffsetStride)
618 int OffsetImm = getLdStOffsetOp(*RtMI).getImm();
619 // Change the scaled offset from small to large type.
621 assert(((OffsetImm & 1) == 0) && "Unexpected offset to merge");
625 // Construct the new instruction.
626 DebugLoc DL = I->getDebugLoc();
627 MachineBasicBlock *MBB = I->getParent();
628 MachineInstrBuilder MIB;
629 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
630 .addReg(isNarrowStore(Opc) ? AArch64::WZR : AArch64::XZR)
633 .setMemRefs(I->mergeMemRefsWith(*MergeMI));
636 DEBUG(dbgs() << "Creating wider store. Replacing instructions:\n ");
637 DEBUG(I->print(dbgs()));
638 DEBUG(dbgs() << " ");
639 DEBUG(MergeMI->print(dbgs()));
640 DEBUG(dbgs() << " with instruction:\n ");
641 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
642 DEBUG(dbgs() << "\n");
644 // Erase the old instructions.
645 I->eraseFromParent();
646 MergeMI->eraseFromParent();
650 MachineBasicBlock::iterator
651 AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
652 MachineBasicBlock::iterator Paired,
653 const LdStPairFlags &Flags) {
654 MachineBasicBlock::iterator NextI = I;
656 // If NextI is the second of the two instructions to be merged, we need
657 // to skip one further. Either way we merge will invalidate the iterator,
658 // and we don't need to scan the new instruction, as it's a pairwise
659 // instruction, which we're not considering for further action anyway.
663 int SExtIdx = Flags.getSExtIdx();
665 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
666 bool IsUnscaled = TII->isUnscaledLdSt(Opc);
667 int OffsetStride = IsUnscaled ? getMemScale(*I) : 1;
669 bool MergeForward = Flags.getMergeForward();
670 // Insert our new paired instruction after whichever of the paired
671 // instructions MergeForward indicates.
672 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
673 // Also based on MergeForward is from where we copy the base register operand
674 // so we get the flags compatible with the input code.
675 const MachineOperand &BaseRegOp =
676 MergeForward ? getLdStBaseOp(*Paired) : getLdStBaseOp(*I);
678 int Offset = getLdStOffsetOp(*I).getImm();
679 int PairedOffset = getLdStOffsetOp(*Paired).getImm();
680 bool PairedIsUnscaled = TII->isUnscaledLdSt(Paired->getOpcode());
681 if (IsUnscaled != PairedIsUnscaled) {
682 // We're trying to pair instructions that differ in how they are scaled. If
683 // I is scaled then scale the offset of Paired accordingly. Otherwise, do
684 // the opposite (i.e., make Paired's offset unscaled).
685 int MemSize = getMemScale(*Paired);
686 if (PairedIsUnscaled) {
687 // If the unscaled offset isn't a multiple of the MemSize, we can't
688 // pair the operations together.
689 assert(!(PairedOffset % getMemScale(*Paired)) &&
690 "Offset should be a multiple of the stride!");
691 PairedOffset /= MemSize;
693 PairedOffset *= MemSize;
697 // Which register is Rt and which is Rt2 depends on the offset order.
698 MachineInstr *RtMI, *Rt2MI;
699 if (Offset == PairedOffset + OffsetStride) {
702 // Here we swapped the assumption made for SExtIdx.
703 // I.e., we turn ldp I, Paired into ldp Paired, I.
704 // Update the index accordingly.
706 SExtIdx = (SExtIdx + 1) % 2;
711 int OffsetImm = getLdStOffsetOp(*RtMI).getImm();
712 // Scale the immediate offset, if necessary.
713 if (TII->isUnscaledLdSt(RtMI->getOpcode())) {
714 assert(!(OffsetImm % getMemScale(*RtMI)) &&
715 "Unscaled offset cannot be scaled.");
716 OffsetImm /= getMemScale(*RtMI);
719 // Construct the new instruction.
720 MachineInstrBuilder MIB;
721 DebugLoc DL = I->getDebugLoc();
722 MachineBasicBlock *MBB = I->getParent();
723 MachineOperand RegOp0 = getLdStRegOp(*RtMI);
724 MachineOperand RegOp1 = getLdStRegOp(*Rt2MI);
725 // Kill flags may become invalid when moving stores for pairing.
726 if (RegOp0.isUse()) {
728 // Clear kill flags on store if moving upwards. Example:
731 // STRWui kill %w1 ; need to clear kill flag when moving STRWui upwards
732 RegOp0.setIsKill(false);
733 RegOp1.setIsKill(false);
735 // Clear kill flags of the first stores register. Example:
737 // USE kill %w1 ; need to clear kill flag when moving STRWui downwards
739 unsigned Reg = getLdStRegOp(*I).getReg();
740 for (MachineInstr &MI : make_range(std::next(I), Paired))
741 MI.clearRegisterKills(Reg, TRI);
744 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingPairOpcode(Opc)))
749 .setMemRefs(I->mergeMemRefsWith(*Paired));
753 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
754 DEBUG(I->print(dbgs()));
755 DEBUG(dbgs() << " ");
756 DEBUG(Paired->print(dbgs()));
757 DEBUG(dbgs() << " with instruction:\n ");
759 // Generate the sign extension for the proper result of the ldp.
760 // I.e., with X1, that would be:
761 // %W1<def> = KILL %W1, %X1<imp-def>
762 // %X1<def> = SBFMXri %X1<kill>, 0, 31
763 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
764 // Right now, DstMO has the extended register, since it comes from an
766 unsigned DstRegX = DstMO.getReg();
767 // Get the W variant of that register.
768 unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
769 // Update the result of LDP to use the W instead of the X variant.
770 DstMO.setReg(DstRegW);
771 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
772 DEBUG(dbgs() << "\n");
773 // Make the machine verifier happy by providing a definition for
775 // Insert this definition right after the generated LDP, i.e., before
777 MachineInstrBuilder MIBKill =
778 BuildMI(*MBB, InsertionPoint, DL, TII->get(TargetOpcode::KILL), DstRegW)
780 .addReg(DstRegX, RegState::Define);
781 MIBKill->getOperand(2).setImplicit();
782 // Create the sign extension.
783 MachineInstrBuilder MIBSXTW =
784 BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::SBFMXri), DstRegX)
789 DEBUG(dbgs() << " Extend operand:\n ");
790 DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
792 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
794 DEBUG(dbgs() << "\n");
796 // Erase the old instructions.
797 I->eraseFromParent();
798 Paired->eraseFromParent();
803 MachineBasicBlock::iterator
804 AArch64LoadStoreOpt::promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
805 MachineBasicBlock::iterator StoreI) {
806 MachineBasicBlock::iterator NextI = LoadI;
809 int LoadSize = getMemScale(*LoadI);
810 int StoreSize = getMemScale(*StoreI);
811 unsigned LdRt = getLdStRegOp(*LoadI).getReg();
812 const MachineOperand &StMO = getLdStRegOp(*StoreI);
813 unsigned StRt = getLdStRegOp(*StoreI).getReg();
814 bool IsStoreXReg = TRI->getRegClass(AArch64::GPR64RegClassID)->contains(StRt);
816 assert((IsStoreXReg ||
817 TRI->getRegClass(AArch64::GPR32RegClassID)->contains(StRt)) &&
818 "Unexpected RegClass");
820 MachineInstr *BitExtMI;
821 if (LoadSize == StoreSize && (LoadSize == 4 || LoadSize == 8)) {
822 // Remove the load, if the destination register of the loads is the same
823 // register for stored value.
824 if (StRt == LdRt && LoadSize == 8) {
825 for (MachineInstr &MI : make_range(StoreI->getIterator(),
826 LoadI->getIterator())) {
827 if (MI.killsRegister(StRt, TRI)) {
828 MI.clearRegisterKills(StRt, TRI);
832 DEBUG(dbgs() << "Remove load instruction:\n ");
833 DEBUG(LoadI->print(dbgs()));
834 DEBUG(dbgs() << "\n");
835 LoadI->eraseFromParent();
838 // Replace the load with a mov if the load and store are in the same size.
840 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
841 TII->get(IsStoreXReg ? AArch64::ORRXrs : AArch64::ORRWrs), LdRt)
842 .addReg(IsStoreXReg ? AArch64::XZR : AArch64::WZR)
844 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0));
846 // FIXME: Currently we disable this transformation in big-endian targets as
847 // performance and correctness are verified only in little-endian.
848 if (!Subtarget->isLittleEndian())
850 bool IsUnscaled = TII->isUnscaledLdSt(*LoadI);
851 assert(IsUnscaled == TII->isUnscaledLdSt(*StoreI) &&
852 "Unsupported ld/st match");
853 assert(LoadSize <= StoreSize && "Invalid load size");
854 int UnscaledLdOffset = IsUnscaled
855 ? getLdStOffsetOp(*LoadI).getImm()
856 : getLdStOffsetOp(*LoadI).getImm() * LoadSize;
857 int UnscaledStOffset = IsUnscaled
858 ? getLdStOffsetOp(*StoreI).getImm()
859 : getLdStOffsetOp(*StoreI).getImm() * StoreSize;
860 int Width = LoadSize * 8;
861 int Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
862 int Imms = Immr + Width - 1;
863 unsigned DestReg = IsStoreXReg
864 ? TRI->getMatchingSuperReg(LdRt, AArch64::sub_32,
865 &AArch64::GPR64RegClass)
868 assert((UnscaledLdOffset >= UnscaledStOffset &&
869 (UnscaledLdOffset + LoadSize) <= UnscaledStOffset + StoreSize) &&
872 Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
873 Imms = Immr + Width - 1;
874 if (UnscaledLdOffset == UnscaledStOffset) {
875 uint32_t AndMaskEncoded = ((IsStoreXReg ? 1 : 0) << 12) // N
876 | ((Immr) << 6) // immr
877 | ((Imms) << 0) // imms
881 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
882 TII->get(IsStoreXReg ? AArch64::ANDXri : AArch64::ANDWri),
885 .addImm(AndMaskEncoded);
888 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
889 TII->get(IsStoreXReg ? AArch64::UBFMXri : AArch64::UBFMWri),
897 // Clear kill flags between store and load.
898 for (MachineInstr &MI : make_range(StoreI->getIterator(),
899 BitExtMI->getIterator()))
900 if (MI.killsRegister(StRt, TRI)) {
901 MI.clearRegisterKills(StRt, TRI);
905 DEBUG(dbgs() << "Promoting load by replacing :\n ");
906 DEBUG(StoreI->print(dbgs()));
907 DEBUG(dbgs() << " ");
908 DEBUG(LoadI->print(dbgs()));
909 DEBUG(dbgs() << " with instructions:\n ");
910 DEBUG(StoreI->print(dbgs()));
911 DEBUG(dbgs() << " ");
912 DEBUG((BitExtMI)->print(dbgs()));
913 DEBUG(dbgs() << "\n");
915 // Erase the old instructions.
916 LoadI->eraseFromParent();
920 /// trackRegDefsUses - Remember what registers the specified instruction uses
922 static void trackRegDefsUses(const MachineInstr &MI, BitVector &ModifiedRegs,
924 const TargetRegisterInfo *TRI) {
925 for (const MachineOperand &MO : MI.operands()) {
927 ModifiedRegs.setBitsNotInMask(MO.getRegMask());
931 unsigned Reg = MO.getReg();
935 // WZR/XZR are not modified even when used as a destination register.
936 if (Reg != AArch64::WZR && Reg != AArch64::XZR)
937 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
938 ModifiedRegs.set(*AI);
940 assert(MO.isUse() && "Reg operand not a def and not a use?!?");
941 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
947 static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
948 // Convert the byte-offset used by unscaled into an "element" offset used
949 // by the scaled pair load/store instructions.
951 // If the byte-offset isn't a multiple of the stride, there's no point
952 // trying to match it.
953 if (Offset % OffsetStride)
955 Offset /= OffsetStride;
957 return Offset <= 63 && Offset >= -64;
960 // Do alignment, specialized to power of 2 and for signed ints,
961 // avoiding having to do a C-style cast from uint_64t to int when
962 // using alignTo from include/llvm/Support/MathExtras.h.
963 // FIXME: Move this function to include/MathExtras.h?
964 static int alignTo(int Num, int PowOf2) {
965 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
968 static bool mayAlias(MachineInstr &MIa, MachineInstr &MIb,
970 // One of the instructions must modify memory.
971 if (!MIa.mayStore() && !MIb.mayStore())
974 // Both instructions must be memory operations.
975 if (!MIa.mayLoadOrStore() && !MIb.mayLoadOrStore())
978 return MIa.mayAlias(AA, MIb, /*UseTBAA*/false);
981 static bool mayAlias(MachineInstr &MIa,
982 SmallVectorImpl<MachineInstr *> &MemInsns,
984 for (MachineInstr *MIb : MemInsns)
985 if (mayAlias(MIa, *MIb, AA))
991 bool AArch64LoadStoreOpt::findMatchingStore(
992 MachineBasicBlock::iterator I, unsigned Limit,
993 MachineBasicBlock::iterator &StoreI) {
994 MachineBasicBlock::iterator B = I->getParent()->begin();
995 MachineBasicBlock::iterator MBBI = I;
996 MachineInstr &LoadMI = *I;
997 unsigned BaseReg = getLdStBaseOp(LoadMI).getReg();
999 // If the load is the first instruction in the block, there's obviously
1000 // not any matching store.
1004 // Track which registers have been modified and used between the first insn
1005 // and the second insn.
1006 ModifiedRegs.reset();
1012 MachineInstr &MI = *MBBI;
1014 // Don't count transient instructions towards the search limit since there
1015 // may be different numbers of them if e.g. debug information is present.
1016 if (!MI.isTransient())
1019 // If the load instruction reads directly from the address to which the
1020 // store instruction writes and the stored value is not modified, we can
1021 // promote the load. Since we do not handle stores with pre-/post-index,
1022 // it's unnecessary to check if BaseReg is modified by the store itself.
1023 if (MI.mayStore() && isMatchingStore(LoadMI, MI) &&
1024 BaseReg == getLdStBaseOp(MI).getReg() &&
1025 isLdOffsetInRangeOfSt(LoadMI, MI, TII) &&
1026 !ModifiedRegs[getLdStRegOp(MI).getReg()]) {
1034 // Update modified / uses register lists.
1035 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1037 // Otherwise, if the base register is modified, we have no match, so
1039 if (ModifiedRegs[BaseReg])
1042 // If we encounter a store aliased with the load, return early.
1043 if (MI.mayStore() && mayAlias(LoadMI, MI, AA))
1045 } while (MBBI != B && Count < Limit);
1049 // Returns true if FirstMI and MI are candidates for merging or pairing.
1050 // Otherwise, returns false.
1051 static bool areCandidatesToMergeOrPair(MachineInstr &FirstMI, MachineInstr &MI,
1052 LdStPairFlags &Flags,
1053 const AArch64InstrInfo *TII) {
1054 // If this is volatile or if pairing is suppressed, not a candidate.
1055 if (MI.hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
1058 // We should have already checked FirstMI for pair suppression and volatility.
1059 assert(!FirstMI.hasOrderedMemoryRef() &&
1060 !TII->isLdStPairSuppressed(FirstMI) &&
1061 "FirstMI shouldn't get here if either of these checks are true.");
1063 unsigned OpcA = FirstMI.getOpcode();
1064 unsigned OpcB = MI.getOpcode();
1066 // Opcodes match: nothing more to check.
1070 // Try to match a sign-extended load/store with a zero-extended load/store.
1071 bool IsValidLdStrOpc, PairIsValidLdStrOpc;
1072 unsigned NonSExtOpc = getMatchingNonSExtOpcode(OpcA, &IsValidLdStrOpc);
1073 assert(IsValidLdStrOpc &&
1074 "Given Opc should be a Load or Store with an immediate");
1075 // OpcA will be the first instruction in the pair.
1076 if (NonSExtOpc == getMatchingNonSExtOpcode(OpcB, &PairIsValidLdStrOpc)) {
1077 Flags.setSExtIdx(NonSExtOpc == (unsigned)OpcA ? 1 : 0);
1081 // If the second instruction isn't even a mergable/pairable load/store, bail
1083 if (!PairIsValidLdStrOpc)
1086 // FIXME: We don't support merging narrow stores with mixed scaled/unscaled
1088 if (isNarrowStore(OpcA) || isNarrowStore(OpcB))
1091 // Try to match an unscaled load/store with a scaled load/store.
1092 return TII->isUnscaledLdSt(OpcA) != TII->isUnscaledLdSt(OpcB) &&
1093 getMatchingPairOpcode(OpcA) == getMatchingPairOpcode(OpcB);
1095 // FIXME: Can we also match a mixed sext/zext unscaled/scaled pair?
1098 /// Scan the instructions looking for a load/store that can be combined with the
1099 /// current instruction into a wider equivalent or a load/store pair.
1100 MachineBasicBlock::iterator
1101 AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
1102 LdStPairFlags &Flags, unsigned Limit,
1103 bool FindNarrowMerge) {
1104 MachineBasicBlock::iterator E = I->getParent()->end();
1105 MachineBasicBlock::iterator MBBI = I;
1106 MachineInstr &FirstMI = *I;
1109 bool MayLoad = FirstMI.mayLoad();
1110 bool IsUnscaled = TII->isUnscaledLdSt(FirstMI);
1111 unsigned Reg = getLdStRegOp(FirstMI).getReg();
1112 unsigned BaseReg = getLdStBaseOp(FirstMI).getReg();
1113 int Offset = getLdStOffsetOp(FirstMI).getImm();
1114 int OffsetStride = IsUnscaled ? getMemScale(FirstMI) : 1;
1115 bool IsPromotableZeroStore = isPromotableZeroStoreInst(FirstMI);
1117 // Track which registers have been modified and used between the first insn
1118 // (inclusive) and the second insn.
1119 ModifiedRegs.reset();
1122 // Remember any instructions that read/write memory between FirstMI and MI.
1123 SmallVector<MachineInstr *, 4> MemInsns;
1125 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
1126 MachineInstr &MI = *MBBI;
1128 // Don't count transient instructions towards the search limit since there
1129 // may be different numbers of them if e.g. debug information is present.
1130 if (!MI.isTransient())
1133 Flags.setSExtIdx(-1);
1134 if (areCandidatesToMergeOrPair(FirstMI, MI, Flags, TII) &&
1135 getLdStOffsetOp(MI).isImm()) {
1136 assert(MI.mayLoadOrStore() && "Expected memory operation.");
1137 // If we've found another instruction with the same opcode, check to see
1138 // if the base and offset are compatible with our starting instruction.
1139 // These instructions all have scaled immediate operands, so we just
1140 // check for +1/-1. Make sure to check the new instruction offset is
1141 // actually an immediate and not a symbolic reference destined for
1143 unsigned MIBaseReg = getLdStBaseOp(MI).getReg();
1144 int MIOffset = getLdStOffsetOp(MI).getImm();
1145 bool MIIsUnscaled = TII->isUnscaledLdSt(MI);
1146 if (IsUnscaled != MIIsUnscaled) {
1147 // We're trying to pair instructions that differ in how they are scaled.
1148 // If FirstMI is scaled then scale the offset of MI accordingly.
1149 // Otherwise, do the opposite (i.e., make MI's offset unscaled).
1150 int MemSize = getMemScale(MI);
1152 // If the unscaled offset isn't a multiple of the MemSize, we can't
1153 // pair the operations together: bail and keep looking.
1154 if (MIOffset % MemSize) {
1155 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1156 MemInsns.push_back(&MI);
1159 MIOffset /= MemSize;
1161 MIOffset *= MemSize;
1165 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
1166 (Offset + OffsetStride == MIOffset))) {
1167 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
1168 if (FindNarrowMerge) {
1169 // If the alignment requirements of the scaled wide load/store
1170 // instruction can't express the offset of the scaled narrow input,
1171 // bail and keep looking. For promotable zero stores, allow only when
1172 // the stored value is the same (i.e., WZR).
1173 if ((!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) ||
1174 (IsPromotableZeroStore && Reg != getLdStRegOp(MI).getReg())) {
1175 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1176 MemInsns.push_back(&MI);
1180 // Pairwise instructions have a 7-bit signed offset field. Single
1181 // insns have a 12-bit unsigned offset field. If the resultant
1182 // immediate offset of merging these instructions is out of range for
1183 // a pairwise instruction, bail and keep looking.
1184 if (!inBoundsForPair(IsUnscaled, MinOffset, OffsetStride)) {
1185 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1186 MemInsns.push_back(&MI);
1189 // If the alignment requirements of the paired (scaled) instruction
1190 // can't express the offset of the unscaled input, bail and keep
1192 if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) {
1193 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1194 MemInsns.push_back(&MI);
1198 // If the destination register of the loads is the same register, bail
1199 // and keep looking. A load-pair instruction with both destination
1200 // registers the same is UNPREDICTABLE and will result in an exception.
1201 if (MayLoad && Reg == getLdStRegOp(MI).getReg()) {
1202 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1203 MemInsns.push_back(&MI);
1207 // If the Rt of the second instruction was not modified or used between
1208 // the two instructions and none of the instructions between the second
1209 // and first alias with the second, we can combine the second into the
1211 if (!ModifiedRegs[getLdStRegOp(MI).getReg()] &&
1212 !(MI.mayLoad() && UsedRegs[getLdStRegOp(MI).getReg()]) &&
1213 !mayAlias(MI, MemInsns, AA)) {
1214 Flags.setMergeForward(false);
1218 // Likewise, if the Rt of the first instruction is not modified or used
1219 // between the two instructions and none of the instructions between the
1220 // first and the second alias with the first, we can combine the first
1222 if (!ModifiedRegs[getLdStRegOp(FirstMI).getReg()] &&
1223 !(MayLoad && UsedRegs[getLdStRegOp(FirstMI).getReg()]) &&
1224 !mayAlias(FirstMI, MemInsns, AA)) {
1225 Flags.setMergeForward(true);
1228 // Unable to combine these instructions due to interference in between.
1233 // If the instruction wasn't a matching load or store. Stop searching if we
1234 // encounter a call instruction that might modify memory.
1238 // Update modified / uses register lists.
1239 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1241 // Otherwise, if the base register is modified, we have no match, so
1243 if (ModifiedRegs[BaseReg])
1246 // Update list of instructions that read/write memory.
1247 if (MI.mayLoadOrStore())
1248 MemInsns.push_back(&MI);
1253 MachineBasicBlock::iterator
1254 AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
1255 MachineBasicBlock::iterator Update,
1257 assert((Update->getOpcode() == AArch64::ADDXri ||
1258 Update->getOpcode() == AArch64::SUBXri) &&
1259 "Unexpected base register update instruction to merge!");
1260 MachineBasicBlock::iterator NextI = I;
1261 // Return the instruction following the merged instruction, which is
1262 // the instruction following our unmerged load. Unless that's the add/sub
1263 // instruction we're merging, in which case it's the one after that.
1264 if (++NextI == Update)
1267 int Value = Update->getOperand(2).getImm();
1268 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
1269 "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
1270 if (Update->getOpcode() == AArch64::SUBXri)
1273 unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
1274 : getPostIndexedOpcode(I->getOpcode());
1275 MachineInstrBuilder MIB;
1276 if (!isPairedLdSt(*I)) {
1277 // Non-paired instruction.
1278 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1279 .add(getLdStRegOp(*Update))
1280 .add(getLdStRegOp(*I))
1281 .add(getLdStBaseOp(*I))
1283 .setMemRefs(I->memoperands_begin(), I->memoperands_end());
1285 // Paired instruction.
1286 int Scale = getMemScale(*I);
1287 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1288 .add(getLdStRegOp(*Update))
1289 .add(getLdStRegOp(*I, 0))
1290 .add(getLdStRegOp(*I, 1))
1291 .add(getLdStBaseOp(*I))
1292 .addImm(Value / Scale)
1293 .setMemRefs(I->memoperands_begin(), I->memoperands_end());
1298 DEBUG(dbgs() << "Creating pre-indexed load/store.");
1300 DEBUG(dbgs() << "Creating post-indexed load/store.");
1301 DEBUG(dbgs() << " Replacing instructions:\n ");
1302 DEBUG(I->print(dbgs()));
1303 DEBUG(dbgs() << " ");
1304 DEBUG(Update->print(dbgs()));
1305 DEBUG(dbgs() << " with instruction:\n ");
1306 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1307 DEBUG(dbgs() << "\n");
1309 // Erase the old instructions for the block.
1310 I->eraseFromParent();
1311 Update->eraseFromParent();
1316 bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr &MemMI,
1318 unsigned BaseReg, int Offset) {
1319 switch (MI.getOpcode()) {
1322 case AArch64::SUBXri:
1323 case AArch64::ADDXri:
1324 // Make sure it's a vanilla immediate operand, not a relocation or
1325 // anything else we can't handle.
1326 if (!MI.getOperand(2).isImm())
1328 // Watch out for 1 << 12 shifted value.
1329 if (AArch64_AM::getShiftValue(MI.getOperand(3).getImm()))
1332 // The update instruction source and destination register must be the
1333 // same as the load/store base register.
1334 if (MI.getOperand(0).getReg() != BaseReg ||
1335 MI.getOperand(1).getReg() != BaseReg)
1338 bool IsPairedInsn = isPairedLdSt(MemMI);
1339 int UpdateOffset = MI.getOperand(2).getImm();
1340 if (MI.getOpcode() == AArch64::SUBXri)
1341 UpdateOffset = -UpdateOffset;
1343 // For non-paired load/store instructions, the immediate must fit in a
1344 // signed 9-bit integer.
1345 if (!IsPairedInsn && (UpdateOffset > 255 || UpdateOffset < -256))
1348 // For paired load/store instructions, the immediate must be a multiple of
1349 // the scaling factor. The scaled offset must also fit into a signed 7-bit
1352 int Scale = getMemScale(MemMI);
1353 if (UpdateOffset % Scale != 0)
1356 int ScaledOffset = UpdateOffset / Scale;
1357 if (ScaledOffset > 63 || ScaledOffset < -64)
1361 // If we have a non-zero Offset, we check that it matches the amount
1362 // we're adding to the register.
1363 if (!Offset || Offset == UpdateOffset)
1370 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
1371 MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) {
1372 MachineBasicBlock::iterator E = I->getParent()->end();
1373 MachineInstr &MemMI = *I;
1374 MachineBasicBlock::iterator MBBI = I;
1376 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
1377 int MIUnscaledOffset = getLdStOffsetOp(MemMI).getImm() * getMemScale(MemMI);
1379 // Scan forward looking for post-index opportunities. Updating instructions
1380 // can't be formed if the memory instruction doesn't have the offset we're
1382 if (MIUnscaledOffset != UnscaledOffset)
1385 // If the base register overlaps a destination register, we can't
1386 // merge the update.
1387 bool IsPairedInsn = isPairedLdSt(MemMI);
1388 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1389 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1390 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1394 // Track which registers have been modified and used between the first insn
1395 // (inclusive) and the second insn.
1396 ModifiedRegs.reset();
1399 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
1400 MachineInstr &MI = *MBBI;
1402 // Don't count transient instructions towards the search limit since there
1403 // may be different numbers of them if e.g. debug information is present.
1404 if (!MI.isTransient())
1407 // If we found a match, return it.
1408 if (isMatchingUpdateInsn(*I, MI, BaseReg, UnscaledOffset))
1411 // Update the status of what the instruction clobbered and used.
1412 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1414 // Otherwise, if the base register is used or modified, we have no match, so
1416 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
1422 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
1423 MachineBasicBlock::iterator I, unsigned Limit) {
1424 MachineBasicBlock::iterator B = I->getParent()->begin();
1425 MachineBasicBlock::iterator E = I->getParent()->end();
1426 MachineInstr &MemMI = *I;
1427 MachineBasicBlock::iterator MBBI = I;
1429 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
1430 int Offset = getLdStOffsetOp(MemMI).getImm();
1432 // If the load/store is the first instruction in the block, there's obviously
1433 // not any matching update. Ditto if the memory offset isn't zero.
1434 if (MBBI == B || Offset != 0)
1436 // If the base register overlaps a destination register, we can't
1437 // merge the update.
1438 bool IsPairedInsn = isPairedLdSt(MemMI);
1439 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1440 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1441 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1445 // Track which registers have been modified and used between the first insn
1446 // (inclusive) and the second insn.
1447 ModifiedRegs.reset();
1452 MachineInstr &MI = *MBBI;
1454 // Don't count transient instructions towards the search limit since there
1455 // may be different numbers of them if e.g. debug information is present.
1456 if (!MI.isTransient())
1459 // If we found a match, return it.
1460 if (isMatchingUpdateInsn(*I, MI, BaseReg, Offset))
1463 // Update the status of what the instruction clobbered and used.
1464 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1466 // Otherwise, if the base register is used or modified, we have no match, so
1468 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
1470 } while (MBBI != B && Count < Limit);
1474 bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore(
1475 MachineBasicBlock::iterator &MBBI) {
1476 MachineInstr &MI = *MBBI;
1477 // If this is a volatile load, don't mess with it.
1478 if (MI.hasOrderedMemoryRef())
1481 // Make sure this is a reg+imm.
1482 // FIXME: It is possible to extend it to handle reg+reg cases.
1483 if (!getLdStOffsetOp(MI).isImm())
1486 // Look backward up to LdStLimit instructions.
1487 MachineBasicBlock::iterator StoreI;
1488 if (findMatchingStore(MBBI, LdStLimit, StoreI)) {
1489 ++NumLoadsFromStoresPromoted;
1490 // Promote the load. Keeping the iterator straight is a
1491 // pain, so we let the merge routine tell us what the next instruction
1492 // is after it's done mucking about.
1493 MBBI = promoteLoadFromStore(MBBI, StoreI);
1499 // Merge adjacent zero stores into a wider store.
1500 bool AArch64LoadStoreOpt::tryToMergeZeroStInst(
1501 MachineBasicBlock::iterator &MBBI) {
1502 assert(isPromotableZeroStoreInst(*MBBI) && "Expected narrow store.");
1503 MachineInstr &MI = *MBBI;
1504 MachineBasicBlock::iterator E = MI.getParent()->end();
1506 if (!TII->isCandidateToMergeOrPair(MI))
1509 // Look ahead up to LdStLimit instructions for a mergable instruction.
1510 LdStPairFlags Flags;
1511 MachineBasicBlock::iterator MergeMI =
1512 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ true);
1514 ++NumZeroStoresPromoted;
1516 // Keeping the iterator straight is a pain, so we let the merge routine tell
1517 // us what the next instruction is after it's done mucking about.
1518 MBBI = mergeNarrowZeroStores(MBBI, MergeMI, Flags);
1524 // Find loads and stores that can be merged into a single load or store pair
1526 bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
1527 MachineInstr &MI = *MBBI;
1528 MachineBasicBlock::iterator E = MI.getParent()->end();
1530 if (!TII->isCandidateToMergeOrPair(MI))
1533 // Early exit if the offset is not possible to match. (6 bits of positive
1534 // range, plus allow an extra one in case we find a later insn that matches
1536 bool IsUnscaled = TII->isUnscaledLdSt(MI);
1537 int Offset = getLdStOffsetOp(MI).getImm();
1538 int OffsetStride = IsUnscaled ? getMemScale(MI) : 1;
1539 // Allow one more for offset.
1541 Offset -= OffsetStride;
1542 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
1545 // Look ahead up to LdStLimit instructions for a pairable instruction.
1546 LdStPairFlags Flags;
1547 MachineBasicBlock::iterator Paired =
1548 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ false);
1551 if (TII->isUnscaledLdSt(MI))
1552 ++NumUnscaledPairCreated;
1553 // Keeping the iterator straight is a pain, so we let the merge routine tell
1554 // us what the next instruction is after it's done mucking about.
1555 MBBI = mergePairedInsns(MBBI, Paired, Flags);
1561 bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
1562 bool EnableNarrowZeroStOpt) {
1563 bool Modified = false;
1564 // Four tranformations to do here:
1565 // 1) Find loads that directly read from stores and promote them by
1566 // replacing with mov instructions. If the store is wider than the load,
1567 // the load will be replaced with a bitfield extract.
1570 // ldrh w2, [x0, #6]
1574 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1576 MachineInstr &MI = *MBBI;
1577 switch (MI.getOpcode()) {
1579 // Just move on to the next instruction.
1582 // Scaled instructions.
1583 case AArch64::LDRBBui:
1584 case AArch64::LDRHHui:
1585 case AArch64::LDRWui:
1586 case AArch64::LDRXui:
1587 // Unscaled instructions.
1588 case AArch64::LDURBBi:
1589 case AArch64::LDURHHi:
1590 case AArch64::LDURWi:
1591 case AArch64::LDURXi:
1592 if (tryToPromoteLoadFromStore(MBBI)) {
1600 // 2) Merge adjacent zero stores into a wider store.
1603 // strh wzr, [x0, #2]
1608 // str wzr, [x0, #4]
1611 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1612 EnableNarrowZeroStOpt && MBBI != E;) {
1613 if (isPromotableZeroStoreInst(*MBBI)) {
1614 if (tryToMergeZeroStInst(MBBI)) {
1622 // 3) Find loads and stores that can be merged into a single load or store
1623 // pair instruction.
1629 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1631 if (TII->isPairableLdStInst(*MBBI) && tryToPairLdStInst(MBBI))
1636 // 4) Find base register updates that can be merged into the load or store
1637 // as a base-reg writeback.
1643 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1645 MachineInstr &MI = *MBBI;
1646 // Do update merging. It's simpler to keep this separate from the above
1647 // switchs, though not strictly necessary.
1648 unsigned Opc = MI.getOpcode();
1651 // Just move on to the next instruction.
1654 // Scaled instructions.
1655 case AArch64::STRSui:
1656 case AArch64::STRDui:
1657 case AArch64::STRQui:
1658 case AArch64::STRXui:
1659 case AArch64::STRWui:
1660 case AArch64::STRHHui:
1661 case AArch64::STRBBui:
1662 case AArch64::LDRSui:
1663 case AArch64::LDRDui:
1664 case AArch64::LDRQui:
1665 case AArch64::LDRXui:
1666 case AArch64::LDRWui:
1667 case AArch64::LDRHHui:
1668 case AArch64::LDRBBui:
1669 // Unscaled instructions.
1670 case AArch64::STURSi:
1671 case AArch64::STURDi:
1672 case AArch64::STURQi:
1673 case AArch64::STURWi:
1674 case AArch64::STURXi:
1675 case AArch64::LDURSi:
1676 case AArch64::LDURDi:
1677 case AArch64::LDURQi:
1678 case AArch64::LDURWi:
1679 case AArch64::LDURXi:
1680 // Paired instructions.
1681 case AArch64::LDPSi:
1682 case AArch64::LDPSWi:
1683 case AArch64::LDPDi:
1684 case AArch64::LDPQi:
1685 case AArch64::LDPWi:
1686 case AArch64::LDPXi:
1687 case AArch64::STPSi:
1688 case AArch64::STPDi:
1689 case AArch64::STPQi:
1690 case AArch64::STPWi:
1691 case AArch64::STPXi: {
1692 // Make sure this is a reg+imm (as opposed to an address reloc).
1693 if (!getLdStOffsetOp(MI).isImm()) {
1697 // Look forward to try to form a post-index instruction. For example,
1699 // add x20, x20, #32
1701 // ldr x0, [x20], #32
1702 MachineBasicBlock::iterator Update =
1703 findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit);
1705 // Merge the update into the ld/st.
1706 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
1712 // Don't know how to handle unscaled pre/post-index versions below, so
1713 // move to the next instruction.
1714 if (TII->isUnscaledLdSt(Opc)) {
1719 // Look back to try to find a pre-index instruction. For example,
1723 // ldr x1, [x0, #8]!
1724 Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit);
1726 // Merge the update into the ld/st.
1727 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
1732 // The immediate in the load/store is scaled by the size of the memory
1733 // operation. The immediate in the add we're looking for,
1734 // however, is not, so adjust here.
1735 int UnscaledOffset = getLdStOffsetOp(MI).getImm() * getMemScale(MI);
1737 // Look forward to try to find a post-index instruction. For example,
1738 // ldr x1, [x0, #64]
1741 // ldr x1, [x0, #64]!
1742 Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit);
1744 // Merge the update into the ld/st.
1745 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
1751 // Nothing found. Just move to the next instruction.
1761 bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
1762 if (skipFunction(*Fn.getFunction()))
1765 Subtarget = &static_cast<const AArch64Subtarget &>(Fn.getSubtarget());
1766 TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo());
1767 TRI = Subtarget->getRegisterInfo();
1768 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1770 // Resize the modified and used register bitfield trackers. We do this once
1771 // per function and then clear the bitfield each time we optimize a load or
1773 ModifiedRegs.resize(TRI->getNumRegs());
1774 UsedRegs.resize(TRI->getNumRegs());
1776 bool Modified = false;
1777 bool enableNarrowZeroStOpt = !Subtarget->requiresStrictAlign();
1778 for (auto &MBB : Fn)
1779 Modified |= optimizeBlock(MBB, enableNarrowZeroStOpt);
1784 // FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep loads and
1785 // stores near one another? Note: The pre-RA instruction scheduler already has
1786 // hooks to try and schedule pairable loads/stores together to improve pairing
1787 // opportunities. Thus, pre-RA pairing pass may not be worth the effort.
1789 // FIXME: When pairing store instructions it's very possible for this pass to
1790 // hoist a store with a KILL marker above another use (without a KILL marker).
1791 // The resulting IR is invalid, but nothing uses the KILL markers after this
1792 // pass, so it's never caused a problem in practice.
1794 /// createAArch64LoadStoreOptimizationPass - returns an instance of the
1795 /// load / store optimization pass.
1796 FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
1797 return new AArch64LoadStoreOpt();