AArch64LoadStoreOptimizer.cpp revision dce4a407a24b04eebc6a376f8e62b41aaa7b071f
1//=- AArch64LoadStoreOptimizer.cpp - AArch64 load/store opt. pass -*- C++ -*-=//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a pass that performs load / store related peephole
11// optimizations. This pass should be run after register allocation.
12//
13//===----------------------------------------------------------------------===//
14
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"
30using namespace llvm;
31
32#define DEBUG_TYPE "aarch64-ldst-opt"
33
34/// AArch64AllocLoadStoreOpt - Post-register allocation pass to combine
35/// load / store instructions to form ldp / stp instructions.
36
37STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
38STATISTIC(NumPostFolded, "Number of post-index updates folded");
39STATISTIC(NumPreFolded, "Number of pre-index updates folded");
40STATISTIC(NumUnscaledPairCreated,
41          "Number of load/store from unscaled generated");
42
43static cl::opt<unsigned> ScanLimit("aarch64-load-store-scan-limit", cl::init(20),
44                                   cl::Hidden);
45
46// Place holder while testing unscaled load/store combining
47static cl::opt<bool>
48EnableAArch64UnscaledMemOp("aarch64-unscaled-mem-op", cl::Hidden,
49                         cl::desc("Allow AArch64 unscaled load/store combining"),
50                         cl::init(true));
51
52namespace {
53struct AArch64LoadStoreOpt : public MachineFunctionPass {
54  static char ID;
55  AArch64LoadStoreOpt() : MachineFunctionPass(ID) {}
56
57  const AArch64InstrInfo *TII;
58  const TargetRegisterInfo *TRI;
59
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,
67                                               bool &mergeForward,
68                                               unsigned Limit);
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);
76
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,
82                                int Value);
83
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);
89
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);
94
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);
99
100  bool optimizeBlock(MachineBasicBlock &MBB);
101
102  bool runOnMachineFunction(MachineFunction &Fn) override;
103
104  const char *getPassName() const override {
105    return "AArch64 load / store optimization pass";
106  }
107
108private:
109  int getMemSize(MachineInstr *MemMI);
110};
111char AArch64LoadStoreOpt::ID = 0;
112}
113
114static bool isUnscaledLdst(unsigned Opc) {
115  switch (Opc) {
116  default:
117    return false;
118  case AArch64::STURSi:
119    return true;
120  case AArch64::STURDi:
121    return true;
122  case AArch64::STURQi:
123    return true;
124  case AArch64::STURWi:
125    return true;
126  case AArch64::STURXi:
127    return true;
128  case AArch64::LDURSi:
129    return true;
130  case AArch64::LDURDi:
131    return true;
132  case AArch64::LDURQi:
133    return true;
134  case AArch64::LDURWi:
135    return true;
136  case AArch64::LDURXi:
137    return true;
138  }
139}
140
141// Size in bytes of the data moved by an unscaled load or store
142int AArch64LoadStoreOpt::getMemSize(MachineInstr *MemMI) {
143  switch (MemMI->getOpcode()) {
144  default:
145    llvm_unreachable("Opcode has has unknown size!");
146  case AArch64::STRSui:
147  case AArch64::STURSi:
148    return 4;
149  case AArch64::STRDui:
150  case AArch64::STURDi:
151    return 8;
152  case AArch64::STRQui:
153  case AArch64::STURQi:
154    return 16;
155  case AArch64::STRWui:
156  case AArch64::STURWi:
157    return 4;
158  case AArch64::STRXui:
159  case AArch64::STURXi:
160    return 8;
161  case AArch64::LDRSui:
162  case AArch64::LDURSi:
163    return 4;
164  case AArch64::LDRDui:
165  case AArch64::LDURDi:
166    return 8;
167  case AArch64::LDRQui:
168  case AArch64::LDURQi:
169    return 16;
170  case AArch64::LDRWui:
171  case AArch64::LDURWi:
172    return 4;
173  case AArch64::LDRXui:
174  case AArch64::LDURXi:
175    return 8;
176  }
177}
178
179static unsigned getMatchingPairOpcode(unsigned Opc) {
180  switch (Opc) {
181  default:
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;
213  }
214}
215
216static unsigned getPreIndexedOpcode(unsigned Opc) {
217  switch (Opc) {
218  default:
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;
230  }
231}
232
233static unsigned getPostIndexedOpcode(unsigned Opc) {
234  switch (Opc) {
235  default:
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;
257  }
258}
259
260MachineBasicBlock::iterator
261AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
262                                      MachineBasicBlock::iterator Paired,
263                                      bool mergeForward) {
264  MachineBasicBlock::iterator NextI = I;
265  ++NextI;
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.
270  if (NextI == Paired)
271    ++NextI;
272
273  bool IsUnscaled = isUnscaledLdst(I->getOpcode());
274  int OffsetStride =
275      IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(I) : 1;
276
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);
285
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) {
290    RtMI = Paired;
291    Rt2MI = I;
292  } else {
293    RtMI = I;
294    Rt2MI = Paired;
295  }
296  // Handle Unscaled
297  int OffsetImm = RtMI->getOperand(2).getImm();
298  if (IsUnscaled && EnableAArch64UnscaledMemOp)
299    OffsetImm /= OffsetStride;
300
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)
307                                .addImm(OffsetImm);
308  (void)MIB;
309
310  // FIXME: Do we need/want to copy the mem operands from the source
311  //        instructions? Probably. What uses them after this?
312
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");
320
321  // Erase the old instructions.
322  I->eraseFromParent();
323  Paired->eraseFromParent();
324
325  return NextI;
326}
327
328/// trackRegDefsUses - Remember what registers the specified instruction uses
329/// and modifies.
330static void trackRegDefsUses(MachineInstr *MI, BitVector &ModifiedRegs,
331                             BitVector &UsedRegs,
332                             const TargetRegisterInfo *TRI) {
333  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
334    MachineOperand &MO = MI->getOperand(i);
335    if (MO.isRegMask())
336      ModifiedRegs.setBitsNotInMask(MO.getRegMask());
337
338    if (!MO.isReg())
339      continue;
340    unsigned Reg = MO.getReg();
341    if (MO.isDef()) {
342      for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
343        ModifiedRegs.set(*AI);
344    } else {
345      assert(MO.isUse() && "Reg operand not a def and not a use?!?");
346      for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
347        UsedRegs.set(*AI);
348    }
349  }
350}
351
352static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
353  if (!IsUnscaled && (Offset > 63 || Offset < -64))
354    return false;
355  if (IsUnscaled) {
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)
360      return false;
361  }
362  return true;
363}
364
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?
369static int alignTo(int Num, int PowOf2) {
370  return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
371}
372
373/// findMatchingInsn - Scan the instructions looking for a load/store that can
374/// be combined with the current instruction into a load/store pair.
375MachineBasicBlock::iterator
376AArch64LoadStoreOpt::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;
381  ++MBBI;
382
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();
389
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
394  // with Offset-1
395  if (FirstMI->modifiesRegister(BaseReg, TRI))
396    return E;
397  int OffsetStride =
398      IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(FirstMI) : 1;
399  if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
400    return E;
401
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())
412      continue;
413
414    // Now that we know this is a real instruction, count it.
415    ++Count;
416
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
423      // a relocation.
424      //
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))
437          return E;
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);
443          continue;
444        }
445        // If the alignment requirements of the paired (scaled) instruction
446        // can't express the offset of the unscaled input, bail and keep
447        // looking.
448        if (IsUnscaled && EnableAArch64UnscaledMemOp &&
449            (alignTo(MinOffset, OffsetStride) != MinOffset)) {
450          trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
451          continue;
452        }
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);
458          continue;
459        }
460
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;
466          return MBBI;
467        }
468
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
471        // second.
472        if (!ModifiedRegs[FirstMI->getOperand(0).getReg()] &&
473            !UsedRegs[FirstMI->getOperand(0).getReg()]) {
474          mergeForward = true;
475          return MBBI;
476        }
477        // Unable to combine these instructions due to interference in between.
478        // Keep looking.
479      }
480    }
481
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.
486    //
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
491    // instructions.
492    if (MI->mayStore() || MI->isCall())
493      return E;
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())
497      return E;
498
499    // Update modified / uses register lists.
500    trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
501
502    // Otherwise, if the base register is modified, we have no match, so
503    // return early.
504    if (ModifiedRegs[BaseReg])
505      return E;
506  }
507  return E;
508}
509
510MachineBasicBlock::iterator
511AArch64LoadStoreOpt::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)
521    ++NextI;
522
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)
527    Value = -Value;
528
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))
535          .addImm(Value);
536  (void)MIB;
537
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");
546
547  // Erase the old instructions for the block.
548  I->eraseFromParent();
549  Update->eraseFromParent();
550
551  return NextI;
552}
553
554MachineBasicBlock::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)
564    ++NextI;
565
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)
570    Value = -Value;
571
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))
578          .addImm(Value);
579  (void)MIB;
580
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");
589
590  // Erase the old instructions for the block.
591  I->eraseFromParent();
592  Update->eraseFromParent();
593
594  return NextI;
595}
596
597static bool isMatchingUpdateInsn(MachineInstr *MI, unsigned BaseReg,
598                                 int Offset) {
599  switch (MI->getOpcode()) {
600  default:
601    break;
602  case AArch64::SUBXri:
603    // Negate the offset for a SUB instruction.
604    Offset *= -1;
605  // FALLTHROUGH
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())
610      break;
611    // Watch out for 1 << 12 shifted value.
612    if (AArch64_AM::getShiftValue(MI->getOperand(3).getImm()))
613      break;
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())
623        return true;
624    }
625    break;
626  }
627  return false;
628}
629
630MachineBasicBlock::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();
636
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();
641
642  // If the base register overlaps the destination register, we can't
643  // merge the update.
644  if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
645    return E;
646
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.
650  if (Offset != Value)
651    return E;
652
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());
658  ++MBBI;
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())
664      continue;
665
666    // Now that we know this is a real instruction, count it.
667    ++Count;
668
669    // If we found a match, return it.
670    if (isMatchingUpdateInsn(MI, BaseReg, Value))
671      return MBBI;
672
673    // Update the status of what the instruction clobbered and used.
674    trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
675
676    // Otherwise, if the base register is used or modified, we have no match, so
677    // return early.
678    if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
679      return E;
680  }
681  return E;
682}
683
684MachineBasicBlock::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();
691
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();
696
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)
700    return E;
701  // If the base register overlaps the destination register, we can't
702  // merge the update.
703  if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
704    return E;
705
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());
711  --MBBI;
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())
717      continue;
718
719    // Now that we know this is a real instruction, count it.
720    ++Count;
721
722    // If we found a match, return it.
723    if (isMatchingUpdateInsn(MI, BaseReg, RegSize))
724      return MBBI;
725
726    // Update the status of what the instruction clobbered and used.
727    trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
728
729    // Otherwise, if the base register is used or modified, we have no match, so
730    // return early.
731    if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
732      return E;
733  }
734  return E;
735}
736
737bool 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
741  //    pair instruction.
742  //      e.g.,
743  //        ldr x0, [x2]
744  //        ldr x1, [x2, #8]
745  //        ; becomes
746  //        ldp x0, x1, [x2]
747  // 2) Find base register updates that can be merged into the load or store
748  //    as a base-reg writeback.
749  //      e.g.,
750  //        ldr x0, [x2]
751  //        add x2, x2, #4
752  //        ; becomes
753  //        ldr x0, [x2], #4
754
755  for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
756       MBBI != E;) {
757    MachineInstr *MI = MBBI;
758    switch (MI->getOpcode()) {
759    default:
760      // Just move on to the next instruction.
761      ++MBBI;
762      break;
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()) {
786        ++MBBI;
787        break;
788      }
789      // Make sure this is a reg+imm (as opposed to an address reloc).
790      if (!MI->getOperand(2).isImm()) {
791        ++MBBI;
792        break;
793      }
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)) {
797        ++MBBI;
798        break;
799      }
800      // Look ahead up to ScanLimit instructions for a pairable instruction.
801      bool mergeForward = false;
802      MachineBasicBlock::iterator Paired =
803          findMatchingInsn(MBBI, mergeForward, ScanLimit);
804      if (Paired != E) {
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);
809
810        Modified = true;
811        ++NumPairCreated;
812        if (isUnscaledLdst(MI->getOpcode()))
813          ++NumUnscaledPairCreated;
814        break;
815      }
816      ++MBBI;
817      break;
818    }
819      // FIXME: Do the other instructions.
820    }
821  }
822
823  for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
824       MBBI != E;) {
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();
829    switch (Opc) {
830    default:
831      // Just move on to the next instruction.
832      ++MBBI;
833      break;
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()) {
857        ++MBBI;
858        break;
859      }
860      // Look ahead up to ScanLimit instructions for a mergable instruction.
861      MachineBasicBlock::iterator Update =
862          findMatchingUpdateInsnForward(MBBI, ScanLimit, 0);
863      if (Update != E) {
864        // Merge the update into the ld/st.
865        MBBI = mergePostIdxUpdateInsn(MBBI, Update);
866        Modified = true;
867        ++NumPostFolded;
868        break;
869      }
870      // Don't know how to handle pre/post-index versions, so move to the next
871      // instruction.
872      if (isUnscaledLdst(Opc)) {
873        ++MBBI;
874        break;
875      }
876
877      // Look back to try to find a pre-index instruction. For example,
878      // add x0, x0, #8
879      // ldr x1, [x0]
880      //   merged into:
881      // ldr x1, [x0, #8]!
882      Update = findMatchingUpdateInsnBackward(MBBI, ScanLimit);
883      if (Update != E) {
884        // Merge the update into the ld/st.
885        MBBI = mergePreIdxUpdateInsn(MBBI, Update);
886        Modified = true;
887        ++NumPreFolded;
888        break;
889      }
890
891      // Look forward to try to find a post-index instruction. For example,
892      // ldr x1, [x0, #64]
893      // add x0, x0, #64
894      //   merged into:
895      // ldr x1, [x0, #64]!
896
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()))
902                      ->getSize();
903      Update = findMatchingUpdateInsnForward(MBBI, ScanLimit, Value);
904      if (Update != E) {
905        // Merge the update into the ld/st.
906        MBBI = mergePreIdxUpdateInsn(MBBI, Update);
907        Modified = true;
908        ++NumPreFolded;
909        break;
910      }
911
912      // Nothing found. Just move to the next instruction.
913      ++MBBI;
914      break;
915    }
916      // FIXME: Do the other instructions.
917    }
918  }
919
920  return Modified;
921}
922
923bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
924  const TargetMachine &TM = Fn.getTarget();
925  TII = static_cast<const AArch64InstrInfo *>(TM.getInstrInfo());
926  TRI = TM.getRegisterInfo();
927
928  bool Modified = false;
929  for (auto &MBB : Fn)
930    Modified |= optimizeBlock(MBB);
931
932  return Modified;
933}
934
935// FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
936// loads and stores near one another?
937
938/// createARMLoadStoreOptimizationPass - returns an instance of the load / store
939/// optimization pass.
940FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
941  return new AArch64LoadStoreOpt();
942}
943