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", cl::init(20),
46 // Place holder while testing unscaled load/store combining
48 EnableAArch64UnscaledMemOp("aarch64-unscaled-mem-op", cl::Hidden,
49 cl::desc("Allow AArch64 unscaled load/store combining"),
53 struct AArch64LoadStoreOpt : public MachineFunctionPass {
55 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {}
57 const AArch64InstrInfo *TII;
58 const TargetRegisterInfo *TRI;
60 // Scan the instructions looking for a load/store that can be combined
61 // with the current instruction into a load/store pair.
62 // Return the matching instruction if one is found, else MBB->end().
63 // If a matching instruction is found, mergeForward is set to true if the
64 // merge is to remove the first instruction and replace the second with
65 // a pair-wise insn, and false if the reverse is true.
66 MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
69 // Merge the two instructions indicated into a single pair-wise instruction.
70 // If mergeForward is true, erase the first instruction and fold its
71 // operation into the second. If false, the reverse. Return the instruction
72 // following the first instruction (which may change during processing).
73 MachineBasicBlock::iterator
74 mergePairedInsns(MachineBasicBlock::iterator I,
75 MachineBasicBlock::iterator Paired, bool mergeForward);
77 // Scan the instruction list to find a base register update that can
78 // be combined with the current instruction (a load or store) using
79 // pre or post indexed addressing with writeback. Scan forwards.
80 MachineBasicBlock::iterator
81 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I, unsigned Limit,
84 // Scan the instruction list to find a base register update that can
85 // be combined with the current instruction (a load or store) using
86 // pre or post indexed addressing with writeback. Scan backwards.
87 MachineBasicBlock::iterator
88 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
90 // Merge a pre-index base register update into a ld/st instruction.
91 MachineBasicBlock::iterator
92 mergePreIdxUpdateInsn(MachineBasicBlock::iterator I,
93 MachineBasicBlock::iterator Update);
95 // Merge a post-index base register update into a ld/st instruction.
96 MachineBasicBlock::iterator
97 mergePostIdxUpdateInsn(MachineBasicBlock::iterator I,
98 MachineBasicBlock::iterator Update);
100 bool optimizeBlock(MachineBasicBlock &MBB);
102 bool runOnMachineFunction(MachineFunction &Fn) override;
104 const char *getPassName() const override {
105 return "AArch64 load / store optimization pass";
109 int getMemSize(MachineInstr *MemMI);
111 char AArch64LoadStoreOpt::ID = 0;
114 static bool isUnscaledLdst(unsigned Opc) {
118 case AArch64::STURSi:
120 case AArch64::STURDi:
122 case AArch64::STURQi:
124 case AArch64::STURWi:
126 case AArch64::STURXi:
128 case AArch64::LDURSi:
130 case AArch64::LDURDi:
132 case AArch64::LDURQi:
134 case AArch64::LDURWi:
136 case AArch64::LDURXi:
141 // Size in bytes of the data moved by an unscaled load or store
142 int AArch64LoadStoreOpt::getMemSize(MachineInstr *MemMI) {
143 switch (MemMI->getOpcode()) {
145 llvm_unreachable("Opcode has unknown size!");
146 case AArch64::STRSui:
147 case AArch64::STURSi:
149 case AArch64::STRDui:
150 case AArch64::STURDi:
152 case AArch64::STRQui:
153 case AArch64::STURQi:
155 case AArch64::STRWui:
156 case AArch64::STURWi:
158 case AArch64::STRXui:
159 case AArch64::STURXi:
161 case AArch64::LDRSui:
162 case AArch64::LDURSi:
164 case AArch64::LDRDui:
165 case AArch64::LDURDi:
167 case AArch64::LDRQui:
168 case AArch64::LDURQi:
170 case AArch64::LDRWui:
171 case AArch64::LDURWi:
173 case AArch64::LDRXui:
174 case AArch64::LDURXi:
179 static unsigned getMatchingPairOpcode(unsigned Opc) {
182 llvm_unreachable("Opcode has no pairwise equivalent!");
183 case AArch64::STRSui:
184 case AArch64::STURSi:
185 return AArch64::STPSi;
186 case AArch64::STRDui:
187 case AArch64::STURDi:
188 return AArch64::STPDi;
189 case AArch64::STRQui:
190 case AArch64::STURQi:
191 return AArch64::STPQi;
192 case AArch64::STRWui:
193 case AArch64::STURWi:
194 return AArch64::STPWi;
195 case AArch64::STRXui:
196 case AArch64::STURXi:
197 return AArch64::STPXi;
198 case AArch64::LDRSui:
199 case AArch64::LDURSi:
200 return AArch64::LDPSi;
201 case AArch64::LDRDui:
202 case AArch64::LDURDi:
203 return AArch64::LDPDi;
204 case AArch64::LDRQui:
205 case AArch64::LDURQi:
206 return AArch64::LDPQi;
207 case AArch64::LDRWui:
208 case AArch64::LDURWi:
209 return AArch64::LDPWi;
210 case AArch64::LDRXui:
211 case AArch64::LDURXi:
212 return AArch64::LDPXi;
216 static unsigned getPreIndexedOpcode(unsigned Opc) {
219 llvm_unreachable("Opcode has no pre-indexed equivalent!");
220 case AArch64::STRSui: return AArch64::STRSpre;
221 case AArch64::STRDui: return AArch64::STRDpre;
222 case AArch64::STRQui: return AArch64::STRQpre;
223 case AArch64::STRWui: return AArch64::STRWpre;
224 case AArch64::STRXui: return AArch64::STRXpre;
225 case AArch64::LDRSui: return AArch64::LDRSpre;
226 case AArch64::LDRDui: return AArch64::LDRDpre;
227 case AArch64::LDRQui: return AArch64::LDRQpre;
228 case AArch64::LDRWui: return AArch64::LDRWpre;
229 case AArch64::LDRXui: return AArch64::LDRXpre;
233 static unsigned getPostIndexedOpcode(unsigned Opc) {
236 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
237 case AArch64::STRSui:
238 return AArch64::STRSpost;
239 case AArch64::STRDui:
240 return AArch64::STRDpost;
241 case AArch64::STRQui:
242 return AArch64::STRQpost;
243 case AArch64::STRWui:
244 return AArch64::STRWpost;
245 case AArch64::STRXui:
246 return AArch64::STRXpost;
247 case AArch64::LDRSui:
248 return AArch64::LDRSpost;
249 case AArch64::LDRDui:
250 return AArch64::LDRDpost;
251 case AArch64::LDRQui:
252 return AArch64::LDRQpost;
253 case AArch64::LDRWui:
254 return AArch64::LDRWpost;
255 case AArch64::LDRXui:
256 return AArch64::LDRXpost;
260 MachineBasicBlock::iterator
261 AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
262 MachineBasicBlock::iterator Paired,
264 MachineBasicBlock::iterator NextI = I;
266 // If NextI is the second of the two instructions to be merged, we need
267 // to skip one further. Either way we merge will invalidate the iterator,
268 // and we don't need to scan the new instruction, as it's a pairwise
269 // instruction, which we're not considering for further action anyway.
273 bool IsUnscaled = isUnscaledLdst(I->getOpcode());
275 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(I) : 1;
277 unsigned NewOpc = getMatchingPairOpcode(I->getOpcode());
278 // Insert our new paired instruction after whichever of the paired
279 // instructions mergeForward indicates.
280 MachineBasicBlock::iterator InsertionPoint = mergeForward ? Paired : I;
281 // Also based on mergeForward is from where we copy the base register operand
282 // so we get the flags compatible with the input code.
283 MachineOperand &BaseRegOp =
284 mergeForward ? Paired->getOperand(1) : I->getOperand(1);
286 // Which register is Rt and which is Rt2 depends on the offset order.
287 MachineInstr *RtMI, *Rt2MI;
288 if (I->getOperand(2).getImm() ==
289 Paired->getOperand(2).getImm() + OffsetStride) {
297 int OffsetImm = RtMI->getOperand(2).getImm();
298 if (IsUnscaled && EnableAArch64UnscaledMemOp)
299 OffsetImm /= OffsetStride;
301 // Construct the new instruction.
302 MachineInstrBuilder MIB = BuildMI(*I->getParent(), InsertionPoint,
303 I->getDebugLoc(), TII->get(NewOpc))
304 .addOperand(RtMI->getOperand(0))
305 .addOperand(Rt2MI->getOperand(0))
306 .addOperand(BaseRegOp)
310 // FIXME: Do we need/want to copy the mem operands from the source
311 // instructions? Probably. What uses them after this?
313 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
314 DEBUG(I->print(dbgs()));
315 DEBUG(dbgs() << " ");
316 DEBUG(Paired->print(dbgs()));
317 DEBUG(dbgs() << " with instruction:\n ");
318 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
319 DEBUG(dbgs() << "\n");
321 // Erase the old instructions.
322 I->eraseFromParent();
323 Paired->eraseFromParent();
328 /// trackRegDefsUses - Remember what registers the specified instruction uses
330 static void trackRegDefsUses(MachineInstr *MI, BitVector &ModifiedRegs,
332 const TargetRegisterInfo *TRI) {
333 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
334 MachineOperand &MO = MI->getOperand(i);
336 ModifiedRegs.setBitsNotInMask(MO.getRegMask());
340 unsigned Reg = MO.getReg();
342 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
343 ModifiedRegs.set(*AI);
345 assert(MO.isUse() && "Reg operand not a def and not a use?!?");
346 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
352 static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
353 if (!IsUnscaled && (Offset > 63 || Offset < -64))
356 // Convert the byte-offset used by unscaled into an "element" offset used
357 // by the scaled pair load/store instructions.
358 int elemOffset = Offset / OffsetStride;
359 if (elemOffset > 63 || elemOffset < -64)
365 // Do alignment, specialized to power of 2 and for signed ints,
366 // avoiding having to do a C-style cast from uint_64t to int when
367 // using RoundUpToAlignment from include/llvm/Support/MathExtras.h.
368 // FIXME: Move this function to include/MathExtras.h?
369 static int alignTo(int Num, int PowOf2) {
370 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
373 /// findMatchingInsn - Scan the instructions looking for a load/store that can
374 /// be combined with the current instruction into a load/store pair.
375 MachineBasicBlock::iterator
376 AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
377 bool &mergeForward, unsigned Limit) {
378 MachineBasicBlock::iterator E = I->getParent()->end();
379 MachineBasicBlock::iterator MBBI = I;
380 MachineInstr *FirstMI = I;
383 int Opc = FirstMI->getOpcode();
384 bool mayLoad = FirstMI->mayLoad();
385 bool IsUnscaled = isUnscaledLdst(Opc);
386 unsigned Reg = FirstMI->getOperand(0).getReg();
387 unsigned BaseReg = FirstMI->getOperand(1).getReg();
388 int Offset = FirstMI->getOperand(2).getImm();
390 // Early exit if the first instruction modifies the base register.
391 // e.g., ldr x0, [x0]
392 // Early exit if the offset if not possible to match. (6 bits of positive
393 // range, plus allow an extra one in case we find a later insn that matches
395 if (FirstMI->modifiesRegister(BaseReg, TRI))
398 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(FirstMI) : 1;
399 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
402 // Track which registers have been modified and used between the first insn
403 // (inclusive) and the second insn.
404 BitVector ModifiedRegs, UsedRegs;
405 ModifiedRegs.resize(TRI->getNumRegs());
406 UsedRegs.resize(TRI->getNumRegs());
407 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
408 MachineInstr *MI = MBBI;
409 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
410 // optimization by changing how far we scan.
411 if (MI->isDebugValue())
414 // Now that we know this is a real instruction, count it.
417 if (Opc == MI->getOpcode() && MI->getOperand(2).isImm()) {
418 // If we've found another instruction with the same opcode, check to see
419 // if the base and offset are compatible with our starting instruction.
420 // These instructions all have scaled immediate operands, so we just
421 // check for +1/-1. Make sure to check the new instruction offset is
422 // actually an immediate and not a symbolic reference destined for
425 // Pairwise instructions have a 7-bit signed offset field. Single insns
426 // have a 12-bit unsigned offset field. To be a valid combine, the
427 // final offset must be in range.
428 unsigned MIBaseReg = MI->getOperand(1).getReg();
429 int MIOffset = MI->getOperand(2).getImm();
430 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
431 (Offset + OffsetStride == MIOffset))) {
432 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
433 // If this is a volatile load/store that otherwise matched, stop looking
434 // as something is going on that we don't have enough information to
435 // safely transform. Similarly, stop if we see a hint to avoid pairs.
436 if (MI->hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
438 // If the resultant immediate offset of merging these instructions
439 // is out of range for a pairwise instruction, bail and keep looking.
440 bool MIIsUnscaled = isUnscaledLdst(MI->getOpcode());
441 if (!inBoundsForPair(MIIsUnscaled, MinOffset, OffsetStride)) {
442 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
445 // If the alignment requirements of the paired (scaled) instruction
446 // can't express the offset of the unscaled input, bail and keep
448 if (IsUnscaled && EnableAArch64UnscaledMemOp &&
449 (alignTo(MinOffset, OffsetStride) != MinOffset)) {
450 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
453 // If the destination register of the loads is the same register, bail
454 // and keep looking. A load-pair instruction with both destination
455 // registers the same is UNPREDICTABLE and will result in an exception.
456 if (mayLoad && Reg == MI->getOperand(0).getReg()) {
457 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
461 // If the Rt of the second instruction was not modified or used between
462 // the two instructions, we can combine the second into the first.
463 if (!ModifiedRegs[MI->getOperand(0).getReg()] &&
464 !UsedRegs[MI->getOperand(0).getReg()]) {
465 mergeForward = false;
469 // Likewise, if the Rt of the first instruction is not modified or used
470 // between the two instructions, we can combine the first into the
472 if (!ModifiedRegs[FirstMI->getOperand(0).getReg()] &&
473 !UsedRegs[FirstMI->getOperand(0).getReg()]) {
477 // Unable to combine these instructions due to interference in between.
482 // If the instruction wasn't a matching load or store, but does (or can)
483 // modify memory, stop searching, as we don't have alias analysis or
484 // anything like that to tell us whether the access is tromping on the
485 // locations we care about. The big one we want to catch is calls.
487 // FIXME: Theoretically, we can do better than that for SP and FP based
488 // references since we can effectively know where those are touching. It's
489 // unclear if it's worth the extra code, though. Most paired instructions
490 // will be sequential, perhaps with a few intervening non-memory related
492 if (MI->mayStore() || MI->isCall())
494 // Likewise, if we're matching a store instruction, we don't want to
495 // move across a load, as it may be reading the same location.
496 if (FirstMI->mayStore() && MI->mayLoad())
499 // Update modified / uses register lists.
500 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
502 // Otherwise, if the base register is modified, we have no match, so
504 if (ModifiedRegs[BaseReg])
510 MachineBasicBlock::iterator
511 AArch64LoadStoreOpt::mergePreIdxUpdateInsn(MachineBasicBlock::iterator I,
512 MachineBasicBlock::iterator Update) {
513 assert((Update->getOpcode() == AArch64::ADDXri ||
514 Update->getOpcode() == AArch64::SUBXri) &&
515 "Unexpected base register update instruction to merge!");
516 MachineBasicBlock::iterator NextI = I;
517 // Return the instruction following the merged instruction, which is
518 // the instruction following our unmerged load. Unless that's the add/sub
519 // instruction we're merging, in which case it's the one after that.
520 if (++NextI == Update)
523 int Value = Update->getOperand(2).getImm();
524 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
525 "Can't merge 1 << 12 offset into pre-indexed load / store");
526 if (Update->getOpcode() == AArch64::SUBXri)
529 unsigned NewOpc = getPreIndexedOpcode(I->getOpcode());
530 MachineInstrBuilder MIB =
531 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
532 .addOperand(Update->getOperand(0))
533 .addOperand(I->getOperand(0))
534 .addOperand(I->getOperand(1))
538 DEBUG(dbgs() << "Creating pre-indexed load/store.");
539 DEBUG(dbgs() << " Replacing instructions:\n ");
540 DEBUG(I->print(dbgs()));
541 DEBUG(dbgs() << " ");
542 DEBUG(Update->print(dbgs()));
543 DEBUG(dbgs() << " with instruction:\n ");
544 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
545 DEBUG(dbgs() << "\n");
547 // Erase the old instructions for the block.
548 I->eraseFromParent();
549 Update->eraseFromParent();
554 MachineBasicBlock::iterator AArch64LoadStoreOpt::mergePostIdxUpdateInsn(
555 MachineBasicBlock::iterator I, MachineBasicBlock::iterator Update) {
556 assert((Update->getOpcode() == AArch64::ADDXri ||
557 Update->getOpcode() == AArch64::SUBXri) &&
558 "Unexpected base register update instruction to merge!");
559 MachineBasicBlock::iterator NextI = I;
560 // Return the instruction following the merged instruction, which is
561 // the instruction following our unmerged load. Unless that's the add/sub
562 // instruction we're merging, in which case it's the one after that.
563 if (++NextI == Update)
566 int Value = Update->getOperand(2).getImm();
567 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
568 "Can't merge 1 << 12 offset into post-indexed load / store");
569 if (Update->getOpcode() == AArch64::SUBXri)
572 unsigned NewOpc = getPostIndexedOpcode(I->getOpcode());
573 MachineInstrBuilder MIB =
574 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
575 .addOperand(Update->getOperand(0))
576 .addOperand(I->getOperand(0))
577 .addOperand(I->getOperand(1))
581 DEBUG(dbgs() << "Creating post-indexed load/store.");
582 DEBUG(dbgs() << " Replacing instructions:\n ");
583 DEBUG(I->print(dbgs()));
584 DEBUG(dbgs() << " ");
585 DEBUG(Update->print(dbgs()));
586 DEBUG(dbgs() << " with instruction:\n ");
587 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
588 DEBUG(dbgs() << "\n");
590 // Erase the old instructions for the block.
591 I->eraseFromParent();
592 Update->eraseFromParent();
597 static bool isMatchingUpdateInsn(MachineInstr *MI, unsigned BaseReg,
599 switch (MI->getOpcode()) {
602 case AArch64::SUBXri:
603 // Negate the offset for a SUB instruction.
606 case AArch64::ADDXri:
607 // Make sure it's a vanilla immediate operand, not a relocation or
608 // anything else we can't handle.
609 if (!MI->getOperand(2).isImm())
611 // Watch out for 1 << 12 shifted value.
612 if (AArch64_AM::getShiftValue(MI->getOperand(3).getImm()))
614 // If the instruction has the base register as source and dest and the
615 // immediate will fit in a signed 9-bit integer, then we have a match.
616 if (MI->getOperand(0).getReg() == BaseReg &&
617 MI->getOperand(1).getReg() == BaseReg &&
618 MI->getOperand(2).getImm() <= 255 &&
619 MI->getOperand(2).getImm() >= -256) {
620 // If we have a non-zero Offset, we check that it matches the amount
621 // we're adding to the register.
622 if (!Offset || Offset == MI->getOperand(2).getImm())
630 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
631 MachineBasicBlock::iterator I, unsigned Limit, int Value) {
632 MachineBasicBlock::iterator E = I->getParent()->end();
633 MachineInstr *MemMI = I;
634 MachineBasicBlock::iterator MBBI = I;
635 const MachineFunction &MF = *MemMI->getParent()->getParent();
637 unsigned DestReg = MemMI->getOperand(0).getReg();
638 unsigned BaseReg = MemMI->getOperand(1).getReg();
639 int Offset = MemMI->getOperand(2).getImm() *
640 TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
642 // If the base register overlaps the destination register, we can't
644 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
647 // Scan forward looking for post-index opportunities.
648 // Updating instructions can't be formed if the memory insn already
649 // has an offset other than the value we're looking for.
653 // Track which registers have been modified and used between the first insn
654 // (inclusive) and the second insn.
655 BitVector ModifiedRegs, UsedRegs;
656 ModifiedRegs.resize(TRI->getNumRegs());
657 UsedRegs.resize(TRI->getNumRegs());
659 for (unsigned Count = 0; MBBI != E; ++MBBI) {
660 MachineInstr *MI = MBBI;
661 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
662 // optimization by changing how far we scan.
663 if (MI->isDebugValue())
666 // Now that we know this is a real instruction, count it.
669 // If we found a match, return it.
670 if (isMatchingUpdateInsn(MI, BaseReg, Value))
673 // Update the status of what the instruction clobbered and used.
674 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
676 // Otherwise, if the base register is used or modified, we have no match, so
678 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
684 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
685 MachineBasicBlock::iterator I, unsigned Limit) {
686 MachineBasicBlock::iterator B = I->getParent()->begin();
687 MachineBasicBlock::iterator E = I->getParent()->end();
688 MachineInstr *MemMI = I;
689 MachineBasicBlock::iterator MBBI = I;
690 const MachineFunction &MF = *MemMI->getParent()->getParent();
692 unsigned DestReg = MemMI->getOperand(0).getReg();
693 unsigned BaseReg = MemMI->getOperand(1).getReg();
694 int Offset = MemMI->getOperand(2).getImm();
695 unsigned RegSize = TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
697 // If the load/store is the first instruction in the block, there's obviously
698 // not any matching update. Ditto if the memory offset isn't zero.
699 if (MBBI == B || Offset != 0)
701 // If the base register overlaps the destination register, we can't
703 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
706 // Track which registers have been modified and used between the first insn
707 // (inclusive) and the second insn.
708 BitVector ModifiedRegs, UsedRegs;
709 ModifiedRegs.resize(TRI->getNumRegs());
710 UsedRegs.resize(TRI->getNumRegs());
712 for (unsigned Count = 0; MBBI != B; --MBBI) {
713 MachineInstr *MI = MBBI;
714 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
715 // optimization by changing how far we scan.
716 if (MI->isDebugValue())
719 // Now that we know this is a real instruction, count it.
722 // If we found a match, return it.
723 if (isMatchingUpdateInsn(MI, BaseReg, RegSize))
726 // Update the status of what the instruction clobbered and used.
727 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
729 // Otherwise, if the base register is used or modified, we have no match, so
731 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
737 bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB) {
738 bool Modified = false;
739 // Two tranformations to do here:
740 // 1) Find loads and stores that can be merged into a single load or store
747 // 2) Find base register updates that can be merged into the load or store
748 // as a base-reg writeback.
755 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
757 MachineInstr *MI = MBBI;
758 switch (MI->getOpcode()) {
760 // Just move on to the next instruction.
763 case AArch64::STRSui:
764 case AArch64::STRDui:
765 case AArch64::STRQui:
766 case AArch64::STRXui:
767 case AArch64::STRWui:
768 case AArch64::LDRSui:
769 case AArch64::LDRDui:
770 case AArch64::LDRQui:
771 case AArch64::LDRXui:
772 case AArch64::LDRWui:
773 // do the unscaled versions as well
774 case AArch64::STURSi:
775 case AArch64::STURDi:
776 case AArch64::STURQi:
777 case AArch64::STURWi:
778 case AArch64::STURXi:
779 case AArch64::LDURSi:
780 case AArch64::LDURDi:
781 case AArch64::LDURQi:
782 case AArch64::LDURWi:
783 case AArch64::LDURXi: {
784 // If this is a volatile load/store, don't mess with it.
785 if (MI->hasOrderedMemoryRef()) {
789 // Make sure this is a reg+imm (as opposed to an address reloc).
790 if (!MI->getOperand(2).isImm()) {
794 // Check if this load/store has a hint to avoid pair formation.
795 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
796 if (TII->isLdStPairSuppressed(MI)) {
800 // Look ahead up to ScanLimit instructions for a pairable instruction.
801 bool mergeForward = false;
802 MachineBasicBlock::iterator Paired =
803 findMatchingInsn(MBBI, mergeForward, ScanLimit);
805 // Merge the loads into a pair. Keeping the iterator straight is a
806 // pain, so we let the merge routine tell us what the next instruction
807 // is after it's done mucking about.
808 MBBI = mergePairedInsns(MBBI, Paired, mergeForward);
812 if (isUnscaledLdst(MI->getOpcode()))
813 ++NumUnscaledPairCreated;
819 // FIXME: Do the other instructions.
823 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
825 MachineInstr *MI = MBBI;
826 // Do update merging. It's simpler to keep this separate from the above
827 // switch, though not strictly necessary.
828 int Opc = MI->getOpcode();
831 // Just move on to the next instruction.
834 case AArch64::STRSui:
835 case AArch64::STRDui:
836 case AArch64::STRQui:
837 case AArch64::STRXui:
838 case AArch64::STRWui:
839 case AArch64::LDRSui:
840 case AArch64::LDRDui:
841 case AArch64::LDRQui:
842 case AArch64::LDRXui:
843 case AArch64::LDRWui:
844 // do the unscaled versions as well
845 case AArch64::STURSi:
846 case AArch64::STURDi:
847 case AArch64::STURQi:
848 case AArch64::STURWi:
849 case AArch64::STURXi:
850 case AArch64::LDURSi:
851 case AArch64::LDURDi:
852 case AArch64::LDURQi:
853 case AArch64::LDURWi:
854 case AArch64::LDURXi: {
855 // Make sure this is a reg+imm (as opposed to an address reloc).
856 if (!MI->getOperand(2).isImm()) {
860 // Look ahead up to ScanLimit instructions for a mergable instruction.
861 MachineBasicBlock::iterator Update =
862 findMatchingUpdateInsnForward(MBBI, ScanLimit, 0);
864 // Merge the update into the ld/st.
865 MBBI = mergePostIdxUpdateInsn(MBBI, Update);
870 // Don't know how to handle pre/post-index versions, so move to the next
872 if (isUnscaledLdst(Opc)) {
877 // Look back to try to find a pre-index instruction. For example,
882 Update = findMatchingUpdateInsnBackward(MBBI, ScanLimit);
884 // Merge the update into the ld/st.
885 MBBI = mergePreIdxUpdateInsn(MBBI, Update);
891 // Look forward to try to find a post-index instruction. For example,
895 // ldr x1, [x0, #64]!
897 // The immediate in the load/store is scaled by the size of the register
898 // being loaded. The immediate in the add we're looking for,
899 // however, is not, so adjust here.
900 int Value = MI->getOperand(2).getImm() *
901 TII->getRegClass(MI->getDesc(), 0, TRI, *(MBB.getParent()))
903 Update = findMatchingUpdateInsnForward(MBBI, ScanLimit, Value);
905 // Merge the update into the ld/st.
906 MBBI = mergePreIdxUpdateInsn(MBBI, Update);
912 // Nothing found. Just move to the next instruction.
916 // FIXME: Do the other instructions.
923 bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
924 const TargetMachine &TM = Fn.getTarget();
925 TII = static_cast<const AArch64InstrInfo *>(TM.getInstrInfo());
926 TRI = TM.getRegisterInfo();
928 bool Modified = false;
930 Modified |= optimizeBlock(MBB);
935 // FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
936 // loads and stores near one another?
938 /// createARMLoadStoreOptimizationPass - returns an instance of the load / store
939 /// optimization pass.
940 FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
941 return new AArch64LoadStoreOpt();