1 //===- AArch64LoadStoreOptimizer.cpp - AArch64 load/store opt. pass -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains a pass that performs load / store related peephole
10 // optimizations. This pass should be run after register allocation.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "AArch64InstrInfo.h"
15 #include "AArch64Subtarget.h"
16 #include "MCTargetDesc/AArch64AddressingModes.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/iterator_range.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineOperand.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/TargetRegisterInfo.h"
31 #include "llvm/IR/DebugLoc.h"
32 #include "llvm/MC/MCRegisterInfo.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/DebugCounter.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include <cassert>
40 #include <cstdint>
41 #include <functional>
42 #include <iterator>
43 #include <limits>
44 
45 using namespace llvm;
46 
47 #define DEBUG_TYPE "aarch64-ldst-opt"
48 
49 STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
50 STATISTIC(NumPostFolded, "Number of post-index updates folded");
51 STATISTIC(NumPreFolded, "Number of pre-index updates folded");
52 STATISTIC(NumUnscaledPairCreated,
53           "Number of load/store from unscaled generated");
54 STATISTIC(NumZeroStoresPromoted, "Number of narrow zero stores promoted");
55 STATISTIC(NumLoadsFromStoresPromoted, "Number of loads from stores promoted");
56 
57 DEBUG_COUNTER(RegRenamingCounter, DEBUG_TYPE "-reg-renaming",
58               "Controls which pairs are considered for renaming");
59 
60 // The LdStLimit limits how far we search for load/store pairs.
61 static cl::opt<unsigned> LdStLimit("aarch64-load-store-scan-limit",
62                                    cl::init(20), cl::Hidden);
63 
64 // The UpdateLimit limits how far we search for update instructions when we form
65 // pre-/post-index instructions.
66 static cl::opt<unsigned> UpdateLimit("aarch64-update-scan-limit", cl::init(100),
67                                      cl::Hidden);
68 
69 #define AARCH64_LOAD_STORE_OPT_NAME "AArch64 load / store optimization pass"
70 
71 namespace {
72 
73 using LdStPairFlags = struct LdStPairFlags {
74   // If a matching instruction is found, MergeForward is set to true if the
75   // merge is to remove the first instruction and replace the second with
76   // a pair-wise insn, and false if the reverse is true.
77   bool MergeForward = false;
78 
79   // SExtIdx gives the index of the result of the load pair that must be
80   // extended. The value of SExtIdx assumes that the paired load produces the
81   // value in this order: (I, returned iterator), i.e., -1 means no value has
82   // to be extended, 0 means I, and 1 means the returned iterator.
83   int SExtIdx = -1;
84 
85   // If not none, RenameReg can be used to rename the result register of the
86   // first store in a pair. Currently this only works when merging stores
87   // forward.
88   Optional<MCPhysReg> RenameReg = None;
89 
90   LdStPairFlags() = default;
91 
92   void setMergeForward(bool V = true) { MergeForward = V; }
93   bool getMergeForward() const { return MergeForward; }
94 
95   void setSExtIdx(int V) { SExtIdx = V; }
96   int getSExtIdx() const { return SExtIdx; }
97 
98   void setRenameReg(MCPhysReg R) { RenameReg = R; }
99   void clearRenameReg() { RenameReg = None; }
100   Optional<MCPhysReg> getRenameReg() const { return RenameReg; }
101 };
102 
103 struct AArch64LoadStoreOpt : public MachineFunctionPass {
104   static char ID;
105 
106   AArch64LoadStoreOpt() : MachineFunctionPass(ID) {
107     initializeAArch64LoadStoreOptPass(*PassRegistry::getPassRegistry());
108   }
109 
110   AliasAnalysis *AA;
111   const AArch64InstrInfo *TII;
112   const TargetRegisterInfo *TRI;
113   const AArch64Subtarget *Subtarget;
114 
115   // Track which register units have been modified and used.
116   LiveRegUnits ModifiedRegUnits, UsedRegUnits;
117   LiveRegUnits DefinedInBB;
118 
119   void getAnalysisUsage(AnalysisUsage &AU) const override {
120     AU.addRequired<AAResultsWrapperPass>();
121     MachineFunctionPass::getAnalysisUsage(AU);
122   }
123 
124   // Scan the instructions looking for a load/store that can be combined
125   // with the current instruction into a load/store pair.
126   // Return the matching instruction if one is found, else MBB->end().
127   MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
128                                                LdStPairFlags &Flags,
129                                                unsigned Limit,
130                                                bool FindNarrowMerge);
131 
132   // Scan the instructions looking for a store that writes to the address from
133   // which the current load instruction reads. Return true if one is found.
134   bool findMatchingStore(MachineBasicBlock::iterator I, unsigned Limit,
135                          MachineBasicBlock::iterator &StoreI);
136 
137   // Merge the two instructions indicated into a wider narrow store instruction.
138   MachineBasicBlock::iterator
139   mergeNarrowZeroStores(MachineBasicBlock::iterator I,
140                         MachineBasicBlock::iterator MergeMI,
141                         const LdStPairFlags &Flags);
142 
143   // Merge the two instructions indicated into a single pair-wise instruction.
144   MachineBasicBlock::iterator
145   mergePairedInsns(MachineBasicBlock::iterator I,
146                    MachineBasicBlock::iterator Paired,
147                    const LdStPairFlags &Flags);
148 
149   // Promote the load that reads directly from the address stored to.
150   MachineBasicBlock::iterator
151   promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
152                        MachineBasicBlock::iterator StoreI);
153 
154   // Scan the instruction list to find a base register update that can
155   // be combined with the current instruction (a load or store) using
156   // pre or post indexed addressing with writeback. Scan forwards.
157   MachineBasicBlock::iterator
158   findMatchingUpdateInsnForward(MachineBasicBlock::iterator I,
159                                 int UnscaledOffset, unsigned Limit);
160 
161   // Scan the instruction list to find a base register update that can
162   // be combined with the current instruction (a load or store) using
163   // pre or post indexed addressing with writeback. Scan backwards.
164   MachineBasicBlock::iterator
165   findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
166 
167   // Find an instruction that updates the base register of the ld/st
168   // instruction.
169   bool isMatchingUpdateInsn(MachineInstr &MemMI, MachineInstr &MI,
170                             unsigned BaseReg, int Offset);
171 
172   // Merge a pre- or post-index base register update into a ld/st instruction.
173   MachineBasicBlock::iterator
174   mergeUpdateInsn(MachineBasicBlock::iterator I,
175                   MachineBasicBlock::iterator Update, bool IsPreIdx);
176 
177   // Find and merge zero store instructions.
178   bool tryToMergeZeroStInst(MachineBasicBlock::iterator &MBBI);
179 
180   // Find and pair ldr/str instructions.
181   bool tryToPairLdStInst(MachineBasicBlock::iterator &MBBI);
182 
183   // Find and promote load instructions which read directly from store.
184   bool tryToPromoteLoadFromStore(MachineBasicBlock::iterator &MBBI);
185 
186   // Find and merge a base register updates before or after a ld/st instruction.
187   bool tryToMergeLdStUpdate(MachineBasicBlock::iterator &MBBI);
188 
189   bool optimizeBlock(MachineBasicBlock &MBB, bool EnableNarrowZeroStOpt);
190 
191   bool runOnMachineFunction(MachineFunction &Fn) override;
192 
193   MachineFunctionProperties getRequiredProperties() const override {
194     return MachineFunctionProperties().set(
195         MachineFunctionProperties::Property::NoVRegs);
196   }
197 
198   StringRef getPassName() const override { return AARCH64_LOAD_STORE_OPT_NAME; }
199 };
200 
201 char AArch64LoadStoreOpt::ID = 0;
202 
203 } // end anonymous namespace
204 
205 INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
206                 AARCH64_LOAD_STORE_OPT_NAME, false, false)
207 
208 static bool isNarrowStore(unsigned Opc) {
209   switch (Opc) {
210   default:
211     return false;
212   case AArch64::STRBBui:
213   case AArch64::STURBBi:
214   case AArch64::STRHHui:
215   case AArch64::STURHHi:
216     return true;
217   }
218 }
219 
220 // These instruction set memory tag and either keep memory contents unchanged or
221 // set it to zero, ignoring the address part of the source register.
222 static bool isTagStore(const MachineInstr &MI) {
223   switch (MI.getOpcode()) {
224   default:
225     return false;
226   case AArch64::STGOffset:
227   case AArch64::STZGOffset:
228   case AArch64::ST2GOffset:
229   case AArch64::STZ2GOffset:
230     return true;
231   }
232 }
233 
234 static unsigned getMatchingNonSExtOpcode(unsigned Opc,
235                                          bool *IsValidLdStrOpc = nullptr) {
236   if (IsValidLdStrOpc)
237     *IsValidLdStrOpc = true;
238   switch (Opc) {
239   default:
240     if (IsValidLdStrOpc)
241       *IsValidLdStrOpc = false;
242     return std::numeric_limits<unsigned>::max();
243   case AArch64::STRDui:
244   case AArch64::STURDi:
245   case AArch64::STRQui:
246   case AArch64::STURQi:
247   case AArch64::STRBBui:
248   case AArch64::STURBBi:
249   case AArch64::STRHHui:
250   case AArch64::STURHHi:
251   case AArch64::STRWui:
252   case AArch64::STURWi:
253   case AArch64::STRXui:
254   case AArch64::STURXi:
255   case AArch64::LDRDui:
256   case AArch64::LDURDi:
257   case AArch64::LDRQui:
258   case AArch64::LDURQi:
259   case AArch64::LDRWui:
260   case AArch64::LDURWi:
261   case AArch64::LDRXui:
262   case AArch64::LDURXi:
263   case AArch64::STRSui:
264   case AArch64::STURSi:
265   case AArch64::LDRSui:
266   case AArch64::LDURSi:
267     return Opc;
268   case AArch64::LDRSWui:
269     return AArch64::LDRWui;
270   case AArch64::LDURSWi:
271     return AArch64::LDURWi;
272   }
273 }
274 
275 static unsigned getMatchingWideOpcode(unsigned Opc) {
276   switch (Opc) {
277   default:
278     llvm_unreachable("Opcode has no wide equivalent!");
279   case AArch64::STRBBui:
280     return AArch64::STRHHui;
281   case AArch64::STRHHui:
282     return AArch64::STRWui;
283   case AArch64::STURBBi:
284     return AArch64::STURHHi;
285   case AArch64::STURHHi:
286     return AArch64::STURWi;
287   case AArch64::STURWi:
288     return AArch64::STURXi;
289   case AArch64::STRWui:
290     return AArch64::STRXui;
291   }
292 }
293 
294 static unsigned getMatchingPairOpcode(unsigned Opc) {
295   switch (Opc) {
296   default:
297     llvm_unreachable("Opcode has no pairwise equivalent!");
298   case AArch64::STRSui:
299   case AArch64::STURSi:
300     return AArch64::STPSi;
301   case AArch64::STRDui:
302   case AArch64::STURDi:
303     return AArch64::STPDi;
304   case AArch64::STRQui:
305   case AArch64::STURQi:
306     return AArch64::STPQi;
307   case AArch64::STRWui:
308   case AArch64::STURWi:
309     return AArch64::STPWi;
310   case AArch64::STRXui:
311   case AArch64::STURXi:
312     return AArch64::STPXi;
313   case AArch64::LDRSui:
314   case AArch64::LDURSi:
315     return AArch64::LDPSi;
316   case AArch64::LDRDui:
317   case AArch64::LDURDi:
318     return AArch64::LDPDi;
319   case AArch64::LDRQui:
320   case AArch64::LDURQi:
321     return AArch64::LDPQi;
322   case AArch64::LDRWui:
323   case AArch64::LDURWi:
324     return AArch64::LDPWi;
325   case AArch64::LDRXui:
326   case AArch64::LDURXi:
327     return AArch64::LDPXi;
328   case AArch64::LDRSWui:
329   case AArch64::LDURSWi:
330     return AArch64::LDPSWi;
331   }
332 }
333 
334 static unsigned isMatchingStore(MachineInstr &LoadInst,
335                                 MachineInstr &StoreInst) {
336   unsigned LdOpc = LoadInst.getOpcode();
337   unsigned StOpc = StoreInst.getOpcode();
338   switch (LdOpc) {
339   default:
340     llvm_unreachable("Unsupported load instruction!");
341   case AArch64::LDRBBui:
342     return StOpc == AArch64::STRBBui || StOpc == AArch64::STRHHui ||
343            StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
344   case AArch64::LDURBBi:
345     return StOpc == AArch64::STURBBi || StOpc == AArch64::STURHHi ||
346            StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
347   case AArch64::LDRHHui:
348     return StOpc == AArch64::STRHHui || StOpc == AArch64::STRWui ||
349            StOpc == AArch64::STRXui;
350   case AArch64::LDURHHi:
351     return StOpc == AArch64::STURHHi || StOpc == AArch64::STURWi ||
352            StOpc == AArch64::STURXi;
353   case AArch64::LDRWui:
354     return StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
355   case AArch64::LDURWi:
356     return StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
357   case AArch64::LDRXui:
358     return StOpc == AArch64::STRXui;
359   case AArch64::LDURXi:
360     return StOpc == AArch64::STURXi;
361   }
362 }
363 
364 static unsigned getPreIndexedOpcode(unsigned Opc) {
365   // FIXME: We don't currently support creating pre-indexed loads/stores when
366   // the load or store is the unscaled version.  If we decide to perform such an
367   // optimization in the future the cases for the unscaled loads/stores will
368   // need to be added here.
369   switch (Opc) {
370   default:
371     llvm_unreachable("Opcode has no pre-indexed equivalent!");
372   case AArch64::STRSui:
373     return AArch64::STRSpre;
374   case AArch64::STRDui:
375     return AArch64::STRDpre;
376   case AArch64::STRQui:
377     return AArch64::STRQpre;
378   case AArch64::STRBBui:
379     return AArch64::STRBBpre;
380   case AArch64::STRHHui:
381     return AArch64::STRHHpre;
382   case AArch64::STRWui:
383     return AArch64::STRWpre;
384   case AArch64::STRXui:
385     return AArch64::STRXpre;
386   case AArch64::LDRSui:
387     return AArch64::LDRSpre;
388   case AArch64::LDRDui:
389     return AArch64::LDRDpre;
390   case AArch64::LDRQui:
391     return AArch64::LDRQpre;
392   case AArch64::LDRBBui:
393     return AArch64::LDRBBpre;
394   case AArch64::LDRHHui:
395     return AArch64::LDRHHpre;
396   case AArch64::LDRWui:
397     return AArch64::LDRWpre;
398   case AArch64::LDRXui:
399     return AArch64::LDRXpre;
400   case AArch64::LDRSWui:
401     return AArch64::LDRSWpre;
402   case AArch64::LDPSi:
403     return AArch64::LDPSpre;
404   case AArch64::LDPSWi:
405     return AArch64::LDPSWpre;
406   case AArch64::LDPDi:
407     return AArch64::LDPDpre;
408   case AArch64::LDPQi:
409     return AArch64::LDPQpre;
410   case AArch64::LDPWi:
411     return AArch64::LDPWpre;
412   case AArch64::LDPXi:
413     return AArch64::LDPXpre;
414   case AArch64::STPSi:
415     return AArch64::STPSpre;
416   case AArch64::STPDi:
417     return AArch64::STPDpre;
418   case AArch64::STPQi:
419     return AArch64::STPQpre;
420   case AArch64::STPWi:
421     return AArch64::STPWpre;
422   case AArch64::STPXi:
423     return AArch64::STPXpre;
424   case AArch64::STGOffset:
425     return AArch64::STGPreIndex;
426   case AArch64::STZGOffset:
427     return AArch64::STZGPreIndex;
428   case AArch64::ST2GOffset:
429     return AArch64::ST2GPreIndex;
430   case AArch64::STZ2GOffset:
431     return AArch64::STZ2GPreIndex;
432   case AArch64::STGPi:
433     return AArch64::STGPpre;
434   }
435 }
436 
437 static unsigned getPostIndexedOpcode(unsigned Opc) {
438   switch (Opc) {
439   default:
440     llvm_unreachable("Opcode has no post-indexed wise equivalent!");
441   case AArch64::STRSui:
442   case AArch64::STURSi:
443     return AArch64::STRSpost;
444   case AArch64::STRDui:
445   case AArch64::STURDi:
446     return AArch64::STRDpost;
447   case AArch64::STRQui:
448   case AArch64::STURQi:
449     return AArch64::STRQpost;
450   case AArch64::STRBBui:
451     return AArch64::STRBBpost;
452   case AArch64::STRHHui:
453     return AArch64::STRHHpost;
454   case AArch64::STRWui:
455   case AArch64::STURWi:
456     return AArch64::STRWpost;
457   case AArch64::STRXui:
458   case AArch64::STURXi:
459     return AArch64::STRXpost;
460   case AArch64::LDRSui:
461   case AArch64::LDURSi:
462     return AArch64::LDRSpost;
463   case AArch64::LDRDui:
464   case AArch64::LDURDi:
465     return AArch64::LDRDpost;
466   case AArch64::LDRQui:
467   case AArch64::LDURQi:
468     return AArch64::LDRQpost;
469   case AArch64::LDRBBui:
470     return AArch64::LDRBBpost;
471   case AArch64::LDRHHui:
472     return AArch64::LDRHHpost;
473   case AArch64::LDRWui:
474   case AArch64::LDURWi:
475     return AArch64::LDRWpost;
476   case AArch64::LDRXui:
477   case AArch64::LDURXi:
478     return AArch64::LDRXpost;
479   case AArch64::LDRSWui:
480     return AArch64::LDRSWpost;
481   case AArch64::LDPSi:
482     return AArch64::LDPSpost;
483   case AArch64::LDPSWi:
484     return AArch64::LDPSWpost;
485   case AArch64::LDPDi:
486     return AArch64::LDPDpost;
487   case AArch64::LDPQi:
488     return AArch64::LDPQpost;
489   case AArch64::LDPWi:
490     return AArch64::LDPWpost;
491   case AArch64::LDPXi:
492     return AArch64::LDPXpost;
493   case AArch64::STPSi:
494     return AArch64::STPSpost;
495   case AArch64::STPDi:
496     return AArch64::STPDpost;
497   case AArch64::STPQi:
498     return AArch64::STPQpost;
499   case AArch64::STPWi:
500     return AArch64::STPWpost;
501   case AArch64::STPXi:
502     return AArch64::STPXpost;
503   case AArch64::STGOffset:
504     return AArch64::STGPostIndex;
505   case AArch64::STZGOffset:
506     return AArch64::STZGPostIndex;
507   case AArch64::ST2GOffset:
508     return AArch64::ST2GPostIndex;
509   case AArch64::STZ2GOffset:
510     return AArch64::STZ2GPostIndex;
511   case AArch64::STGPi:
512     return AArch64::STGPpost;
513   }
514 }
515 
516 static bool isPairedLdSt(const MachineInstr &MI) {
517   switch (MI.getOpcode()) {
518   default:
519     return false;
520   case AArch64::LDPSi:
521   case AArch64::LDPSWi:
522   case AArch64::LDPDi:
523   case AArch64::LDPQi:
524   case AArch64::LDPWi:
525   case AArch64::LDPXi:
526   case AArch64::STPSi:
527   case AArch64::STPDi:
528   case AArch64::STPQi:
529   case AArch64::STPWi:
530   case AArch64::STPXi:
531   case AArch64::STGPi:
532     return true;
533   }
534 }
535 
536 // Returns the scale and offset range of pre/post indexed variants of MI.
537 static void getPrePostIndexedMemOpInfo(const MachineInstr &MI, int &Scale,
538                                        int &MinOffset, int &MaxOffset) {
539   bool IsPaired = isPairedLdSt(MI);
540   bool IsTagStore = isTagStore(MI);
541   // ST*G and all paired ldst have the same scale in pre/post-indexed variants
542   // as in the "unsigned offset" variant.
543   // All other pre/post indexed ldst instructions are unscaled.
544   Scale = (IsTagStore || IsPaired) ? AArch64InstrInfo::getMemScale(MI) : 1;
545 
546   if (IsPaired) {
547     MinOffset = -64;
548     MaxOffset = 63;
549   } else {
550     MinOffset = -256;
551     MaxOffset = 255;
552   }
553 }
554 
555 static MachineOperand &getLdStRegOp(MachineInstr &MI,
556                                     unsigned PairedRegOp = 0) {
557   assert(PairedRegOp < 2 && "Unexpected register operand idx.");
558   unsigned Idx = isPairedLdSt(MI) ? PairedRegOp : 0;
559   return MI.getOperand(Idx);
560 }
561 
562 static const MachineOperand &getLdStBaseOp(const MachineInstr &MI) {
563   unsigned Idx = isPairedLdSt(MI) ? 2 : 1;
564   return MI.getOperand(Idx);
565 }
566 
567 static const MachineOperand &getLdStOffsetOp(const MachineInstr &MI) {
568   unsigned Idx = isPairedLdSt(MI) ? 3 : 2;
569   return MI.getOperand(Idx);
570 }
571 
572 static bool isLdOffsetInRangeOfSt(MachineInstr &LoadInst,
573                                   MachineInstr &StoreInst,
574                                   const AArch64InstrInfo *TII) {
575   assert(isMatchingStore(LoadInst, StoreInst) && "Expect only matched ld/st.");
576   int LoadSize = TII->getMemScale(LoadInst);
577   int StoreSize = TII->getMemScale(StoreInst);
578   int UnscaledStOffset = TII->isUnscaledLdSt(StoreInst)
579                              ? getLdStOffsetOp(StoreInst).getImm()
580                              : getLdStOffsetOp(StoreInst).getImm() * StoreSize;
581   int UnscaledLdOffset = TII->isUnscaledLdSt(LoadInst)
582                              ? getLdStOffsetOp(LoadInst).getImm()
583                              : getLdStOffsetOp(LoadInst).getImm() * LoadSize;
584   return (UnscaledStOffset <= UnscaledLdOffset) &&
585          (UnscaledLdOffset + LoadSize <= (UnscaledStOffset + StoreSize));
586 }
587 
588 static bool isPromotableZeroStoreInst(MachineInstr &MI) {
589   unsigned Opc = MI.getOpcode();
590   return (Opc == AArch64::STRWui || Opc == AArch64::STURWi ||
591           isNarrowStore(Opc)) &&
592          getLdStRegOp(MI).getReg() == AArch64::WZR;
593 }
594 
595 static bool isPromotableLoadFromStore(MachineInstr &MI) {
596   switch (MI.getOpcode()) {
597   default:
598     return false;
599   // Scaled instructions.
600   case AArch64::LDRBBui:
601   case AArch64::LDRHHui:
602   case AArch64::LDRWui:
603   case AArch64::LDRXui:
604   // Unscaled instructions.
605   case AArch64::LDURBBi:
606   case AArch64::LDURHHi:
607   case AArch64::LDURWi:
608   case AArch64::LDURXi:
609     return true;
610   }
611 }
612 
613 static bool isMergeableLdStUpdate(MachineInstr &MI) {
614   unsigned Opc = MI.getOpcode();
615   switch (Opc) {
616   default:
617     return false;
618   // Scaled instructions.
619   case AArch64::STRSui:
620   case AArch64::STRDui:
621   case AArch64::STRQui:
622   case AArch64::STRXui:
623   case AArch64::STRWui:
624   case AArch64::STRHHui:
625   case AArch64::STRBBui:
626   case AArch64::LDRSui:
627   case AArch64::LDRDui:
628   case AArch64::LDRQui:
629   case AArch64::LDRXui:
630   case AArch64::LDRWui:
631   case AArch64::LDRHHui:
632   case AArch64::LDRBBui:
633   case AArch64::STGOffset:
634   case AArch64::STZGOffset:
635   case AArch64::ST2GOffset:
636   case AArch64::STZ2GOffset:
637   case AArch64::STGPi:
638   // Unscaled instructions.
639   case AArch64::STURSi:
640   case AArch64::STURDi:
641   case AArch64::STURQi:
642   case AArch64::STURWi:
643   case AArch64::STURXi:
644   case AArch64::LDURSi:
645   case AArch64::LDURDi:
646   case AArch64::LDURQi:
647   case AArch64::LDURWi:
648   case AArch64::LDURXi:
649   // Paired instructions.
650   case AArch64::LDPSi:
651   case AArch64::LDPSWi:
652   case AArch64::LDPDi:
653   case AArch64::LDPQi:
654   case AArch64::LDPWi:
655   case AArch64::LDPXi:
656   case AArch64::STPSi:
657   case AArch64::STPDi:
658   case AArch64::STPQi:
659   case AArch64::STPWi:
660   case AArch64::STPXi:
661     // Make sure this is a reg+imm (as opposed to an address reloc).
662     if (!getLdStOffsetOp(MI).isImm())
663       return false;
664 
665     return true;
666   }
667 }
668 
669 MachineBasicBlock::iterator
670 AArch64LoadStoreOpt::mergeNarrowZeroStores(MachineBasicBlock::iterator I,
671                                            MachineBasicBlock::iterator MergeMI,
672                                            const LdStPairFlags &Flags) {
673   assert(isPromotableZeroStoreInst(*I) && isPromotableZeroStoreInst(*MergeMI) &&
674          "Expected promotable zero stores.");
675 
676   MachineBasicBlock::iterator NextI = I;
677   ++NextI;
678   // If NextI is the second of the two instructions to be merged, we need
679   // to skip one further. Either way we merge will invalidate the iterator,
680   // and we don't need to scan the new instruction, as it's a pairwise
681   // instruction, which we're not considering for further action anyway.
682   if (NextI == MergeMI)
683     ++NextI;
684 
685   unsigned Opc = I->getOpcode();
686   bool IsScaled = !TII->isUnscaledLdSt(Opc);
687   int OffsetStride = IsScaled ? 1 : TII->getMemScale(*I);
688 
689   bool MergeForward = Flags.getMergeForward();
690   // Insert our new paired instruction after whichever of the paired
691   // instructions MergeForward indicates.
692   MachineBasicBlock::iterator InsertionPoint = MergeForward ? MergeMI : I;
693   // Also based on MergeForward is from where we copy the base register operand
694   // so we get the flags compatible with the input code.
695   const MachineOperand &BaseRegOp =
696       MergeForward ? getLdStBaseOp(*MergeMI) : getLdStBaseOp(*I);
697 
698   // Which register is Rt and which is Rt2 depends on the offset order.
699   MachineInstr *RtMI;
700   if (getLdStOffsetOp(*I).getImm() ==
701       getLdStOffsetOp(*MergeMI).getImm() + OffsetStride)
702     RtMI = &*MergeMI;
703   else
704     RtMI = &*I;
705 
706   int OffsetImm = getLdStOffsetOp(*RtMI).getImm();
707   // Change the scaled offset from small to large type.
708   if (IsScaled) {
709     assert(((OffsetImm & 1) == 0) && "Unexpected offset to merge");
710     OffsetImm /= 2;
711   }
712 
713   // Construct the new instruction.
714   DebugLoc DL = I->getDebugLoc();
715   MachineBasicBlock *MBB = I->getParent();
716   MachineInstrBuilder MIB;
717   MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
718             .addReg(isNarrowStore(Opc) ? AArch64::WZR : AArch64::XZR)
719             .add(BaseRegOp)
720             .addImm(OffsetImm)
721             .cloneMergedMemRefs({&*I, &*MergeMI})
722             .setMIFlags(I->mergeFlagsWith(*MergeMI));
723   (void)MIB;
724 
725   LLVM_DEBUG(dbgs() << "Creating wider store. Replacing instructions:\n    ");
726   LLVM_DEBUG(I->print(dbgs()));
727   LLVM_DEBUG(dbgs() << "    ");
728   LLVM_DEBUG(MergeMI->print(dbgs()));
729   LLVM_DEBUG(dbgs() << "  with instruction:\n    ");
730   LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
731   LLVM_DEBUG(dbgs() << "\n");
732 
733   // Erase the old instructions.
734   I->eraseFromParent();
735   MergeMI->eraseFromParent();
736   return NextI;
737 }
738 
739 // Apply Fn to all instructions between MI and the beginning of the block, until
740 // a def for DefReg is reached. Returns true, iff Fn returns true for all
741 // visited instructions. Stop after visiting Limit iterations.
742 static bool forAllMIsUntilDef(MachineInstr &MI, MCPhysReg DefReg,
743                               const TargetRegisterInfo *TRI, unsigned Limit,
744                               std::function<bool(MachineInstr &, bool)> &Fn) {
745   auto MBB = MI.getParent();
746   for (MachineBasicBlock::reverse_iterator I = MI.getReverseIterator(),
747                                            E = MBB->rend();
748        I != E; I++) {
749     if (!Limit)
750       return false;
751     --Limit;
752 
753     bool isDef = any_of(I->operands(), [DefReg, TRI](MachineOperand &MOP) {
754       return MOP.isReg() && MOP.isDef() && !MOP.isDebug() && MOP.getReg() &&
755              TRI->regsOverlap(MOP.getReg(), DefReg);
756     });
757     if (!Fn(*I, isDef))
758       return false;
759     if (isDef)
760       break;
761   }
762   return true;
763 }
764 
765 static void updateDefinedRegisters(MachineInstr &MI, LiveRegUnits &Units,
766                                    const TargetRegisterInfo *TRI) {
767 
768   for (const MachineOperand &MOP : phys_regs_and_masks(MI))
769     if (MOP.isReg() && MOP.isKill())
770       Units.removeReg(MOP.getReg());
771 
772   for (const MachineOperand &MOP : phys_regs_and_masks(MI))
773     if (MOP.isReg() && !MOP.isKill())
774       Units.addReg(MOP.getReg());
775 }
776 
777 MachineBasicBlock::iterator
778 AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
779                                       MachineBasicBlock::iterator Paired,
780                                       const LdStPairFlags &Flags) {
781   MachineBasicBlock::iterator NextI = I;
782   ++NextI;
783   // If NextI is the second of the two instructions to be merged, we need
784   // to skip one further. Either way we merge will invalidate the iterator,
785   // and we don't need to scan the new instruction, as it's a pairwise
786   // instruction, which we're not considering for further action anyway.
787   if (NextI == Paired)
788     ++NextI;
789 
790   int SExtIdx = Flags.getSExtIdx();
791   unsigned Opc =
792       SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
793   bool IsUnscaled = TII->isUnscaledLdSt(Opc);
794   int OffsetStride = IsUnscaled ? TII->getMemScale(*I) : 1;
795 
796   bool MergeForward = Flags.getMergeForward();
797 
798   Optional<MCPhysReg> RenameReg = Flags.getRenameReg();
799   if (MergeForward && RenameReg) {
800     MCRegister RegToRename = getLdStRegOp(*I).getReg();
801     DefinedInBB.addReg(*RenameReg);
802 
803     // Return the sub/super register for RenameReg, matching the size of
804     // OriginalReg.
805     auto GetMatchingSubReg = [this,
806                               RenameReg](MCPhysReg OriginalReg) -> MCPhysReg {
807       for (MCPhysReg SubOrSuper : TRI->sub_and_superregs_inclusive(*RenameReg))
808         if (TRI->getMinimalPhysRegClass(OriginalReg) ==
809             TRI->getMinimalPhysRegClass(SubOrSuper))
810           return SubOrSuper;
811       llvm_unreachable("Should have found matching sub or super register!");
812     };
813 
814     std::function<bool(MachineInstr &, bool)> UpdateMIs =
815         [this, RegToRename, GetMatchingSubReg](MachineInstr &MI, bool IsDef) {
816           if (IsDef) {
817             bool SeenDef = false;
818             for (auto &MOP : MI.operands()) {
819               // Rename the first explicit definition and all implicit
820               // definitions matching RegToRename.
821               if (MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
822                   (!SeenDef || (MOP.isDef() && MOP.isImplicit())) &&
823                   TRI->regsOverlap(MOP.getReg(), RegToRename)) {
824                 assert((MOP.isImplicit() ||
825                         (MOP.isRenamable() && !MOP.isEarlyClobber())) &&
826                        "Need renamable operands");
827                 MOP.setReg(GetMatchingSubReg(MOP.getReg()));
828                 SeenDef = true;
829               }
830             }
831           } else {
832             for (auto &MOP : MI.operands()) {
833               if (MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
834                   TRI->regsOverlap(MOP.getReg(), RegToRename)) {
835                 assert((MOP.isImplicit() ||
836                         (MOP.isRenamable() && !MOP.isEarlyClobber())) &&
837                            "Need renamable operands");
838                 MOP.setReg(GetMatchingSubReg(MOP.getReg()));
839               }
840             }
841           }
842           LLVM_DEBUG(dbgs() << "Renamed " << MI << "\n");
843           return true;
844         };
845     forAllMIsUntilDef(*I, RegToRename, TRI, LdStLimit, UpdateMIs);
846 
847 #if !defined(NDEBUG)
848     // Make sure the register used for renaming is not used between the paired
849     // instructions. That would trash the content before the new paired
850     // instruction.
851     for (auto &MI :
852          iterator_range<MachineInstrBundleIterator<llvm::MachineInstr>>(
853              std::next(I), std::next(Paired)))
854       assert(all_of(MI.operands(),
855                     [this, &RenameReg](const MachineOperand &MOP) {
856                       return !MOP.isReg() || MOP.isDebug() || !MOP.getReg() ||
857                              !TRI->regsOverlap(MOP.getReg(), *RenameReg);
858                     }) &&
859              "Rename register used between paired instruction, trashing the "
860              "content");
861 #endif
862   }
863 
864   // Insert our new paired instruction after whichever of the paired
865   // instructions MergeForward indicates.
866   MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
867   // Also based on MergeForward is from where we copy the base register operand
868   // so we get the flags compatible with the input code.
869   const MachineOperand &BaseRegOp =
870       MergeForward ? getLdStBaseOp(*Paired) : getLdStBaseOp(*I);
871 
872   int Offset = getLdStOffsetOp(*I).getImm();
873   int PairedOffset = getLdStOffsetOp(*Paired).getImm();
874   bool PairedIsUnscaled = TII->isUnscaledLdSt(Paired->getOpcode());
875   if (IsUnscaled != PairedIsUnscaled) {
876     // We're trying to pair instructions that differ in how they are scaled.  If
877     // I is scaled then scale the offset of Paired accordingly.  Otherwise, do
878     // the opposite (i.e., make Paired's offset unscaled).
879     int MemSize = TII->getMemScale(*Paired);
880     if (PairedIsUnscaled) {
881       // If the unscaled offset isn't a multiple of the MemSize, we can't
882       // pair the operations together.
883       assert(!(PairedOffset % TII->getMemScale(*Paired)) &&
884              "Offset should be a multiple of the stride!");
885       PairedOffset /= MemSize;
886     } else {
887       PairedOffset *= MemSize;
888     }
889   }
890 
891   // Which register is Rt and which is Rt2 depends on the offset order.
892   MachineInstr *RtMI, *Rt2MI;
893   if (Offset == PairedOffset + OffsetStride) {
894     RtMI = &*Paired;
895     Rt2MI = &*I;
896     // Here we swapped the assumption made for SExtIdx.
897     // I.e., we turn ldp I, Paired into ldp Paired, I.
898     // Update the index accordingly.
899     if (SExtIdx != -1)
900       SExtIdx = (SExtIdx + 1) % 2;
901   } else {
902     RtMI = &*I;
903     Rt2MI = &*Paired;
904   }
905   int OffsetImm = getLdStOffsetOp(*RtMI).getImm();
906   // Scale the immediate offset, if necessary.
907   if (TII->isUnscaledLdSt(RtMI->getOpcode())) {
908     assert(!(OffsetImm % TII->getMemScale(*RtMI)) &&
909            "Unscaled offset cannot be scaled.");
910     OffsetImm /= TII->getMemScale(*RtMI);
911   }
912 
913   // Construct the new instruction.
914   MachineInstrBuilder MIB;
915   DebugLoc DL = I->getDebugLoc();
916   MachineBasicBlock *MBB = I->getParent();
917   MachineOperand RegOp0 = getLdStRegOp(*RtMI);
918   MachineOperand RegOp1 = getLdStRegOp(*Rt2MI);
919   // Kill flags may become invalid when moving stores for pairing.
920   if (RegOp0.isUse()) {
921     if (!MergeForward) {
922       // Clear kill flags on store if moving upwards. Example:
923       //   STRWui %w0, ...
924       //   USE %w1
925       //   STRWui kill %w1  ; need to clear kill flag when moving STRWui upwards
926       RegOp0.setIsKill(false);
927       RegOp1.setIsKill(false);
928     } else {
929       // Clear kill flags of the first stores register. Example:
930       //   STRWui %w1, ...
931       //   USE kill %w1   ; need to clear kill flag when moving STRWui downwards
932       //   STRW %w0
933       Register Reg = getLdStRegOp(*I).getReg();
934       for (MachineInstr &MI : make_range(std::next(I), Paired))
935         MI.clearRegisterKills(Reg, TRI);
936     }
937   }
938   MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingPairOpcode(Opc)))
939             .add(RegOp0)
940             .add(RegOp1)
941             .add(BaseRegOp)
942             .addImm(OffsetImm)
943             .cloneMergedMemRefs({&*I, &*Paired})
944             .setMIFlags(I->mergeFlagsWith(*Paired));
945 
946   (void)MIB;
947 
948   LLVM_DEBUG(
949       dbgs() << "Creating pair load/store. Replacing instructions:\n    ");
950   LLVM_DEBUG(I->print(dbgs()));
951   LLVM_DEBUG(dbgs() << "    ");
952   LLVM_DEBUG(Paired->print(dbgs()));
953   LLVM_DEBUG(dbgs() << "  with instruction:\n    ");
954   if (SExtIdx != -1) {
955     // Generate the sign extension for the proper result of the ldp.
956     // I.e., with X1, that would be:
957     // %w1 = KILL %w1, implicit-def %x1
958     // %x1 = SBFMXri killed %x1, 0, 31
959     MachineOperand &DstMO = MIB->getOperand(SExtIdx);
960     // Right now, DstMO has the extended register, since it comes from an
961     // extended opcode.
962     Register DstRegX = DstMO.getReg();
963     // Get the W variant of that register.
964     Register DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
965     // Update the result of LDP to use the W instead of the X variant.
966     DstMO.setReg(DstRegW);
967     LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
968     LLVM_DEBUG(dbgs() << "\n");
969     // Make the machine verifier happy by providing a definition for
970     // the X register.
971     // Insert this definition right after the generated LDP, i.e., before
972     // InsertionPoint.
973     MachineInstrBuilder MIBKill =
974         BuildMI(*MBB, InsertionPoint, DL, TII->get(TargetOpcode::KILL), DstRegW)
975             .addReg(DstRegW)
976             .addReg(DstRegX, RegState::Define);
977     MIBKill->getOperand(2).setImplicit();
978     // Create the sign extension.
979     MachineInstrBuilder MIBSXTW =
980         BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::SBFMXri), DstRegX)
981             .addReg(DstRegX)
982             .addImm(0)
983             .addImm(31);
984     (void)MIBSXTW;
985     LLVM_DEBUG(dbgs() << "  Extend operand:\n    ");
986     LLVM_DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
987   } else {
988     LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
989   }
990   LLVM_DEBUG(dbgs() << "\n");
991 
992   if (MergeForward)
993     for (const MachineOperand &MOP : phys_regs_and_masks(*I))
994       if (MOP.isReg() && MOP.isKill())
995         DefinedInBB.addReg(MOP.getReg());
996 
997   // Erase the old instructions.
998   I->eraseFromParent();
999   Paired->eraseFromParent();
1000 
1001   return NextI;
1002 }
1003 
1004 MachineBasicBlock::iterator
1005 AArch64LoadStoreOpt::promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
1006                                           MachineBasicBlock::iterator StoreI) {
1007   MachineBasicBlock::iterator NextI = LoadI;
1008   ++NextI;
1009 
1010   int LoadSize = TII->getMemScale(*LoadI);
1011   int StoreSize = TII->getMemScale(*StoreI);
1012   Register LdRt = getLdStRegOp(*LoadI).getReg();
1013   const MachineOperand &StMO = getLdStRegOp(*StoreI);
1014   Register StRt = getLdStRegOp(*StoreI).getReg();
1015   bool IsStoreXReg = TRI->getRegClass(AArch64::GPR64RegClassID)->contains(StRt);
1016 
1017   assert((IsStoreXReg ||
1018           TRI->getRegClass(AArch64::GPR32RegClassID)->contains(StRt)) &&
1019          "Unexpected RegClass");
1020 
1021   MachineInstr *BitExtMI;
1022   if (LoadSize == StoreSize && (LoadSize == 4 || LoadSize == 8)) {
1023     // Remove the load, if the destination register of the loads is the same
1024     // register for stored value.
1025     if (StRt == LdRt && LoadSize == 8) {
1026       for (MachineInstr &MI : make_range(StoreI->getIterator(),
1027                                          LoadI->getIterator())) {
1028         if (MI.killsRegister(StRt, TRI)) {
1029           MI.clearRegisterKills(StRt, TRI);
1030           break;
1031         }
1032       }
1033       LLVM_DEBUG(dbgs() << "Remove load instruction:\n    ");
1034       LLVM_DEBUG(LoadI->print(dbgs()));
1035       LLVM_DEBUG(dbgs() << "\n");
1036       LoadI->eraseFromParent();
1037       return NextI;
1038     }
1039     // Replace the load with a mov if the load and store are in the same size.
1040     BitExtMI =
1041         BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1042                 TII->get(IsStoreXReg ? AArch64::ORRXrs : AArch64::ORRWrs), LdRt)
1043             .addReg(IsStoreXReg ? AArch64::XZR : AArch64::WZR)
1044             .add(StMO)
1045             .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0))
1046             .setMIFlags(LoadI->getFlags());
1047   } else {
1048     // FIXME: Currently we disable this transformation in big-endian targets as
1049     // performance and correctness are verified only in little-endian.
1050     if (!Subtarget->isLittleEndian())
1051       return NextI;
1052     bool IsUnscaled = TII->isUnscaledLdSt(*LoadI);
1053     assert(IsUnscaled == TII->isUnscaledLdSt(*StoreI) &&
1054            "Unsupported ld/st match");
1055     assert(LoadSize <= StoreSize && "Invalid load size");
1056     int UnscaledLdOffset = IsUnscaled
1057                                ? getLdStOffsetOp(*LoadI).getImm()
1058                                : getLdStOffsetOp(*LoadI).getImm() * LoadSize;
1059     int UnscaledStOffset = IsUnscaled
1060                                ? getLdStOffsetOp(*StoreI).getImm()
1061                                : getLdStOffsetOp(*StoreI).getImm() * StoreSize;
1062     int Width = LoadSize * 8;
1063     unsigned DestReg =
1064         IsStoreXReg ? Register(TRI->getMatchingSuperReg(
1065                           LdRt, AArch64::sub_32, &AArch64::GPR64RegClass))
1066                     : LdRt;
1067 
1068     assert((UnscaledLdOffset >= UnscaledStOffset &&
1069             (UnscaledLdOffset + LoadSize) <= UnscaledStOffset + StoreSize) &&
1070            "Invalid offset");
1071 
1072     int Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
1073     int Imms = Immr + Width - 1;
1074     if (UnscaledLdOffset == UnscaledStOffset) {
1075       uint32_t AndMaskEncoded = ((IsStoreXReg ? 1 : 0) << 12) // N
1076                                 | ((Immr) << 6)               // immr
1077                                 | ((Imms) << 0)               // imms
1078           ;
1079 
1080       BitExtMI =
1081           BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1082                   TII->get(IsStoreXReg ? AArch64::ANDXri : AArch64::ANDWri),
1083                   DestReg)
1084               .add(StMO)
1085               .addImm(AndMaskEncoded)
1086               .setMIFlags(LoadI->getFlags());
1087     } else {
1088       BitExtMI =
1089           BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1090                   TII->get(IsStoreXReg ? AArch64::UBFMXri : AArch64::UBFMWri),
1091                   DestReg)
1092               .add(StMO)
1093               .addImm(Immr)
1094               .addImm(Imms)
1095               .setMIFlags(LoadI->getFlags());
1096     }
1097   }
1098 
1099   // Clear kill flags between store and load.
1100   for (MachineInstr &MI : make_range(StoreI->getIterator(),
1101                                      BitExtMI->getIterator()))
1102     if (MI.killsRegister(StRt, TRI)) {
1103       MI.clearRegisterKills(StRt, TRI);
1104       break;
1105     }
1106 
1107   LLVM_DEBUG(dbgs() << "Promoting load by replacing :\n    ");
1108   LLVM_DEBUG(StoreI->print(dbgs()));
1109   LLVM_DEBUG(dbgs() << "    ");
1110   LLVM_DEBUG(LoadI->print(dbgs()));
1111   LLVM_DEBUG(dbgs() << "  with instructions:\n    ");
1112   LLVM_DEBUG(StoreI->print(dbgs()));
1113   LLVM_DEBUG(dbgs() << "    ");
1114   LLVM_DEBUG((BitExtMI)->print(dbgs()));
1115   LLVM_DEBUG(dbgs() << "\n");
1116 
1117   // Erase the old instructions.
1118   LoadI->eraseFromParent();
1119   return NextI;
1120 }
1121 
1122 static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
1123   // Convert the byte-offset used by unscaled into an "element" offset used
1124   // by the scaled pair load/store instructions.
1125   if (IsUnscaled) {
1126     // If the byte-offset isn't a multiple of the stride, there's no point
1127     // trying to match it.
1128     if (Offset % OffsetStride)
1129       return false;
1130     Offset /= OffsetStride;
1131   }
1132   return Offset <= 63 && Offset >= -64;
1133 }
1134 
1135 // Do alignment, specialized to power of 2 and for signed ints,
1136 // avoiding having to do a C-style cast from uint_64t to int when
1137 // using alignTo from include/llvm/Support/MathExtras.h.
1138 // FIXME: Move this function to include/MathExtras.h?
1139 static int alignTo(int Num, int PowOf2) {
1140   return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
1141 }
1142 
1143 static bool mayAlias(MachineInstr &MIa, MachineInstr &MIb,
1144                      AliasAnalysis *AA) {
1145   // One of the instructions must modify memory.
1146   if (!MIa.mayStore() && !MIb.mayStore())
1147     return false;
1148 
1149   // Both instructions must be memory operations.
1150   if (!MIa.mayLoadOrStore() && !MIb.mayLoadOrStore())
1151     return false;
1152 
1153   return MIa.mayAlias(AA, MIb, /*UseTBAA*/false);
1154 }
1155 
1156 static bool mayAlias(MachineInstr &MIa,
1157                      SmallVectorImpl<MachineInstr *> &MemInsns,
1158                      AliasAnalysis *AA) {
1159   for (MachineInstr *MIb : MemInsns)
1160     if (mayAlias(MIa, *MIb, AA))
1161       return true;
1162 
1163   return false;
1164 }
1165 
1166 bool AArch64LoadStoreOpt::findMatchingStore(
1167     MachineBasicBlock::iterator I, unsigned Limit,
1168     MachineBasicBlock::iterator &StoreI) {
1169   MachineBasicBlock::iterator B = I->getParent()->begin();
1170   MachineBasicBlock::iterator MBBI = I;
1171   MachineInstr &LoadMI = *I;
1172   Register BaseReg = getLdStBaseOp(LoadMI).getReg();
1173 
1174   // If the load is the first instruction in the block, there's obviously
1175   // not any matching store.
1176   if (MBBI == B)
1177     return false;
1178 
1179   // Track which register units have been modified and used between the first
1180   // insn and the second insn.
1181   ModifiedRegUnits.clear();
1182   UsedRegUnits.clear();
1183 
1184   unsigned Count = 0;
1185   do {
1186     --MBBI;
1187     MachineInstr &MI = *MBBI;
1188 
1189     // Don't count transient instructions towards the search limit since there
1190     // may be different numbers of them if e.g. debug information is present.
1191     if (!MI.isTransient())
1192       ++Count;
1193 
1194     // If the load instruction reads directly from the address to which the
1195     // store instruction writes and the stored value is not modified, we can
1196     // promote the load. Since we do not handle stores with pre-/post-index,
1197     // it's unnecessary to check if BaseReg is modified by the store itself.
1198     if (MI.mayStore() && isMatchingStore(LoadMI, MI) &&
1199         BaseReg == getLdStBaseOp(MI).getReg() &&
1200         isLdOffsetInRangeOfSt(LoadMI, MI, TII) &&
1201         ModifiedRegUnits.available(getLdStRegOp(MI).getReg())) {
1202       StoreI = MBBI;
1203       return true;
1204     }
1205 
1206     if (MI.isCall())
1207       return false;
1208 
1209     // Update modified / uses register units.
1210     LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
1211 
1212     // Otherwise, if the base register is modified, we have no match, so
1213     // return early.
1214     if (!ModifiedRegUnits.available(BaseReg))
1215       return false;
1216 
1217     // If we encounter a store aliased with the load, return early.
1218     if (MI.mayStore() && mayAlias(LoadMI, MI, AA))
1219       return false;
1220   } while (MBBI != B && Count < Limit);
1221   return false;
1222 }
1223 
1224 // Returns true if FirstMI and MI are candidates for merging or pairing.
1225 // Otherwise, returns false.
1226 static bool areCandidatesToMergeOrPair(MachineInstr &FirstMI, MachineInstr &MI,
1227                                        LdStPairFlags &Flags,
1228                                        const AArch64InstrInfo *TII) {
1229   // If this is volatile or if pairing is suppressed, not a candidate.
1230   if (MI.hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
1231     return false;
1232 
1233   // We should have already checked FirstMI for pair suppression and volatility.
1234   assert(!FirstMI.hasOrderedMemoryRef() &&
1235          !TII->isLdStPairSuppressed(FirstMI) &&
1236          "FirstMI shouldn't get here if either of these checks are true.");
1237 
1238   unsigned OpcA = FirstMI.getOpcode();
1239   unsigned OpcB = MI.getOpcode();
1240 
1241   // Opcodes match: nothing more to check.
1242   if (OpcA == OpcB)
1243     return true;
1244 
1245   // Try to match a sign-extended load/store with a zero-extended load/store.
1246   bool IsValidLdStrOpc, PairIsValidLdStrOpc;
1247   unsigned NonSExtOpc = getMatchingNonSExtOpcode(OpcA, &IsValidLdStrOpc);
1248   assert(IsValidLdStrOpc &&
1249          "Given Opc should be a Load or Store with an immediate");
1250   // OpcA will be the first instruction in the pair.
1251   if (NonSExtOpc == getMatchingNonSExtOpcode(OpcB, &PairIsValidLdStrOpc)) {
1252     Flags.setSExtIdx(NonSExtOpc == (unsigned)OpcA ? 1 : 0);
1253     return true;
1254   }
1255 
1256   // If the second instruction isn't even a mergable/pairable load/store, bail
1257   // out.
1258   if (!PairIsValidLdStrOpc)
1259     return false;
1260 
1261   // FIXME: We don't support merging narrow stores with mixed scaled/unscaled
1262   // offsets.
1263   if (isNarrowStore(OpcA) || isNarrowStore(OpcB))
1264     return false;
1265 
1266   // Try to match an unscaled load/store with a scaled load/store.
1267   return TII->isUnscaledLdSt(OpcA) != TII->isUnscaledLdSt(OpcB) &&
1268          getMatchingPairOpcode(OpcA) == getMatchingPairOpcode(OpcB);
1269 
1270   // FIXME: Can we also match a mixed sext/zext unscaled/scaled pair?
1271 }
1272 
1273 static bool
1274 canRenameUpToDef(MachineInstr &FirstMI, LiveRegUnits &UsedInBetween,
1275                  SmallPtrSetImpl<const TargetRegisterClass *> &RequiredClasses,
1276                  const TargetRegisterInfo *TRI) {
1277   if (!FirstMI.mayStore())
1278     return false;
1279 
1280   // Check if we can find an unused register which we can use to rename
1281   // the register used by the first load/store.
1282   auto *RegClass = TRI->getMinimalPhysRegClass(getLdStRegOp(FirstMI).getReg());
1283   MachineFunction &MF = *FirstMI.getParent()->getParent();
1284   if (!RegClass || !MF.getRegInfo().tracksLiveness())
1285     return false;
1286 
1287   auto RegToRename = getLdStRegOp(FirstMI).getReg();
1288   // For now, we only rename if the store operand gets killed at the store.
1289   if (!getLdStRegOp(FirstMI).isKill() &&
1290       !any_of(FirstMI.operands(),
1291               [TRI, RegToRename](const MachineOperand &MOP) {
1292                 return MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
1293                        MOP.isImplicit() && MOP.isKill() &&
1294                        TRI->regsOverlap(RegToRename, MOP.getReg());
1295               })) {
1296     LLVM_DEBUG(dbgs() << "  Operand not killed at " << FirstMI << "\n");
1297     return false;
1298   }
1299   auto canRenameMOP = [](const MachineOperand &MOP) {
1300     return MOP.isImplicit() ||
1301            (MOP.isRenamable() && !MOP.isEarlyClobber() && !MOP.isTied());
1302   };
1303 
1304   bool FoundDef = false;
1305 
1306   // For each instruction between FirstMI and the previous def for RegToRename,
1307   // we
1308   // * check if we can rename RegToRename in this instruction
1309   // * collect the registers used and required register classes for RegToRename.
1310   std::function<bool(MachineInstr &, bool)> CheckMIs = [&](MachineInstr &MI,
1311                                                            bool IsDef) {
1312     LLVM_DEBUG(dbgs() << "Checking " << MI << "\n");
1313     // Currently we do not try to rename across frame-setup instructions.
1314     if (MI.getFlag(MachineInstr::FrameSetup)) {
1315       LLVM_DEBUG(dbgs() << "  Cannot rename framesetup instructions currently ("
1316                         << MI << ")\n");
1317       return false;
1318     }
1319 
1320     UsedInBetween.accumulate(MI);
1321 
1322     // For a definition, check that we can rename the definition and exit the
1323     // loop.
1324     FoundDef = IsDef;
1325 
1326     // For defs, check if we can rename the first def of RegToRename.
1327     if (FoundDef) {
1328       for (auto &MOP : MI.operands()) {
1329         if (!MOP.isReg() || !MOP.isDef() || MOP.isDebug() || !MOP.getReg() ||
1330             !TRI->regsOverlap(MOP.getReg(), RegToRename))
1331           continue;
1332         if (!canRenameMOP(MOP)) {
1333           LLVM_DEBUG(dbgs()
1334                      << "  Cannot rename " << MOP << " in " << MI << "\n");
1335           return false;
1336         }
1337         RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
1338       }
1339       return true;
1340     } else {
1341       for (auto &MOP : MI.operands()) {
1342         if (!MOP.isReg() || MOP.isDebug() || !MOP.getReg() ||
1343             !TRI->regsOverlap(MOP.getReg(), RegToRename))
1344           continue;
1345 
1346         if (!canRenameMOP(MOP)) {
1347           LLVM_DEBUG(dbgs()
1348                      << "  Cannot rename " << MOP << " in " << MI << "\n");
1349           return false;
1350         }
1351         RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
1352       }
1353     }
1354     return true;
1355   };
1356 
1357   if (!forAllMIsUntilDef(FirstMI, RegToRename, TRI, LdStLimit, CheckMIs))
1358     return false;
1359 
1360   if (!FoundDef) {
1361     LLVM_DEBUG(dbgs() << "  Did not find definition for register in BB\n");
1362     return false;
1363   }
1364   return true;
1365 }
1366 
1367 // Check if we can find a physical register for renaming. This register must:
1368 // * not be defined up to FirstMI (checking DefinedInBB)
1369 // * not used between the MI and the defining instruction of the register to
1370 //   rename (checked using UsedInBetween).
1371 // * is available in all used register classes (checked using RequiredClasses).
1372 static Optional<MCPhysReg> tryToFindRegisterToRename(
1373     MachineInstr &FirstMI, MachineInstr &MI, LiveRegUnits &DefinedInBB,
1374     LiveRegUnits &UsedInBetween,
1375     SmallPtrSetImpl<const TargetRegisterClass *> &RequiredClasses,
1376     const TargetRegisterInfo *TRI) {
1377   auto &MF = *FirstMI.getParent()->getParent();
1378   MachineRegisterInfo &RegInfo = MF.getRegInfo();
1379 
1380   // Checks if any sub- or super-register of PR is callee saved.
1381   auto AnySubOrSuperRegCalleePreserved = [&MF, TRI](MCPhysReg PR) {
1382     return any_of(TRI->sub_and_superregs_inclusive(PR),
1383                   [&MF, TRI](MCPhysReg SubOrSuper) {
1384                     return TRI->isCalleeSavedPhysReg(SubOrSuper, MF);
1385                   });
1386   };
1387 
1388   // Check if PR or one of its sub- or super-registers can be used for all
1389   // required register classes.
1390   auto CanBeUsedForAllClasses = [&RequiredClasses, TRI](MCPhysReg PR) {
1391     return all_of(RequiredClasses, [PR, TRI](const TargetRegisterClass *C) {
1392       return any_of(TRI->sub_and_superregs_inclusive(PR),
1393                     [C, TRI](MCPhysReg SubOrSuper) {
1394                       return C == TRI->getMinimalPhysRegClass(SubOrSuper);
1395                     });
1396     });
1397   };
1398 
1399   auto *RegClass = TRI->getMinimalPhysRegClass(getLdStRegOp(FirstMI).getReg());
1400   for (const MCPhysReg &PR : *RegClass) {
1401     if (DefinedInBB.available(PR) && UsedInBetween.available(PR) &&
1402         !RegInfo.isReserved(PR) && !AnySubOrSuperRegCalleePreserved(PR) &&
1403         CanBeUsedForAllClasses(PR)) {
1404       DefinedInBB.addReg(PR);
1405       LLVM_DEBUG(dbgs() << "Found rename register " << printReg(PR, TRI)
1406                         << "\n");
1407       return {PR};
1408     }
1409   }
1410   LLVM_DEBUG(dbgs() << "No rename register found from "
1411                     << TRI->getRegClassName(RegClass) << "\n");
1412   return None;
1413 }
1414 
1415 /// Scan the instructions looking for a load/store that can be combined with the
1416 /// current instruction into a wider equivalent or a load/store pair.
1417 MachineBasicBlock::iterator
1418 AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
1419                                       LdStPairFlags &Flags, unsigned Limit,
1420                                       bool FindNarrowMerge) {
1421   MachineBasicBlock::iterator E = I->getParent()->end();
1422   MachineBasicBlock::iterator MBBI = I;
1423   MachineBasicBlock::iterator MBBIWithRenameReg;
1424   MachineInstr &FirstMI = *I;
1425   ++MBBI;
1426 
1427   bool MayLoad = FirstMI.mayLoad();
1428   bool IsUnscaled = TII->isUnscaledLdSt(FirstMI);
1429   Register Reg = getLdStRegOp(FirstMI).getReg();
1430   Register BaseReg = getLdStBaseOp(FirstMI).getReg();
1431   int Offset = getLdStOffsetOp(FirstMI).getImm();
1432   int OffsetStride = IsUnscaled ? TII->getMemScale(FirstMI) : 1;
1433   bool IsPromotableZeroStore = isPromotableZeroStoreInst(FirstMI);
1434 
1435   Optional<bool> MaybeCanRename = None;
1436   SmallPtrSet<const TargetRegisterClass *, 5> RequiredClasses;
1437   LiveRegUnits UsedInBetween;
1438   UsedInBetween.init(*TRI);
1439 
1440   Flags.clearRenameReg();
1441 
1442   // Track which register units have been modified and used between the first
1443   // insn (inclusive) and the second insn.
1444   ModifiedRegUnits.clear();
1445   UsedRegUnits.clear();
1446 
1447   // Remember any instructions that read/write memory between FirstMI and MI.
1448   SmallVector<MachineInstr *, 4> MemInsns;
1449 
1450   for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
1451     MachineInstr &MI = *MBBI;
1452 
1453     UsedInBetween.accumulate(MI);
1454 
1455     // Don't count transient instructions towards the search limit since there
1456     // may be different numbers of them if e.g. debug information is present.
1457     if (!MI.isTransient())
1458       ++Count;
1459 
1460     Flags.setSExtIdx(-1);
1461     if (areCandidatesToMergeOrPair(FirstMI, MI, Flags, TII) &&
1462         getLdStOffsetOp(MI).isImm()) {
1463       assert(MI.mayLoadOrStore() && "Expected memory operation.");
1464       // If we've found another instruction with the same opcode, check to see
1465       // if the base and offset are compatible with our starting instruction.
1466       // These instructions all have scaled immediate operands, so we just
1467       // check for +1/-1. Make sure to check the new instruction offset is
1468       // actually an immediate and not a symbolic reference destined for
1469       // a relocation.
1470       Register MIBaseReg = getLdStBaseOp(MI).getReg();
1471       int MIOffset = getLdStOffsetOp(MI).getImm();
1472       bool MIIsUnscaled = TII->isUnscaledLdSt(MI);
1473       if (IsUnscaled != MIIsUnscaled) {
1474         // We're trying to pair instructions that differ in how they are scaled.
1475         // If FirstMI is scaled then scale the offset of MI accordingly.
1476         // Otherwise, do the opposite (i.e., make MI's offset unscaled).
1477         int MemSize = TII->getMemScale(MI);
1478         if (MIIsUnscaled) {
1479           // If the unscaled offset isn't a multiple of the MemSize, we can't
1480           // pair the operations together: bail and keep looking.
1481           if (MIOffset % MemSize) {
1482             LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1483                                               UsedRegUnits, TRI);
1484             MemInsns.push_back(&MI);
1485             continue;
1486           }
1487           MIOffset /= MemSize;
1488         } else {
1489           MIOffset *= MemSize;
1490         }
1491       }
1492 
1493       if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
1494                                    (Offset + OffsetStride == MIOffset))) {
1495         int MinOffset = Offset < MIOffset ? Offset : MIOffset;
1496         if (FindNarrowMerge) {
1497           // If the alignment requirements of the scaled wide load/store
1498           // instruction can't express the offset of the scaled narrow input,
1499           // bail and keep looking. For promotable zero stores, allow only when
1500           // the stored value is the same (i.e., WZR).
1501           if ((!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) ||
1502               (IsPromotableZeroStore && Reg != getLdStRegOp(MI).getReg())) {
1503             LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1504                                               UsedRegUnits, TRI);
1505             MemInsns.push_back(&MI);
1506             continue;
1507           }
1508         } else {
1509           // Pairwise instructions have a 7-bit signed offset field. Single
1510           // insns have a 12-bit unsigned offset field.  If the resultant
1511           // immediate offset of merging these instructions is out of range for
1512           // a pairwise instruction, bail and keep looking.
1513           if (!inBoundsForPair(IsUnscaled, MinOffset, OffsetStride)) {
1514             LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1515                                               UsedRegUnits, TRI);
1516             MemInsns.push_back(&MI);
1517             continue;
1518           }
1519           // If the alignment requirements of the paired (scaled) instruction
1520           // can't express the offset of the unscaled input, bail and keep
1521           // looking.
1522           if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) {
1523             LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1524                                               UsedRegUnits, TRI);
1525             MemInsns.push_back(&MI);
1526             continue;
1527           }
1528         }
1529         // If the destination register of the loads is the same register, bail
1530         // and keep looking. A load-pair instruction with both destination
1531         // registers the same is UNPREDICTABLE and will result in an exception.
1532         if (MayLoad && Reg == getLdStRegOp(MI).getReg()) {
1533           LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
1534                                             TRI);
1535           MemInsns.push_back(&MI);
1536           continue;
1537         }
1538 
1539         // If the Rt of the second instruction was not modified or used between
1540         // the two instructions and none of the instructions between the second
1541         // and first alias with the second, we can combine the second into the
1542         // first.
1543         if (ModifiedRegUnits.available(getLdStRegOp(MI).getReg()) &&
1544             !(MI.mayLoad() &&
1545               !UsedRegUnits.available(getLdStRegOp(MI).getReg())) &&
1546             !mayAlias(MI, MemInsns, AA)) {
1547 
1548           Flags.setMergeForward(false);
1549           Flags.clearRenameReg();
1550           return MBBI;
1551         }
1552 
1553         // Likewise, if the Rt of the first instruction is not modified or used
1554         // between the two instructions and none of the instructions between the
1555         // first and the second alias with the first, we can combine the first
1556         // into the second.
1557         if (!(MayLoad &&
1558               !UsedRegUnits.available(getLdStRegOp(FirstMI).getReg())) &&
1559             !mayAlias(FirstMI, MemInsns, AA)) {
1560 
1561           if (ModifiedRegUnits.available(getLdStRegOp(FirstMI).getReg())) {
1562             Flags.setMergeForward(true);
1563             Flags.clearRenameReg();
1564             return MBBI;
1565           }
1566 
1567           if (DebugCounter::shouldExecute(RegRenamingCounter)) {
1568             if (!MaybeCanRename)
1569               MaybeCanRename = {canRenameUpToDef(FirstMI, UsedInBetween,
1570                                                  RequiredClasses, TRI)};
1571 
1572             if (*MaybeCanRename) {
1573               Optional<MCPhysReg> MaybeRenameReg = tryToFindRegisterToRename(
1574                   FirstMI, MI, DefinedInBB, UsedInBetween, RequiredClasses,
1575                   TRI);
1576               if (MaybeRenameReg) {
1577                 Flags.setRenameReg(*MaybeRenameReg);
1578                 Flags.setMergeForward(true);
1579                 MBBIWithRenameReg = MBBI;
1580               }
1581             }
1582           }
1583         }
1584         // Unable to combine these instructions due to interference in between.
1585         // Keep looking.
1586       }
1587     }
1588 
1589     if (Flags.getRenameReg())
1590       return MBBIWithRenameReg;
1591 
1592     // If the instruction wasn't a matching load or store.  Stop searching if we
1593     // encounter a call instruction that might modify memory.
1594     if (MI.isCall())
1595       return E;
1596 
1597     // Update modified / uses register units.
1598     LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
1599 
1600     // Otherwise, if the base register is modified, we have no match, so
1601     // return early.
1602     if (!ModifiedRegUnits.available(BaseReg))
1603       return E;
1604 
1605     // Update list of instructions that read/write memory.
1606     if (MI.mayLoadOrStore())
1607       MemInsns.push_back(&MI);
1608   }
1609   return E;
1610 }
1611 
1612 MachineBasicBlock::iterator
1613 AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
1614                                      MachineBasicBlock::iterator Update,
1615                                      bool IsPreIdx) {
1616   assert((Update->getOpcode() == AArch64::ADDXri ||
1617           Update->getOpcode() == AArch64::SUBXri) &&
1618          "Unexpected base register update instruction to merge!");
1619   MachineBasicBlock::iterator NextI = I;
1620   // Return the instruction following the merged instruction, which is
1621   // the instruction following our unmerged load. Unless that's the add/sub
1622   // instruction we're merging, in which case it's the one after that.
1623   if (++NextI == Update)
1624     ++NextI;
1625 
1626   int Value = Update->getOperand(2).getImm();
1627   assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
1628          "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
1629   if (Update->getOpcode() == AArch64::SUBXri)
1630     Value = -Value;
1631 
1632   unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
1633                              : getPostIndexedOpcode(I->getOpcode());
1634   MachineInstrBuilder MIB;
1635   int Scale, MinOffset, MaxOffset;
1636   getPrePostIndexedMemOpInfo(*I, Scale, MinOffset, MaxOffset);
1637   if (!isPairedLdSt(*I)) {
1638     // Non-paired instruction.
1639     MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1640               .add(getLdStRegOp(*Update))
1641               .add(getLdStRegOp(*I))
1642               .add(getLdStBaseOp(*I))
1643               .addImm(Value / Scale)
1644               .setMemRefs(I->memoperands())
1645               .setMIFlags(I->mergeFlagsWith(*Update));
1646   } else {
1647     // Paired instruction.
1648     MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1649               .add(getLdStRegOp(*Update))
1650               .add(getLdStRegOp(*I, 0))
1651               .add(getLdStRegOp(*I, 1))
1652               .add(getLdStBaseOp(*I))
1653               .addImm(Value / Scale)
1654               .setMemRefs(I->memoperands())
1655               .setMIFlags(I->mergeFlagsWith(*Update));
1656   }
1657   (void)MIB;
1658 
1659   if (IsPreIdx) {
1660     ++NumPreFolded;
1661     LLVM_DEBUG(dbgs() << "Creating pre-indexed load/store.");
1662   } else {
1663     ++NumPostFolded;
1664     LLVM_DEBUG(dbgs() << "Creating post-indexed load/store.");
1665   }
1666   LLVM_DEBUG(dbgs() << "    Replacing instructions:\n    ");
1667   LLVM_DEBUG(I->print(dbgs()));
1668   LLVM_DEBUG(dbgs() << "    ");
1669   LLVM_DEBUG(Update->print(dbgs()));
1670   LLVM_DEBUG(dbgs() << "  with instruction:\n    ");
1671   LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1672   LLVM_DEBUG(dbgs() << "\n");
1673 
1674   // Erase the old instructions for the block.
1675   I->eraseFromParent();
1676   Update->eraseFromParent();
1677 
1678   return NextI;
1679 }
1680 
1681 bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr &MemMI,
1682                                                MachineInstr &MI,
1683                                                unsigned BaseReg, int Offset) {
1684   switch (MI.getOpcode()) {
1685   default:
1686     break;
1687   case AArch64::SUBXri:
1688   case AArch64::ADDXri:
1689     // Make sure it's a vanilla immediate operand, not a relocation or
1690     // anything else we can't handle.
1691     if (!MI.getOperand(2).isImm())
1692       break;
1693     // Watch out for 1 << 12 shifted value.
1694     if (AArch64_AM::getShiftValue(MI.getOperand(3).getImm()))
1695       break;
1696 
1697     // The update instruction source and destination register must be the
1698     // same as the load/store base register.
1699     if (MI.getOperand(0).getReg() != BaseReg ||
1700         MI.getOperand(1).getReg() != BaseReg)
1701       break;
1702 
1703     int UpdateOffset = MI.getOperand(2).getImm();
1704     if (MI.getOpcode() == AArch64::SUBXri)
1705       UpdateOffset = -UpdateOffset;
1706 
1707     // The immediate must be a multiple of the scaling factor of the pre/post
1708     // indexed instruction.
1709     int Scale, MinOffset, MaxOffset;
1710     getPrePostIndexedMemOpInfo(MemMI, Scale, MinOffset, MaxOffset);
1711     if (UpdateOffset % Scale != 0)
1712       break;
1713 
1714     // Scaled offset must fit in the instruction immediate.
1715     int ScaledOffset = UpdateOffset / Scale;
1716     if (ScaledOffset > MaxOffset || ScaledOffset < MinOffset)
1717       break;
1718 
1719     // If we have a non-zero Offset, we check that it matches the amount
1720     // we're adding to the register.
1721     if (!Offset || Offset == UpdateOffset)
1722       return true;
1723     break;
1724   }
1725   return false;
1726 }
1727 
1728 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
1729     MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) {
1730   MachineBasicBlock::iterator E = I->getParent()->end();
1731   MachineInstr &MemMI = *I;
1732   MachineBasicBlock::iterator MBBI = I;
1733 
1734   Register BaseReg = getLdStBaseOp(MemMI).getReg();
1735   int MIUnscaledOffset = getLdStOffsetOp(MemMI).getImm() * TII->getMemScale(MemMI);
1736 
1737   // Scan forward looking for post-index opportunities.  Updating instructions
1738   // can't be formed if the memory instruction doesn't have the offset we're
1739   // looking for.
1740   if (MIUnscaledOffset != UnscaledOffset)
1741     return E;
1742 
1743   // If the base register overlaps a source/destination register, we can't
1744   // merge the update. This does not apply to tag store instructions which
1745   // ignore the address part of the source register.
1746   // This does not apply to STGPi as well, which does not have unpredictable
1747   // behavior in this case unlike normal stores, and always performs writeback
1748   // after reading the source register value.
1749   if (!isTagStore(MemMI) && MemMI.getOpcode() != AArch64::STGPi) {
1750     bool IsPairedInsn = isPairedLdSt(MemMI);
1751     for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1752       Register DestReg = getLdStRegOp(MemMI, i).getReg();
1753       if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1754         return E;
1755     }
1756   }
1757 
1758   // Track which register units have been modified and used between the first
1759   // insn (inclusive) and the second insn.
1760   ModifiedRegUnits.clear();
1761   UsedRegUnits.clear();
1762   ++MBBI;
1763   for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
1764     MachineInstr &MI = *MBBI;
1765 
1766     // Don't count transient instructions towards the search limit since there
1767     // may be different numbers of them if e.g. debug information is present.
1768     if (!MI.isTransient())
1769       ++Count;
1770 
1771     // If we found a match, return it.
1772     if (isMatchingUpdateInsn(*I, MI, BaseReg, UnscaledOffset))
1773       return MBBI;
1774 
1775     // Update the status of what the instruction clobbered and used.
1776     LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
1777 
1778     // Otherwise, if the base register is used or modified, we have no match, so
1779     // return early.
1780     if (!ModifiedRegUnits.available(BaseReg) ||
1781         !UsedRegUnits.available(BaseReg))
1782       return E;
1783   }
1784   return E;
1785 }
1786 
1787 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
1788     MachineBasicBlock::iterator I, unsigned Limit) {
1789   MachineBasicBlock::iterator B = I->getParent()->begin();
1790   MachineBasicBlock::iterator E = I->getParent()->end();
1791   MachineInstr &MemMI = *I;
1792   MachineBasicBlock::iterator MBBI = I;
1793 
1794   Register BaseReg = getLdStBaseOp(MemMI).getReg();
1795   int Offset = getLdStOffsetOp(MemMI).getImm();
1796 
1797   // If the load/store is the first instruction in the block, there's obviously
1798   // not any matching update. Ditto if the memory offset isn't zero.
1799   if (MBBI == B || Offset != 0)
1800     return E;
1801   // If the base register overlaps a destination register, we can't
1802   // merge the update.
1803   if (!isTagStore(MemMI)) {
1804     bool IsPairedInsn = isPairedLdSt(MemMI);
1805     for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1806       Register DestReg = getLdStRegOp(MemMI, i).getReg();
1807       if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1808         return E;
1809     }
1810   }
1811 
1812   // Track which register units have been modified and used between the first
1813   // insn (inclusive) and the second insn.
1814   ModifiedRegUnits.clear();
1815   UsedRegUnits.clear();
1816   unsigned Count = 0;
1817   do {
1818     --MBBI;
1819     MachineInstr &MI = *MBBI;
1820 
1821     // Don't count transient instructions towards the search limit since there
1822     // may be different numbers of them if e.g. debug information is present.
1823     if (!MI.isTransient())
1824       ++Count;
1825 
1826     // If we found a match, return it.
1827     if (isMatchingUpdateInsn(*I, MI, BaseReg, Offset))
1828       return MBBI;
1829 
1830     // Update the status of what the instruction clobbered and used.
1831     LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
1832 
1833     // Otherwise, if the base register is used or modified, we have no match, so
1834     // return early.
1835     if (!ModifiedRegUnits.available(BaseReg) ||
1836         !UsedRegUnits.available(BaseReg))
1837       return E;
1838   } while (MBBI != B && Count < Limit);
1839   return E;
1840 }
1841 
1842 bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore(
1843     MachineBasicBlock::iterator &MBBI) {
1844   MachineInstr &MI = *MBBI;
1845   // If this is a volatile load, don't mess with it.
1846   if (MI.hasOrderedMemoryRef())
1847     return false;
1848 
1849   // Make sure this is a reg+imm.
1850   // FIXME: It is possible to extend it to handle reg+reg cases.
1851   if (!getLdStOffsetOp(MI).isImm())
1852     return false;
1853 
1854   // Look backward up to LdStLimit instructions.
1855   MachineBasicBlock::iterator StoreI;
1856   if (findMatchingStore(MBBI, LdStLimit, StoreI)) {
1857     ++NumLoadsFromStoresPromoted;
1858     // Promote the load. Keeping the iterator straight is a
1859     // pain, so we let the merge routine tell us what the next instruction
1860     // is after it's done mucking about.
1861     MBBI = promoteLoadFromStore(MBBI, StoreI);
1862     return true;
1863   }
1864   return false;
1865 }
1866 
1867 // Merge adjacent zero stores into a wider store.
1868 bool AArch64LoadStoreOpt::tryToMergeZeroStInst(
1869     MachineBasicBlock::iterator &MBBI) {
1870   assert(isPromotableZeroStoreInst(*MBBI) && "Expected narrow store.");
1871   MachineInstr &MI = *MBBI;
1872   MachineBasicBlock::iterator E = MI.getParent()->end();
1873 
1874   if (!TII->isCandidateToMergeOrPair(MI))
1875     return false;
1876 
1877   // Look ahead up to LdStLimit instructions for a mergable instruction.
1878   LdStPairFlags Flags;
1879   MachineBasicBlock::iterator MergeMI =
1880       findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ true);
1881   if (MergeMI != E) {
1882     ++NumZeroStoresPromoted;
1883 
1884     // Keeping the iterator straight is a pain, so we let the merge routine tell
1885     // us what the next instruction is after it's done mucking about.
1886     MBBI = mergeNarrowZeroStores(MBBI, MergeMI, Flags);
1887     return true;
1888   }
1889   return false;
1890 }
1891 
1892 // Find loads and stores that can be merged into a single load or store pair
1893 // instruction.
1894 bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
1895   MachineInstr &MI = *MBBI;
1896   MachineBasicBlock::iterator E = MI.getParent()->end();
1897 
1898   if (!TII->isCandidateToMergeOrPair(MI))
1899     return false;
1900 
1901   // Early exit if the offset is not possible to match. (6 bits of positive
1902   // range, plus allow an extra one in case we find a later insn that matches
1903   // with Offset-1)
1904   bool IsUnscaled = TII->isUnscaledLdSt(MI);
1905   int Offset = getLdStOffsetOp(MI).getImm();
1906   int OffsetStride = IsUnscaled ? TII->getMemScale(MI) : 1;
1907   // Allow one more for offset.
1908   if (Offset > 0)
1909     Offset -= OffsetStride;
1910   if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
1911     return false;
1912 
1913   // Look ahead up to LdStLimit instructions for a pairable instruction.
1914   LdStPairFlags Flags;
1915   MachineBasicBlock::iterator Paired =
1916       findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ false);
1917   if (Paired != E) {
1918     ++NumPairCreated;
1919     if (TII->isUnscaledLdSt(MI))
1920       ++NumUnscaledPairCreated;
1921     // Keeping the iterator straight is a pain, so we let the merge routine tell
1922     // us what the next instruction is after it's done mucking about.
1923     auto Prev = std::prev(MBBI);
1924     MBBI = mergePairedInsns(MBBI, Paired, Flags);
1925     // Collect liveness info for instructions between Prev and the new position
1926     // MBBI.
1927     for (auto I = std::next(Prev); I != MBBI; I++)
1928       updateDefinedRegisters(*I, DefinedInBB, TRI);
1929 
1930     return true;
1931   }
1932   return false;
1933 }
1934 
1935 bool AArch64LoadStoreOpt::tryToMergeLdStUpdate
1936     (MachineBasicBlock::iterator &MBBI) {
1937   MachineInstr &MI = *MBBI;
1938   MachineBasicBlock::iterator E = MI.getParent()->end();
1939   MachineBasicBlock::iterator Update;
1940 
1941   // Look forward to try to form a post-index instruction. For example,
1942   // ldr x0, [x20]
1943   // add x20, x20, #32
1944   //   merged into:
1945   // ldr x0, [x20], #32
1946   Update = findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit);
1947   if (Update != E) {
1948     // Merge the update into the ld/st.
1949     MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
1950     return true;
1951   }
1952 
1953   // Don't know how to handle unscaled pre/post-index versions below, so bail.
1954   if (TII->isUnscaledLdSt(MI.getOpcode()))
1955     return false;
1956 
1957   // Look back to try to find a pre-index instruction. For example,
1958   // add x0, x0, #8
1959   // ldr x1, [x0]
1960   //   merged into:
1961   // ldr x1, [x0, #8]!
1962   Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit);
1963   if (Update != E) {
1964     // Merge the update into the ld/st.
1965     MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
1966     return true;
1967   }
1968 
1969   // The immediate in the load/store is scaled by the size of the memory
1970   // operation. The immediate in the add we're looking for,
1971   // however, is not, so adjust here.
1972   int UnscaledOffset = getLdStOffsetOp(MI).getImm() * TII->getMemScale(MI);
1973 
1974   // Look forward to try to find a pre-index instruction. For example,
1975   // ldr x1, [x0, #64]
1976   // add x0, x0, #64
1977   //   merged into:
1978   // ldr x1, [x0, #64]!
1979   Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit);
1980   if (Update != E) {
1981     // Merge the update into the ld/st.
1982     MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
1983     return true;
1984   }
1985 
1986   return false;
1987 }
1988 
1989 bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
1990                                         bool EnableNarrowZeroStOpt) {
1991 
1992   bool Modified = false;
1993   // Four tranformations to do here:
1994   // 1) Find loads that directly read from stores and promote them by
1995   //    replacing with mov instructions. If the store is wider than the load,
1996   //    the load will be replaced with a bitfield extract.
1997   //      e.g.,
1998   //        str w1, [x0, #4]
1999   //        ldrh w2, [x0, #6]
2000   //        ; becomes
2001   //        str w1, [x0, #4]
2002   //        lsr w2, w1, #16
2003   for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
2004        MBBI != E;) {
2005     if (isPromotableLoadFromStore(*MBBI) && tryToPromoteLoadFromStore(MBBI))
2006       Modified = true;
2007     else
2008       ++MBBI;
2009   }
2010   // 2) Merge adjacent zero stores into a wider store.
2011   //      e.g.,
2012   //        strh wzr, [x0]
2013   //        strh wzr, [x0, #2]
2014   //        ; becomes
2015   //        str wzr, [x0]
2016   //      e.g.,
2017   //        str wzr, [x0]
2018   //        str wzr, [x0, #4]
2019   //        ; becomes
2020   //        str xzr, [x0]
2021   if (EnableNarrowZeroStOpt)
2022     for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
2023          MBBI != E;) {
2024       if (isPromotableZeroStoreInst(*MBBI) && tryToMergeZeroStInst(MBBI))
2025         Modified = true;
2026       else
2027         ++MBBI;
2028     }
2029   // 3) Find loads and stores that can be merged into a single load or store
2030   //    pair instruction.
2031   //      e.g.,
2032   //        ldr x0, [x2]
2033   //        ldr x1, [x2, #8]
2034   //        ; becomes
2035   //        ldp x0, x1, [x2]
2036 
2037   if (MBB.getParent()->getRegInfo().tracksLiveness()) {
2038     DefinedInBB.clear();
2039     DefinedInBB.addLiveIns(MBB);
2040   }
2041 
2042   for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
2043        MBBI != E;) {
2044     // Track currently live registers up to this point, to help with
2045     // searching for a rename register on demand.
2046     updateDefinedRegisters(*MBBI, DefinedInBB, TRI);
2047     if (TII->isPairableLdStInst(*MBBI) && tryToPairLdStInst(MBBI))
2048       Modified = true;
2049     else
2050       ++MBBI;
2051   }
2052   // 4) Find base register updates that can be merged into the load or store
2053   //    as a base-reg writeback.
2054   //      e.g.,
2055   //        ldr x0, [x2]
2056   //        add x2, x2, #4
2057   //        ; becomes
2058   //        ldr x0, [x2], #4
2059   for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
2060        MBBI != E;) {
2061     if (isMergeableLdStUpdate(*MBBI) && tryToMergeLdStUpdate(MBBI))
2062       Modified = true;
2063     else
2064       ++MBBI;
2065   }
2066 
2067   return Modified;
2068 }
2069 
2070 bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
2071   if (skipFunction(Fn.getFunction()))
2072     return false;
2073 
2074   Subtarget = &static_cast<const AArch64Subtarget &>(Fn.getSubtarget());
2075   TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo());
2076   TRI = Subtarget->getRegisterInfo();
2077   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2078 
2079   // Resize the modified and used register unit trackers.  We do this once
2080   // per function and then clear the register units each time we optimize a load
2081   // or store.
2082   ModifiedRegUnits.init(*TRI);
2083   UsedRegUnits.init(*TRI);
2084   DefinedInBB.init(*TRI);
2085 
2086   bool Modified = false;
2087   bool enableNarrowZeroStOpt = !Subtarget->requiresStrictAlign();
2088   for (auto &MBB : Fn) {
2089     auto M = optimizeBlock(MBB, enableNarrowZeroStOpt);
2090     Modified |= M;
2091   }
2092 
2093   return Modified;
2094 }
2095 
2096 // FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep loads and
2097 // stores near one another?  Note: The pre-RA instruction scheduler already has
2098 // hooks to try and schedule pairable loads/stores together to improve pairing
2099 // opportunities.  Thus, pre-RA pairing pass may not be worth the effort.
2100 
2101 // FIXME: When pairing store instructions it's very possible for this pass to
2102 // hoist a store with a KILL marker above another use (without a KILL marker).
2103 // The resulting IR is invalid, but nothing uses the KILL markers after this
2104 // pass, so it's never caused a problem in practice.
2105 
2106 /// createAArch64LoadStoreOptimizationPass - returns an instance of the
2107 /// load / store optimization pass.
2108 FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
2109   return new AArch64LoadStoreOpt();
2110 }
2111