1 //===-- ARMLoadStoreOptimizer.cpp - ARM load / store opt. pass ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file This file contains a pass that performs load / store related peephole
11 /// optimizations. This pass should be run after register allocation.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ARM.h"
16 #include "ARMBaseInstrInfo.h"
17 #include "ARMBaseRegisterInfo.h"
18 #include "ARMISelLowering.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMSubtarget.h"
21 #include "MCTargetDesc/ARMAddressingModes.h"
22 #include "ThumbRegisterInfo.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/RegisterClassInfo.h"
35 #include "llvm/CodeGen/SelectionDAGNodes.h"
36 #include "llvm/CodeGen/LivePhysRegs.h"
37 #include "llvm/IR/DataLayout.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/Support/Allocator.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetRegisterInfo.h"
47 using namespace llvm;
48 
49 #define DEBUG_TYPE "arm-ldst-opt"
50 
51 STATISTIC(NumLDMGened , "Number of ldm instructions generated");
52 STATISTIC(NumSTMGened , "Number of stm instructions generated");
53 STATISTIC(NumVLDMGened, "Number of vldm instructions generated");
54 STATISTIC(NumVSTMGened, "Number of vstm instructions generated");
55 STATISTIC(NumLdStMoved, "Number of load / store instructions moved");
56 STATISTIC(NumLDRDFormed,"Number of ldrd created before allocation");
57 STATISTIC(NumSTRDFormed,"Number of strd created before allocation");
58 STATISTIC(NumLDRD2LDM,  "Number of ldrd instructions turned back into ldm");
59 STATISTIC(NumSTRD2STM,  "Number of strd instructions turned back into stm");
60 STATISTIC(NumLDRD2LDR,  "Number of ldrd instructions turned back into ldr's");
61 STATISTIC(NumSTRD2STR,  "Number of strd instructions turned back into str's");
62 
63 /// This switch disables formation of double/multi instructions that could
64 /// potentially lead to (new) alignment traps even with CCR.UNALIGN_TRP
65 /// disabled. This can be used to create libraries that are robust even when
66 /// users provoke undefined behaviour by supplying misaligned pointers.
67 /// \see mayCombineMisaligned()
68 static cl::opt<bool>
69 AssumeMisalignedLoadStores("arm-assume-misaligned-load-store", cl::Hidden,
70     cl::init(false), cl::desc("Be more conservative in ARM load/store opt"));
71 
72 #define ARM_LOAD_STORE_OPT_NAME "ARM load / store optimization pass"
73 
74 namespace {
75   /// Post- register allocation pass the combine load / store instructions to
76   /// form ldm / stm instructions.
77   struct ARMLoadStoreOpt : public MachineFunctionPass {
78     static char ID;
79     ARMLoadStoreOpt() : MachineFunctionPass(ID) {}
80 
81     const MachineFunction *MF;
82     const TargetInstrInfo *TII;
83     const TargetRegisterInfo *TRI;
84     const ARMSubtarget *STI;
85     const TargetLowering *TL;
86     ARMFunctionInfo *AFI;
87     LivePhysRegs LiveRegs;
88     RegisterClassInfo RegClassInfo;
89     MachineBasicBlock::const_iterator LiveRegPos;
90     bool LiveRegsValid;
91     bool RegClassInfoValid;
92     bool isThumb1, isThumb2;
93 
94     bool runOnMachineFunction(MachineFunction &Fn) override;
95 
96     MachineFunctionProperties getRequiredProperties() const override {
97       return MachineFunctionProperties().set(
98           MachineFunctionProperties::Property::NoVRegs);
99     }
100 
101     StringRef getPassName() const override { return ARM_LOAD_STORE_OPT_NAME; }
102 
103   private:
104     /// A set of load/store MachineInstrs with same base register sorted by
105     /// offset.
106     struct MemOpQueueEntry {
107       MachineInstr *MI;
108       int Offset;        ///< Load/Store offset.
109       unsigned Position; ///< Position as counted from end of basic block.
110       MemOpQueueEntry(MachineInstr &MI, int Offset, unsigned Position)
111           : MI(&MI), Offset(Offset), Position(Position) {}
112     };
113     typedef SmallVector<MemOpQueueEntry,8> MemOpQueue;
114 
115     /// A set of MachineInstrs that fulfill (nearly all) conditions to get
116     /// merged into a LDM/STM.
117     struct MergeCandidate {
118       /// List of instructions ordered by load/store offset.
119       SmallVector<MachineInstr*, 4> Instrs;
120       /// Index in Instrs of the instruction being latest in the schedule.
121       unsigned LatestMIIdx;
122       /// Index in Instrs of the instruction being earliest in the schedule.
123       unsigned EarliestMIIdx;
124       /// Index into the basic block where the merged instruction will be
125       /// inserted. (See MemOpQueueEntry.Position)
126       unsigned InsertPos;
127       /// Whether the instructions can be merged into a ldm/stm instruction.
128       bool CanMergeToLSMulti;
129       /// Whether the instructions can be merged into a ldrd/strd instruction.
130       bool CanMergeToLSDouble;
131     };
132     SpecificBumpPtrAllocator<MergeCandidate> Allocator;
133     SmallVector<const MergeCandidate*,4> Candidates;
134     SmallVector<MachineInstr*,4> MergeBaseCandidates;
135 
136     void moveLiveRegsBefore(const MachineBasicBlock &MBB,
137                             MachineBasicBlock::const_iterator Before);
138     unsigned findFreeReg(const TargetRegisterClass &RegClass);
139     void UpdateBaseRegUses(MachineBasicBlock &MBB,
140                            MachineBasicBlock::iterator MBBI, const DebugLoc &DL,
141                            unsigned Base, unsigned WordOffset,
142                            ARMCC::CondCodes Pred, unsigned PredReg);
143     MachineInstr *CreateLoadStoreMulti(
144         MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
145         int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
146         ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
147         ArrayRef<std::pair<unsigned, bool>> Regs);
148     MachineInstr *CreateLoadStoreDouble(
149         MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
150         int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
151         ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
152         ArrayRef<std::pair<unsigned, bool>> Regs) const;
153     void FormCandidates(const MemOpQueue &MemOps);
154     MachineInstr *MergeOpsUpdate(const MergeCandidate &Cand);
155     bool FixInvalidRegPairOp(MachineBasicBlock &MBB,
156                              MachineBasicBlock::iterator &MBBI);
157     bool MergeBaseUpdateLoadStore(MachineInstr *MI);
158     bool MergeBaseUpdateLSMultiple(MachineInstr *MI);
159     bool MergeBaseUpdateLSDouble(MachineInstr &MI) const;
160     bool LoadStoreMultipleOpti(MachineBasicBlock &MBB);
161     bool MergeReturnIntoLDM(MachineBasicBlock &MBB);
162     bool CombineMovBx(MachineBasicBlock &MBB);
163   };
164   char ARMLoadStoreOpt::ID = 0;
165 }
166 
167 INITIALIZE_PASS(ARMLoadStoreOpt, "arm-ldst-opt", ARM_LOAD_STORE_OPT_NAME, false,
168                 false)
169 
170 static bool definesCPSR(const MachineInstr &MI) {
171   for (const auto &MO : MI.operands()) {
172     if (!MO.isReg())
173       continue;
174     if (MO.isDef() && MO.getReg() == ARM::CPSR && !MO.isDead())
175       // If the instruction has live CPSR def, then it's not safe to fold it
176       // into load / store.
177       return true;
178   }
179 
180   return false;
181 }
182 
183 static int getMemoryOpOffset(const MachineInstr &MI) {
184   unsigned Opcode = MI.getOpcode();
185   bool isAM3 = Opcode == ARM::LDRD || Opcode == ARM::STRD;
186   unsigned NumOperands = MI.getDesc().getNumOperands();
187   unsigned OffField = MI.getOperand(NumOperands - 3).getImm();
188 
189   if (Opcode == ARM::t2LDRi12 || Opcode == ARM::t2LDRi8 ||
190       Opcode == ARM::t2STRi12 || Opcode == ARM::t2STRi8 ||
191       Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8 ||
192       Opcode == ARM::LDRi12   || Opcode == ARM::STRi12)
193     return OffField;
194 
195   // Thumb1 immediate offsets are scaled by 4
196   if (Opcode == ARM::tLDRi || Opcode == ARM::tSTRi ||
197       Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi)
198     return OffField * 4;
199 
200   int Offset = isAM3 ? ARM_AM::getAM3Offset(OffField)
201     : ARM_AM::getAM5Offset(OffField) * 4;
202   ARM_AM::AddrOpc Op = isAM3 ? ARM_AM::getAM3Op(OffField)
203     : ARM_AM::getAM5Op(OffField);
204 
205   if (Op == ARM_AM::sub)
206     return -Offset;
207 
208   return Offset;
209 }
210 
211 static const MachineOperand &getLoadStoreBaseOp(const MachineInstr &MI) {
212   return MI.getOperand(1);
213 }
214 
215 static const MachineOperand &getLoadStoreRegOp(const MachineInstr &MI) {
216   return MI.getOperand(0);
217 }
218 
219 static int getLoadStoreMultipleOpcode(unsigned Opcode, ARM_AM::AMSubMode Mode) {
220   switch (Opcode) {
221   default: llvm_unreachable("Unhandled opcode!");
222   case ARM::LDRi12:
223     ++NumLDMGened;
224     switch (Mode) {
225     default: llvm_unreachable("Unhandled submode!");
226     case ARM_AM::ia: return ARM::LDMIA;
227     case ARM_AM::da: return ARM::LDMDA;
228     case ARM_AM::db: return ARM::LDMDB;
229     case ARM_AM::ib: return ARM::LDMIB;
230     }
231   case ARM::STRi12:
232     ++NumSTMGened;
233     switch (Mode) {
234     default: llvm_unreachable("Unhandled submode!");
235     case ARM_AM::ia: return ARM::STMIA;
236     case ARM_AM::da: return ARM::STMDA;
237     case ARM_AM::db: return ARM::STMDB;
238     case ARM_AM::ib: return ARM::STMIB;
239     }
240   case ARM::tLDRi:
241   case ARM::tLDRspi:
242     // tLDMIA is writeback-only - unless the base register is in the input
243     // reglist.
244     ++NumLDMGened;
245     switch (Mode) {
246     default: llvm_unreachable("Unhandled submode!");
247     case ARM_AM::ia: return ARM::tLDMIA;
248     }
249   case ARM::tSTRi:
250   case ARM::tSTRspi:
251     // There is no non-writeback tSTMIA either.
252     ++NumSTMGened;
253     switch (Mode) {
254     default: llvm_unreachable("Unhandled submode!");
255     case ARM_AM::ia: return ARM::tSTMIA_UPD;
256     }
257   case ARM::t2LDRi8:
258   case ARM::t2LDRi12:
259     ++NumLDMGened;
260     switch (Mode) {
261     default: llvm_unreachable("Unhandled submode!");
262     case ARM_AM::ia: return ARM::t2LDMIA;
263     case ARM_AM::db: return ARM::t2LDMDB;
264     }
265   case ARM::t2STRi8:
266   case ARM::t2STRi12:
267     ++NumSTMGened;
268     switch (Mode) {
269     default: llvm_unreachable("Unhandled submode!");
270     case ARM_AM::ia: return ARM::t2STMIA;
271     case ARM_AM::db: return ARM::t2STMDB;
272     }
273   case ARM::VLDRS:
274     ++NumVLDMGened;
275     switch (Mode) {
276     default: llvm_unreachable("Unhandled submode!");
277     case ARM_AM::ia: return ARM::VLDMSIA;
278     case ARM_AM::db: return 0; // Only VLDMSDB_UPD exists.
279     }
280   case ARM::VSTRS:
281     ++NumVSTMGened;
282     switch (Mode) {
283     default: llvm_unreachable("Unhandled submode!");
284     case ARM_AM::ia: return ARM::VSTMSIA;
285     case ARM_AM::db: return 0; // Only VSTMSDB_UPD exists.
286     }
287   case ARM::VLDRD:
288     ++NumVLDMGened;
289     switch (Mode) {
290     default: llvm_unreachable("Unhandled submode!");
291     case ARM_AM::ia: return ARM::VLDMDIA;
292     case ARM_AM::db: return 0; // Only VLDMDDB_UPD exists.
293     }
294   case ARM::VSTRD:
295     ++NumVSTMGened;
296     switch (Mode) {
297     default: llvm_unreachable("Unhandled submode!");
298     case ARM_AM::ia: return ARM::VSTMDIA;
299     case ARM_AM::db: return 0; // Only VSTMDDB_UPD exists.
300     }
301   }
302 }
303 
304 static ARM_AM::AMSubMode getLoadStoreMultipleSubMode(unsigned Opcode) {
305   switch (Opcode) {
306   default: llvm_unreachable("Unhandled opcode!");
307   case ARM::LDMIA_RET:
308   case ARM::LDMIA:
309   case ARM::LDMIA_UPD:
310   case ARM::STMIA:
311   case ARM::STMIA_UPD:
312   case ARM::tLDMIA:
313   case ARM::tLDMIA_UPD:
314   case ARM::tSTMIA_UPD:
315   case ARM::t2LDMIA_RET:
316   case ARM::t2LDMIA:
317   case ARM::t2LDMIA_UPD:
318   case ARM::t2STMIA:
319   case ARM::t2STMIA_UPD:
320   case ARM::VLDMSIA:
321   case ARM::VLDMSIA_UPD:
322   case ARM::VSTMSIA:
323   case ARM::VSTMSIA_UPD:
324   case ARM::VLDMDIA:
325   case ARM::VLDMDIA_UPD:
326   case ARM::VSTMDIA:
327   case ARM::VSTMDIA_UPD:
328     return ARM_AM::ia;
329 
330   case ARM::LDMDA:
331   case ARM::LDMDA_UPD:
332   case ARM::STMDA:
333   case ARM::STMDA_UPD:
334     return ARM_AM::da;
335 
336   case ARM::LDMDB:
337   case ARM::LDMDB_UPD:
338   case ARM::STMDB:
339   case ARM::STMDB_UPD:
340   case ARM::t2LDMDB:
341   case ARM::t2LDMDB_UPD:
342   case ARM::t2STMDB:
343   case ARM::t2STMDB_UPD:
344   case ARM::VLDMSDB_UPD:
345   case ARM::VSTMSDB_UPD:
346   case ARM::VLDMDDB_UPD:
347   case ARM::VSTMDDB_UPD:
348     return ARM_AM::db;
349 
350   case ARM::LDMIB:
351   case ARM::LDMIB_UPD:
352   case ARM::STMIB:
353   case ARM::STMIB_UPD:
354     return ARM_AM::ib;
355   }
356 }
357 
358 static bool isT1i32Load(unsigned Opc) {
359   return Opc == ARM::tLDRi || Opc == ARM::tLDRspi;
360 }
361 
362 static bool isT2i32Load(unsigned Opc) {
363   return Opc == ARM::t2LDRi12 || Opc == ARM::t2LDRi8;
364 }
365 
366 static bool isi32Load(unsigned Opc) {
367   return Opc == ARM::LDRi12 || isT1i32Load(Opc) || isT2i32Load(Opc) ;
368 }
369 
370 static bool isT1i32Store(unsigned Opc) {
371   return Opc == ARM::tSTRi || Opc == ARM::tSTRspi;
372 }
373 
374 static bool isT2i32Store(unsigned Opc) {
375   return Opc == ARM::t2STRi12 || Opc == ARM::t2STRi8;
376 }
377 
378 static bool isi32Store(unsigned Opc) {
379   return Opc == ARM::STRi12 || isT1i32Store(Opc) || isT2i32Store(Opc);
380 }
381 
382 static bool isLoadSingle(unsigned Opc) {
383   return isi32Load(Opc) || Opc == ARM::VLDRS || Opc == ARM::VLDRD;
384 }
385 
386 static unsigned getImmScale(unsigned Opc) {
387   switch (Opc) {
388   default: llvm_unreachable("Unhandled opcode!");
389   case ARM::tLDRi:
390   case ARM::tSTRi:
391   case ARM::tLDRspi:
392   case ARM::tSTRspi:
393     return 1;
394   case ARM::tLDRHi:
395   case ARM::tSTRHi:
396     return 2;
397   case ARM::tLDRBi:
398   case ARM::tSTRBi:
399     return 4;
400   }
401 }
402 
403 static unsigned getLSMultipleTransferSize(const MachineInstr *MI) {
404   switch (MI->getOpcode()) {
405   default: return 0;
406   case ARM::LDRi12:
407   case ARM::STRi12:
408   case ARM::tLDRi:
409   case ARM::tSTRi:
410   case ARM::tLDRspi:
411   case ARM::tSTRspi:
412   case ARM::t2LDRi8:
413   case ARM::t2LDRi12:
414   case ARM::t2STRi8:
415   case ARM::t2STRi12:
416   case ARM::VLDRS:
417   case ARM::VSTRS:
418     return 4;
419   case ARM::VLDRD:
420   case ARM::VSTRD:
421     return 8;
422   case ARM::LDMIA:
423   case ARM::LDMDA:
424   case ARM::LDMDB:
425   case ARM::LDMIB:
426   case ARM::STMIA:
427   case ARM::STMDA:
428   case ARM::STMDB:
429   case ARM::STMIB:
430   case ARM::tLDMIA:
431   case ARM::tLDMIA_UPD:
432   case ARM::tSTMIA_UPD:
433   case ARM::t2LDMIA:
434   case ARM::t2LDMDB:
435   case ARM::t2STMIA:
436   case ARM::t2STMDB:
437   case ARM::VLDMSIA:
438   case ARM::VSTMSIA:
439     return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 4;
440   case ARM::VLDMDIA:
441   case ARM::VSTMDIA:
442     return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 8;
443   }
444 }
445 
446 /// Update future uses of the base register with the offset introduced
447 /// due to writeback. This function only works on Thumb1.
448 void ARMLoadStoreOpt::UpdateBaseRegUses(MachineBasicBlock &MBB,
449                                         MachineBasicBlock::iterator MBBI,
450                                         const DebugLoc &DL, unsigned Base,
451                                         unsigned WordOffset,
452                                         ARMCC::CondCodes Pred,
453                                         unsigned PredReg) {
454   assert(isThumb1 && "Can only update base register uses for Thumb1!");
455   // Start updating any instructions with immediate offsets. Insert a SUB before
456   // the first non-updateable instruction (if any).
457   for (; MBBI != MBB.end(); ++MBBI) {
458     bool InsertSub = false;
459     unsigned Opc = MBBI->getOpcode();
460 
461     if (MBBI->readsRegister(Base)) {
462       int Offset;
463       bool IsLoad =
464         Opc == ARM::tLDRi || Opc == ARM::tLDRHi || Opc == ARM::tLDRBi;
465       bool IsStore =
466         Opc == ARM::tSTRi || Opc == ARM::tSTRHi || Opc == ARM::tSTRBi;
467 
468       if (IsLoad || IsStore) {
469         // Loads and stores with immediate offsets can be updated, but only if
470         // the new offset isn't negative.
471         // The MachineOperand containing the offset immediate is the last one
472         // before predicates.
473         MachineOperand &MO =
474           MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3);
475         // The offsets are scaled by 1, 2 or 4 depending on the Opcode.
476         Offset = MO.getImm() - WordOffset * getImmScale(Opc);
477 
478         // If storing the base register, it needs to be reset first.
479         unsigned InstrSrcReg = getLoadStoreRegOp(*MBBI).getReg();
480 
481         if (Offset >= 0 && !(IsStore && InstrSrcReg == Base))
482           MO.setImm(Offset);
483         else
484           InsertSub = true;
485 
486       } else if ((Opc == ARM::tSUBi8 || Opc == ARM::tADDi8) &&
487                  !definesCPSR(*MBBI)) {
488         // SUBS/ADDS using this register, with a dead def of the CPSR.
489         // Merge it with the update; if the merged offset is too large,
490         // insert a new sub instead.
491         MachineOperand &MO =
492           MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3);
493         Offset = (Opc == ARM::tSUBi8) ?
494           MO.getImm() + WordOffset * 4 :
495           MO.getImm() - WordOffset * 4 ;
496         if (Offset >= 0 && TL->isLegalAddImmediate(Offset)) {
497           // FIXME: Swap ADDS<->SUBS if Offset < 0, erase instruction if
498           // Offset == 0.
499           MO.setImm(Offset);
500           // The base register has now been reset, so exit early.
501           return;
502         } else {
503           InsertSub = true;
504         }
505 
506       } else {
507         // Can't update the instruction.
508         InsertSub = true;
509       }
510 
511     } else if (definesCPSR(*MBBI) || MBBI->isCall() || MBBI->isBranch()) {
512       // Since SUBS sets the condition flags, we can't place the base reset
513       // after an instruction that has a live CPSR def.
514       // The base register might also contain an argument for a function call.
515       InsertSub = true;
516     }
517 
518     if (InsertSub) {
519       // An instruction above couldn't be updated, so insert a sub.
520       BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base)
521           .add(t1CondCodeOp(true))
522           .addReg(Base)
523           .addImm(WordOffset * 4)
524           .addImm(Pred)
525           .addReg(PredReg);
526       return;
527     }
528 
529     if (MBBI->killsRegister(Base) || MBBI->definesRegister(Base))
530       // Register got killed. Stop updating.
531       return;
532   }
533 
534   // End of block was reached.
535   if (MBB.succ_size() > 0) {
536     // FIXME: Because of a bug, live registers are sometimes missing from
537     // the successor blocks' live-in sets. This means we can't trust that
538     // information and *always* have to reset at the end of a block.
539     // See PR21029.
540     if (MBBI != MBB.end()) --MBBI;
541     BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base)
542         .add(t1CondCodeOp(true))
543         .addReg(Base)
544         .addImm(WordOffset * 4)
545         .addImm(Pred)
546         .addReg(PredReg);
547   }
548 }
549 
550 /// Return the first register of class \p RegClass that is not in \p Regs.
551 unsigned ARMLoadStoreOpt::findFreeReg(const TargetRegisterClass &RegClass) {
552   if (!RegClassInfoValid) {
553     RegClassInfo.runOnMachineFunction(*MF);
554     RegClassInfoValid = true;
555   }
556 
557   for (unsigned Reg : RegClassInfo.getOrder(&RegClass))
558     if (!LiveRegs.contains(Reg))
559       return Reg;
560   return 0;
561 }
562 
563 /// Compute live registers just before instruction \p Before (in normal schedule
564 /// direction). Computes backwards so multiple queries in the same block must
565 /// come in reverse order.
566 void ARMLoadStoreOpt::moveLiveRegsBefore(const MachineBasicBlock &MBB,
567     MachineBasicBlock::const_iterator Before) {
568   // Initialize if we never queried in this block.
569   if (!LiveRegsValid) {
570     LiveRegs.init(*TRI);
571     LiveRegs.addLiveOuts(MBB);
572     LiveRegPos = MBB.end();
573     LiveRegsValid = true;
574   }
575   // Move backward just before the "Before" position.
576   while (LiveRegPos != Before) {
577     --LiveRegPos;
578     LiveRegs.stepBackward(*LiveRegPos);
579   }
580 }
581 
582 static bool ContainsReg(const ArrayRef<std::pair<unsigned, bool>> &Regs,
583                         unsigned Reg) {
584   for (const std::pair<unsigned, bool> &R : Regs)
585     if (R.first == Reg)
586       return true;
587   return false;
588 }
589 
590 /// Create and insert a LDM or STM with Base as base register and registers in
591 /// Regs as the register operands that would be loaded / stored.  It returns
592 /// true if the transformation is done.
593 MachineInstr *ARMLoadStoreOpt::CreateLoadStoreMulti(
594     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
595     int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
596     ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
597     ArrayRef<std::pair<unsigned, bool>> Regs) {
598   unsigned NumRegs = Regs.size();
599   assert(NumRegs > 1);
600 
601   // For Thumb1 targets, it might be necessary to clobber the CPSR to merge.
602   // Compute liveness information for that register to make the decision.
603   bool SafeToClobberCPSR = !isThumb1 ||
604     (MBB.computeRegisterLiveness(TRI, ARM::CPSR, InsertBefore, 20) ==
605      MachineBasicBlock::LQR_Dead);
606 
607   bool Writeback = isThumb1; // Thumb1 LDM/STM have base reg writeback.
608 
609   // Exception: If the base register is in the input reglist, Thumb1 LDM is
610   // non-writeback.
611   // It's also not possible to merge an STR of the base register in Thumb1.
612   if (isThumb1 && isi32Load(Opcode) && ContainsReg(Regs, Base)) {
613     assert(Base != ARM::SP && "Thumb1 does not allow SP in register list");
614     if (Opcode == ARM::tLDRi) {
615       Writeback = false;
616     } else if (Opcode == ARM::tSTRi) {
617       return nullptr;
618     }
619   }
620 
621   ARM_AM::AMSubMode Mode = ARM_AM::ia;
622   // VFP and Thumb2 do not support IB or DA modes. Thumb1 only supports IA.
623   bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);
624   bool haveIBAndDA = isNotVFP && !isThumb2 && !isThumb1;
625 
626   if (Offset == 4 && haveIBAndDA) {
627     Mode = ARM_AM::ib;
628   } else if (Offset == -4 * (int)NumRegs + 4 && haveIBAndDA) {
629     Mode = ARM_AM::da;
630   } else if (Offset == -4 * (int)NumRegs && isNotVFP && !isThumb1) {
631     // VLDM/VSTM do not support DB mode without also updating the base reg.
632     Mode = ARM_AM::db;
633   } else if (Offset != 0 || Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi) {
634     // Check if this is a supported opcode before inserting instructions to
635     // calculate a new base register.
636     if (!getLoadStoreMultipleOpcode(Opcode, Mode)) return nullptr;
637 
638     // If starting offset isn't zero, insert a MI to materialize a new base.
639     // But only do so if it is cost effective, i.e. merging more than two
640     // loads / stores.
641     if (NumRegs <= 2)
642       return nullptr;
643 
644     // On Thumb1, it's not worth materializing a new base register without
645     // clobbering the CPSR (i.e. not using ADDS/SUBS).
646     if (!SafeToClobberCPSR)
647       return nullptr;
648 
649     unsigned NewBase;
650     if (isi32Load(Opcode)) {
651       // If it is a load, then just use one of the destination registers
652       // as the new base. Will no longer be writeback in Thumb1.
653       NewBase = Regs[NumRegs-1].first;
654       Writeback = false;
655     } else {
656       // Find a free register that we can use as scratch register.
657       moveLiveRegsBefore(MBB, InsertBefore);
658       // The merged instruction does not exist yet but will use several Regs if
659       // it is a Store.
660       if (!isLoadSingle(Opcode))
661         for (const std::pair<unsigned, bool> &R : Regs)
662           LiveRegs.addReg(R.first);
663 
664       NewBase = findFreeReg(isThumb1 ? ARM::tGPRRegClass : ARM::GPRRegClass);
665       if (NewBase == 0)
666         return nullptr;
667     }
668 
669     int BaseOpc =
670       isThumb2 ? ARM::t2ADDri :
671       (isThumb1 && Base == ARM::SP) ? ARM::tADDrSPi :
672       (isThumb1 && Offset < 8) ? ARM::tADDi3 :
673       isThumb1 ? ARM::tADDi8  : ARM::ADDri;
674 
675     if (Offset < 0) {
676       Offset = - Offset;
677       BaseOpc =
678         isThumb2 ? ARM::t2SUBri :
679         (isThumb1 && Offset < 8 && Base != ARM::SP) ? ARM::tSUBi3 :
680         isThumb1 ? ARM::tSUBi8  : ARM::SUBri;
681     }
682 
683     if (!TL->isLegalAddImmediate(Offset))
684       // FIXME: Try add with register operand?
685       return nullptr; // Probably not worth it then.
686 
687     // We can only append a kill flag to the add/sub input if the value is not
688     // used in the register list of the stm as well.
689     bool KillOldBase = BaseKill &&
690       (!isi32Store(Opcode) || !ContainsReg(Regs, Base));
691 
692     if (isThumb1) {
693       // Thumb1: depending on immediate size, use either
694       //   ADDS NewBase, Base, #imm3
695       // or
696       //   MOV  NewBase, Base
697       //   ADDS NewBase, #imm8.
698       if (Base != NewBase &&
699           (BaseOpc == ARM::tADDi8 || BaseOpc == ARM::tSUBi8)) {
700         // Need to insert a MOV to the new base first.
701         if (isARMLowRegister(NewBase) && isARMLowRegister(Base) &&
702             !STI->hasV6Ops()) {
703           // thumbv4t doesn't have lo->lo copies, and we can't predicate tMOVSr
704           if (Pred != ARMCC::AL)
705             return nullptr;
706           BuildMI(MBB, InsertBefore, DL, TII->get(ARM::tMOVSr), NewBase)
707             .addReg(Base, getKillRegState(KillOldBase));
708         } else
709           BuildMI(MBB, InsertBefore, DL, TII->get(ARM::tMOVr), NewBase)
710               .addReg(Base, getKillRegState(KillOldBase))
711               .add(predOps(Pred, PredReg));
712 
713         // The following ADDS/SUBS becomes an update.
714         Base = NewBase;
715         KillOldBase = true;
716       }
717       if (BaseOpc == ARM::tADDrSPi) {
718         assert(Offset % 4 == 0 && "tADDrSPi offset is scaled by 4");
719         BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
720             .addReg(Base, getKillRegState(KillOldBase))
721             .addImm(Offset / 4)
722             .add(predOps(Pred, PredReg));
723       } else
724         BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
725             .add(t1CondCodeOp(true))
726             .addReg(Base, getKillRegState(KillOldBase))
727             .addImm(Offset)
728             .add(predOps(Pred, PredReg));
729     } else {
730       BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
731           .addReg(Base, getKillRegState(KillOldBase))
732           .addImm(Offset)
733           .add(predOps(Pred, PredReg))
734           .add(condCodeOp());
735     }
736     Base = NewBase;
737     BaseKill = true; // New base is always killed straight away.
738   }
739 
740   bool isDef = isLoadSingle(Opcode);
741 
742   // Get LS multiple opcode. Note that for Thumb1 this might be an opcode with
743   // base register writeback.
744   Opcode = getLoadStoreMultipleOpcode(Opcode, Mode);
745   if (!Opcode)
746     return nullptr;
747 
748   // Check if a Thumb1 LDM/STM merge is safe. This is the case if:
749   // - There is no writeback (LDM of base register),
750   // - the base register is killed by the merged instruction,
751   // - or it's safe to overwrite the condition flags, i.e. to insert a SUBS
752   //   to reset the base register.
753   // Otherwise, don't merge.
754   // It's safe to return here since the code to materialize a new base register
755   // above is also conditional on SafeToClobberCPSR.
756   if (isThumb1 && !SafeToClobberCPSR && Writeback && !BaseKill)
757     return nullptr;
758 
759   MachineInstrBuilder MIB;
760 
761   if (Writeback) {
762     assert(isThumb1 && "expected Writeback only inThumb1");
763     if (Opcode == ARM::tLDMIA) {
764       assert(!(ContainsReg(Regs, Base)) && "Thumb1 can't LDM ! with Base in Regs");
765       // Update tLDMIA with writeback if necessary.
766       Opcode = ARM::tLDMIA_UPD;
767     }
768 
769     MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode));
770 
771     // Thumb1: we might need to set base writeback when building the MI.
772     MIB.addReg(Base, getDefRegState(true))
773        .addReg(Base, getKillRegState(BaseKill));
774 
775     // The base isn't dead after a merged instruction with writeback.
776     // Insert a sub instruction after the newly formed instruction to reset.
777     if (!BaseKill)
778       UpdateBaseRegUses(MBB, InsertBefore, DL, Base, NumRegs, Pred, PredReg);
779 
780   } else {
781     // No writeback, simply build the MachineInstr.
782     MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode));
783     MIB.addReg(Base, getKillRegState(BaseKill));
784   }
785 
786   MIB.addImm(Pred).addReg(PredReg);
787 
788   for (const std::pair<unsigned, bool> &R : Regs)
789     MIB.addReg(R.first, getDefRegState(isDef) | getKillRegState(R.second));
790 
791   return MIB.getInstr();
792 }
793 
794 MachineInstr *ARMLoadStoreOpt::CreateLoadStoreDouble(
795     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
796     int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
797     ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
798     ArrayRef<std::pair<unsigned, bool>> Regs) const {
799   bool IsLoad = isi32Load(Opcode);
800   assert((IsLoad || isi32Store(Opcode)) && "Must have integer load or store");
801   unsigned LoadStoreOpcode = IsLoad ? ARM::t2LDRDi8 : ARM::t2STRDi8;
802 
803   assert(Regs.size() == 2);
804   MachineInstrBuilder MIB = BuildMI(MBB, InsertBefore, DL,
805                                     TII->get(LoadStoreOpcode));
806   if (IsLoad) {
807     MIB.addReg(Regs[0].first, RegState::Define)
808        .addReg(Regs[1].first, RegState::Define);
809   } else {
810     MIB.addReg(Regs[0].first, getKillRegState(Regs[0].second))
811        .addReg(Regs[1].first, getKillRegState(Regs[1].second));
812   }
813   MIB.addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
814   return MIB.getInstr();
815 }
816 
817 /// Call MergeOps and update MemOps and merges accordingly on success.
818 MachineInstr *ARMLoadStoreOpt::MergeOpsUpdate(const MergeCandidate &Cand) {
819   const MachineInstr *First = Cand.Instrs.front();
820   unsigned Opcode = First->getOpcode();
821   bool IsLoad = isLoadSingle(Opcode);
822   SmallVector<std::pair<unsigned, bool>, 8> Regs;
823   SmallVector<unsigned, 4> ImpDefs;
824   DenseSet<unsigned> KilledRegs;
825   DenseSet<unsigned> UsedRegs;
826   // Determine list of registers and list of implicit super-register defs.
827   for (const MachineInstr *MI : Cand.Instrs) {
828     const MachineOperand &MO = getLoadStoreRegOp(*MI);
829     unsigned Reg = MO.getReg();
830     bool IsKill = MO.isKill();
831     if (IsKill)
832       KilledRegs.insert(Reg);
833     Regs.push_back(std::make_pair(Reg, IsKill));
834     UsedRegs.insert(Reg);
835 
836     if (IsLoad) {
837       // Collect any implicit defs of super-registers, after merging we can't
838       // be sure anymore that we properly preserved these live ranges and must
839       // removed these implicit operands.
840       for (const MachineOperand &MO : MI->implicit_operands()) {
841         if (!MO.isReg() || !MO.isDef() || MO.isDead())
842           continue;
843         assert(MO.isImplicit());
844         unsigned DefReg = MO.getReg();
845 
846         if (is_contained(ImpDefs, DefReg))
847           continue;
848         // We can ignore cases where the super-reg is read and written.
849         if (MI->readsRegister(DefReg))
850           continue;
851         ImpDefs.push_back(DefReg);
852       }
853     }
854   }
855 
856   // Attempt the merge.
857   typedef MachineBasicBlock::iterator iterator;
858   MachineInstr *LatestMI = Cand.Instrs[Cand.LatestMIIdx];
859   iterator InsertBefore = std::next(iterator(LatestMI));
860   MachineBasicBlock &MBB = *LatestMI->getParent();
861   unsigned Offset = getMemoryOpOffset(*First);
862   unsigned Base = getLoadStoreBaseOp(*First).getReg();
863   bool BaseKill = LatestMI->killsRegister(Base);
864   unsigned PredReg = 0;
865   ARMCC::CondCodes Pred = getInstrPredicate(*First, PredReg);
866   DebugLoc DL = First->getDebugLoc();
867   MachineInstr *Merged = nullptr;
868   if (Cand.CanMergeToLSDouble)
869     Merged = CreateLoadStoreDouble(MBB, InsertBefore, Offset, Base, BaseKill,
870                                    Opcode, Pred, PredReg, DL, Regs);
871   if (!Merged && Cand.CanMergeToLSMulti)
872     Merged = CreateLoadStoreMulti(MBB, InsertBefore, Offset, Base, BaseKill,
873                                   Opcode, Pred, PredReg, DL, Regs);
874   if (!Merged)
875     return nullptr;
876 
877   // Determine earliest instruction that will get removed. We then keep an
878   // iterator just above it so the following erases don't invalidated it.
879   iterator EarliestI(Cand.Instrs[Cand.EarliestMIIdx]);
880   bool EarliestAtBegin = false;
881   if (EarliestI == MBB.begin()) {
882     EarliestAtBegin = true;
883   } else {
884     EarliestI = std::prev(EarliestI);
885   }
886 
887   // Remove instructions which have been merged.
888   for (MachineInstr *MI : Cand.Instrs)
889     MBB.erase(MI);
890 
891   // Determine range between the earliest removed instruction and the new one.
892   if (EarliestAtBegin)
893     EarliestI = MBB.begin();
894   else
895     EarliestI = std::next(EarliestI);
896   auto FixupRange = make_range(EarliestI, iterator(Merged));
897 
898   if (isLoadSingle(Opcode)) {
899     // If the previous loads defined a super-reg, then we have to mark earlier
900     // operands undef; Replicate the super-reg def on the merged instruction.
901     for (MachineInstr &MI : FixupRange) {
902       for (unsigned &ImpDefReg : ImpDefs) {
903         for (MachineOperand &MO : MI.implicit_operands()) {
904           if (!MO.isReg() || MO.getReg() != ImpDefReg)
905             continue;
906           if (MO.readsReg())
907             MO.setIsUndef();
908           else if (MO.isDef())
909             ImpDefReg = 0;
910         }
911       }
912     }
913 
914     MachineInstrBuilder MIB(*Merged->getParent()->getParent(), Merged);
915     for (unsigned ImpDef : ImpDefs)
916       MIB.addReg(ImpDef, RegState::ImplicitDefine);
917   } else {
918     // Remove kill flags: We are possibly storing the values later now.
919     assert(isi32Store(Opcode) || Opcode == ARM::VSTRS || Opcode == ARM::VSTRD);
920     for (MachineInstr &MI : FixupRange) {
921       for (MachineOperand &MO : MI.uses()) {
922         if (!MO.isReg() || !MO.isKill())
923           continue;
924         if (UsedRegs.count(MO.getReg()))
925           MO.setIsKill(false);
926       }
927     }
928     assert(ImpDefs.empty());
929   }
930 
931   return Merged;
932 }
933 
934 static bool isValidLSDoubleOffset(int Offset) {
935   unsigned Value = abs(Offset);
936   // t2LDRDi8/t2STRDi8 supports an 8 bit immediate which is internally
937   // multiplied by 4.
938   return (Value % 4) == 0 && Value < 1024;
939 }
940 
941 /// Return true for loads/stores that can be combined to a double/multi
942 /// operation without increasing the requirements for alignment.
943 static bool mayCombineMisaligned(const TargetSubtargetInfo &STI,
944                                  const MachineInstr &MI) {
945   // vldr/vstr trap on misaligned pointers anyway, forming vldm makes no
946   // difference.
947   unsigned Opcode = MI.getOpcode();
948   if (!isi32Load(Opcode) && !isi32Store(Opcode))
949     return true;
950 
951   // Stack pointer alignment is out of the programmers control so we can trust
952   // SP-relative loads/stores.
953   if (getLoadStoreBaseOp(MI).getReg() == ARM::SP &&
954       STI.getFrameLowering()->getTransientStackAlignment() >= 4)
955     return true;
956   return false;
957 }
958 
959 /// Find candidates for load/store multiple merge in list of MemOpQueueEntries.
960 void ARMLoadStoreOpt::FormCandidates(const MemOpQueue &MemOps) {
961   const MachineInstr *FirstMI = MemOps[0].MI;
962   unsigned Opcode = FirstMI->getOpcode();
963   bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);
964   unsigned Size = getLSMultipleTransferSize(FirstMI);
965 
966   unsigned SIndex = 0;
967   unsigned EIndex = MemOps.size();
968   do {
969     // Look at the first instruction.
970     const MachineInstr *MI = MemOps[SIndex].MI;
971     int Offset = MemOps[SIndex].Offset;
972     const MachineOperand &PMO = getLoadStoreRegOp(*MI);
973     unsigned PReg = PMO.getReg();
974     unsigned PRegNum = PMO.isUndef() ? UINT_MAX : TRI->getEncodingValue(PReg);
975     unsigned Latest = SIndex;
976     unsigned Earliest = SIndex;
977     unsigned Count = 1;
978     bool CanMergeToLSDouble =
979       STI->isThumb2() && isNotVFP && isValidLSDoubleOffset(Offset);
980     // ARM errata 602117: LDRD with base in list may result in incorrect base
981     // register when interrupted or faulted.
982     if (STI->isCortexM3() && isi32Load(Opcode) &&
983         PReg == getLoadStoreBaseOp(*MI).getReg())
984       CanMergeToLSDouble = false;
985 
986     bool CanMergeToLSMulti = true;
987     // On swift vldm/vstm starting with an odd register number as that needs
988     // more uops than single vldrs.
989     if (STI->hasSlowOddRegister() && !isNotVFP && (PRegNum % 2) == 1)
990       CanMergeToLSMulti = false;
991 
992     // LDRD/STRD do not allow SP/PC. LDM/STM do not support it or have it
993     // deprecated; LDM to PC is fine but cannot happen here.
994     if (PReg == ARM::SP || PReg == ARM::PC)
995       CanMergeToLSMulti = CanMergeToLSDouble = false;
996 
997     // Should we be conservative?
998     if (AssumeMisalignedLoadStores && !mayCombineMisaligned(*STI, *MI))
999       CanMergeToLSMulti = CanMergeToLSDouble = false;
1000 
1001     // Merge following instructions where possible.
1002     for (unsigned I = SIndex+1; I < EIndex; ++I, ++Count) {
1003       int NewOffset = MemOps[I].Offset;
1004       if (NewOffset != Offset + (int)Size)
1005         break;
1006       const MachineOperand &MO = getLoadStoreRegOp(*MemOps[I].MI);
1007       unsigned Reg = MO.getReg();
1008       if (Reg == ARM::SP || Reg == ARM::PC)
1009         break;
1010 
1011       // See if the current load/store may be part of a multi load/store.
1012       unsigned RegNum = MO.isUndef() ? UINT_MAX : TRI->getEncodingValue(Reg);
1013       bool PartOfLSMulti = CanMergeToLSMulti;
1014       if (PartOfLSMulti) {
1015         // Register numbers must be in ascending order.
1016         if (RegNum <= PRegNum)
1017           PartOfLSMulti = false;
1018         // For VFP / NEON load/store multiples, the registers must be
1019         // consecutive and within the limit on the number of registers per
1020         // instruction.
1021         else if (!isNotVFP && RegNum != PRegNum+1)
1022           PartOfLSMulti = false;
1023       }
1024       // See if the current load/store may be part of a double load/store.
1025       bool PartOfLSDouble = CanMergeToLSDouble && Count <= 1;
1026 
1027       if (!PartOfLSMulti && !PartOfLSDouble)
1028         break;
1029       CanMergeToLSMulti &= PartOfLSMulti;
1030       CanMergeToLSDouble &= PartOfLSDouble;
1031       // Track MemOp with latest and earliest position (Positions are
1032       // counted in reverse).
1033       unsigned Position = MemOps[I].Position;
1034       if (Position < MemOps[Latest].Position)
1035         Latest = I;
1036       else if (Position > MemOps[Earliest].Position)
1037         Earliest = I;
1038       // Prepare for next MemOp.
1039       Offset += Size;
1040       PRegNum = RegNum;
1041     }
1042 
1043     // Form a candidate from the Ops collected so far.
1044     MergeCandidate *Candidate = new(Allocator.Allocate()) MergeCandidate;
1045     for (unsigned C = SIndex, CE = SIndex + Count; C < CE; ++C)
1046       Candidate->Instrs.push_back(MemOps[C].MI);
1047     Candidate->LatestMIIdx = Latest - SIndex;
1048     Candidate->EarliestMIIdx = Earliest - SIndex;
1049     Candidate->InsertPos = MemOps[Latest].Position;
1050     if (Count == 1)
1051       CanMergeToLSMulti = CanMergeToLSDouble = false;
1052     Candidate->CanMergeToLSMulti = CanMergeToLSMulti;
1053     Candidate->CanMergeToLSDouble = CanMergeToLSDouble;
1054     Candidates.push_back(Candidate);
1055     // Continue after the chain.
1056     SIndex += Count;
1057   } while (SIndex < EIndex);
1058 }
1059 
1060 static unsigned getUpdatingLSMultipleOpcode(unsigned Opc,
1061                                             ARM_AM::AMSubMode Mode) {
1062   switch (Opc) {
1063   default: llvm_unreachable("Unhandled opcode!");
1064   case ARM::LDMIA:
1065   case ARM::LDMDA:
1066   case ARM::LDMDB:
1067   case ARM::LDMIB:
1068     switch (Mode) {
1069     default: llvm_unreachable("Unhandled submode!");
1070     case ARM_AM::ia: return ARM::LDMIA_UPD;
1071     case ARM_AM::ib: return ARM::LDMIB_UPD;
1072     case ARM_AM::da: return ARM::LDMDA_UPD;
1073     case ARM_AM::db: return ARM::LDMDB_UPD;
1074     }
1075   case ARM::STMIA:
1076   case ARM::STMDA:
1077   case ARM::STMDB:
1078   case ARM::STMIB:
1079     switch (Mode) {
1080     default: llvm_unreachable("Unhandled submode!");
1081     case ARM_AM::ia: return ARM::STMIA_UPD;
1082     case ARM_AM::ib: return ARM::STMIB_UPD;
1083     case ARM_AM::da: return ARM::STMDA_UPD;
1084     case ARM_AM::db: return ARM::STMDB_UPD;
1085     }
1086   case ARM::t2LDMIA:
1087   case ARM::t2LDMDB:
1088     switch (Mode) {
1089     default: llvm_unreachable("Unhandled submode!");
1090     case ARM_AM::ia: return ARM::t2LDMIA_UPD;
1091     case ARM_AM::db: return ARM::t2LDMDB_UPD;
1092     }
1093   case ARM::t2STMIA:
1094   case ARM::t2STMDB:
1095     switch (Mode) {
1096     default: llvm_unreachable("Unhandled submode!");
1097     case ARM_AM::ia: return ARM::t2STMIA_UPD;
1098     case ARM_AM::db: return ARM::t2STMDB_UPD;
1099     }
1100   case ARM::VLDMSIA:
1101     switch (Mode) {
1102     default: llvm_unreachable("Unhandled submode!");
1103     case ARM_AM::ia: return ARM::VLDMSIA_UPD;
1104     case ARM_AM::db: return ARM::VLDMSDB_UPD;
1105     }
1106   case ARM::VLDMDIA:
1107     switch (Mode) {
1108     default: llvm_unreachable("Unhandled submode!");
1109     case ARM_AM::ia: return ARM::VLDMDIA_UPD;
1110     case ARM_AM::db: return ARM::VLDMDDB_UPD;
1111     }
1112   case ARM::VSTMSIA:
1113     switch (Mode) {
1114     default: llvm_unreachable("Unhandled submode!");
1115     case ARM_AM::ia: return ARM::VSTMSIA_UPD;
1116     case ARM_AM::db: return ARM::VSTMSDB_UPD;
1117     }
1118   case ARM::VSTMDIA:
1119     switch (Mode) {
1120     default: llvm_unreachable("Unhandled submode!");
1121     case ARM_AM::ia: return ARM::VSTMDIA_UPD;
1122     case ARM_AM::db: return ARM::VSTMDDB_UPD;
1123     }
1124   }
1125 }
1126 
1127 /// Check if the given instruction increments or decrements a register and
1128 /// return the amount it is incremented/decremented. Returns 0 if the CPSR flags
1129 /// generated by the instruction are possibly read as well.
1130 static int isIncrementOrDecrement(const MachineInstr &MI, unsigned Reg,
1131                                   ARMCC::CondCodes Pred, unsigned PredReg) {
1132   bool CheckCPSRDef;
1133   int Scale;
1134   switch (MI.getOpcode()) {
1135   case ARM::tADDi8:  Scale =  4; CheckCPSRDef = true; break;
1136   case ARM::tSUBi8:  Scale = -4; CheckCPSRDef = true; break;
1137   case ARM::t2SUBri:
1138   case ARM::SUBri:   Scale = -1; CheckCPSRDef = true; break;
1139   case ARM::t2ADDri:
1140   case ARM::ADDri:   Scale =  1; CheckCPSRDef = true; break;
1141   case ARM::tADDspi: Scale =  4; CheckCPSRDef = false; break;
1142   case ARM::tSUBspi: Scale = -4; CheckCPSRDef = false; break;
1143   default: return 0;
1144   }
1145 
1146   unsigned MIPredReg;
1147   if (MI.getOperand(0).getReg() != Reg ||
1148       MI.getOperand(1).getReg() != Reg ||
1149       getInstrPredicate(MI, MIPredReg) != Pred ||
1150       MIPredReg != PredReg)
1151     return 0;
1152 
1153   if (CheckCPSRDef && definesCPSR(MI))
1154     return 0;
1155   return MI.getOperand(2).getImm() * Scale;
1156 }
1157 
1158 /// Searches for an increment or decrement of \p Reg before \p MBBI.
1159 static MachineBasicBlock::iterator
1160 findIncDecBefore(MachineBasicBlock::iterator MBBI, unsigned Reg,
1161                  ARMCC::CondCodes Pred, unsigned PredReg, int &Offset) {
1162   Offset = 0;
1163   MachineBasicBlock &MBB = *MBBI->getParent();
1164   MachineBasicBlock::iterator BeginMBBI = MBB.begin();
1165   MachineBasicBlock::iterator EndMBBI = MBB.end();
1166   if (MBBI == BeginMBBI)
1167     return EndMBBI;
1168 
1169   // Skip debug values.
1170   MachineBasicBlock::iterator PrevMBBI = std::prev(MBBI);
1171   while (PrevMBBI->isDebugValue() && PrevMBBI != BeginMBBI)
1172     --PrevMBBI;
1173 
1174   Offset = isIncrementOrDecrement(*PrevMBBI, Reg, Pred, PredReg);
1175   return Offset == 0 ? EndMBBI : PrevMBBI;
1176 }
1177 
1178 /// Searches for a increment or decrement of \p Reg after \p MBBI.
1179 static MachineBasicBlock::iterator
1180 findIncDecAfter(MachineBasicBlock::iterator MBBI, unsigned Reg,
1181                 ARMCC::CondCodes Pred, unsigned PredReg, int &Offset) {
1182   Offset = 0;
1183   MachineBasicBlock &MBB = *MBBI->getParent();
1184   MachineBasicBlock::iterator EndMBBI = MBB.end();
1185   MachineBasicBlock::iterator NextMBBI = std::next(MBBI);
1186   // Skip debug values.
1187   while (NextMBBI != EndMBBI && NextMBBI->isDebugValue())
1188     ++NextMBBI;
1189   if (NextMBBI == EndMBBI)
1190     return EndMBBI;
1191 
1192   Offset = isIncrementOrDecrement(*NextMBBI, Reg, Pred, PredReg);
1193   return Offset == 0 ? EndMBBI : NextMBBI;
1194 }
1195 
1196 /// Fold proceeding/trailing inc/dec of base register into the
1197 /// LDM/STM/VLDM{D|S}/VSTM{D|S} op when possible:
1198 ///
1199 /// stmia rn, <ra, rb, rc>
1200 /// rn := rn + 4 * 3;
1201 /// =>
1202 /// stmia rn!, <ra, rb, rc>
1203 ///
1204 /// rn := rn - 4 * 3;
1205 /// ldmia rn, <ra, rb, rc>
1206 /// =>
1207 /// ldmdb rn!, <ra, rb, rc>
1208 bool ARMLoadStoreOpt::MergeBaseUpdateLSMultiple(MachineInstr *MI) {
1209   // Thumb1 is already using updating loads/stores.
1210   if (isThumb1) return false;
1211 
1212   const MachineOperand &BaseOP = MI->getOperand(0);
1213   unsigned Base = BaseOP.getReg();
1214   bool BaseKill = BaseOP.isKill();
1215   unsigned PredReg = 0;
1216   ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
1217   unsigned Opcode = MI->getOpcode();
1218   DebugLoc DL = MI->getDebugLoc();
1219 
1220   // Can't use an updating ld/st if the base register is also a dest
1221   // register. e.g. ldmdb r0!, {r0, r1, r2}. The behavior is undefined.
1222   for (unsigned i = 2, e = MI->getNumOperands(); i != e; ++i)
1223     if (MI->getOperand(i).getReg() == Base)
1224       return false;
1225 
1226   int Bytes = getLSMultipleTransferSize(MI);
1227   MachineBasicBlock &MBB = *MI->getParent();
1228   MachineBasicBlock::iterator MBBI(MI);
1229   int Offset;
1230   MachineBasicBlock::iterator MergeInstr
1231     = findIncDecBefore(MBBI, Base, Pred, PredReg, Offset);
1232   ARM_AM::AMSubMode Mode = getLoadStoreMultipleSubMode(Opcode);
1233   if (Mode == ARM_AM::ia && Offset == -Bytes) {
1234     Mode = ARM_AM::db;
1235   } else if (Mode == ARM_AM::ib && Offset == -Bytes) {
1236     Mode = ARM_AM::da;
1237   } else {
1238     MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset);
1239     if (((Mode != ARM_AM::ia && Mode != ARM_AM::ib) || Offset != Bytes) &&
1240         ((Mode != ARM_AM::da && Mode != ARM_AM::db) || Offset != -Bytes)) {
1241 
1242       // We couldn't find an inc/dec to merge. But if the base is dead, we
1243       // can still change to a writeback form as that will save us 2 bytes
1244       // of code size. It can create WAW hazards though, so only do it if
1245       // we're minimizing code size.
1246       if (!MBB.getParent()->getFunction()->optForMinSize() || !BaseKill)
1247         return false;
1248 
1249       bool HighRegsUsed = false;
1250       for (unsigned i = 2, e = MI->getNumOperands(); i != e; ++i)
1251         if (MI->getOperand(i).getReg() >= ARM::R8) {
1252           HighRegsUsed = true;
1253           break;
1254         }
1255 
1256       if (!HighRegsUsed)
1257         MergeInstr = MBB.end();
1258       else
1259         return false;
1260     }
1261   }
1262   if (MergeInstr != MBB.end())
1263     MBB.erase(MergeInstr);
1264 
1265   unsigned NewOpc = getUpdatingLSMultipleOpcode(Opcode, Mode);
1266   MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
1267     .addReg(Base, getDefRegState(true)) // WB base register
1268     .addReg(Base, getKillRegState(BaseKill))
1269     .addImm(Pred).addReg(PredReg);
1270 
1271   // Transfer the rest of operands.
1272   for (unsigned OpNum = 3, e = MI->getNumOperands(); OpNum != e; ++OpNum)
1273     MIB.add(MI->getOperand(OpNum));
1274 
1275   // Transfer memoperands.
1276   MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1277 
1278   MBB.erase(MBBI);
1279   return true;
1280 }
1281 
1282 static unsigned getPreIndexedLoadStoreOpcode(unsigned Opc,
1283                                              ARM_AM::AddrOpc Mode) {
1284   switch (Opc) {
1285   case ARM::LDRi12:
1286     return ARM::LDR_PRE_IMM;
1287   case ARM::STRi12:
1288     return ARM::STR_PRE_IMM;
1289   case ARM::VLDRS:
1290     return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;
1291   case ARM::VLDRD:
1292     return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;
1293   case ARM::VSTRS:
1294     return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;
1295   case ARM::VSTRD:
1296     return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;
1297   case ARM::t2LDRi8:
1298   case ARM::t2LDRi12:
1299     return ARM::t2LDR_PRE;
1300   case ARM::t2STRi8:
1301   case ARM::t2STRi12:
1302     return ARM::t2STR_PRE;
1303   default: llvm_unreachable("Unhandled opcode!");
1304   }
1305 }
1306 
1307 static unsigned getPostIndexedLoadStoreOpcode(unsigned Opc,
1308                                               ARM_AM::AddrOpc Mode) {
1309   switch (Opc) {
1310   case ARM::LDRi12:
1311     return ARM::LDR_POST_IMM;
1312   case ARM::STRi12:
1313     return ARM::STR_POST_IMM;
1314   case ARM::VLDRS:
1315     return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;
1316   case ARM::VLDRD:
1317     return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;
1318   case ARM::VSTRS:
1319     return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;
1320   case ARM::VSTRD:
1321     return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;
1322   case ARM::t2LDRi8:
1323   case ARM::t2LDRi12:
1324     return ARM::t2LDR_POST;
1325   case ARM::t2STRi8:
1326   case ARM::t2STRi12:
1327     return ARM::t2STR_POST;
1328   default: llvm_unreachable("Unhandled opcode!");
1329   }
1330 }
1331 
1332 /// Fold proceeding/trailing inc/dec of base register into the
1333 /// LDR/STR/FLD{D|S}/FST{D|S} op when possible:
1334 bool ARMLoadStoreOpt::MergeBaseUpdateLoadStore(MachineInstr *MI) {
1335   // Thumb1 doesn't have updating LDR/STR.
1336   // FIXME: Use LDM/STM with single register instead.
1337   if (isThumb1) return false;
1338 
1339   unsigned Base = getLoadStoreBaseOp(*MI).getReg();
1340   bool BaseKill = getLoadStoreBaseOp(*MI).isKill();
1341   unsigned Opcode = MI->getOpcode();
1342   DebugLoc DL = MI->getDebugLoc();
1343   bool isAM5 = (Opcode == ARM::VLDRD || Opcode == ARM::VLDRS ||
1344                 Opcode == ARM::VSTRD || Opcode == ARM::VSTRS);
1345   bool isAM2 = (Opcode == ARM::LDRi12 || Opcode == ARM::STRi12);
1346   if (isi32Load(Opcode) || isi32Store(Opcode))
1347     if (MI->getOperand(2).getImm() != 0)
1348       return false;
1349   if (isAM5 && ARM_AM::getAM5Offset(MI->getOperand(2).getImm()) != 0)
1350     return false;
1351 
1352   // Can't do the merge if the destination register is the same as the would-be
1353   // writeback register.
1354   if (MI->getOperand(0).getReg() == Base)
1355     return false;
1356 
1357   unsigned PredReg = 0;
1358   ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
1359   int Bytes = getLSMultipleTransferSize(MI);
1360   MachineBasicBlock &MBB = *MI->getParent();
1361   MachineBasicBlock::iterator MBBI(MI);
1362   int Offset;
1363   MachineBasicBlock::iterator MergeInstr
1364     = findIncDecBefore(MBBI, Base, Pred, PredReg, Offset);
1365   unsigned NewOpc;
1366   if (!isAM5 && Offset == Bytes) {
1367     NewOpc = getPreIndexedLoadStoreOpcode(Opcode, ARM_AM::add);
1368   } else if (Offset == -Bytes) {
1369     NewOpc = getPreIndexedLoadStoreOpcode(Opcode, ARM_AM::sub);
1370   } else {
1371     MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset);
1372     if (Offset == Bytes) {
1373       NewOpc = getPostIndexedLoadStoreOpcode(Opcode, ARM_AM::add);
1374     } else if (!isAM5 && Offset == -Bytes) {
1375       NewOpc = getPostIndexedLoadStoreOpcode(Opcode, ARM_AM::sub);
1376     } else
1377       return false;
1378   }
1379   MBB.erase(MergeInstr);
1380 
1381   ARM_AM::AddrOpc AddSub = Offset < 0 ? ARM_AM::sub : ARM_AM::add;
1382 
1383   bool isLd = isLoadSingle(Opcode);
1384   if (isAM5) {
1385     // VLDM[SD]_UPD, VSTM[SD]_UPD
1386     // (There are no base-updating versions of VLDR/VSTR instructions, but the
1387     // updating load/store-multiple instructions can be used with only one
1388     // register.)
1389     MachineOperand &MO = MI->getOperand(0);
1390     BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
1391       .addReg(Base, getDefRegState(true)) // WB base register
1392       .addReg(Base, getKillRegState(isLd ? BaseKill : false))
1393       .addImm(Pred).addReg(PredReg)
1394       .addReg(MO.getReg(), (isLd ? getDefRegState(true) :
1395                             getKillRegState(MO.isKill())));
1396   } else if (isLd) {
1397     if (isAM2) {
1398       // LDR_PRE, LDR_POST
1399       if (NewOpc == ARM::LDR_PRE_IMM || NewOpc == ARM::LDRB_PRE_IMM) {
1400         BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
1401           .addReg(Base, RegState::Define)
1402           .addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
1403       } else {
1404         int Imm = ARM_AM::getAM2Opc(AddSub, Bytes, ARM_AM::no_shift);
1405         BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
1406             .addReg(Base, RegState::Define)
1407             .addReg(Base)
1408             .addReg(0)
1409             .addImm(Imm)
1410             .add(predOps(Pred, PredReg));
1411       }
1412     } else {
1413       // t2LDR_PRE, t2LDR_POST
1414       BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
1415           .addReg(Base, RegState::Define)
1416           .addReg(Base)
1417           .addImm(Offset)
1418           .add(predOps(Pred, PredReg));
1419     }
1420   } else {
1421     MachineOperand &MO = MI->getOperand(0);
1422     // FIXME: post-indexed stores use am2offset_imm, which still encodes
1423     // the vestigal zero-reg offset register. When that's fixed, this clause
1424     // can be removed entirely.
1425     if (isAM2 && NewOpc == ARM::STR_POST_IMM) {
1426       int Imm = ARM_AM::getAM2Opc(AddSub, Bytes, ARM_AM::no_shift);
1427       // STR_PRE, STR_POST
1428       BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base)
1429           .addReg(MO.getReg(), getKillRegState(MO.isKill()))
1430           .addReg(Base)
1431           .addReg(0)
1432           .addImm(Imm)
1433           .add(predOps(Pred, PredReg));
1434     } else {
1435       // t2STR_PRE, t2STR_POST
1436       BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base)
1437           .addReg(MO.getReg(), getKillRegState(MO.isKill()))
1438           .addReg(Base)
1439           .addImm(Offset)
1440           .add(predOps(Pred, PredReg));
1441     }
1442   }
1443   MBB.erase(MBBI);
1444 
1445   return true;
1446 }
1447 
1448 bool ARMLoadStoreOpt::MergeBaseUpdateLSDouble(MachineInstr &MI) const {
1449   unsigned Opcode = MI.getOpcode();
1450   assert((Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8) &&
1451          "Must have t2STRDi8 or t2LDRDi8");
1452   if (MI.getOperand(3).getImm() != 0)
1453     return false;
1454 
1455   // Behaviour for writeback is undefined if base register is the same as one
1456   // of the others.
1457   const MachineOperand &BaseOp = MI.getOperand(2);
1458   unsigned Base = BaseOp.getReg();
1459   const MachineOperand &Reg0Op = MI.getOperand(0);
1460   const MachineOperand &Reg1Op = MI.getOperand(1);
1461   if (Reg0Op.getReg() == Base || Reg1Op.getReg() == Base)
1462     return false;
1463 
1464   unsigned PredReg;
1465   ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
1466   MachineBasicBlock::iterator MBBI(MI);
1467   MachineBasicBlock &MBB = *MI.getParent();
1468   int Offset;
1469   MachineBasicBlock::iterator MergeInstr = findIncDecBefore(MBBI, Base, Pred,
1470                                                             PredReg, Offset);
1471   unsigned NewOpc;
1472   if (Offset == 8 || Offset == -8) {
1473     NewOpc = Opcode == ARM::t2LDRDi8 ? ARM::t2LDRD_PRE : ARM::t2STRD_PRE;
1474   } else {
1475     MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset);
1476     if (Offset == 8 || Offset == -8) {
1477       NewOpc = Opcode == ARM::t2LDRDi8 ? ARM::t2LDRD_POST : ARM::t2STRD_POST;
1478     } else
1479       return false;
1480   }
1481   MBB.erase(MergeInstr);
1482 
1483   DebugLoc DL = MI.getDebugLoc();
1484   MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
1485   if (NewOpc == ARM::t2LDRD_PRE || NewOpc == ARM::t2LDRD_POST) {
1486     MIB.add(Reg0Op).add(Reg1Op).addReg(BaseOp.getReg(), RegState::Define);
1487   } else {
1488     assert(NewOpc == ARM::t2STRD_PRE || NewOpc == ARM::t2STRD_POST);
1489     MIB.addReg(BaseOp.getReg(), RegState::Define).add(Reg0Op).add(Reg1Op);
1490   }
1491   MIB.addReg(BaseOp.getReg(), RegState::Kill)
1492      .addImm(Offset).addImm(Pred).addReg(PredReg);
1493   assert(TII->get(Opcode).getNumOperands() == 6 &&
1494          TII->get(NewOpc).getNumOperands() == 7 &&
1495          "Unexpected number of operands in Opcode specification.");
1496 
1497   // Transfer implicit operands.
1498   for (const MachineOperand &MO : MI.implicit_operands())
1499     MIB.add(MO);
1500   MIB->setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
1501 
1502   MBB.erase(MBBI);
1503   return true;
1504 }
1505 
1506 /// Returns true if instruction is a memory operation that this pass is capable
1507 /// of operating on.
1508 static bool isMemoryOp(const MachineInstr &MI) {
1509   unsigned Opcode = MI.getOpcode();
1510   switch (Opcode) {
1511   case ARM::VLDRS:
1512   case ARM::VSTRS:
1513   case ARM::VLDRD:
1514   case ARM::VSTRD:
1515   case ARM::LDRi12:
1516   case ARM::STRi12:
1517   case ARM::tLDRi:
1518   case ARM::tSTRi:
1519   case ARM::tLDRspi:
1520   case ARM::tSTRspi:
1521   case ARM::t2LDRi8:
1522   case ARM::t2LDRi12:
1523   case ARM::t2STRi8:
1524   case ARM::t2STRi12:
1525     break;
1526   default:
1527     return false;
1528   }
1529   if (!MI.getOperand(1).isReg())
1530     return false;
1531 
1532   // When no memory operands are present, conservatively assume unaligned,
1533   // volatile, unfoldable.
1534   if (!MI.hasOneMemOperand())
1535     return false;
1536 
1537   const MachineMemOperand &MMO = **MI.memoperands_begin();
1538 
1539   // Don't touch volatile memory accesses - we may be changing their order.
1540   if (MMO.isVolatile())
1541     return false;
1542 
1543   // Unaligned ldr/str is emulated by some kernels, but unaligned ldm/stm is
1544   // not.
1545   if (MMO.getAlignment() < 4)
1546     return false;
1547 
1548   // str <undef> could probably be eliminated entirely, but for now we just want
1549   // to avoid making a mess of it.
1550   // FIXME: Use str <undef> as a wildcard to enable better stm folding.
1551   if (MI.getOperand(0).isReg() && MI.getOperand(0).isUndef())
1552     return false;
1553 
1554   // Likewise don't mess with references to undefined addresses.
1555   if (MI.getOperand(1).isUndef())
1556     return false;
1557 
1558   return true;
1559 }
1560 
1561 static void InsertLDR_STR(MachineBasicBlock &MBB,
1562                           MachineBasicBlock::iterator &MBBI, int Offset,
1563                           bool isDef, const DebugLoc &DL, unsigned NewOpc,
1564                           unsigned Reg, bool RegDeadKill, bool RegUndef,
1565                           unsigned BaseReg, bool BaseKill, bool BaseUndef,
1566                           bool OffKill, bool OffUndef, ARMCC::CondCodes Pred,
1567                           unsigned PredReg, const TargetInstrInfo *TII,
1568                           bool isT2) {
1569   if (isDef) {
1570     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(),
1571                                       TII->get(NewOpc))
1572       .addReg(Reg, getDefRegState(true) | getDeadRegState(RegDeadKill))
1573       .addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef));
1574     MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
1575   } else {
1576     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(),
1577                                       TII->get(NewOpc))
1578       .addReg(Reg, getKillRegState(RegDeadKill) | getUndefRegState(RegUndef))
1579       .addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef));
1580     MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
1581   }
1582 }
1583 
1584 bool ARMLoadStoreOpt::FixInvalidRegPairOp(MachineBasicBlock &MBB,
1585                                           MachineBasicBlock::iterator &MBBI) {
1586   MachineInstr *MI = &*MBBI;
1587   unsigned Opcode = MI->getOpcode();
1588   if (Opcode != ARM::LDRD && Opcode != ARM::STRD && Opcode != ARM::t2LDRDi8)
1589     return false;
1590 
1591   const MachineOperand &BaseOp = MI->getOperand(2);
1592   unsigned BaseReg = BaseOp.getReg();
1593   unsigned EvenReg = MI->getOperand(0).getReg();
1594   unsigned OddReg  = MI->getOperand(1).getReg();
1595   unsigned EvenRegNum = TRI->getDwarfRegNum(EvenReg, false);
1596   unsigned OddRegNum  = TRI->getDwarfRegNum(OddReg, false);
1597 
1598   // ARM errata 602117: LDRD with base in list may result in incorrect base
1599   // register when interrupted or faulted.
1600   bool Errata602117 = EvenReg == BaseReg &&
1601     (Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8) && STI->isCortexM3();
1602   // ARM LDRD/STRD needs consecutive registers.
1603   bool NonConsecutiveRegs = (Opcode == ARM::LDRD || Opcode == ARM::STRD) &&
1604     (EvenRegNum % 2 != 0 || EvenRegNum + 1 != OddRegNum);
1605 
1606   if (!Errata602117 && !NonConsecutiveRegs)
1607     return false;
1608 
1609   bool isT2 = Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8;
1610   bool isLd = Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8;
1611   bool EvenDeadKill = isLd ?
1612     MI->getOperand(0).isDead() : MI->getOperand(0).isKill();
1613   bool EvenUndef = MI->getOperand(0).isUndef();
1614   bool OddDeadKill  = isLd ?
1615     MI->getOperand(1).isDead() : MI->getOperand(1).isKill();
1616   bool OddUndef = MI->getOperand(1).isUndef();
1617   bool BaseKill = BaseOp.isKill();
1618   bool BaseUndef = BaseOp.isUndef();
1619   bool OffKill = isT2 ? false : MI->getOperand(3).isKill();
1620   bool OffUndef = isT2 ? false : MI->getOperand(3).isUndef();
1621   int OffImm = getMemoryOpOffset(*MI);
1622   unsigned PredReg = 0;
1623   ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
1624 
1625   if (OddRegNum > EvenRegNum && OffImm == 0) {
1626     // Ascending register numbers and no offset. It's safe to change it to a
1627     // ldm or stm.
1628     unsigned NewOpc = (isLd)
1629       ? (isT2 ? ARM::t2LDMIA : ARM::LDMIA)
1630       : (isT2 ? ARM::t2STMIA : ARM::STMIA);
1631     if (isLd) {
1632       BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc))
1633         .addReg(BaseReg, getKillRegState(BaseKill))
1634         .addImm(Pred).addReg(PredReg)
1635         .addReg(EvenReg, getDefRegState(isLd) | getDeadRegState(EvenDeadKill))
1636         .addReg(OddReg,  getDefRegState(isLd) | getDeadRegState(OddDeadKill));
1637       ++NumLDRD2LDM;
1638     } else {
1639       BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc))
1640         .addReg(BaseReg, getKillRegState(BaseKill))
1641         .addImm(Pred).addReg(PredReg)
1642         .addReg(EvenReg,
1643                 getKillRegState(EvenDeadKill) | getUndefRegState(EvenUndef))
1644         .addReg(OddReg,
1645                 getKillRegState(OddDeadKill)  | getUndefRegState(OddUndef));
1646       ++NumSTRD2STM;
1647     }
1648   } else {
1649     // Split into two instructions.
1650     unsigned NewOpc = (isLd)
1651       ? (isT2 ? (OffImm < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12)
1652       : (isT2 ? (OffImm < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12);
1653     // Be extra careful for thumb2. t2LDRi8 can't reference a zero offset,
1654     // so adjust and use t2LDRi12 here for that.
1655     unsigned NewOpc2 = (isLd)
1656       ? (isT2 ? (OffImm+4 < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12)
1657       : (isT2 ? (OffImm+4 < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12);
1658     DebugLoc dl = MBBI->getDebugLoc();
1659     // If this is a load and base register is killed, it may have been
1660     // re-defed by the load, make sure the first load does not clobber it.
1661     if (isLd &&
1662         (BaseKill || OffKill) &&
1663         (TRI->regsOverlap(EvenReg, BaseReg))) {
1664       assert(!TRI->regsOverlap(OddReg, BaseReg));
1665       InsertLDR_STR(MBB, MBBI, OffImm+4, isLd, dl, NewOpc2,
1666                     OddReg, OddDeadKill, false,
1667                     BaseReg, false, BaseUndef, false, OffUndef,
1668                     Pred, PredReg, TII, isT2);
1669       InsertLDR_STR(MBB, MBBI, OffImm, isLd, dl, NewOpc,
1670                     EvenReg, EvenDeadKill, false,
1671                     BaseReg, BaseKill, BaseUndef, OffKill, OffUndef,
1672                     Pred, PredReg, TII, isT2);
1673     } else {
1674       if (OddReg == EvenReg && EvenDeadKill) {
1675         // If the two source operands are the same, the kill marker is
1676         // probably on the first one. e.g.
1677         // t2STRDi8 %R5<kill>, %R5, %R9<kill>, 0, 14, %reg0
1678         EvenDeadKill = false;
1679         OddDeadKill = true;
1680       }
1681       // Never kill the base register in the first instruction.
1682       if (EvenReg == BaseReg)
1683         EvenDeadKill = false;
1684       InsertLDR_STR(MBB, MBBI, OffImm, isLd, dl, NewOpc,
1685                     EvenReg, EvenDeadKill, EvenUndef,
1686                     BaseReg, false, BaseUndef, false, OffUndef,
1687                     Pred, PredReg, TII, isT2);
1688       InsertLDR_STR(MBB, MBBI, OffImm+4, isLd, dl, NewOpc2,
1689                     OddReg, OddDeadKill, OddUndef,
1690                     BaseReg, BaseKill, BaseUndef, OffKill, OffUndef,
1691                     Pred, PredReg, TII, isT2);
1692     }
1693     if (isLd)
1694       ++NumLDRD2LDR;
1695     else
1696       ++NumSTRD2STR;
1697   }
1698 
1699   MBBI = MBB.erase(MBBI);
1700   return true;
1701 }
1702 
1703 /// An optimization pass to turn multiple LDR / STR ops of the same base and
1704 /// incrementing offset into LDM / STM ops.
1705 bool ARMLoadStoreOpt::LoadStoreMultipleOpti(MachineBasicBlock &MBB) {
1706   MemOpQueue MemOps;
1707   unsigned CurrBase = 0;
1708   unsigned CurrOpc = ~0u;
1709   ARMCC::CondCodes CurrPred = ARMCC::AL;
1710   unsigned Position = 0;
1711   assert(Candidates.size() == 0);
1712   assert(MergeBaseCandidates.size() == 0);
1713   LiveRegsValid = false;
1714 
1715   for (MachineBasicBlock::iterator I = MBB.end(), MBBI; I != MBB.begin();
1716        I = MBBI) {
1717     // The instruction in front of the iterator is the one we look at.
1718     MBBI = std::prev(I);
1719     if (FixInvalidRegPairOp(MBB, MBBI))
1720       continue;
1721     ++Position;
1722 
1723     if (isMemoryOp(*MBBI)) {
1724       unsigned Opcode = MBBI->getOpcode();
1725       const MachineOperand &MO = MBBI->getOperand(0);
1726       unsigned Reg = MO.getReg();
1727       unsigned Base = getLoadStoreBaseOp(*MBBI).getReg();
1728       unsigned PredReg = 0;
1729       ARMCC::CondCodes Pred = getInstrPredicate(*MBBI, PredReg);
1730       int Offset = getMemoryOpOffset(*MBBI);
1731       if (CurrBase == 0) {
1732         // Start of a new chain.
1733         CurrBase = Base;
1734         CurrOpc  = Opcode;
1735         CurrPred = Pred;
1736         MemOps.push_back(MemOpQueueEntry(*MBBI, Offset, Position));
1737         continue;
1738       }
1739       // Note: No need to match PredReg in the next if.
1740       if (CurrOpc == Opcode && CurrBase == Base && CurrPred == Pred) {
1741         // Watch out for:
1742         //   r4 := ldr [r0, #8]
1743         //   r4 := ldr [r0, #4]
1744         // or
1745         //   r0 := ldr [r0]
1746         // If a load overrides the base register or a register loaded by
1747         // another load in our chain, we cannot take this instruction.
1748         bool Overlap = false;
1749         if (isLoadSingle(Opcode)) {
1750           Overlap = (Base == Reg);
1751           if (!Overlap) {
1752             for (const MemOpQueueEntry &E : MemOps) {
1753               if (TRI->regsOverlap(Reg, E.MI->getOperand(0).getReg())) {
1754                 Overlap = true;
1755                 break;
1756               }
1757             }
1758           }
1759         }
1760 
1761         if (!Overlap) {
1762           // Check offset and sort memory operation into the current chain.
1763           if (Offset > MemOps.back().Offset) {
1764             MemOps.push_back(MemOpQueueEntry(*MBBI, Offset, Position));
1765             continue;
1766           } else {
1767             MemOpQueue::iterator MI, ME;
1768             for (MI = MemOps.begin(), ME = MemOps.end(); MI != ME; ++MI) {
1769               if (Offset < MI->Offset) {
1770                 // Found a place to insert.
1771                 break;
1772               }
1773               if (Offset == MI->Offset) {
1774                 // Collision, abort.
1775                 MI = ME;
1776                 break;
1777               }
1778             }
1779             if (MI != MemOps.end()) {
1780               MemOps.insert(MI, MemOpQueueEntry(*MBBI, Offset, Position));
1781               continue;
1782             }
1783           }
1784         }
1785       }
1786 
1787       // Don't advance the iterator; The op will start a new chain next.
1788       MBBI = I;
1789       --Position;
1790       // Fallthrough to look into existing chain.
1791     } else if (MBBI->isDebugValue()) {
1792       continue;
1793     } else if (MBBI->getOpcode() == ARM::t2LDRDi8 ||
1794                MBBI->getOpcode() == ARM::t2STRDi8) {
1795       // ARMPreAllocLoadStoreOpt has already formed some LDRD/STRD instructions
1796       // remember them because we may still be able to merge add/sub into them.
1797       MergeBaseCandidates.push_back(&*MBBI);
1798     }
1799 
1800 
1801     // If we are here then the chain is broken; Extract candidates for a merge.
1802     if (MemOps.size() > 0) {
1803       FormCandidates(MemOps);
1804       // Reset for the next chain.
1805       CurrBase = 0;
1806       CurrOpc = ~0u;
1807       CurrPred = ARMCC::AL;
1808       MemOps.clear();
1809     }
1810   }
1811   if (MemOps.size() > 0)
1812     FormCandidates(MemOps);
1813 
1814   // Sort candidates so they get processed from end to begin of the basic
1815   // block later; This is necessary for liveness calculation.
1816   auto LessThan = [](const MergeCandidate* M0, const MergeCandidate *M1) {
1817     return M0->InsertPos < M1->InsertPos;
1818   };
1819   std::sort(Candidates.begin(), Candidates.end(), LessThan);
1820 
1821   // Go through list of candidates and merge.
1822   bool Changed = false;
1823   for (const MergeCandidate *Candidate : Candidates) {
1824     if (Candidate->CanMergeToLSMulti || Candidate->CanMergeToLSDouble) {
1825       MachineInstr *Merged = MergeOpsUpdate(*Candidate);
1826       // Merge preceding/trailing base inc/dec into the merged op.
1827       if (Merged) {
1828         Changed = true;
1829         unsigned Opcode = Merged->getOpcode();
1830         if (Opcode == ARM::t2STRDi8 || Opcode == ARM::t2LDRDi8)
1831           MergeBaseUpdateLSDouble(*Merged);
1832         else
1833           MergeBaseUpdateLSMultiple(Merged);
1834       } else {
1835         for (MachineInstr *MI : Candidate->Instrs) {
1836           if (MergeBaseUpdateLoadStore(MI))
1837             Changed = true;
1838         }
1839       }
1840     } else {
1841       assert(Candidate->Instrs.size() == 1);
1842       if (MergeBaseUpdateLoadStore(Candidate->Instrs.front()))
1843         Changed = true;
1844     }
1845   }
1846   Candidates.clear();
1847   // Try to fold add/sub into the LDRD/STRD formed by ARMPreAllocLoadStoreOpt.
1848   for (MachineInstr *MI : MergeBaseCandidates)
1849     MergeBaseUpdateLSDouble(*MI);
1850   MergeBaseCandidates.clear();
1851 
1852   return Changed;
1853 }
1854 
1855 /// If this is a exit BB, try merging the return ops ("bx lr" and "mov pc, lr")
1856 /// into the preceding stack restore so it directly restore the value of LR
1857 /// into pc.
1858 ///   ldmfd sp!, {..., lr}
1859 ///   bx lr
1860 /// or
1861 ///   ldmfd sp!, {..., lr}
1862 ///   mov pc, lr
1863 /// =>
1864 ///   ldmfd sp!, {..., pc}
1865 bool ARMLoadStoreOpt::MergeReturnIntoLDM(MachineBasicBlock &MBB) {
1866   // Thumb1 LDM doesn't allow high registers.
1867   if (isThumb1) return false;
1868   if (MBB.empty()) return false;
1869 
1870   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
1871   if (MBBI != MBB.begin() && MBBI != MBB.end() &&
1872       (MBBI->getOpcode() == ARM::BX_RET ||
1873        MBBI->getOpcode() == ARM::tBX_RET ||
1874        MBBI->getOpcode() == ARM::MOVPCLR)) {
1875     MachineBasicBlock::iterator PrevI = std::prev(MBBI);
1876     // Ignore any DBG_VALUE instructions.
1877     while (PrevI->isDebugValue() && PrevI != MBB.begin())
1878       --PrevI;
1879     MachineInstr &PrevMI = *PrevI;
1880     unsigned Opcode = PrevMI.getOpcode();
1881     if (Opcode == ARM::LDMIA_UPD || Opcode == ARM::LDMDA_UPD ||
1882         Opcode == ARM::LDMDB_UPD || Opcode == ARM::LDMIB_UPD ||
1883         Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
1884       MachineOperand &MO = PrevMI.getOperand(PrevMI.getNumOperands() - 1);
1885       if (MO.getReg() != ARM::LR)
1886         return false;
1887       unsigned NewOpc = (isThumb2 ? ARM::t2LDMIA_RET : ARM::LDMIA_RET);
1888       assert(((isThumb2 && Opcode == ARM::t2LDMIA_UPD) ||
1889               Opcode == ARM::LDMIA_UPD) && "Unsupported multiple load-return!");
1890       PrevMI.setDesc(TII->get(NewOpc));
1891       MO.setReg(ARM::PC);
1892       PrevMI.copyImplicitOps(*MBB.getParent(), *MBBI);
1893       MBB.erase(MBBI);
1894       return true;
1895     }
1896   }
1897   return false;
1898 }
1899 
1900 bool ARMLoadStoreOpt::CombineMovBx(MachineBasicBlock &MBB) {
1901   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1902   if (MBBI == MBB.begin() || MBBI == MBB.end() ||
1903       MBBI->getOpcode() != ARM::tBX_RET)
1904     return false;
1905 
1906   MachineBasicBlock::iterator Prev = MBBI;
1907   --Prev;
1908   if (Prev->getOpcode() != ARM::tMOVr || !Prev->definesRegister(ARM::LR))
1909     return false;
1910 
1911   for (auto Use : Prev->uses())
1912     if (Use.isKill()) {
1913       BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(ARM::tBX))
1914           .addReg(Use.getReg(), RegState::Kill)
1915           .add(predOps(ARMCC::AL))
1916           .copyImplicitOps(*MBBI);
1917       MBB.erase(MBBI);
1918       MBB.erase(Prev);
1919       return true;
1920     }
1921 
1922   llvm_unreachable("tMOVr doesn't kill a reg before tBX_RET?");
1923 }
1924 
1925 bool ARMLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
1926   if (skipFunction(*Fn.getFunction()))
1927     return false;
1928 
1929   MF = &Fn;
1930   STI = &static_cast<const ARMSubtarget &>(Fn.getSubtarget());
1931   TL = STI->getTargetLowering();
1932   AFI = Fn.getInfo<ARMFunctionInfo>();
1933   TII = STI->getInstrInfo();
1934   TRI = STI->getRegisterInfo();
1935 
1936   RegClassInfoValid = false;
1937   isThumb2 = AFI->isThumb2Function();
1938   isThumb1 = AFI->isThumbFunction() && !isThumb2;
1939 
1940   bool Modified = false;
1941   for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
1942        ++MFI) {
1943     MachineBasicBlock &MBB = *MFI;
1944     Modified |= LoadStoreMultipleOpti(MBB);
1945     if (STI->hasV5TOps())
1946       Modified |= MergeReturnIntoLDM(MBB);
1947     if (isThumb1)
1948       Modified |= CombineMovBx(MBB);
1949   }
1950 
1951   Allocator.DestroyAll();
1952   return Modified;
1953 }
1954 
1955 #define ARM_PREALLOC_LOAD_STORE_OPT_NAME                                       \
1956   "ARM pre- register allocation load / store optimization pass"
1957 
1958 namespace {
1959   /// Pre- register allocation pass that move load / stores from consecutive
1960   /// locations close to make it more likely they will be combined later.
1961   struct ARMPreAllocLoadStoreOpt : public MachineFunctionPass{
1962     static char ID;
1963     ARMPreAllocLoadStoreOpt() : MachineFunctionPass(ID) {}
1964 
1965     const DataLayout *TD;
1966     const TargetInstrInfo *TII;
1967     const TargetRegisterInfo *TRI;
1968     const ARMSubtarget *STI;
1969     MachineRegisterInfo *MRI;
1970     MachineFunction *MF;
1971 
1972     bool runOnMachineFunction(MachineFunction &Fn) override;
1973 
1974     StringRef getPassName() const override {
1975       return ARM_PREALLOC_LOAD_STORE_OPT_NAME;
1976     }
1977 
1978   private:
1979     bool CanFormLdStDWord(MachineInstr *Op0, MachineInstr *Op1, DebugLoc &dl,
1980                           unsigned &NewOpc, unsigned &EvenReg,
1981                           unsigned &OddReg, unsigned &BaseReg,
1982                           int &Offset,
1983                           unsigned &PredReg, ARMCC::CondCodes &Pred,
1984                           bool &isT2);
1985     bool RescheduleOps(MachineBasicBlock *MBB,
1986                        SmallVectorImpl<MachineInstr *> &Ops,
1987                        unsigned Base, bool isLd,
1988                        DenseMap<MachineInstr*, unsigned> &MI2LocMap);
1989     bool RescheduleLoadStoreInstrs(MachineBasicBlock *MBB);
1990   };
1991   char ARMPreAllocLoadStoreOpt::ID = 0;
1992 }
1993 
1994 INITIALIZE_PASS(ARMPreAllocLoadStoreOpt, "arm-prera-ldst-opt",
1995                 ARM_PREALLOC_LOAD_STORE_OPT_NAME, false, false)
1996 
1997 bool ARMPreAllocLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
1998   if (AssumeMisalignedLoadStores || skipFunction(*Fn.getFunction()))
1999     return false;
2000 
2001   TD = &Fn.getDataLayout();
2002   STI = &static_cast<const ARMSubtarget &>(Fn.getSubtarget());
2003   TII = STI->getInstrInfo();
2004   TRI = STI->getRegisterInfo();
2005   MRI = &Fn.getRegInfo();
2006   MF  = &Fn;
2007 
2008   bool Modified = false;
2009   for (MachineBasicBlock &MFI : Fn)
2010     Modified |= RescheduleLoadStoreInstrs(&MFI);
2011 
2012   return Modified;
2013 }
2014 
2015 static bool IsSafeAndProfitableToMove(bool isLd, unsigned Base,
2016                                       MachineBasicBlock::iterator I,
2017                                       MachineBasicBlock::iterator E,
2018                                       SmallPtrSetImpl<MachineInstr*> &MemOps,
2019                                       SmallSet<unsigned, 4> &MemRegs,
2020                                       const TargetRegisterInfo *TRI) {
2021   // Are there stores / loads / calls between them?
2022   // FIXME: This is overly conservative. We should make use of alias information
2023   // some day.
2024   SmallSet<unsigned, 4> AddedRegPressure;
2025   while (++I != E) {
2026     if (I->isDebugValue() || MemOps.count(&*I))
2027       continue;
2028     if (I->isCall() || I->isTerminator() || I->hasUnmodeledSideEffects())
2029       return false;
2030     if (isLd && I->mayStore())
2031       return false;
2032     if (!isLd) {
2033       if (I->mayLoad())
2034         return false;
2035       // It's not safe to move the first 'str' down.
2036       // str r1, [r0]
2037       // strh r5, [r0]
2038       // str r4, [r0, #+4]
2039       if (I->mayStore())
2040         return false;
2041     }
2042     for (unsigned j = 0, NumOps = I->getNumOperands(); j != NumOps; ++j) {
2043       MachineOperand &MO = I->getOperand(j);
2044       if (!MO.isReg())
2045         continue;
2046       unsigned Reg = MO.getReg();
2047       if (MO.isDef() && TRI->regsOverlap(Reg, Base))
2048         return false;
2049       if (Reg != Base && !MemRegs.count(Reg))
2050         AddedRegPressure.insert(Reg);
2051     }
2052   }
2053 
2054   // Estimate register pressure increase due to the transformation.
2055   if (MemRegs.size() <= 4)
2056     // Ok if we are moving small number of instructions.
2057     return true;
2058   return AddedRegPressure.size() <= MemRegs.size() * 2;
2059 }
2060 
2061 bool
2062 ARMPreAllocLoadStoreOpt::CanFormLdStDWord(MachineInstr *Op0, MachineInstr *Op1,
2063                                           DebugLoc &dl, unsigned &NewOpc,
2064                                           unsigned &FirstReg,
2065                                           unsigned &SecondReg,
2066                                           unsigned &BaseReg, int &Offset,
2067                                           unsigned &PredReg,
2068                                           ARMCC::CondCodes &Pred,
2069                                           bool &isT2) {
2070   // Make sure we're allowed to generate LDRD/STRD.
2071   if (!STI->hasV5TEOps())
2072     return false;
2073 
2074   // FIXME: VLDRS / VSTRS -> VLDRD / VSTRD
2075   unsigned Scale = 1;
2076   unsigned Opcode = Op0->getOpcode();
2077   if (Opcode == ARM::LDRi12) {
2078     NewOpc = ARM::LDRD;
2079   } else if (Opcode == ARM::STRi12) {
2080     NewOpc = ARM::STRD;
2081   } else if (Opcode == ARM::t2LDRi8 || Opcode == ARM::t2LDRi12) {
2082     NewOpc = ARM::t2LDRDi8;
2083     Scale = 4;
2084     isT2 = true;
2085   } else if (Opcode == ARM::t2STRi8 || Opcode == ARM::t2STRi12) {
2086     NewOpc = ARM::t2STRDi8;
2087     Scale = 4;
2088     isT2 = true;
2089   } else {
2090     return false;
2091   }
2092 
2093   // Make sure the base address satisfies i64 ld / st alignment requirement.
2094   // At the moment, we ignore the memoryoperand's value.
2095   // If we want to use AliasAnalysis, we should check it accordingly.
2096   if (!Op0->hasOneMemOperand() ||
2097       (*Op0->memoperands_begin())->isVolatile())
2098     return false;
2099 
2100   unsigned Align = (*Op0->memoperands_begin())->getAlignment();
2101   const Function *Func = MF->getFunction();
2102   unsigned ReqAlign = STI->hasV6Ops()
2103     ? TD->getABITypeAlignment(Type::getInt64Ty(Func->getContext()))
2104     : 8;  // Pre-v6 need 8-byte align
2105   if (Align < ReqAlign)
2106     return false;
2107 
2108   // Then make sure the immediate offset fits.
2109   int OffImm = getMemoryOpOffset(*Op0);
2110   if (isT2) {
2111     int Limit = (1 << 8) * Scale;
2112     if (OffImm >= Limit || (OffImm <= -Limit) || (OffImm & (Scale-1)))
2113       return false;
2114     Offset = OffImm;
2115   } else {
2116     ARM_AM::AddrOpc AddSub = ARM_AM::add;
2117     if (OffImm < 0) {
2118       AddSub = ARM_AM::sub;
2119       OffImm = - OffImm;
2120     }
2121     int Limit = (1 << 8) * Scale;
2122     if (OffImm >= Limit || (OffImm & (Scale-1)))
2123       return false;
2124     Offset = ARM_AM::getAM3Opc(AddSub, OffImm);
2125   }
2126   FirstReg = Op0->getOperand(0).getReg();
2127   SecondReg = Op1->getOperand(0).getReg();
2128   if (FirstReg == SecondReg)
2129     return false;
2130   BaseReg = Op0->getOperand(1).getReg();
2131   Pred = getInstrPredicate(*Op0, PredReg);
2132   dl = Op0->getDebugLoc();
2133   return true;
2134 }
2135 
2136 bool ARMPreAllocLoadStoreOpt::RescheduleOps(MachineBasicBlock *MBB,
2137                                  SmallVectorImpl<MachineInstr *> &Ops,
2138                                  unsigned Base, bool isLd,
2139                                  DenseMap<MachineInstr*, unsigned> &MI2LocMap) {
2140   bool RetVal = false;
2141 
2142   // Sort by offset (in reverse order).
2143   std::sort(Ops.begin(), Ops.end(),
2144             [](const MachineInstr *LHS, const MachineInstr *RHS) {
2145               int LOffset = getMemoryOpOffset(*LHS);
2146               int ROffset = getMemoryOpOffset(*RHS);
2147               assert(LHS == RHS || LOffset != ROffset);
2148               return LOffset > ROffset;
2149             });
2150 
2151   // The loads / stores of the same base are in order. Scan them from first to
2152   // last and check for the following:
2153   // 1. Any def of base.
2154   // 2. Any gaps.
2155   while (Ops.size() > 1) {
2156     unsigned FirstLoc = ~0U;
2157     unsigned LastLoc = 0;
2158     MachineInstr *FirstOp = nullptr;
2159     MachineInstr *LastOp = nullptr;
2160     int LastOffset = 0;
2161     unsigned LastOpcode = 0;
2162     unsigned LastBytes = 0;
2163     unsigned NumMove = 0;
2164     for (int i = Ops.size() - 1; i >= 0; --i) {
2165       MachineInstr *Op = Ops[i];
2166       unsigned Loc = MI2LocMap[Op];
2167       if (Loc <= FirstLoc) {
2168         FirstLoc = Loc;
2169         FirstOp = Op;
2170       }
2171       if (Loc >= LastLoc) {
2172         LastLoc = Loc;
2173         LastOp = Op;
2174       }
2175 
2176       unsigned LSMOpcode
2177         = getLoadStoreMultipleOpcode(Op->getOpcode(), ARM_AM::ia);
2178       if (LastOpcode && LSMOpcode != LastOpcode)
2179         break;
2180 
2181       int Offset = getMemoryOpOffset(*Op);
2182       unsigned Bytes = getLSMultipleTransferSize(Op);
2183       if (LastBytes) {
2184         if (Bytes != LastBytes || Offset != (LastOffset + (int)Bytes))
2185           break;
2186       }
2187       LastOffset = Offset;
2188       LastBytes = Bytes;
2189       LastOpcode = LSMOpcode;
2190       if (++NumMove == 8) // FIXME: Tune this limit.
2191         break;
2192     }
2193 
2194     if (NumMove <= 1)
2195       Ops.pop_back();
2196     else {
2197       SmallPtrSet<MachineInstr*, 4> MemOps;
2198       SmallSet<unsigned, 4> MemRegs;
2199       for (int i = NumMove-1; i >= 0; --i) {
2200         MemOps.insert(Ops[i]);
2201         MemRegs.insert(Ops[i]->getOperand(0).getReg());
2202       }
2203 
2204       // Be conservative, if the instructions are too far apart, don't
2205       // move them. We want to limit the increase of register pressure.
2206       bool DoMove = (LastLoc - FirstLoc) <= NumMove*4; // FIXME: Tune this.
2207       if (DoMove)
2208         DoMove = IsSafeAndProfitableToMove(isLd, Base, FirstOp, LastOp,
2209                                            MemOps, MemRegs, TRI);
2210       if (!DoMove) {
2211         for (unsigned i = 0; i != NumMove; ++i)
2212           Ops.pop_back();
2213       } else {
2214         // This is the new location for the loads / stores.
2215         MachineBasicBlock::iterator InsertPos = isLd ? FirstOp : LastOp;
2216         while (InsertPos != MBB->end() &&
2217                (MemOps.count(&*InsertPos) || InsertPos->isDebugValue()))
2218           ++InsertPos;
2219 
2220         // If we are moving a pair of loads / stores, see if it makes sense
2221         // to try to allocate a pair of registers that can form register pairs.
2222         MachineInstr *Op0 = Ops.back();
2223         MachineInstr *Op1 = Ops[Ops.size()-2];
2224         unsigned FirstReg = 0, SecondReg = 0;
2225         unsigned BaseReg = 0, PredReg = 0;
2226         ARMCC::CondCodes Pred = ARMCC::AL;
2227         bool isT2 = false;
2228         unsigned NewOpc = 0;
2229         int Offset = 0;
2230         DebugLoc dl;
2231         if (NumMove == 2 && CanFormLdStDWord(Op0, Op1, dl, NewOpc,
2232                                              FirstReg, SecondReg, BaseReg,
2233                                              Offset, PredReg, Pred, isT2)) {
2234           Ops.pop_back();
2235           Ops.pop_back();
2236 
2237           const MCInstrDesc &MCID = TII->get(NewOpc);
2238           const TargetRegisterClass *TRC = TII->getRegClass(MCID, 0, TRI, *MF);
2239           MRI->constrainRegClass(FirstReg, TRC);
2240           MRI->constrainRegClass(SecondReg, TRC);
2241 
2242           // Form the pair instruction.
2243           if (isLd) {
2244             MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)
2245               .addReg(FirstReg, RegState::Define)
2246               .addReg(SecondReg, RegState::Define)
2247               .addReg(BaseReg);
2248             // FIXME: We're converting from LDRi12 to an insn that still
2249             // uses addrmode2, so we need an explicit offset reg. It should
2250             // always by reg0 since we're transforming LDRi12s.
2251             if (!isT2)
2252               MIB.addReg(0);
2253             MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
2254             MIB.setMemRefs(Op0->mergeMemRefsWith(*Op1));
2255             DEBUG(dbgs() << "Formed " << *MIB << "\n");
2256             ++NumLDRDFormed;
2257           } else {
2258             MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)
2259               .addReg(FirstReg)
2260               .addReg(SecondReg)
2261               .addReg(BaseReg);
2262             // FIXME: We're converting from LDRi12 to an insn that still
2263             // uses addrmode2, so we need an explicit offset reg. It should
2264             // always by reg0 since we're transforming STRi12s.
2265             if (!isT2)
2266               MIB.addReg(0);
2267             MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
2268             MIB.setMemRefs(Op0->mergeMemRefsWith(*Op1));
2269             DEBUG(dbgs() << "Formed " << *MIB << "\n");
2270             ++NumSTRDFormed;
2271           }
2272           MBB->erase(Op0);
2273           MBB->erase(Op1);
2274 
2275           if (!isT2) {
2276             // Add register allocation hints to form register pairs.
2277             MRI->setRegAllocationHint(FirstReg, ARMRI::RegPairEven, SecondReg);
2278             MRI->setRegAllocationHint(SecondReg,  ARMRI::RegPairOdd, FirstReg);
2279           }
2280         } else {
2281           for (unsigned i = 0; i != NumMove; ++i) {
2282             MachineInstr *Op = Ops.back();
2283             Ops.pop_back();
2284             MBB->splice(InsertPos, MBB, Op);
2285           }
2286         }
2287 
2288         NumLdStMoved += NumMove;
2289         RetVal = true;
2290       }
2291     }
2292   }
2293 
2294   return RetVal;
2295 }
2296 
2297 bool
2298 ARMPreAllocLoadStoreOpt::RescheduleLoadStoreInstrs(MachineBasicBlock *MBB) {
2299   bool RetVal = false;
2300 
2301   DenseMap<MachineInstr*, unsigned> MI2LocMap;
2302   DenseMap<unsigned, SmallVector<MachineInstr*, 4> > Base2LdsMap;
2303   DenseMap<unsigned, SmallVector<MachineInstr*, 4> > Base2StsMap;
2304   SmallVector<unsigned, 4> LdBases;
2305   SmallVector<unsigned, 4> StBases;
2306 
2307   unsigned Loc = 0;
2308   MachineBasicBlock::iterator MBBI = MBB->begin();
2309   MachineBasicBlock::iterator E = MBB->end();
2310   while (MBBI != E) {
2311     for (; MBBI != E; ++MBBI) {
2312       MachineInstr &MI = *MBBI;
2313       if (MI.isCall() || MI.isTerminator()) {
2314         // Stop at barriers.
2315         ++MBBI;
2316         break;
2317       }
2318 
2319       if (!MI.isDebugValue())
2320         MI2LocMap[&MI] = ++Loc;
2321 
2322       if (!isMemoryOp(MI))
2323         continue;
2324       unsigned PredReg = 0;
2325       if (getInstrPredicate(MI, PredReg) != ARMCC::AL)
2326         continue;
2327 
2328       int Opc = MI.getOpcode();
2329       bool isLd = isLoadSingle(Opc);
2330       unsigned Base = MI.getOperand(1).getReg();
2331       int Offset = getMemoryOpOffset(MI);
2332 
2333       bool StopHere = false;
2334       if (isLd) {
2335         DenseMap<unsigned, SmallVector<MachineInstr*, 4> >::iterator BI =
2336           Base2LdsMap.find(Base);
2337         if (BI != Base2LdsMap.end()) {
2338           for (unsigned i = 0, e = BI->second.size(); i != e; ++i) {
2339             if (Offset == getMemoryOpOffset(*BI->second[i])) {
2340               StopHere = true;
2341               break;
2342             }
2343           }
2344           if (!StopHere)
2345             BI->second.push_back(&MI);
2346         } else {
2347           Base2LdsMap[Base].push_back(&MI);
2348           LdBases.push_back(Base);
2349         }
2350       } else {
2351         DenseMap<unsigned, SmallVector<MachineInstr*, 4> >::iterator BI =
2352           Base2StsMap.find(Base);
2353         if (BI != Base2StsMap.end()) {
2354           for (unsigned i = 0, e = BI->second.size(); i != e; ++i) {
2355             if (Offset == getMemoryOpOffset(*BI->second[i])) {
2356               StopHere = true;
2357               break;
2358             }
2359           }
2360           if (!StopHere)
2361             BI->second.push_back(&MI);
2362         } else {
2363           Base2StsMap[Base].push_back(&MI);
2364           StBases.push_back(Base);
2365         }
2366       }
2367 
2368       if (StopHere) {
2369         // Found a duplicate (a base+offset combination that's seen earlier).
2370         // Backtrack.
2371         --Loc;
2372         break;
2373       }
2374     }
2375 
2376     // Re-schedule loads.
2377     for (unsigned i = 0, e = LdBases.size(); i != e; ++i) {
2378       unsigned Base = LdBases[i];
2379       SmallVectorImpl<MachineInstr *> &Lds = Base2LdsMap[Base];
2380       if (Lds.size() > 1)
2381         RetVal |= RescheduleOps(MBB, Lds, Base, true, MI2LocMap);
2382     }
2383 
2384     // Re-schedule stores.
2385     for (unsigned i = 0, e = StBases.size(); i != e; ++i) {
2386       unsigned Base = StBases[i];
2387       SmallVectorImpl<MachineInstr *> &Sts = Base2StsMap[Base];
2388       if (Sts.size() > 1)
2389         RetVal |= RescheduleOps(MBB, Sts, Base, false, MI2LocMap);
2390     }
2391 
2392     if (MBBI != E) {
2393       Base2LdsMap.clear();
2394       Base2StsMap.clear();
2395       LdBases.clear();
2396       StBases.clear();
2397     }
2398   }
2399 
2400   return RetVal;
2401 }
2402 
2403 
2404 /// Returns an instance of the load / store optimization pass.
2405 FunctionPass *llvm::createARMLoadStoreOptimizationPass(bool PreAlloc) {
2406   if (PreAlloc)
2407     return new ARMPreAllocLoadStoreOpt();
2408   return new ARMLoadStoreOpt();
2409 }
2410