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