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