xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AArch64/AArch64LoadStoreOptimizer.cpp (revision c66ec88fed842fbaad62c30d510644ceb7bd2d71)
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,
1148                      SmallVectorImpl<MachineInstr *> &MemInsns,
1149                      AliasAnalysis *AA) {
1150   for (MachineInstr *MIb : MemInsns)
1151     if (MIa.mayAlias(AA, *MIb, /*UseTBAA*/ false))
1152       return true;
1153 
1154   return false;
1155 }
1156 
1157 bool AArch64LoadStoreOpt::findMatchingStore(
1158     MachineBasicBlock::iterator I, unsigned Limit,
1159     MachineBasicBlock::iterator &StoreI) {
1160   MachineBasicBlock::iterator B = I->getParent()->begin();
1161   MachineBasicBlock::iterator MBBI = I;
1162   MachineInstr &LoadMI = *I;
1163   Register BaseReg = getLdStBaseOp(LoadMI).getReg();
1164 
1165   // If the load is the first instruction in the block, there's obviously
1166   // not any matching store.
1167   if (MBBI == B)
1168     return false;
1169 
1170   // Track which register units have been modified and used between the first
1171   // insn and the second insn.
1172   ModifiedRegUnits.clear();
1173   UsedRegUnits.clear();
1174 
1175   unsigned Count = 0;
1176   do {
1177     MBBI = prev_nodbg(MBBI, B);
1178     MachineInstr &MI = *MBBI;
1179 
1180     // Don't count transient instructions towards the search limit since there
1181     // may be different numbers of them if e.g. debug information is present.
1182     if (!MI.isTransient())
1183       ++Count;
1184 
1185     // If the load instruction reads directly from the address to which the
1186     // store instruction writes and the stored value is not modified, we can
1187     // promote the load. Since we do not handle stores with pre-/post-index,
1188     // it's unnecessary to check if BaseReg is modified by the store itself.
1189     if (MI.mayStore() && isMatchingStore(LoadMI, MI) &&
1190         BaseReg == getLdStBaseOp(MI).getReg() &&
1191         isLdOffsetInRangeOfSt(LoadMI, MI, TII) &&
1192         ModifiedRegUnits.available(getLdStRegOp(MI).getReg())) {
1193       StoreI = MBBI;
1194       return true;
1195     }
1196 
1197     if (MI.isCall())
1198       return false;
1199 
1200     // Update modified / uses register units.
1201     LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
1202 
1203     // Otherwise, if the base register is modified, we have no match, so
1204     // return early.
1205     if (!ModifiedRegUnits.available(BaseReg))
1206       return false;
1207 
1208     // If we encounter a store aliased with the load, return early.
1209     if (MI.mayStore() && LoadMI.mayAlias(AA, MI, /*UseTBAA*/ false))
1210       return false;
1211   } while (MBBI != B && Count < Limit);
1212   return false;
1213 }
1214 
1215 // Returns true if FirstMI and MI are candidates for merging or pairing.
1216 // Otherwise, returns false.
1217 static bool areCandidatesToMergeOrPair(MachineInstr &FirstMI, MachineInstr &MI,
1218                                        LdStPairFlags &Flags,
1219                                        const AArch64InstrInfo *TII) {
1220   // If this is volatile or if pairing is suppressed, not a candidate.
1221   if (MI.hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
1222     return false;
1223 
1224   // We should have already checked FirstMI for pair suppression and volatility.
1225   assert(!FirstMI.hasOrderedMemoryRef() &&
1226          !TII->isLdStPairSuppressed(FirstMI) &&
1227          "FirstMI shouldn't get here if either of these checks are true.");
1228 
1229   unsigned OpcA = FirstMI.getOpcode();
1230   unsigned OpcB = MI.getOpcode();
1231 
1232   // Opcodes match: nothing more to check.
1233   if (OpcA == OpcB)
1234     return true;
1235 
1236   // Try to match a sign-extended load/store with a zero-extended load/store.
1237   bool IsValidLdStrOpc, PairIsValidLdStrOpc;
1238   unsigned NonSExtOpc = getMatchingNonSExtOpcode(OpcA, &IsValidLdStrOpc);
1239   assert(IsValidLdStrOpc &&
1240          "Given Opc should be a Load or Store with an immediate");
1241   // OpcA will be the first instruction in the pair.
1242   if (NonSExtOpc == getMatchingNonSExtOpcode(OpcB, &PairIsValidLdStrOpc)) {
1243     Flags.setSExtIdx(NonSExtOpc == (unsigned)OpcA ? 1 : 0);
1244     return true;
1245   }
1246 
1247   // If the second instruction isn't even a mergable/pairable load/store, bail
1248   // out.
1249   if (!PairIsValidLdStrOpc)
1250     return false;
1251 
1252   // FIXME: We don't support merging narrow stores with mixed scaled/unscaled
1253   // offsets.
1254   if (isNarrowStore(OpcA) || isNarrowStore(OpcB))
1255     return false;
1256 
1257   // Try to match an unscaled load/store with a scaled load/store.
1258   return TII->isUnscaledLdSt(OpcA) != TII->isUnscaledLdSt(OpcB) &&
1259          getMatchingPairOpcode(OpcA) == getMatchingPairOpcode(OpcB);
1260 
1261   // FIXME: Can we also match a mixed sext/zext unscaled/scaled pair?
1262 }
1263 
1264 static bool
1265 canRenameUpToDef(MachineInstr &FirstMI, LiveRegUnits &UsedInBetween,
1266                  SmallPtrSetImpl<const TargetRegisterClass *> &RequiredClasses,
1267                  const TargetRegisterInfo *TRI) {
1268   if (!FirstMI.mayStore())
1269     return false;
1270 
1271   // Check if we can find an unused register which we can use to rename
1272   // the register used by the first load/store.
1273   auto *RegClass = TRI->getMinimalPhysRegClass(getLdStRegOp(FirstMI).getReg());
1274   MachineFunction &MF = *FirstMI.getParent()->getParent();
1275   if (!RegClass || !MF.getRegInfo().tracksLiveness())
1276     return false;
1277 
1278   auto RegToRename = getLdStRegOp(FirstMI).getReg();
1279   // For now, we only rename if the store operand gets killed at the store.
1280   if (!getLdStRegOp(FirstMI).isKill() &&
1281       !any_of(FirstMI.operands(),
1282               [TRI, RegToRename](const MachineOperand &MOP) {
1283                 return MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
1284                        MOP.isImplicit() && MOP.isKill() &&
1285                        TRI->regsOverlap(RegToRename, MOP.getReg());
1286               })) {
1287     LLVM_DEBUG(dbgs() << "  Operand not killed at " << FirstMI << "\n");
1288     return false;
1289   }
1290   auto canRenameMOP = [TRI](const MachineOperand &MOP) {
1291     if (MOP.isReg()) {
1292       auto *RegClass = TRI->getMinimalPhysRegClass(MOP.getReg());
1293       // Renaming registers with multiple disjunct sub-registers (e.g. the
1294       // result of a LD3) means that all sub-registers are renamed, potentially
1295       // impacting other instructions we did not check. Bail out.
1296       // Note that this relies on the structure of the AArch64 register file. In
1297       // particular, a subregister cannot be written without overwriting the
1298       // whole register.
1299       if (RegClass->HasDisjunctSubRegs) {
1300         LLVM_DEBUG(
1301             dbgs()
1302             << "  Cannot rename operands with multiple disjunct subregisters ("
1303             << MOP << ")\n");
1304         return false;
1305       }
1306     }
1307     return MOP.isImplicit() ||
1308            (MOP.isRenamable() && !MOP.isEarlyClobber() && !MOP.isTied());
1309   };
1310 
1311   bool FoundDef = false;
1312 
1313   // For each instruction between FirstMI and the previous def for RegToRename,
1314   // we
1315   // * check if we can rename RegToRename in this instruction
1316   // * collect the registers used and required register classes for RegToRename.
1317   std::function<bool(MachineInstr &, bool)> CheckMIs = [&](MachineInstr &MI,
1318                                                            bool IsDef) {
1319     LLVM_DEBUG(dbgs() << "Checking " << MI << "\n");
1320     // Currently we do not try to rename across frame-setup instructions.
1321     if (MI.getFlag(MachineInstr::FrameSetup)) {
1322       LLVM_DEBUG(dbgs() << "  Cannot rename framesetup instructions currently ("
1323                         << MI << ")\n");
1324       return false;
1325     }
1326 
1327     UsedInBetween.accumulate(MI);
1328 
1329     // For a definition, check that we can rename the definition and exit the
1330     // loop.
1331     FoundDef = IsDef;
1332 
1333     // For defs, check if we can rename the first def of RegToRename.
1334     if (FoundDef) {
1335       // For some pseudo instructions, we might not generate code in the end
1336       // (e.g. KILL) and we would end up without a correct def for the rename
1337       // register.
1338       // TODO: This might be overly conservative and we could handle those cases
1339       // in multiple ways:
1340       //       1. Insert an extra copy, to materialize the def.
1341       //       2. Skip pseudo-defs until we find an non-pseudo def.
1342       if (MI.isPseudo()) {
1343         LLVM_DEBUG(dbgs() << "  Cannot rename pseudo instruction " << MI
1344                           << "\n");
1345         return false;
1346       }
1347 
1348       for (auto &MOP : MI.operands()) {
1349         if (!MOP.isReg() || !MOP.isDef() || MOP.isDebug() || !MOP.getReg() ||
1350             !TRI->regsOverlap(MOP.getReg(), RegToRename))
1351           continue;
1352         if (!canRenameMOP(MOP)) {
1353           LLVM_DEBUG(dbgs()
1354                      << "  Cannot rename " << MOP << " in " << MI << "\n");
1355           return false;
1356         }
1357         RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
1358       }
1359       return true;
1360     } else {
1361       for (auto &MOP : MI.operands()) {
1362         if (!MOP.isReg() || MOP.isDebug() || !MOP.getReg() ||
1363             !TRI->regsOverlap(MOP.getReg(), RegToRename))
1364           continue;
1365 
1366         if (!canRenameMOP(MOP)) {
1367           LLVM_DEBUG(dbgs()
1368                      << "  Cannot rename " << MOP << " in " << MI << "\n");
1369           return false;
1370         }
1371         RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
1372       }
1373     }
1374     return true;
1375   };
1376 
1377   if (!forAllMIsUntilDef(FirstMI, RegToRename, TRI, LdStLimit, CheckMIs))
1378     return false;
1379 
1380   if (!FoundDef) {
1381     LLVM_DEBUG(dbgs() << "  Did not find definition for register in BB\n");
1382     return false;
1383   }
1384   return true;
1385 }
1386 
1387 // Check if we can find a physical register for renaming. This register must:
1388 // * not be defined up to FirstMI (checking DefinedInBB)
1389 // * not used between the MI and the defining instruction of the register to
1390 //   rename (checked using UsedInBetween).
1391 // * is available in all used register classes (checked using RequiredClasses).
1392 static Optional<MCPhysReg> tryToFindRegisterToRename(
1393     MachineInstr &FirstMI, MachineInstr &MI, LiveRegUnits &DefinedInBB,
1394     LiveRegUnits &UsedInBetween,
1395     SmallPtrSetImpl<const TargetRegisterClass *> &RequiredClasses,
1396     const TargetRegisterInfo *TRI) {
1397   auto &MF = *FirstMI.getParent()->getParent();
1398   MachineRegisterInfo &RegInfo = MF.getRegInfo();
1399 
1400   // Checks if any sub- or super-register of PR is callee saved.
1401   auto AnySubOrSuperRegCalleePreserved = [&MF, TRI](MCPhysReg PR) {
1402     return any_of(TRI->sub_and_superregs_inclusive(PR),
1403                   [&MF, TRI](MCPhysReg SubOrSuper) {
1404                     return TRI->isCalleeSavedPhysReg(SubOrSuper, MF);
1405                   });
1406   };
1407 
1408   // Check if PR or one of its sub- or super-registers can be used for all
1409   // required register classes.
1410   auto CanBeUsedForAllClasses = [&RequiredClasses, TRI](MCPhysReg PR) {
1411     return all_of(RequiredClasses, [PR, TRI](const TargetRegisterClass *C) {
1412       return any_of(TRI->sub_and_superregs_inclusive(PR),
1413                     [C, TRI](MCPhysReg SubOrSuper) {
1414                       return C == TRI->getMinimalPhysRegClass(SubOrSuper);
1415                     });
1416     });
1417   };
1418 
1419   auto *RegClass = TRI->getMinimalPhysRegClass(getLdStRegOp(FirstMI).getReg());
1420   for (const MCPhysReg &PR : *RegClass) {
1421     if (DefinedInBB.available(PR) && UsedInBetween.available(PR) &&
1422         !RegInfo.isReserved(PR) && !AnySubOrSuperRegCalleePreserved(PR) &&
1423         CanBeUsedForAllClasses(PR)) {
1424       DefinedInBB.addReg(PR);
1425       LLVM_DEBUG(dbgs() << "Found rename register " << printReg(PR, TRI)
1426                         << "\n");
1427       return {PR};
1428     }
1429   }
1430   LLVM_DEBUG(dbgs() << "No rename register found from "
1431                     << TRI->getRegClassName(RegClass) << "\n");
1432   return None;
1433 }
1434 
1435 /// Scan the instructions looking for a load/store that can be combined with the
1436 /// current instruction into a wider equivalent or a load/store pair.
1437 MachineBasicBlock::iterator
1438 AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
1439                                       LdStPairFlags &Flags, unsigned Limit,
1440                                       bool FindNarrowMerge) {
1441   MachineBasicBlock::iterator E = I->getParent()->end();
1442   MachineBasicBlock::iterator MBBI = I;
1443   MachineBasicBlock::iterator MBBIWithRenameReg;
1444   MachineInstr &FirstMI = *I;
1445   MBBI = next_nodbg(MBBI, E);
1446 
1447   bool MayLoad = FirstMI.mayLoad();
1448   bool IsUnscaled = TII->isUnscaledLdSt(FirstMI);
1449   Register Reg = getLdStRegOp(FirstMI).getReg();
1450   Register BaseReg = getLdStBaseOp(FirstMI).getReg();
1451   int Offset = getLdStOffsetOp(FirstMI).getImm();
1452   int OffsetStride = IsUnscaled ? TII->getMemScale(FirstMI) : 1;
1453   bool IsPromotableZeroStore = isPromotableZeroStoreInst(FirstMI);
1454 
1455   Optional<bool> MaybeCanRename = None;
1456   if (!EnableRenaming)
1457     MaybeCanRename = {false};
1458 
1459   SmallPtrSet<const TargetRegisterClass *, 5> RequiredClasses;
1460   LiveRegUnits UsedInBetween;
1461   UsedInBetween.init(*TRI);
1462 
1463   Flags.clearRenameReg();
1464 
1465   // Track which register units have been modified and used between the first
1466   // insn (inclusive) and the second insn.
1467   ModifiedRegUnits.clear();
1468   UsedRegUnits.clear();
1469 
1470   // Remember any instructions that read/write memory between FirstMI and MI.
1471   SmallVector<MachineInstr *, 4> MemInsns;
1472 
1473   for (unsigned Count = 0; MBBI != E && Count < Limit;
1474        MBBI = next_nodbg(MBBI, E)) {
1475     MachineInstr &MI = *MBBI;
1476 
1477     UsedInBetween.accumulate(MI);
1478 
1479     // Don't count transient instructions towards the search limit since there
1480     // may be different numbers of them if e.g. debug information is present.
1481     if (!MI.isTransient())
1482       ++Count;
1483 
1484     Flags.setSExtIdx(-1);
1485     if (areCandidatesToMergeOrPair(FirstMI, MI, Flags, TII) &&
1486         getLdStOffsetOp(MI).isImm()) {
1487       assert(MI.mayLoadOrStore() && "Expected memory operation.");
1488       // If we've found another instruction with the same opcode, check to see
1489       // if the base and offset are compatible with our starting instruction.
1490       // These instructions all have scaled immediate operands, so we just
1491       // check for +1/-1. Make sure to check the new instruction offset is
1492       // actually an immediate and not a symbolic reference destined for
1493       // a relocation.
1494       Register MIBaseReg = getLdStBaseOp(MI).getReg();
1495       int MIOffset = getLdStOffsetOp(MI).getImm();
1496       bool MIIsUnscaled = TII->isUnscaledLdSt(MI);
1497       if (IsUnscaled != MIIsUnscaled) {
1498         // We're trying to pair instructions that differ in how they are scaled.
1499         // If FirstMI is scaled then scale the offset of MI accordingly.
1500         // Otherwise, do the opposite (i.e., make MI's offset unscaled).
1501         int MemSize = TII->getMemScale(MI);
1502         if (MIIsUnscaled) {
1503           // If the unscaled offset isn't a multiple of the MemSize, we can't
1504           // pair the operations together: bail and keep looking.
1505           if (MIOffset % MemSize) {
1506             LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1507                                               UsedRegUnits, TRI);
1508             MemInsns.push_back(&MI);
1509             continue;
1510           }
1511           MIOffset /= MemSize;
1512         } else {
1513           MIOffset *= MemSize;
1514         }
1515       }
1516 
1517       if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
1518                                    (Offset + OffsetStride == MIOffset))) {
1519         int MinOffset = Offset < MIOffset ? Offset : MIOffset;
1520         if (FindNarrowMerge) {
1521           // If the alignment requirements of the scaled wide load/store
1522           // instruction can't express the offset of the scaled narrow input,
1523           // bail and keep looking. For promotable zero stores, allow only when
1524           // the stored value is the same (i.e., WZR).
1525           if ((!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) ||
1526               (IsPromotableZeroStore && Reg != getLdStRegOp(MI).getReg())) {
1527             LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1528                                               UsedRegUnits, TRI);
1529             MemInsns.push_back(&MI);
1530             continue;
1531           }
1532         } else {
1533           // Pairwise instructions have a 7-bit signed offset field. Single
1534           // insns have a 12-bit unsigned offset field.  If the resultant
1535           // immediate offset of merging these instructions is out of range for
1536           // a pairwise instruction, bail and keep looking.
1537           if (!inBoundsForPair(IsUnscaled, MinOffset, OffsetStride)) {
1538             LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1539                                               UsedRegUnits, TRI);
1540             MemInsns.push_back(&MI);
1541             continue;
1542           }
1543           // If the alignment requirements of the paired (scaled) instruction
1544           // can't express the offset of the unscaled input, bail and keep
1545           // looking.
1546           if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) {
1547             LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1548                                               UsedRegUnits, TRI);
1549             MemInsns.push_back(&MI);
1550             continue;
1551           }
1552         }
1553         // If the destination register of the loads is the same register, bail
1554         // and keep looking. A load-pair instruction with both destination
1555         // registers the same is UNPREDICTABLE and will result in an exception.
1556         if (MayLoad && Reg == getLdStRegOp(MI).getReg()) {
1557           LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
1558                                             TRI);
1559           MemInsns.push_back(&MI);
1560           continue;
1561         }
1562 
1563         // If the Rt of the second instruction was not modified or used between
1564         // the two instructions and none of the instructions between the second
1565         // and first alias with the second, we can combine the second into the
1566         // first.
1567         if (ModifiedRegUnits.available(getLdStRegOp(MI).getReg()) &&
1568             !(MI.mayLoad() &&
1569               !UsedRegUnits.available(getLdStRegOp(MI).getReg())) &&
1570             !mayAlias(MI, MemInsns, AA)) {
1571 
1572           Flags.setMergeForward(false);
1573           Flags.clearRenameReg();
1574           return MBBI;
1575         }
1576 
1577         // Likewise, if the Rt of the first instruction is not modified or used
1578         // between the two instructions and none of the instructions between the
1579         // first and the second alias with the first, we can combine the first
1580         // into the second.
1581         if (!(MayLoad &&
1582               !UsedRegUnits.available(getLdStRegOp(FirstMI).getReg())) &&
1583             !mayAlias(FirstMI, MemInsns, AA)) {
1584 
1585           if (ModifiedRegUnits.available(getLdStRegOp(FirstMI).getReg())) {
1586             Flags.setMergeForward(true);
1587             Flags.clearRenameReg();
1588             return MBBI;
1589           }
1590 
1591           if (DebugCounter::shouldExecute(RegRenamingCounter)) {
1592             if (!MaybeCanRename)
1593               MaybeCanRename = {canRenameUpToDef(FirstMI, UsedInBetween,
1594                                                  RequiredClasses, TRI)};
1595 
1596             if (*MaybeCanRename) {
1597               Optional<MCPhysReg> MaybeRenameReg = tryToFindRegisterToRename(
1598                   FirstMI, MI, DefinedInBB, UsedInBetween, RequiredClasses,
1599                   TRI);
1600               if (MaybeRenameReg) {
1601                 Flags.setRenameReg(*MaybeRenameReg);
1602                 Flags.setMergeForward(true);
1603                 MBBIWithRenameReg = MBBI;
1604               }
1605             }
1606           }
1607         }
1608         // Unable to combine these instructions due to interference in between.
1609         // Keep looking.
1610       }
1611     }
1612 
1613     if (Flags.getRenameReg())
1614       return MBBIWithRenameReg;
1615 
1616     // If the instruction wasn't a matching load or store.  Stop searching if we
1617     // encounter a call instruction that might modify memory.
1618     if (MI.isCall())
1619       return E;
1620 
1621     // Update modified / uses register units.
1622     LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
1623 
1624     // Otherwise, if the base register is modified, we have no match, so
1625     // return early.
1626     if (!ModifiedRegUnits.available(BaseReg))
1627       return E;
1628 
1629     // Update list of instructions that read/write memory.
1630     if (MI.mayLoadOrStore())
1631       MemInsns.push_back(&MI);
1632   }
1633   return E;
1634 }
1635 
1636 MachineBasicBlock::iterator
1637 AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
1638                                      MachineBasicBlock::iterator Update,
1639                                      bool IsPreIdx) {
1640   assert((Update->getOpcode() == AArch64::ADDXri ||
1641           Update->getOpcode() == AArch64::SUBXri) &&
1642          "Unexpected base register update instruction to merge!");
1643   MachineBasicBlock::iterator E = I->getParent()->end();
1644   MachineBasicBlock::iterator NextI = next_nodbg(I, E);
1645   // Return the instruction following the merged instruction, which is
1646   // the instruction following our unmerged load. Unless that's the add/sub
1647   // instruction we're merging, in which case it's the one after that.
1648   if (NextI == Update)
1649     NextI = next_nodbg(NextI, E);
1650 
1651   int Value = Update->getOperand(2).getImm();
1652   assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
1653          "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
1654   if (Update->getOpcode() == AArch64::SUBXri)
1655     Value = -Value;
1656 
1657   unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
1658                              : getPostIndexedOpcode(I->getOpcode());
1659   MachineInstrBuilder MIB;
1660   int Scale, MinOffset, MaxOffset;
1661   getPrePostIndexedMemOpInfo(*I, Scale, MinOffset, MaxOffset);
1662   if (!isPairedLdSt(*I)) {
1663     // Non-paired instruction.
1664     MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1665               .add(getLdStRegOp(*Update))
1666               .add(getLdStRegOp(*I))
1667               .add(getLdStBaseOp(*I))
1668               .addImm(Value / Scale)
1669               .setMemRefs(I->memoperands())
1670               .setMIFlags(I->mergeFlagsWith(*Update));
1671   } else {
1672     // Paired instruction.
1673     MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1674               .add(getLdStRegOp(*Update))
1675               .add(getLdStRegOp(*I, 0))
1676               .add(getLdStRegOp(*I, 1))
1677               .add(getLdStBaseOp(*I))
1678               .addImm(Value / Scale)
1679               .setMemRefs(I->memoperands())
1680               .setMIFlags(I->mergeFlagsWith(*Update));
1681   }
1682   (void)MIB;
1683 
1684   if (IsPreIdx) {
1685     ++NumPreFolded;
1686     LLVM_DEBUG(dbgs() << "Creating pre-indexed load/store.");
1687   } else {
1688     ++NumPostFolded;
1689     LLVM_DEBUG(dbgs() << "Creating post-indexed load/store.");
1690   }
1691   LLVM_DEBUG(dbgs() << "    Replacing instructions:\n    ");
1692   LLVM_DEBUG(I->print(dbgs()));
1693   LLVM_DEBUG(dbgs() << "    ");
1694   LLVM_DEBUG(Update->print(dbgs()));
1695   LLVM_DEBUG(dbgs() << "  with instruction:\n    ");
1696   LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1697   LLVM_DEBUG(dbgs() << "\n");
1698 
1699   // Erase the old instructions for the block.
1700   I->eraseFromParent();
1701   Update->eraseFromParent();
1702 
1703   return NextI;
1704 }
1705 
1706 bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr &MemMI,
1707                                                MachineInstr &MI,
1708                                                unsigned BaseReg, int Offset) {
1709   switch (MI.getOpcode()) {
1710   default:
1711     break;
1712   case AArch64::SUBXri:
1713   case AArch64::ADDXri:
1714     // Make sure it's a vanilla immediate operand, not a relocation or
1715     // anything else we can't handle.
1716     if (!MI.getOperand(2).isImm())
1717       break;
1718     // Watch out for 1 << 12 shifted value.
1719     if (AArch64_AM::getShiftValue(MI.getOperand(3).getImm()))
1720       break;
1721 
1722     // The update instruction source and destination register must be the
1723     // same as the load/store base register.
1724     if (MI.getOperand(0).getReg() != BaseReg ||
1725         MI.getOperand(1).getReg() != BaseReg)
1726       break;
1727 
1728     int UpdateOffset = MI.getOperand(2).getImm();
1729     if (MI.getOpcode() == AArch64::SUBXri)
1730       UpdateOffset = -UpdateOffset;
1731 
1732     // The immediate must be a multiple of the scaling factor of the pre/post
1733     // indexed instruction.
1734     int Scale, MinOffset, MaxOffset;
1735     getPrePostIndexedMemOpInfo(MemMI, Scale, MinOffset, MaxOffset);
1736     if (UpdateOffset % Scale != 0)
1737       break;
1738 
1739     // Scaled offset must fit in the instruction immediate.
1740     int ScaledOffset = UpdateOffset / Scale;
1741     if (ScaledOffset > MaxOffset || ScaledOffset < MinOffset)
1742       break;
1743 
1744     // If we have a non-zero Offset, we check that it matches the amount
1745     // we're adding to the register.
1746     if (!Offset || Offset == UpdateOffset)
1747       return true;
1748     break;
1749   }
1750   return false;
1751 }
1752 
1753 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
1754     MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) {
1755   MachineBasicBlock::iterator E = I->getParent()->end();
1756   MachineInstr &MemMI = *I;
1757   MachineBasicBlock::iterator MBBI = I;
1758 
1759   Register BaseReg = getLdStBaseOp(MemMI).getReg();
1760   int MIUnscaledOffset = getLdStOffsetOp(MemMI).getImm() * TII->getMemScale(MemMI);
1761 
1762   // Scan forward looking for post-index opportunities.  Updating instructions
1763   // can't be formed if the memory instruction doesn't have the offset we're
1764   // looking for.
1765   if (MIUnscaledOffset != UnscaledOffset)
1766     return E;
1767 
1768   // If the base register overlaps a source/destination register, we can't
1769   // merge the update. This does not apply to tag store instructions which
1770   // ignore the address part of the source register.
1771   // This does not apply to STGPi as well, which does not have unpredictable
1772   // behavior in this case unlike normal stores, and always performs writeback
1773   // after reading the source register value.
1774   if (!isTagStore(MemMI) && MemMI.getOpcode() != AArch64::STGPi) {
1775     bool IsPairedInsn = isPairedLdSt(MemMI);
1776     for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1777       Register DestReg = getLdStRegOp(MemMI, i).getReg();
1778       if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1779         return E;
1780     }
1781   }
1782 
1783   // Track which register units have been modified and used between the first
1784   // insn (inclusive) and the second insn.
1785   ModifiedRegUnits.clear();
1786   UsedRegUnits.clear();
1787   MBBI = next_nodbg(MBBI, E);
1788 
1789   // We can't post-increment the stack pointer if any instruction between
1790   // the memory access (I) and the increment (MBBI) can access the memory
1791   // region defined by [SP, MBBI].
1792   const bool BaseRegSP = BaseReg == AArch64::SP;
1793   if (BaseRegSP) {
1794     // FIXME: For now, we always block the optimization over SP in windows
1795     // targets as it requires to adjust the unwind/debug info, messing up
1796     // the unwind info can actually cause a miscompile.
1797     const MCAsmInfo *MAI = I->getMF()->getTarget().getMCAsmInfo();
1798     if (MAI->usesWindowsCFI() &&
1799         I->getMF()->getFunction().needsUnwindTableEntry())
1800       return E;
1801   }
1802 
1803   for (unsigned Count = 0; MBBI != E && Count < Limit;
1804        MBBI = next_nodbg(MBBI, E)) {
1805     MachineInstr &MI = *MBBI;
1806 
1807     // Don't count transient instructions towards the search limit since there
1808     // may be different numbers of them if e.g. debug information is present.
1809     if (!MI.isTransient())
1810       ++Count;
1811 
1812     // If we found a match, return it.
1813     if (isMatchingUpdateInsn(*I, MI, BaseReg, UnscaledOffset))
1814       return MBBI;
1815 
1816     // Update the status of what the instruction clobbered and used.
1817     LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
1818 
1819     // Otherwise, if the base register is used or modified, we have no match, so
1820     // return early.
1821     // If we are optimizing SP, do not allow instructions that may load or store
1822     // in between the load and the optimized value update.
1823     if (!ModifiedRegUnits.available(BaseReg) ||
1824         !UsedRegUnits.available(BaseReg) ||
1825         (BaseRegSP && MBBI->mayLoadOrStore()))
1826       return E;
1827   }
1828   return E;
1829 }
1830 
1831 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
1832     MachineBasicBlock::iterator I, unsigned Limit) {
1833   MachineBasicBlock::iterator B = I->getParent()->begin();
1834   MachineBasicBlock::iterator E = I->getParent()->end();
1835   MachineInstr &MemMI = *I;
1836   MachineBasicBlock::iterator MBBI = I;
1837 
1838   Register BaseReg = getLdStBaseOp(MemMI).getReg();
1839   int Offset = getLdStOffsetOp(MemMI).getImm();
1840 
1841   // If the load/store is the first instruction in the block, there's obviously
1842   // not any matching update. Ditto if the memory offset isn't zero.
1843   if (MBBI == B || Offset != 0)
1844     return E;
1845   // If the base register overlaps a destination register, we can't
1846   // merge the update.
1847   if (!isTagStore(MemMI)) {
1848     bool IsPairedInsn = isPairedLdSt(MemMI);
1849     for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1850       Register DestReg = getLdStRegOp(MemMI, i).getReg();
1851       if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1852         return E;
1853     }
1854   }
1855 
1856   // Track which register units have been modified and used between the first
1857   // insn (inclusive) and the second insn.
1858   ModifiedRegUnits.clear();
1859   UsedRegUnits.clear();
1860   unsigned Count = 0;
1861   do {
1862     MBBI = prev_nodbg(MBBI, B);
1863     MachineInstr &MI = *MBBI;
1864 
1865     // Don't count transient instructions towards the search limit since there
1866     // may be different numbers of them if e.g. debug information is present.
1867     if (!MI.isTransient())
1868       ++Count;
1869 
1870     // If we found a match, return it.
1871     if (isMatchingUpdateInsn(*I, MI, BaseReg, Offset))
1872       return MBBI;
1873 
1874     // Update the status of what the instruction clobbered and used.
1875     LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
1876 
1877     // Otherwise, if the base register is used or modified, we have no match, so
1878     // return early.
1879     if (!ModifiedRegUnits.available(BaseReg) ||
1880         !UsedRegUnits.available(BaseReg))
1881       return E;
1882   } while (MBBI != B && Count < Limit);
1883   return E;
1884 }
1885 
1886 bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore(
1887     MachineBasicBlock::iterator &MBBI) {
1888   MachineInstr &MI = *MBBI;
1889   // If this is a volatile load, don't mess with it.
1890   if (MI.hasOrderedMemoryRef())
1891     return false;
1892 
1893   // Make sure this is a reg+imm.
1894   // FIXME: It is possible to extend it to handle reg+reg cases.
1895   if (!getLdStOffsetOp(MI).isImm())
1896     return false;
1897 
1898   // Look backward up to LdStLimit instructions.
1899   MachineBasicBlock::iterator StoreI;
1900   if (findMatchingStore(MBBI, LdStLimit, StoreI)) {
1901     ++NumLoadsFromStoresPromoted;
1902     // Promote the load. Keeping the iterator straight is a
1903     // pain, so we let the merge routine tell us what the next instruction
1904     // is after it's done mucking about.
1905     MBBI = promoteLoadFromStore(MBBI, StoreI);
1906     return true;
1907   }
1908   return false;
1909 }
1910 
1911 // Merge adjacent zero stores into a wider store.
1912 bool AArch64LoadStoreOpt::tryToMergeZeroStInst(
1913     MachineBasicBlock::iterator &MBBI) {
1914   assert(isPromotableZeroStoreInst(*MBBI) && "Expected narrow store.");
1915   MachineInstr &MI = *MBBI;
1916   MachineBasicBlock::iterator E = MI.getParent()->end();
1917 
1918   if (!TII->isCandidateToMergeOrPair(MI))
1919     return false;
1920 
1921   // Look ahead up to LdStLimit instructions for a mergable instruction.
1922   LdStPairFlags Flags;
1923   MachineBasicBlock::iterator MergeMI =
1924       findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ true);
1925   if (MergeMI != E) {
1926     ++NumZeroStoresPromoted;
1927 
1928     // Keeping the iterator straight is a pain, so we let the merge routine tell
1929     // us what the next instruction is after it's done mucking about.
1930     MBBI = mergeNarrowZeroStores(MBBI, MergeMI, Flags);
1931     return true;
1932   }
1933   return false;
1934 }
1935 
1936 // Find loads and stores that can be merged into a single load or store pair
1937 // instruction.
1938 bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
1939   MachineInstr &MI = *MBBI;
1940   MachineBasicBlock::iterator E = MI.getParent()->end();
1941 
1942   if (!TII->isCandidateToMergeOrPair(MI))
1943     return false;
1944 
1945   // Early exit if the offset is not possible to match. (6 bits of positive
1946   // range, plus allow an extra one in case we find a later insn that matches
1947   // with Offset-1)
1948   bool IsUnscaled = TII->isUnscaledLdSt(MI);
1949   int Offset = getLdStOffsetOp(MI).getImm();
1950   int OffsetStride = IsUnscaled ? TII->getMemScale(MI) : 1;
1951   // Allow one more for offset.
1952   if (Offset > 0)
1953     Offset -= OffsetStride;
1954   if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
1955     return false;
1956 
1957   // Look ahead up to LdStLimit instructions for a pairable instruction.
1958   LdStPairFlags Flags;
1959   MachineBasicBlock::iterator Paired =
1960       findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ false);
1961   if (Paired != E) {
1962     ++NumPairCreated;
1963     if (TII->isUnscaledLdSt(MI))
1964       ++NumUnscaledPairCreated;
1965     // Keeping the iterator straight is a pain, so we let the merge routine tell
1966     // us what the next instruction is after it's done mucking about.
1967     auto Prev = std::prev(MBBI);
1968     MBBI = mergePairedInsns(MBBI, Paired, Flags);
1969     // Collect liveness info for instructions between Prev and the new position
1970     // MBBI.
1971     for (auto I = std::next(Prev); I != MBBI; I++)
1972       updateDefinedRegisters(*I, DefinedInBB, TRI);
1973 
1974     return true;
1975   }
1976   return false;
1977 }
1978 
1979 bool AArch64LoadStoreOpt::tryToMergeLdStUpdate
1980     (MachineBasicBlock::iterator &MBBI) {
1981   MachineInstr &MI = *MBBI;
1982   MachineBasicBlock::iterator E = MI.getParent()->end();
1983   MachineBasicBlock::iterator Update;
1984 
1985   // Look forward to try to form a post-index instruction. For example,
1986   // ldr x0, [x20]
1987   // add x20, x20, #32
1988   //   merged into:
1989   // ldr x0, [x20], #32
1990   Update = findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit);
1991   if (Update != E) {
1992     // Merge the update into the ld/st.
1993     MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
1994     return true;
1995   }
1996 
1997   // Don't know how to handle unscaled pre/post-index versions below, so bail.
1998   if (TII->isUnscaledLdSt(MI.getOpcode()))
1999     return false;
2000 
2001   // Look back to try to find a pre-index instruction. For example,
2002   // add x0, x0, #8
2003   // ldr x1, [x0]
2004   //   merged into:
2005   // ldr x1, [x0, #8]!
2006   Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit);
2007   if (Update != E) {
2008     // Merge the update into the ld/st.
2009     MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
2010     return true;
2011   }
2012 
2013   // The immediate in the load/store is scaled by the size of the memory
2014   // operation. The immediate in the add we're looking for,
2015   // however, is not, so adjust here.
2016   int UnscaledOffset = getLdStOffsetOp(MI).getImm() * TII->getMemScale(MI);
2017 
2018   // Look forward to try to find a pre-index instruction. For example,
2019   // ldr x1, [x0, #64]
2020   // add x0, x0, #64
2021   //   merged into:
2022   // ldr x1, [x0, #64]!
2023   Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit);
2024   if (Update != E) {
2025     // Merge the update into the ld/st.
2026     MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
2027     return true;
2028   }
2029 
2030   return false;
2031 }
2032 
2033 bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
2034                                         bool EnableNarrowZeroStOpt) {
2035 
2036   bool Modified = false;
2037   // Four tranformations to do here:
2038   // 1) Find loads that directly read from stores and promote them by
2039   //    replacing with mov instructions. If the store is wider than the load,
2040   //    the load will be replaced with a bitfield extract.
2041   //      e.g.,
2042   //        str w1, [x0, #4]
2043   //        ldrh w2, [x0, #6]
2044   //        ; becomes
2045   //        str w1, [x0, #4]
2046   //        lsr w2, w1, #16
2047   for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
2048        MBBI != E;) {
2049     if (isPromotableLoadFromStore(*MBBI) && tryToPromoteLoadFromStore(MBBI))
2050       Modified = true;
2051     else
2052       ++MBBI;
2053   }
2054   // 2) Merge adjacent zero stores into a wider store.
2055   //      e.g.,
2056   //        strh wzr, [x0]
2057   //        strh wzr, [x0, #2]
2058   //        ; becomes
2059   //        str wzr, [x0]
2060   //      e.g.,
2061   //        str wzr, [x0]
2062   //        str wzr, [x0, #4]
2063   //        ; becomes
2064   //        str xzr, [x0]
2065   if (EnableNarrowZeroStOpt)
2066     for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
2067          MBBI != E;) {
2068       if (isPromotableZeroStoreInst(*MBBI) && tryToMergeZeroStInst(MBBI))
2069         Modified = true;
2070       else
2071         ++MBBI;
2072     }
2073   // 3) Find loads and stores that can be merged into a single load or store
2074   //    pair instruction.
2075   //      e.g.,
2076   //        ldr x0, [x2]
2077   //        ldr x1, [x2, #8]
2078   //        ; becomes
2079   //        ldp x0, x1, [x2]
2080 
2081   if (MBB.getParent()->getRegInfo().tracksLiveness()) {
2082     DefinedInBB.clear();
2083     DefinedInBB.addLiveIns(MBB);
2084   }
2085 
2086   for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
2087        MBBI != E;) {
2088     // Track currently live registers up to this point, to help with
2089     // searching for a rename register on demand.
2090     updateDefinedRegisters(*MBBI, DefinedInBB, TRI);
2091     if (TII->isPairableLdStInst(*MBBI) && tryToPairLdStInst(MBBI))
2092       Modified = true;
2093     else
2094       ++MBBI;
2095   }
2096   // 4) Find base register updates that can be merged into the load or store
2097   //    as a base-reg writeback.
2098   //      e.g.,
2099   //        ldr x0, [x2]
2100   //        add x2, x2, #4
2101   //        ; becomes
2102   //        ldr x0, [x2], #4
2103   for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
2104        MBBI != E;) {
2105     if (isMergeableLdStUpdate(*MBBI) && tryToMergeLdStUpdate(MBBI))
2106       Modified = true;
2107     else
2108       ++MBBI;
2109   }
2110 
2111   return Modified;
2112 }
2113 
2114 bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
2115   if (skipFunction(Fn.getFunction()))
2116     return false;
2117 
2118   Subtarget = &static_cast<const AArch64Subtarget &>(Fn.getSubtarget());
2119   TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo());
2120   TRI = Subtarget->getRegisterInfo();
2121   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2122 
2123   // Resize the modified and used register unit trackers.  We do this once
2124   // per function and then clear the register units each time we optimize a load
2125   // or store.
2126   ModifiedRegUnits.init(*TRI);
2127   UsedRegUnits.init(*TRI);
2128   DefinedInBB.init(*TRI);
2129 
2130   bool Modified = false;
2131   bool enableNarrowZeroStOpt = !Subtarget->requiresStrictAlign();
2132   for (auto &MBB : Fn) {
2133     auto M = optimizeBlock(MBB, enableNarrowZeroStOpt);
2134     Modified |= M;
2135   }
2136 
2137   return Modified;
2138 }
2139 
2140 // FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep loads and
2141 // stores near one another?  Note: The pre-RA instruction scheduler already has
2142 // hooks to try and schedule pairable loads/stores together to improve pairing
2143 // opportunities.  Thus, pre-RA pairing pass may not be worth the effort.
2144 
2145 // FIXME: When pairing store instructions it's very possible for this pass to
2146 // hoist a store with a KILL marker above another use (without a KILL marker).
2147 // The resulting IR is invalid, but nothing uses the KILL markers after this
2148 // pass, so it's never caused a problem in practice.
2149 
2150 /// createAArch64LoadStoreOptimizationPass - returns an instance of the
2151 /// load / store optimization pass.
2152 FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
2153   return new AArch64LoadStoreOpt();
2154 }
2155