1 //===-- ARM64LoadStoreOptimizer.cpp - ARM64 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 #define DEBUG_TYPE "arm64-ldst-opt"
16 #include "ARM64InstrInfo.h"
17 #include "MCTargetDesc/ARM64AddressingModes.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/CodeGen/MachineBasicBlock.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetRegisterInfo.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/ADT/Statistic.h"
33 /// ARM64AllocLoadStoreOpt - Post-register allocation pass to combine
34 /// load / store instructions to form ldp / stp instructions.
36 STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
37 STATISTIC(NumPostFolded, "Number of post-index updates folded");
38 STATISTIC(NumPreFolded, "Number of pre-index updates folded");
39 STATISTIC(NumUnscaledPairCreated,
40 "Number of load/store from unscaled generated");
42 static cl::opt<bool> DoLoadStoreOpt("arm64-load-store-opt", cl::init(true),
44 static cl::opt<unsigned> ScanLimit("arm64-load-store-scan-limit", cl::init(20),
47 // Place holder while testing unscaled load/store combining
49 EnableARM64UnscaledMemOp("arm64-unscaled-mem-op", cl::Hidden,
50 cl::desc("Allow ARM64 unscaled load/store combining"),
54 struct ARM64LoadStoreOpt : public MachineFunctionPass {
56 ARM64LoadStoreOpt() : MachineFunctionPass(ID) {}
58 const ARM64InstrInfo *TII;
59 const TargetRegisterInfo *TRI;
61 // Scan the instructions looking for a load/store that can be combined
62 // with the current instruction into a load/store pair.
63 // Return the matching instruction if one is found, else MBB->end().
64 // If a matching instruction is found, mergeForward is set to true if the
65 // merge is to remove the first instruction and replace the second with
66 // a pair-wise insn, and false if the reverse is true.
67 MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
70 // Merge the two instructions indicated into a single pair-wise instruction.
71 // If mergeForward is true, erase the first instruction and fold its
72 // operation into the second. If false, the reverse. Return the instruction
73 // following the first instruction (which may change during processing).
74 MachineBasicBlock::iterator
75 mergePairedInsns(MachineBasicBlock::iterator I,
76 MachineBasicBlock::iterator Paired, bool mergeForward);
78 // Scan the instruction list to find a base register update that can
79 // be combined with the current instruction (a load or store) using
80 // pre or post indexed addressing with writeback. Scan forwards.
81 MachineBasicBlock::iterator
82 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I, unsigned Limit,
85 // Scan the instruction list to find a base register update that can
86 // be combined with the current instruction (a load or store) using
87 // pre or post indexed addressing with writeback. Scan backwards.
88 MachineBasicBlock::iterator
89 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
91 // Merge a pre-index base register update into a ld/st instruction.
92 MachineBasicBlock::iterator
93 mergePreIdxUpdateInsn(MachineBasicBlock::iterator I,
94 MachineBasicBlock::iterator Update);
96 // Merge a post-index base register update into a ld/st instruction.
97 MachineBasicBlock::iterator
98 mergePostIdxUpdateInsn(MachineBasicBlock::iterator I,
99 MachineBasicBlock::iterator Update);
101 bool optimizeBlock(MachineBasicBlock &MBB);
103 virtual bool runOnMachineFunction(MachineFunction &Fn);
105 virtual const char *getPassName() const {
106 return "ARM64 load / store optimization pass";
110 int getMemSize(MachineInstr *MemMI);
112 char ARM64LoadStoreOpt::ID = 0;
115 static bool isUnscaledLdst(unsigned Opc) {
142 // Size in bytes of the data moved by an unscaled load or store
143 int ARM64LoadStoreOpt::getMemSize(MachineInstr *MemMI) {
144 switch (MemMI->getOpcode()) {
146 llvm_unreachable("Opcode has has unknown size!");
180 static unsigned getMatchingPairOpcode(unsigned Opc) {
183 llvm_unreachable("Opcode has no pairwise equivalent!");
217 static unsigned getPreIndexedOpcode(unsigned Opc) {
220 llvm_unreachable("Opcode has no pre-indexed equivalent!");
221 case ARM64::STRSui: return ARM64::STRSpre;
222 case ARM64::STRDui: return ARM64::STRDpre;
223 case ARM64::STRQui: return ARM64::STRQpre;
224 case ARM64::STRWui: return ARM64::STRWpre;
225 case ARM64::STRXui: return ARM64::STRXpre;
226 case ARM64::LDRSui: return ARM64::LDRSpre;
227 case ARM64::LDRDui: return ARM64::LDRDpre;
228 case ARM64::LDRQui: return ARM64::LDRQpre;
229 case ARM64::LDRWui: return ARM64::LDRWpre;
230 case ARM64::LDRXui: return ARM64::LDRXpre;
234 static unsigned getPostIndexedOpcode(unsigned Opc) {
237 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
239 return ARM64::STRSpost;
241 return ARM64::STRDpost;
243 return ARM64::STRQpost;
245 return ARM64::STRWpost;
247 return ARM64::STRXpost;
249 return ARM64::LDRSpost;
251 return ARM64::LDRDpost;
253 return ARM64::LDRQpost;
255 return ARM64::LDRWpost;
257 return ARM64::LDRXpost;
261 MachineBasicBlock::iterator
262 ARM64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
263 MachineBasicBlock::iterator Paired,
265 MachineBasicBlock::iterator NextI = I;
267 // If NextI is the second of the two instructions to be merged, we need
268 // to skip one further. Either way we merge will invalidate the iterator,
269 // and we don't need to scan the new instruction, as it's a pairwise
270 // instruction, which we're not considering for further action anyway.
274 bool IsUnscaled = isUnscaledLdst(I->getOpcode());
275 int OffsetStride = IsUnscaled && EnableARM64UnscaledMemOp ? 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 && EnableARM64UnscaledMemOp)
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 ARM64LoadStoreOpt::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 && EnableARM64UnscaledMemOp ? 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 && EnableARM64UnscaledMemOp &&
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 ARM64LoadStoreOpt::mergePreIdxUpdateInsn(MachineBasicBlock::iterator I,
512 MachineBasicBlock::iterator Update) {
513 assert((Update->getOpcode() == ARM64::ADDXri ||
514 Update->getOpcode() == ARM64::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(ARM64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
525 "Can't merge 1 << 12 offset into pre-indexed load / store");
526 if (Update->getOpcode() == ARM64::SUBXri)
529 unsigned NewOpc = getPreIndexedOpcode(I->getOpcode());
530 MachineInstrBuilder MIB =
531 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
532 .addOperand(I->getOperand(0))
533 .addOperand(I->getOperand(1))
537 DEBUG(dbgs() << "Creating pre-indexed load/store.");
538 DEBUG(dbgs() << " Replacing instructions:\n ");
539 DEBUG(I->print(dbgs()));
540 DEBUG(dbgs() << " ");
541 DEBUG(Update->print(dbgs()));
542 DEBUG(dbgs() << " with instruction:\n ");
543 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
544 DEBUG(dbgs() << "\n");
546 // Erase the old instructions for the block.
547 I->eraseFromParent();
548 Update->eraseFromParent();
553 MachineBasicBlock::iterator
554 ARM64LoadStoreOpt::mergePostIdxUpdateInsn(MachineBasicBlock::iterator I,
555 MachineBasicBlock::iterator Update) {
556 assert((Update->getOpcode() == ARM64::ADDXri ||
557 Update->getOpcode() == ARM64::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(ARM64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
568 "Can't merge 1 << 12 offset into post-indexed load / store");
569 if (Update->getOpcode() == ARM64::SUBXri)
572 unsigned NewOpc = getPostIndexedOpcode(I->getOpcode());
573 MachineInstrBuilder MIB =
574 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
575 .addOperand(I->getOperand(0))
576 .addOperand(I->getOperand(1))
580 DEBUG(dbgs() << "Creating post-indexed load/store.");
581 DEBUG(dbgs() << " Replacing instructions:\n ");
582 DEBUG(I->print(dbgs()));
583 DEBUG(dbgs() << " ");
584 DEBUG(Update->print(dbgs()));
585 DEBUG(dbgs() << " with instruction:\n ");
586 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
587 DEBUG(dbgs() << "\n");
589 // Erase the old instructions for the block.
590 I->eraseFromParent();
591 Update->eraseFromParent();
596 static bool isMatchingUpdateInsn(MachineInstr *MI, unsigned BaseReg,
598 switch (MI->getOpcode()) {
602 // Negate the offset for a SUB instruction.
606 // Make sure it's a vanilla immediate operand, not a relocation or
607 // anything else we can't handle.
608 if (!MI->getOperand(2).isImm())
610 // Watch out for 1 << 12 shifted value.
611 if (ARM64_AM::getShiftValue(MI->getOperand(3).getImm()))
613 // If the instruction has the base register as source and dest and the
614 // immediate will fit in a signed 9-bit integer, then we have a match.
615 if (MI->getOperand(0).getReg() == BaseReg &&
616 MI->getOperand(1).getReg() == BaseReg &&
617 MI->getOperand(2).getImm() <= 255 &&
618 MI->getOperand(2).getImm() >= -256) {
619 // If we have a non-zero Offset, we check that it matches the amount
620 // we're adding to the register.
621 if (!Offset || Offset == MI->getOperand(2).getImm())
629 MachineBasicBlock::iterator
630 ARM64LoadStoreOpt::findMatchingUpdateInsnForward(MachineBasicBlock::iterator I,
631 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
685 ARM64LoadStoreOpt::findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I,
687 MachineBasicBlock::iterator B = I->getParent()->begin();
688 MachineBasicBlock::iterator E = I->getParent()->end();
689 MachineInstr *MemMI = I;
690 MachineBasicBlock::iterator MBBI = I;
691 const MachineFunction &MF = *MemMI->getParent()->getParent();
693 unsigned DestReg = MemMI->getOperand(0).getReg();
694 unsigned BaseReg = MemMI->getOperand(1).getReg();
695 int Offset = MemMI->getOperand(2).getImm();
696 unsigned RegSize = TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
698 // If the load/store is the first instruction in the block, there's obviously
699 // not any matching update. Ditto if the memory offset isn't zero.
700 if (MBBI == B || Offset != 0)
702 // If the base register overlaps the destination register, we can't
704 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
707 // Track which registers have been modified and used between the first insn
708 // (inclusive) and the second insn.
709 BitVector ModifiedRegs, UsedRegs;
710 ModifiedRegs.resize(TRI->getNumRegs());
711 UsedRegs.resize(TRI->getNumRegs());
713 for (unsigned Count = 0; MBBI != B; --MBBI) {
714 MachineInstr *MI = MBBI;
715 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
716 // optimization by changing how far we scan.
717 if (MI->isDebugValue())
720 // Now that we know this is a real instruction, count it.
723 // If we found a match, return it.
724 if (isMatchingUpdateInsn(MI, BaseReg, RegSize))
727 // Update the status of what the instruction clobbered and used.
728 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
730 // Otherwise, if the base register is used or modified, we have no match, so
732 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
738 bool ARM64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB) {
739 bool Modified = false;
740 // Two tranformations to do here:
741 // 1) Find loads and stores that can be merged into a single load or store
748 // 2) Find base register updates that can be merged into the load or store
749 // as a base-reg writeback.
756 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
758 MachineInstr *MI = MBBI;
759 switch (MI->getOpcode()) {
761 // Just move on to the next instruction.
774 // do the unscaled versions as well
784 case ARM64::LDURXi: {
785 // If this is a volatile load/store, don't mess with it.
786 if (MI->hasOrderedMemoryRef()) {
790 // Make sure this is a reg+imm (as opposed to an address reloc).
791 if (!MI->getOperand(2).isImm()) {
795 // Check if this load/store has a hint to avoid pair formation.
796 // MachineMemOperands hints are set by the ARM64StorePairSuppress pass.
797 if (TII->isLdStPairSuppressed(MI)) {
801 // Look ahead up to ScanLimit instructions for a pairable instruction.
802 bool mergeForward = false;
803 MachineBasicBlock::iterator Paired =
804 findMatchingInsn(MBBI, mergeForward, ScanLimit);
806 // Merge the loads into a pair. Keeping the iterator straight is a
807 // pain, so we let the merge routine tell us what the next instruction
808 // is after it's done mucking about.
809 MBBI = mergePairedInsns(MBBI, Paired, mergeForward);
813 if (isUnscaledLdst(MI->getOpcode()))
814 ++NumUnscaledPairCreated;
820 // FIXME: Do the other instructions.
824 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
826 MachineInstr *MI = MBBI;
827 // Do update merging. It's simpler to keep this separate from the above
828 // switch, though not strictly necessary.
829 int Opc = MI->getOpcode();
832 // Just move on to the next instruction.
845 // do the unscaled versions as well
855 case ARM64::LDURXi: {
856 // Make sure this is a reg+imm (as opposed to an address reloc).
857 if (!MI->getOperand(2).isImm()) {
861 // Look ahead up to ScanLimit instructions for a mergable instruction.
862 MachineBasicBlock::iterator Update =
863 findMatchingUpdateInsnForward(MBBI, ScanLimit, 0);
865 // Merge the update into the ld/st.
866 MBBI = mergePostIdxUpdateInsn(MBBI, Update);
871 // Don't know how to handle pre/post-index versions, so move to the next
873 if (isUnscaledLdst(Opc)) {
878 // Look back to try to find a pre-index instruction. For example,
883 Update = findMatchingUpdateInsnBackward(MBBI, ScanLimit);
885 // Merge the update into the ld/st.
886 MBBI = mergePreIdxUpdateInsn(MBBI, Update);
892 // Look forward to try to find a post-index instruction. For example,
898 // The immediate in the load/store is scaled by the size of the register
899 // being loaded. The immediate in the add we're looking for,
900 // however, is not, so adjust here.
901 int Value = MI->getOperand(2).getImm() *
902 TII->getRegClass(MI->getDesc(), 0, TRI, *(MBB.getParent()))
904 Update = findMatchingUpdateInsnForward(MBBI, ScanLimit, Value);
906 // Merge the update into the ld/st.
907 MBBI = mergePreIdxUpdateInsn(MBBI, Update);
913 // Nothing found. Just move to the next instruction.
917 // FIXME: Do the other instructions.
924 bool ARM64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
925 // Early exit if pass disabled.
929 const TargetMachine &TM = Fn.getTarget();
930 TII = static_cast<const ARM64InstrInfo *>(TM.getInstrInfo());
931 TRI = TM.getRegisterInfo();
933 bool Modified = false;
935 Modified |= optimizeBlock(MBB);
940 // FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
941 // loads and stores near one another?
943 /// createARMLoadStoreOptimizationPass - returns an instance of the load / store
944 /// optimization pass.
945 FunctionPass *llvm::createARM64LoadStoreOptimizationPass() {
946 return new ARM64LoadStoreOpt();