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