1 //===- ARMLoadStoreOptimizer.cpp - ARM 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 /// \file 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 "ARM.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMISelLowering.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMSubtarget.h"
20 #include "MCTargetDesc/ARMAddressingModes.h"
21 #include "MCTargetDesc/ARMBaseInfo.h"
22 #include "Utils/ARMBaseInfo.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/DenseSet.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/iterator_range.h"
33 #include "llvm/Analysis/AliasAnalysis.h"
34 #include "llvm/CodeGen/LivePhysRegs.h"
35 #include "llvm/CodeGen/MachineBasicBlock.h"
36 #include "llvm/CodeGen/MachineDominators.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineFunctionPass.h"
39 #include "llvm/CodeGen/MachineInstr.h"
40 #include "llvm/CodeGen/MachineInstrBuilder.h"
41 #include "llvm/CodeGen/MachineMemOperand.h"
42 #include "llvm/CodeGen/MachineOperand.h"
43 #include "llvm/CodeGen/MachineRegisterInfo.h"
44 #include "llvm/CodeGen/RegisterClassInfo.h"
45 #include "llvm/CodeGen/TargetFrameLowering.h"
46 #include "llvm/CodeGen/TargetInstrInfo.h"
47 #include "llvm/CodeGen/TargetLowering.h"
48 #include "llvm/CodeGen/TargetRegisterInfo.h"
49 #include "llvm/CodeGen/TargetSubtargetInfo.h"
50 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/DebugLoc.h"
52 #include "llvm/IR/DerivedTypes.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/Type.h"
55 #include "llvm/InitializePasses.h"
56 #include "llvm/MC/MCInstrDesc.h"
57 #include "llvm/Pass.h"
58 #include "llvm/Support/Allocator.h"
59 #include "llvm/Support/CommandLine.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/ErrorHandling.h"
62 #include "llvm/Support/raw_ostream.h"
63 #include <algorithm>
64 #include <cassert>
65 #include <cstddef>
66 #include <cstdlib>
67 #include <iterator>
68 #include <limits>
69 #include <utility>
70 
71 using namespace llvm;
72 
73 #define DEBUG_TYPE "arm-ldst-opt"
74 
75 STATISTIC(NumLDMGened , "Number of ldm instructions generated");
76 STATISTIC(NumSTMGened , "Number of stm instructions generated");
77 STATISTIC(NumVLDMGened, "Number of vldm instructions generated");
78 STATISTIC(NumVSTMGened, "Number of vstm instructions generated");
79 STATISTIC(NumLdStMoved, "Number of load / store instructions moved");
80 STATISTIC(NumLDRDFormed,"Number of ldrd created before allocation");
81 STATISTIC(NumSTRDFormed,"Number of strd created before allocation");
82 STATISTIC(NumLDRD2LDM,  "Number of ldrd instructions turned back into ldm");
83 STATISTIC(NumSTRD2STM,  "Number of strd instructions turned back into stm");
84 STATISTIC(NumLDRD2LDR,  "Number of ldrd instructions turned back into ldr's");
85 STATISTIC(NumSTRD2STR,  "Number of strd instructions turned back into str's");
86 
87 /// This switch disables formation of double/multi instructions that could
88 /// potentially lead to (new) alignment traps even with CCR.UNALIGN_TRP
89 /// disabled. This can be used to create libraries that are robust even when
90 /// users provoke undefined behaviour by supplying misaligned pointers.
91 /// \see mayCombineMisaligned()
92 static cl::opt<bool>
93 AssumeMisalignedLoadStores("arm-assume-misaligned-load-store", cl::Hidden,
94     cl::init(false), cl::desc("Be more conservative in ARM load/store opt"));
95 
96 #define ARM_LOAD_STORE_OPT_NAME "ARM load / store optimization pass"
97 
98 namespace {
99 
100   /// Post- register allocation pass the combine load / store instructions to
101   /// form ldm / stm instructions.
102   struct ARMLoadStoreOpt : public MachineFunctionPass {
103     static char ID;
104 
105     const MachineFunction *MF;
106     const TargetInstrInfo *TII;
107     const TargetRegisterInfo *TRI;
108     const ARMSubtarget *STI;
109     const TargetLowering *TL;
110     ARMFunctionInfo *AFI;
111     LivePhysRegs LiveRegs;
112     RegisterClassInfo RegClassInfo;
113     MachineBasicBlock::const_iterator LiveRegPos;
114     bool LiveRegsValid;
115     bool RegClassInfoValid;
116     bool isThumb1, isThumb2;
117 
118     ARMLoadStoreOpt() : MachineFunctionPass(ID) {}
119 
120     bool runOnMachineFunction(MachineFunction &Fn) override;
121 
122     MachineFunctionProperties getRequiredProperties() const override {
123       return MachineFunctionProperties().set(
124           MachineFunctionProperties::Property::NoVRegs);
125     }
126 
127     StringRef getPassName() const override { return ARM_LOAD_STORE_OPT_NAME; }
128 
129   private:
130     /// A set of load/store MachineInstrs with same base register sorted by
131     /// offset.
132     struct MemOpQueueEntry {
133       MachineInstr *MI;
134       int Offset;        ///< Load/Store offset.
135       unsigned Position; ///< Position as counted from end of basic block.
136 
137       MemOpQueueEntry(MachineInstr &MI, int Offset, unsigned Position)
138           : MI(&MI), Offset(Offset), Position(Position) {}
139     };
140     using MemOpQueue = SmallVector<MemOpQueueEntry, 8>;
141 
142     /// A set of MachineInstrs that fulfill (nearly all) conditions to get
143     /// merged into a LDM/STM.
144     struct MergeCandidate {
145       /// List of instructions ordered by load/store offset.
146       SmallVector<MachineInstr*, 4> Instrs;
147 
148       /// Index in Instrs of the instruction being latest in the schedule.
149       unsigned LatestMIIdx;
150 
151       /// Index in Instrs of the instruction being earliest in the schedule.
152       unsigned EarliestMIIdx;
153 
154       /// Index into the basic block where the merged instruction will be
155       /// inserted. (See MemOpQueueEntry.Position)
156       unsigned InsertPos;
157 
158       /// Whether the instructions can be merged into a ldm/stm instruction.
159       bool CanMergeToLSMulti;
160 
161       /// Whether the instructions can be merged into a ldrd/strd instruction.
162       bool CanMergeToLSDouble;
163     };
164     SpecificBumpPtrAllocator<MergeCandidate> Allocator;
165     SmallVector<const MergeCandidate*,4> Candidates;
166     SmallVector<MachineInstr*,4> MergeBaseCandidates;
167 
168     void moveLiveRegsBefore(const MachineBasicBlock &MBB,
169                             MachineBasicBlock::const_iterator Before);
170     unsigned findFreeReg(const TargetRegisterClass &RegClass);
171     void UpdateBaseRegUses(MachineBasicBlock &MBB,
172                            MachineBasicBlock::iterator MBBI, const DebugLoc &DL,
173                            unsigned Base, unsigned WordOffset,
174                            ARMCC::CondCodes Pred, unsigned PredReg);
175     MachineInstr *CreateLoadStoreMulti(
176         MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
177         int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
178         ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
179         ArrayRef<std::pair<unsigned, bool>> Regs,
180         ArrayRef<MachineInstr*> Instrs);
181     MachineInstr *CreateLoadStoreDouble(
182         MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
183         int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
184         ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
185         ArrayRef<std::pair<unsigned, bool>> Regs,
186         ArrayRef<MachineInstr*> Instrs) const;
187     void FormCandidates(const MemOpQueue &MemOps);
188     MachineInstr *MergeOpsUpdate(const MergeCandidate &Cand);
189     bool FixInvalidRegPairOp(MachineBasicBlock &MBB,
190                              MachineBasicBlock::iterator &MBBI);
191     bool MergeBaseUpdateLoadStore(MachineInstr *MI);
192     bool MergeBaseUpdateLSMultiple(MachineInstr *MI);
193     bool MergeBaseUpdateLSDouble(MachineInstr &MI) const;
194     bool LoadStoreMultipleOpti(MachineBasicBlock &MBB);
195     bool MergeReturnIntoLDM(MachineBasicBlock &MBB);
196     bool CombineMovBx(MachineBasicBlock &MBB);
197   };
198 
199 } // end anonymous namespace
200 
201 char ARMLoadStoreOpt::ID = 0;
202 
203 INITIALIZE_PASS(ARMLoadStoreOpt, "arm-ldst-opt", ARM_LOAD_STORE_OPT_NAME, false,
204                 false)
205 
206 static bool definesCPSR(const MachineInstr &MI) {
207   for (const auto &MO : MI.operands()) {
208     if (!MO.isReg())
209       continue;
210     if (MO.isDef() && MO.getReg() == ARM::CPSR && !MO.isDead())
211       // If the instruction has live CPSR def, then it's not safe to fold it
212       // into load / store.
213       return true;
214   }
215 
216   return false;
217 }
218 
219 static int getMemoryOpOffset(const MachineInstr &MI) {
220   unsigned Opcode = MI.getOpcode();
221   bool isAM3 = Opcode == ARM::LDRD || Opcode == ARM::STRD;
222   unsigned NumOperands = MI.getDesc().getNumOperands();
223   unsigned OffField = MI.getOperand(NumOperands - 3).getImm();
224 
225   if (Opcode == ARM::t2LDRi12 || Opcode == ARM::t2LDRi8 ||
226       Opcode == ARM::t2STRi12 || Opcode == ARM::t2STRi8 ||
227       Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8 ||
228       Opcode == ARM::LDRi12   || Opcode == ARM::STRi12)
229     return OffField;
230 
231   // Thumb1 immediate offsets are scaled by 4
232   if (Opcode == ARM::tLDRi || Opcode == ARM::tSTRi ||
233       Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi)
234     return OffField * 4;
235 
236   int Offset = isAM3 ? ARM_AM::getAM3Offset(OffField)
237     : ARM_AM::getAM5Offset(OffField) * 4;
238   ARM_AM::AddrOpc Op = isAM3 ? ARM_AM::getAM3Op(OffField)
239     : ARM_AM::getAM5Op(OffField);
240 
241   if (Op == ARM_AM::sub)
242     return -Offset;
243 
244   return Offset;
245 }
246 
247 static const MachineOperand &getLoadStoreBaseOp(const MachineInstr &MI) {
248   return MI.getOperand(1);
249 }
250 
251 static const MachineOperand &getLoadStoreRegOp(const MachineInstr &MI) {
252   return MI.getOperand(0);
253 }
254 
255 static int getLoadStoreMultipleOpcode(unsigned Opcode, ARM_AM::AMSubMode Mode) {
256   switch (Opcode) {
257   default: llvm_unreachable("Unhandled opcode!");
258   case ARM::LDRi12:
259     ++NumLDMGened;
260     switch (Mode) {
261     default: llvm_unreachable("Unhandled submode!");
262     case ARM_AM::ia: return ARM::LDMIA;
263     case ARM_AM::da: return ARM::LDMDA;
264     case ARM_AM::db: return ARM::LDMDB;
265     case ARM_AM::ib: return ARM::LDMIB;
266     }
267   case ARM::STRi12:
268     ++NumSTMGened;
269     switch (Mode) {
270     default: llvm_unreachable("Unhandled submode!");
271     case ARM_AM::ia: return ARM::STMIA;
272     case ARM_AM::da: return ARM::STMDA;
273     case ARM_AM::db: return ARM::STMDB;
274     case ARM_AM::ib: return ARM::STMIB;
275     }
276   case ARM::tLDRi:
277   case ARM::tLDRspi:
278     // tLDMIA is writeback-only - unless the base register is in the input
279     // reglist.
280     ++NumLDMGened;
281     switch (Mode) {
282     default: llvm_unreachable("Unhandled submode!");
283     case ARM_AM::ia: return ARM::tLDMIA;
284     }
285   case ARM::tSTRi:
286   case ARM::tSTRspi:
287     // There is no non-writeback tSTMIA either.
288     ++NumSTMGened;
289     switch (Mode) {
290     default: llvm_unreachable("Unhandled submode!");
291     case ARM_AM::ia: return ARM::tSTMIA_UPD;
292     }
293   case ARM::t2LDRi8:
294   case ARM::t2LDRi12:
295     ++NumLDMGened;
296     switch (Mode) {
297     default: llvm_unreachable("Unhandled submode!");
298     case ARM_AM::ia: return ARM::t2LDMIA;
299     case ARM_AM::db: return ARM::t2LDMDB;
300     }
301   case ARM::t2STRi8:
302   case ARM::t2STRi12:
303     ++NumSTMGened;
304     switch (Mode) {
305     default: llvm_unreachable("Unhandled submode!");
306     case ARM_AM::ia: return ARM::t2STMIA;
307     case ARM_AM::db: return ARM::t2STMDB;
308     }
309   case ARM::VLDRS:
310     ++NumVLDMGened;
311     switch (Mode) {
312     default: llvm_unreachable("Unhandled submode!");
313     case ARM_AM::ia: return ARM::VLDMSIA;
314     case ARM_AM::db: return 0; // Only VLDMSDB_UPD exists.
315     }
316   case ARM::VSTRS:
317     ++NumVSTMGened;
318     switch (Mode) {
319     default: llvm_unreachable("Unhandled submode!");
320     case ARM_AM::ia: return ARM::VSTMSIA;
321     case ARM_AM::db: return 0; // Only VSTMSDB_UPD exists.
322     }
323   case ARM::VLDRD:
324     ++NumVLDMGened;
325     switch (Mode) {
326     default: llvm_unreachable("Unhandled submode!");
327     case ARM_AM::ia: return ARM::VLDMDIA;
328     case ARM_AM::db: return 0; // Only VLDMDDB_UPD exists.
329     }
330   case ARM::VSTRD:
331     ++NumVSTMGened;
332     switch (Mode) {
333     default: llvm_unreachable("Unhandled submode!");
334     case ARM_AM::ia: return ARM::VSTMDIA;
335     case ARM_AM::db: return 0; // Only VSTMDDB_UPD exists.
336     }
337   }
338 }
339 
340 static ARM_AM::AMSubMode getLoadStoreMultipleSubMode(unsigned Opcode) {
341   switch (Opcode) {
342   default: llvm_unreachable("Unhandled opcode!");
343   case ARM::LDMIA_RET:
344   case ARM::LDMIA:
345   case ARM::LDMIA_UPD:
346   case ARM::STMIA:
347   case ARM::STMIA_UPD:
348   case ARM::tLDMIA:
349   case ARM::tLDMIA_UPD:
350   case ARM::tSTMIA_UPD:
351   case ARM::t2LDMIA_RET:
352   case ARM::t2LDMIA:
353   case ARM::t2LDMIA_UPD:
354   case ARM::t2STMIA:
355   case ARM::t2STMIA_UPD:
356   case ARM::VLDMSIA:
357   case ARM::VLDMSIA_UPD:
358   case ARM::VSTMSIA:
359   case ARM::VSTMSIA_UPD:
360   case ARM::VLDMDIA:
361   case ARM::VLDMDIA_UPD:
362   case ARM::VSTMDIA:
363   case ARM::VSTMDIA_UPD:
364     return ARM_AM::ia;
365 
366   case ARM::LDMDA:
367   case ARM::LDMDA_UPD:
368   case ARM::STMDA:
369   case ARM::STMDA_UPD:
370     return ARM_AM::da;
371 
372   case ARM::LDMDB:
373   case ARM::LDMDB_UPD:
374   case ARM::STMDB:
375   case ARM::STMDB_UPD:
376   case ARM::t2LDMDB:
377   case ARM::t2LDMDB_UPD:
378   case ARM::t2STMDB:
379   case ARM::t2STMDB_UPD:
380   case ARM::VLDMSDB_UPD:
381   case ARM::VSTMSDB_UPD:
382   case ARM::VLDMDDB_UPD:
383   case ARM::VSTMDDB_UPD:
384     return ARM_AM::db;
385 
386   case ARM::LDMIB:
387   case ARM::LDMIB_UPD:
388   case ARM::STMIB:
389   case ARM::STMIB_UPD:
390     return ARM_AM::ib;
391   }
392 }
393 
394 static bool isT1i32Load(unsigned Opc) {
395   return Opc == ARM::tLDRi || Opc == ARM::tLDRspi;
396 }
397 
398 static bool isT2i32Load(unsigned Opc) {
399   return Opc == ARM::t2LDRi12 || Opc == ARM::t2LDRi8;
400 }
401 
402 static bool isi32Load(unsigned Opc) {
403   return Opc == ARM::LDRi12 || isT1i32Load(Opc) || isT2i32Load(Opc) ;
404 }
405 
406 static bool isT1i32Store(unsigned Opc) {
407   return Opc == ARM::tSTRi || Opc == ARM::tSTRspi;
408 }
409 
410 static bool isT2i32Store(unsigned Opc) {
411   return Opc == ARM::t2STRi12 || Opc == ARM::t2STRi8;
412 }
413 
414 static bool isi32Store(unsigned Opc) {
415   return Opc == ARM::STRi12 || isT1i32Store(Opc) || isT2i32Store(Opc);
416 }
417 
418 static bool isLoadSingle(unsigned Opc) {
419   return isi32Load(Opc) || Opc == ARM::VLDRS || Opc == ARM::VLDRD;
420 }
421 
422 static unsigned getImmScale(unsigned Opc) {
423   switch (Opc) {
424   default: llvm_unreachable("Unhandled opcode!");
425   case ARM::tLDRi:
426   case ARM::tSTRi:
427   case ARM::tLDRspi:
428   case ARM::tSTRspi:
429     return 1;
430   case ARM::tLDRHi:
431   case ARM::tSTRHi:
432     return 2;
433   case ARM::tLDRBi:
434   case ARM::tSTRBi:
435     return 4;
436   }
437 }
438 
439 static unsigned getLSMultipleTransferSize(const MachineInstr *MI) {
440   switch (MI->getOpcode()) {
441   default: return 0;
442   case ARM::LDRi12:
443   case ARM::STRi12:
444   case ARM::tLDRi:
445   case ARM::tSTRi:
446   case ARM::tLDRspi:
447   case ARM::tSTRspi:
448   case ARM::t2LDRi8:
449   case ARM::t2LDRi12:
450   case ARM::t2STRi8:
451   case ARM::t2STRi12:
452   case ARM::VLDRS:
453   case ARM::VSTRS:
454     return 4;
455   case ARM::VLDRD:
456   case ARM::VSTRD:
457     return 8;
458   case ARM::LDMIA:
459   case ARM::LDMDA:
460   case ARM::LDMDB:
461   case ARM::LDMIB:
462   case ARM::STMIA:
463   case ARM::STMDA:
464   case ARM::STMDB:
465   case ARM::STMIB:
466   case ARM::tLDMIA:
467   case ARM::tLDMIA_UPD:
468   case ARM::tSTMIA_UPD:
469   case ARM::t2LDMIA:
470   case ARM::t2LDMDB:
471   case ARM::t2STMIA:
472   case ARM::t2STMDB:
473   case ARM::VLDMSIA:
474   case ARM::VSTMSIA:
475     return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 4;
476   case ARM::VLDMDIA:
477   case ARM::VSTMDIA:
478     return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 8;
479   }
480 }
481 
482 /// Update future uses of the base register with the offset introduced
483 /// due to writeback. This function only works on Thumb1.
484 void ARMLoadStoreOpt::UpdateBaseRegUses(MachineBasicBlock &MBB,
485                                         MachineBasicBlock::iterator MBBI,
486                                         const DebugLoc &DL, unsigned Base,
487                                         unsigned WordOffset,
488                                         ARMCC::CondCodes Pred,
489                                         unsigned PredReg) {
490   assert(isThumb1 && "Can only update base register uses for Thumb1!");
491   // Start updating any instructions with immediate offsets. Insert a SUB before
492   // the first non-updateable instruction (if any).
493   for (; MBBI != MBB.end(); ++MBBI) {
494     bool InsertSub = false;
495     unsigned Opc = MBBI->getOpcode();
496 
497     if (MBBI->readsRegister(Base)) {
498       int Offset;
499       bool IsLoad =
500         Opc == ARM::tLDRi || Opc == ARM::tLDRHi || Opc == ARM::tLDRBi;
501       bool IsStore =
502         Opc == ARM::tSTRi || Opc == ARM::tSTRHi || Opc == ARM::tSTRBi;
503 
504       if (IsLoad || IsStore) {
505         // Loads and stores with immediate offsets can be updated, but only if
506         // the new offset isn't negative.
507         // The MachineOperand containing the offset immediate is the last one
508         // before predicates.
509         MachineOperand &MO =
510           MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3);
511         // The offsets are scaled by 1, 2 or 4 depending on the Opcode.
512         Offset = MO.getImm() - WordOffset * getImmScale(Opc);
513 
514         // If storing the base register, it needs to be reset first.
515         Register InstrSrcReg = getLoadStoreRegOp(*MBBI).getReg();
516 
517         if (Offset >= 0 && !(IsStore && InstrSrcReg == Base))
518           MO.setImm(Offset);
519         else
520           InsertSub = true;
521       } else if ((Opc == ARM::tSUBi8 || Opc == ARM::tADDi8) &&
522                  !definesCPSR(*MBBI)) {
523         // SUBS/ADDS using this register, with a dead def of the CPSR.
524         // Merge it with the update; if the merged offset is too large,
525         // insert a new sub instead.
526         MachineOperand &MO =
527           MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3);
528         Offset = (Opc == ARM::tSUBi8) ?
529           MO.getImm() + WordOffset * 4 :
530           MO.getImm() - WordOffset * 4 ;
531         if (Offset >= 0 && TL->isLegalAddImmediate(Offset)) {
532           // FIXME: Swap ADDS<->SUBS if Offset < 0, erase instruction if
533           // Offset == 0.
534           MO.setImm(Offset);
535           // The base register has now been reset, so exit early.
536           return;
537         } else {
538           InsertSub = true;
539         }
540       } else {
541         // Can't update the instruction.
542         InsertSub = true;
543       }
544     } else if (definesCPSR(*MBBI) || MBBI->isCall() || MBBI->isBranch()) {
545       // Since SUBS sets the condition flags, we can't place the base reset
546       // after an instruction that has a live CPSR def.
547       // The base register might also contain an argument for a function call.
548       InsertSub = true;
549     }
550 
551     if (InsertSub) {
552       // An instruction above couldn't be updated, so insert a sub.
553       BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base)
554           .add(t1CondCodeOp(true))
555           .addReg(Base)
556           .addImm(WordOffset * 4)
557           .addImm(Pred)
558           .addReg(PredReg);
559       return;
560     }
561 
562     if (MBBI->killsRegister(Base) || MBBI->definesRegister(Base))
563       // Register got killed. Stop updating.
564       return;
565   }
566 
567   // End of block was reached.
568   if (!MBB.succ_empty()) {
569     // FIXME: Because of a bug, live registers are sometimes missing from
570     // the successor blocks' live-in sets. This means we can't trust that
571     // information and *always* have to reset at the end of a block.
572     // See PR21029.
573     if (MBBI != MBB.end()) --MBBI;
574     BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base)
575         .add(t1CondCodeOp(true))
576         .addReg(Base)
577         .addImm(WordOffset * 4)
578         .addImm(Pred)
579         .addReg(PredReg);
580   }
581 }
582 
583 /// Return the first register of class \p RegClass that is not in \p Regs.
584 unsigned ARMLoadStoreOpt::findFreeReg(const TargetRegisterClass &RegClass) {
585   if (!RegClassInfoValid) {
586     RegClassInfo.runOnMachineFunction(*MF);
587     RegClassInfoValid = true;
588   }
589 
590   for (unsigned Reg : RegClassInfo.getOrder(&RegClass))
591     if (LiveRegs.available(MF->getRegInfo(), Reg))
592       return Reg;
593   return 0;
594 }
595 
596 /// Compute live registers just before instruction \p Before (in normal schedule
597 /// direction). Computes backwards so multiple queries in the same block must
598 /// come in reverse order.
599 void ARMLoadStoreOpt::moveLiveRegsBefore(const MachineBasicBlock &MBB,
600     MachineBasicBlock::const_iterator Before) {
601   // Initialize if we never queried in this block.
602   if (!LiveRegsValid) {
603     LiveRegs.init(*TRI);
604     LiveRegs.addLiveOuts(MBB);
605     LiveRegPos = MBB.end();
606     LiveRegsValid = true;
607   }
608   // Move backward just before the "Before" position.
609   while (LiveRegPos != Before) {
610     --LiveRegPos;
611     LiveRegs.stepBackward(*LiveRegPos);
612   }
613 }
614 
615 static bool ContainsReg(const ArrayRef<std::pair<unsigned, bool>> &Regs,
616                         unsigned Reg) {
617   for (const std::pair<unsigned, bool> &R : Regs)
618     if (R.first == Reg)
619       return true;
620   return false;
621 }
622 
623 /// Create and insert a LDM or STM with Base as base register and registers in
624 /// Regs as the register operands that would be loaded / stored.  It returns
625 /// true if the transformation is done.
626 MachineInstr *ARMLoadStoreOpt::CreateLoadStoreMulti(
627     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
628     int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
629     ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
630     ArrayRef<std::pair<unsigned, bool>> Regs,
631     ArrayRef<MachineInstr*> Instrs) {
632   unsigned NumRegs = Regs.size();
633   assert(NumRegs > 1);
634 
635   // For Thumb1 targets, it might be necessary to clobber the CPSR to merge.
636   // Compute liveness information for that register to make the decision.
637   bool SafeToClobberCPSR = !isThumb1 ||
638     (MBB.computeRegisterLiveness(TRI, ARM::CPSR, InsertBefore, 20) ==
639      MachineBasicBlock::LQR_Dead);
640 
641   bool Writeback = isThumb1; // Thumb1 LDM/STM have base reg writeback.
642 
643   // Exception: If the base register is in the input reglist, Thumb1 LDM is
644   // non-writeback.
645   // It's also not possible to merge an STR of the base register in Thumb1.
646   if (isThumb1 && ContainsReg(Regs, Base)) {
647     assert(Base != ARM::SP && "Thumb1 does not allow SP in register list");
648     if (Opcode == ARM::tLDRi)
649       Writeback = false;
650     else if (Opcode == ARM::tSTRi)
651       return nullptr;
652   }
653 
654   ARM_AM::AMSubMode Mode = ARM_AM::ia;
655   // VFP and Thumb2 do not support IB or DA modes. Thumb1 only supports IA.
656   bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);
657   bool haveIBAndDA = isNotVFP && !isThumb2 && !isThumb1;
658 
659   if (Offset == 4 && haveIBAndDA) {
660     Mode = ARM_AM::ib;
661   } else if (Offset == -4 * (int)NumRegs + 4 && haveIBAndDA) {
662     Mode = ARM_AM::da;
663   } else if (Offset == -4 * (int)NumRegs && isNotVFP && !isThumb1) {
664     // VLDM/VSTM do not support DB mode without also updating the base reg.
665     Mode = ARM_AM::db;
666   } else if (Offset != 0 || Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi) {
667     // Check if this is a supported opcode before inserting instructions to
668     // calculate a new base register.
669     if (!getLoadStoreMultipleOpcode(Opcode, Mode)) return nullptr;
670 
671     // If starting offset isn't zero, insert a MI to materialize a new base.
672     // But only do so if it is cost effective, i.e. merging more than two
673     // loads / stores.
674     if (NumRegs <= 2)
675       return nullptr;
676 
677     // On Thumb1, it's not worth materializing a new base register without
678     // clobbering the CPSR (i.e. not using ADDS/SUBS).
679     if (!SafeToClobberCPSR)
680       return nullptr;
681 
682     unsigned NewBase;
683     if (isi32Load(Opcode)) {
684       // If it is a load, then just use one of the destination registers
685       // as the new base. Will no longer be writeback in Thumb1.
686       NewBase = Regs[NumRegs-1].first;
687       Writeback = false;
688     } else {
689       // Find a free register that we can use as scratch register.
690       moveLiveRegsBefore(MBB, InsertBefore);
691       // The merged instruction does not exist yet but will use several Regs if
692       // it is a Store.
693       if (!isLoadSingle(Opcode))
694         for (const std::pair<unsigned, bool> &R : Regs)
695           LiveRegs.addReg(R.first);
696 
697       NewBase = findFreeReg(isThumb1 ? ARM::tGPRRegClass : ARM::GPRRegClass);
698       if (NewBase == 0)
699         return nullptr;
700     }
701 
702     int BaseOpc = isThumb2 ? (BaseKill && Base == ARM::SP ? ARM::t2ADDspImm
703                                                           : ARM::t2ADDri)
704                            : (isThumb1 && Base == ARM::SP)
705                                  ? ARM::tADDrSPi
706                                  : (isThumb1 && Offset < 8)
707                                        ? ARM::tADDi3
708                                        : isThumb1 ? ARM::tADDi8 : ARM::ADDri;
709 
710     if (Offset < 0) {
711       // FIXME: There are no Thumb1 load/store instructions with negative
712       // offsets. So the Base != ARM::SP might be unnecessary.
713       Offset = -Offset;
714       BaseOpc = isThumb2 ? (BaseKill && Base == ARM::SP ? ARM::t2SUBspImm
715                                                         : ARM::t2SUBri)
716                          : (isThumb1 && Offset < 8 && Base != ARM::SP)
717                                ? ARM::tSUBi3
718                                : isThumb1 ? ARM::tSUBi8 : ARM::SUBri;
719     }
720 
721     if (!TL->isLegalAddImmediate(Offset))
722       // FIXME: Try add with register operand?
723       return nullptr; // Probably not worth it then.
724 
725     // We can only append a kill flag to the add/sub input if the value is not
726     // used in the register list of the stm as well.
727     bool KillOldBase = BaseKill &&
728       (!isi32Store(Opcode) || !ContainsReg(Regs, Base));
729 
730     if (isThumb1) {
731       // Thumb1: depending on immediate size, use either
732       //   ADDS NewBase, Base, #imm3
733       // or
734       //   MOV  NewBase, Base
735       //   ADDS NewBase, #imm8.
736       if (Base != NewBase &&
737           (BaseOpc == ARM::tADDi8 || BaseOpc == ARM::tSUBi8)) {
738         // Need to insert a MOV to the new base first.
739         if (isARMLowRegister(NewBase) && isARMLowRegister(Base) &&
740             !STI->hasV6Ops()) {
741           // thumbv4t doesn't have lo->lo copies, and we can't predicate tMOVSr
742           if (Pred != ARMCC::AL)
743             return nullptr;
744           BuildMI(MBB, InsertBefore, DL, TII->get(ARM::tMOVSr), NewBase)
745             .addReg(Base, getKillRegState(KillOldBase));
746         } else
747           BuildMI(MBB, InsertBefore, DL, TII->get(ARM::tMOVr), NewBase)
748               .addReg(Base, getKillRegState(KillOldBase))
749               .add(predOps(Pred, PredReg));
750 
751         // The following ADDS/SUBS becomes an update.
752         Base = NewBase;
753         KillOldBase = true;
754       }
755       if (BaseOpc == ARM::tADDrSPi) {
756         assert(Offset % 4 == 0 && "tADDrSPi offset is scaled by 4");
757         BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
758             .addReg(Base, getKillRegState(KillOldBase))
759             .addImm(Offset / 4)
760             .add(predOps(Pred, PredReg));
761       } else
762         BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
763             .add(t1CondCodeOp(true))
764             .addReg(Base, getKillRegState(KillOldBase))
765             .addImm(Offset)
766             .add(predOps(Pred, PredReg));
767     } else {
768       BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
769           .addReg(Base, getKillRegState(KillOldBase))
770           .addImm(Offset)
771           .add(predOps(Pred, PredReg))
772           .add(condCodeOp());
773     }
774     Base = NewBase;
775     BaseKill = true; // New base is always killed straight away.
776   }
777 
778   bool isDef = isLoadSingle(Opcode);
779 
780   // Get LS multiple opcode. Note that for Thumb1 this might be an opcode with
781   // base register writeback.
782   Opcode = getLoadStoreMultipleOpcode(Opcode, Mode);
783   if (!Opcode)
784     return nullptr;
785 
786   // Check if a Thumb1 LDM/STM merge is safe. This is the case if:
787   // - There is no writeback (LDM of base register),
788   // - the base register is killed by the merged instruction,
789   // - or it's safe to overwrite the condition flags, i.e. to insert a SUBS
790   //   to reset the base register.
791   // Otherwise, don't merge.
792   // It's safe to return here since the code to materialize a new base register
793   // above is also conditional on SafeToClobberCPSR.
794   if (isThumb1 && !SafeToClobberCPSR && Writeback && !BaseKill)
795     return nullptr;
796 
797   MachineInstrBuilder MIB;
798 
799   if (Writeback) {
800     assert(isThumb1 && "expected Writeback only inThumb1");
801     if (Opcode == ARM::tLDMIA) {
802       assert(!(ContainsReg(Regs, Base)) && "Thumb1 can't LDM ! with Base in Regs");
803       // Update tLDMIA with writeback if necessary.
804       Opcode = ARM::tLDMIA_UPD;
805     }
806 
807     MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode));
808 
809     // Thumb1: we might need to set base writeback when building the MI.
810     MIB.addReg(Base, getDefRegState(true))
811        .addReg(Base, getKillRegState(BaseKill));
812 
813     // The base isn't dead after a merged instruction with writeback.
814     // Insert a sub instruction after the newly formed instruction to reset.
815     if (!BaseKill)
816       UpdateBaseRegUses(MBB, InsertBefore, DL, Base, NumRegs, Pred, PredReg);
817   } else {
818     // No writeback, simply build the MachineInstr.
819     MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode));
820     MIB.addReg(Base, getKillRegState(BaseKill));
821   }
822 
823   MIB.addImm(Pred).addReg(PredReg);
824 
825   for (const std::pair<unsigned, bool> &R : Regs)
826     MIB.addReg(R.first, getDefRegState(isDef) | getKillRegState(R.second));
827 
828   MIB.cloneMergedMemRefs(Instrs);
829 
830   return MIB.getInstr();
831 }
832 
833 MachineInstr *ARMLoadStoreOpt::CreateLoadStoreDouble(
834     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
835     int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
836     ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
837     ArrayRef<std::pair<unsigned, bool>> Regs,
838     ArrayRef<MachineInstr*> Instrs) const {
839   bool IsLoad = isi32Load(Opcode);
840   assert((IsLoad || isi32Store(Opcode)) && "Must have integer load or store");
841   unsigned LoadStoreOpcode = IsLoad ? ARM::t2LDRDi8 : ARM::t2STRDi8;
842 
843   assert(Regs.size() == 2);
844   MachineInstrBuilder MIB = BuildMI(MBB, InsertBefore, DL,
845                                     TII->get(LoadStoreOpcode));
846   if (IsLoad) {
847     MIB.addReg(Regs[0].first, RegState::Define)
848        .addReg(Regs[1].first, RegState::Define);
849   } else {
850     MIB.addReg(Regs[0].first, getKillRegState(Regs[0].second))
851        .addReg(Regs[1].first, getKillRegState(Regs[1].second));
852   }
853   MIB.addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
854   MIB.cloneMergedMemRefs(Instrs);
855   return MIB.getInstr();
856 }
857 
858 /// Call MergeOps and update MemOps and merges accordingly on success.
859 MachineInstr *ARMLoadStoreOpt::MergeOpsUpdate(const MergeCandidate &Cand) {
860   const MachineInstr *First = Cand.Instrs.front();
861   unsigned Opcode = First->getOpcode();
862   bool IsLoad = isLoadSingle(Opcode);
863   SmallVector<std::pair<unsigned, bool>, 8> Regs;
864   SmallVector<unsigned, 4> ImpDefs;
865   DenseSet<unsigned> KilledRegs;
866   DenseSet<unsigned> UsedRegs;
867   // Determine list of registers and list of implicit super-register defs.
868   for (const MachineInstr *MI : Cand.Instrs) {
869     const MachineOperand &MO = getLoadStoreRegOp(*MI);
870     Register Reg = MO.getReg();
871     bool IsKill = MO.isKill();
872     if (IsKill)
873       KilledRegs.insert(Reg);
874     Regs.push_back(std::make_pair(Reg, IsKill));
875     UsedRegs.insert(Reg);
876 
877     if (IsLoad) {
878       // Collect any implicit defs of super-registers, after merging we can't
879       // be sure anymore that we properly preserved these live ranges and must
880       // removed these implicit operands.
881       for (const MachineOperand &MO : MI->implicit_operands()) {
882         if (!MO.isReg() || !MO.isDef() || MO.isDead())
883           continue;
884         assert(MO.isImplicit());
885         Register DefReg = MO.getReg();
886 
887         if (is_contained(ImpDefs, DefReg))
888           continue;
889         // We can ignore cases where the super-reg is read and written.
890         if (MI->readsRegister(DefReg))
891           continue;
892         ImpDefs.push_back(DefReg);
893       }
894     }
895   }
896 
897   // Attempt the merge.
898   using iterator = MachineBasicBlock::iterator;
899 
900   MachineInstr *LatestMI = Cand.Instrs[Cand.LatestMIIdx];
901   iterator InsertBefore = std::next(iterator(LatestMI));
902   MachineBasicBlock &MBB = *LatestMI->getParent();
903   unsigned Offset = getMemoryOpOffset(*First);
904   Register Base = getLoadStoreBaseOp(*First).getReg();
905   bool BaseKill = LatestMI->killsRegister(Base);
906   Register PredReg;
907   ARMCC::CondCodes Pred = getInstrPredicate(*First, PredReg);
908   DebugLoc DL = First->getDebugLoc();
909   MachineInstr *Merged = nullptr;
910   if (Cand.CanMergeToLSDouble)
911     Merged = CreateLoadStoreDouble(MBB, InsertBefore, Offset, Base, BaseKill,
912                                    Opcode, Pred, PredReg, DL, Regs,
913                                    Cand.Instrs);
914   if (!Merged && Cand.CanMergeToLSMulti)
915     Merged = CreateLoadStoreMulti(MBB, InsertBefore, Offset, Base, BaseKill,
916                                   Opcode, Pred, PredReg, DL, Regs, Cand.Instrs);
917   if (!Merged)
918     return nullptr;
919 
920   // Determine earliest instruction that will get removed. We then keep an
921   // iterator just above it so the following erases don't invalidated it.
922   iterator EarliestI(Cand.Instrs[Cand.EarliestMIIdx]);
923   bool EarliestAtBegin = false;
924   if (EarliestI == MBB.begin()) {
925     EarliestAtBegin = true;
926   } else {
927     EarliestI = std::prev(EarliestI);
928   }
929 
930   // Remove instructions which have been merged.
931   for (MachineInstr *MI : Cand.Instrs)
932     MBB.erase(MI);
933 
934   // Determine range between the earliest removed instruction and the new one.
935   if (EarliestAtBegin)
936     EarliestI = MBB.begin();
937   else
938     EarliestI = std::next(EarliestI);
939   auto FixupRange = make_range(EarliestI, iterator(Merged));
940 
941   if (isLoadSingle(Opcode)) {
942     // If the previous loads defined a super-reg, then we have to mark earlier
943     // operands undef; Replicate the super-reg def on the merged instruction.
944     for (MachineInstr &MI : FixupRange) {
945       for (unsigned &ImpDefReg : ImpDefs) {
946         for (MachineOperand &MO : MI.implicit_operands()) {
947           if (!MO.isReg() || MO.getReg() != ImpDefReg)
948             continue;
949           if (MO.readsReg())
950             MO.setIsUndef();
951           else if (MO.isDef())
952             ImpDefReg = 0;
953         }
954       }
955     }
956 
957     MachineInstrBuilder MIB(*Merged->getParent()->getParent(), Merged);
958     for (unsigned ImpDef : ImpDefs)
959       MIB.addReg(ImpDef, RegState::ImplicitDefine);
960   } else {
961     // Remove kill flags: We are possibly storing the values later now.
962     assert(isi32Store(Opcode) || Opcode == ARM::VSTRS || Opcode == ARM::VSTRD);
963     for (MachineInstr &MI : FixupRange) {
964       for (MachineOperand &MO : MI.uses()) {
965         if (!MO.isReg() || !MO.isKill())
966           continue;
967         if (UsedRegs.count(MO.getReg()))
968           MO.setIsKill(false);
969       }
970     }
971     assert(ImpDefs.empty());
972   }
973 
974   return Merged;
975 }
976 
977 static bool isValidLSDoubleOffset(int Offset) {
978   unsigned Value = abs(Offset);
979   // t2LDRDi8/t2STRDi8 supports an 8 bit immediate which is internally
980   // multiplied by 4.
981   return (Value % 4) == 0 && Value < 1024;
982 }
983 
984 /// Return true for loads/stores that can be combined to a double/multi
985 /// operation without increasing the requirements for alignment.
986 static bool mayCombineMisaligned(const TargetSubtargetInfo &STI,
987                                  const MachineInstr &MI) {
988   // vldr/vstr trap on misaligned pointers anyway, forming vldm makes no
989   // difference.
990   unsigned Opcode = MI.getOpcode();
991   if (!isi32Load(Opcode) && !isi32Store(Opcode))
992     return true;
993 
994   // Stack pointer alignment is out of the programmers control so we can trust
995   // SP-relative loads/stores.
996   if (getLoadStoreBaseOp(MI).getReg() == ARM::SP &&
997       STI.getFrameLowering()->getTransientStackAlign() >= Align(4))
998     return true;
999   return false;
1000 }
1001 
1002 /// Find candidates for load/store multiple merge in list of MemOpQueueEntries.
1003 void ARMLoadStoreOpt::FormCandidates(const MemOpQueue &MemOps) {
1004   const MachineInstr *FirstMI = MemOps[0].MI;
1005   unsigned Opcode = FirstMI->getOpcode();
1006   bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);
1007   unsigned Size = getLSMultipleTransferSize(FirstMI);
1008 
1009   unsigned SIndex = 0;
1010   unsigned EIndex = MemOps.size();
1011   do {
1012     // Look at the first instruction.
1013     const MachineInstr *MI = MemOps[SIndex].MI;
1014     int Offset = MemOps[SIndex].Offset;
1015     const MachineOperand &PMO = getLoadStoreRegOp(*MI);
1016     Register PReg = PMO.getReg();
1017     unsigned PRegNum = PMO.isUndef() ? std::numeric_limits<unsigned>::max()
1018                                      : TRI->getEncodingValue(PReg);
1019     unsigned Latest = SIndex;
1020     unsigned Earliest = SIndex;
1021     unsigned Count = 1;
1022     bool CanMergeToLSDouble =
1023       STI->isThumb2() && isNotVFP && isValidLSDoubleOffset(Offset);
1024     // ARM errata 602117: LDRD with base in list may result in incorrect base
1025     // register when interrupted or faulted.
1026     if (STI->isCortexM3() && isi32Load(Opcode) &&
1027         PReg == getLoadStoreBaseOp(*MI).getReg())
1028       CanMergeToLSDouble = false;
1029 
1030     bool CanMergeToLSMulti = true;
1031     // On swift vldm/vstm starting with an odd register number as that needs
1032     // more uops than single vldrs.
1033     if (STI->hasSlowOddRegister() && !isNotVFP && (PRegNum % 2) == 1)
1034       CanMergeToLSMulti = false;
1035 
1036     // LDRD/STRD do not allow SP/PC. LDM/STM do not support it or have it
1037     // deprecated; LDM to PC is fine but cannot happen here.
1038     if (PReg == ARM::SP || PReg == ARM::PC)
1039       CanMergeToLSMulti = CanMergeToLSDouble = false;
1040 
1041     // Should we be conservative?
1042     if (AssumeMisalignedLoadStores && !mayCombineMisaligned(*STI, *MI))
1043       CanMergeToLSMulti = CanMergeToLSDouble = false;
1044 
1045     // vldm / vstm limit are 32 for S variants, 16 for D variants.
1046     unsigned Limit;
1047     switch (Opcode) {
1048     default:
1049       Limit = UINT_MAX;
1050       break;
1051     case ARM::VLDRD:
1052     case ARM::VSTRD:
1053       Limit = 16;
1054       break;
1055     }
1056 
1057     // Merge following instructions where possible.
1058     for (unsigned I = SIndex+1; I < EIndex; ++I, ++Count) {
1059       int NewOffset = MemOps[I].Offset;
1060       if (NewOffset != Offset + (int)Size)
1061         break;
1062       const MachineOperand &MO = getLoadStoreRegOp(*MemOps[I].MI);
1063       Register Reg = MO.getReg();
1064       if (Reg == ARM::SP || Reg == ARM::PC)
1065         break;
1066       if (Count == Limit)
1067         break;
1068 
1069       // See if the current load/store may be part of a multi load/store.
1070       unsigned RegNum = MO.isUndef() ? std::numeric_limits<unsigned>::max()
1071                                      : TRI->getEncodingValue(Reg);
1072       bool PartOfLSMulti = CanMergeToLSMulti;
1073       if (PartOfLSMulti) {
1074         // Register numbers must be in ascending order.
1075         if (RegNum <= PRegNum)
1076           PartOfLSMulti = false;
1077         // For VFP / NEON load/store multiples, the registers must be
1078         // consecutive and within the limit on the number of registers per
1079         // instruction.
1080         else if (!isNotVFP && RegNum != PRegNum+1)
1081           PartOfLSMulti = false;
1082       }
1083       // See if the current load/store may be part of a double load/store.
1084       bool PartOfLSDouble = CanMergeToLSDouble && Count <= 1;
1085 
1086       if (!PartOfLSMulti && !PartOfLSDouble)
1087         break;
1088       CanMergeToLSMulti &= PartOfLSMulti;
1089       CanMergeToLSDouble &= PartOfLSDouble;
1090       // Track MemOp with latest and earliest position (Positions are
1091       // counted in reverse).
1092       unsigned Position = MemOps[I].Position;
1093       if (Position < MemOps[Latest].Position)
1094         Latest = I;
1095       else if (Position > MemOps[Earliest].Position)
1096         Earliest = I;
1097       // Prepare for next MemOp.
1098       Offset += Size;
1099       PRegNum = RegNum;
1100     }
1101 
1102     // Form a candidate from the Ops collected so far.
1103     MergeCandidate *Candidate = new(Allocator.Allocate()) MergeCandidate;
1104     for (unsigned C = SIndex, CE = SIndex + Count; C < CE; ++C)
1105       Candidate->Instrs.push_back(MemOps[C].MI);
1106     Candidate->LatestMIIdx = Latest - SIndex;
1107     Candidate->EarliestMIIdx = Earliest - SIndex;
1108     Candidate->InsertPos = MemOps[Latest].Position;
1109     if (Count == 1)
1110       CanMergeToLSMulti = CanMergeToLSDouble = false;
1111     Candidate->CanMergeToLSMulti = CanMergeToLSMulti;
1112     Candidate->CanMergeToLSDouble = CanMergeToLSDouble;
1113     Candidates.push_back(Candidate);
1114     // Continue after the chain.
1115     SIndex += Count;
1116   } while (SIndex < EIndex);
1117 }
1118 
1119 static unsigned getUpdatingLSMultipleOpcode(unsigned Opc,
1120                                             ARM_AM::AMSubMode Mode) {
1121   switch (Opc) {
1122   default: llvm_unreachable("Unhandled opcode!");
1123   case ARM::LDMIA:
1124   case ARM::LDMDA:
1125   case ARM::LDMDB:
1126   case ARM::LDMIB:
1127     switch (Mode) {
1128     default: llvm_unreachable("Unhandled submode!");
1129     case ARM_AM::ia: return ARM::LDMIA_UPD;
1130     case ARM_AM::ib: return ARM::LDMIB_UPD;
1131     case ARM_AM::da: return ARM::LDMDA_UPD;
1132     case ARM_AM::db: return ARM::LDMDB_UPD;
1133     }
1134   case ARM::STMIA:
1135   case ARM::STMDA:
1136   case ARM::STMDB:
1137   case ARM::STMIB:
1138     switch (Mode) {
1139     default: llvm_unreachable("Unhandled submode!");
1140     case ARM_AM::ia: return ARM::STMIA_UPD;
1141     case ARM_AM::ib: return ARM::STMIB_UPD;
1142     case ARM_AM::da: return ARM::STMDA_UPD;
1143     case ARM_AM::db: return ARM::STMDB_UPD;
1144     }
1145   case ARM::t2LDMIA:
1146   case ARM::t2LDMDB:
1147     switch (Mode) {
1148     default: llvm_unreachable("Unhandled submode!");
1149     case ARM_AM::ia: return ARM::t2LDMIA_UPD;
1150     case ARM_AM::db: return ARM::t2LDMDB_UPD;
1151     }
1152   case ARM::t2STMIA:
1153   case ARM::t2STMDB:
1154     switch (Mode) {
1155     default: llvm_unreachable("Unhandled submode!");
1156     case ARM_AM::ia: return ARM::t2STMIA_UPD;
1157     case ARM_AM::db: return ARM::t2STMDB_UPD;
1158     }
1159   case ARM::VLDMSIA:
1160     switch (Mode) {
1161     default: llvm_unreachable("Unhandled submode!");
1162     case ARM_AM::ia: return ARM::VLDMSIA_UPD;
1163     case ARM_AM::db: return ARM::VLDMSDB_UPD;
1164     }
1165   case ARM::VLDMDIA:
1166     switch (Mode) {
1167     default: llvm_unreachable("Unhandled submode!");
1168     case ARM_AM::ia: return ARM::VLDMDIA_UPD;
1169     case ARM_AM::db: return ARM::VLDMDDB_UPD;
1170     }
1171   case ARM::VSTMSIA:
1172     switch (Mode) {
1173     default: llvm_unreachable("Unhandled submode!");
1174     case ARM_AM::ia: return ARM::VSTMSIA_UPD;
1175     case ARM_AM::db: return ARM::VSTMSDB_UPD;
1176     }
1177   case ARM::VSTMDIA:
1178     switch (Mode) {
1179     default: llvm_unreachable("Unhandled submode!");
1180     case ARM_AM::ia: return ARM::VSTMDIA_UPD;
1181     case ARM_AM::db: return ARM::VSTMDDB_UPD;
1182     }
1183   }
1184 }
1185 
1186 /// Check if the given instruction increments or decrements a register and
1187 /// return the amount it is incremented/decremented. Returns 0 if the CPSR flags
1188 /// generated by the instruction are possibly read as well.
1189 static int isIncrementOrDecrement(const MachineInstr &MI, Register Reg,
1190                                   ARMCC::CondCodes Pred, Register PredReg) {
1191   bool CheckCPSRDef;
1192   int Scale;
1193   switch (MI.getOpcode()) {
1194   case ARM::tADDi8:  Scale =  4; CheckCPSRDef = true; break;
1195   case ARM::tSUBi8:  Scale = -4; CheckCPSRDef = true; break;
1196   case ARM::t2SUBri:
1197   case ARM::t2SUBspImm:
1198   case ARM::SUBri:   Scale = -1; CheckCPSRDef = true; break;
1199   case ARM::t2ADDri:
1200   case ARM::t2ADDspImm:
1201   case ARM::ADDri:   Scale =  1; CheckCPSRDef = true; break;
1202   case ARM::tADDspi: Scale =  4; CheckCPSRDef = false; break;
1203   case ARM::tSUBspi: Scale = -4; CheckCPSRDef = false; break;
1204   default: return 0;
1205   }
1206 
1207   Register MIPredReg;
1208   if (MI.getOperand(0).getReg() != Reg ||
1209       MI.getOperand(1).getReg() != Reg ||
1210       getInstrPredicate(MI, MIPredReg) != Pred ||
1211       MIPredReg != PredReg)
1212     return 0;
1213 
1214   if (CheckCPSRDef && definesCPSR(MI))
1215     return 0;
1216   return MI.getOperand(2).getImm() * Scale;
1217 }
1218 
1219 /// Searches for an increment or decrement of \p Reg before \p MBBI.
1220 static MachineBasicBlock::iterator
1221 findIncDecBefore(MachineBasicBlock::iterator MBBI, Register Reg,
1222                  ARMCC::CondCodes Pred, Register PredReg, int &Offset) {
1223   Offset = 0;
1224   MachineBasicBlock &MBB = *MBBI->getParent();
1225   MachineBasicBlock::iterator BeginMBBI = MBB.begin();
1226   MachineBasicBlock::iterator EndMBBI = MBB.end();
1227   if (MBBI == BeginMBBI)
1228     return EndMBBI;
1229 
1230   // Skip debug values.
1231   MachineBasicBlock::iterator PrevMBBI = std::prev(MBBI);
1232   while (PrevMBBI->isDebugInstr() && PrevMBBI != BeginMBBI)
1233     --PrevMBBI;
1234 
1235   Offset = isIncrementOrDecrement(*PrevMBBI, Reg, Pred, PredReg);
1236   return Offset == 0 ? EndMBBI : PrevMBBI;
1237 }
1238 
1239 /// Searches for a increment or decrement of \p Reg after \p MBBI.
1240 static MachineBasicBlock::iterator
1241 findIncDecAfter(MachineBasicBlock::iterator MBBI, Register Reg,
1242                 ARMCC::CondCodes Pred, Register PredReg, int &Offset,
1243                 const TargetRegisterInfo *TRI) {
1244   Offset = 0;
1245   MachineBasicBlock &MBB = *MBBI->getParent();
1246   MachineBasicBlock::iterator EndMBBI = MBB.end();
1247   MachineBasicBlock::iterator NextMBBI = std::next(MBBI);
1248   while (NextMBBI != EndMBBI) {
1249     // Skip debug values.
1250     while (NextMBBI != EndMBBI && NextMBBI->isDebugInstr())
1251       ++NextMBBI;
1252     if (NextMBBI == EndMBBI)
1253       return EndMBBI;
1254 
1255     unsigned Off = isIncrementOrDecrement(*NextMBBI, Reg, Pred, PredReg);
1256     if (Off) {
1257       Offset = Off;
1258       return NextMBBI;
1259     }
1260 
1261     // SP can only be combined if it is the next instruction after the original
1262     // MBBI, otherwise we may be incrementing the stack pointer (invalidating
1263     // anything below the new pointer) when its frame elements are still in
1264     // use. Other registers can attempt to look further, until a different use
1265     // or def of the register is found.
1266     if (Reg == ARM::SP || NextMBBI->readsRegister(Reg, TRI) ||
1267         NextMBBI->definesRegister(Reg, TRI))
1268       return EndMBBI;
1269 
1270     ++NextMBBI;
1271   }
1272   return EndMBBI;
1273 }
1274 
1275 /// Fold proceeding/trailing inc/dec of base register into the
1276 /// LDM/STM/VLDM{D|S}/VSTM{D|S} op when possible:
1277 ///
1278 /// stmia rn, <ra, rb, rc>
1279 /// rn := rn + 4 * 3;
1280 /// =>
1281 /// stmia rn!, <ra, rb, rc>
1282 ///
1283 /// rn := rn - 4 * 3;
1284 /// ldmia rn, <ra, rb, rc>
1285 /// =>
1286 /// ldmdb rn!, <ra, rb, rc>
1287 bool ARMLoadStoreOpt::MergeBaseUpdateLSMultiple(MachineInstr *MI) {
1288   // Thumb1 is already using updating loads/stores.
1289   if (isThumb1) return false;
1290   LLVM_DEBUG(dbgs() << "Attempting to merge update of: " << *MI);
1291 
1292   const MachineOperand &BaseOP = MI->getOperand(0);
1293   Register Base = BaseOP.getReg();
1294   bool BaseKill = BaseOP.isKill();
1295   Register PredReg;
1296   ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
1297   unsigned Opcode = MI->getOpcode();
1298   DebugLoc DL = MI->getDebugLoc();
1299 
1300   // Can't use an updating ld/st if the base register is also a dest
1301   // register. e.g. ldmdb r0!, {r0, r1, r2}. The behavior is undefined.
1302   for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))
1303     if (MO.getReg() == Base)
1304       return false;
1305 
1306   int Bytes = getLSMultipleTransferSize(MI);
1307   MachineBasicBlock &MBB = *MI->getParent();
1308   MachineBasicBlock::iterator MBBI(MI);
1309   int Offset;
1310   MachineBasicBlock::iterator MergeInstr
1311     = findIncDecBefore(MBBI, Base, Pred, PredReg, Offset);
1312   ARM_AM::AMSubMode Mode = getLoadStoreMultipleSubMode(Opcode);
1313   if (Mode == ARM_AM::ia && Offset == -Bytes) {
1314     Mode = ARM_AM::db;
1315   } else if (Mode == ARM_AM::ib && Offset == -Bytes) {
1316     Mode = ARM_AM::da;
1317   } else {
1318     MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset, TRI);
1319     if (((Mode != ARM_AM::ia && Mode != ARM_AM::ib) || Offset != Bytes) &&
1320         ((Mode != ARM_AM::da && Mode != ARM_AM::db) || Offset != -Bytes)) {
1321 
1322       // We couldn't find an inc/dec to merge. But if the base is dead, we
1323       // can still change to a writeback form as that will save us 2 bytes
1324       // of code size. It can create WAW hazards though, so only do it if
1325       // we're minimizing code size.
1326       if (!STI->hasMinSize() || !BaseKill)
1327         return false;
1328 
1329       bool HighRegsUsed = false;
1330       for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))
1331         if (MO.getReg() >= ARM::R8) {
1332           HighRegsUsed = true;
1333           break;
1334         }
1335 
1336       if (!HighRegsUsed)
1337         MergeInstr = MBB.end();
1338       else
1339         return false;
1340     }
1341   }
1342   if (MergeInstr != MBB.end()) {
1343     LLVM_DEBUG(dbgs() << "  Erasing old increment: " << *MergeInstr);
1344     MBB.erase(MergeInstr);
1345   }
1346 
1347   unsigned NewOpc = getUpdatingLSMultipleOpcode(Opcode, Mode);
1348   MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
1349     .addReg(Base, getDefRegState(true)) // WB base register
1350     .addReg(Base, getKillRegState(BaseKill))
1351     .addImm(Pred).addReg(PredReg);
1352 
1353   // Transfer the rest of operands.
1354   for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 3))
1355     MIB.add(MO);
1356 
1357   // Transfer memoperands.
1358   MIB.setMemRefs(MI->memoperands());
1359 
1360   LLVM_DEBUG(dbgs() << "  Added new load/store: " << *MIB);
1361   MBB.erase(MBBI);
1362   return true;
1363 }
1364 
1365 static unsigned getPreIndexedLoadStoreOpcode(unsigned Opc,
1366                                              ARM_AM::AddrOpc Mode) {
1367   switch (Opc) {
1368   case ARM::LDRi12:
1369     return ARM::LDR_PRE_IMM;
1370   case ARM::STRi12:
1371     return ARM::STR_PRE_IMM;
1372   case ARM::VLDRS:
1373     return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;
1374   case ARM::VLDRD:
1375     return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;
1376   case ARM::VSTRS:
1377     return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;
1378   case ARM::VSTRD:
1379     return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;
1380   case ARM::t2LDRi8:
1381   case ARM::t2LDRi12:
1382     return ARM::t2LDR_PRE;
1383   case ARM::t2STRi8:
1384   case ARM::t2STRi12:
1385     return ARM::t2STR_PRE;
1386   default: llvm_unreachable("Unhandled opcode!");
1387   }
1388 }
1389 
1390 static unsigned getPostIndexedLoadStoreOpcode(unsigned Opc,
1391                                               ARM_AM::AddrOpc Mode) {
1392   switch (Opc) {
1393   case ARM::LDRi12:
1394     return ARM::LDR_POST_IMM;
1395   case ARM::STRi12:
1396     return ARM::STR_POST_IMM;
1397   case ARM::VLDRS:
1398     return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;
1399   case ARM::VLDRD:
1400     return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;
1401   case ARM::VSTRS:
1402     return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;
1403   case ARM::VSTRD:
1404     return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;
1405   case ARM::t2LDRi8:
1406   case ARM::t2LDRi12:
1407     return ARM::t2LDR_POST;
1408   case ARM::t2LDRBi8:
1409   case ARM::t2LDRBi12:
1410     return ARM::t2LDRB_POST;
1411   case ARM::t2LDRSBi8:
1412   case ARM::t2LDRSBi12:
1413     return ARM::t2LDRSB_POST;
1414   case ARM::t2LDRHi8:
1415   case ARM::t2LDRHi12:
1416     return ARM::t2LDRH_POST;
1417   case ARM::t2LDRSHi8:
1418   case ARM::t2LDRSHi12:
1419     return ARM::t2LDRSH_POST;
1420   case ARM::t2STRi8:
1421   case ARM::t2STRi12:
1422     return ARM::t2STR_POST;
1423   case ARM::t2STRBi8:
1424   case ARM::t2STRBi12:
1425     return ARM::t2STRB_POST;
1426   case ARM::t2STRHi8:
1427   case ARM::t2STRHi12:
1428     return ARM::t2STRH_POST;
1429 
1430   case ARM::MVE_VLDRBS16:
1431     return ARM::MVE_VLDRBS16_post;
1432   case ARM::MVE_VLDRBS32:
1433     return ARM::MVE_VLDRBS32_post;
1434   case ARM::MVE_VLDRBU16:
1435     return ARM::MVE_VLDRBU16_post;
1436   case ARM::MVE_VLDRBU32:
1437     return ARM::MVE_VLDRBU32_post;
1438   case ARM::MVE_VLDRHS32:
1439     return ARM::MVE_VLDRHS32_post;
1440   case ARM::MVE_VLDRHU32:
1441     return ARM::MVE_VLDRHU32_post;
1442   case ARM::MVE_VLDRBU8:
1443     return ARM::MVE_VLDRBU8_post;
1444   case ARM::MVE_VLDRHU16:
1445     return ARM::MVE_VLDRHU16_post;
1446   case ARM::MVE_VLDRWU32:
1447     return ARM::MVE_VLDRWU32_post;
1448   case ARM::MVE_VSTRB16:
1449     return ARM::MVE_VSTRB16_post;
1450   case ARM::MVE_VSTRB32:
1451     return ARM::MVE_VSTRB32_post;
1452   case ARM::MVE_VSTRH32:
1453     return ARM::MVE_VSTRH32_post;
1454   case ARM::MVE_VSTRBU8:
1455     return ARM::MVE_VSTRBU8_post;
1456   case ARM::MVE_VSTRHU16:
1457     return ARM::MVE_VSTRHU16_post;
1458   case ARM::MVE_VSTRWU32:
1459     return ARM::MVE_VSTRWU32_post;
1460 
1461   default: llvm_unreachable("Unhandled opcode!");
1462   }
1463 }
1464 
1465 /// Fold proceeding/trailing inc/dec of base register into the
1466 /// LDR/STR/FLD{D|S}/FST{D|S} op when possible:
1467 bool ARMLoadStoreOpt::MergeBaseUpdateLoadStore(MachineInstr *MI) {
1468   // Thumb1 doesn't have updating LDR/STR.
1469   // FIXME: Use LDM/STM with single register instead.
1470   if (isThumb1) return false;
1471   LLVM_DEBUG(dbgs() << "Attempting to merge update of: " << *MI);
1472 
1473   Register Base = getLoadStoreBaseOp(*MI).getReg();
1474   bool BaseKill = getLoadStoreBaseOp(*MI).isKill();
1475   unsigned Opcode = MI->getOpcode();
1476   DebugLoc DL = MI->getDebugLoc();
1477   bool isAM5 = (Opcode == ARM::VLDRD || Opcode == ARM::VLDRS ||
1478                 Opcode == ARM::VSTRD || Opcode == ARM::VSTRS);
1479   bool isAM2 = (Opcode == ARM::LDRi12 || Opcode == ARM::STRi12);
1480   if (isi32Load(Opcode) || isi32Store(Opcode))
1481     if (MI->getOperand(2).getImm() != 0)
1482       return false;
1483   if (isAM5 && ARM_AM::getAM5Offset(MI->getOperand(2).getImm()) != 0)
1484     return false;
1485 
1486   // Can't do the merge if the destination register is the same as the would-be
1487   // writeback register.
1488   if (MI->getOperand(0).getReg() == Base)
1489     return false;
1490 
1491   Register PredReg;
1492   ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
1493   int Bytes = getLSMultipleTransferSize(MI);
1494   MachineBasicBlock &MBB = *MI->getParent();
1495   MachineBasicBlock::iterator MBBI(MI);
1496   int Offset;
1497   MachineBasicBlock::iterator MergeInstr
1498     = findIncDecBefore(MBBI, Base, Pred, PredReg, Offset);
1499   unsigned NewOpc;
1500   if (!isAM5 && Offset == Bytes) {
1501     NewOpc = getPreIndexedLoadStoreOpcode(Opcode, ARM_AM::add);
1502   } else if (Offset == -Bytes) {
1503     NewOpc = getPreIndexedLoadStoreOpcode(Opcode, ARM_AM::sub);
1504   } else {
1505     MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset, TRI);
1506     if (MergeInstr == MBB.end())
1507       return false;
1508 
1509     NewOpc = getPostIndexedLoadStoreOpcode(Opcode, ARM_AM::add);
1510     if ((isAM5 && Offset != Bytes) ||
1511         (!isAM5 && !isLegalAddressImm(NewOpc, Offset, TII))) {
1512       NewOpc = getPostIndexedLoadStoreOpcode(Opcode, ARM_AM::sub);
1513       if (isAM5 || !isLegalAddressImm(NewOpc, Offset, TII))
1514         return false;
1515     }
1516   }
1517   LLVM_DEBUG(dbgs() << "  Erasing old increment: " << *MergeInstr);
1518   MBB.erase(MergeInstr);
1519 
1520   ARM_AM::AddrOpc AddSub = Offset < 0 ? ARM_AM::sub : ARM_AM::add;
1521 
1522   bool isLd = isLoadSingle(Opcode);
1523   if (isAM5) {
1524     // VLDM[SD]_UPD, VSTM[SD]_UPD
1525     // (There are no base-updating versions of VLDR/VSTR instructions, but the
1526     // updating load/store-multiple instructions can be used with only one
1527     // register.)
1528     MachineOperand &MO = MI->getOperand(0);
1529     auto MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
1530                    .addReg(Base, getDefRegState(true)) // WB base register
1531                    .addReg(Base, getKillRegState(isLd ? BaseKill : false))
1532                    .addImm(Pred)
1533                    .addReg(PredReg)
1534                    .addReg(MO.getReg(), (isLd ? getDefRegState(true)
1535                                               : getKillRegState(MO.isKill())))
1536                    .cloneMemRefs(*MI);
1537     (void)MIB;
1538     LLVM_DEBUG(dbgs() << "  Added new instruction: " << *MIB);
1539   } else if (isLd) {
1540     if (isAM2) {
1541       // LDR_PRE, LDR_POST
1542       if (NewOpc == ARM::LDR_PRE_IMM || NewOpc == ARM::LDRB_PRE_IMM) {
1543         auto MIB =
1544             BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
1545                 .addReg(Base, RegState::Define)
1546                 .addReg(Base)
1547                 .addImm(Offset)
1548                 .addImm(Pred)
1549                 .addReg(PredReg)
1550                 .cloneMemRefs(*MI);
1551         (void)MIB;
1552         LLVM_DEBUG(dbgs() << "  Added new instruction: " << *MIB);
1553       } else {
1554         int Imm = ARM_AM::getAM2Opc(AddSub, abs(Offset), ARM_AM::no_shift);
1555         auto MIB =
1556             BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
1557                 .addReg(Base, RegState::Define)
1558                 .addReg(Base)
1559                 .addReg(0)
1560                 .addImm(Imm)
1561                 .add(predOps(Pred, PredReg))
1562                 .cloneMemRefs(*MI);
1563         (void)MIB;
1564         LLVM_DEBUG(dbgs() << "  Added new instruction: " << *MIB);
1565       }
1566     } else {
1567       // t2LDR_PRE, t2LDR_POST
1568       auto MIB =
1569           BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
1570               .addReg(Base, RegState::Define)
1571               .addReg(Base)
1572               .addImm(Offset)
1573               .add(predOps(Pred, PredReg))
1574               .cloneMemRefs(*MI);
1575       (void)MIB;
1576       LLVM_DEBUG(dbgs() << "  Added new instruction: " << *MIB);
1577     }
1578   } else {
1579     MachineOperand &MO = MI->getOperand(0);
1580     // FIXME: post-indexed stores use am2offset_imm, which still encodes
1581     // the vestigal zero-reg offset register. When that's fixed, this clause
1582     // can be removed entirely.
1583     if (isAM2 && NewOpc == ARM::STR_POST_IMM) {
1584       int Imm = ARM_AM::getAM2Opc(AddSub, abs(Offset), ARM_AM::no_shift);
1585       // STR_PRE, STR_POST
1586       auto MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base)
1587                      .addReg(MO.getReg(), getKillRegState(MO.isKill()))
1588                      .addReg(Base)
1589                      .addReg(0)
1590                      .addImm(Imm)
1591                      .add(predOps(Pred, PredReg))
1592                      .cloneMemRefs(*MI);
1593       (void)MIB;
1594       LLVM_DEBUG(dbgs() << "  Added new instruction: " << *MIB);
1595     } else {
1596       // t2STR_PRE, t2STR_POST
1597       auto MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base)
1598                      .addReg(MO.getReg(), getKillRegState(MO.isKill()))
1599                      .addReg(Base)
1600                      .addImm(Offset)
1601                      .add(predOps(Pred, PredReg))
1602                      .cloneMemRefs(*MI);
1603       (void)MIB;
1604       LLVM_DEBUG(dbgs() << "  Added new instruction: " << *MIB);
1605     }
1606   }
1607   MBB.erase(MBBI);
1608 
1609   return true;
1610 }
1611 
1612 bool ARMLoadStoreOpt::MergeBaseUpdateLSDouble(MachineInstr &MI) const {
1613   unsigned Opcode = MI.getOpcode();
1614   assert((Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8) &&
1615          "Must have t2STRDi8 or t2LDRDi8");
1616   if (MI.getOperand(3).getImm() != 0)
1617     return false;
1618   LLVM_DEBUG(dbgs() << "Attempting to merge update of: " << MI);
1619 
1620   // Behaviour for writeback is undefined if base register is the same as one
1621   // of the others.
1622   const MachineOperand &BaseOp = MI.getOperand(2);
1623   Register Base = BaseOp.getReg();
1624   const MachineOperand &Reg0Op = MI.getOperand(0);
1625   const MachineOperand &Reg1Op = MI.getOperand(1);
1626   if (Reg0Op.getReg() == Base || Reg1Op.getReg() == Base)
1627     return false;
1628 
1629   Register PredReg;
1630   ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
1631   MachineBasicBlock::iterator MBBI(MI);
1632   MachineBasicBlock &MBB = *MI.getParent();
1633   int Offset;
1634   MachineBasicBlock::iterator MergeInstr = findIncDecBefore(MBBI, Base, Pred,
1635                                                             PredReg, Offset);
1636   unsigned NewOpc;
1637   if (Offset == 8 || Offset == -8) {
1638     NewOpc = Opcode == ARM::t2LDRDi8 ? ARM::t2LDRD_PRE : ARM::t2STRD_PRE;
1639   } else {
1640     MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset, TRI);
1641     if (MergeInstr == MBB.end())
1642       return false;
1643     NewOpc = Opcode == ARM::t2LDRDi8 ? ARM::t2LDRD_POST : ARM::t2STRD_POST;
1644     if (!isLegalAddressImm(NewOpc, Offset, TII))
1645       return false;
1646   }
1647   LLVM_DEBUG(dbgs() << "  Erasing old increment: " << *MergeInstr);
1648   MBB.erase(MergeInstr);
1649 
1650   DebugLoc DL = MI.getDebugLoc();
1651   MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
1652   if (NewOpc == ARM::t2LDRD_PRE || NewOpc == ARM::t2LDRD_POST) {
1653     MIB.add(Reg0Op).add(Reg1Op).addReg(BaseOp.getReg(), RegState::Define);
1654   } else {
1655     assert(NewOpc == ARM::t2STRD_PRE || NewOpc == ARM::t2STRD_POST);
1656     MIB.addReg(BaseOp.getReg(), RegState::Define).add(Reg0Op).add(Reg1Op);
1657   }
1658   MIB.addReg(BaseOp.getReg(), RegState::Kill)
1659      .addImm(Offset).addImm(Pred).addReg(PredReg);
1660   assert(TII->get(Opcode).getNumOperands() == 6 &&
1661          TII->get(NewOpc).getNumOperands() == 7 &&
1662          "Unexpected number of operands in Opcode specification.");
1663 
1664   // Transfer implicit operands.
1665   for (const MachineOperand &MO : MI.implicit_operands())
1666     MIB.add(MO);
1667   MIB.cloneMemRefs(MI);
1668 
1669   LLVM_DEBUG(dbgs() << "  Added new load/store: " << *MIB);
1670   MBB.erase(MBBI);
1671   return true;
1672 }
1673 
1674 /// Returns true if instruction is a memory operation that this pass is capable
1675 /// of operating on.
1676 static bool isMemoryOp(const MachineInstr &MI) {
1677   unsigned Opcode = MI.getOpcode();
1678   switch (Opcode) {
1679   case ARM::VLDRS:
1680   case ARM::VSTRS:
1681   case ARM::VLDRD:
1682   case ARM::VSTRD:
1683   case ARM::LDRi12:
1684   case ARM::STRi12:
1685   case ARM::tLDRi:
1686   case ARM::tSTRi:
1687   case ARM::tLDRspi:
1688   case ARM::tSTRspi:
1689   case ARM::t2LDRi8:
1690   case ARM::t2LDRi12:
1691   case ARM::t2STRi8:
1692   case ARM::t2STRi12:
1693     break;
1694   default:
1695     return false;
1696   }
1697   if (!MI.getOperand(1).isReg())
1698     return false;
1699 
1700   // When no memory operands are present, conservatively assume unaligned,
1701   // volatile, unfoldable.
1702   if (!MI.hasOneMemOperand())
1703     return false;
1704 
1705   const MachineMemOperand &MMO = **MI.memoperands_begin();
1706 
1707   // Don't touch volatile memory accesses - we may be changing their order.
1708   // TODO: We could allow unordered and monotonic atomics here, but we need to
1709   // make sure the resulting ldm/stm is correctly marked as atomic.
1710   if (MMO.isVolatile() || MMO.isAtomic())
1711     return false;
1712 
1713   // Unaligned ldr/str is emulated by some kernels, but unaligned ldm/stm is
1714   // not.
1715   if (MMO.getAlign() < Align(4))
1716     return false;
1717 
1718   // str <undef> could probably be eliminated entirely, but for now we just want
1719   // to avoid making a mess of it.
1720   // FIXME: Use str <undef> as a wildcard to enable better stm folding.
1721   if (MI.getOperand(0).isReg() && MI.getOperand(0).isUndef())
1722     return false;
1723 
1724   // Likewise don't mess with references to undefined addresses.
1725   if (MI.getOperand(1).isUndef())
1726     return false;
1727 
1728   return true;
1729 }
1730 
1731 static void InsertLDR_STR(MachineBasicBlock &MBB,
1732                           MachineBasicBlock::iterator &MBBI, int Offset,
1733                           bool isDef, unsigned NewOpc, unsigned Reg,
1734                           bool RegDeadKill, bool RegUndef, unsigned BaseReg,
1735                           bool BaseKill, bool BaseUndef, ARMCC::CondCodes Pred,
1736                           unsigned PredReg, const TargetInstrInfo *TII,
1737                           MachineInstr *MI) {
1738   if (isDef) {
1739     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(),
1740                                       TII->get(NewOpc))
1741       .addReg(Reg, getDefRegState(true) | getDeadRegState(RegDeadKill))
1742       .addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef));
1743     MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
1744     // FIXME: This is overly conservative; the new instruction accesses 4
1745     // bytes, not 8.
1746     MIB.cloneMemRefs(*MI);
1747   } else {
1748     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(),
1749                                       TII->get(NewOpc))
1750       .addReg(Reg, getKillRegState(RegDeadKill) | getUndefRegState(RegUndef))
1751       .addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef));
1752     MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
1753     // FIXME: This is overly conservative; the new instruction accesses 4
1754     // bytes, not 8.
1755     MIB.cloneMemRefs(*MI);
1756   }
1757 }
1758 
1759 bool ARMLoadStoreOpt::FixInvalidRegPairOp(MachineBasicBlock &MBB,
1760                                           MachineBasicBlock::iterator &MBBI) {
1761   MachineInstr *MI = &*MBBI;
1762   unsigned Opcode = MI->getOpcode();
1763   // FIXME: Code/comments below check Opcode == t2STRDi8, but this check returns
1764   // if we see this opcode.
1765   if (Opcode != ARM::LDRD && Opcode != ARM::STRD && Opcode != ARM::t2LDRDi8)
1766     return false;
1767 
1768   const MachineOperand &BaseOp = MI->getOperand(2);
1769   Register BaseReg = BaseOp.getReg();
1770   Register EvenReg = MI->getOperand(0).getReg();
1771   Register OddReg = MI->getOperand(1).getReg();
1772   unsigned EvenRegNum = TRI->getDwarfRegNum(EvenReg, false);
1773   unsigned OddRegNum  = TRI->getDwarfRegNum(OddReg, false);
1774 
1775   // ARM errata 602117: LDRD with base in list may result in incorrect base
1776   // register when interrupted or faulted.
1777   bool Errata602117 = EvenReg == BaseReg &&
1778     (Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8) && STI->isCortexM3();
1779   // ARM LDRD/STRD needs consecutive registers.
1780   bool NonConsecutiveRegs = (Opcode == ARM::LDRD || Opcode == ARM::STRD) &&
1781     (EvenRegNum % 2 != 0 || EvenRegNum + 1 != OddRegNum);
1782 
1783   if (!Errata602117 && !NonConsecutiveRegs)
1784     return false;
1785 
1786   bool isT2 = Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8;
1787   bool isLd = Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8;
1788   bool EvenDeadKill = isLd ?
1789     MI->getOperand(0).isDead() : MI->getOperand(0).isKill();
1790   bool EvenUndef = MI->getOperand(0).isUndef();
1791   bool OddDeadKill  = isLd ?
1792     MI->getOperand(1).isDead() : MI->getOperand(1).isKill();
1793   bool OddUndef = MI->getOperand(1).isUndef();
1794   bool BaseKill = BaseOp.isKill();
1795   bool BaseUndef = BaseOp.isUndef();
1796   assert((isT2 || MI->getOperand(3).getReg() == ARM::NoRegister) &&
1797          "register offset not handled below");
1798   int OffImm = getMemoryOpOffset(*MI);
1799   Register PredReg;
1800   ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
1801 
1802   if (OddRegNum > EvenRegNum && OffImm == 0) {
1803     // Ascending register numbers and no offset. It's safe to change it to a
1804     // ldm or stm.
1805     unsigned NewOpc = (isLd)
1806       ? (isT2 ? ARM::t2LDMIA : ARM::LDMIA)
1807       : (isT2 ? ARM::t2STMIA : ARM::STMIA);
1808     if (isLd) {
1809       BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc))
1810         .addReg(BaseReg, getKillRegState(BaseKill))
1811         .addImm(Pred).addReg(PredReg)
1812         .addReg(EvenReg, getDefRegState(isLd) | getDeadRegState(EvenDeadKill))
1813         .addReg(OddReg,  getDefRegState(isLd) | getDeadRegState(OddDeadKill))
1814         .cloneMemRefs(*MI);
1815       ++NumLDRD2LDM;
1816     } else {
1817       BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc))
1818         .addReg(BaseReg, getKillRegState(BaseKill))
1819         .addImm(Pred).addReg(PredReg)
1820         .addReg(EvenReg,
1821                 getKillRegState(EvenDeadKill) | getUndefRegState(EvenUndef))
1822         .addReg(OddReg,
1823                 getKillRegState(OddDeadKill)  | getUndefRegState(OddUndef))
1824         .cloneMemRefs(*MI);
1825       ++NumSTRD2STM;
1826     }
1827   } else {
1828     // Split into two instructions.
1829     unsigned NewOpc = (isLd)
1830       ? (isT2 ? (OffImm < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12)
1831       : (isT2 ? (OffImm < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12);
1832     // Be extra careful for thumb2. t2LDRi8 can't reference a zero offset,
1833     // so adjust and use t2LDRi12 here for that.
1834     unsigned NewOpc2 = (isLd)
1835       ? (isT2 ? (OffImm+4 < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12)
1836       : (isT2 ? (OffImm+4 < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12);
1837     // If this is a load, make sure the first load does not clobber the base
1838     // register before the second load reads it.
1839     if (isLd && TRI->regsOverlap(EvenReg, BaseReg)) {
1840       assert(!TRI->regsOverlap(OddReg, BaseReg));
1841       InsertLDR_STR(MBB, MBBI, OffImm + 4, isLd, NewOpc2, OddReg, OddDeadKill,
1842                     false, BaseReg, false, BaseUndef, Pred, PredReg, TII, MI);
1843       InsertLDR_STR(MBB, MBBI, OffImm, isLd, NewOpc, EvenReg, EvenDeadKill,
1844                     false, BaseReg, BaseKill, BaseUndef, Pred, PredReg, TII,
1845                     MI);
1846     } else {
1847       if (OddReg == EvenReg && EvenDeadKill) {
1848         // If the two source operands are the same, the kill marker is
1849         // probably on the first one. e.g.
1850         // t2STRDi8 killed %r5, %r5, killed %r9, 0, 14, %reg0
1851         EvenDeadKill = false;
1852         OddDeadKill = true;
1853       }
1854       // Never kill the base register in the first instruction.
1855       if (EvenReg == BaseReg)
1856         EvenDeadKill = false;
1857       InsertLDR_STR(MBB, MBBI, OffImm, isLd, NewOpc, EvenReg, EvenDeadKill,
1858                     EvenUndef, BaseReg, false, BaseUndef, Pred, PredReg, TII,
1859                     MI);
1860       InsertLDR_STR(MBB, MBBI, OffImm + 4, isLd, NewOpc2, OddReg, OddDeadKill,
1861                     OddUndef, BaseReg, BaseKill, BaseUndef, Pred, PredReg, TII,
1862                     MI);
1863     }
1864     if (isLd)
1865       ++NumLDRD2LDR;
1866     else
1867       ++NumSTRD2STR;
1868   }
1869 
1870   MBBI = MBB.erase(MBBI);
1871   return true;
1872 }
1873 
1874 /// An optimization pass to turn multiple LDR / STR ops of the same base and
1875 /// incrementing offset into LDM / STM ops.
1876 bool ARMLoadStoreOpt::LoadStoreMultipleOpti(MachineBasicBlock &MBB) {
1877   MemOpQueue MemOps;
1878   unsigned CurrBase = 0;
1879   unsigned CurrOpc = ~0u;
1880   ARMCC::CondCodes CurrPred = ARMCC::AL;
1881   unsigned Position = 0;
1882   assert(Candidates.size() == 0);
1883   assert(MergeBaseCandidates.size() == 0);
1884   LiveRegsValid = false;
1885 
1886   for (MachineBasicBlock::iterator I = MBB.end(), MBBI; I != MBB.begin();
1887        I = MBBI) {
1888     // The instruction in front of the iterator is the one we look at.
1889     MBBI = std::prev(I);
1890     if (FixInvalidRegPairOp(MBB, MBBI))
1891       continue;
1892     ++Position;
1893 
1894     if (isMemoryOp(*MBBI)) {
1895       unsigned Opcode = MBBI->getOpcode();
1896       const MachineOperand &MO = MBBI->getOperand(0);
1897       Register Reg = MO.getReg();
1898       Register Base = getLoadStoreBaseOp(*MBBI).getReg();
1899       Register PredReg;
1900       ARMCC::CondCodes Pred = getInstrPredicate(*MBBI, PredReg);
1901       int Offset = getMemoryOpOffset(*MBBI);
1902       if (CurrBase == 0) {
1903         // Start of a new chain.
1904         CurrBase = Base;
1905         CurrOpc  = Opcode;
1906         CurrPred = Pred;
1907         MemOps.push_back(MemOpQueueEntry(*MBBI, Offset, Position));
1908         continue;
1909       }
1910       // Note: No need to match PredReg in the next if.
1911       if (CurrOpc == Opcode && CurrBase == Base && CurrPred == Pred) {
1912         // Watch out for:
1913         //   r4 := ldr [r0, #8]
1914         //   r4 := ldr [r0, #4]
1915         // or
1916         //   r0 := ldr [r0]
1917         // If a load overrides the base register or a register loaded by
1918         // another load in our chain, we cannot take this instruction.
1919         bool Overlap = false;
1920         if (isLoadSingle(Opcode)) {
1921           Overlap = (Base == Reg);
1922           if (!Overlap) {
1923             for (const MemOpQueueEntry &E : MemOps) {
1924               if (TRI->regsOverlap(Reg, E.MI->getOperand(0).getReg())) {
1925                 Overlap = true;
1926                 break;
1927               }
1928             }
1929           }
1930         }
1931 
1932         if (!Overlap) {
1933           // Check offset and sort memory operation into the current chain.
1934           if (Offset > MemOps.back().Offset) {
1935             MemOps.push_back(MemOpQueueEntry(*MBBI, Offset, Position));
1936             continue;
1937           } else {
1938             MemOpQueue::iterator MI, ME;
1939             for (MI = MemOps.begin(), ME = MemOps.end(); MI != ME; ++MI) {
1940               if (Offset < MI->Offset) {
1941                 // Found a place to insert.
1942                 break;
1943               }
1944               if (Offset == MI->Offset) {
1945                 // Collision, abort.
1946                 MI = ME;
1947                 break;
1948               }
1949             }
1950             if (MI != MemOps.end()) {
1951               MemOps.insert(MI, MemOpQueueEntry(*MBBI, Offset, Position));
1952               continue;
1953             }
1954           }
1955         }
1956       }
1957 
1958       // Don't advance the iterator; The op will start a new chain next.
1959       MBBI = I;
1960       --Position;
1961       // Fallthrough to look into existing chain.
1962     } else if (MBBI->isDebugInstr()) {
1963       continue;
1964     } else if (MBBI->getOpcode() == ARM::t2LDRDi8 ||
1965                MBBI->getOpcode() == ARM::t2STRDi8) {
1966       // ARMPreAllocLoadStoreOpt has already formed some LDRD/STRD instructions
1967       // remember them because we may still be able to merge add/sub into them.
1968       MergeBaseCandidates.push_back(&*MBBI);
1969     }
1970 
1971     // If we are here then the chain is broken; Extract candidates for a merge.
1972     if (MemOps.size() > 0) {
1973       FormCandidates(MemOps);
1974       // Reset for the next chain.
1975       CurrBase = 0;
1976       CurrOpc = ~0u;
1977       CurrPred = ARMCC::AL;
1978       MemOps.clear();
1979     }
1980   }
1981   if (MemOps.size() > 0)
1982     FormCandidates(MemOps);
1983 
1984   // Sort candidates so they get processed from end to begin of the basic
1985   // block later; This is necessary for liveness calculation.
1986   auto LessThan = [](const MergeCandidate* M0, const MergeCandidate *M1) {
1987     return M0->InsertPos < M1->InsertPos;
1988   };
1989   llvm::sort(Candidates, LessThan);
1990 
1991   // Go through list of candidates and merge.
1992   bool Changed = false;
1993   for (const MergeCandidate *Candidate : Candidates) {
1994     if (Candidate->CanMergeToLSMulti || Candidate->CanMergeToLSDouble) {
1995       MachineInstr *Merged = MergeOpsUpdate(*Candidate);
1996       // Merge preceding/trailing base inc/dec into the merged op.
1997       if (Merged) {
1998         Changed = true;
1999         unsigned Opcode = Merged->getOpcode();
2000         if (Opcode == ARM::t2STRDi8 || Opcode == ARM::t2LDRDi8)
2001           MergeBaseUpdateLSDouble(*Merged);
2002         else
2003           MergeBaseUpdateLSMultiple(Merged);
2004       } else {
2005         for (MachineInstr *MI : Candidate->Instrs) {
2006           if (MergeBaseUpdateLoadStore(MI))
2007             Changed = true;
2008         }
2009       }
2010     } else {
2011       assert(Candidate->Instrs.size() == 1);
2012       if (MergeBaseUpdateLoadStore(Candidate->Instrs.front()))
2013         Changed = true;
2014     }
2015   }
2016   Candidates.clear();
2017   // Try to fold add/sub into the LDRD/STRD formed by ARMPreAllocLoadStoreOpt.
2018   for (MachineInstr *MI : MergeBaseCandidates)
2019     MergeBaseUpdateLSDouble(*MI);
2020   MergeBaseCandidates.clear();
2021 
2022   return Changed;
2023 }
2024 
2025 /// If this is a exit BB, try merging the return ops ("bx lr" and "mov pc, lr")
2026 /// into the preceding stack restore so it directly restore the value of LR
2027 /// into pc.
2028 ///   ldmfd sp!, {..., lr}
2029 ///   bx lr
2030 /// or
2031 ///   ldmfd sp!, {..., lr}
2032 ///   mov pc, lr
2033 /// =>
2034 ///   ldmfd sp!, {..., pc}
2035 bool ARMLoadStoreOpt::MergeReturnIntoLDM(MachineBasicBlock &MBB) {
2036   // Thumb1 LDM doesn't allow high registers.
2037   if (isThumb1) return false;
2038   if (MBB.empty()) return false;
2039 
2040   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
2041   if (MBBI != MBB.begin() && MBBI != MBB.end() &&
2042       (MBBI->getOpcode() == ARM::BX_RET ||
2043        MBBI->getOpcode() == ARM::tBX_RET ||
2044        MBBI->getOpcode() == ARM::MOVPCLR)) {
2045     MachineBasicBlock::iterator PrevI = std::prev(MBBI);
2046     // Ignore any debug instructions.
2047     while (PrevI->isDebugInstr() && PrevI != MBB.begin())
2048       --PrevI;
2049     MachineInstr &PrevMI = *PrevI;
2050     unsigned Opcode = PrevMI.getOpcode();
2051     if (Opcode == ARM::LDMIA_UPD || Opcode == ARM::LDMDA_UPD ||
2052         Opcode == ARM::LDMDB_UPD || Opcode == ARM::LDMIB_UPD ||
2053         Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
2054       MachineOperand &MO = PrevMI.getOperand(PrevMI.getNumOperands() - 1);
2055       if (MO.getReg() != ARM::LR)
2056         return false;
2057       unsigned NewOpc = (isThumb2 ? ARM::t2LDMIA_RET : ARM::LDMIA_RET);
2058       assert(((isThumb2 && Opcode == ARM::t2LDMIA_UPD) ||
2059               Opcode == ARM::LDMIA_UPD) && "Unsupported multiple load-return!");
2060       PrevMI.setDesc(TII->get(NewOpc));
2061       MO.setReg(ARM::PC);
2062       PrevMI.copyImplicitOps(*MBB.getParent(), *MBBI);
2063       MBB.erase(MBBI);
2064       // We now restore LR into PC so it is not live-out of the return block
2065       // anymore: Clear the CSI Restored bit.
2066       MachineFrameInfo &MFI = MBB.getParent()->getFrameInfo();
2067       // CSI should be fixed after PrologEpilog Insertion
2068       assert(MFI.isCalleeSavedInfoValid() && "CSI should be valid");
2069       for (CalleeSavedInfo &Info : MFI.getCalleeSavedInfo()) {
2070         if (Info.getReg() == ARM::LR) {
2071           Info.setRestored(false);
2072           break;
2073         }
2074       }
2075       return true;
2076     }
2077   }
2078   return false;
2079 }
2080 
2081 bool ARMLoadStoreOpt::CombineMovBx(MachineBasicBlock &MBB) {
2082   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
2083   if (MBBI == MBB.begin() || MBBI == MBB.end() ||
2084       MBBI->getOpcode() != ARM::tBX_RET)
2085     return false;
2086 
2087   MachineBasicBlock::iterator Prev = MBBI;
2088   --Prev;
2089   if (Prev->getOpcode() != ARM::tMOVr || !Prev->definesRegister(ARM::LR))
2090     return false;
2091 
2092   for (auto Use : Prev->uses())
2093     if (Use.isKill()) {
2094       assert(STI->hasV4TOps());
2095       BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(ARM::tBX))
2096           .addReg(Use.getReg(), RegState::Kill)
2097           .add(predOps(ARMCC::AL))
2098           .copyImplicitOps(*MBBI);
2099       MBB.erase(MBBI);
2100       MBB.erase(Prev);
2101       return true;
2102     }
2103 
2104   llvm_unreachable("tMOVr doesn't kill a reg before tBX_RET?");
2105 }
2106 
2107 bool ARMLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
2108   if (skipFunction(Fn.getFunction()))
2109     return false;
2110 
2111   MF = &Fn;
2112   STI = &static_cast<const ARMSubtarget &>(Fn.getSubtarget());
2113   TL = STI->getTargetLowering();
2114   AFI = Fn.getInfo<ARMFunctionInfo>();
2115   TII = STI->getInstrInfo();
2116   TRI = STI->getRegisterInfo();
2117 
2118   RegClassInfoValid = false;
2119   isThumb2 = AFI->isThumb2Function();
2120   isThumb1 = AFI->isThumbFunction() && !isThumb2;
2121 
2122   bool Modified = false;
2123   for (MachineBasicBlock &MBB : Fn) {
2124     Modified |= LoadStoreMultipleOpti(MBB);
2125     if (STI->hasV5TOps() && !AFI->shouldSignReturnAddress())
2126       Modified |= MergeReturnIntoLDM(MBB);
2127     if (isThumb1)
2128       Modified |= CombineMovBx(MBB);
2129   }
2130 
2131   Allocator.DestroyAll();
2132   return Modified;
2133 }
2134 
2135 #define ARM_PREALLOC_LOAD_STORE_OPT_NAME                                       \
2136   "ARM pre- register allocation load / store optimization pass"
2137 
2138 namespace {
2139 
2140   /// Pre- register allocation pass that move load / stores from consecutive
2141   /// locations close to make it more likely they will be combined later.
2142   struct ARMPreAllocLoadStoreOpt : public MachineFunctionPass{
2143     static char ID;
2144 
2145     AliasAnalysis *AA;
2146     const DataLayout *TD;
2147     const TargetInstrInfo *TII;
2148     const TargetRegisterInfo *TRI;
2149     const ARMSubtarget *STI;
2150     MachineRegisterInfo *MRI;
2151     MachineDominatorTree *DT;
2152     MachineFunction *MF;
2153 
2154     ARMPreAllocLoadStoreOpt() : MachineFunctionPass(ID) {}
2155 
2156     bool runOnMachineFunction(MachineFunction &Fn) override;
2157 
2158     StringRef getPassName() const override {
2159       return ARM_PREALLOC_LOAD_STORE_OPT_NAME;
2160     }
2161 
2162     void getAnalysisUsage(AnalysisUsage &AU) const override {
2163       AU.addRequired<AAResultsWrapperPass>();
2164       AU.addRequired<MachineDominatorTree>();
2165       AU.addPreserved<MachineDominatorTree>();
2166       MachineFunctionPass::getAnalysisUsage(AU);
2167     }
2168 
2169   private:
2170     bool CanFormLdStDWord(MachineInstr *Op0, MachineInstr *Op1, DebugLoc &dl,
2171                           unsigned &NewOpc, Register &EvenReg, Register &OddReg,
2172                           Register &BaseReg, int &Offset, Register &PredReg,
2173                           ARMCC::CondCodes &Pred, bool &isT2);
2174     bool RescheduleOps(MachineBasicBlock *MBB,
2175                        SmallVectorImpl<MachineInstr *> &Ops,
2176                        unsigned Base, bool isLd,
2177                        DenseMap<MachineInstr*, unsigned> &MI2LocMap);
2178     bool RescheduleLoadStoreInstrs(MachineBasicBlock *MBB);
2179     bool DistributeIncrements();
2180     bool DistributeIncrements(Register Base);
2181   };
2182 
2183 } // end anonymous namespace
2184 
2185 char ARMPreAllocLoadStoreOpt::ID = 0;
2186 
2187 INITIALIZE_PASS_BEGIN(ARMPreAllocLoadStoreOpt, "arm-prera-ldst-opt",
2188                       ARM_PREALLOC_LOAD_STORE_OPT_NAME, false, false)
2189 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
2190 INITIALIZE_PASS_END(ARMPreAllocLoadStoreOpt, "arm-prera-ldst-opt",
2191                     ARM_PREALLOC_LOAD_STORE_OPT_NAME, false, false)
2192 
2193 // Limit the number of instructions to be rescheduled.
2194 // FIXME: tune this limit, and/or come up with some better heuristics.
2195 static cl::opt<unsigned> InstReorderLimit("arm-prera-ldst-opt-reorder-limit",
2196                                           cl::init(8), cl::Hidden);
2197 
2198 bool ARMPreAllocLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
2199   if (AssumeMisalignedLoadStores || skipFunction(Fn.getFunction()))
2200     return false;
2201 
2202   TD = &Fn.getDataLayout();
2203   STI = &static_cast<const ARMSubtarget &>(Fn.getSubtarget());
2204   TII = STI->getInstrInfo();
2205   TRI = STI->getRegisterInfo();
2206   MRI = &Fn.getRegInfo();
2207   DT = &getAnalysis<MachineDominatorTree>();
2208   MF  = &Fn;
2209   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2210 
2211   bool Modified = DistributeIncrements();
2212   for (MachineBasicBlock &MFI : Fn)
2213     Modified |= RescheduleLoadStoreInstrs(&MFI);
2214 
2215   return Modified;
2216 }
2217 
2218 static bool IsSafeAndProfitableToMove(bool isLd, unsigned Base,
2219                                       MachineBasicBlock::iterator I,
2220                                       MachineBasicBlock::iterator E,
2221                                       SmallPtrSetImpl<MachineInstr*> &MemOps,
2222                                       SmallSet<unsigned, 4> &MemRegs,
2223                                       const TargetRegisterInfo *TRI,
2224                                       AliasAnalysis *AA) {
2225   // Are there stores / loads / calls between them?
2226   SmallSet<unsigned, 4> AddedRegPressure;
2227   while (++I != E) {
2228     if (I->isDebugInstr() || MemOps.count(&*I))
2229       continue;
2230     if (I->isCall() || I->isTerminator() || I->hasUnmodeledSideEffects())
2231       return false;
2232     if (I->mayStore() || (!isLd && I->mayLoad()))
2233       for (MachineInstr *MemOp : MemOps)
2234         if (I->mayAlias(AA, *MemOp, /*UseTBAA*/ false))
2235           return false;
2236     for (unsigned j = 0, NumOps = I->getNumOperands(); j != NumOps; ++j) {
2237       MachineOperand &MO = I->getOperand(j);
2238       if (!MO.isReg())
2239         continue;
2240       Register Reg = MO.getReg();
2241       if (MO.isDef() && TRI->regsOverlap(Reg, Base))
2242         return false;
2243       if (Reg != Base && !MemRegs.count(Reg))
2244         AddedRegPressure.insert(Reg);
2245     }
2246   }
2247 
2248   // Estimate register pressure increase due to the transformation.
2249   if (MemRegs.size() <= 4)
2250     // Ok if we are moving small number of instructions.
2251     return true;
2252   return AddedRegPressure.size() <= MemRegs.size() * 2;
2253 }
2254 
2255 bool ARMPreAllocLoadStoreOpt::CanFormLdStDWord(
2256     MachineInstr *Op0, MachineInstr *Op1, DebugLoc &dl, unsigned &NewOpc,
2257     Register &FirstReg, Register &SecondReg, Register &BaseReg, int &Offset,
2258     Register &PredReg, ARMCC::CondCodes &Pred, bool &isT2) {
2259   // Make sure we're allowed to generate LDRD/STRD.
2260   if (!STI->hasV5TEOps())
2261     return false;
2262 
2263   // FIXME: VLDRS / VSTRS -> VLDRD / VSTRD
2264   unsigned Scale = 1;
2265   unsigned Opcode = Op0->getOpcode();
2266   if (Opcode == ARM::LDRi12) {
2267     NewOpc = ARM::LDRD;
2268   } else if (Opcode == ARM::STRi12) {
2269     NewOpc = ARM::STRD;
2270   } else if (Opcode == ARM::t2LDRi8 || Opcode == ARM::t2LDRi12) {
2271     NewOpc = ARM::t2LDRDi8;
2272     Scale = 4;
2273     isT2 = true;
2274   } else if (Opcode == ARM::t2STRi8 || Opcode == ARM::t2STRi12) {
2275     NewOpc = ARM::t2STRDi8;
2276     Scale = 4;
2277     isT2 = true;
2278   } else {
2279     return false;
2280   }
2281 
2282   // Make sure the base address satisfies i64 ld / st alignment requirement.
2283   // At the moment, we ignore the memoryoperand's value.
2284   // If we want to use AliasAnalysis, we should check it accordingly.
2285   if (!Op0->hasOneMemOperand() ||
2286       (*Op0->memoperands_begin())->isVolatile() ||
2287       (*Op0->memoperands_begin())->isAtomic())
2288     return false;
2289 
2290   Align Alignment = (*Op0->memoperands_begin())->getAlign();
2291   const Function &Func = MF->getFunction();
2292   Align ReqAlign =
2293       STI->hasV6Ops() ? TD->getABITypeAlign(Type::getInt64Ty(Func.getContext()))
2294                       : Align(8); // Pre-v6 need 8-byte align
2295   if (Alignment < ReqAlign)
2296     return false;
2297 
2298   // Then make sure the immediate offset fits.
2299   int OffImm = getMemoryOpOffset(*Op0);
2300   if (isT2) {
2301     int Limit = (1 << 8) * Scale;
2302     if (OffImm >= Limit || (OffImm <= -Limit) || (OffImm & (Scale-1)))
2303       return false;
2304     Offset = OffImm;
2305   } else {
2306     ARM_AM::AddrOpc AddSub = ARM_AM::add;
2307     if (OffImm < 0) {
2308       AddSub = ARM_AM::sub;
2309       OffImm = - OffImm;
2310     }
2311     int Limit = (1 << 8) * Scale;
2312     if (OffImm >= Limit || (OffImm & (Scale-1)))
2313       return false;
2314     Offset = ARM_AM::getAM3Opc(AddSub, OffImm);
2315   }
2316   FirstReg = Op0->getOperand(0).getReg();
2317   SecondReg = Op1->getOperand(0).getReg();
2318   if (FirstReg == SecondReg)
2319     return false;
2320   BaseReg = Op0->getOperand(1).getReg();
2321   Pred = getInstrPredicate(*Op0, PredReg);
2322   dl = Op0->getDebugLoc();
2323   return true;
2324 }
2325 
2326 bool ARMPreAllocLoadStoreOpt::RescheduleOps(MachineBasicBlock *MBB,
2327                                  SmallVectorImpl<MachineInstr *> &Ops,
2328                                  unsigned Base, bool isLd,
2329                                  DenseMap<MachineInstr*, unsigned> &MI2LocMap) {
2330   bool RetVal = false;
2331 
2332   // Sort by offset (in reverse order).
2333   llvm::sort(Ops, [](const MachineInstr *LHS, const MachineInstr *RHS) {
2334     int LOffset = getMemoryOpOffset(*LHS);
2335     int ROffset = getMemoryOpOffset(*RHS);
2336     assert(LHS == RHS || LOffset != ROffset);
2337     return LOffset > ROffset;
2338   });
2339 
2340   // The loads / stores of the same base are in order. Scan them from first to
2341   // last and check for the following:
2342   // 1. Any def of base.
2343   // 2. Any gaps.
2344   while (Ops.size() > 1) {
2345     unsigned FirstLoc = ~0U;
2346     unsigned LastLoc = 0;
2347     MachineInstr *FirstOp = nullptr;
2348     MachineInstr *LastOp = nullptr;
2349     int LastOffset = 0;
2350     unsigned LastOpcode = 0;
2351     unsigned LastBytes = 0;
2352     unsigned NumMove = 0;
2353     for (MachineInstr *Op : llvm::reverse(Ops)) {
2354       // Make sure each operation has the same kind.
2355       unsigned LSMOpcode
2356         = getLoadStoreMultipleOpcode(Op->getOpcode(), ARM_AM::ia);
2357       if (LastOpcode && LSMOpcode != LastOpcode)
2358         break;
2359 
2360       // Check that we have a continuous set of offsets.
2361       int Offset = getMemoryOpOffset(*Op);
2362       unsigned Bytes = getLSMultipleTransferSize(Op);
2363       if (LastBytes) {
2364         if (Bytes != LastBytes || Offset != (LastOffset + (int)Bytes))
2365           break;
2366       }
2367 
2368       // Don't try to reschedule too many instructions.
2369       if (NumMove == InstReorderLimit)
2370         break;
2371 
2372       // Found a mergable instruction; save information about it.
2373       ++NumMove;
2374       LastOffset = Offset;
2375       LastBytes = Bytes;
2376       LastOpcode = LSMOpcode;
2377 
2378       unsigned Loc = MI2LocMap[Op];
2379       if (Loc <= FirstLoc) {
2380         FirstLoc = Loc;
2381         FirstOp = Op;
2382       }
2383       if (Loc >= LastLoc) {
2384         LastLoc = Loc;
2385         LastOp = Op;
2386       }
2387     }
2388 
2389     if (NumMove <= 1)
2390       Ops.pop_back();
2391     else {
2392       SmallPtrSet<MachineInstr*, 4> MemOps;
2393       SmallSet<unsigned, 4> MemRegs;
2394       for (size_t i = Ops.size() - NumMove, e = Ops.size(); i != e; ++i) {
2395         MemOps.insert(Ops[i]);
2396         MemRegs.insert(Ops[i]->getOperand(0).getReg());
2397       }
2398 
2399       // Be conservative, if the instructions are too far apart, don't
2400       // move them. We want to limit the increase of register pressure.
2401       bool DoMove = (LastLoc - FirstLoc) <= NumMove*4; // FIXME: Tune this.
2402       if (DoMove)
2403         DoMove = IsSafeAndProfitableToMove(isLd, Base, FirstOp, LastOp,
2404                                            MemOps, MemRegs, TRI, AA);
2405       if (!DoMove) {
2406         for (unsigned i = 0; i != NumMove; ++i)
2407           Ops.pop_back();
2408       } else {
2409         // This is the new location for the loads / stores.
2410         MachineBasicBlock::iterator InsertPos = isLd ? FirstOp : LastOp;
2411         while (InsertPos != MBB->end() &&
2412                (MemOps.count(&*InsertPos) || InsertPos->isDebugInstr()))
2413           ++InsertPos;
2414 
2415         // If we are moving a pair of loads / stores, see if it makes sense
2416         // to try to allocate a pair of registers that can form register pairs.
2417         MachineInstr *Op0 = Ops.back();
2418         MachineInstr *Op1 = Ops[Ops.size()-2];
2419         Register FirstReg, SecondReg;
2420         Register BaseReg, PredReg;
2421         ARMCC::CondCodes Pred = ARMCC::AL;
2422         bool isT2 = false;
2423         unsigned NewOpc = 0;
2424         int Offset = 0;
2425         DebugLoc dl;
2426         if (NumMove == 2 && CanFormLdStDWord(Op0, Op1, dl, NewOpc,
2427                                              FirstReg, SecondReg, BaseReg,
2428                                              Offset, PredReg, Pred, isT2)) {
2429           Ops.pop_back();
2430           Ops.pop_back();
2431 
2432           const MCInstrDesc &MCID = TII->get(NewOpc);
2433           const TargetRegisterClass *TRC = TII->getRegClass(MCID, 0, TRI, *MF);
2434           MRI->constrainRegClass(FirstReg, TRC);
2435           MRI->constrainRegClass(SecondReg, TRC);
2436 
2437           // Form the pair instruction.
2438           if (isLd) {
2439             MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)
2440               .addReg(FirstReg, RegState::Define)
2441               .addReg(SecondReg, RegState::Define)
2442               .addReg(BaseReg);
2443             // FIXME: We're converting from LDRi12 to an insn that still
2444             // uses addrmode2, so we need an explicit offset reg. It should
2445             // always by reg0 since we're transforming LDRi12s.
2446             if (!isT2)
2447               MIB.addReg(0);
2448             MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
2449             MIB.cloneMergedMemRefs({Op0, Op1});
2450             LLVM_DEBUG(dbgs() << "Formed " << *MIB << "\n");
2451             ++NumLDRDFormed;
2452           } else {
2453             MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)
2454               .addReg(FirstReg)
2455               .addReg(SecondReg)
2456               .addReg(BaseReg);
2457             // FIXME: We're converting from LDRi12 to an insn that still
2458             // uses addrmode2, so we need an explicit offset reg. It should
2459             // always by reg0 since we're transforming STRi12s.
2460             if (!isT2)
2461               MIB.addReg(0);
2462             MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
2463             MIB.cloneMergedMemRefs({Op0, Op1});
2464             LLVM_DEBUG(dbgs() << "Formed " << *MIB << "\n");
2465             ++NumSTRDFormed;
2466           }
2467           MBB->erase(Op0);
2468           MBB->erase(Op1);
2469 
2470           if (!isT2) {
2471             // Add register allocation hints to form register pairs.
2472             MRI->setRegAllocationHint(FirstReg, ARMRI::RegPairEven, SecondReg);
2473             MRI->setRegAllocationHint(SecondReg,  ARMRI::RegPairOdd, FirstReg);
2474           }
2475         } else {
2476           for (unsigned i = 0; i != NumMove; ++i) {
2477             MachineInstr *Op = Ops.pop_back_val();
2478             MBB->splice(InsertPos, MBB, Op);
2479           }
2480         }
2481 
2482         NumLdStMoved += NumMove;
2483         RetVal = true;
2484       }
2485     }
2486   }
2487 
2488   return RetVal;
2489 }
2490 
2491 bool
2492 ARMPreAllocLoadStoreOpt::RescheduleLoadStoreInstrs(MachineBasicBlock *MBB) {
2493   bool RetVal = false;
2494 
2495   DenseMap<MachineInstr*, unsigned> MI2LocMap;
2496   using MapIt = DenseMap<unsigned, SmallVector<MachineInstr *, 4>>::iterator;
2497   using Base2InstMap = DenseMap<unsigned, SmallVector<MachineInstr *, 4>>;
2498   using BaseVec = SmallVector<unsigned, 4>;
2499   Base2InstMap Base2LdsMap;
2500   Base2InstMap Base2StsMap;
2501   BaseVec LdBases;
2502   BaseVec StBases;
2503 
2504   unsigned Loc = 0;
2505   MachineBasicBlock::iterator MBBI = MBB->begin();
2506   MachineBasicBlock::iterator E = MBB->end();
2507   while (MBBI != E) {
2508     for (; MBBI != E; ++MBBI) {
2509       MachineInstr &MI = *MBBI;
2510       if (MI.isCall() || MI.isTerminator()) {
2511         // Stop at barriers.
2512         ++MBBI;
2513         break;
2514       }
2515 
2516       if (!MI.isDebugInstr())
2517         MI2LocMap[&MI] = ++Loc;
2518 
2519       if (!isMemoryOp(MI))
2520         continue;
2521       Register PredReg;
2522       if (getInstrPredicate(MI, PredReg) != ARMCC::AL)
2523         continue;
2524 
2525       int Opc = MI.getOpcode();
2526       bool isLd = isLoadSingle(Opc);
2527       Register Base = MI.getOperand(1).getReg();
2528       int Offset = getMemoryOpOffset(MI);
2529       bool StopHere = false;
2530       auto FindBases = [&] (Base2InstMap &Base2Ops, BaseVec &Bases) {
2531         MapIt BI = Base2Ops.find(Base);
2532         if (BI == Base2Ops.end()) {
2533           Base2Ops[Base].push_back(&MI);
2534           Bases.push_back(Base);
2535           return;
2536         }
2537         for (unsigned i = 0, e = BI->second.size(); i != e; ++i) {
2538           if (Offset == getMemoryOpOffset(*BI->second[i])) {
2539             StopHere = true;
2540             break;
2541           }
2542         }
2543         if (!StopHere)
2544           BI->second.push_back(&MI);
2545       };
2546 
2547       if (isLd)
2548         FindBases(Base2LdsMap, LdBases);
2549       else
2550         FindBases(Base2StsMap, StBases);
2551 
2552       if (StopHere) {
2553         // Found a duplicate (a base+offset combination that's seen earlier).
2554         // Backtrack.
2555         --Loc;
2556         break;
2557       }
2558     }
2559 
2560     // Re-schedule loads.
2561     for (unsigned i = 0, e = LdBases.size(); i != e; ++i) {
2562       unsigned Base = LdBases[i];
2563       SmallVectorImpl<MachineInstr *> &Lds = Base2LdsMap[Base];
2564       if (Lds.size() > 1)
2565         RetVal |= RescheduleOps(MBB, Lds, Base, true, MI2LocMap);
2566     }
2567 
2568     // Re-schedule stores.
2569     for (unsigned i = 0, e = StBases.size(); i != e; ++i) {
2570       unsigned Base = StBases[i];
2571       SmallVectorImpl<MachineInstr *> &Sts = Base2StsMap[Base];
2572       if (Sts.size() > 1)
2573         RetVal |= RescheduleOps(MBB, Sts, Base, false, MI2LocMap);
2574     }
2575 
2576     if (MBBI != E) {
2577       Base2LdsMap.clear();
2578       Base2StsMap.clear();
2579       LdBases.clear();
2580       StBases.clear();
2581     }
2582   }
2583 
2584   return RetVal;
2585 }
2586 
2587 // Get the Base register operand index from the memory access MachineInst if we
2588 // should attempt to distribute postinc on it. Return -1 if not of a valid
2589 // instruction type. If it returns an index, it is assumed that instruction is a
2590 // r+i indexing mode, and getBaseOperandIndex() + 1 is the Offset index.
2591 static int getBaseOperandIndex(MachineInstr &MI) {
2592   switch (MI.getOpcode()) {
2593   case ARM::MVE_VLDRBS16:
2594   case ARM::MVE_VLDRBS32:
2595   case ARM::MVE_VLDRBU16:
2596   case ARM::MVE_VLDRBU32:
2597   case ARM::MVE_VLDRHS32:
2598   case ARM::MVE_VLDRHU32:
2599   case ARM::MVE_VLDRBU8:
2600   case ARM::MVE_VLDRHU16:
2601   case ARM::MVE_VLDRWU32:
2602   case ARM::MVE_VSTRB16:
2603   case ARM::MVE_VSTRB32:
2604   case ARM::MVE_VSTRH32:
2605   case ARM::MVE_VSTRBU8:
2606   case ARM::MVE_VSTRHU16:
2607   case ARM::MVE_VSTRWU32:
2608   case ARM::t2LDRHi8:
2609   case ARM::t2LDRHi12:
2610   case ARM::t2LDRSHi8:
2611   case ARM::t2LDRSHi12:
2612   case ARM::t2LDRBi8:
2613   case ARM::t2LDRBi12:
2614   case ARM::t2LDRSBi8:
2615   case ARM::t2LDRSBi12:
2616   case ARM::t2STRBi8:
2617   case ARM::t2STRBi12:
2618   case ARM::t2STRHi8:
2619   case ARM::t2STRHi12:
2620     return 1;
2621   case ARM::MVE_VLDRBS16_post:
2622   case ARM::MVE_VLDRBS32_post:
2623   case ARM::MVE_VLDRBU16_post:
2624   case ARM::MVE_VLDRBU32_post:
2625   case ARM::MVE_VLDRHS32_post:
2626   case ARM::MVE_VLDRHU32_post:
2627   case ARM::MVE_VLDRBU8_post:
2628   case ARM::MVE_VLDRHU16_post:
2629   case ARM::MVE_VLDRWU32_post:
2630   case ARM::MVE_VSTRB16_post:
2631   case ARM::MVE_VSTRB32_post:
2632   case ARM::MVE_VSTRH32_post:
2633   case ARM::MVE_VSTRBU8_post:
2634   case ARM::MVE_VSTRHU16_post:
2635   case ARM::MVE_VSTRWU32_post:
2636   case ARM::MVE_VLDRBS16_pre:
2637   case ARM::MVE_VLDRBS32_pre:
2638   case ARM::MVE_VLDRBU16_pre:
2639   case ARM::MVE_VLDRBU32_pre:
2640   case ARM::MVE_VLDRHS32_pre:
2641   case ARM::MVE_VLDRHU32_pre:
2642   case ARM::MVE_VLDRBU8_pre:
2643   case ARM::MVE_VLDRHU16_pre:
2644   case ARM::MVE_VLDRWU32_pre:
2645   case ARM::MVE_VSTRB16_pre:
2646   case ARM::MVE_VSTRB32_pre:
2647   case ARM::MVE_VSTRH32_pre:
2648   case ARM::MVE_VSTRBU8_pre:
2649   case ARM::MVE_VSTRHU16_pre:
2650   case ARM::MVE_VSTRWU32_pre:
2651     return 2;
2652   }
2653   return -1;
2654 }
2655 
2656 static bool isPostIndex(MachineInstr &MI) {
2657   switch (MI.getOpcode()) {
2658   case ARM::MVE_VLDRBS16_post:
2659   case ARM::MVE_VLDRBS32_post:
2660   case ARM::MVE_VLDRBU16_post:
2661   case ARM::MVE_VLDRBU32_post:
2662   case ARM::MVE_VLDRHS32_post:
2663   case ARM::MVE_VLDRHU32_post:
2664   case ARM::MVE_VLDRBU8_post:
2665   case ARM::MVE_VLDRHU16_post:
2666   case ARM::MVE_VLDRWU32_post:
2667   case ARM::MVE_VSTRB16_post:
2668   case ARM::MVE_VSTRB32_post:
2669   case ARM::MVE_VSTRH32_post:
2670   case ARM::MVE_VSTRBU8_post:
2671   case ARM::MVE_VSTRHU16_post:
2672   case ARM::MVE_VSTRWU32_post:
2673     return true;
2674   }
2675   return false;
2676 }
2677 
2678 static bool isPreIndex(MachineInstr &MI) {
2679   switch (MI.getOpcode()) {
2680   case ARM::MVE_VLDRBS16_pre:
2681   case ARM::MVE_VLDRBS32_pre:
2682   case ARM::MVE_VLDRBU16_pre:
2683   case ARM::MVE_VLDRBU32_pre:
2684   case ARM::MVE_VLDRHS32_pre:
2685   case ARM::MVE_VLDRHU32_pre:
2686   case ARM::MVE_VLDRBU8_pre:
2687   case ARM::MVE_VLDRHU16_pre:
2688   case ARM::MVE_VLDRWU32_pre:
2689   case ARM::MVE_VSTRB16_pre:
2690   case ARM::MVE_VSTRB32_pre:
2691   case ARM::MVE_VSTRH32_pre:
2692   case ARM::MVE_VSTRBU8_pre:
2693   case ARM::MVE_VSTRHU16_pre:
2694   case ARM::MVE_VSTRWU32_pre:
2695     return true;
2696   }
2697   return false;
2698 }
2699 
2700 // Given a memory access Opcode, check that the give Imm would be a valid Offset
2701 // for this instruction (same as isLegalAddressImm), Or if the instruction
2702 // could be easily converted to one where that was valid. For example converting
2703 // t2LDRi12 to t2LDRi8 for negative offsets. Works in conjunction with
2704 // AdjustBaseAndOffset below.
2705 static bool isLegalOrConvertableAddressImm(unsigned Opcode, int Imm,
2706                                            const TargetInstrInfo *TII,
2707                                            int &CodesizeEstimate) {
2708   if (isLegalAddressImm(Opcode, Imm, TII))
2709     return true;
2710 
2711   // We can convert AddrModeT2_i12 to AddrModeT2_i8neg.
2712   const MCInstrDesc &Desc = TII->get(Opcode);
2713   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
2714   switch (AddrMode) {
2715   case ARMII::AddrModeT2_i12:
2716     CodesizeEstimate += 1;
2717     return Imm < 0 && -Imm < ((1 << 8) * 1);
2718   }
2719   return false;
2720 }
2721 
2722 // Given an MI adjust its address BaseReg to use NewBaseReg and address offset
2723 // by -Offset. This can either happen in-place or be a replacement as MI is
2724 // converted to another instruction type.
2725 static void AdjustBaseAndOffset(MachineInstr *MI, Register NewBaseReg,
2726                                 int Offset, const TargetInstrInfo *TII,
2727                                 const TargetRegisterInfo *TRI) {
2728   // Set the Base reg
2729   unsigned BaseOp = getBaseOperandIndex(*MI);
2730   MI->getOperand(BaseOp).setReg(NewBaseReg);
2731   // and constrain the reg class to that required by the instruction.
2732   MachineFunction *MF = MI->getMF();
2733   MachineRegisterInfo &MRI = MF->getRegInfo();
2734   const MCInstrDesc &MCID = TII->get(MI->getOpcode());
2735   const TargetRegisterClass *TRC = TII->getRegClass(MCID, BaseOp, TRI, *MF);
2736   MRI.constrainRegClass(NewBaseReg, TRC);
2737 
2738   int OldOffset = MI->getOperand(BaseOp + 1).getImm();
2739   if (isLegalAddressImm(MI->getOpcode(), OldOffset - Offset, TII))
2740     MI->getOperand(BaseOp + 1).setImm(OldOffset - Offset);
2741   else {
2742     unsigned ConvOpcode;
2743     switch (MI->getOpcode()) {
2744     case ARM::t2LDRHi12:
2745       ConvOpcode = ARM::t2LDRHi8;
2746       break;
2747     case ARM::t2LDRSHi12:
2748       ConvOpcode = ARM::t2LDRSHi8;
2749       break;
2750     case ARM::t2LDRBi12:
2751       ConvOpcode = ARM::t2LDRBi8;
2752       break;
2753     case ARM::t2LDRSBi12:
2754       ConvOpcode = ARM::t2LDRSBi8;
2755       break;
2756     case ARM::t2STRHi12:
2757       ConvOpcode = ARM::t2STRHi8;
2758       break;
2759     case ARM::t2STRBi12:
2760       ConvOpcode = ARM::t2STRBi8;
2761       break;
2762     default:
2763       llvm_unreachable("Unhandled convertable opcode");
2764     }
2765     assert(isLegalAddressImm(ConvOpcode, OldOffset - Offset, TII) &&
2766            "Illegal Address Immediate after convert!");
2767 
2768     const MCInstrDesc &MCID = TII->get(ConvOpcode);
2769     BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), MCID)
2770         .add(MI->getOperand(0))
2771         .add(MI->getOperand(1))
2772         .addImm(OldOffset - Offset)
2773         .add(MI->getOperand(3))
2774         .add(MI->getOperand(4))
2775         .cloneMemRefs(*MI);
2776     MI->eraseFromParent();
2777   }
2778 }
2779 
2780 static MachineInstr *createPostIncLoadStore(MachineInstr *MI, int Offset,
2781                                             Register NewReg,
2782                                             const TargetInstrInfo *TII,
2783                                             const TargetRegisterInfo *TRI) {
2784   MachineFunction *MF = MI->getMF();
2785   MachineRegisterInfo &MRI = MF->getRegInfo();
2786 
2787   unsigned NewOpcode = getPostIndexedLoadStoreOpcode(
2788       MI->getOpcode(), Offset > 0 ? ARM_AM::add : ARM_AM::sub);
2789 
2790   const MCInstrDesc &MCID = TII->get(NewOpcode);
2791   // Constrain the def register class
2792   const TargetRegisterClass *TRC = TII->getRegClass(MCID, 0, TRI, *MF);
2793   MRI.constrainRegClass(NewReg, TRC);
2794   // And do the same for the base operand
2795   TRC = TII->getRegClass(MCID, 2, TRI, *MF);
2796   MRI.constrainRegClass(MI->getOperand(1).getReg(), TRC);
2797 
2798   unsigned AddrMode = (MCID.TSFlags & ARMII::AddrModeMask);
2799   switch (AddrMode) {
2800   case ARMII::AddrModeT2_i7:
2801   case ARMII::AddrModeT2_i7s2:
2802   case ARMII::AddrModeT2_i7s4:
2803     // Any MVE load/store
2804     return BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), MCID)
2805         .addReg(NewReg, RegState::Define)
2806         .add(MI->getOperand(0))
2807         .add(MI->getOperand(1))
2808         .addImm(Offset)
2809         .add(MI->getOperand(3))
2810         .add(MI->getOperand(4))
2811         .add(MI->getOperand(5))
2812         .cloneMemRefs(*MI);
2813   case ARMII::AddrModeT2_i8:
2814     if (MI->mayLoad()) {
2815       return BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), MCID)
2816           .add(MI->getOperand(0))
2817           .addReg(NewReg, RegState::Define)
2818           .add(MI->getOperand(1))
2819           .addImm(Offset)
2820           .add(MI->getOperand(3))
2821           .add(MI->getOperand(4))
2822           .cloneMemRefs(*MI);
2823     } else {
2824       return BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), MCID)
2825           .addReg(NewReg, RegState::Define)
2826           .add(MI->getOperand(0))
2827           .add(MI->getOperand(1))
2828           .addImm(Offset)
2829           .add(MI->getOperand(3))
2830           .add(MI->getOperand(4))
2831           .cloneMemRefs(*MI);
2832     }
2833   default:
2834     llvm_unreachable("Unhandled createPostIncLoadStore");
2835   }
2836 }
2837 
2838 // Given a Base Register, optimise the load/store uses to attempt to create more
2839 // post-inc accesses and less register moves. We do this by taking zero offset
2840 // loads/stores with an add, and convert them to a postinc load/store of the
2841 // same type. Any subsequent accesses will be adjusted to use and account for
2842 // the post-inc value.
2843 // For example:
2844 // LDR #0            LDR_POSTINC #16
2845 // LDR #4            LDR #-12
2846 // LDR #8            LDR #-8
2847 // LDR #12           LDR #-4
2848 // ADD #16
2849 //
2850 // At the same time if we do not find an increment but do find an existing
2851 // pre/post inc instruction, we can still adjust the offsets of subsequent
2852 // instructions to save the register move that would otherwise be needed for the
2853 // in-place increment.
2854 bool ARMPreAllocLoadStoreOpt::DistributeIncrements(Register Base) {
2855   // We are looking for:
2856   // One zero offset load/store that can become postinc
2857   MachineInstr *BaseAccess = nullptr;
2858   MachineInstr *PrePostInc = nullptr;
2859   // An increment that can be folded in
2860   MachineInstr *Increment = nullptr;
2861   // Other accesses after BaseAccess that will need to be updated to use the
2862   // postinc value.
2863   SmallPtrSet<MachineInstr *, 8> OtherAccesses;
2864   for (auto &Use : MRI->use_nodbg_instructions(Base)) {
2865     if (!Increment && getAddSubImmediate(Use) != 0) {
2866       Increment = &Use;
2867       continue;
2868     }
2869 
2870     int BaseOp = getBaseOperandIndex(Use);
2871     if (BaseOp == -1)
2872       return false;
2873 
2874     if (!Use.getOperand(BaseOp).isReg() ||
2875         Use.getOperand(BaseOp).getReg() != Base)
2876       return false;
2877     if (isPreIndex(Use) || isPostIndex(Use))
2878       PrePostInc = &Use;
2879     else if (Use.getOperand(BaseOp + 1).getImm() == 0)
2880       BaseAccess = &Use;
2881     else
2882       OtherAccesses.insert(&Use);
2883   }
2884 
2885   int IncrementOffset;
2886   Register NewBaseReg;
2887   if (BaseAccess && Increment) {
2888     if (PrePostInc || BaseAccess->getParent() != Increment->getParent())
2889       return false;
2890     Register PredReg;
2891     if (Increment->definesRegister(ARM::CPSR) ||
2892         getInstrPredicate(*Increment, PredReg) != ARMCC::AL)
2893       return false;
2894 
2895     LLVM_DEBUG(dbgs() << "\nAttempting to distribute increments on VirtualReg "
2896                       << Base.virtRegIndex() << "\n");
2897 
2898     // Make sure that Increment has no uses before BaseAccess.
2899     for (MachineInstr &Use :
2900         MRI->use_nodbg_instructions(Increment->getOperand(0).getReg())) {
2901       if (!DT->dominates(BaseAccess, &Use) || &Use == BaseAccess) {
2902         LLVM_DEBUG(dbgs() << "  BaseAccess doesn't dominate use of increment\n");
2903         return false;
2904       }
2905     }
2906 
2907     // Make sure that Increment can be folded into Base
2908     IncrementOffset = getAddSubImmediate(*Increment);
2909     unsigned NewPostIncOpcode = getPostIndexedLoadStoreOpcode(
2910         BaseAccess->getOpcode(), IncrementOffset > 0 ? ARM_AM::add : ARM_AM::sub);
2911     if (!isLegalAddressImm(NewPostIncOpcode, IncrementOffset, TII)) {
2912       LLVM_DEBUG(dbgs() << "  Illegal addressing mode immediate on postinc\n");
2913       return false;
2914     }
2915   }
2916   else if (PrePostInc) {
2917     // If we already have a pre/post index load/store then set BaseAccess,
2918     // IncrementOffset and NewBaseReg to the values it already produces,
2919     // allowing us to update and subsequent uses of BaseOp reg with the
2920     // incremented value.
2921     if (Increment)
2922       return false;
2923 
2924     LLVM_DEBUG(dbgs() << "\nAttempting to distribute increments on already "
2925                       << "indexed VirtualReg " << Base.virtRegIndex() << "\n");
2926     int BaseOp = getBaseOperandIndex(*PrePostInc);
2927     IncrementOffset = PrePostInc->getOperand(BaseOp+1).getImm();
2928     BaseAccess = PrePostInc;
2929     NewBaseReg = PrePostInc->getOperand(0).getReg();
2930   }
2931   else
2932     return false;
2933 
2934   // And make sure that the negative value of increment can be added to all
2935   // other offsets after the BaseAccess. We rely on either
2936   // dominates(BaseAccess, OtherAccess) or dominates(OtherAccess, BaseAccess)
2937   // to keep things simple.
2938   // This also adds a simple codesize metric, to detect if an instruction (like
2939   // t2LDRBi12) which can often be shrunk to a thumb1 instruction (tLDRBi)
2940   // cannot because it is converted to something else (t2LDRBi8). We start this
2941   // at -1 for the gain from removing the increment.
2942   SmallPtrSet<MachineInstr *, 4> SuccessorAccesses;
2943   int CodesizeEstimate = -1;
2944   for (auto *Use : OtherAccesses) {
2945     if (DT->dominates(BaseAccess, Use)) {
2946       SuccessorAccesses.insert(Use);
2947       unsigned BaseOp = getBaseOperandIndex(*Use);
2948       if (!isLegalOrConvertableAddressImm(Use->getOpcode(),
2949                                           Use->getOperand(BaseOp + 1).getImm() -
2950                                               IncrementOffset,
2951                                           TII, CodesizeEstimate)) {
2952         LLVM_DEBUG(dbgs() << "  Illegal addressing mode immediate on use\n");
2953         return false;
2954       }
2955     } else if (!DT->dominates(Use, BaseAccess)) {
2956       LLVM_DEBUG(
2957           dbgs() << "  Unknown dominance relation between Base and Use\n");
2958       return false;
2959     }
2960   }
2961   if (STI->hasMinSize() && CodesizeEstimate > 0) {
2962     LLVM_DEBUG(dbgs() << "  Expected to grow instructions under minsize\n");
2963     return false;
2964   }
2965 
2966   if (!PrePostInc) {
2967     // Replace BaseAccess with a post inc
2968     LLVM_DEBUG(dbgs() << "Changing: "; BaseAccess->dump());
2969     LLVM_DEBUG(dbgs() << "  And   : "; Increment->dump());
2970     NewBaseReg = Increment->getOperand(0).getReg();
2971     MachineInstr *BaseAccessPost =
2972         createPostIncLoadStore(BaseAccess, IncrementOffset, NewBaseReg, TII, TRI);
2973     BaseAccess->eraseFromParent();
2974     Increment->eraseFromParent();
2975     (void)BaseAccessPost;
2976     LLVM_DEBUG(dbgs() << "  To    : "; BaseAccessPost->dump());
2977   }
2978 
2979   for (auto *Use : SuccessorAccesses) {
2980     LLVM_DEBUG(dbgs() << "Changing: "; Use->dump());
2981     AdjustBaseAndOffset(Use, NewBaseReg, IncrementOffset, TII, TRI);
2982     LLVM_DEBUG(dbgs() << "  To    : "; Use->dump());
2983   }
2984 
2985   // Remove the kill flag from all uses of NewBaseReg, in case any old uses
2986   // remain.
2987   for (MachineOperand &Op : MRI->use_nodbg_operands(NewBaseReg))
2988     Op.setIsKill(false);
2989   return true;
2990 }
2991 
2992 bool ARMPreAllocLoadStoreOpt::DistributeIncrements() {
2993   bool Changed = false;
2994   SmallSetVector<Register, 4> Visited;
2995   for (auto &MBB : *MF) {
2996     for (auto &MI : MBB) {
2997       int BaseOp = getBaseOperandIndex(MI);
2998       if (BaseOp == -1 || !MI.getOperand(BaseOp).isReg())
2999         continue;
3000 
3001       Register Base = MI.getOperand(BaseOp).getReg();
3002       if (!Base.isVirtual() || Visited.count(Base))
3003         continue;
3004 
3005       Visited.insert(Base);
3006     }
3007   }
3008 
3009   for (auto Base : Visited)
3010     Changed |= DistributeIncrements(Base);
3011 
3012   return Changed;
3013 }
3014 
3015 /// Returns an instance of the load / store optimization pass.
3016 FunctionPass *llvm::createARMLoadStoreOptimizationPass(bool PreAlloc) {
3017   if (PreAlloc)
3018     return new ARMPreAllocLoadStoreOpt();
3019   return new ARMLoadStoreOpt();
3020 }
3021