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));
54 void initializeAArch64LoadStoreOptPass(PassRegistry &);
57 #define AARCH64_LOAD_STORE_OPT_NAME "AArch64 load / store optimization pass"
61 typedef struct LdStPairFlags {
62 // If a matching instruction is found, MergeForward is set to true if the
63 // merge is to remove the first instruction and replace the second with
64 // a pair-wise insn, and false if the reverse is true.
67 // SExtIdx gives the index of the result of the load pair that must be
68 // extended. The value of SExtIdx assumes that the paired load produces the
69 // value in this order: (I, returned iterator), i.e., -1 means no value has
70 // to be extended, 0 means I, and 1 means the returned iterator.
73 LdStPairFlags() : MergeForward(false), SExtIdx(-1) {}
75 void setMergeForward(bool V = true) { MergeForward = V; }
76 bool getMergeForward() const { return MergeForward; }
78 void setSExtIdx(int V) { SExtIdx = V; }
79 int getSExtIdx() const { return SExtIdx; }
83 struct AArch64LoadStoreOpt : public MachineFunctionPass {
85 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {
86 initializeAArch64LoadStoreOptPass(*PassRegistry::getPassRegistry());
89 const AArch64InstrInfo *TII;
90 const TargetRegisterInfo *TRI;
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,
98 // Merge the two instructions indicated into a single pair-wise instruction.
99 // If MergeForward is true, erase the first instruction and fold its
100 // operation into the second. If false, the reverse. Return the instruction
101 // following the first instruction (which may change during processing).
102 MachineBasicBlock::iterator
103 mergePairedInsns(MachineBasicBlock::iterator I,
104 MachineBasicBlock::iterator Paired,
105 const LdStPairFlags &Flags);
107 // Scan the instruction list to find a base register update that can
108 // be combined with the current instruction (a load or store) using
109 // pre or post indexed addressing with writeback. Scan forwards.
110 MachineBasicBlock::iterator
111 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I, unsigned Limit,
114 // Scan the instruction list to find a base register update that can
115 // be combined with the current instruction (a load or store) using
116 // pre or post indexed addressing with writeback. Scan backwards.
117 MachineBasicBlock::iterator
118 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
120 // Merge a pre-index base register update into a ld/st instruction.
121 MachineBasicBlock::iterator
122 mergePreIdxUpdateInsn(MachineBasicBlock::iterator I,
123 MachineBasicBlock::iterator Update);
125 // Merge a post-index base register update into a ld/st instruction.
126 MachineBasicBlock::iterator
127 mergePostIdxUpdateInsn(MachineBasicBlock::iterator I,
128 MachineBasicBlock::iterator Update);
130 bool optimizeBlock(MachineBasicBlock &MBB);
132 bool runOnMachineFunction(MachineFunction &Fn) override;
134 const char *getPassName() const override {
135 return AARCH64_LOAD_STORE_OPT_NAME;
138 char AArch64LoadStoreOpt::ID = 0;
141 INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
142 AARCH64_LOAD_STORE_OPT_NAME, false, false)
144 static bool isUnscaledLdSt(unsigned Opc) {
148 case AArch64::STURSi:
149 case AArch64::STURDi:
150 case AArch64::STURQi:
151 case AArch64::STURWi:
152 case AArch64::STURXi:
153 case AArch64::LDURSi:
154 case AArch64::LDURDi:
155 case AArch64::LDURQi:
156 case AArch64::LDURWi:
157 case AArch64::LDURXi:
158 case AArch64::LDURSWi:
163 static bool isUnscaledLdSt(MachineInstr *MI) {
164 return isUnscaledLdSt(MI->getOpcode());
167 // Size in bytes of the data moved by an unscaled load or store
168 static int getMemSize(MachineInstr *MI) {
169 switch (MI->getOpcode()) {
171 llvm_unreachable("Opcode has unknown size!");
172 case AArch64::STRSui:
173 case AArch64::STURSi:
175 case AArch64::STRDui:
176 case AArch64::STURDi:
178 case AArch64::STRQui:
179 case AArch64::STURQi:
181 case AArch64::STRWui:
182 case AArch64::STURWi:
184 case AArch64::STRXui:
185 case AArch64::STURXi:
187 case AArch64::LDRSui:
188 case AArch64::LDURSi:
190 case AArch64::LDRDui:
191 case AArch64::LDURDi:
193 case AArch64::LDRQui:
194 case AArch64::LDURQi:
196 case AArch64::LDRWui:
197 case AArch64::LDURWi:
199 case AArch64::LDRXui:
200 case AArch64::LDURXi:
202 case AArch64::LDRSWui:
203 case AArch64::LDURSWi:
208 static unsigned getMatchingNonSExtOpcode(unsigned Opc,
209 bool *IsValidLdStrOpc = nullptr) {
211 *IsValidLdStrOpc = true;
215 *IsValidLdStrOpc = false;
217 case AArch64::STRDui:
218 case AArch64::STURDi:
219 case AArch64::STRQui:
220 case AArch64::STURQi:
221 case AArch64::STRWui:
222 case AArch64::STURWi:
223 case AArch64::STRXui:
224 case AArch64::STURXi:
225 case AArch64::LDRDui:
226 case AArch64::LDURDi:
227 case AArch64::LDRQui:
228 case AArch64::LDURQi:
229 case AArch64::LDRWui:
230 case AArch64::LDURWi:
231 case AArch64::LDRXui:
232 case AArch64::LDURXi:
233 case AArch64::STRSui:
234 case AArch64::STURSi:
235 case AArch64::LDRSui:
236 case AArch64::LDURSi:
238 case AArch64::LDRSWui:
239 return AArch64::LDRWui;
240 case AArch64::LDURSWi:
241 return AArch64::LDURWi;
245 static unsigned getMatchingPairOpcode(unsigned Opc) {
248 llvm_unreachable("Opcode has no pairwise equivalent!");
249 case AArch64::STRSui:
250 case AArch64::STURSi:
251 return AArch64::STPSi;
252 case AArch64::STRDui:
253 case AArch64::STURDi:
254 return AArch64::STPDi;
255 case AArch64::STRQui:
256 case AArch64::STURQi:
257 return AArch64::STPQi;
258 case AArch64::STRWui:
259 case AArch64::STURWi:
260 return AArch64::STPWi;
261 case AArch64::STRXui:
262 case AArch64::STURXi:
263 return AArch64::STPXi;
264 case AArch64::LDRSui:
265 case AArch64::LDURSi:
266 return AArch64::LDPSi;
267 case AArch64::LDRDui:
268 case AArch64::LDURDi:
269 return AArch64::LDPDi;
270 case AArch64::LDRQui:
271 case AArch64::LDURQi:
272 return AArch64::LDPQi;
273 case AArch64::LDRWui:
274 case AArch64::LDURWi:
275 return AArch64::LDPWi;
276 case AArch64::LDRXui:
277 case AArch64::LDURXi:
278 return AArch64::LDPXi;
279 case AArch64::LDRSWui:
280 case AArch64::LDURSWi:
281 return AArch64::LDPSWi;
285 static unsigned getPreIndexedOpcode(unsigned Opc) {
288 llvm_unreachable("Opcode has no pre-indexed equivalent!");
289 case AArch64::STRSui:
290 return AArch64::STRSpre;
291 case AArch64::STRDui:
292 return AArch64::STRDpre;
293 case AArch64::STRQui:
294 return AArch64::STRQpre;
295 case AArch64::STRWui:
296 return AArch64::STRWpre;
297 case AArch64::STRXui:
298 return AArch64::STRXpre;
299 case AArch64::LDRSui:
300 return AArch64::LDRSpre;
301 case AArch64::LDRDui:
302 return AArch64::LDRDpre;
303 case AArch64::LDRQui:
304 return AArch64::LDRQpre;
305 case AArch64::LDRWui:
306 return AArch64::LDRWpre;
307 case AArch64::LDRXui:
308 return AArch64::LDRXpre;
309 case AArch64::LDRSWui:
310 return AArch64::LDRSWpre;
314 static unsigned getPostIndexedOpcode(unsigned Opc) {
317 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
318 case AArch64::STRSui:
319 return AArch64::STRSpost;
320 case AArch64::STRDui:
321 return AArch64::STRDpost;
322 case AArch64::STRQui:
323 return AArch64::STRQpost;
324 case AArch64::STRWui:
325 return AArch64::STRWpost;
326 case AArch64::STRXui:
327 return AArch64::STRXpost;
328 case AArch64::LDRSui:
329 return AArch64::LDRSpost;
330 case AArch64::LDRDui:
331 return AArch64::LDRDpost;
332 case AArch64::LDRQui:
333 return AArch64::LDRQpost;
334 case AArch64::LDRWui:
335 return AArch64::LDRWpost;
336 case AArch64::LDRXui:
337 return AArch64::LDRXpost;
338 case AArch64::LDRSWui:
339 return AArch64::LDRSWpost;
343 static const MachineOperand &getLdStRegOp(const MachineInstr *MI) {
344 return MI->getOperand(0);
347 static const MachineOperand &getLdStBaseOp(const MachineInstr *MI) {
348 return MI->getOperand(1);
351 static const MachineOperand &getLdStOffsetOp(const MachineInstr *MI) {
352 return MI->getOperand(2);
355 MachineBasicBlock::iterator
356 AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
357 MachineBasicBlock::iterator Paired,
358 const LdStPairFlags &Flags) {
359 MachineBasicBlock::iterator NextI = I;
361 // If NextI is the second of the two instructions to be merged, we need
362 // to skip one further. Either way we merge will invalidate the iterator,
363 // and we don't need to scan the new instruction, as it's a pairwise
364 // instruction, which we're not considering for further action anyway.
368 int SExtIdx = Flags.getSExtIdx();
370 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
371 bool IsUnscaled = isUnscaledLdSt(Opc);
373 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(I) : 1;
375 bool MergeForward = Flags.getMergeForward();
376 unsigned NewOpc = getMatchingPairOpcode(Opc);
377 // Insert our new paired instruction after whichever of the paired
378 // instructions MergeForward indicates.
379 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
380 // Also based on MergeForward is from where we copy the base register operand
381 // so we get the flags compatible with the input code.
382 const MachineOperand &BaseRegOp =
383 MergeForward ? getLdStBaseOp(Paired) : getLdStBaseOp(I);
385 int Offset = getLdStOffsetOp(I).getImm();
386 int PairedOffset = getLdStOffsetOp(Paired).getImm();
388 // Which register is Rt and which is Rt2 depends on the offset order.
389 MachineInstr *RtMI, *Rt2MI;
390 if (Offset == PairedOffset + OffsetStride) {
393 // Here we swapped the assumption made for SExtIdx.
394 // I.e., we turn ldp I, Paired into ldp Paired, I.
395 // Update the index accordingly.
397 SExtIdx = (SExtIdx + 1) % 2;
402 // Scale the immediate offset, if necessary.
403 int OffsetImm = getLdStOffsetOp(RtMI).getImm();
404 if (IsUnscaled && EnableAArch64UnscaledMemOp)
405 OffsetImm /= OffsetStride;
407 // Construct the new instruction.
408 MachineInstrBuilder MIB = BuildMI(*I->getParent(), InsertionPoint,
409 I->getDebugLoc(), TII->get(NewOpc))
410 .addOperand(getLdStRegOp(RtMI))
411 .addOperand(getLdStRegOp(Rt2MI))
412 .addOperand(BaseRegOp)
416 // FIXME: Do we need/want to copy the mem operands from the source
417 // instructions? Probably. What uses them after this?
419 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
420 DEBUG(I->print(dbgs()));
421 DEBUG(dbgs() << " ");
422 DEBUG(Paired->print(dbgs()));
423 DEBUG(dbgs() << " with instruction:\n ");
426 // Generate the sign extension for the proper result of the ldp.
427 // I.e., with X1, that would be:
428 // %W1<def> = KILL %W1, %X1<imp-def>
429 // %X1<def> = SBFMXri %X1<kill>, 0, 31
430 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
431 // Right now, DstMO has the extended register, since it comes from an
433 unsigned DstRegX = DstMO.getReg();
434 // Get the W variant of that register.
435 unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
436 // Update the result of LDP to use the W instead of the X variant.
437 DstMO.setReg(DstRegW);
438 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
439 DEBUG(dbgs() << "\n");
440 // Make the machine verifier happy by providing a definition for
442 // Insert this definition right after the generated LDP, i.e., before
444 MachineInstrBuilder MIBKill =
445 BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
446 TII->get(TargetOpcode::KILL), DstRegW)
448 .addReg(DstRegX, RegState::Define);
449 MIBKill->getOperand(2).setImplicit();
450 // Create the sign extension.
451 MachineInstrBuilder MIBSXTW =
452 BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
453 TII->get(AArch64::SBFMXri), DstRegX)
458 DEBUG(dbgs() << " Extend operand:\n ");
459 DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
460 DEBUG(dbgs() << "\n");
462 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
463 DEBUG(dbgs() << "\n");
466 // Erase the old instructions.
467 I->eraseFromParent();
468 Paired->eraseFromParent();
473 /// trackRegDefsUses - Remember what registers the specified instruction uses
475 static void trackRegDefsUses(const MachineInstr *MI, BitVector &ModifiedRegs,
477 const TargetRegisterInfo *TRI) {
478 for (const MachineOperand &MO : MI->operands()) {
480 ModifiedRegs.setBitsNotInMask(MO.getRegMask());
484 unsigned Reg = MO.getReg();
486 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
487 ModifiedRegs.set(*AI);
489 assert(MO.isUse() && "Reg operand not a def and not a use?!?");
490 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
496 static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
497 // Convert the byte-offset used by unscaled into an "element" offset used
498 // by the scaled pair load/store instructions.
500 Offset /= OffsetStride;
502 return Offset <= 63 && Offset >= -64;
505 // Do alignment, specialized to power of 2 and for signed ints,
506 // avoiding having to do a C-style cast from uint_64t to int when
507 // using RoundUpToAlignment from include/llvm/Support/MathExtras.h.
508 // FIXME: Move this function to include/MathExtras.h?
509 static int alignTo(int Num, int PowOf2) {
510 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
513 static bool mayAlias(MachineInstr *MIa, MachineInstr *MIb,
514 const AArch64InstrInfo *TII) {
515 // One of the instructions must modify memory.
516 if (!MIa->mayStore() && !MIb->mayStore())
519 // Both instructions must be memory operations.
520 if (!MIa->mayLoadOrStore() && !MIb->mayLoadOrStore())
523 return !TII->areMemAccessesTriviallyDisjoint(MIa, MIb);
526 static bool mayAlias(MachineInstr *MIa,
527 SmallVectorImpl<MachineInstr *> &MemInsns,
528 const AArch64InstrInfo *TII) {
529 for (auto &MIb : MemInsns)
530 if (mayAlias(MIa, MIb, TII))
536 static bool canMergeOpc(unsigned Opc, unsigned PairOpc, LdStPairFlags &Flags) {
537 bool CanMergeOpc = Opc == PairOpc;
538 // Opcodes match nothing more to check.
542 // Try to match a signed-extended load/store with a zero-extended load/store.
543 Flags.setSExtIdx(-1);
544 bool IsValidLdStrOpc;
545 unsigned NonSExtOpc = getMatchingNonSExtOpcode(Opc, &IsValidLdStrOpc);
546 assert(IsValidLdStrOpc &&
547 "Given Opc should be a Load or Store with an immediate");
548 // Opc will be the first instruction in the pair.
549 CanMergeOpc = NonSExtOpc == getMatchingNonSExtOpcode(PairOpc);
551 Flags.setSExtIdx(NonSExtOpc == (unsigned)Opc ? 1 : 0);
558 /// findMatchingInsn - Scan the instructions looking for a load/store that can
559 /// be combined with the current instruction into a load/store pair.
560 MachineBasicBlock::iterator
561 AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
562 LdStPairFlags &Flags,
564 MachineBasicBlock::iterator E = I->getParent()->end();
565 MachineBasicBlock::iterator MBBI = I;
566 MachineInstr *FirstMI = I;
569 unsigned Opc = FirstMI->getOpcode();
570 bool MayLoad = FirstMI->mayLoad();
571 bool IsUnscaled = isUnscaledLdSt(FirstMI);
572 unsigned Reg = getLdStRegOp(FirstMI).getReg();
573 unsigned BaseReg = getLdStBaseOp(FirstMI).getReg();
574 int Offset = getLdStOffsetOp(FirstMI).getImm();
576 // Early exit if the first instruction modifies the base register.
577 // e.g., ldr x0, [x0]
578 if (FirstMI->modifiesRegister(BaseReg, TRI))
581 // Early exit if the offset if not possible to match. (6 bits of positive
582 // range, plus allow an extra one in case we find a later insn that matches
585 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(FirstMI) : 1;
586 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
589 // Track which registers have been modified and used between the first insn
590 // (inclusive) and the second insn.
591 BitVector ModifiedRegs, UsedRegs;
592 ModifiedRegs.resize(TRI->getNumRegs());
593 UsedRegs.resize(TRI->getNumRegs());
595 // Remember any instructions that read/write memory between FirstMI and MI.
596 SmallVector<MachineInstr *, 4> MemInsns;
598 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
599 MachineInstr *MI = MBBI;
600 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
601 // optimization by changing how far we scan.
602 if (MI->isDebugValue())
605 // Now that we know this is a real instruction, count it.
608 if (canMergeOpc(Opc, MI->getOpcode(), Flags) &&
609 getLdStOffsetOp(MI).isImm()) {
610 assert(MI->mayLoadOrStore() && "Expected memory operation.");
611 // If we've found another instruction with the same opcode, check to see
612 // if the base and offset are compatible with our starting instruction.
613 // These instructions all have scaled immediate operands, so we just
614 // check for +1/-1. Make sure to check the new instruction offset is
615 // actually an immediate and not a symbolic reference destined for
618 // Pairwise instructions have a 7-bit signed offset field. Single insns
619 // have a 12-bit unsigned offset field. To be a valid combine, the
620 // final offset must be in range.
621 unsigned MIBaseReg = getLdStBaseOp(MI).getReg();
622 int MIOffset = getLdStOffsetOp(MI).getImm();
623 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
624 (Offset + OffsetStride == MIOffset))) {
625 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
626 // If this is a volatile load/store that otherwise matched, stop looking
627 // as something is going on that we don't have enough information to
628 // safely transform. Similarly, stop if we see a hint to avoid pairs.
629 if (MI->hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
631 // If the resultant immediate offset of merging these instructions
632 // is out of range for a pairwise instruction, bail and keep looking.
633 assert (IsUnscaled == isUnscaledLdSt(MI) &&
634 "Pair candidates should not be a mix of scaled and unscaled.");
635 if (!inBoundsForPair(IsUnscaled, MinOffset, OffsetStride)) {
636 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
637 MemInsns.push_back(MI);
640 // If the alignment requirements of the paired (scaled) instruction
641 // can't express the offset of the unscaled input, bail and keep
643 if (IsUnscaled && EnableAArch64UnscaledMemOp &&
644 (alignTo(MinOffset, OffsetStride) != MinOffset)) {
645 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
646 MemInsns.push_back(MI);
649 // If the destination register of the loads is the same register, bail
650 // and keep looking. A load-pair instruction with both destination
651 // registers the same is UNPREDICTABLE and will result in an exception.
652 if (MayLoad && Reg == getLdStRegOp(MI).getReg()) {
653 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
654 MemInsns.push_back(MI);
658 // If the Rt of the second instruction was not modified or used between
659 // the two instructions and none of the instructions between the second
660 // and first alias with the second, we can combine the second into the
662 if (!ModifiedRegs[getLdStRegOp(MI).getReg()] &&
663 !(MI->mayLoad() && UsedRegs[getLdStRegOp(MI).getReg()]) &&
664 !mayAlias(MI, MemInsns, TII)) {
665 Flags.setMergeForward(false);
669 // Likewise, if the Rt of the first instruction is not modified or used
670 // between the two instructions and none of the instructions between the
671 // first and the second alias with the first, we can combine the first
673 if (!ModifiedRegs[getLdStRegOp(FirstMI).getReg()] &&
674 !(FirstMI->mayLoad() && UsedRegs[getLdStRegOp(FirstMI).getReg()]) &&
675 !mayAlias(FirstMI, MemInsns, TII)) {
676 Flags.setMergeForward(true);
679 // Unable to combine these instructions due to interference in between.
684 // If the instruction wasn't a matching load or store. Stop searching if we
685 // encounter a call instruction that might modify memory.
689 // Update modified / uses register lists.
690 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
692 // Otherwise, if the base register is modified, we have no match, so
694 if (ModifiedRegs[BaseReg])
697 // Update list of instructions that read/write memory.
698 if (MI->mayLoadOrStore())
699 MemInsns.push_back(MI);
704 MachineBasicBlock::iterator
705 AArch64LoadStoreOpt::mergePreIdxUpdateInsn(MachineBasicBlock::iterator I,
706 MachineBasicBlock::iterator Update) {
707 assert((Update->getOpcode() == AArch64::ADDXri ||
708 Update->getOpcode() == AArch64::SUBXri) &&
709 "Unexpected base register update instruction to merge!");
710 MachineBasicBlock::iterator NextI = I;
711 // Return the instruction following the merged instruction, which is
712 // the instruction following our unmerged load. Unless that's the add/sub
713 // instruction we're merging, in which case it's the one after that.
714 if (++NextI == Update)
717 int Value = Update->getOperand(2).getImm();
718 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
719 "Can't merge 1 << 12 offset into pre-indexed load / store");
720 if (Update->getOpcode() == AArch64::SUBXri)
723 unsigned NewOpc = getPreIndexedOpcode(I->getOpcode());
724 MachineInstrBuilder MIB =
725 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
726 .addOperand(getLdStRegOp(Update))
727 .addOperand(getLdStRegOp(I))
728 .addOperand(getLdStBaseOp(I))
732 DEBUG(dbgs() << "Creating pre-indexed load/store.");
733 DEBUG(dbgs() << " Replacing instructions:\n ");
734 DEBUG(I->print(dbgs()));
735 DEBUG(dbgs() << " ");
736 DEBUG(Update->print(dbgs()));
737 DEBUG(dbgs() << " with instruction:\n ");
738 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
739 DEBUG(dbgs() << "\n");
741 // Erase the old instructions for the block.
742 I->eraseFromParent();
743 Update->eraseFromParent();
748 MachineBasicBlock::iterator AArch64LoadStoreOpt::mergePostIdxUpdateInsn(
749 MachineBasicBlock::iterator I, MachineBasicBlock::iterator Update) {
750 assert((Update->getOpcode() == AArch64::ADDXri ||
751 Update->getOpcode() == AArch64::SUBXri) &&
752 "Unexpected base register update instruction to merge!");
753 MachineBasicBlock::iterator NextI = I;
754 // Return the instruction following the merged instruction, which is
755 // the instruction following our unmerged load. Unless that's the add/sub
756 // instruction we're merging, in which case it's the one after that.
757 if (++NextI == Update)
760 int Value = Update->getOperand(2).getImm();
761 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
762 "Can't merge 1 << 12 offset into post-indexed load / store");
763 if (Update->getOpcode() == AArch64::SUBXri)
766 unsigned NewOpc = getPostIndexedOpcode(I->getOpcode());
767 MachineInstrBuilder MIB =
768 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
769 .addOperand(getLdStRegOp(Update))
770 .addOperand(getLdStRegOp(I))
771 .addOperand(getLdStBaseOp(I))
775 DEBUG(dbgs() << "Creating post-indexed load/store.");
776 DEBUG(dbgs() << " Replacing instructions:\n ");
777 DEBUG(I->print(dbgs()));
778 DEBUG(dbgs() << " ");
779 DEBUG(Update->print(dbgs()));
780 DEBUG(dbgs() << " with instruction:\n ");
781 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
782 DEBUG(dbgs() << "\n");
784 // Erase the old instructions for the block.
785 I->eraseFromParent();
786 Update->eraseFromParent();
791 static bool isMatchingUpdateInsn(MachineInstr *MI, unsigned BaseReg,
793 switch (MI->getOpcode()) {
796 case AArch64::SUBXri:
797 // Negate the offset for a SUB instruction.
800 case AArch64::ADDXri:
801 // Make sure it's a vanilla immediate operand, not a relocation or
802 // anything else we can't handle.
803 if (!MI->getOperand(2).isImm())
805 // Watch out for 1 << 12 shifted value.
806 if (AArch64_AM::getShiftValue(MI->getOperand(3).getImm()))
808 // If the instruction has the base register as source and dest and the
809 // immediate will fit in a signed 9-bit integer, then we have a match.
810 if (getLdStRegOp(MI).getReg() == BaseReg &&
811 getLdStBaseOp(MI).getReg() == BaseReg &&
812 getLdStOffsetOp(MI).getImm() <= 255 &&
813 getLdStOffsetOp(MI).getImm() >= -256) {
814 // If we have a non-zero Offset, we check that it matches the amount
815 // we're adding to the register.
816 if (!Offset || Offset == MI->getOperand(2).getImm())
824 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
825 MachineBasicBlock::iterator I, unsigned Limit, int Value) {
826 MachineBasicBlock::iterator E = I->getParent()->end();
827 MachineInstr *MemMI = I;
828 MachineBasicBlock::iterator MBBI = I;
829 const MachineFunction &MF = *MemMI->getParent()->getParent();
831 unsigned DestReg = getLdStRegOp(MemMI).getReg();
832 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
833 int Offset = getLdStOffsetOp(MemMI).getImm() *
834 TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
836 // If the base register overlaps the destination register, we can't
838 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
841 // Scan forward looking for post-index opportunities.
842 // Updating instructions can't be formed if the memory insn already
843 // has an offset other than the value we're looking for.
847 // Track which registers have been modified and used between the first insn
848 // (inclusive) and the second insn.
849 BitVector ModifiedRegs, UsedRegs;
850 ModifiedRegs.resize(TRI->getNumRegs());
851 UsedRegs.resize(TRI->getNumRegs());
853 for (unsigned Count = 0; MBBI != E; ++MBBI) {
854 MachineInstr *MI = MBBI;
855 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
856 // optimization by changing how far we scan.
857 if (MI->isDebugValue())
860 // Now that we know this is a real instruction, count it.
863 // If we found a match, return it.
864 if (isMatchingUpdateInsn(MI, BaseReg, Value))
867 // Update the status of what the instruction clobbered and used.
868 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
870 // Otherwise, if the base register is used or modified, we have no match, so
872 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
878 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
879 MachineBasicBlock::iterator I, unsigned Limit) {
880 MachineBasicBlock::iterator B = I->getParent()->begin();
881 MachineBasicBlock::iterator E = I->getParent()->end();
882 MachineInstr *MemMI = I;
883 MachineBasicBlock::iterator MBBI = I;
884 const MachineFunction &MF = *MemMI->getParent()->getParent();
886 unsigned DestReg = getLdStRegOp(MemMI).getReg();
887 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
888 int Offset = getLdStOffsetOp(MemMI).getImm();
889 unsigned RegSize = TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
891 // If the load/store is the first instruction in the block, there's obviously
892 // not any matching update. Ditto if the memory offset isn't zero.
893 if (MBBI == B || Offset != 0)
895 // If the base register overlaps the destination register, we can't
897 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
900 // Track which registers have been modified and used between the first insn
901 // (inclusive) and the second insn.
902 BitVector ModifiedRegs, UsedRegs;
903 ModifiedRegs.resize(TRI->getNumRegs());
904 UsedRegs.resize(TRI->getNumRegs());
906 for (unsigned Count = 0; MBBI != B; --MBBI) {
907 MachineInstr *MI = MBBI;
908 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
909 // optimization by changing how far we scan.
910 if (MI->isDebugValue())
913 // Now that we know this is a real instruction, count it.
916 // If we found a match, return it.
917 if (isMatchingUpdateInsn(MI, BaseReg, RegSize))
920 // Update the status of what the instruction clobbered and used.
921 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
923 // Otherwise, if the base register is used or modified, we have no match, so
925 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
931 bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB) {
932 bool Modified = false;
933 // Two tranformations to do here:
934 // 1) Find loads and stores that can be merged into a single load or store
941 // 2) Find base register updates that can be merged into the load or store
942 // as a base-reg writeback.
949 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
951 MachineInstr *MI = MBBI;
952 switch (MI->getOpcode()) {
954 // Just move on to the next instruction.
957 case AArch64::STRSui:
958 case AArch64::STRDui:
959 case AArch64::STRQui:
960 case AArch64::STRXui:
961 case AArch64::STRWui:
962 case AArch64::LDRSui:
963 case AArch64::LDRDui:
964 case AArch64::LDRQui:
965 case AArch64::LDRXui:
966 case AArch64::LDRWui:
967 case AArch64::LDRSWui:
968 // do the unscaled versions as well
969 case AArch64::STURSi:
970 case AArch64::STURDi:
971 case AArch64::STURQi:
972 case AArch64::STURWi:
973 case AArch64::STURXi:
974 case AArch64::LDURSi:
975 case AArch64::LDURDi:
976 case AArch64::LDURQi:
977 case AArch64::LDURWi:
978 case AArch64::LDURXi:
979 case AArch64::LDURSWi: {
980 // If this is a volatile load/store, don't mess with it.
981 if (MI->hasOrderedMemoryRef()) {
985 // Make sure this is a reg+imm (as opposed to an address reloc).
986 if (!getLdStOffsetOp(MI).isImm()) {
990 // Check if this load/store has a hint to avoid pair formation.
991 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
992 if (TII->isLdStPairSuppressed(MI)) {
996 // Look ahead up to ScanLimit instructions for a pairable instruction.
998 MachineBasicBlock::iterator Paired =
999 findMatchingInsn(MBBI, Flags, ScanLimit);
1001 // Merge the loads into a pair. Keeping the iterator straight is a
1002 // pain, so we let the merge routine tell us what the next instruction
1003 // is after it's done mucking about.
1004 MBBI = mergePairedInsns(MBBI, Paired, Flags);
1008 if (isUnscaledLdSt(MI))
1009 ++NumUnscaledPairCreated;
1015 // FIXME: Do the other instructions.
1019 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1021 MachineInstr *MI = MBBI;
1022 // Do update merging. It's simpler to keep this separate from the above
1023 // switch, though not strictly necessary.
1024 unsigned Opc = MI->getOpcode();
1027 // Just move on to the next instruction.
1030 case AArch64::STRSui:
1031 case AArch64::STRDui:
1032 case AArch64::STRQui:
1033 case AArch64::STRXui:
1034 case AArch64::STRWui:
1035 case AArch64::LDRSui:
1036 case AArch64::LDRDui:
1037 case AArch64::LDRQui:
1038 case AArch64::LDRXui:
1039 case AArch64::LDRWui:
1040 // do the unscaled versions as well
1041 case AArch64::STURSi:
1042 case AArch64::STURDi:
1043 case AArch64::STURQi:
1044 case AArch64::STURWi:
1045 case AArch64::STURXi:
1046 case AArch64::LDURSi:
1047 case AArch64::LDURDi:
1048 case AArch64::LDURQi:
1049 case AArch64::LDURWi:
1050 case AArch64::LDURXi: {
1051 // Make sure this is a reg+imm (as opposed to an address reloc).
1052 if (!getLdStOffsetOp(MI).isImm()) {
1056 // Look ahead up to ScanLimit instructions for a mergable instruction.
1057 MachineBasicBlock::iterator Update =
1058 findMatchingUpdateInsnForward(MBBI, ScanLimit, 0);
1060 // Merge the update into the ld/st.
1061 MBBI = mergePostIdxUpdateInsn(MBBI, Update);
1066 // Don't know how to handle pre/post-index versions, so move to the next
1068 if (isUnscaledLdSt(Opc)) {
1073 // Look back to try to find a pre-index instruction. For example,
1077 // ldr x1, [x0, #8]!
1078 Update = findMatchingUpdateInsnBackward(MBBI, ScanLimit);
1080 // Merge the update into the ld/st.
1081 MBBI = mergePreIdxUpdateInsn(MBBI, Update);
1087 // Look forward to try to find a post-index instruction. For example,
1088 // ldr x1, [x0, #64]
1091 // ldr x1, [x0, #64]!
1093 // The immediate in the load/store is scaled by the size of the register
1094 // being loaded. The immediate in the add we're looking for,
1095 // however, is not, so adjust here.
1096 int Value = MI->getOperand(2).getImm() *
1097 TII->getRegClass(MI->getDesc(), 0, TRI, *(MBB.getParent()))
1099 Update = findMatchingUpdateInsnForward(MBBI, ScanLimit, Value);
1101 // Merge the update into the ld/st.
1102 MBBI = mergePreIdxUpdateInsn(MBBI, Update);
1108 // Nothing found. Just move to the next instruction.
1112 // FIXME: Do the other instructions.
1119 bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
1120 TII = static_cast<const AArch64InstrInfo *>(Fn.getSubtarget().getInstrInfo());
1121 TRI = Fn.getSubtarget().getRegisterInfo();
1123 bool Modified = false;
1124 for (auto &MBB : Fn)
1125 Modified |= optimizeBlock(MBB);
1130 // FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
1131 // loads and stores near one another?
1133 /// createAArch64LoadStoreOptimizationPass - returns an instance of the
1134 /// load / store optimization pass.
1135 FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
1136 return new AArch64LoadStoreOpt();