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