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 NextI = I;
682   ++NextI;
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;
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 (MachineBasicBlock::reverse_iterator I = MI.getReverseIterator(),
752                                            E = MBB->rend();
753        I != E; I++) {
754     if (!Limit)
755       return false;
756     --Limit;
757 
758     bool isDef = any_of(I->operands(), [DefReg, TRI](MachineOperand &MOP) {
759       return MOP.isReg() && MOP.isDef() && !MOP.isDebug() && MOP.getReg() &&
760              TRI->regsOverlap(MOP.getReg(), DefReg);
761     });
762     if (!Fn(*I, isDef))
763       return false;
764     if (isDef)
765       break;
766   }
767   return true;
768 }
769 
770 static void updateDefinedRegisters(MachineInstr &MI, LiveRegUnits &Units,
771                                    const TargetRegisterInfo *TRI) {
772 
773   for (const MachineOperand &MOP : phys_regs_and_masks(MI))
774     if (MOP.isReg() && MOP.isKill())
775       Units.removeReg(MOP.getReg());
776 
777   for (const MachineOperand &MOP : phys_regs_and_masks(MI))
778     if (MOP.isReg() && !MOP.isKill())
779       Units.addReg(MOP.getReg());
780 }
781 
782 MachineBasicBlock::iterator
783 AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
784                                       MachineBasicBlock::iterator Paired,
785                                       const LdStPairFlags &Flags) {
786   MachineBasicBlock::iterator NextI = I;
787   ++NextI;
788   // If NextI is the second of the two instructions to be merged, we need
789   // to skip one further. Either way we merge will invalidate the iterator,
790   // and we don't need to scan the new instruction, as it's a pairwise
791   // instruction, which we're not considering for further action anyway.
792   if (NextI == Paired)
793     ++NextI;
794 
795   int SExtIdx = Flags.getSExtIdx();
796   unsigned Opc =
797       SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
798   bool IsUnscaled = TII->isUnscaledLdSt(Opc);
799   int OffsetStride = IsUnscaled ? TII->getMemScale(*I) : 1;
800 
801   bool MergeForward = Flags.getMergeForward();
802 
803   Optional<MCPhysReg> RenameReg = Flags.getRenameReg();
804   if (MergeForward && RenameReg) {
805     MCRegister RegToRename = getLdStRegOp(*I).getReg();
806     DefinedInBB.addReg(*RenameReg);
807 
808     // Return the sub/super register for RenameReg, matching the size of
809     // OriginalReg.
810     auto GetMatchingSubReg = [this,
811                               RenameReg](MCPhysReg OriginalReg) -> MCPhysReg {
812       for (MCPhysReg SubOrSuper : TRI->sub_and_superregs_inclusive(*RenameReg))
813         if (TRI->getMinimalPhysRegClass(OriginalReg) ==
814             TRI->getMinimalPhysRegClass(SubOrSuper))
815           return SubOrSuper;
816       llvm_unreachable("Should have found matching sub or super register!");
817     };
818 
819     std::function<bool(MachineInstr &, bool)> UpdateMIs =
820         [this, RegToRename, GetMatchingSubReg](MachineInstr &MI, bool IsDef) {
821           if (IsDef) {
822             bool SeenDef = false;
823             for (auto &MOP : MI.operands()) {
824               // Rename the first explicit definition and all implicit
825               // definitions matching RegToRename.
826               if (MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
827                   (!SeenDef || (MOP.isDef() && MOP.isImplicit())) &&
828                   TRI->regsOverlap(MOP.getReg(), RegToRename)) {
829                 assert((MOP.isImplicit() ||
830                         (MOP.isRenamable() && !MOP.isEarlyClobber())) &&
831                        "Need renamable operands");
832                 MOP.setReg(GetMatchingSubReg(MOP.getReg()));
833                 SeenDef = true;
834               }
835             }
836           } else {
837             for (auto &MOP : MI.operands()) {
838               if (MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
839                   TRI->regsOverlap(MOP.getReg(), RegToRename)) {
840                 assert((MOP.isImplicit() ||
841                         (MOP.isRenamable() && !MOP.isEarlyClobber())) &&
842                            "Need renamable operands");
843                 MOP.setReg(GetMatchingSubReg(MOP.getReg()));
844               }
845             }
846           }
847           LLVM_DEBUG(dbgs() << "Renamed " << MI << "\n");
848           return true;
849         };
850     forAllMIsUntilDef(*I, RegToRename, TRI, LdStLimit, UpdateMIs);
851 
852 #if !defined(NDEBUG)
853     // Make sure the register used for renaming is not used between the paired
854     // instructions. That would trash the content before the new paired
855     // instruction.
856     for (auto &MI :
857          iterator_range<MachineInstrBundleIterator<llvm::MachineInstr>>(
858              std::next(I), std::next(Paired)))
859       assert(all_of(MI.operands(),
860                     [this, &RenameReg](const MachineOperand &MOP) {
861                       return !MOP.isReg() || MOP.isDebug() || !MOP.getReg() ||
862                              !TRI->regsOverlap(MOP.getReg(), *RenameReg);
863                     }) &&
864              "Rename register used between paired instruction, trashing the "
865              "content");
866 #endif
867   }
868 
869   // Insert our new paired instruction after whichever of the paired
870   // instructions MergeForward indicates.
871   MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
872   // Also based on MergeForward is from where we copy the base register operand
873   // so we get the flags compatible with the input code.
874   const MachineOperand &BaseRegOp =
875       MergeForward ? getLdStBaseOp(*Paired) : getLdStBaseOp(*I);
876 
877   int Offset = getLdStOffsetOp(*I).getImm();
878   int PairedOffset = getLdStOffsetOp(*Paired).getImm();
879   bool PairedIsUnscaled = TII->isUnscaledLdSt(Paired->getOpcode());
880   if (IsUnscaled != PairedIsUnscaled) {
881     // We're trying to pair instructions that differ in how they are scaled.  If
882     // I is scaled then scale the offset of Paired accordingly.  Otherwise, do
883     // the opposite (i.e., make Paired's offset unscaled).
884     int MemSize = TII->getMemScale(*Paired);
885     if (PairedIsUnscaled) {
886       // If the unscaled offset isn't a multiple of the MemSize, we can't
887       // pair the operations together.
888       assert(!(PairedOffset % TII->getMemScale(*Paired)) &&
889              "Offset should be a multiple of the stride!");
890       PairedOffset /= MemSize;
891     } else {
892       PairedOffset *= MemSize;
893     }
894   }
895 
896   // Which register is Rt and which is Rt2 depends on the offset order.
897   MachineInstr *RtMI, *Rt2MI;
898   if (Offset == PairedOffset + OffsetStride) {
899     RtMI = &*Paired;
900     Rt2MI = &*I;
901     // Here we swapped the assumption made for SExtIdx.
902     // I.e., we turn ldp I, Paired into ldp Paired, I.
903     // Update the index accordingly.
904     if (SExtIdx != -1)
905       SExtIdx = (SExtIdx + 1) % 2;
906   } else {
907     RtMI = &*I;
908     Rt2MI = &*Paired;
909   }
910   int OffsetImm = getLdStOffsetOp(*RtMI).getImm();
911   // Scale the immediate offset, if necessary.
912   if (TII->isUnscaledLdSt(RtMI->getOpcode())) {
913     assert(!(OffsetImm % TII->getMemScale(*RtMI)) &&
914            "Unscaled offset cannot be scaled.");
915     OffsetImm /= TII->getMemScale(*RtMI);
916   }
917 
918   // Construct the new instruction.
919   MachineInstrBuilder MIB;
920   DebugLoc DL = I->getDebugLoc();
921   MachineBasicBlock *MBB = I->getParent();
922   MachineOperand RegOp0 = getLdStRegOp(*RtMI);
923   MachineOperand RegOp1 = getLdStRegOp(*Rt2MI);
924   // Kill flags may become invalid when moving stores for pairing.
925   if (RegOp0.isUse()) {
926     if (!MergeForward) {
927       // Clear kill flags on store if moving upwards. Example:
928       //   STRWui %w0, ...
929       //   USE %w1
930       //   STRWui kill %w1  ; need to clear kill flag when moving STRWui upwards
931       RegOp0.setIsKill(false);
932       RegOp1.setIsKill(false);
933     } else {
934       // Clear kill flags of the first stores register. Example:
935       //   STRWui %w1, ...
936       //   USE kill %w1   ; need to clear kill flag when moving STRWui downwards
937       //   STRW %w0
938       Register Reg = getLdStRegOp(*I).getReg();
939       for (MachineInstr &MI : make_range(std::next(I), Paired))
940         MI.clearRegisterKills(Reg, TRI);
941     }
942   }
943   MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingPairOpcode(Opc)))
944             .add(RegOp0)
945             .add(RegOp1)
946             .add(BaseRegOp)
947             .addImm(OffsetImm)
948             .cloneMergedMemRefs({&*I, &*Paired})
949             .setMIFlags(I->mergeFlagsWith(*Paired));
950 
951   (void)MIB;
952 
953   LLVM_DEBUG(
954       dbgs() << "Creating pair load/store. Replacing instructions:\n    ");
955   LLVM_DEBUG(I->print(dbgs()));
956   LLVM_DEBUG(dbgs() << "    ");
957   LLVM_DEBUG(Paired->print(dbgs()));
958   LLVM_DEBUG(dbgs() << "  with instruction:\n    ");
959   if (SExtIdx != -1) {
960     // Generate the sign extension for the proper result of the ldp.
961     // I.e., with X1, that would be:
962     // %w1 = KILL %w1, implicit-def %x1
963     // %x1 = SBFMXri killed %x1, 0, 31
964     MachineOperand &DstMO = MIB->getOperand(SExtIdx);
965     // Right now, DstMO has the extended register, since it comes from an
966     // extended opcode.
967     Register DstRegX = DstMO.getReg();
968     // Get the W variant of that register.
969     Register DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
970     // Update the result of LDP to use the W instead of the X variant.
971     DstMO.setReg(DstRegW);
972     LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
973     LLVM_DEBUG(dbgs() << "\n");
974     // Make the machine verifier happy by providing a definition for
975     // the X register.
976     // Insert this definition right after the generated LDP, i.e., before
977     // InsertionPoint.
978     MachineInstrBuilder MIBKill =
979         BuildMI(*MBB, InsertionPoint, DL, TII->get(TargetOpcode::KILL), DstRegW)
980             .addReg(DstRegW)
981             .addReg(DstRegX, RegState::Define);
982     MIBKill->getOperand(2).setImplicit();
983     // Create the sign extension.
984     MachineInstrBuilder MIBSXTW =
985         BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::SBFMXri), DstRegX)
986             .addReg(DstRegX)
987             .addImm(0)
988             .addImm(31);
989     (void)MIBSXTW;
990     LLVM_DEBUG(dbgs() << "  Extend operand:\n    ");
991     LLVM_DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
992   } else {
993     LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
994   }
995   LLVM_DEBUG(dbgs() << "\n");
996 
997   if (MergeForward)
998     for (const MachineOperand &MOP : phys_regs_and_masks(*I))
999       if (MOP.isReg() && MOP.isKill())
1000         DefinedInBB.addReg(MOP.getReg());
1001 
1002   // Erase the old instructions.
1003   I->eraseFromParent();
1004   Paired->eraseFromParent();
1005 
1006   return NextI;
1007 }
1008 
1009 MachineBasicBlock::iterator
1010 AArch64LoadStoreOpt::promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
1011                                           MachineBasicBlock::iterator StoreI) {
1012   MachineBasicBlock::iterator NextI = LoadI;
1013   ++NextI;
1014 
1015   int LoadSize = TII->getMemScale(*LoadI);
1016   int StoreSize = TII->getMemScale(*StoreI);
1017   Register LdRt = getLdStRegOp(*LoadI).getReg();
1018   const MachineOperand &StMO = getLdStRegOp(*StoreI);
1019   Register StRt = getLdStRegOp(*StoreI).getReg();
1020   bool IsStoreXReg = TRI->getRegClass(AArch64::GPR64RegClassID)->contains(StRt);
1021 
1022   assert((IsStoreXReg ||
1023           TRI->getRegClass(AArch64::GPR32RegClassID)->contains(StRt)) &&
1024          "Unexpected RegClass");
1025 
1026   MachineInstr *BitExtMI;
1027   if (LoadSize == StoreSize && (LoadSize == 4 || LoadSize == 8)) {
1028     // Remove the load, if the destination register of the loads is the same
1029     // register for stored value.
1030     if (StRt == LdRt && LoadSize == 8) {
1031       for (MachineInstr &MI : make_range(StoreI->getIterator(),
1032                                          LoadI->getIterator())) {
1033         if (MI.killsRegister(StRt, TRI)) {
1034           MI.clearRegisterKills(StRt, TRI);
1035           break;
1036         }
1037       }
1038       LLVM_DEBUG(dbgs() << "Remove load instruction:\n    ");
1039       LLVM_DEBUG(LoadI->print(dbgs()));
1040       LLVM_DEBUG(dbgs() << "\n");
1041       LoadI->eraseFromParent();
1042       return NextI;
1043     }
1044     // Replace the load with a mov if the load and store are in the same size.
1045     BitExtMI =
1046         BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1047                 TII->get(IsStoreXReg ? AArch64::ORRXrs : AArch64::ORRWrs), LdRt)
1048             .addReg(IsStoreXReg ? AArch64::XZR : AArch64::WZR)
1049             .add(StMO)
1050             .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0))
1051             .setMIFlags(LoadI->getFlags());
1052   } else {
1053     // FIXME: Currently we disable this transformation in big-endian targets as
1054     // performance and correctness are verified only in little-endian.
1055     if (!Subtarget->isLittleEndian())
1056       return NextI;
1057     bool IsUnscaled = TII->isUnscaledLdSt(*LoadI);
1058     assert(IsUnscaled == TII->isUnscaledLdSt(*StoreI) &&
1059            "Unsupported ld/st match");
1060     assert(LoadSize <= StoreSize && "Invalid load size");
1061     int UnscaledLdOffset = IsUnscaled
1062                                ? getLdStOffsetOp(*LoadI).getImm()
1063                                : getLdStOffsetOp(*LoadI).getImm() * LoadSize;
1064     int UnscaledStOffset = IsUnscaled
1065                                ? getLdStOffsetOp(*StoreI).getImm()
1066                                : getLdStOffsetOp(*StoreI).getImm() * StoreSize;
1067     int Width = LoadSize * 8;
1068     unsigned DestReg =
1069         IsStoreXReg ? Register(TRI->getMatchingSuperReg(
1070                           LdRt, AArch64::sub_32, &AArch64::GPR64RegClass))
1071                     : LdRt;
1072 
1073     assert((UnscaledLdOffset >= UnscaledStOffset &&
1074             (UnscaledLdOffset + LoadSize) <= UnscaledStOffset + StoreSize) &&
1075            "Invalid offset");
1076 
1077     int Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
1078     int Imms = Immr + Width - 1;
1079     if (UnscaledLdOffset == UnscaledStOffset) {
1080       uint32_t AndMaskEncoded = ((IsStoreXReg ? 1 : 0) << 12) // N
1081                                 | ((Immr) << 6)               // immr
1082                                 | ((Imms) << 0)               // imms
1083           ;
1084 
1085       BitExtMI =
1086           BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1087                   TII->get(IsStoreXReg ? AArch64::ANDXri : AArch64::ANDWri),
1088                   DestReg)
1089               .add(StMO)
1090               .addImm(AndMaskEncoded)
1091               .setMIFlags(LoadI->getFlags());
1092     } else {
1093       BitExtMI =
1094           BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1095                   TII->get(IsStoreXReg ? AArch64::UBFMXri : AArch64::UBFMWri),
1096                   DestReg)
1097               .add(StMO)
1098               .addImm(Immr)
1099               .addImm(Imms)
1100               .setMIFlags(LoadI->getFlags());
1101     }
1102   }
1103 
1104   // Clear kill flags between store and load.
1105   for (MachineInstr &MI : make_range(StoreI->getIterator(),
1106                                      BitExtMI->getIterator()))
1107     if (MI.killsRegister(StRt, TRI)) {
1108       MI.clearRegisterKills(StRt, TRI);
1109       break;
1110     }
1111 
1112   LLVM_DEBUG(dbgs() << "Promoting load by replacing :\n    ");
1113   LLVM_DEBUG(StoreI->print(dbgs()));
1114   LLVM_DEBUG(dbgs() << "    ");
1115   LLVM_DEBUG(LoadI->print(dbgs()));
1116   LLVM_DEBUG(dbgs() << "  with instructions:\n    ");
1117   LLVM_DEBUG(StoreI->print(dbgs()));
1118   LLVM_DEBUG(dbgs() << "    ");
1119   LLVM_DEBUG((BitExtMI)->print(dbgs()));
1120   LLVM_DEBUG(dbgs() << "\n");
1121 
1122   // Erase the old instructions.
1123   LoadI->eraseFromParent();
1124   return NextI;
1125 }
1126 
1127 static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
1128   // Convert the byte-offset used by unscaled into an "element" offset used
1129   // by the scaled pair load/store instructions.
1130   if (IsUnscaled) {
1131     // If the byte-offset isn't a multiple of the stride, there's no point
1132     // trying to match it.
1133     if (Offset % OffsetStride)
1134       return false;
1135     Offset /= OffsetStride;
1136   }
1137   return Offset <= 63 && Offset >= -64;
1138 }
1139 
1140 // Do alignment, specialized to power of 2 and for signed ints,
1141 // avoiding having to do a C-style cast from uint_64t to int when
1142 // using alignTo from include/llvm/Support/MathExtras.h.
1143 // FIXME: Move this function to include/MathExtras.h?
1144 static int alignTo(int Num, int PowOf2) {
1145   return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
1146 }
1147 
1148 static bool mayAlias(MachineInstr &MIa, MachineInstr &MIb,
1149                      AliasAnalysis *AA) {
1150   // One of the instructions must modify memory.
1151   if (!MIa.mayStore() && !MIb.mayStore())
1152     return false;
1153 
1154   // Both instructions must be memory operations.
1155   if (!MIa.mayLoadOrStore() && !MIb.mayLoadOrStore())
1156     return false;
1157 
1158   return MIa.mayAlias(AA, MIb, /*UseTBAA*/false);
1159 }
1160 
1161 static bool mayAlias(MachineInstr &MIa,
1162                      SmallVectorImpl<MachineInstr *> &MemInsns,
1163                      AliasAnalysis *AA) {
1164   for (MachineInstr *MIb : MemInsns)
1165     if (mayAlias(MIa, *MIb, AA))
1166       return true;
1167 
1168   return false;
1169 }
1170 
1171 bool AArch64LoadStoreOpt::findMatchingStore(
1172     MachineBasicBlock::iterator I, unsigned Limit,
1173     MachineBasicBlock::iterator &StoreI) {
1174   MachineBasicBlock::iterator B = I->getParent()->begin();
1175   MachineBasicBlock::iterator MBBI = I;
1176   MachineInstr &LoadMI = *I;
1177   Register BaseReg = getLdStBaseOp(LoadMI).getReg();
1178 
1179   // If the load is the first instruction in the block, there's obviously
1180   // not any matching store.
1181   if (MBBI == B)
1182     return false;
1183 
1184   // Track which register units have been modified and used between the first
1185   // insn and the second insn.
1186   ModifiedRegUnits.clear();
1187   UsedRegUnits.clear();
1188 
1189   unsigned Count = 0;
1190   do {
1191     --MBBI;
1192     MachineInstr &MI = *MBBI;
1193 
1194     // Don't count transient instructions towards the search limit since there
1195     // may be different numbers of them if e.g. debug information is present.
1196     if (!MI.isTransient())
1197       ++Count;
1198 
1199     // If the load instruction reads directly from the address to which the
1200     // store instruction writes and the stored value is not modified, we can
1201     // promote the load. Since we do not handle stores with pre-/post-index,
1202     // it's unnecessary to check if BaseReg is modified by the store itself.
1203     if (MI.mayStore() && isMatchingStore(LoadMI, MI) &&
1204         BaseReg == getLdStBaseOp(MI).getReg() &&
1205         isLdOffsetInRangeOfSt(LoadMI, MI, TII) &&
1206         ModifiedRegUnits.available(getLdStRegOp(MI).getReg())) {
1207       StoreI = MBBI;
1208       return true;
1209     }
1210 
1211     if (MI.isCall())
1212       return false;
1213 
1214     // Update modified / uses register units.
1215     LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
1216 
1217     // Otherwise, if the base register is modified, we have no match, so
1218     // return early.
1219     if (!ModifiedRegUnits.available(BaseReg))
1220       return false;
1221 
1222     // If we encounter a store aliased with the load, return early.
1223     if (MI.mayStore() && mayAlias(LoadMI, MI, AA))
1224       return false;
1225   } while (MBBI != B && Count < Limit);
1226   return false;
1227 }
1228 
1229 // Returns true if FirstMI and MI are candidates for merging or pairing.
1230 // Otherwise, returns false.
1231 static bool areCandidatesToMergeOrPair(MachineInstr &FirstMI, MachineInstr &MI,
1232                                        LdStPairFlags &Flags,
1233                                        const AArch64InstrInfo *TII) {
1234   // If this is volatile or if pairing is suppressed, not a candidate.
1235   if (MI.hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
1236     return false;
1237 
1238   // We should have already checked FirstMI for pair suppression and volatility.
1239   assert(!FirstMI.hasOrderedMemoryRef() &&
1240          !TII->isLdStPairSuppressed(FirstMI) &&
1241          "FirstMI shouldn't get here if either of these checks are true.");
1242 
1243   unsigned OpcA = FirstMI.getOpcode();
1244   unsigned OpcB = MI.getOpcode();
1245 
1246   // Opcodes match: nothing more to check.
1247   if (OpcA == OpcB)
1248     return true;
1249 
1250   // Try to match a sign-extended load/store with a zero-extended load/store.
1251   bool IsValidLdStrOpc, PairIsValidLdStrOpc;
1252   unsigned NonSExtOpc = getMatchingNonSExtOpcode(OpcA, &IsValidLdStrOpc);
1253   assert(IsValidLdStrOpc &&
1254          "Given Opc should be a Load or Store with an immediate");
1255   // OpcA will be the first instruction in the pair.
1256   if (NonSExtOpc == getMatchingNonSExtOpcode(OpcB, &PairIsValidLdStrOpc)) {
1257     Flags.setSExtIdx(NonSExtOpc == (unsigned)OpcA ? 1 : 0);
1258     return true;
1259   }
1260 
1261   // If the second instruction isn't even a mergable/pairable load/store, bail
1262   // out.
1263   if (!PairIsValidLdStrOpc)
1264     return false;
1265 
1266   // FIXME: We don't support merging narrow stores with mixed scaled/unscaled
1267   // offsets.
1268   if (isNarrowStore(OpcA) || isNarrowStore(OpcB))
1269     return false;
1270 
1271   // Try to match an unscaled load/store with a scaled load/store.
1272   return TII->isUnscaledLdSt(OpcA) != TII->isUnscaledLdSt(OpcB) &&
1273          getMatchingPairOpcode(OpcA) == getMatchingPairOpcode(OpcB);
1274 
1275   // FIXME: Can we also match a mixed sext/zext unscaled/scaled pair?
1276 }
1277 
1278 static bool
1279 canRenameUpToDef(MachineInstr &FirstMI, LiveRegUnits &UsedInBetween,
1280                  SmallPtrSetImpl<const TargetRegisterClass *> &RequiredClasses,
1281                  const TargetRegisterInfo *TRI) {
1282   if (!FirstMI.mayStore())
1283     return false;
1284 
1285   // Check if we can find an unused register which we can use to rename
1286   // the register used by the first load/store.
1287   auto *RegClass = TRI->getMinimalPhysRegClass(getLdStRegOp(FirstMI).getReg());
1288   MachineFunction &MF = *FirstMI.getParent()->getParent();
1289   if (!RegClass || !MF.getRegInfo().tracksLiveness())
1290     return false;
1291 
1292   auto RegToRename = getLdStRegOp(FirstMI).getReg();
1293   // For now, we only rename if the store operand gets killed at the store.
1294   if (!getLdStRegOp(FirstMI).isKill() &&
1295       !any_of(FirstMI.operands(),
1296               [TRI, RegToRename](const MachineOperand &MOP) {
1297                 return MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
1298                        MOP.isImplicit() && MOP.isKill() &&
1299                        TRI->regsOverlap(RegToRename, MOP.getReg());
1300               })) {
1301     LLVM_DEBUG(dbgs() << "  Operand not killed at " << FirstMI << "\n");
1302     return false;
1303   }
1304   auto canRenameMOP = [](const MachineOperand &MOP) {
1305     return MOP.isImplicit() ||
1306            (MOP.isRenamable() && !MOP.isEarlyClobber() && !MOP.isTied());
1307   };
1308 
1309   bool FoundDef = false;
1310 
1311   // For each instruction between FirstMI and the previous def for RegToRename,
1312   // we
1313   // * check if we can rename RegToRename in this instruction
1314   // * collect the registers used and required register classes for RegToRename.
1315   std::function<bool(MachineInstr &, bool)> CheckMIs = [&](MachineInstr &MI,
1316                                                            bool IsDef) {
1317     LLVM_DEBUG(dbgs() << "Checking " << MI << "\n");
1318     // Currently we do not try to rename across frame-setup instructions.
1319     if (MI.getFlag(MachineInstr::FrameSetup)) {
1320       LLVM_DEBUG(dbgs() << "  Cannot rename framesetup instructions currently ("
1321                         << MI << ")\n");
1322       return false;
1323     }
1324 
1325     UsedInBetween.accumulate(MI);
1326 
1327     // For a definition, check that we can rename the definition and exit the
1328     // loop.
1329     FoundDef = IsDef;
1330 
1331     // For defs, check if we can rename the first def of RegToRename.
1332     if (FoundDef) {
1333       // For some pseudo instructions, we might not generate code in the end
1334       // (e.g. KILL) and we would end up without a correct def for the rename
1335       // register.
1336       // TODO: This might be overly conservative and we could handle those cases
1337       // in multiple ways:
1338       //       1. Insert an extra copy, to materialize the def.
1339       //       2. Skip pseudo-defs until we find an non-pseudo def.
1340       if (MI.isPseudo()) {
1341         LLVM_DEBUG(dbgs() << "  Cannot rename pseudo instruction " << MI
1342                           << "\n");
1343         return false;
1344       }
1345 
1346       for (auto &MOP : MI.operands()) {
1347         if (!MOP.isReg() || !MOP.isDef() || MOP.isDebug() || !MOP.getReg() ||
1348             !TRI->regsOverlap(MOP.getReg(), RegToRename))
1349           continue;
1350         if (!canRenameMOP(MOP)) {
1351           LLVM_DEBUG(dbgs()
1352                      << "  Cannot rename " << MOP << " in " << MI << "\n");
1353           return false;
1354         }
1355         RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
1356       }
1357       return true;
1358     } else {
1359       for (auto &MOP : MI.operands()) {
1360         if (!MOP.isReg() || MOP.isDebug() || !MOP.getReg() ||
1361             !TRI->regsOverlap(MOP.getReg(), RegToRename))
1362           continue;
1363 
1364         if (!canRenameMOP(MOP)) {
1365           LLVM_DEBUG(dbgs()
1366                      << "  Cannot rename " << MOP << " in " << MI << "\n");
1367           return false;
1368         }
1369         RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
1370       }
1371     }
1372     return true;
1373   };
1374 
1375   if (!forAllMIsUntilDef(FirstMI, RegToRename, TRI, LdStLimit, CheckMIs))
1376     return false;
1377 
1378   if (!FoundDef) {
1379     LLVM_DEBUG(dbgs() << "  Did not find definition for register in BB\n");
1380     return false;
1381   }
1382   return true;
1383 }
1384 
1385 // Check if we can find a physical register for renaming. This register must:
1386 // * not be defined up to FirstMI (checking DefinedInBB)
1387 // * not used between the MI and the defining instruction of the register to
1388 //   rename (checked using UsedInBetween).
1389 // * is available in all used register classes (checked using RequiredClasses).
1390 static Optional<MCPhysReg> tryToFindRegisterToRename(
1391     MachineInstr &FirstMI, MachineInstr &MI, LiveRegUnits &DefinedInBB,
1392     LiveRegUnits &UsedInBetween,
1393     SmallPtrSetImpl<const TargetRegisterClass *> &RequiredClasses,
1394     const TargetRegisterInfo *TRI) {
1395   auto &MF = *FirstMI.getParent()->getParent();
1396   MachineRegisterInfo &RegInfo = MF.getRegInfo();
1397 
1398   // Checks if any sub- or super-register of PR is callee saved.
1399   auto AnySubOrSuperRegCalleePreserved = [&MF, TRI](MCPhysReg PR) {
1400     return any_of(TRI->sub_and_superregs_inclusive(PR),
1401                   [&MF, TRI](MCPhysReg SubOrSuper) {
1402                     return TRI->isCalleeSavedPhysReg(SubOrSuper, MF);
1403                   });
1404   };
1405 
1406   // Check if PR or one of its sub- or super-registers can be used for all
1407   // required register classes.
1408   auto CanBeUsedForAllClasses = [&RequiredClasses, TRI](MCPhysReg PR) {
1409     return all_of(RequiredClasses, [PR, TRI](const TargetRegisterClass *C) {
1410       return any_of(TRI->sub_and_superregs_inclusive(PR),
1411                     [C, TRI](MCPhysReg SubOrSuper) {
1412                       return C == TRI->getMinimalPhysRegClass(SubOrSuper);
1413                     });
1414     });
1415   };
1416 
1417   auto *RegClass = TRI->getMinimalPhysRegClass(getLdStRegOp(FirstMI).getReg());
1418   for (const MCPhysReg &PR : *RegClass) {
1419     if (DefinedInBB.available(PR) && UsedInBetween.available(PR) &&
1420         !RegInfo.isReserved(PR) && !AnySubOrSuperRegCalleePreserved(PR) &&
1421         CanBeUsedForAllClasses(PR)) {
1422       DefinedInBB.addReg(PR);
1423       LLVM_DEBUG(dbgs() << "Found rename register " << printReg(PR, TRI)
1424                         << "\n");
1425       return {PR};
1426     }
1427   }
1428   LLVM_DEBUG(dbgs() << "No rename register found from "
1429                     << TRI->getRegClassName(RegClass) << "\n");
1430   return None;
1431 }
1432 
1433 /// Scan the instructions looking for a load/store that can be combined with the
1434 /// current instruction into a wider equivalent or a load/store pair.
1435 MachineBasicBlock::iterator
1436 AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
1437                                       LdStPairFlags &Flags, unsigned Limit,
1438                                       bool FindNarrowMerge) {
1439   MachineBasicBlock::iterator E = I->getParent()->end();
1440   MachineBasicBlock::iterator MBBI = I;
1441   MachineBasicBlock::iterator MBBIWithRenameReg;
1442   MachineInstr &FirstMI = *I;
1443   ++MBBI;
1444 
1445   bool MayLoad = FirstMI.mayLoad();
1446   bool IsUnscaled = TII->isUnscaledLdSt(FirstMI);
1447   Register Reg = getLdStRegOp(FirstMI).getReg();
1448   Register BaseReg = getLdStBaseOp(FirstMI).getReg();
1449   int Offset = getLdStOffsetOp(FirstMI).getImm();
1450   int OffsetStride = IsUnscaled ? TII->getMemScale(FirstMI) : 1;
1451   bool IsPromotableZeroStore = isPromotableZeroStoreInst(FirstMI);
1452 
1453   Optional<bool> MaybeCanRename = None;
1454   if (!EnableRenaming)
1455     MaybeCanRename = {false};
1456 
1457   SmallPtrSet<const TargetRegisterClass *, 5> RequiredClasses;
1458   LiveRegUnits UsedInBetween;
1459   UsedInBetween.init(*TRI);
1460 
1461   Flags.clearRenameReg();
1462 
1463   // Track which register units have been modified and used between the first
1464   // insn (inclusive) and the second insn.
1465   ModifiedRegUnits.clear();
1466   UsedRegUnits.clear();
1467 
1468   // Remember any instructions that read/write memory between FirstMI and MI.
1469   SmallVector<MachineInstr *, 4> MemInsns;
1470 
1471   for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
1472     MachineInstr &MI = *MBBI;
1473 
1474     UsedInBetween.accumulate(MI);
1475 
1476     // Don't count transient instructions towards the search limit since there
1477     // may be different numbers of them if e.g. debug information is present.
1478     if (!MI.isTransient())
1479       ++Count;
1480 
1481     Flags.setSExtIdx(-1);
1482     if (areCandidatesToMergeOrPair(FirstMI, MI, Flags, TII) &&
1483         getLdStOffsetOp(MI).isImm()) {
1484       assert(MI.mayLoadOrStore() && "Expected memory operation.");
1485       // If we've found another instruction with the same opcode, check to see
1486       // if the base and offset are compatible with our starting instruction.
1487       // These instructions all have scaled immediate operands, so we just
1488       // check for +1/-1. Make sure to check the new instruction offset is
1489       // actually an immediate and not a symbolic reference destined for
1490       // a relocation.
1491       Register MIBaseReg = getLdStBaseOp(MI).getReg();
1492       int MIOffset = getLdStOffsetOp(MI).getImm();
1493       bool MIIsUnscaled = TII->isUnscaledLdSt(MI);
1494       if (IsUnscaled != MIIsUnscaled) {
1495         // We're trying to pair instructions that differ in how they are scaled.
1496         // If FirstMI is scaled then scale the offset of MI accordingly.
1497         // Otherwise, do the opposite (i.e., make MI's offset unscaled).
1498         int MemSize = TII->getMemScale(MI);
1499         if (MIIsUnscaled) {
1500           // If the unscaled offset isn't a multiple of the MemSize, we can't
1501           // pair the operations together: bail and keep looking.
1502           if (MIOffset % MemSize) {
1503             LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1504                                               UsedRegUnits, TRI);
1505             MemInsns.push_back(&MI);
1506             continue;
1507           }
1508           MIOffset /= MemSize;
1509         } else {
1510           MIOffset *= MemSize;
1511         }
1512       }
1513 
1514       if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
1515                                    (Offset + OffsetStride == MIOffset))) {
1516         int MinOffset = Offset < MIOffset ? Offset : MIOffset;
1517         if (FindNarrowMerge) {
1518           // If the alignment requirements of the scaled wide load/store
1519           // instruction can't express the offset of the scaled narrow input,
1520           // bail and keep looking. For promotable zero stores, allow only when
1521           // the stored value is the same (i.e., WZR).
1522           if ((!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) ||
1523               (IsPromotableZeroStore && Reg != getLdStRegOp(MI).getReg())) {
1524             LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1525                                               UsedRegUnits, TRI);
1526             MemInsns.push_back(&MI);
1527             continue;
1528           }
1529         } else {
1530           // Pairwise instructions have a 7-bit signed offset field. Single
1531           // insns have a 12-bit unsigned offset field.  If the resultant
1532           // immediate offset of merging these instructions is out of range for
1533           // a pairwise instruction, bail and keep looking.
1534           if (!inBoundsForPair(IsUnscaled, MinOffset, OffsetStride)) {
1535             LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1536                                               UsedRegUnits, TRI);
1537             MemInsns.push_back(&MI);
1538             continue;
1539           }
1540           // If the alignment requirements of the paired (scaled) instruction
1541           // can't express the offset of the unscaled input, bail and keep
1542           // looking.
1543           if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) {
1544             LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1545                                               UsedRegUnits, TRI);
1546             MemInsns.push_back(&MI);
1547             continue;
1548           }
1549         }
1550         // If the destination register of the loads is the same register, bail
1551         // and keep looking. A load-pair instruction with both destination
1552         // registers the same is UNPREDICTABLE and will result in an exception.
1553         if (MayLoad && Reg == getLdStRegOp(MI).getReg()) {
1554           LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
1555                                             TRI);
1556           MemInsns.push_back(&MI);
1557           continue;
1558         }
1559 
1560         // If the Rt of the second instruction was not modified or used between
1561         // the two instructions and none of the instructions between the second
1562         // and first alias with the second, we can combine the second into the
1563         // first.
1564         if (ModifiedRegUnits.available(getLdStRegOp(MI).getReg()) &&
1565             !(MI.mayLoad() &&
1566               !UsedRegUnits.available(getLdStRegOp(MI).getReg())) &&
1567             !mayAlias(MI, MemInsns, AA)) {
1568 
1569           Flags.setMergeForward(false);
1570           Flags.clearRenameReg();
1571           return MBBI;
1572         }
1573 
1574         // Likewise, if the Rt of the first instruction is not modified or used
1575         // between the two instructions and none of the instructions between the
1576         // first and the second alias with the first, we can combine the first
1577         // into the second.
1578         if (!(MayLoad &&
1579               !UsedRegUnits.available(getLdStRegOp(FirstMI).getReg())) &&
1580             !mayAlias(FirstMI, MemInsns, AA)) {
1581 
1582           if (ModifiedRegUnits.available(getLdStRegOp(FirstMI).getReg())) {
1583             Flags.setMergeForward(true);
1584             Flags.clearRenameReg();
1585             return MBBI;
1586           }
1587 
1588           if (DebugCounter::shouldExecute(RegRenamingCounter)) {
1589             if (!MaybeCanRename)
1590               MaybeCanRename = {canRenameUpToDef(FirstMI, UsedInBetween,
1591                                                  RequiredClasses, TRI)};
1592 
1593             if (*MaybeCanRename) {
1594               Optional<MCPhysReg> MaybeRenameReg = tryToFindRegisterToRename(
1595                   FirstMI, MI, DefinedInBB, UsedInBetween, RequiredClasses,
1596                   TRI);
1597               if (MaybeRenameReg) {
1598                 Flags.setRenameReg(*MaybeRenameReg);
1599                 Flags.setMergeForward(true);
1600                 MBBIWithRenameReg = MBBI;
1601               }
1602             }
1603           }
1604         }
1605         // Unable to combine these instructions due to interference in between.
1606         // Keep looking.
1607       }
1608     }
1609 
1610     if (Flags.getRenameReg())
1611       return MBBIWithRenameReg;
1612 
1613     // If the instruction wasn't a matching load or store.  Stop searching if we
1614     // encounter a call instruction that might modify memory.
1615     if (MI.isCall())
1616       return E;
1617 
1618     // Update modified / uses register units.
1619     LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
1620 
1621     // Otherwise, if the base register is modified, we have no match, so
1622     // return early.
1623     if (!ModifiedRegUnits.available(BaseReg))
1624       return E;
1625 
1626     // Update list of instructions that read/write memory.
1627     if (MI.mayLoadOrStore())
1628       MemInsns.push_back(&MI);
1629   }
1630   return E;
1631 }
1632 
1633 MachineBasicBlock::iterator
1634 AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
1635                                      MachineBasicBlock::iterator Update,
1636                                      bool IsPreIdx) {
1637   assert((Update->getOpcode() == AArch64::ADDXri ||
1638           Update->getOpcode() == AArch64::SUBXri) &&
1639          "Unexpected base register update instruction to merge!");
1640   MachineBasicBlock::iterator NextI = I;
1641   // Return the instruction following the merged instruction, which is
1642   // the instruction following our unmerged load. Unless that's the add/sub
1643   // instruction we're merging, in which case it's the one after that.
1644   if (++NextI == Update)
1645     ++NextI;
1646 
1647   int Value = Update->getOperand(2).getImm();
1648   assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
1649          "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
1650   if (Update->getOpcode() == AArch64::SUBXri)
1651     Value = -Value;
1652 
1653   unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
1654                              : getPostIndexedOpcode(I->getOpcode());
1655   MachineInstrBuilder MIB;
1656   int Scale, MinOffset, MaxOffset;
1657   getPrePostIndexedMemOpInfo(*I, Scale, MinOffset, MaxOffset);
1658   if (!isPairedLdSt(*I)) {
1659     // Non-paired instruction.
1660     MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1661               .add(getLdStRegOp(*Update))
1662               .add(getLdStRegOp(*I))
1663               .add(getLdStBaseOp(*I))
1664               .addImm(Value / Scale)
1665               .setMemRefs(I->memoperands())
1666               .setMIFlags(I->mergeFlagsWith(*Update));
1667   } else {
1668     // Paired instruction.
1669     MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1670               .add(getLdStRegOp(*Update))
1671               .add(getLdStRegOp(*I, 0))
1672               .add(getLdStRegOp(*I, 1))
1673               .add(getLdStBaseOp(*I))
1674               .addImm(Value / Scale)
1675               .setMemRefs(I->memoperands())
1676               .setMIFlags(I->mergeFlagsWith(*Update));
1677   }
1678   (void)MIB;
1679 
1680   if (IsPreIdx) {
1681     ++NumPreFolded;
1682     LLVM_DEBUG(dbgs() << "Creating pre-indexed load/store.");
1683   } else {
1684     ++NumPostFolded;
1685     LLVM_DEBUG(dbgs() << "Creating post-indexed load/store.");
1686   }
1687   LLVM_DEBUG(dbgs() << "    Replacing instructions:\n    ");
1688   LLVM_DEBUG(I->print(dbgs()));
1689   LLVM_DEBUG(dbgs() << "    ");
1690   LLVM_DEBUG(Update->print(dbgs()));
1691   LLVM_DEBUG(dbgs() << "  with instruction:\n    ");
1692   LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1693   LLVM_DEBUG(dbgs() << "\n");
1694 
1695   // Erase the old instructions for the block.
1696   I->eraseFromParent();
1697   Update->eraseFromParent();
1698 
1699   return NextI;
1700 }
1701 
1702 bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr &MemMI,
1703                                                MachineInstr &MI,
1704                                                unsigned BaseReg, int Offset) {
1705   switch (MI.getOpcode()) {
1706   default:
1707     break;
1708   case AArch64::SUBXri:
1709   case AArch64::ADDXri:
1710     // Make sure it's a vanilla immediate operand, not a relocation or
1711     // anything else we can't handle.
1712     if (!MI.getOperand(2).isImm())
1713       break;
1714     // Watch out for 1 << 12 shifted value.
1715     if (AArch64_AM::getShiftValue(MI.getOperand(3).getImm()))
1716       break;
1717 
1718     // The update instruction source and destination register must be the
1719     // same as the load/store base register.
1720     if (MI.getOperand(0).getReg() != BaseReg ||
1721         MI.getOperand(1).getReg() != BaseReg)
1722       break;
1723 
1724     int UpdateOffset = MI.getOperand(2).getImm();
1725     if (MI.getOpcode() == AArch64::SUBXri)
1726       UpdateOffset = -UpdateOffset;
1727 
1728     // The immediate must be a multiple of the scaling factor of the pre/post
1729     // indexed instruction.
1730     int Scale, MinOffset, MaxOffset;
1731     getPrePostIndexedMemOpInfo(MemMI, Scale, MinOffset, MaxOffset);
1732     if (UpdateOffset % Scale != 0)
1733       break;
1734 
1735     // Scaled offset must fit in the instruction immediate.
1736     int ScaledOffset = UpdateOffset / Scale;
1737     if (ScaledOffset > MaxOffset || ScaledOffset < MinOffset)
1738       break;
1739 
1740     // If we have a non-zero Offset, we check that it matches the amount
1741     // we're adding to the register.
1742     if (!Offset || Offset == UpdateOffset)
1743       return true;
1744     break;
1745   }
1746   return false;
1747 }
1748 
1749 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
1750     MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) {
1751   MachineBasicBlock::iterator E = I->getParent()->end();
1752   MachineInstr &MemMI = *I;
1753   MachineBasicBlock::iterator MBBI = I;
1754 
1755   Register BaseReg = getLdStBaseOp(MemMI).getReg();
1756   int MIUnscaledOffset = getLdStOffsetOp(MemMI).getImm() * TII->getMemScale(MemMI);
1757 
1758   // Scan forward looking for post-index opportunities.  Updating instructions
1759   // can't be formed if the memory instruction doesn't have the offset we're
1760   // looking for.
1761   if (MIUnscaledOffset != UnscaledOffset)
1762     return E;
1763 
1764   // If the base register overlaps a source/destination register, we can't
1765   // merge the update. This does not apply to tag store instructions which
1766   // ignore the address part of the source register.
1767   // This does not apply to STGPi as well, which does not have unpredictable
1768   // behavior in this case unlike normal stores, and always performs writeback
1769   // after reading the source register value.
1770   if (!isTagStore(MemMI) && MemMI.getOpcode() != AArch64::STGPi) {
1771     bool IsPairedInsn = isPairedLdSt(MemMI);
1772     for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1773       Register DestReg = getLdStRegOp(MemMI, i).getReg();
1774       if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1775         return E;
1776     }
1777   }
1778 
1779   // Track which register units have been modified and used between the first
1780   // insn (inclusive) and the second insn.
1781   ModifiedRegUnits.clear();
1782   UsedRegUnits.clear();
1783   ++MBBI;
1784 
1785   // We can't post-increment the stack pointer if any instruction between
1786   // the memory access (I) and the increment (MBBI) can access the memory
1787   // region defined by [SP, MBBI].
1788   const bool BaseRegSP = BaseReg == AArch64::SP;
1789   if (BaseRegSP) {
1790     // FIXME: For now, we always block the optimization over SP in windows
1791     // targets as it requires to adjust the unwind/debug info, messing up
1792     // the unwind info can actually cause a miscompile.
1793     const MCAsmInfo *MAI = I->getMF()->getTarget().getMCAsmInfo();
1794     if (MAI->usesWindowsCFI() &&
1795         I->getMF()->getFunction().needsUnwindTableEntry())
1796       return E;
1797   }
1798 
1799   for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
1800     MachineInstr &MI = *MBBI;
1801 
1802     // Don't count transient instructions towards the search limit since there
1803     // may be different numbers of them if e.g. debug information is present.
1804     if (!MI.isTransient())
1805       ++Count;
1806 
1807     // If we found a match, return it.
1808     if (isMatchingUpdateInsn(*I, MI, BaseReg, UnscaledOffset))
1809       return MBBI;
1810 
1811     // Update the status of what the instruction clobbered and used.
1812     LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
1813 
1814     // Otherwise, if the base register is used or modified, we have no match, so
1815     // return early.
1816     // If we are optimizing SP, do not allow instructions that may load or store
1817     // in between the load and the optimized value update.
1818     if (!ModifiedRegUnits.available(BaseReg) ||
1819         !UsedRegUnits.available(BaseReg) ||
1820         (BaseRegSP && MBBI->mayLoadOrStore()))
1821       return E;
1822   }
1823   return E;
1824 }
1825 
1826 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
1827     MachineBasicBlock::iterator I, unsigned Limit) {
1828   MachineBasicBlock::iterator B = I->getParent()->begin();
1829   MachineBasicBlock::iterator E = I->getParent()->end();
1830   MachineInstr &MemMI = *I;
1831   MachineBasicBlock::iterator MBBI = I;
1832 
1833   Register BaseReg = getLdStBaseOp(MemMI).getReg();
1834   int Offset = getLdStOffsetOp(MemMI).getImm();
1835 
1836   // If the load/store is the first instruction in the block, there's obviously
1837   // not any matching update. Ditto if the memory offset isn't zero.
1838   if (MBBI == B || Offset != 0)
1839     return E;
1840   // If the base register overlaps a destination register, we can't
1841   // merge the update.
1842   if (!isTagStore(MemMI)) {
1843     bool IsPairedInsn = isPairedLdSt(MemMI);
1844     for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1845       Register DestReg = getLdStRegOp(MemMI, i).getReg();
1846       if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1847         return E;
1848     }
1849   }
1850 
1851   // Track which register units have been modified and used between the first
1852   // insn (inclusive) and the second insn.
1853   ModifiedRegUnits.clear();
1854   UsedRegUnits.clear();
1855   unsigned Count = 0;
1856   do {
1857     --MBBI;
1858     MachineInstr &MI = *MBBI;
1859 
1860     // Don't count transient instructions towards the search limit since there
1861     // may be different numbers of them if e.g. debug information is present.
1862     if (!MI.isTransient())
1863       ++Count;
1864 
1865     // If we found a match, return it.
1866     if (isMatchingUpdateInsn(*I, MI, BaseReg, Offset))
1867       return MBBI;
1868 
1869     // Update the status of what the instruction clobbered and used.
1870     LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
1871 
1872     // Otherwise, if the base register is used or modified, we have no match, so
1873     // return early.
1874     if (!ModifiedRegUnits.available(BaseReg) ||
1875         !UsedRegUnits.available(BaseReg))
1876       return E;
1877   } while (MBBI != B && Count < Limit);
1878   return E;
1879 }
1880 
1881 bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore(
1882     MachineBasicBlock::iterator &MBBI) {
1883   MachineInstr &MI = *MBBI;
1884   // If this is a volatile load, don't mess with it.
1885   if (MI.hasOrderedMemoryRef())
1886     return false;
1887 
1888   // Make sure this is a reg+imm.
1889   // FIXME: It is possible to extend it to handle reg+reg cases.
1890   if (!getLdStOffsetOp(MI).isImm())
1891     return false;
1892 
1893   // Look backward up to LdStLimit instructions.
1894   MachineBasicBlock::iterator StoreI;
1895   if (findMatchingStore(MBBI, LdStLimit, StoreI)) {
1896     ++NumLoadsFromStoresPromoted;
1897     // Promote the load. Keeping the iterator straight is a
1898     // pain, so we let the merge routine tell us what the next instruction
1899     // is after it's done mucking about.
1900     MBBI = promoteLoadFromStore(MBBI, StoreI);
1901     return true;
1902   }
1903   return false;
1904 }
1905 
1906 // Merge adjacent zero stores into a wider store.
1907 bool AArch64LoadStoreOpt::tryToMergeZeroStInst(
1908     MachineBasicBlock::iterator &MBBI) {
1909   assert(isPromotableZeroStoreInst(*MBBI) && "Expected narrow store.");
1910   MachineInstr &MI = *MBBI;
1911   MachineBasicBlock::iterator E = MI.getParent()->end();
1912 
1913   if (!TII->isCandidateToMergeOrPair(MI))
1914     return false;
1915 
1916   // Look ahead up to LdStLimit instructions for a mergable instruction.
1917   LdStPairFlags Flags;
1918   MachineBasicBlock::iterator MergeMI =
1919       findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ true);
1920   if (MergeMI != E) {
1921     ++NumZeroStoresPromoted;
1922 
1923     // Keeping the iterator straight is a pain, so we let the merge routine tell
1924     // us what the next instruction is after it's done mucking about.
1925     MBBI = mergeNarrowZeroStores(MBBI, MergeMI, Flags);
1926     return true;
1927   }
1928   return false;
1929 }
1930 
1931 // Find loads and stores that can be merged into a single load or store pair
1932 // instruction.
1933 bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
1934   MachineInstr &MI = *MBBI;
1935   MachineBasicBlock::iterator E = MI.getParent()->end();
1936 
1937   if (!TII->isCandidateToMergeOrPair(MI))
1938     return false;
1939 
1940   // Early exit if the offset is not possible to match. (6 bits of positive
1941   // range, plus allow an extra one in case we find a later insn that matches
1942   // with Offset-1)
1943   bool IsUnscaled = TII->isUnscaledLdSt(MI);
1944   int Offset = getLdStOffsetOp(MI).getImm();
1945   int OffsetStride = IsUnscaled ? TII->getMemScale(MI) : 1;
1946   // Allow one more for offset.
1947   if (Offset > 0)
1948     Offset -= OffsetStride;
1949   if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
1950     return false;
1951 
1952   // Look ahead up to LdStLimit instructions for a pairable instruction.
1953   LdStPairFlags Flags;
1954   MachineBasicBlock::iterator Paired =
1955       findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ false);
1956   if (Paired != E) {
1957     ++NumPairCreated;
1958     if (TII->isUnscaledLdSt(MI))
1959       ++NumUnscaledPairCreated;
1960     // Keeping the iterator straight is a pain, so we let the merge routine tell
1961     // us what the next instruction is after it's done mucking about.
1962     auto Prev = std::prev(MBBI);
1963     MBBI = mergePairedInsns(MBBI, Paired, Flags);
1964     // Collect liveness info for instructions between Prev and the new position
1965     // MBBI.
1966     for (auto I = std::next(Prev); I != MBBI; I++)
1967       updateDefinedRegisters(*I, DefinedInBB, TRI);
1968 
1969     return true;
1970   }
1971   return false;
1972 }
1973 
1974 bool AArch64LoadStoreOpt::tryToMergeLdStUpdate
1975     (MachineBasicBlock::iterator &MBBI) {
1976   MachineInstr &MI = *MBBI;
1977   MachineBasicBlock::iterator E = MI.getParent()->end();
1978   MachineBasicBlock::iterator Update;
1979 
1980   // Look forward to try to form a post-index instruction. For example,
1981   // ldr x0, [x20]
1982   // add x20, x20, #32
1983   //   merged into:
1984   // ldr x0, [x20], #32
1985   Update = findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit);
1986   if (Update != E) {
1987     // Merge the update into the ld/st.
1988     MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
1989     return true;
1990   }
1991 
1992   // Don't know how to handle unscaled pre/post-index versions below, so bail.
1993   if (TII->isUnscaledLdSt(MI.getOpcode()))
1994     return false;
1995 
1996   // Look back to try to find a pre-index instruction. For example,
1997   // add x0, x0, #8
1998   // ldr x1, [x0]
1999   //   merged into:
2000   // ldr x1, [x0, #8]!
2001   Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit);
2002   if (Update != E) {
2003     // Merge the update into the ld/st.
2004     MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
2005     return true;
2006   }
2007 
2008   // The immediate in the load/store is scaled by the size of the memory
2009   // operation. The immediate in the add we're looking for,
2010   // however, is not, so adjust here.
2011   int UnscaledOffset = getLdStOffsetOp(MI).getImm() * TII->getMemScale(MI);
2012 
2013   // Look forward to try to find a pre-index instruction. For example,
2014   // ldr x1, [x0, #64]
2015   // add x0, x0, #64
2016   //   merged into:
2017   // ldr x1, [x0, #64]!
2018   Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit);
2019   if (Update != E) {
2020     // Merge the update into the ld/st.
2021     MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
2022     return true;
2023   }
2024 
2025   return false;
2026 }
2027 
2028 bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
2029                                         bool EnableNarrowZeroStOpt) {
2030 
2031   bool Modified = false;
2032   // Four tranformations to do here:
2033   // 1) Find loads that directly read from stores and promote them by
2034   //    replacing with mov instructions. If the store is wider than the load,
2035   //    the load will be replaced with a bitfield extract.
2036   //      e.g.,
2037   //        str w1, [x0, #4]
2038   //        ldrh w2, [x0, #6]
2039   //        ; becomes
2040   //        str w1, [x0, #4]
2041   //        lsr w2, w1, #16
2042   for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
2043        MBBI != E;) {
2044     if (isPromotableLoadFromStore(*MBBI) && tryToPromoteLoadFromStore(MBBI))
2045       Modified = true;
2046     else
2047       ++MBBI;
2048   }
2049   // 2) Merge adjacent zero stores into a wider store.
2050   //      e.g.,
2051   //        strh wzr, [x0]
2052   //        strh wzr, [x0, #2]
2053   //        ; becomes
2054   //        str wzr, [x0]
2055   //      e.g.,
2056   //        str wzr, [x0]
2057   //        str wzr, [x0, #4]
2058   //        ; becomes
2059   //        str xzr, [x0]
2060   if (EnableNarrowZeroStOpt)
2061     for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
2062          MBBI != E;) {
2063       if (isPromotableZeroStoreInst(*MBBI) && tryToMergeZeroStInst(MBBI))
2064         Modified = true;
2065       else
2066         ++MBBI;
2067     }
2068   // 3) Find loads and stores that can be merged into a single load or store
2069   //    pair instruction.
2070   //      e.g.,
2071   //        ldr x0, [x2]
2072   //        ldr x1, [x2, #8]
2073   //        ; becomes
2074   //        ldp x0, x1, [x2]
2075 
2076   if (MBB.getParent()->getRegInfo().tracksLiveness()) {
2077     DefinedInBB.clear();
2078     DefinedInBB.addLiveIns(MBB);
2079   }
2080 
2081   for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
2082        MBBI != E;) {
2083     // Track currently live registers up to this point, to help with
2084     // searching for a rename register on demand.
2085     updateDefinedRegisters(*MBBI, DefinedInBB, TRI);
2086     if (TII->isPairableLdStInst(*MBBI) && tryToPairLdStInst(MBBI))
2087       Modified = true;
2088     else
2089       ++MBBI;
2090   }
2091   // 4) Find base register updates that can be merged into the load or store
2092   //    as a base-reg writeback.
2093   //      e.g.,
2094   //        ldr x0, [x2]
2095   //        add x2, x2, #4
2096   //        ; becomes
2097   //        ldr x0, [x2], #4
2098   for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
2099        MBBI != E;) {
2100     if (isMergeableLdStUpdate(*MBBI) && tryToMergeLdStUpdate(MBBI))
2101       Modified = true;
2102     else
2103       ++MBBI;
2104   }
2105 
2106   return Modified;
2107 }
2108 
2109 bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
2110   if (skipFunction(Fn.getFunction()))
2111     return false;
2112 
2113   Subtarget = &static_cast<const AArch64Subtarget &>(Fn.getSubtarget());
2114   TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo());
2115   TRI = Subtarget->getRegisterInfo();
2116   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2117 
2118   // Resize the modified and used register unit trackers.  We do this once
2119   // per function and then clear the register units each time we optimize a load
2120   // or store.
2121   ModifiedRegUnits.init(*TRI);
2122   UsedRegUnits.init(*TRI);
2123   DefinedInBB.init(*TRI);
2124 
2125   bool Modified = false;
2126   bool enableNarrowZeroStOpt = !Subtarget->requiresStrictAlign();
2127   for (auto &MBB : Fn) {
2128     auto M = optimizeBlock(MBB, enableNarrowZeroStOpt);
2129     Modified |= M;
2130   }
2131 
2132   return Modified;
2133 }
2134 
2135 // FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep loads and
2136 // stores near one another?  Note: The pre-RA instruction scheduler already has
2137 // hooks to try and schedule pairable loads/stores together to improve pairing
2138 // opportunities.  Thus, pre-RA pairing pass may not be worth the effort.
2139 
2140 // FIXME: When pairing store instructions it's very possible for this pass to
2141 // hoist a store with a KILL marker above another use (without a KILL marker).
2142 // The resulting IR is invalid, but nothing uses the KILL markers after this
2143 // pass, so it's never caused a problem in practice.
2144 
2145 /// createAArch64LoadStoreOptimizationPass - returns an instance of the
2146 /// load / store optimization pass.
2147 FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
2148   return new AArch64LoadStoreOpt();
2149 }
2150