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/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"
34 #define DEBUG_TYPE "aarch64-ldst-opt"
36 /// AArch64AllocLoadStoreOpt - Post-register allocation pass to combine
37 /// load / store instructions to form ldp / stp instructions.
39 STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
40 STATISTIC(NumPostFolded, "Number of post-index updates folded");
41 STATISTIC(NumPreFolded, "Number of pre-index updates folded");
42 STATISTIC(NumUnscaledPairCreated,
43 "Number of load/store from unscaled generated");
45 static cl::opt<unsigned> ScanLimit("aarch64-load-store-scan-limit",
46 cl::init(20), cl::Hidden);
48 // Place holder while testing unscaled load/store combining
49 static cl::opt<bool> EnableAArch64UnscaledMemOp(
50 "aarch64-unscaled-mem-op", cl::Hidden,
51 cl::desc("Allow AArch64 unscaled load/store combining"), cl::init(true));
55 typedef struct LdStPairFlags {
56 // If a matching instruction is found, MergeForward is set to true if the
57 // merge is to remove the first instruction and replace the second with
58 // a pair-wise insn, and false if the reverse is true.
61 // SExtIdx gives the index of the result of the load pair that must be
62 // extended. The value of SExtIdx assumes that the paired load produces the
63 // value in this order: (I, returned iterator), i.e., -1 means no value has
64 // to be extended, 0 means I, and 1 means the returned iterator.
67 LdStPairFlags() : MergeForward(false), SExtIdx(-1) {}
69 void setMergeForward(bool V = true) { MergeForward = V; }
70 bool getMergeForward() const { return MergeForward; }
72 void setSExtIdx(int V) { SExtIdx = V; }
73 int getSExtIdx() const { return SExtIdx; }
77 struct AArch64LoadStoreOpt : public MachineFunctionPass {
79 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {}
81 const AArch64InstrInfo *TII;
82 const TargetRegisterInfo *TRI;
84 // Scan the instructions looking for a load/store that can be combined
85 // with the current instruction into a load/store pair.
86 // Return the matching instruction if one is found, else MBB->end().
87 MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
90 // Merge the two instructions indicated into a single pair-wise instruction.
91 // If MergeForward is true, erase the first instruction and fold its
92 // operation into the second. If false, the reverse. Return the instruction
93 // following the first instruction (which may change during processing).
94 MachineBasicBlock::iterator
95 mergePairedInsns(MachineBasicBlock::iterator I,
96 MachineBasicBlock::iterator Paired,
97 const LdStPairFlags &Flags);
99 // Scan the instruction list to find a base register update that can
100 // be combined with the current instruction (a load or store) using
101 // pre or post indexed addressing with writeback. Scan forwards.
102 MachineBasicBlock::iterator
103 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I, unsigned Limit,
106 // Scan the instruction list to find a base register update that can
107 // be combined with the current instruction (a load or store) using
108 // pre or post indexed addressing with writeback. Scan backwards.
109 MachineBasicBlock::iterator
110 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
112 // Merge a pre-index base register update into a ld/st instruction.
113 MachineBasicBlock::iterator
114 mergePreIdxUpdateInsn(MachineBasicBlock::iterator I,
115 MachineBasicBlock::iterator Update);
117 // Merge a post-index base register update into a ld/st instruction.
118 MachineBasicBlock::iterator
119 mergePostIdxUpdateInsn(MachineBasicBlock::iterator I,
120 MachineBasicBlock::iterator Update);
122 bool optimizeBlock(MachineBasicBlock &MBB);
124 bool runOnMachineFunction(MachineFunction &Fn) override;
126 const char *getPassName() const override {
127 return "AArch64 load / store optimization pass";
131 int getMemSize(MachineInstr *MemMI);
133 char AArch64LoadStoreOpt::ID = 0;
136 static bool isUnscaledLdst(unsigned Opc) {
140 case AArch64::STURSi:
141 case AArch64::STURDi:
142 case AArch64::STURQi:
143 case AArch64::STURWi:
144 case AArch64::STURXi:
145 case AArch64::LDURSi:
146 case AArch64::LDURDi:
147 case AArch64::LDURQi:
148 case AArch64::LDURWi:
149 case AArch64::LDURXi:
150 case AArch64::LDURSWi:
155 // Size in bytes of the data moved by an unscaled load or store
156 int AArch64LoadStoreOpt::getMemSize(MachineInstr *MemMI) {
157 switch (MemMI->getOpcode()) {
159 llvm_unreachable("Opcode has unknown size!");
160 case AArch64::STRSui:
161 case AArch64::STURSi:
163 case AArch64::STRDui:
164 case AArch64::STURDi:
166 case AArch64::STRQui:
167 case AArch64::STURQi:
169 case AArch64::STRWui:
170 case AArch64::STURWi:
172 case AArch64::STRXui:
173 case AArch64::STURXi:
175 case AArch64::LDRSui:
176 case AArch64::LDURSi:
178 case AArch64::LDRDui:
179 case AArch64::LDURDi:
181 case AArch64::LDRQui:
182 case AArch64::LDURQi:
184 case AArch64::LDRWui:
185 case AArch64::LDURWi:
187 case AArch64::LDRXui:
188 case AArch64::LDURXi:
190 case AArch64::LDRSWui:
191 case AArch64::LDURSWi:
196 static unsigned getMatchingNonSExtOpcode(unsigned Opc,
197 bool *IsValidLdStrOpc = nullptr) {
199 *IsValidLdStrOpc = true;
203 *IsValidLdStrOpc = false;
205 case AArch64::STRDui:
206 case AArch64::STURDi:
207 case AArch64::STRQui:
208 case AArch64::STURQi:
209 case AArch64::STRWui:
210 case AArch64::STURWi:
211 case AArch64::STRXui:
212 case AArch64::STURXi:
213 case AArch64::LDRDui:
214 case AArch64::LDURDi:
215 case AArch64::LDRQui:
216 case AArch64::LDURQi:
217 case AArch64::LDRWui:
218 case AArch64::LDURWi:
219 case AArch64::LDRXui:
220 case AArch64::LDURXi:
221 case AArch64::STRSui:
222 case AArch64::STURSi:
223 case AArch64::LDRSui:
224 case AArch64::LDURSi:
226 case AArch64::LDRSWui:
227 return AArch64::LDRWui;
228 case AArch64::LDURSWi:
229 return AArch64::LDURWi;
233 static unsigned getMatchingPairOpcode(unsigned Opc) {
236 llvm_unreachable("Opcode has no pairwise equivalent!");
237 case AArch64::STRSui:
238 case AArch64::STURSi:
239 return AArch64::STPSi;
240 case AArch64::STRDui:
241 case AArch64::STURDi:
242 return AArch64::STPDi;
243 case AArch64::STRQui:
244 case AArch64::STURQi:
245 return AArch64::STPQi;
246 case AArch64::STRWui:
247 case AArch64::STURWi:
248 return AArch64::STPWi;
249 case AArch64::STRXui:
250 case AArch64::STURXi:
251 return AArch64::STPXi;
252 case AArch64::LDRSui:
253 case AArch64::LDURSi:
254 return AArch64::LDPSi;
255 case AArch64::LDRDui:
256 case AArch64::LDURDi:
257 return AArch64::LDPDi;
258 case AArch64::LDRQui:
259 case AArch64::LDURQi:
260 return AArch64::LDPQi;
261 case AArch64::LDRWui:
262 case AArch64::LDURWi:
263 return AArch64::LDPWi;
264 case AArch64::LDRXui:
265 case AArch64::LDURXi:
266 return AArch64::LDPXi;
267 case AArch64::LDRSWui:
268 case AArch64::LDURSWi:
269 return AArch64::LDPSWi;
273 static unsigned getPreIndexedOpcode(unsigned Opc) {
276 llvm_unreachable("Opcode has no pre-indexed equivalent!");
277 case AArch64::STRSui:
278 return AArch64::STRSpre;
279 case AArch64::STRDui:
280 return AArch64::STRDpre;
281 case AArch64::STRQui:
282 return AArch64::STRQpre;
283 case AArch64::STRWui:
284 return AArch64::STRWpre;
285 case AArch64::STRXui:
286 return AArch64::STRXpre;
287 case AArch64::LDRSui:
288 return AArch64::LDRSpre;
289 case AArch64::LDRDui:
290 return AArch64::LDRDpre;
291 case AArch64::LDRQui:
292 return AArch64::LDRQpre;
293 case AArch64::LDRWui:
294 return AArch64::LDRWpre;
295 case AArch64::LDRXui:
296 return AArch64::LDRXpre;
297 case AArch64::LDRSWui:
298 return AArch64::LDRSWpre;
302 static unsigned getPostIndexedOpcode(unsigned Opc) {
305 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
306 case AArch64::STRSui:
307 return AArch64::STRSpost;
308 case AArch64::STRDui:
309 return AArch64::STRDpost;
310 case AArch64::STRQui:
311 return AArch64::STRQpost;
312 case AArch64::STRWui:
313 return AArch64::STRWpost;
314 case AArch64::STRXui:
315 return AArch64::STRXpost;
316 case AArch64::LDRSui:
317 return AArch64::LDRSpost;
318 case AArch64::LDRDui:
319 return AArch64::LDRDpost;
320 case AArch64::LDRQui:
321 return AArch64::LDRQpost;
322 case AArch64::LDRWui:
323 return AArch64::LDRWpost;
324 case AArch64::LDRXui:
325 return AArch64::LDRXpost;
326 case AArch64::LDRSWui:
327 return AArch64::LDRSWpost;
331 MachineBasicBlock::iterator
332 AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
333 MachineBasicBlock::iterator Paired,
334 const LdStPairFlags &Flags) {
335 MachineBasicBlock::iterator NextI = I;
337 // If NextI is the second of the two instructions to be merged, we need
338 // to skip one further. Either way we merge will invalidate the iterator,
339 // and we don't need to scan the new instruction, as it's a pairwise
340 // instruction, which we're not considering for further action anyway.
344 int SExtIdx = Flags.getSExtIdx();
346 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
347 bool IsUnscaled = isUnscaledLdst(Opc);
349 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(I) : 1;
351 bool MergeForward = Flags.getMergeForward();
352 unsigned NewOpc = getMatchingPairOpcode(Opc);
353 // Insert our new paired instruction after whichever of the paired
354 // instructions MergeForward indicates.
355 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
356 // Also based on MergeForward is from where we copy the base register operand
357 // so we get the flags compatible with the input code.
358 MachineOperand &BaseRegOp =
359 MergeForward ? Paired->getOperand(1) : I->getOperand(1);
361 // Which register is Rt and which is Rt2 depends on the offset order.
362 MachineInstr *RtMI, *Rt2MI;
363 if (I->getOperand(2).getImm() ==
364 Paired->getOperand(2).getImm() + OffsetStride) {
367 // Here we swapped the assumption made for SExtIdx.
368 // I.e., we turn ldp I, Paired into ldp Paired, I.
369 // Update the index accordingly.
371 SExtIdx = (SExtIdx + 1) % 2;
377 int OffsetImm = RtMI->getOperand(2).getImm();
378 if (IsUnscaled && EnableAArch64UnscaledMemOp)
379 OffsetImm /= OffsetStride;
381 // Construct the new instruction.
382 MachineInstrBuilder MIB = BuildMI(*I->getParent(), InsertionPoint,
383 I->getDebugLoc(), TII->get(NewOpc))
384 .addOperand(RtMI->getOperand(0))
385 .addOperand(Rt2MI->getOperand(0))
386 .addOperand(BaseRegOp)
390 // FIXME: Do we need/want to copy the mem operands from the source
391 // instructions? Probably. What uses them after this?
393 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
394 DEBUG(I->print(dbgs()));
395 DEBUG(dbgs() << " ");
396 DEBUG(Paired->print(dbgs()));
397 DEBUG(dbgs() << " with instruction:\n ");
400 // Generate the sign extension for the proper result of the ldp.
401 // I.e., with X1, that would be:
402 // %W1<def> = KILL %W1, %X1<imp-def>
403 // %X1<def> = SBFMXri %X1<kill>, 0, 31
404 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
405 // Right now, DstMO has the extended register, since it comes from an
407 unsigned DstRegX = DstMO.getReg();
408 // Get the W variant of that register.
409 unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
410 // Update the result of LDP to use the W instead of the X variant.
411 DstMO.setReg(DstRegW);
412 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
413 DEBUG(dbgs() << "\n");
414 // Make the machine verifier happy by providing a definition for
416 // Insert this definition right after the generated LDP, i.e., before
418 MachineInstrBuilder MIBKill =
419 BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
420 TII->get(TargetOpcode::KILL), DstRegW)
422 .addReg(DstRegX, RegState::Define);
423 MIBKill->getOperand(2).setImplicit();
424 // Create the sign extension.
425 MachineInstrBuilder MIBSXTW =
426 BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
427 TII->get(AArch64::SBFMXri), DstRegX)
432 DEBUG(dbgs() << " Extend operand:\n ");
433 DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
434 DEBUG(dbgs() << "\n");
436 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
437 DEBUG(dbgs() << "\n");
440 // Erase the old instructions.
441 I->eraseFromParent();
442 Paired->eraseFromParent();
447 /// trackRegDefsUses - Remember what registers the specified instruction uses
449 static void trackRegDefsUses(MachineInstr *MI, BitVector &ModifiedRegs,
451 const TargetRegisterInfo *TRI) {
452 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
453 MachineOperand &MO = MI->getOperand(i);
455 ModifiedRegs.setBitsNotInMask(MO.getRegMask());
459 unsigned Reg = MO.getReg();
461 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
462 ModifiedRegs.set(*AI);
464 assert(MO.isUse() && "Reg operand not a def and not a use?!?");
465 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
471 static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
472 if (!IsUnscaled && (Offset > 63 || Offset < -64))
475 // Convert the byte-offset used by unscaled into an "element" offset used
476 // by the scaled pair load/store instructions.
477 int ElemOffset = Offset / OffsetStride;
478 if (ElemOffset > 63 || ElemOffset < -64)
484 // Do alignment, specialized to power of 2 and for signed ints,
485 // avoiding having to do a C-style cast from uint_64t to int when
486 // using RoundUpToAlignment from include/llvm/Support/MathExtras.h.
487 // FIXME: Move this function to include/MathExtras.h?
488 static int alignTo(int Num, int PowOf2) {
489 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
492 static bool mayAlias(MachineInstr *MIa, MachineInstr *MIb,
493 const AArch64InstrInfo *TII) {
494 // One of the instructions must modify memory.
495 if (!MIa->mayStore() && !MIb->mayStore())
498 // Both instructions must be memory operations.
499 if (!MIa->mayLoadOrStore() && !MIb->mayLoadOrStore())
502 return !TII->areMemAccessesTriviallyDisjoint(MIa, MIb);
505 static bool mayAlias(MachineInstr *MIa,
506 SmallVectorImpl<MachineInstr *> &MemInsns,
507 const AArch64InstrInfo *TII) {
508 for (auto &MIb : MemInsns)
509 if (mayAlias(MIa, MIb, TII))
515 /// findMatchingInsn - Scan the instructions looking for a load/store that can
516 /// be combined with the current instruction into a load/store pair.
517 MachineBasicBlock::iterator
518 AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
519 LdStPairFlags &Flags,
521 MachineBasicBlock::iterator E = I->getParent()->end();
522 MachineBasicBlock::iterator MBBI = I;
523 MachineInstr *FirstMI = I;
526 unsigned Opc = FirstMI->getOpcode();
527 bool MayLoad = FirstMI->mayLoad();
528 bool IsUnscaled = isUnscaledLdst(Opc);
529 unsigned Reg = FirstMI->getOperand(0).getReg();
530 unsigned BaseReg = FirstMI->getOperand(1).getReg();
531 int Offset = FirstMI->getOperand(2).getImm();
533 // Early exit if the first instruction modifies the base register.
534 // e.g., ldr x0, [x0]
535 // Early exit if the offset if not possible to match. (6 bits of positive
536 // range, plus allow an extra one in case we find a later insn that matches
538 if (FirstMI->modifiesRegister(BaseReg, TRI))
541 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(FirstMI) : 1;
542 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
545 // Track which registers have been modified and used between the first insn
546 // (inclusive) and the second insn.
547 BitVector ModifiedRegs, UsedRegs;
548 ModifiedRegs.resize(TRI->getNumRegs());
549 UsedRegs.resize(TRI->getNumRegs());
551 // Remember any instructions that read/write memory between FirstMI and MI.
552 SmallVector<MachineInstr *, 4> MemInsns;
554 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
555 MachineInstr *MI = MBBI;
556 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
557 // optimization by changing how far we scan.
558 if (MI->isDebugValue())
561 // Now that we know this is a real instruction, count it.
564 bool CanMergeOpc = Opc == MI->getOpcode();
565 Flags.setSExtIdx(-1);
567 bool IsValidLdStrOpc;
568 unsigned NonSExtOpc = getMatchingNonSExtOpcode(Opc, &IsValidLdStrOpc);
569 if (!IsValidLdStrOpc)
571 // Opc will be the first instruction in the pair.
572 Flags.setSExtIdx(NonSExtOpc == (unsigned)Opc ? 1 : 0);
573 CanMergeOpc = NonSExtOpc == getMatchingNonSExtOpcode(MI->getOpcode());
576 if (CanMergeOpc && MI->getOperand(2).isImm()) {
577 // If we've found another instruction with the same opcode, check to see
578 // if the base and offset are compatible with our starting instruction.
579 // These instructions all have scaled immediate operands, so we just
580 // check for +1/-1. Make sure to check the new instruction offset is
581 // actually an immediate and not a symbolic reference destined for
584 // Pairwise instructions have a 7-bit signed offset field. Single insns
585 // have a 12-bit unsigned offset field. To be a valid combine, the
586 // final offset must be in range.
587 unsigned MIBaseReg = MI->getOperand(1).getReg();
588 int MIOffset = MI->getOperand(2).getImm();
589 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
590 (Offset + OffsetStride == MIOffset))) {
591 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
592 // If this is a volatile load/store that otherwise matched, stop looking
593 // as something is going on that we don't have enough information to
594 // safely transform. Similarly, stop if we see a hint to avoid pairs.
595 if (MI->hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
597 // If the resultant immediate offset of merging these instructions
598 // is out of range for a pairwise instruction, bail and keep looking.
599 bool MIIsUnscaled = isUnscaledLdst(MI->getOpcode());
600 if (!inBoundsForPair(MIIsUnscaled, MinOffset, OffsetStride)) {
601 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
602 if (MI->mayLoadOrStore())
603 MemInsns.push_back(MI);
606 // If the alignment requirements of the paired (scaled) instruction
607 // can't express the offset of the unscaled input, bail and keep
609 if (IsUnscaled && EnableAArch64UnscaledMemOp &&
610 (alignTo(MinOffset, OffsetStride) != MinOffset)) {
611 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
612 if (MI->mayLoadOrStore())
613 MemInsns.push_back(MI);
616 // If the destination register of the loads is the same register, bail
617 // and keep looking. A load-pair instruction with both destination
618 // registers the same is UNPREDICTABLE and will result in an exception.
619 if (MayLoad && Reg == MI->getOperand(0).getReg()) {
620 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
621 if (MI->mayLoadOrStore())
622 MemInsns.push_back(MI);
626 // If the Rt of the second instruction was not modified or used between
627 // the two instructions and none of the instructions between the second
628 // and first alias with the second, we can combine the second into the
630 if (!ModifiedRegs[MI->getOperand(0).getReg()] &&
631 !(MI->mayLoad() && UsedRegs[MI->getOperand(0).getReg()]) &&
632 !mayAlias(MI, MemInsns, TII)) {
633 Flags.setMergeForward(false);
637 // Likewise, if the Rt of the first instruction is not modified or used
638 // between the two instructions and none of the instructions between the
639 // first and the second alias with the first, we can combine the first
641 if (!ModifiedRegs[FirstMI->getOperand(0).getReg()] &&
642 !(FirstMI->mayLoad() &&
643 UsedRegs[FirstMI->getOperand(0).getReg()]) &&
644 !mayAlias(FirstMI, MemInsns, TII)) {
645 Flags.setMergeForward(true);
648 // Unable to combine these instructions due to interference in between.
653 // If the instruction wasn't a matching load or store. Stop searching if we
654 // encounter a call instruction that might modify memory.
658 // Update modified / uses register lists.
659 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
661 // Otherwise, if the base register is modified, we have no match, so
663 if (ModifiedRegs[BaseReg])
666 // Update list of instructions that read/write memory.
667 if (MI->mayLoadOrStore())
668 MemInsns.push_back(MI);
673 MachineBasicBlock::iterator
674 AArch64LoadStoreOpt::mergePreIdxUpdateInsn(MachineBasicBlock::iterator I,
675 MachineBasicBlock::iterator Update) {
676 assert((Update->getOpcode() == AArch64::ADDXri ||
677 Update->getOpcode() == AArch64::SUBXri) &&
678 "Unexpected base register update instruction to merge!");
679 MachineBasicBlock::iterator NextI = I;
680 // Return the instruction following the merged instruction, which is
681 // the instruction following our unmerged load. Unless that's the add/sub
682 // instruction we're merging, in which case it's the one after that.
683 if (++NextI == Update)
686 int Value = Update->getOperand(2).getImm();
687 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
688 "Can't merge 1 << 12 offset into pre-indexed load / store");
689 if (Update->getOpcode() == AArch64::SUBXri)
692 unsigned NewOpc = getPreIndexedOpcode(I->getOpcode());
693 MachineInstrBuilder MIB =
694 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
695 .addOperand(Update->getOperand(0))
696 .addOperand(I->getOperand(0))
697 .addOperand(I->getOperand(1))
701 DEBUG(dbgs() << "Creating pre-indexed load/store.");
702 DEBUG(dbgs() << " Replacing instructions:\n ");
703 DEBUG(I->print(dbgs()));
704 DEBUG(dbgs() << " ");
705 DEBUG(Update->print(dbgs()));
706 DEBUG(dbgs() << " with instruction:\n ");
707 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
708 DEBUG(dbgs() << "\n");
710 // Erase the old instructions for the block.
711 I->eraseFromParent();
712 Update->eraseFromParent();
717 MachineBasicBlock::iterator AArch64LoadStoreOpt::mergePostIdxUpdateInsn(
718 MachineBasicBlock::iterator I, MachineBasicBlock::iterator Update) {
719 assert((Update->getOpcode() == AArch64::ADDXri ||
720 Update->getOpcode() == AArch64::SUBXri) &&
721 "Unexpected base register update instruction to merge!");
722 MachineBasicBlock::iterator NextI = I;
723 // Return the instruction following the merged instruction, which is
724 // the instruction following our unmerged load. Unless that's the add/sub
725 // instruction we're merging, in which case it's the one after that.
726 if (++NextI == Update)
729 int Value = Update->getOperand(2).getImm();
730 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
731 "Can't merge 1 << 12 offset into post-indexed load / store");
732 if (Update->getOpcode() == AArch64::SUBXri)
735 unsigned NewOpc = getPostIndexedOpcode(I->getOpcode());
736 MachineInstrBuilder MIB =
737 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
738 .addOperand(Update->getOperand(0))
739 .addOperand(I->getOperand(0))
740 .addOperand(I->getOperand(1))
744 DEBUG(dbgs() << "Creating post-indexed load/store.");
745 DEBUG(dbgs() << " Replacing instructions:\n ");
746 DEBUG(I->print(dbgs()));
747 DEBUG(dbgs() << " ");
748 DEBUG(Update->print(dbgs()));
749 DEBUG(dbgs() << " with instruction:\n ");
750 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
751 DEBUG(dbgs() << "\n");
753 // Erase the old instructions for the block.
754 I->eraseFromParent();
755 Update->eraseFromParent();
760 static bool isMatchingUpdateInsn(MachineInstr *MI, unsigned BaseReg,
762 switch (MI->getOpcode()) {
765 case AArch64::SUBXri:
766 // Negate the offset for a SUB instruction.
769 case AArch64::ADDXri:
770 // Make sure it's a vanilla immediate operand, not a relocation or
771 // anything else we can't handle.
772 if (!MI->getOperand(2).isImm())
774 // Watch out for 1 << 12 shifted value.
775 if (AArch64_AM::getShiftValue(MI->getOperand(3).getImm()))
777 // If the instruction has the base register as source and dest and the
778 // immediate will fit in a signed 9-bit integer, then we have a match.
779 if (MI->getOperand(0).getReg() == BaseReg &&
780 MI->getOperand(1).getReg() == BaseReg &&
781 MI->getOperand(2).getImm() <= 255 &&
782 MI->getOperand(2).getImm() >= -256) {
783 // If we have a non-zero Offset, we check that it matches the amount
784 // we're adding to the register.
785 if (!Offset || Offset == MI->getOperand(2).getImm())
793 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
794 MachineBasicBlock::iterator I, unsigned Limit, int Value) {
795 MachineBasicBlock::iterator E = I->getParent()->end();
796 MachineInstr *MemMI = I;
797 MachineBasicBlock::iterator MBBI = I;
798 const MachineFunction &MF = *MemMI->getParent()->getParent();
800 unsigned DestReg = MemMI->getOperand(0).getReg();
801 unsigned BaseReg = MemMI->getOperand(1).getReg();
802 int Offset = MemMI->getOperand(2).getImm() *
803 TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
805 // If the base register overlaps the destination register, we can't
807 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
810 // Scan forward looking for post-index opportunities.
811 // Updating instructions can't be formed if the memory insn already
812 // has an offset other than the value we're looking for.
816 // Track which registers have been modified and used between the first insn
817 // (inclusive) and the second insn.
818 BitVector ModifiedRegs, UsedRegs;
819 ModifiedRegs.resize(TRI->getNumRegs());
820 UsedRegs.resize(TRI->getNumRegs());
822 for (unsigned Count = 0; MBBI != E; ++MBBI) {
823 MachineInstr *MI = MBBI;
824 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
825 // optimization by changing how far we scan.
826 if (MI->isDebugValue())
829 // Now that we know this is a real instruction, count it.
832 // If we found a match, return it.
833 if (isMatchingUpdateInsn(MI, BaseReg, Value))
836 // Update the status of what the instruction clobbered and used.
837 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
839 // Otherwise, if the base register is used or modified, we have no match, so
841 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
847 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
848 MachineBasicBlock::iterator I, unsigned Limit) {
849 MachineBasicBlock::iterator B = I->getParent()->begin();
850 MachineBasicBlock::iterator E = I->getParent()->end();
851 MachineInstr *MemMI = I;
852 MachineBasicBlock::iterator MBBI = I;
853 const MachineFunction &MF = *MemMI->getParent()->getParent();
855 unsigned DestReg = MemMI->getOperand(0).getReg();
856 unsigned BaseReg = MemMI->getOperand(1).getReg();
857 int Offset = MemMI->getOperand(2).getImm();
858 unsigned RegSize = TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
860 // If the load/store is the first instruction in the block, there's obviously
861 // not any matching update. Ditto if the memory offset isn't zero.
862 if (MBBI == B || Offset != 0)
864 // If the base register overlaps the destination register, we can't
866 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
869 // Track which registers have been modified and used between the first insn
870 // (inclusive) and the second insn.
871 BitVector ModifiedRegs, UsedRegs;
872 ModifiedRegs.resize(TRI->getNumRegs());
873 UsedRegs.resize(TRI->getNumRegs());
875 for (unsigned Count = 0; MBBI != B; --MBBI) {
876 MachineInstr *MI = MBBI;
877 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
878 // optimization by changing how far we scan.
879 if (MI->isDebugValue())
882 // Now that we know this is a real instruction, count it.
885 // If we found a match, return it.
886 if (isMatchingUpdateInsn(MI, BaseReg, RegSize))
889 // Update the status of what the instruction clobbered and used.
890 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
892 // Otherwise, if the base register is used or modified, we have no match, so
894 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
900 bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB) {
901 bool Modified = false;
902 // Two tranformations to do here:
903 // 1) Find loads and stores that can be merged into a single load or store
910 // 2) Find base register updates that can be merged into the load or store
911 // as a base-reg writeback.
918 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
920 MachineInstr *MI = MBBI;
921 switch (MI->getOpcode()) {
923 // Just move on to the next instruction.
926 case AArch64::STRSui:
927 case AArch64::STRDui:
928 case AArch64::STRQui:
929 case AArch64::STRXui:
930 case AArch64::STRWui:
931 case AArch64::LDRSui:
932 case AArch64::LDRDui:
933 case AArch64::LDRQui:
934 case AArch64::LDRXui:
935 case AArch64::LDRWui:
936 case AArch64::LDRSWui:
937 // do the unscaled versions as well
938 case AArch64::STURSi:
939 case AArch64::STURDi:
940 case AArch64::STURQi:
941 case AArch64::STURWi:
942 case AArch64::STURXi:
943 case AArch64::LDURSi:
944 case AArch64::LDURDi:
945 case AArch64::LDURQi:
946 case AArch64::LDURWi:
947 case AArch64::LDURXi:
948 case AArch64::LDURSWi: {
949 // If this is a volatile load/store, don't mess with it.
950 if (MI->hasOrderedMemoryRef()) {
954 // Make sure this is a reg+imm (as opposed to an address reloc).
955 if (!MI->getOperand(2).isImm()) {
959 // Check if this load/store has a hint to avoid pair formation.
960 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
961 if (TII->isLdStPairSuppressed(MI)) {
965 // Look ahead up to ScanLimit instructions for a pairable instruction.
967 MachineBasicBlock::iterator Paired =
968 findMatchingInsn(MBBI, Flags, ScanLimit);
970 // Merge the loads into a pair. Keeping the iterator straight is a
971 // pain, so we let the merge routine tell us what the next instruction
972 // is after it's done mucking about.
973 MBBI = mergePairedInsns(MBBI, Paired, Flags);
977 if (isUnscaledLdst(MI->getOpcode()))
978 ++NumUnscaledPairCreated;
984 // FIXME: Do the other instructions.
988 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
990 MachineInstr *MI = MBBI;
991 // Do update merging. It's simpler to keep this separate from the above
992 // switch, though not strictly necessary.
993 unsigned Opc = MI->getOpcode();
996 // Just move on to the next instruction.
999 case AArch64::STRSui:
1000 case AArch64::STRDui:
1001 case AArch64::STRQui:
1002 case AArch64::STRXui:
1003 case AArch64::STRWui:
1004 case AArch64::LDRSui:
1005 case AArch64::LDRDui:
1006 case AArch64::LDRQui:
1007 case AArch64::LDRXui:
1008 case AArch64::LDRWui:
1009 // do the unscaled versions as well
1010 case AArch64::STURSi:
1011 case AArch64::STURDi:
1012 case AArch64::STURQi:
1013 case AArch64::STURWi:
1014 case AArch64::STURXi:
1015 case AArch64::LDURSi:
1016 case AArch64::LDURDi:
1017 case AArch64::LDURQi:
1018 case AArch64::LDURWi:
1019 case AArch64::LDURXi: {
1020 // Make sure this is a reg+imm (as opposed to an address reloc).
1021 if (!MI->getOperand(2).isImm()) {
1025 // Look ahead up to ScanLimit instructions for a mergable instruction.
1026 MachineBasicBlock::iterator Update =
1027 findMatchingUpdateInsnForward(MBBI, ScanLimit, 0);
1029 // Merge the update into the ld/st.
1030 MBBI = mergePostIdxUpdateInsn(MBBI, Update);
1035 // Don't know how to handle pre/post-index versions, so move to the next
1037 if (isUnscaledLdst(Opc)) {
1042 // Look back to try to find a pre-index instruction. For example,
1046 // ldr x1, [x0, #8]!
1047 Update = findMatchingUpdateInsnBackward(MBBI, ScanLimit);
1049 // Merge the update into the ld/st.
1050 MBBI = mergePreIdxUpdateInsn(MBBI, Update);
1056 // Look forward to try to find a post-index instruction. For example,
1057 // ldr x1, [x0, #64]
1060 // ldr x1, [x0, #64]!
1062 // The immediate in the load/store is scaled by the size of the register
1063 // being loaded. The immediate in the add we're looking for,
1064 // however, is not, so adjust here.
1065 int Value = MI->getOperand(2).getImm() *
1066 TII->getRegClass(MI->getDesc(), 0, TRI, *(MBB.getParent()))
1068 Update = findMatchingUpdateInsnForward(MBBI, ScanLimit, Value);
1070 // Merge the update into the ld/st.
1071 MBBI = mergePreIdxUpdateInsn(MBBI, Update);
1077 // Nothing found. Just move to the next instruction.
1081 // FIXME: Do the other instructions.
1088 bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
1089 TII = static_cast<const AArch64InstrInfo *>(Fn.getSubtarget().getInstrInfo());
1090 TRI = Fn.getSubtarget().getRegisterInfo();
1092 bool Modified = false;
1093 for (auto &MBB : Fn)
1094 Modified |= optimizeBlock(MBB);
1099 // FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
1100 // loads and stores near one another?
1102 /// createARMLoadStoreOptimizationPass - returns an instance of the load / store
1103 /// optimization pass.
1104 FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
1105 return new AArch64LoadStoreOpt();