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;
139 int getMemSize(MachineInstr *MemMI);
141 char AArch64LoadStoreOpt::ID = 0;
144 INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
145 AARCH64_LOAD_STORE_OPT_NAME, false, false)
147 static bool isUnscaledLdst(unsigned Opc) {
151 case AArch64::STURSi:
152 case AArch64::STURDi:
153 case AArch64::STURQi:
154 case AArch64::STURWi:
155 case AArch64::STURXi:
156 case AArch64::LDURSi:
157 case AArch64::LDURDi:
158 case AArch64::LDURQi:
159 case AArch64::LDURWi:
160 case AArch64::LDURXi:
161 case AArch64::LDURSWi:
166 // Size in bytes of the data moved by an unscaled load or store
167 int AArch64LoadStoreOpt::getMemSize(MachineInstr *MemMI) {
168 switch (MemMI->getOpcode()) {
170 llvm_unreachable("Opcode has unknown size!");
171 case AArch64::STRSui:
172 case AArch64::STURSi:
174 case AArch64::STRDui:
175 case AArch64::STURDi:
177 case AArch64::STRQui:
178 case AArch64::STURQi:
180 case AArch64::STRWui:
181 case AArch64::STURWi:
183 case AArch64::STRXui:
184 case AArch64::STURXi:
186 case AArch64::LDRSui:
187 case AArch64::LDURSi:
189 case AArch64::LDRDui:
190 case AArch64::LDURDi:
192 case AArch64::LDRQui:
193 case AArch64::LDURQi:
195 case AArch64::LDRWui:
196 case AArch64::LDURWi:
198 case AArch64::LDRXui:
199 case AArch64::LDURXi:
201 case AArch64::LDRSWui:
202 case AArch64::LDURSWi:
207 static unsigned getMatchingNonSExtOpcode(unsigned Opc,
208 bool *IsValidLdStrOpc = nullptr) {
210 *IsValidLdStrOpc = true;
214 *IsValidLdStrOpc = false;
216 case AArch64::STRDui:
217 case AArch64::STURDi:
218 case AArch64::STRQui:
219 case AArch64::STURQi:
220 case AArch64::STRWui:
221 case AArch64::STURWi:
222 case AArch64::STRXui:
223 case AArch64::STURXi:
224 case AArch64::LDRDui:
225 case AArch64::LDURDi:
226 case AArch64::LDRQui:
227 case AArch64::LDURQi:
228 case AArch64::LDRWui:
229 case AArch64::LDURWi:
230 case AArch64::LDRXui:
231 case AArch64::LDURXi:
232 case AArch64::STRSui:
233 case AArch64::STURSi:
234 case AArch64::LDRSui:
235 case AArch64::LDURSi:
237 case AArch64::LDRSWui:
238 return AArch64::LDRWui;
239 case AArch64::LDURSWi:
240 return AArch64::LDURWi;
244 static unsigned getMatchingPairOpcode(unsigned Opc) {
247 llvm_unreachable("Opcode has no pairwise equivalent!");
248 case AArch64::STRSui:
249 case AArch64::STURSi:
250 return AArch64::STPSi;
251 case AArch64::STRDui:
252 case AArch64::STURDi:
253 return AArch64::STPDi;
254 case AArch64::STRQui:
255 case AArch64::STURQi:
256 return AArch64::STPQi;
257 case AArch64::STRWui:
258 case AArch64::STURWi:
259 return AArch64::STPWi;
260 case AArch64::STRXui:
261 case AArch64::STURXi:
262 return AArch64::STPXi;
263 case AArch64::LDRSui:
264 case AArch64::LDURSi:
265 return AArch64::LDPSi;
266 case AArch64::LDRDui:
267 case AArch64::LDURDi:
268 return AArch64::LDPDi;
269 case AArch64::LDRQui:
270 case AArch64::LDURQi:
271 return AArch64::LDPQi;
272 case AArch64::LDRWui:
273 case AArch64::LDURWi:
274 return AArch64::LDPWi;
275 case AArch64::LDRXui:
276 case AArch64::LDURXi:
277 return AArch64::LDPXi;
278 case AArch64::LDRSWui:
279 case AArch64::LDURSWi:
280 return AArch64::LDPSWi;
284 static unsigned getPreIndexedOpcode(unsigned Opc) {
287 llvm_unreachable("Opcode has no pre-indexed equivalent!");
288 case AArch64::STRSui:
289 return AArch64::STRSpre;
290 case AArch64::STRDui:
291 return AArch64::STRDpre;
292 case AArch64::STRQui:
293 return AArch64::STRQpre;
294 case AArch64::STRWui:
295 return AArch64::STRWpre;
296 case AArch64::STRXui:
297 return AArch64::STRXpre;
298 case AArch64::LDRSui:
299 return AArch64::LDRSpre;
300 case AArch64::LDRDui:
301 return AArch64::LDRDpre;
302 case AArch64::LDRQui:
303 return AArch64::LDRQpre;
304 case AArch64::LDRWui:
305 return AArch64::LDRWpre;
306 case AArch64::LDRXui:
307 return AArch64::LDRXpre;
308 case AArch64::LDRSWui:
309 return AArch64::LDRSWpre;
313 static unsigned getPostIndexedOpcode(unsigned Opc) {
316 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
317 case AArch64::STRSui:
318 return AArch64::STRSpost;
319 case AArch64::STRDui:
320 return AArch64::STRDpost;
321 case AArch64::STRQui:
322 return AArch64::STRQpost;
323 case AArch64::STRWui:
324 return AArch64::STRWpost;
325 case AArch64::STRXui:
326 return AArch64::STRXpost;
327 case AArch64::LDRSui:
328 return AArch64::LDRSpost;
329 case AArch64::LDRDui:
330 return AArch64::LDRDpost;
331 case AArch64::LDRQui:
332 return AArch64::LDRQpost;
333 case AArch64::LDRWui:
334 return AArch64::LDRWpost;
335 case AArch64::LDRXui:
336 return AArch64::LDRXpost;
337 case AArch64::LDRSWui:
338 return AArch64::LDRSWpost;
342 MachineBasicBlock::iterator
343 AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
344 MachineBasicBlock::iterator Paired,
345 const LdStPairFlags &Flags) {
346 MachineBasicBlock::iterator NextI = I;
348 // If NextI is the second of the two instructions to be merged, we need
349 // to skip one further. Either way we merge will invalidate the iterator,
350 // and we don't need to scan the new instruction, as it's a pairwise
351 // instruction, which we're not considering for further action anyway.
355 int SExtIdx = Flags.getSExtIdx();
357 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
358 bool IsUnscaled = isUnscaledLdst(Opc);
360 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(I) : 1;
362 bool MergeForward = Flags.getMergeForward();
363 unsigned NewOpc = getMatchingPairOpcode(Opc);
364 // Insert our new paired instruction after whichever of the paired
365 // instructions MergeForward indicates.
366 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
367 // Also based on MergeForward is from where we copy the base register operand
368 // so we get the flags compatible with the input code.
369 MachineOperand &BaseRegOp =
370 MergeForward ? Paired->getOperand(1) : I->getOperand(1);
372 // Which register is Rt and which is Rt2 depends on the offset order.
373 MachineInstr *RtMI, *Rt2MI;
374 if (I->getOperand(2).getImm() ==
375 Paired->getOperand(2).getImm() + OffsetStride) {
378 // Here we swapped the assumption made for SExtIdx.
379 // I.e., we turn ldp I, Paired into ldp Paired, I.
380 // Update the index accordingly.
382 SExtIdx = (SExtIdx + 1) % 2;
388 int OffsetImm = RtMI->getOperand(2).getImm();
389 if (IsUnscaled && EnableAArch64UnscaledMemOp)
390 OffsetImm /= OffsetStride;
392 // Construct the new instruction.
393 MachineInstrBuilder MIB = BuildMI(*I->getParent(), InsertionPoint,
394 I->getDebugLoc(), TII->get(NewOpc))
395 .addOperand(RtMI->getOperand(0))
396 .addOperand(Rt2MI->getOperand(0))
397 .addOperand(BaseRegOp)
401 // FIXME: Do we need/want to copy the mem operands from the source
402 // instructions? Probably. What uses them after this?
404 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
405 DEBUG(I->print(dbgs()));
406 DEBUG(dbgs() << " ");
407 DEBUG(Paired->print(dbgs()));
408 DEBUG(dbgs() << " with instruction:\n ");
411 // Generate the sign extension for the proper result of the ldp.
412 // I.e., with X1, that would be:
413 // %W1<def> = KILL %W1, %X1<imp-def>
414 // %X1<def> = SBFMXri %X1<kill>, 0, 31
415 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
416 // Right now, DstMO has the extended register, since it comes from an
418 unsigned DstRegX = DstMO.getReg();
419 // Get the W variant of that register.
420 unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
421 // Update the result of LDP to use the W instead of the X variant.
422 DstMO.setReg(DstRegW);
423 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
424 DEBUG(dbgs() << "\n");
425 // Make the machine verifier happy by providing a definition for
427 // Insert this definition right after the generated LDP, i.e., before
429 MachineInstrBuilder MIBKill =
430 BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
431 TII->get(TargetOpcode::KILL), DstRegW)
433 .addReg(DstRegX, RegState::Define);
434 MIBKill->getOperand(2).setImplicit();
435 // Create the sign extension.
436 MachineInstrBuilder MIBSXTW =
437 BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
438 TII->get(AArch64::SBFMXri), DstRegX)
443 DEBUG(dbgs() << " Extend operand:\n ");
444 DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
445 DEBUG(dbgs() << "\n");
447 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
448 DEBUG(dbgs() << "\n");
451 // Erase the old instructions.
452 I->eraseFromParent();
453 Paired->eraseFromParent();
458 /// trackRegDefsUses - Remember what registers the specified instruction uses
460 static void trackRegDefsUses(const MachineInstr *MI, BitVector &ModifiedRegs,
462 const TargetRegisterInfo *TRI) {
463 for (const MachineOperand &MO : MI->operands()) {
465 ModifiedRegs.setBitsNotInMask(MO.getRegMask());
469 unsigned Reg = MO.getReg();
471 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
472 ModifiedRegs.set(*AI);
474 assert(MO.isUse() && "Reg operand not a def and not a use?!?");
475 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
481 static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
482 if (!IsUnscaled && (Offset > 63 || Offset < -64))
485 // Convert the byte-offset used by unscaled into an "element" offset used
486 // by the scaled pair load/store instructions.
487 int ElemOffset = Offset / OffsetStride;
488 if (ElemOffset > 63 || ElemOffset < -64)
494 // Do alignment, specialized to power of 2 and for signed ints,
495 // avoiding having to do a C-style cast from uint_64t to int when
496 // using RoundUpToAlignment from include/llvm/Support/MathExtras.h.
497 // FIXME: Move this function to include/MathExtras.h?
498 static int alignTo(int Num, int PowOf2) {
499 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
502 static bool mayAlias(MachineInstr *MIa, MachineInstr *MIb,
503 const AArch64InstrInfo *TII) {
504 // One of the instructions must modify memory.
505 if (!MIa->mayStore() && !MIb->mayStore())
508 // Both instructions must be memory operations.
509 if (!MIa->mayLoadOrStore() && !MIb->mayLoadOrStore())
512 return !TII->areMemAccessesTriviallyDisjoint(MIa, MIb);
515 static bool mayAlias(MachineInstr *MIa,
516 SmallVectorImpl<MachineInstr *> &MemInsns,
517 const AArch64InstrInfo *TII) {
518 for (auto &MIb : MemInsns)
519 if (mayAlias(MIa, MIb, TII))
525 /// findMatchingInsn - Scan the instructions looking for a load/store that can
526 /// be combined with the current instruction into a load/store pair.
527 MachineBasicBlock::iterator
528 AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
529 LdStPairFlags &Flags,
531 MachineBasicBlock::iterator E = I->getParent()->end();
532 MachineBasicBlock::iterator MBBI = I;
533 MachineInstr *FirstMI = I;
536 unsigned Opc = FirstMI->getOpcode();
537 bool MayLoad = FirstMI->mayLoad();
538 bool IsUnscaled = isUnscaledLdst(Opc);
539 unsigned Reg = FirstMI->getOperand(0).getReg();
540 unsigned BaseReg = FirstMI->getOperand(1).getReg();
541 int Offset = FirstMI->getOperand(2).getImm();
543 // Early exit if the first instruction modifies the base register.
544 // e.g., ldr x0, [x0]
545 // Early exit if the offset if not possible to match. (6 bits of positive
546 // range, plus allow an extra one in case we find a later insn that matches
548 if (FirstMI->modifiesRegister(BaseReg, TRI))
551 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(FirstMI) : 1;
552 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
555 // Track which registers have been modified and used between the first insn
556 // (inclusive) and the second insn.
557 BitVector ModifiedRegs, UsedRegs;
558 ModifiedRegs.resize(TRI->getNumRegs());
559 UsedRegs.resize(TRI->getNumRegs());
561 // Remember any instructions that read/write memory between FirstMI and MI.
562 SmallVector<MachineInstr *, 4> MemInsns;
564 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
565 MachineInstr *MI = MBBI;
566 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
567 // optimization by changing how far we scan.
568 if (MI->isDebugValue())
571 // Now that we know this is a real instruction, count it.
574 bool CanMergeOpc = Opc == MI->getOpcode();
575 Flags.setSExtIdx(-1);
577 bool IsValidLdStrOpc;
578 unsigned NonSExtOpc = getMatchingNonSExtOpcode(Opc, &IsValidLdStrOpc);
579 if (!IsValidLdStrOpc)
581 // Opc will be the first instruction in the pair.
582 Flags.setSExtIdx(NonSExtOpc == (unsigned)Opc ? 1 : 0);
583 CanMergeOpc = NonSExtOpc == getMatchingNonSExtOpcode(MI->getOpcode());
586 if (CanMergeOpc && MI->getOperand(2).isImm()) {
587 // If we've found another instruction with the same opcode, check to see
588 // if the base and offset are compatible with our starting instruction.
589 // These instructions all have scaled immediate operands, so we just
590 // check for +1/-1. Make sure to check the new instruction offset is
591 // actually an immediate and not a symbolic reference destined for
594 // Pairwise instructions have a 7-bit signed offset field. Single insns
595 // have a 12-bit unsigned offset field. To be a valid combine, the
596 // final offset must be in range.
597 unsigned MIBaseReg = MI->getOperand(1).getReg();
598 int MIOffset = MI->getOperand(2).getImm();
599 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
600 (Offset + OffsetStride == MIOffset))) {
601 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
602 // If this is a volatile load/store that otherwise matched, stop looking
603 // as something is going on that we don't have enough information to
604 // safely transform. Similarly, stop if we see a hint to avoid pairs.
605 if (MI->hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
607 // If the resultant immediate offset of merging these instructions
608 // is out of range for a pairwise instruction, bail and keep looking.
609 bool MIIsUnscaled = isUnscaledLdst(MI->getOpcode());
610 if (!inBoundsForPair(MIIsUnscaled, MinOffset, OffsetStride)) {
611 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
612 if (MI->mayLoadOrStore())
613 MemInsns.push_back(MI);
616 // If the alignment requirements of the paired (scaled) instruction
617 // can't express the offset of the unscaled input, bail and keep
619 if (IsUnscaled && EnableAArch64UnscaledMemOp &&
620 (alignTo(MinOffset, OffsetStride) != MinOffset)) {
621 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
622 if (MI->mayLoadOrStore())
623 MemInsns.push_back(MI);
626 // If the destination register of the loads is the same register, bail
627 // and keep looking. A load-pair instruction with both destination
628 // registers the same is UNPREDICTABLE and will result in an exception.
629 if (MayLoad && Reg == MI->getOperand(0).getReg()) {
630 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
631 if (MI->mayLoadOrStore())
632 MemInsns.push_back(MI);
636 // If the Rt of the second instruction was not modified or used between
637 // the two instructions and none of the instructions between the second
638 // and first alias with the second, we can combine the second into the
640 if (!ModifiedRegs[MI->getOperand(0).getReg()] &&
641 !(MI->mayLoad() && UsedRegs[MI->getOperand(0).getReg()]) &&
642 !mayAlias(MI, MemInsns, TII)) {
643 Flags.setMergeForward(false);
647 // Likewise, if the Rt of the first instruction is not modified or used
648 // between the two instructions and none of the instructions between the
649 // first and the second alias with the first, we can combine the first
651 if (!ModifiedRegs[FirstMI->getOperand(0).getReg()] &&
652 !(FirstMI->mayLoad() &&
653 UsedRegs[FirstMI->getOperand(0).getReg()]) &&
654 !mayAlias(FirstMI, MemInsns, TII)) {
655 Flags.setMergeForward(true);
658 // Unable to combine these instructions due to interference in between.
663 // If the instruction wasn't a matching load or store. Stop searching if we
664 // encounter a call instruction that might modify memory.
668 // Update modified / uses register lists.
669 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
671 // Otherwise, if the base register is modified, we have no match, so
673 if (ModifiedRegs[BaseReg])
676 // Update list of instructions that read/write memory.
677 if (MI->mayLoadOrStore())
678 MemInsns.push_back(MI);
683 MachineBasicBlock::iterator
684 AArch64LoadStoreOpt::mergePreIdxUpdateInsn(MachineBasicBlock::iterator I,
685 MachineBasicBlock::iterator Update) {
686 assert((Update->getOpcode() == AArch64::ADDXri ||
687 Update->getOpcode() == AArch64::SUBXri) &&
688 "Unexpected base register update instruction to merge!");
689 MachineBasicBlock::iterator NextI = I;
690 // Return the instruction following the merged instruction, which is
691 // the instruction following our unmerged load. Unless that's the add/sub
692 // instruction we're merging, in which case it's the one after that.
693 if (++NextI == Update)
696 int Value = Update->getOperand(2).getImm();
697 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
698 "Can't merge 1 << 12 offset into pre-indexed load / store");
699 if (Update->getOpcode() == AArch64::SUBXri)
702 unsigned NewOpc = getPreIndexedOpcode(I->getOpcode());
703 MachineInstrBuilder MIB =
704 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
705 .addOperand(Update->getOperand(0))
706 .addOperand(I->getOperand(0))
707 .addOperand(I->getOperand(1))
711 DEBUG(dbgs() << "Creating pre-indexed load/store.");
712 DEBUG(dbgs() << " Replacing instructions:\n ");
713 DEBUG(I->print(dbgs()));
714 DEBUG(dbgs() << " ");
715 DEBUG(Update->print(dbgs()));
716 DEBUG(dbgs() << " with instruction:\n ");
717 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
718 DEBUG(dbgs() << "\n");
720 // Erase the old instructions for the block.
721 I->eraseFromParent();
722 Update->eraseFromParent();
727 MachineBasicBlock::iterator AArch64LoadStoreOpt::mergePostIdxUpdateInsn(
728 MachineBasicBlock::iterator I, MachineBasicBlock::iterator Update) {
729 assert((Update->getOpcode() == AArch64::ADDXri ||
730 Update->getOpcode() == AArch64::SUBXri) &&
731 "Unexpected base register update instruction to merge!");
732 MachineBasicBlock::iterator NextI = I;
733 // Return the instruction following the merged instruction, which is
734 // the instruction following our unmerged load. Unless that's the add/sub
735 // instruction we're merging, in which case it's the one after that.
736 if (++NextI == Update)
739 int Value = Update->getOperand(2).getImm();
740 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
741 "Can't merge 1 << 12 offset into post-indexed load / store");
742 if (Update->getOpcode() == AArch64::SUBXri)
745 unsigned NewOpc = getPostIndexedOpcode(I->getOpcode());
746 MachineInstrBuilder MIB =
747 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
748 .addOperand(Update->getOperand(0))
749 .addOperand(I->getOperand(0))
750 .addOperand(I->getOperand(1))
754 DEBUG(dbgs() << "Creating post-indexed load/store.");
755 DEBUG(dbgs() << " Replacing instructions:\n ");
756 DEBUG(I->print(dbgs()));
757 DEBUG(dbgs() << " ");
758 DEBUG(Update->print(dbgs()));
759 DEBUG(dbgs() << " with instruction:\n ");
760 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
761 DEBUG(dbgs() << "\n");
763 // Erase the old instructions for the block.
764 I->eraseFromParent();
765 Update->eraseFromParent();
770 static bool isMatchingUpdateInsn(MachineInstr *MI, unsigned BaseReg,
772 switch (MI->getOpcode()) {
775 case AArch64::SUBXri:
776 // Negate the offset for a SUB instruction.
779 case AArch64::ADDXri:
780 // Make sure it's a vanilla immediate operand, not a relocation or
781 // anything else we can't handle.
782 if (!MI->getOperand(2).isImm())
784 // Watch out for 1 << 12 shifted value.
785 if (AArch64_AM::getShiftValue(MI->getOperand(3).getImm()))
787 // If the instruction has the base register as source and dest and the
788 // immediate will fit in a signed 9-bit integer, then we have a match.
789 if (MI->getOperand(0).getReg() == BaseReg &&
790 MI->getOperand(1).getReg() == BaseReg &&
791 MI->getOperand(2).getImm() <= 255 &&
792 MI->getOperand(2).getImm() >= -256) {
793 // If we have a non-zero Offset, we check that it matches the amount
794 // we're adding to the register.
795 if (!Offset || Offset == MI->getOperand(2).getImm())
803 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
804 MachineBasicBlock::iterator I, unsigned Limit, int Value) {
805 MachineBasicBlock::iterator E = I->getParent()->end();
806 MachineInstr *MemMI = I;
807 MachineBasicBlock::iterator MBBI = I;
808 const MachineFunction &MF = *MemMI->getParent()->getParent();
810 unsigned DestReg = MemMI->getOperand(0).getReg();
811 unsigned BaseReg = MemMI->getOperand(1).getReg();
812 int Offset = MemMI->getOperand(2).getImm() *
813 TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
815 // If the base register overlaps the destination register, we can't
817 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
820 // Scan forward looking for post-index opportunities.
821 // Updating instructions can't be formed if the memory insn already
822 // has an offset other than the value we're looking for.
826 // Track which registers have been modified and used between the first insn
827 // (inclusive) and the second insn.
828 BitVector ModifiedRegs, UsedRegs;
829 ModifiedRegs.resize(TRI->getNumRegs());
830 UsedRegs.resize(TRI->getNumRegs());
832 for (unsigned Count = 0; MBBI != E; ++MBBI) {
833 MachineInstr *MI = MBBI;
834 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
835 // optimization by changing how far we scan.
836 if (MI->isDebugValue())
839 // Now that we know this is a real instruction, count it.
842 // If we found a match, return it.
843 if (isMatchingUpdateInsn(MI, BaseReg, Value))
846 // Update the status of what the instruction clobbered and used.
847 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
849 // Otherwise, if the base register is used or modified, we have no match, so
851 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
857 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
858 MachineBasicBlock::iterator I, unsigned Limit) {
859 MachineBasicBlock::iterator B = I->getParent()->begin();
860 MachineBasicBlock::iterator E = I->getParent()->end();
861 MachineInstr *MemMI = I;
862 MachineBasicBlock::iterator MBBI = I;
863 const MachineFunction &MF = *MemMI->getParent()->getParent();
865 unsigned DestReg = MemMI->getOperand(0).getReg();
866 unsigned BaseReg = MemMI->getOperand(1).getReg();
867 int Offset = MemMI->getOperand(2).getImm();
868 unsigned RegSize = TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
870 // If the load/store is the first instruction in the block, there's obviously
871 // not any matching update. Ditto if the memory offset isn't zero.
872 if (MBBI == B || Offset != 0)
874 // If the base register overlaps the destination register, we can't
876 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
879 // Track which registers have been modified and used between the first insn
880 // (inclusive) and the second insn.
881 BitVector ModifiedRegs, UsedRegs;
882 ModifiedRegs.resize(TRI->getNumRegs());
883 UsedRegs.resize(TRI->getNumRegs());
885 for (unsigned Count = 0; MBBI != B; --MBBI) {
886 MachineInstr *MI = MBBI;
887 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
888 // optimization by changing how far we scan.
889 if (MI->isDebugValue())
892 // Now that we know this is a real instruction, count it.
895 // If we found a match, return it.
896 if (isMatchingUpdateInsn(MI, BaseReg, RegSize))
899 // Update the status of what the instruction clobbered and used.
900 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
902 // Otherwise, if the base register is used or modified, we have no match, so
904 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
910 bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB) {
911 bool Modified = false;
912 // Two tranformations to do here:
913 // 1) Find loads and stores that can be merged into a single load or store
920 // 2) Find base register updates that can be merged into the load or store
921 // as a base-reg writeback.
928 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
930 MachineInstr *MI = MBBI;
931 switch (MI->getOpcode()) {
933 // Just move on to the next instruction.
936 case AArch64::STRSui:
937 case AArch64::STRDui:
938 case AArch64::STRQui:
939 case AArch64::STRXui:
940 case AArch64::STRWui:
941 case AArch64::LDRSui:
942 case AArch64::LDRDui:
943 case AArch64::LDRQui:
944 case AArch64::LDRXui:
945 case AArch64::LDRWui:
946 case AArch64::LDRSWui:
947 // do the unscaled versions as well
948 case AArch64::STURSi:
949 case AArch64::STURDi:
950 case AArch64::STURQi:
951 case AArch64::STURWi:
952 case AArch64::STURXi:
953 case AArch64::LDURSi:
954 case AArch64::LDURDi:
955 case AArch64::LDURQi:
956 case AArch64::LDURWi:
957 case AArch64::LDURXi:
958 case AArch64::LDURSWi: {
959 // If this is a volatile load/store, don't mess with it.
960 if (MI->hasOrderedMemoryRef()) {
964 // Make sure this is a reg+imm (as opposed to an address reloc).
965 if (!MI->getOperand(2).isImm()) {
969 // Check if this load/store has a hint to avoid pair formation.
970 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
971 if (TII->isLdStPairSuppressed(MI)) {
975 // Look ahead up to ScanLimit instructions for a pairable instruction.
977 MachineBasicBlock::iterator Paired =
978 findMatchingInsn(MBBI, Flags, ScanLimit);
980 // Merge the loads into a pair. Keeping the iterator straight is a
981 // pain, so we let the merge routine tell us what the next instruction
982 // is after it's done mucking about.
983 MBBI = mergePairedInsns(MBBI, Paired, Flags);
987 if (isUnscaledLdst(MI->getOpcode()))
988 ++NumUnscaledPairCreated;
994 // FIXME: Do the other instructions.
998 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1000 MachineInstr *MI = MBBI;
1001 // Do update merging. It's simpler to keep this separate from the above
1002 // switch, though not strictly necessary.
1003 unsigned Opc = MI->getOpcode();
1006 // Just move on to the next instruction.
1009 case AArch64::STRSui:
1010 case AArch64::STRDui:
1011 case AArch64::STRQui:
1012 case AArch64::STRXui:
1013 case AArch64::STRWui:
1014 case AArch64::LDRSui:
1015 case AArch64::LDRDui:
1016 case AArch64::LDRQui:
1017 case AArch64::LDRXui:
1018 case AArch64::LDRWui:
1019 // do the unscaled versions as well
1020 case AArch64::STURSi:
1021 case AArch64::STURDi:
1022 case AArch64::STURQi:
1023 case AArch64::STURWi:
1024 case AArch64::STURXi:
1025 case AArch64::LDURSi:
1026 case AArch64::LDURDi:
1027 case AArch64::LDURQi:
1028 case AArch64::LDURWi:
1029 case AArch64::LDURXi: {
1030 // Make sure this is a reg+imm (as opposed to an address reloc).
1031 if (!MI->getOperand(2).isImm()) {
1035 // Look ahead up to ScanLimit instructions for a mergable instruction.
1036 MachineBasicBlock::iterator Update =
1037 findMatchingUpdateInsnForward(MBBI, ScanLimit, 0);
1039 // Merge the update into the ld/st.
1040 MBBI = mergePostIdxUpdateInsn(MBBI, Update);
1045 // Don't know how to handle pre/post-index versions, so move to the next
1047 if (isUnscaledLdst(Opc)) {
1052 // Look back to try to find a pre-index instruction. For example,
1056 // ldr x1, [x0, #8]!
1057 Update = findMatchingUpdateInsnBackward(MBBI, ScanLimit);
1059 // Merge the update into the ld/st.
1060 MBBI = mergePreIdxUpdateInsn(MBBI, Update);
1066 // Look forward to try to find a post-index instruction. For example,
1067 // ldr x1, [x0, #64]
1070 // ldr x1, [x0, #64]!
1072 // The immediate in the load/store is scaled by the size of the register
1073 // being loaded. The immediate in the add we're looking for,
1074 // however, is not, so adjust here.
1075 int Value = MI->getOperand(2).getImm() *
1076 TII->getRegClass(MI->getDesc(), 0, TRI, *(MBB.getParent()))
1078 Update = findMatchingUpdateInsnForward(MBBI, ScanLimit, Value);
1080 // Merge the update into the ld/st.
1081 MBBI = mergePreIdxUpdateInsn(MBBI, Update);
1087 // Nothing found. Just move to the next instruction.
1091 // FIXME: Do the other instructions.
1098 bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
1099 TII = static_cast<const AArch64InstrInfo *>(Fn.getSubtarget().getInstrInfo());
1100 TRI = Fn.getSubtarget().getRegisterInfo();
1102 bool Modified = false;
1103 for (auto &MBB : Fn)
1104 Modified |= optimizeBlock(MBB);
1109 // FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
1110 // loads and stores near one another?
1112 /// createAArch64LoadStoreOptimizationPass - returns an instance of the
1113 /// load / store optimization pass.
1114 FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
1115 return new AArch64LoadStoreOpt();