Update comment. NFC.
[oota-llvm.git] / lib / Target / AArch64 / AArch64LoadStoreOptimizer.cpp
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 "AArch64Subtarget.h"
17 #include "MCTargetDesc/AArch64AddressingModes.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/CodeGen/MachineBasicBlock.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 using namespace llvm;
33
34 #define DEBUG_TYPE "aarch64-ldst-opt"
35
36 /// AArch64AllocLoadStoreOpt - Post-register allocation pass to combine
37 /// load / store instructions to form ldp / stp instructions.
38
39 STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
40 STATISTIC(NumPostFolded, "Number of post-index updates folded");
41 STATISTIC(NumPreFolded, "Number of pre-index updates folded");
42 STATISTIC(NumUnscaledPairCreated,
43           "Number of load/store from unscaled generated");
44
45 static cl::opt<unsigned> ScanLimit("aarch64-load-store-scan-limit",
46                                    cl::init(20), cl::Hidden);
47
48 // Place holder while testing unscaled load/store combining
49 static cl::opt<bool> EnableAArch64UnscaledMemOp(
50     "aarch64-unscaled-mem-op", cl::Hidden,
51     cl::desc("Allow AArch64 unscaled load/store combining"), cl::init(true));
52
53 namespace {
54
55 typedef struct LdStPairFlags {
56   // If a matching instruction is found, MergeForward is set to true if the
57   // merge is to remove the first instruction and replace the second with
58   // a pair-wise insn, and false if the reverse is true.
59   bool MergeForward;
60
61   // SExtIdx gives the index of the result of the load pair that must be
62   // extended. The value of SExtIdx assumes that the paired load produces the
63   // value in this order: (I, returned iterator), i.e., -1 means no value has
64   // to be extended, 0 means I, and 1 means the returned iterator.
65   int SExtIdx;
66
67   LdStPairFlags() : MergeForward(false), SExtIdx(-1) {}
68
69   void setMergeForward(bool V = true) { MergeForward = V; }
70   bool getMergeForward() const { return MergeForward; }
71
72   void setSExtIdx(int V) { SExtIdx = V; }
73   int getSExtIdx() const { return SExtIdx; }
74
75 } LdStPairFlags;
76
77 struct AArch64LoadStoreOpt : public MachineFunctionPass {
78   static char ID;
79   AArch64LoadStoreOpt() : MachineFunctionPass(ID) {}
80
81   const AArch64InstrInfo *TII;
82   const TargetRegisterInfo *TRI;
83
84   // Scan the instructions looking for a load/store that can be combined
85   // with the current instruction into a load/store pair.
86   // Return the matching instruction if one is found, else MBB->end().
87   MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
88                                                LdStPairFlags &Flags,
89                                                unsigned Limit);
90   // Merge the two instructions indicated into a single pair-wise instruction.
91   // If MergeForward is true, erase the first instruction and fold its
92   // operation into the second. If false, the reverse. Return the instruction
93   // following the first instruction (which may change during processing).
94   MachineBasicBlock::iterator
95   mergePairedInsns(MachineBasicBlock::iterator I,
96                    MachineBasicBlock::iterator Paired,
97                    const LdStPairFlags &Flags);
98
99   // Scan the instruction list to find a base register update that can
100   // be combined with the current instruction (a load or store) using
101   // pre or post indexed addressing with writeback. Scan forwards.
102   MachineBasicBlock::iterator
103   findMatchingUpdateInsnForward(MachineBasicBlock::iterator I, unsigned Limit,
104                                 int Value);
105
106   // Scan the instruction list to find a base register update that can
107   // be combined with the current instruction (a load or store) using
108   // pre or post indexed addressing with writeback. Scan backwards.
109   MachineBasicBlock::iterator
110   findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
111
112   // Merge a pre-index base register update into a ld/st instruction.
113   MachineBasicBlock::iterator
114   mergePreIdxUpdateInsn(MachineBasicBlock::iterator I,
115                         MachineBasicBlock::iterator Update);
116
117   // Merge a post-index base register update into a ld/st instruction.
118   MachineBasicBlock::iterator
119   mergePostIdxUpdateInsn(MachineBasicBlock::iterator I,
120                          MachineBasicBlock::iterator Update);
121
122   bool optimizeBlock(MachineBasicBlock &MBB);
123
124   bool runOnMachineFunction(MachineFunction &Fn) override;
125
126   const char *getPassName() const override {
127     return "AArch64 load / store optimization pass";
128   }
129
130 private:
131   int getMemSize(MachineInstr *MemMI);
132 };
133 char AArch64LoadStoreOpt::ID = 0;
134 } // namespace
135
136 static bool isUnscaledLdst(unsigned Opc) {
137   switch (Opc) {
138   default:
139     return false;
140   case AArch64::STURSi:
141   case AArch64::STURDi:
142   case AArch64::STURQi:
143   case AArch64::STURWi:
144   case AArch64::STURXi:
145   case AArch64::LDURSi:
146   case AArch64::LDURDi:
147   case AArch64::LDURQi:
148   case AArch64::LDURWi:
149   case AArch64::LDURXi:
150   case AArch64::LDURSWi:
151     return true;
152   }
153 }
154
155 // Size in bytes of the data moved by an unscaled load or store
156 int AArch64LoadStoreOpt::getMemSize(MachineInstr *MemMI) {
157   switch (MemMI->getOpcode()) {
158   default:
159     llvm_unreachable("Opcode has unknown size!");
160   case AArch64::STRSui:
161   case AArch64::STURSi:
162     return 4;
163   case AArch64::STRDui:
164   case AArch64::STURDi:
165     return 8;
166   case AArch64::STRQui:
167   case AArch64::STURQi:
168     return 16;
169   case AArch64::STRWui:
170   case AArch64::STURWi:
171     return 4;
172   case AArch64::STRXui:
173   case AArch64::STURXi:
174     return 8;
175   case AArch64::LDRSui:
176   case AArch64::LDURSi:
177     return 4;
178   case AArch64::LDRDui:
179   case AArch64::LDURDi:
180     return 8;
181   case AArch64::LDRQui:
182   case AArch64::LDURQi:
183     return 16;
184   case AArch64::LDRWui:
185   case AArch64::LDURWi:
186     return 4;
187   case AArch64::LDRXui:
188   case AArch64::LDURXi:
189     return 8;
190   case AArch64::LDRSWui:
191   case AArch64::LDURSWi:
192     return 4;
193   }
194 }
195
196 static unsigned getMatchingNonSExtOpcode(unsigned Opc,
197                                          bool *IsValidLdStrOpc = nullptr) {
198   if (IsValidLdStrOpc)
199     *IsValidLdStrOpc = true;
200   switch (Opc) {
201   default:
202     if (IsValidLdStrOpc)
203       *IsValidLdStrOpc = false;
204     return UINT_MAX;
205   case AArch64::STRDui:
206   case AArch64::STURDi:
207   case AArch64::STRQui:
208   case AArch64::STURQi:
209   case AArch64::STRWui:
210   case AArch64::STURWi:
211   case AArch64::STRXui:
212   case AArch64::STURXi:
213   case AArch64::LDRDui:
214   case AArch64::LDURDi:
215   case AArch64::LDRQui:
216   case AArch64::LDURQi:
217   case AArch64::LDRWui:
218   case AArch64::LDURWi:
219   case AArch64::LDRXui:
220   case AArch64::LDURXi:
221   case AArch64::STRSui:
222   case AArch64::STURSi:
223   case AArch64::LDRSui:
224   case AArch64::LDURSi:
225     return Opc;
226   case AArch64::LDRSWui:
227     return AArch64::LDRWui;
228   case AArch64::LDURSWi:
229     return AArch64::LDURWi;
230   }
231 }
232
233 static unsigned getMatchingPairOpcode(unsigned Opc) {
234   switch (Opc) {
235   default:
236     llvm_unreachable("Opcode has no pairwise equivalent!");
237   case AArch64::STRSui:
238   case AArch64::STURSi:
239     return AArch64::STPSi;
240   case AArch64::STRDui:
241   case AArch64::STURDi:
242     return AArch64::STPDi;
243   case AArch64::STRQui:
244   case AArch64::STURQi:
245     return AArch64::STPQi;
246   case AArch64::STRWui:
247   case AArch64::STURWi:
248     return AArch64::STPWi;
249   case AArch64::STRXui:
250   case AArch64::STURXi:
251     return AArch64::STPXi;
252   case AArch64::LDRSui:
253   case AArch64::LDURSi:
254     return AArch64::LDPSi;
255   case AArch64::LDRDui:
256   case AArch64::LDURDi:
257     return AArch64::LDPDi;
258   case AArch64::LDRQui:
259   case AArch64::LDURQi:
260     return AArch64::LDPQi;
261   case AArch64::LDRWui:
262   case AArch64::LDURWi:
263     return AArch64::LDPWi;
264   case AArch64::LDRXui:
265   case AArch64::LDURXi:
266     return AArch64::LDPXi;
267   case AArch64::LDRSWui:
268   case AArch64::LDURSWi:
269     return AArch64::LDPSWi;
270   }
271 }
272
273 static unsigned getPreIndexedOpcode(unsigned Opc) {
274   switch (Opc) {
275   default:
276     llvm_unreachable("Opcode has no pre-indexed equivalent!");
277   case AArch64::STRSui:
278     return AArch64::STRSpre;
279   case AArch64::STRDui:
280     return AArch64::STRDpre;
281   case AArch64::STRQui:
282     return AArch64::STRQpre;
283   case AArch64::STRWui:
284     return AArch64::STRWpre;
285   case AArch64::STRXui:
286     return AArch64::STRXpre;
287   case AArch64::LDRSui:
288     return AArch64::LDRSpre;
289   case AArch64::LDRDui:
290     return AArch64::LDRDpre;
291   case AArch64::LDRQui:
292     return AArch64::LDRQpre;
293   case AArch64::LDRWui:
294     return AArch64::LDRWpre;
295   case AArch64::LDRXui:
296     return AArch64::LDRXpre;
297   case AArch64::LDRSWui:
298     return AArch64::LDRSWpre;
299   }
300 }
301
302 static unsigned getPostIndexedOpcode(unsigned Opc) {
303   switch (Opc) {
304   default:
305     llvm_unreachable("Opcode has no post-indexed wise equivalent!");
306   case AArch64::STRSui:
307     return AArch64::STRSpost;
308   case AArch64::STRDui:
309     return AArch64::STRDpost;
310   case AArch64::STRQui:
311     return AArch64::STRQpost;
312   case AArch64::STRWui:
313     return AArch64::STRWpost;
314   case AArch64::STRXui:
315     return AArch64::STRXpost;
316   case AArch64::LDRSui:
317     return AArch64::LDRSpost;
318   case AArch64::LDRDui:
319     return AArch64::LDRDpost;
320   case AArch64::LDRQui:
321     return AArch64::LDRQpost;
322   case AArch64::LDRWui:
323     return AArch64::LDRWpost;
324   case AArch64::LDRXui:
325     return AArch64::LDRXpost;
326   case AArch64::LDRSWui:
327     return AArch64::LDRSWpost;
328   }
329 }
330
331 MachineBasicBlock::iterator
332 AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
333                                       MachineBasicBlock::iterator Paired,
334                                       const LdStPairFlags &Flags) {
335   MachineBasicBlock::iterator NextI = I;
336   ++NextI;
337   // If NextI is the second of the two instructions to be merged, we need
338   // to skip one further. Either way we merge will invalidate the iterator,
339   // and we don't need to scan the new instruction, as it's a pairwise
340   // instruction, which we're not considering for further action anyway.
341   if (NextI == Paired)
342     ++NextI;
343
344   int SExtIdx = Flags.getSExtIdx();
345   unsigned Opc =
346       SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
347   bool IsUnscaled = isUnscaledLdst(Opc);
348   int OffsetStride =
349       IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(I) : 1;
350
351   bool MergeForward = Flags.getMergeForward();
352   unsigned NewOpc = getMatchingPairOpcode(Opc);
353   // Insert our new paired instruction after whichever of the paired
354   // instructions MergeForward indicates.
355   MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
356   // Also based on MergeForward is from where we copy the base register operand
357   // so we get the flags compatible with the input code.
358   MachineOperand &BaseRegOp =
359       MergeForward ? Paired->getOperand(1) : I->getOperand(1);
360
361   // Which register is Rt and which is Rt2 depends on the offset order.
362   MachineInstr *RtMI, *Rt2MI;
363   if (I->getOperand(2).getImm() ==
364       Paired->getOperand(2).getImm() + OffsetStride) {
365     RtMI = Paired;
366     Rt2MI = I;
367     // Here we swapped the assumption made for SExtIdx.
368     // I.e., we turn ldp I, Paired into ldp Paired, I.
369     // Update the index accordingly.
370     if (SExtIdx != -1)
371       SExtIdx = (SExtIdx + 1) % 2;
372   } else {
373     RtMI = I;
374     Rt2MI = Paired;
375   }
376   // Handle Unscaled
377   int OffsetImm = RtMI->getOperand(2).getImm();
378   if (IsUnscaled && EnableAArch64UnscaledMemOp)
379     OffsetImm /= OffsetStride;
380
381   // Construct the new instruction.
382   MachineInstrBuilder MIB = BuildMI(*I->getParent(), InsertionPoint,
383                                     I->getDebugLoc(), TII->get(NewOpc))
384                                 .addOperand(RtMI->getOperand(0))
385                                 .addOperand(Rt2MI->getOperand(0))
386                                 .addOperand(BaseRegOp)
387                                 .addImm(OffsetImm);
388   (void)MIB;
389
390   // FIXME: Do we need/want to copy the mem operands from the source
391   //        instructions? Probably. What uses them after this?
392
393   DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n    ");
394   DEBUG(I->print(dbgs()));
395   DEBUG(dbgs() << "    ");
396   DEBUG(Paired->print(dbgs()));
397   DEBUG(dbgs() << "  with instruction:\n    ");
398
399   if (SExtIdx != -1) {
400     // Generate the sign extension for the proper result of the ldp.
401     // I.e., with X1, that would be:
402     // %W1<def> = KILL %W1, %X1<imp-def>
403     // %X1<def> = SBFMXri %X1<kill>, 0, 31
404     MachineOperand &DstMO = MIB->getOperand(SExtIdx);
405     // Right now, DstMO has the extended register, since it comes from an
406     // extended opcode.
407     unsigned DstRegX = DstMO.getReg();
408     // Get the W variant of that register.
409     unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
410     // Update the result of LDP to use the W instead of the X variant.
411     DstMO.setReg(DstRegW);
412     DEBUG(((MachineInstr *)MIB)->print(dbgs()));
413     DEBUG(dbgs() << "\n");
414     // Make the machine verifier happy by providing a definition for
415     // the X register.
416     // Insert this definition right after the generated LDP, i.e., before
417     // InsertionPoint.
418     MachineInstrBuilder MIBKill =
419         BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
420                 TII->get(TargetOpcode::KILL), DstRegW)
421             .addReg(DstRegW)
422             .addReg(DstRegX, RegState::Define);
423     MIBKill->getOperand(2).setImplicit();
424     // Create the sign extension.
425     MachineInstrBuilder MIBSXTW =
426         BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
427                 TII->get(AArch64::SBFMXri), DstRegX)
428             .addReg(DstRegX)
429             .addImm(0)
430             .addImm(31);
431     (void)MIBSXTW;
432     DEBUG(dbgs() << "  Extend operand:\n    ");
433     DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
434     DEBUG(dbgs() << "\n");
435   } else {
436     DEBUG(((MachineInstr *)MIB)->print(dbgs()));
437     DEBUG(dbgs() << "\n");
438   }
439
440   // Erase the old instructions.
441   I->eraseFromParent();
442   Paired->eraseFromParent();
443
444   return NextI;
445 }
446
447 /// trackRegDefsUses - Remember what registers the specified instruction uses
448 /// and modifies.
449 static void trackRegDefsUses(const MachineInstr *MI, BitVector &ModifiedRegs,
450                              BitVector &UsedRegs,
451                              const TargetRegisterInfo *TRI) {
452   for (const MachineOperand &MO : MI->operands()) {
453     if (MO.isRegMask())
454       ModifiedRegs.setBitsNotInMask(MO.getRegMask());
455
456     if (!MO.isReg())
457       continue;
458     unsigned Reg = MO.getReg();
459     if (MO.isDef()) {
460       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
461         ModifiedRegs.set(*AI);
462     } else {
463       assert(MO.isUse() && "Reg operand not a def and not a use?!?");
464       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
465         UsedRegs.set(*AI);
466     }
467   }
468 }
469
470 static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
471   if (!IsUnscaled && (Offset > 63 || Offset < -64))
472     return false;
473   if (IsUnscaled) {
474     // Convert the byte-offset used by unscaled into an "element" offset used
475     // by the scaled pair load/store instructions.
476     int ElemOffset = Offset / OffsetStride;
477     if (ElemOffset > 63 || ElemOffset < -64)
478       return false;
479   }
480   return true;
481 }
482
483 // Do alignment, specialized to power of 2 and for signed ints,
484 // avoiding having to do a C-style cast from uint_64t to int when
485 // using RoundUpToAlignment from include/llvm/Support/MathExtras.h.
486 // FIXME: Move this function to include/MathExtras.h?
487 static int alignTo(int Num, int PowOf2) {
488   return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
489 }
490
491 static bool mayAlias(MachineInstr *MIa, MachineInstr *MIb,
492                      const AArch64InstrInfo *TII) {
493   // One of the instructions must modify memory.
494   if (!MIa->mayStore() && !MIb->mayStore())
495     return false;
496
497   // Both instructions must be memory operations.
498   if (!MIa->mayLoadOrStore() && !MIb->mayLoadOrStore())
499     return false;
500
501   return !TII->areMemAccessesTriviallyDisjoint(MIa, MIb);
502 }
503
504 static bool mayAlias(MachineInstr *MIa,
505                      SmallVectorImpl<MachineInstr *> &MemInsns,
506                      const AArch64InstrInfo *TII) {
507   for (auto &MIb : MemInsns)
508     if (mayAlias(MIa, MIb, TII))
509       return true;
510
511   return false;
512 }
513
514 /// findMatchingInsn - Scan the instructions looking for a load/store that can
515 /// be combined with the current instruction into a load/store pair.
516 MachineBasicBlock::iterator
517 AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
518                                       LdStPairFlags &Flags,
519                                       unsigned Limit) {
520   MachineBasicBlock::iterator E = I->getParent()->end();
521   MachineBasicBlock::iterator MBBI = I;
522   MachineInstr *FirstMI = I;
523   ++MBBI;
524
525   unsigned Opc = FirstMI->getOpcode();
526   bool MayLoad = FirstMI->mayLoad();
527   bool IsUnscaled = isUnscaledLdst(Opc);
528   unsigned Reg = FirstMI->getOperand(0).getReg();
529   unsigned BaseReg = FirstMI->getOperand(1).getReg();
530   int Offset = FirstMI->getOperand(2).getImm();
531
532   // Early exit if the first instruction modifies the base register.
533   // e.g., ldr x0, [x0]
534   // Early exit if the offset if not possible to match. (6 bits of positive
535   // range, plus allow an extra one in case we find a later insn that matches
536   // with Offset-1
537   if (FirstMI->modifiesRegister(BaseReg, TRI))
538     return E;
539   int OffsetStride =
540       IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(FirstMI) : 1;
541   if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
542     return E;
543
544   // Track which registers have been modified and used between the first insn
545   // (inclusive) and the second insn.
546   BitVector ModifiedRegs, UsedRegs;
547   ModifiedRegs.resize(TRI->getNumRegs());
548   UsedRegs.resize(TRI->getNumRegs());
549
550   // Remember any instructions that read/write memory between FirstMI and MI.
551   SmallVector<MachineInstr *, 4> MemInsns;
552
553   for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
554     MachineInstr *MI = MBBI;
555     // Skip DBG_VALUE instructions. Otherwise debug info can affect the
556     // optimization by changing how far we scan.
557     if (MI->isDebugValue())
558       continue;
559
560     // Now that we know this is a real instruction, count it.
561     ++Count;
562
563     bool CanMergeOpc = Opc == MI->getOpcode();
564     Flags.setSExtIdx(-1);
565     if (!CanMergeOpc) {
566       bool IsValidLdStrOpc;
567       unsigned NonSExtOpc = getMatchingNonSExtOpcode(Opc, &IsValidLdStrOpc);
568       if (!IsValidLdStrOpc)
569         continue;
570       // Opc will be the first instruction in the pair.
571       Flags.setSExtIdx(NonSExtOpc == (unsigned)Opc ? 1 : 0);
572       CanMergeOpc = NonSExtOpc == getMatchingNonSExtOpcode(MI->getOpcode());
573     }
574
575     if (CanMergeOpc && MI->getOperand(2).isImm()) {
576       // If we've found another instruction with the same opcode, check to see
577       // if the base and offset are compatible with our starting instruction.
578       // These instructions all have scaled immediate operands, so we just
579       // check for +1/-1. Make sure to check the new instruction offset is
580       // actually an immediate and not a symbolic reference destined for
581       // a relocation.
582       //
583       // Pairwise instructions have a 7-bit signed offset field. Single insns
584       // have a 12-bit unsigned offset field. To be a valid combine, the
585       // final offset must be in range.
586       unsigned MIBaseReg = MI->getOperand(1).getReg();
587       int MIOffset = MI->getOperand(2).getImm();
588       if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
589                                    (Offset + OffsetStride == MIOffset))) {
590         int MinOffset = Offset < MIOffset ? Offset : MIOffset;
591         // If this is a volatile load/store that otherwise matched, stop looking
592         // as something is going on that we don't have enough information to
593         // safely transform. Similarly, stop if we see a hint to avoid pairs.
594         if (MI->hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
595           return E;
596         // If the resultant immediate offset of merging these instructions
597         // is out of range for a pairwise instruction, bail and keep looking.
598         bool MIIsUnscaled = isUnscaledLdst(MI->getOpcode());
599         if (!inBoundsForPair(MIIsUnscaled, MinOffset, OffsetStride)) {
600           trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
601           if (MI->mayLoadOrStore())
602             MemInsns.push_back(MI);
603           continue;
604         }
605         // If the alignment requirements of the paired (scaled) instruction
606         // can't express the offset of the unscaled input, bail and keep
607         // looking.
608         if (IsUnscaled && EnableAArch64UnscaledMemOp &&
609             (alignTo(MinOffset, OffsetStride) != MinOffset)) {
610           trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
611           if (MI->mayLoadOrStore())
612             MemInsns.push_back(MI);
613           continue;
614         }
615         // If the destination register of the loads is the same register, bail
616         // and keep looking. A load-pair instruction with both destination
617         // registers the same is UNPREDICTABLE and will result in an exception.
618         if (MayLoad && Reg == MI->getOperand(0).getReg()) {
619           trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
620           if (MI->mayLoadOrStore())
621             MemInsns.push_back(MI);
622           continue;
623         }
624
625         // If the Rt of the second instruction was not modified or used between
626         // the two instructions and none of the instructions between the second
627         // and first alias with the second, we can combine the second into the
628         // first.
629         if (!ModifiedRegs[MI->getOperand(0).getReg()] &&
630             !(MI->mayLoad() && UsedRegs[MI->getOperand(0).getReg()]) &&
631             !mayAlias(MI, MemInsns, TII)) {
632           Flags.setMergeForward(false);
633           return MBBI;
634         }
635
636         // Likewise, if the Rt of the first instruction is not modified or used
637         // between the two instructions and none of the instructions between the
638         // first and the second alias with the first, we can combine the first
639         // into the second.
640         if (!ModifiedRegs[FirstMI->getOperand(0).getReg()] &&
641             !(FirstMI->mayLoad() &&
642               UsedRegs[FirstMI->getOperand(0).getReg()]) &&
643             !mayAlias(FirstMI, MemInsns, TII)) {
644           Flags.setMergeForward(true);
645           return MBBI;
646         }
647         // Unable to combine these instructions due to interference in between.
648         // Keep looking.
649       }
650     }
651
652     // If the instruction wasn't a matching load or store.  Stop searching if we
653     // encounter a call instruction that might modify memory.
654     if (MI->isCall())
655       return E;
656
657     // Update modified / uses register lists.
658     trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
659
660     // Otherwise, if the base register is modified, we have no match, so
661     // return early.
662     if (ModifiedRegs[BaseReg])
663       return E;
664
665     // Update list of instructions that read/write memory.
666     if (MI->mayLoadOrStore())
667       MemInsns.push_back(MI);
668   }
669   return E;
670 }
671
672 MachineBasicBlock::iterator
673 AArch64LoadStoreOpt::mergePreIdxUpdateInsn(MachineBasicBlock::iterator I,
674                                            MachineBasicBlock::iterator Update) {
675   assert((Update->getOpcode() == AArch64::ADDXri ||
676           Update->getOpcode() == AArch64::SUBXri) &&
677          "Unexpected base register update instruction to merge!");
678   MachineBasicBlock::iterator NextI = I;
679   // Return the instruction following the merged instruction, which is
680   // the instruction following our unmerged load. Unless that's the add/sub
681   // instruction we're merging, in which case it's the one after that.
682   if (++NextI == Update)
683     ++NextI;
684
685   int Value = Update->getOperand(2).getImm();
686   assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
687          "Can't merge 1 << 12 offset into pre-indexed load / store");
688   if (Update->getOpcode() == AArch64::SUBXri)
689     Value = -Value;
690
691   unsigned NewOpc = getPreIndexedOpcode(I->getOpcode());
692   MachineInstrBuilder MIB =
693       BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
694           .addOperand(Update->getOperand(0))
695           .addOperand(I->getOperand(0))
696           .addOperand(I->getOperand(1))
697           .addImm(Value);
698   (void)MIB;
699
700   DEBUG(dbgs() << "Creating pre-indexed load/store.");
701   DEBUG(dbgs() << "    Replacing instructions:\n    ");
702   DEBUG(I->print(dbgs()));
703   DEBUG(dbgs() << "    ");
704   DEBUG(Update->print(dbgs()));
705   DEBUG(dbgs() << "  with instruction:\n    ");
706   DEBUG(((MachineInstr *)MIB)->print(dbgs()));
707   DEBUG(dbgs() << "\n");
708
709   // Erase the old instructions for the block.
710   I->eraseFromParent();
711   Update->eraseFromParent();
712
713   return NextI;
714 }
715
716 MachineBasicBlock::iterator AArch64LoadStoreOpt::mergePostIdxUpdateInsn(
717     MachineBasicBlock::iterator I, MachineBasicBlock::iterator Update) {
718   assert((Update->getOpcode() == AArch64::ADDXri ||
719           Update->getOpcode() == AArch64::SUBXri) &&
720          "Unexpected base register update instruction to merge!");
721   MachineBasicBlock::iterator NextI = I;
722   // Return the instruction following the merged instruction, which is
723   // the instruction following our unmerged load. Unless that's the add/sub
724   // instruction we're merging, in which case it's the one after that.
725   if (++NextI == Update)
726     ++NextI;
727
728   int Value = Update->getOperand(2).getImm();
729   assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
730          "Can't merge 1 << 12 offset into post-indexed load / store");
731   if (Update->getOpcode() == AArch64::SUBXri)
732     Value = -Value;
733
734   unsigned NewOpc = getPostIndexedOpcode(I->getOpcode());
735   MachineInstrBuilder MIB =
736       BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
737           .addOperand(Update->getOperand(0))
738           .addOperand(I->getOperand(0))
739           .addOperand(I->getOperand(1))
740           .addImm(Value);
741   (void)MIB;
742
743   DEBUG(dbgs() << "Creating post-indexed load/store.");
744   DEBUG(dbgs() << "    Replacing instructions:\n    ");
745   DEBUG(I->print(dbgs()));
746   DEBUG(dbgs() << "    ");
747   DEBUG(Update->print(dbgs()));
748   DEBUG(dbgs() << "  with instruction:\n    ");
749   DEBUG(((MachineInstr *)MIB)->print(dbgs()));
750   DEBUG(dbgs() << "\n");
751
752   // Erase the old instructions for the block.
753   I->eraseFromParent();
754   Update->eraseFromParent();
755
756   return NextI;
757 }
758
759 static bool isMatchingUpdateInsn(MachineInstr *MI, unsigned BaseReg,
760                                  int Offset) {
761   switch (MI->getOpcode()) {
762   default:
763     break;
764   case AArch64::SUBXri:
765     // Negate the offset for a SUB instruction.
766     Offset *= -1;
767   // FALLTHROUGH
768   case AArch64::ADDXri:
769     // Make sure it's a vanilla immediate operand, not a relocation or
770     // anything else we can't handle.
771     if (!MI->getOperand(2).isImm())
772       break;
773     // Watch out for 1 << 12 shifted value.
774     if (AArch64_AM::getShiftValue(MI->getOperand(3).getImm()))
775       break;
776     // If the instruction has the base register as source and dest and the
777     // immediate will fit in a signed 9-bit integer, then we have a match.
778     if (MI->getOperand(0).getReg() == BaseReg &&
779         MI->getOperand(1).getReg() == BaseReg &&
780         MI->getOperand(2).getImm() <= 255 &&
781         MI->getOperand(2).getImm() >= -256) {
782       // If we have a non-zero Offset, we check that it matches the amount
783       // we're adding to the register.
784       if (!Offset || Offset == MI->getOperand(2).getImm())
785         return true;
786     }
787     break;
788   }
789   return false;
790 }
791
792 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
793     MachineBasicBlock::iterator I, unsigned Limit, int Value) {
794   MachineBasicBlock::iterator E = I->getParent()->end();
795   MachineInstr *MemMI = I;
796   MachineBasicBlock::iterator MBBI = I;
797   const MachineFunction &MF = *MemMI->getParent()->getParent();
798
799   unsigned DestReg = MemMI->getOperand(0).getReg();
800   unsigned BaseReg = MemMI->getOperand(1).getReg();
801   int Offset = MemMI->getOperand(2).getImm() *
802                TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
803
804   // If the base register overlaps the destination register, we can't
805   // merge the update.
806   if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
807     return E;
808
809   // Scan forward looking for post-index opportunities.
810   // Updating instructions can't be formed if the memory insn already
811   // has an offset other than the value we're looking for.
812   if (Offset != Value)
813     return E;
814
815   // Track which registers have been modified and used between the first insn
816   // (inclusive) and the second insn.
817   BitVector ModifiedRegs, UsedRegs;
818   ModifiedRegs.resize(TRI->getNumRegs());
819   UsedRegs.resize(TRI->getNumRegs());
820   ++MBBI;
821   for (unsigned Count = 0; MBBI != E; ++MBBI) {
822     MachineInstr *MI = MBBI;
823     // Skip DBG_VALUE instructions. Otherwise debug info can affect the
824     // optimization by changing how far we scan.
825     if (MI->isDebugValue())
826       continue;
827
828     // Now that we know this is a real instruction, count it.
829     ++Count;
830
831     // If we found a match, return it.
832     if (isMatchingUpdateInsn(MI, BaseReg, Value))
833       return MBBI;
834
835     // Update the status of what the instruction clobbered and used.
836     trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
837
838     // Otherwise, if the base register is used or modified, we have no match, so
839     // return early.
840     if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
841       return E;
842   }
843   return E;
844 }
845
846 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
847     MachineBasicBlock::iterator I, unsigned Limit) {
848   MachineBasicBlock::iterator B = I->getParent()->begin();
849   MachineBasicBlock::iterator E = I->getParent()->end();
850   MachineInstr *MemMI = I;
851   MachineBasicBlock::iterator MBBI = I;
852   const MachineFunction &MF = *MemMI->getParent()->getParent();
853
854   unsigned DestReg = MemMI->getOperand(0).getReg();
855   unsigned BaseReg = MemMI->getOperand(1).getReg();
856   int Offset = MemMI->getOperand(2).getImm();
857   unsigned RegSize = TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
858
859   // If the load/store is the first instruction in the block, there's obviously
860   // not any matching update. Ditto if the memory offset isn't zero.
861   if (MBBI == B || Offset != 0)
862     return E;
863   // If the base register overlaps the destination register, we can't
864   // merge the update.
865   if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
866     return E;
867
868   // Track which registers have been modified and used between the first insn
869   // (inclusive) and the second insn.
870   BitVector ModifiedRegs, UsedRegs;
871   ModifiedRegs.resize(TRI->getNumRegs());
872   UsedRegs.resize(TRI->getNumRegs());
873   --MBBI;
874   for (unsigned Count = 0; MBBI != B; --MBBI) {
875     MachineInstr *MI = MBBI;
876     // Skip DBG_VALUE instructions. Otherwise debug info can affect the
877     // optimization by changing how far we scan.
878     if (MI->isDebugValue())
879       continue;
880
881     // Now that we know this is a real instruction, count it.
882     ++Count;
883
884     // If we found a match, return it.
885     if (isMatchingUpdateInsn(MI, BaseReg, RegSize))
886       return MBBI;
887
888     // Update the status of what the instruction clobbered and used.
889     trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
890
891     // Otherwise, if the base register is used or modified, we have no match, so
892     // return early.
893     if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
894       return E;
895   }
896   return E;
897 }
898
899 bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB) {
900   bool Modified = false;
901   // Two tranformations to do here:
902   // 1) Find loads and stores that can be merged into a single load or store
903   //    pair instruction.
904   //      e.g.,
905   //        ldr x0, [x2]
906   //        ldr x1, [x2, #8]
907   //        ; becomes
908   //        ldp x0, x1, [x2]
909   // 2) Find base register updates that can be merged into the load or store
910   //    as a base-reg writeback.
911   //      e.g.,
912   //        ldr x0, [x2]
913   //        add x2, x2, #4
914   //        ; becomes
915   //        ldr x0, [x2], #4
916
917   for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
918        MBBI != E;) {
919     MachineInstr *MI = MBBI;
920     switch (MI->getOpcode()) {
921     default:
922       // Just move on to the next instruction.
923       ++MBBI;
924       break;
925     case AArch64::STRSui:
926     case AArch64::STRDui:
927     case AArch64::STRQui:
928     case AArch64::STRXui:
929     case AArch64::STRWui:
930     case AArch64::LDRSui:
931     case AArch64::LDRDui:
932     case AArch64::LDRQui:
933     case AArch64::LDRXui:
934     case AArch64::LDRWui:
935     case AArch64::LDRSWui:
936     // do the unscaled versions as well
937     case AArch64::STURSi:
938     case AArch64::STURDi:
939     case AArch64::STURQi:
940     case AArch64::STURWi:
941     case AArch64::STURXi:
942     case AArch64::LDURSi:
943     case AArch64::LDURDi:
944     case AArch64::LDURQi:
945     case AArch64::LDURWi:
946     case AArch64::LDURXi:
947     case AArch64::LDURSWi: {
948       // If this is a volatile load/store, don't mess with it.
949       if (MI->hasOrderedMemoryRef()) {
950         ++MBBI;
951         break;
952       }
953       // Make sure this is a reg+imm (as opposed to an address reloc).
954       if (!MI->getOperand(2).isImm()) {
955         ++MBBI;
956         break;
957       }
958       // Check if this load/store has a hint to avoid pair formation.
959       // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
960       if (TII->isLdStPairSuppressed(MI)) {
961         ++MBBI;
962         break;
963       }
964       // Look ahead up to ScanLimit instructions for a pairable instruction.
965       LdStPairFlags Flags;
966       MachineBasicBlock::iterator Paired =
967           findMatchingInsn(MBBI, Flags, ScanLimit);
968       if (Paired != E) {
969         // Merge the loads into a pair. Keeping the iterator straight is a
970         // pain, so we let the merge routine tell us what the next instruction
971         // is after it's done mucking about.
972         MBBI = mergePairedInsns(MBBI, Paired, Flags);
973
974         Modified = true;
975         ++NumPairCreated;
976         if (isUnscaledLdst(MI->getOpcode()))
977           ++NumUnscaledPairCreated;
978         break;
979       }
980       ++MBBI;
981       break;
982     }
983       // FIXME: Do the other instructions.
984     }
985   }
986
987   for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
988        MBBI != E;) {
989     MachineInstr *MI = MBBI;
990     // Do update merging. It's simpler to keep this separate from the above
991     // switch, though not strictly necessary.
992     unsigned Opc = MI->getOpcode();
993     switch (Opc) {
994     default:
995       // Just move on to the next instruction.
996       ++MBBI;
997       break;
998     case AArch64::STRSui:
999     case AArch64::STRDui:
1000     case AArch64::STRQui:
1001     case AArch64::STRXui:
1002     case AArch64::STRWui:
1003     case AArch64::LDRSui:
1004     case AArch64::LDRDui:
1005     case AArch64::LDRQui:
1006     case AArch64::LDRXui:
1007     case AArch64::LDRWui:
1008     // do the unscaled versions as well
1009     case AArch64::STURSi:
1010     case AArch64::STURDi:
1011     case AArch64::STURQi:
1012     case AArch64::STURWi:
1013     case AArch64::STURXi:
1014     case AArch64::LDURSi:
1015     case AArch64::LDURDi:
1016     case AArch64::LDURQi:
1017     case AArch64::LDURWi:
1018     case AArch64::LDURXi: {
1019       // Make sure this is a reg+imm (as opposed to an address reloc).
1020       if (!MI->getOperand(2).isImm()) {
1021         ++MBBI;
1022         break;
1023       }
1024       // Look ahead up to ScanLimit instructions for a mergable instruction.
1025       MachineBasicBlock::iterator Update =
1026           findMatchingUpdateInsnForward(MBBI, ScanLimit, 0);
1027       if (Update != E) {
1028         // Merge the update into the ld/st.
1029         MBBI = mergePostIdxUpdateInsn(MBBI, Update);
1030         Modified = true;
1031         ++NumPostFolded;
1032         break;
1033       }
1034       // Don't know how to handle pre/post-index versions, so move to the next
1035       // instruction.
1036       if (isUnscaledLdst(Opc)) {
1037         ++MBBI;
1038         break;
1039       }
1040
1041       // Look back to try to find a pre-index instruction. For example,
1042       // add x0, x0, #8
1043       // ldr x1, [x0]
1044       //   merged into:
1045       // ldr x1, [x0, #8]!
1046       Update = findMatchingUpdateInsnBackward(MBBI, ScanLimit);
1047       if (Update != E) {
1048         // Merge the update into the ld/st.
1049         MBBI = mergePreIdxUpdateInsn(MBBI, Update);
1050         Modified = true;
1051         ++NumPreFolded;
1052         break;
1053       }
1054
1055       // Look forward to try to find a post-index instruction. For example,
1056       // ldr x1, [x0, #64]
1057       // add x0, x0, #64
1058       //   merged into:
1059       // ldr x1, [x0, #64]!
1060
1061       // The immediate in the load/store is scaled by the size of the register
1062       // being loaded. The immediate in the add we're looking for,
1063       // however, is not, so adjust here.
1064       int Value = MI->getOperand(2).getImm() *
1065                   TII->getRegClass(MI->getDesc(), 0, TRI, *(MBB.getParent()))
1066                       ->getSize();
1067       Update = findMatchingUpdateInsnForward(MBBI, ScanLimit, Value);
1068       if (Update != E) {
1069         // Merge the update into the ld/st.
1070         MBBI = mergePreIdxUpdateInsn(MBBI, Update);
1071         Modified = true;
1072         ++NumPreFolded;
1073         break;
1074       }
1075
1076       // Nothing found. Just move to the next instruction.
1077       ++MBBI;
1078       break;
1079     }
1080       // FIXME: Do the other instructions.
1081     }
1082   }
1083
1084   return Modified;
1085 }
1086
1087 bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
1088   TII = static_cast<const AArch64InstrInfo *>(Fn.getSubtarget().getInstrInfo());
1089   TRI = Fn.getSubtarget().getRegisterInfo();
1090
1091   bool Modified = false;
1092   for (auto &MBB : Fn)
1093     Modified |= optimizeBlock(MBB);
1094
1095   return Modified;
1096 }
1097
1098 // FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
1099 // loads and stores near one another?
1100
1101 /// createAArch64LoadStoreOptimizationPass - returns an instance of the
1102 /// load / store optimization pass.
1103 FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
1104   return new AArch64LoadStoreOpt();
1105 }