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