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 "MCTargetDesc/AArch64AddressingModes.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetRegisterInfo.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/ADT/Statistic.h"
32 #define DEBUG_TYPE "aarch64-ldst-opt"
34 /// AArch64AllocLoadStoreOpt - Post-register allocation pass to combine
35 /// load / store instructions to form ldp / stp instructions.
37 STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
38 STATISTIC(NumPostFolded, "Number of post-index updates folded");
39 STATISTIC(NumPreFolded, "Number of pre-index updates folded");
40 STATISTIC(NumUnscaledPairCreated,
41 "Number of load/store from unscaled generated");
43 static cl::opt<unsigned> ScanLimit("aarch64-load-store-scan-limit",
44 cl::init(20), cl::Hidden);
46 // Place holder while testing unscaled load/store combining
47 static cl::opt<bool> EnableAArch64UnscaledMemOp(
48 "aarch64-unscaled-mem-op", cl::Hidden,
49 cl::desc("Allow AArch64 unscaled load/store combining"), cl::init(true));
52 struct AArch64LoadStoreOpt : public MachineFunctionPass {
54 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {}
56 const AArch64InstrInfo *TII;
57 const TargetRegisterInfo *TRI;
59 // Scan the instructions looking for a load/store that can be combined
60 // with the current instruction into a load/store pair.
61 // Return the matching instruction if one is found, else MBB->end().
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.
65 MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
68 // Merge the two instructions indicated into a single pair-wise instruction.
69 // If MergeForward is true, erase the first instruction and fold its
70 // operation into the second. If false, the reverse. Return the instruction
71 // following the first instruction (which may change during processing).
72 MachineBasicBlock::iterator
73 mergePairedInsns(MachineBasicBlock::iterator I,
74 MachineBasicBlock::iterator Paired, bool MergeForward);
76 // Scan the instruction list to find a base register update that can
77 // be combined with the current instruction (a load or store) using
78 // pre or post indexed addressing with writeback. Scan forwards.
79 MachineBasicBlock::iterator
80 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I, unsigned Limit,
83 // Scan the instruction list to find a base register update that can
84 // be combined with the current instruction (a load or store) using
85 // pre or post indexed addressing with writeback. Scan backwards.
86 MachineBasicBlock::iterator
87 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
89 // Merge a pre-index base register update into a ld/st instruction.
90 MachineBasicBlock::iterator
91 mergePreIdxUpdateInsn(MachineBasicBlock::iterator I,
92 MachineBasicBlock::iterator Update);
94 // Merge a post-index base register update into a ld/st instruction.
95 MachineBasicBlock::iterator
96 mergePostIdxUpdateInsn(MachineBasicBlock::iterator I,
97 MachineBasicBlock::iterator Update);
99 bool optimizeBlock(MachineBasicBlock &MBB);
101 bool runOnMachineFunction(MachineFunction &Fn) override;
103 const char *getPassName() const override {
104 return "AArch64 load / store optimization pass";
108 int getMemSize(MachineInstr *MemMI);
110 char AArch64LoadStoreOpt::ID = 0;
113 static bool isUnscaledLdst(unsigned Opc) {
117 case AArch64::STURSi:
119 case AArch64::STURDi:
121 case AArch64::STURQi:
123 case AArch64::STURWi:
125 case AArch64::STURXi:
127 case AArch64::LDURSi:
129 case AArch64::LDURDi:
131 case AArch64::LDURQi:
133 case AArch64::LDURWi:
135 case AArch64::LDURXi:
140 // Size in bytes of the data moved by an unscaled load or store
141 int AArch64LoadStoreOpt::getMemSize(MachineInstr *MemMI) {
142 switch (MemMI->getOpcode()) {
144 llvm_unreachable("Opcode has unknown size!");
145 case AArch64::STRSui:
146 case AArch64::STURSi:
148 case AArch64::STRDui:
149 case AArch64::STURDi:
151 case AArch64::STRQui:
152 case AArch64::STURQi:
154 case AArch64::STRWui:
155 case AArch64::STURWi:
157 case AArch64::STRXui:
158 case AArch64::STURXi:
160 case AArch64::LDRSui:
161 case AArch64::LDURSi:
163 case AArch64::LDRDui:
164 case AArch64::LDURDi:
166 case AArch64::LDRQui:
167 case AArch64::LDURQi:
169 case AArch64::LDRWui:
170 case AArch64::LDURWi:
172 case AArch64::LDRXui:
173 case AArch64::LDURXi:
178 static unsigned getMatchingPairOpcode(unsigned Opc) {
181 llvm_unreachable("Opcode has no pairwise equivalent!");
182 case AArch64::STRSui:
183 case AArch64::STURSi:
184 return AArch64::STPSi;
185 case AArch64::STRDui:
186 case AArch64::STURDi:
187 return AArch64::STPDi;
188 case AArch64::STRQui:
189 case AArch64::STURQi:
190 return AArch64::STPQi;
191 case AArch64::STRWui:
192 case AArch64::STURWi:
193 return AArch64::STPWi;
194 case AArch64::STRXui:
195 case AArch64::STURXi:
196 return AArch64::STPXi;
197 case AArch64::LDRSui:
198 case AArch64::LDURSi:
199 return AArch64::LDPSi;
200 case AArch64::LDRDui:
201 case AArch64::LDURDi:
202 return AArch64::LDPDi;
203 case AArch64::LDRQui:
204 case AArch64::LDURQi:
205 return AArch64::LDPQi;
206 case AArch64::LDRWui:
207 case AArch64::LDURWi:
208 return AArch64::LDPWi;
209 case AArch64::LDRXui:
210 case AArch64::LDURXi:
211 return AArch64::LDPXi;
215 static unsigned getPreIndexedOpcode(unsigned Opc) {
218 llvm_unreachable("Opcode has no pre-indexed equivalent!");
219 case AArch64::STRSui:
220 return AArch64::STRSpre;
221 case AArch64::STRDui:
222 return AArch64::STRDpre;
223 case AArch64::STRQui:
224 return AArch64::STRQpre;
225 case AArch64::STRWui:
226 return AArch64::STRWpre;
227 case AArch64::STRXui:
228 return AArch64::STRXpre;
229 case AArch64::LDRSui:
230 return AArch64::LDRSpre;
231 case AArch64::LDRDui:
232 return AArch64::LDRDpre;
233 case AArch64::LDRQui:
234 return AArch64::LDRQpre;
235 case AArch64::LDRWui:
236 return AArch64::LDRWpre;
237 case AArch64::LDRXui:
238 return AArch64::LDRXpre;
242 static unsigned getPostIndexedOpcode(unsigned Opc) {
245 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
246 case AArch64::STRSui:
247 return AArch64::STRSpost;
248 case AArch64::STRDui:
249 return AArch64::STRDpost;
250 case AArch64::STRQui:
251 return AArch64::STRQpost;
252 case AArch64::STRWui:
253 return AArch64::STRWpost;
254 case AArch64::STRXui:
255 return AArch64::STRXpost;
256 case AArch64::LDRSui:
257 return AArch64::LDRSpost;
258 case AArch64::LDRDui:
259 return AArch64::LDRDpost;
260 case AArch64::LDRQui:
261 return AArch64::LDRQpost;
262 case AArch64::LDRWui:
263 return AArch64::LDRWpost;
264 case AArch64::LDRXui:
265 return AArch64::LDRXpost;
269 MachineBasicBlock::iterator
270 AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
271 MachineBasicBlock::iterator Paired,
273 MachineBasicBlock::iterator NextI = I;
275 // If NextI is the second of the two instructions to be merged, we need
276 // to skip one further. Either way we merge will invalidate the iterator,
277 // and we don't need to scan the new instruction, as it's a pairwise
278 // instruction, which we're not considering for further action anyway.
282 bool IsUnscaled = isUnscaledLdst(I->getOpcode());
284 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(I) : 1;
286 unsigned NewOpc = getMatchingPairOpcode(I->getOpcode());
287 // Insert our new paired instruction after whichever of the paired
288 // instructions MergeForward indicates.
289 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
290 // Also based on MergeForward is from where we copy the base register operand
291 // so we get the flags compatible with the input code.
292 MachineOperand &BaseRegOp =
293 MergeForward ? Paired->getOperand(1) : I->getOperand(1);
295 // Which register is Rt and which is Rt2 depends on the offset order.
296 MachineInstr *RtMI, *Rt2MI;
297 if (I->getOperand(2).getImm() ==
298 Paired->getOperand(2).getImm() + OffsetStride) {
306 int OffsetImm = RtMI->getOperand(2).getImm();
307 if (IsUnscaled && EnableAArch64UnscaledMemOp)
308 OffsetImm /= OffsetStride;
310 // Construct the new instruction.
311 MachineInstrBuilder MIB = BuildMI(*I->getParent(), InsertionPoint,
312 I->getDebugLoc(), TII->get(NewOpc))
313 .addOperand(RtMI->getOperand(0))
314 .addOperand(Rt2MI->getOperand(0))
315 .addOperand(BaseRegOp)
319 // FIXME: Do we need/want to copy the mem operands from the source
320 // instructions? Probably. What uses them after this?
322 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
323 DEBUG(I->print(dbgs()));
324 DEBUG(dbgs() << " ");
325 DEBUG(Paired->print(dbgs()));
326 DEBUG(dbgs() << " with instruction:\n ");
327 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
328 DEBUG(dbgs() << "\n");
330 // Erase the old instructions.
331 I->eraseFromParent();
332 Paired->eraseFromParent();
337 /// trackRegDefsUses - Remember what registers the specified instruction uses
339 static void trackRegDefsUses(MachineInstr *MI, BitVector &ModifiedRegs,
341 const TargetRegisterInfo *TRI) {
342 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
343 MachineOperand &MO = MI->getOperand(i);
345 ModifiedRegs.setBitsNotInMask(MO.getRegMask());
349 unsigned Reg = MO.getReg();
351 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
352 ModifiedRegs.set(*AI);
354 assert(MO.isUse() && "Reg operand not a def and not a use?!?");
355 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
361 static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
362 if (!IsUnscaled && (Offset > 63 || Offset < -64))
365 // Convert the byte-offset used by unscaled into an "element" offset used
366 // by the scaled pair load/store instructions.
367 int ElemOffset = Offset / OffsetStride;
368 if (ElemOffset > 63 || ElemOffset < -64)
374 // Do alignment, specialized to power of 2 and for signed ints,
375 // avoiding having to do a C-style cast from uint_64t to int when
376 // using RoundUpToAlignment from include/llvm/Support/MathExtras.h.
377 // FIXME: Move this function to include/MathExtras.h?
378 static int alignTo(int Num, int PowOf2) {
379 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
382 /// findMatchingInsn - Scan the instructions looking for a load/store that can
383 /// be combined with the current instruction into a load/store pair.
384 MachineBasicBlock::iterator
385 AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
386 bool &MergeForward, unsigned Limit) {
387 MachineBasicBlock::iterator E = I->getParent()->end();
388 MachineBasicBlock::iterator MBBI = I;
389 MachineInstr *FirstMI = I;
392 int Opc = FirstMI->getOpcode();
393 bool MayLoad = FirstMI->mayLoad();
394 bool IsUnscaled = isUnscaledLdst(Opc);
395 unsigned Reg = FirstMI->getOperand(0).getReg();
396 unsigned BaseReg = FirstMI->getOperand(1).getReg();
397 int Offset = FirstMI->getOperand(2).getImm();
399 // Early exit if the first instruction modifies the base register.
400 // e.g., ldr x0, [x0]
401 // Early exit if the offset if not possible to match. (6 bits of positive
402 // range, plus allow an extra one in case we find a later insn that matches
404 if (FirstMI->modifiesRegister(BaseReg, TRI))
407 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(FirstMI) : 1;
408 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
411 // Track which registers have been modified and used between the first insn
412 // (inclusive) and the second insn.
413 BitVector ModifiedRegs, UsedRegs;
414 ModifiedRegs.resize(TRI->getNumRegs());
415 UsedRegs.resize(TRI->getNumRegs());
416 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
417 MachineInstr *MI = MBBI;
418 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
419 // optimization by changing how far we scan.
420 if (MI->isDebugValue())
423 // Now that we know this is a real instruction, count it.
426 if (Opc == MI->getOpcode() && MI->getOperand(2).isImm()) {
427 // If we've found another instruction with the same opcode, check to see
428 // if the base and offset are compatible with our starting instruction.
429 // These instructions all have scaled immediate operands, so we just
430 // check for +1/-1. Make sure to check the new instruction offset is
431 // actually an immediate and not a symbolic reference destined for
434 // Pairwise instructions have a 7-bit signed offset field. Single insns
435 // have a 12-bit unsigned offset field. To be a valid combine, the
436 // final offset must be in range.
437 unsigned MIBaseReg = MI->getOperand(1).getReg();
438 int MIOffset = MI->getOperand(2).getImm();
439 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
440 (Offset + OffsetStride == MIOffset))) {
441 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
442 // If this is a volatile load/store that otherwise matched, stop looking
443 // as something is going on that we don't have enough information to
444 // safely transform. Similarly, stop if we see a hint to avoid pairs.
445 if (MI->hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
447 // If the resultant immediate offset of merging these instructions
448 // is out of range for a pairwise instruction, bail and keep looking.
449 bool MIIsUnscaled = isUnscaledLdst(MI->getOpcode());
450 if (!inBoundsForPair(MIIsUnscaled, MinOffset, OffsetStride)) {
451 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
454 // If the alignment requirements of the paired (scaled) instruction
455 // can't express the offset of the unscaled input, bail and keep
457 if (IsUnscaled && EnableAArch64UnscaledMemOp &&
458 (alignTo(MinOffset, OffsetStride) != MinOffset)) {
459 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
462 // If the destination register of the loads is the same register, bail
463 // and keep looking. A load-pair instruction with both destination
464 // registers the same is UNPREDICTABLE and will result in an exception.
465 if (MayLoad && Reg == MI->getOperand(0).getReg()) {
466 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
470 // If the Rt of the second instruction was not modified or used between
471 // the two instructions, we can combine the second into the first.
472 if (!ModifiedRegs[MI->getOperand(0).getReg()] &&
473 !UsedRegs[MI->getOperand(0).getReg()]) {
474 MergeForward = false;
478 // Likewise, if the Rt of the first instruction is not modified or used
479 // between the two instructions, we can combine the first into the
481 if (!ModifiedRegs[FirstMI->getOperand(0).getReg()] &&
482 !UsedRegs[FirstMI->getOperand(0).getReg()]) {
486 // Unable to combine these instructions due to interference in between.
491 // If the instruction wasn't a matching load or store, but does (or can)
492 // modify memory, stop searching, as we don't have alias analysis or
493 // anything like that to tell us whether the access is tromping on the
494 // locations we care about. The big one we want to catch is calls.
496 // FIXME: Theoretically, we can do better than that for SP and FP based
497 // references since we can effectively know where those are touching. It's
498 // unclear if it's worth the extra code, though. Most paired instructions
499 // will be sequential, perhaps with a few intervening non-memory related
501 if (MI->mayStore() || MI->isCall())
503 // Likewise, if we're matching a store instruction, we don't want to
504 // move across a load, as it may be reading the same location.
505 if (FirstMI->mayStore() && MI->mayLoad())
508 // Update modified / uses register lists.
509 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
511 // Otherwise, if the base register is modified, we have no match, so
513 if (ModifiedRegs[BaseReg])
519 MachineBasicBlock::iterator
520 AArch64LoadStoreOpt::mergePreIdxUpdateInsn(MachineBasicBlock::iterator I,
521 MachineBasicBlock::iterator Update) {
522 assert((Update->getOpcode() == AArch64::ADDXri ||
523 Update->getOpcode() == AArch64::SUBXri) &&
524 "Unexpected base register update instruction to merge!");
525 MachineBasicBlock::iterator NextI = I;
526 // Return the instruction following the merged instruction, which is
527 // the instruction following our unmerged load. Unless that's the add/sub
528 // instruction we're merging, in which case it's the one after that.
529 if (++NextI == Update)
532 int Value = Update->getOperand(2).getImm();
533 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
534 "Can't merge 1 << 12 offset into pre-indexed load / store");
535 if (Update->getOpcode() == AArch64::SUBXri)
538 unsigned NewOpc = getPreIndexedOpcode(I->getOpcode());
539 MachineInstrBuilder MIB =
540 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
541 .addOperand(Update->getOperand(0))
542 .addOperand(I->getOperand(0))
543 .addOperand(I->getOperand(1))
547 DEBUG(dbgs() << "Creating pre-indexed load/store.");
548 DEBUG(dbgs() << " Replacing instructions:\n ");
549 DEBUG(I->print(dbgs()));
550 DEBUG(dbgs() << " ");
551 DEBUG(Update->print(dbgs()));
552 DEBUG(dbgs() << " with instruction:\n ");
553 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
554 DEBUG(dbgs() << "\n");
556 // Erase the old instructions for the block.
557 I->eraseFromParent();
558 Update->eraseFromParent();
563 MachineBasicBlock::iterator AArch64LoadStoreOpt::mergePostIdxUpdateInsn(
564 MachineBasicBlock::iterator I, MachineBasicBlock::iterator Update) {
565 assert((Update->getOpcode() == AArch64::ADDXri ||
566 Update->getOpcode() == AArch64::SUBXri) &&
567 "Unexpected base register update instruction to merge!");
568 MachineBasicBlock::iterator NextI = I;
569 // Return the instruction following the merged instruction, which is
570 // the instruction following our unmerged load. Unless that's the add/sub
571 // instruction we're merging, in which case it's the one after that.
572 if (++NextI == Update)
575 int Value = Update->getOperand(2).getImm();
576 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
577 "Can't merge 1 << 12 offset into post-indexed load / store");
578 if (Update->getOpcode() == AArch64::SUBXri)
581 unsigned NewOpc = getPostIndexedOpcode(I->getOpcode());
582 MachineInstrBuilder MIB =
583 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
584 .addOperand(Update->getOperand(0))
585 .addOperand(I->getOperand(0))
586 .addOperand(I->getOperand(1))
590 DEBUG(dbgs() << "Creating post-indexed load/store.");
591 DEBUG(dbgs() << " Replacing instructions:\n ");
592 DEBUG(I->print(dbgs()));
593 DEBUG(dbgs() << " ");
594 DEBUG(Update->print(dbgs()));
595 DEBUG(dbgs() << " with instruction:\n ");
596 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
597 DEBUG(dbgs() << "\n");
599 // Erase the old instructions for the block.
600 I->eraseFromParent();
601 Update->eraseFromParent();
606 static bool isMatchingUpdateInsn(MachineInstr *MI, unsigned BaseReg,
608 switch (MI->getOpcode()) {
611 case AArch64::SUBXri:
612 // Negate the offset for a SUB instruction.
615 case AArch64::ADDXri:
616 // Make sure it's a vanilla immediate operand, not a relocation or
617 // anything else we can't handle.
618 if (!MI->getOperand(2).isImm())
620 // Watch out for 1 << 12 shifted value.
621 if (AArch64_AM::getShiftValue(MI->getOperand(3).getImm()))
623 // If the instruction has the base register as source and dest and the
624 // immediate will fit in a signed 9-bit integer, then we have a match.
625 if (MI->getOperand(0).getReg() == BaseReg &&
626 MI->getOperand(1).getReg() == BaseReg &&
627 MI->getOperand(2).getImm() <= 255 &&
628 MI->getOperand(2).getImm() >= -256) {
629 // If we have a non-zero Offset, we check that it matches the amount
630 // we're adding to the register.
631 if (!Offset || Offset == MI->getOperand(2).getImm())
639 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
640 MachineBasicBlock::iterator I, unsigned Limit, int Value) {
641 MachineBasicBlock::iterator E = I->getParent()->end();
642 MachineInstr *MemMI = I;
643 MachineBasicBlock::iterator MBBI = I;
644 const MachineFunction &MF = *MemMI->getParent()->getParent();
646 unsigned DestReg = MemMI->getOperand(0).getReg();
647 unsigned BaseReg = MemMI->getOperand(1).getReg();
648 int Offset = MemMI->getOperand(2).getImm() *
649 TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
651 // If the base register overlaps the destination register, we can't
653 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
656 // Scan forward looking for post-index opportunities.
657 // Updating instructions can't be formed if the memory insn already
658 // has an offset other than the value we're looking for.
662 // Track which registers have been modified and used between the first insn
663 // (inclusive) and the second insn.
664 BitVector ModifiedRegs, UsedRegs;
665 ModifiedRegs.resize(TRI->getNumRegs());
666 UsedRegs.resize(TRI->getNumRegs());
668 for (unsigned Count = 0; MBBI != E; ++MBBI) {
669 MachineInstr *MI = MBBI;
670 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
671 // optimization by changing how far we scan.
672 if (MI->isDebugValue())
675 // Now that we know this is a real instruction, count it.
678 // If we found a match, return it.
679 if (isMatchingUpdateInsn(MI, BaseReg, Value))
682 // Update the status of what the instruction clobbered and used.
683 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
685 // Otherwise, if the base register is used or modified, we have no match, so
687 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
693 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
694 MachineBasicBlock::iterator I, unsigned Limit) {
695 MachineBasicBlock::iterator B = I->getParent()->begin();
696 MachineBasicBlock::iterator E = I->getParent()->end();
697 MachineInstr *MemMI = I;
698 MachineBasicBlock::iterator MBBI = I;
699 const MachineFunction &MF = *MemMI->getParent()->getParent();
701 unsigned DestReg = MemMI->getOperand(0).getReg();
702 unsigned BaseReg = MemMI->getOperand(1).getReg();
703 int Offset = MemMI->getOperand(2).getImm();
704 unsigned RegSize = TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
706 // If the load/store is the first instruction in the block, there's obviously
707 // not any matching update. Ditto if the memory offset isn't zero.
708 if (MBBI == B || Offset != 0)
710 // If the base register overlaps the destination register, we can't
712 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
715 // Track which registers have been modified and used between the first insn
716 // (inclusive) and the second insn.
717 BitVector ModifiedRegs, UsedRegs;
718 ModifiedRegs.resize(TRI->getNumRegs());
719 UsedRegs.resize(TRI->getNumRegs());
721 for (unsigned Count = 0; MBBI != B; --MBBI) {
722 MachineInstr *MI = MBBI;
723 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
724 // optimization by changing how far we scan.
725 if (MI->isDebugValue())
728 // Now that we know this is a real instruction, count it.
731 // If we found a match, return it.
732 if (isMatchingUpdateInsn(MI, BaseReg, RegSize))
735 // Update the status of what the instruction clobbered and used.
736 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
738 // Otherwise, if the base register is used or modified, we have no match, so
740 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
746 bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB) {
747 bool Modified = false;
748 // Two tranformations to do here:
749 // 1) Find loads and stores that can be merged into a single load or store
756 // 2) Find base register updates that can be merged into the load or store
757 // as a base-reg writeback.
764 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
766 MachineInstr *MI = MBBI;
767 switch (MI->getOpcode()) {
769 // Just move on to the next instruction.
772 case AArch64::STRSui:
773 case AArch64::STRDui:
774 case AArch64::STRQui:
775 case AArch64::STRXui:
776 case AArch64::STRWui:
777 case AArch64::LDRSui:
778 case AArch64::LDRDui:
779 case AArch64::LDRQui:
780 case AArch64::LDRXui:
781 case AArch64::LDRWui:
782 // do the unscaled versions as well
783 case AArch64::STURSi:
784 case AArch64::STURDi:
785 case AArch64::STURQi:
786 case AArch64::STURWi:
787 case AArch64::STURXi:
788 case AArch64::LDURSi:
789 case AArch64::LDURDi:
790 case AArch64::LDURQi:
791 case AArch64::LDURWi:
792 case AArch64::LDURXi: {
793 // If this is a volatile load/store, don't mess with it.
794 if (MI->hasOrderedMemoryRef()) {
798 // Make sure this is a reg+imm (as opposed to an address reloc).
799 if (!MI->getOperand(2).isImm()) {
803 // Check if this load/store has a hint to avoid pair formation.
804 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
805 if (TII->isLdStPairSuppressed(MI)) {
809 // Look ahead up to ScanLimit instructions for a pairable instruction.
810 bool MergeForward = false;
811 MachineBasicBlock::iterator Paired =
812 findMatchingInsn(MBBI, MergeForward, ScanLimit);
814 // Merge the loads into a pair. Keeping the iterator straight is a
815 // pain, so we let the merge routine tell us what the next instruction
816 // is after it's done mucking about.
817 MBBI = mergePairedInsns(MBBI, Paired, MergeForward);
821 if (isUnscaledLdst(MI->getOpcode()))
822 ++NumUnscaledPairCreated;
828 // FIXME: Do the other instructions.
832 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
834 MachineInstr *MI = MBBI;
835 // Do update merging. It's simpler to keep this separate from the above
836 // switch, though not strictly necessary.
837 int Opc = MI->getOpcode();
840 // Just move on to the next instruction.
843 case AArch64::STRSui:
844 case AArch64::STRDui:
845 case AArch64::STRQui:
846 case AArch64::STRXui:
847 case AArch64::STRWui:
848 case AArch64::LDRSui:
849 case AArch64::LDRDui:
850 case AArch64::LDRQui:
851 case AArch64::LDRXui:
852 case AArch64::LDRWui:
853 // do the unscaled versions as well
854 case AArch64::STURSi:
855 case AArch64::STURDi:
856 case AArch64::STURQi:
857 case AArch64::STURWi:
858 case AArch64::STURXi:
859 case AArch64::LDURSi:
860 case AArch64::LDURDi:
861 case AArch64::LDURQi:
862 case AArch64::LDURWi:
863 case AArch64::LDURXi: {
864 // Make sure this is a reg+imm (as opposed to an address reloc).
865 if (!MI->getOperand(2).isImm()) {
869 // Look ahead up to ScanLimit instructions for a mergable instruction.
870 MachineBasicBlock::iterator Update =
871 findMatchingUpdateInsnForward(MBBI, ScanLimit, 0);
873 // Merge the update into the ld/st.
874 MBBI = mergePostIdxUpdateInsn(MBBI, Update);
879 // Don't know how to handle pre/post-index versions, so move to the next
881 if (isUnscaledLdst(Opc)) {
886 // Look back to try to find a pre-index instruction. For example,
891 Update = findMatchingUpdateInsnBackward(MBBI, ScanLimit);
893 // Merge the update into the ld/st.
894 MBBI = mergePreIdxUpdateInsn(MBBI, Update);
900 // Look forward to try to find a post-index instruction. For example,
904 // ldr x1, [x0, #64]!
906 // The immediate in the load/store is scaled by the size of the register
907 // being loaded. The immediate in the add we're looking for,
908 // however, is not, so adjust here.
909 int Value = MI->getOperand(2).getImm() *
910 TII->getRegClass(MI->getDesc(), 0, TRI, *(MBB.getParent()))
912 Update = findMatchingUpdateInsnForward(MBBI, ScanLimit, Value);
914 // Merge the update into the ld/st.
915 MBBI = mergePreIdxUpdateInsn(MBBI, Update);
921 // Nothing found. Just move to the next instruction.
925 // FIXME: Do the other instructions.
932 bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
933 const TargetMachine &TM = Fn.getTarget();
934 TII = static_cast<const AArch64InstrInfo *>(TM.getInstrInfo());
935 TRI = TM.getRegisterInfo();
937 bool Modified = false;
939 Modified |= optimizeBlock(MBB);
944 // FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
945 // loads and stores near one another?
947 /// createARMLoadStoreOptimizationPass - returns an instance of the load / store
948 /// optimization pass.
949 FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
950 return new AArch64LoadStoreOpt();