ARMBaseInstrInfo.cpp revision 360784
1//===-- ARMBaseInstrInfo.cpp - ARM Instruction Information ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the Base ARM implementation of the TargetInstrInfo class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "ARMBaseInstrInfo.h"
14#include "ARMBaseRegisterInfo.h"
15#include "ARMConstantPoolValue.h"
16#include "ARMFeatures.h"
17#include "ARMHazardRecognizer.h"
18#include "ARMMachineFunctionInfo.h"
19#include "ARMSubtarget.h"
20#include "MCTargetDesc/ARMAddressingModes.h"
21#include "MCTargetDesc/ARMBaseInfo.h"
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/SmallSet.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/Triple.h"
27#include "llvm/CodeGen/LiveVariables.h"
28#include "llvm/CodeGen/MachineBasicBlock.h"
29#include "llvm/CodeGen/MachineConstantPool.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
31#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineInstr.h"
33#include "llvm/CodeGen/MachineInstrBuilder.h"
34#include "llvm/CodeGen/MachineMemOperand.h"
35#include "llvm/CodeGen/MachineOperand.h"
36#include "llvm/CodeGen/MachineRegisterInfo.h"
37#include "llvm/CodeGen/ScoreboardHazardRecognizer.h"
38#include "llvm/CodeGen/SelectionDAGNodes.h"
39#include "llvm/CodeGen/TargetInstrInfo.h"
40#include "llvm/CodeGen/TargetRegisterInfo.h"
41#include "llvm/CodeGen/TargetSchedule.h"
42#include "llvm/IR/Attributes.h"
43#include "llvm/IR/Constants.h"
44#include "llvm/IR/DebugLoc.h"
45#include "llvm/IR/Function.h"
46#include "llvm/IR/GlobalValue.h"
47#include "llvm/MC/MCAsmInfo.h"
48#include "llvm/MC/MCInstrDesc.h"
49#include "llvm/MC/MCInstrItineraries.h"
50#include "llvm/Support/BranchProbability.h"
51#include "llvm/Support/Casting.h"
52#include "llvm/Support/CommandLine.h"
53#include "llvm/Support/Compiler.h"
54#include "llvm/Support/Debug.h"
55#include "llvm/Support/ErrorHandling.h"
56#include "llvm/Support/raw_ostream.h"
57#include "llvm/Target/TargetMachine.h"
58#include <algorithm>
59#include <cassert>
60#include <cstdint>
61#include <iterator>
62#include <new>
63#include <utility>
64#include <vector>
65
66using namespace llvm;
67
68#define DEBUG_TYPE "arm-instrinfo"
69
70#define GET_INSTRINFO_CTOR_DTOR
71#include "ARMGenInstrInfo.inc"
72
73static cl::opt<bool>
74EnableARM3Addr("enable-arm-3-addr-conv", cl::Hidden,
75               cl::desc("Enable ARM 2-addr to 3-addr conv"));
76
77/// ARM_MLxEntry - Record information about MLA / MLS instructions.
78struct ARM_MLxEntry {
79  uint16_t MLxOpc;     // MLA / MLS opcode
80  uint16_t MulOpc;     // Expanded multiplication opcode
81  uint16_t AddSubOpc;  // Expanded add / sub opcode
82  bool NegAcc;         // True if the acc is negated before the add / sub.
83  bool HasLane;        // True if instruction has an extra "lane" operand.
84};
85
86static const ARM_MLxEntry ARM_MLxTable[] = {
87  // MLxOpc,          MulOpc,           AddSubOpc,       NegAcc, HasLane
88  // fp scalar ops
89  { ARM::VMLAS,       ARM::VMULS,       ARM::VADDS,      false,  false },
90  { ARM::VMLSS,       ARM::VMULS,       ARM::VSUBS,      false,  false },
91  { ARM::VMLAD,       ARM::VMULD,       ARM::VADDD,      false,  false },
92  { ARM::VMLSD,       ARM::VMULD,       ARM::VSUBD,      false,  false },
93  { ARM::VNMLAS,      ARM::VNMULS,      ARM::VSUBS,      true,   false },
94  { ARM::VNMLSS,      ARM::VMULS,       ARM::VSUBS,      true,   false },
95  { ARM::VNMLAD,      ARM::VNMULD,      ARM::VSUBD,      true,   false },
96  { ARM::VNMLSD,      ARM::VMULD,       ARM::VSUBD,      true,   false },
97
98  // fp SIMD ops
99  { ARM::VMLAfd,      ARM::VMULfd,      ARM::VADDfd,     false,  false },
100  { ARM::VMLSfd,      ARM::VMULfd,      ARM::VSUBfd,     false,  false },
101  { ARM::VMLAfq,      ARM::VMULfq,      ARM::VADDfq,     false,  false },
102  { ARM::VMLSfq,      ARM::VMULfq,      ARM::VSUBfq,     false,  false },
103  { ARM::VMLAslfd,    ARM::VMULslfd,    ARM::VADDfd,     false,  true  },
104  { ARM::VMLSslfd,    ARM::VMULslfd,    ARM::VSUBfd,     false,  true  },
105  { ARM::VMLAslfq,    ARM::VMULslfq,    ARM::VADDfq,     false,  true  },
106  { ARM::VMLSslfq,    ARM::VMULslfq,    ARM::VSUBfq,     false,  true  },
107};
108
109ARMBaseInstrInfo::ARMBaseInstrInfo(const ARMSubtarget& STI)
110  : ARMGenInstrInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP),
111    Subtarget(STI) {
112  for (unsigned i = 0, e = array_lengthof(ARM_MLxTable); i != e; ++i) {
113    if (!MLxEntryMap.insert(std::make_pair(ARM_MLxTable[i].MLxOpc, i)).second)
114      llvm_unreachable("Duplicated entries?");
115    MLxHazardOpcodes.insert(ARM_MLxTable[i].AddSubOpc);
116    MLxHazardOpcodes.insert(ARM_MLxTable[i].MulOpc);
117  }
118}
119
120// Use a ScoreboardHazardRecognizer for prepass ARM scheduling. TargetInstrImpl
121// currently defaults to no prepass hazard recognizer.
122ScheduleHazardRecognizer *
123ARMBaseInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
124                                               const ScheduleDAG *DAG) const {
125  if (usePreRAHazardRecognizer()) {
126    const InstrItineraryData *II =
127        static_cast<const ARMSubtarget *>(STI)->getInstrItineraryData();
128    return new ScoreboardHazardRecognizer(II, DAG, "pre-RA-sched");
129  }
130  return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
131}
132
133ScheduleHazardRecognizer *ARMBaseInstrInfo::
134CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
135                                   const ScheduleDAG *DAG) const {
136  if (Subtarget.isThumb2() || Subtarget.hasVFP2Base())
137    return new ARMHazardRecognizer(II, DAG);
138  return TargetInstrInfo::CreateTargetPostRAHazardRecognizer(II, DAG);
139}
140
141MachineInstr *ARMBaseInstrInfo::convertToThreeAddress(
142    MachineFunction::iterator &MFI, MachineInstr &MI, LiveVariables *LV) const {
143  // FIXME: Thumb2 support.
144
145  if (!EnableARM3Addr)
146    return nullptr;
147
148  MachineFunction &MF = *MI.getParent()->getParent();
149  uint64_t TSFlags = MI.getDesc().TSFlags;
150  bool isPre = false;
151  switch ((TSFlags & ARMII::IndexModeMask) >> ARMII::IndexModeShift) {
152  default: return nullptr;
153  case ARMII::IndexModePre:
154    isPre = true;
155    break;
156  case ARMII::IndexModePost:
157    break;
158  }
159
160  // Try splitting an indexed load/store to an un-indexed one plus an add/sub
161  // operation.
162  unsigned MemOpc = getUnindexedOpcode(MI.getOpcode());
163  if (MemOpc == 0)
164    return nullptr;
165
166  MachineInstr *UpdateMI = nullptr;
167  MachineInstr *MemMI = nullptr;
168  unsigned AddrMode = (TSFlags & ARMII::AddrModeMask);
169  const MCInstrDesc &MCID = MI.getDesc();
170  unsigned NumOps = MCID.getNumOperands();
171  bool isLoad = !MI.mayStore();
172  const MachineOperand &WB = isLoad ? MI.getOperand(1) : MI.getOperand(0);
173  const MachineOperand &Base = MI.getOperand(2);
174  const MachineOperand &Offset = MI.getOperand(NumOps - 3);
175  Register WBReg = WB.getReg();
176  Register BaseReg = Base.getReg();
177  Register OffReg = Offset.getReg();
178  unsigned OffImm = MI.getOperand(NumOps - 2).getImm();
179  ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI.getOperand(NumOps - 1).getImm();
180  switch (AddrMode) {
181  default: llvm_unreachable("Unknown indexed op!");
182  case ARMII::AddrMode2: {
183    bool isSub = ARM_AM::getAM2Op(OffImm) == ARM_AM::sub;
184    unsigned Amt = ARM_AM::getAM2Offset(OffImm);
185    if (OffReg == 0) {
186      if (ARM_AM::getSOImmVal(Amt) == -1)
187        // Can't encode it in a so_imm operand. This transformation will
188        // add more than 1 instruction. Abandon!
189        return nullptr;
190      UpdateMI = BuildMI(MF, MI.getDebugLoc(),
191                         get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
192                     .addReg(BaseReg)
193                     .addImm(Amt)
194                     .add(predOps(Pred))
195                     .add(condCodeOp());
196    } else if (Amt != 0) {
197      ARM_AM::ShiftOpc ShOpc = ARM_AM::getAM2ShiftOpc(OffImm);
198      unsigned SOOpc = ARM_AM::getSORegOpc(ShOpc, Amt);
199      UpdateMI = BuildMI(MF, MI.getDebugLoc(),
200                         get(isSub ? ARM::SUBrsi : ARM::ADDrsi), WBReg)
201                     .addReg(BaseReg)
202                     .addReg(OffReg)
203                     .addReg(0)
204                     .addImm(SOOpc)
205                     .add(predOps(Pred))
206                     .add(condCodeOp());
207    } else
208      UpdateMI = BuildMI(MF, MI.getDebugLoc(),
209                         get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
210                     .addReg(BaseReg)
211                     .addReg(OffReg)
212                     .add(predOps(Pred))
213                     .add(condCodeOp());
214    break;
215  }
216  case ARMII::AddrMode3 : {
217    bool isSub = ARM_AM::getAM3Op(OffImm) == ARM_AM::sub;
218    unsigned Amt = ARM_AM::getAM3Offset(OffImm);
219    if (OffReg == 0)
220      // Immediate is 8-bits. It's guaranteed to fit in a so_imm operand.
221      UpdateMI = BuildMI(MF, MI.getDebugLoc(),
222                         get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
223                     .addReg(BaseReg)
224                     .addImm(Amt)
225                     .add(predOps(Pred))
226                     .add(condCodeOp());
227    else
228      UpdateMI = BuildMI(MF, MI.getDebugLoc(),
229                         get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
230                     .addReg(BaseReg)
231                     .addReg(OffReg)
232                     .add(predOps(Pred))
233                     .add(condCodeOp());
234    break;
235  }
236  }
237
238  std::vector<MachineInstr*> NewMIs;
239  if (isPre) {
240    if (isLoad)
241      MemMI =
242          BuildMI(MF, MI.getDebugLoc(), get(MemOpc), MI.getOperand(0).getReg())
243              .addReg(WBReg)
244              .addImm(0)
245              .addImm(Pred);
246    else
247      MemMI = BuildMI(MF, MI.getDebugLoc(), get(MemOpc))
248                  .addReg(MI.getOperand(1).getReg())
249                  .addReg(WBReg)
250                  .addReg(0)
251                  .addImm(0)
252                  .addImm(Pred);
253    NewMIs.push_back(MemMI);
254    NewMIs.push_back(UpdateMI);
255  } else {
256    if (isLoad)
257      MemMI =
258          BuildMI(MF, MI.getDebugLoc(), get(MemOpc), MI.getOperand(0).getReg())
259              .addReg(BaseReg)
260              .addImm(0)
261              .addImm(Pred);
262    else
263      MemMI = BuildMI(MF, MI.getDebugLoc(), get(MemOpc))
264                  .addReg(MI.getOperand(1).getReg())
265                  .addReg(BaseReg)
266                  .addReg(0)
267                  .addImm(0)
268                  .addImm(Pred);
269    if (WB.isDead())
270      UpdateMI->getOperand(0).setIsDead();
271    NewMIs.push_back(UpdateMI);
272    NewMIs.push_back(MemMI);
273  }
274
275  // Transfer LiveVariables states, kill / dead info.
276  if (LV) {
277    for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
278      MachineOperand &MO = MI.getOperand(i);
279      if (MO.isReg() && Register::isVirtualRegister(MO.getReg())) {
280        Register Reg = MO.getReg();
281
282        LiveVariables::VarInfo &VI = LV->getVarInfo(Reg);
283        if (MO.isDef()) {
284          MachineInstr *NewMI = (Reg == WBReg) ? UpdateMI : MemMI;
285          if (MO.isDead())
286            LV->addVirtualRegisterDead(Reg, *NewMI);
287        }
288        if (MO.isUse() && MO.isKill()) {
289          for (unsigned j = 0; j < 2; ++j) {
290            // Look at the two new MI's in reverse order.
291            MachineInstr *NewMI = NewMIs[j];
292            if (!NewMI->readsRegister(Reg))
293              continue;
294            LV->addVirtualRegisterKilled(Reg, *NewMI);
295            if (VI.removeKill(MI))
296              VI.Kills.push_back(NewMI);
297            break;
298          }
299        }
300      }
301    }
302  }
303
304  MachineBasicBlock::iterator MBBI = MI.getIterator();
305  MFI->insert(MBBI, NewMIs[1]);
306  MFI->insert(MBBI, NewMIs[0]);
307  return NewMIs[0];
308}
309
310// Branch analysis.
311bool ARMBaseInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
312                                     MachineBasicBlock *&TBB,
313                                     MachineBasicBlock *&FBB,
314                                     SmallVectorImpl<MachineOperand> &Cond,
315                                     bool AllowModify) const {
316  TBB = nullptr;
317  FBB = nullptr;
318
319  MachineBasicBlock::iterator I = MBB.end();
320  if (I == MBB.begin())
321    return false; // Empty blocks are easy.
322  --I;
323
324  // Walk backwards from the end of the basic block until the branch is
325  // analyzed or we give up.
326  while (isPredicated(*I) || I->isTerminator() || I->isDebugValue()) {
327    // Flag to be raised on unanalyzeable instructions. This is useful in cases
328    // where we want to clean up on the end of the basic block before we bail
329    // out.
330    bool CantAnalyze = false;
331
332    // Skip over DEBUG values and predicated nonterminators.
333    while (I->isDebugInstr() || !I->isTerminator()) {
334      if (I == MBB.begin())
335        return false;
336      --I;
337    }
338
339    if (isIndirectBranchOpcode(I->getOpcode()) ||
340        isJumpTableBranchOpcode(I->getOpcode())) {
341      // Indirect branches and jump tables can't be analyzed, but we still want
342      // to clean up any instructions at the tail of the basic block.
343      CantAnalyze = true;
344    } else if (isUncondBranchOpcode(I->getOpcode())) {
345      TBB = I->getOperand(0).getMBB();
346    } else if (isCondBranchOpcode(I->getOpcode())) {
347      // Bail out if we encounter multiple conditional branches.
348      if (!Cond.empty())
349        return true;
350
351      assert(!FBB && "FBB should have been null.");
352      FBB = TBB;
353      TBB = I->getOperand(0).getMBB();
354      Cond.push_back(I->getOperand(1));
355      Cond.push_back(I->getOperand(2));
356    } else if (I->isReturn()) {
357      // Returns can't be analyzed, but we should run cleanup.
358      CantAnalyze = !isPredicated(*I);
359    } else {
360      // We encountered other unrecognized terminator. Bail out immediately.
361      return true;
362    }
363
364    // Cleanup code - to be run for unpredicated unconditional branches and
365    //                returns.
366    if (!isPredicated(*I) &&
367          (isUncondBranchOpcode(I->getOpcode()) ||
368           isIndirectBranchOpcode(I->getOpcode()) ||
369           isJumpTableBranchOpcode(I->getOpcode()) ||
370           I->isReturn())) {
371      // Forget any previous condition branch information - it no longer applies.
372      Cond.clear();
373      FBB = nullptr;
374
375      // If we can modify the function, delete everything below this
376      // unconditional branch.
377      if (AllowModify) {
378        MachineBasicBlock::iterator DI = std::next(I);
379        while (DI != MBB.end()) {
380          MachineInstr &InstToDelete = *DI;
381          ++DI;
382          InstToDelete.eraseFromParent();
383        }
384      }
385    }
386
387    if (CantAnalyze)
388      return true;
389
390    if (I == MBB.begin())
391      return false;
392
393    --I;
394  }
395
396  // We made it past the terminators without bailing out - we must have
397  // analyzed this branch successfully.
398  return false;
399}
400
401unsigned ARMBaseInstrInfo::removeBranch(MachineBasicBlock &MBB,
402                                        int *BytesRemoved) const {
403  assert(!BytesRemoved && "code size not handled");
404
405  MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
406  if (I == MBB.end())
407    return 0;
408
409  if (!isUncondBranchOpcode(I->getOpcode()) &&
410      !isCondBranchOpcode(I->getOpcode()))
411    return 0;
412
413  // Remove the branch.
414  I->eraseFromParent();
415
416  I = MBB.end();
417
418  if (I == MBB.begin()) return 1;
419  --I;
420  if (!isCondBranchOpcode(I->getOpcode()))
421    return 1;
422
423  // Remove the branch.
424  I->eraseFromParent();
425  return 2;
426}
427
428unsigned ARMBaseInstrInfo::insertBranch(MachineBasicBlock &MBB,
429                                        MachineBasicBlock *TBB,
430                                        MachineBasicBlock *FBB,
431                                        ArrayRef<MachineOperand> Cond,
432                                        const DebugLoc &DL,
433                                        int *BytesAdded) const {
434  assert(!BytesAdded && "code size not handled");
435  ARMFunctionInfo *AFI = MBB.getParent()->getInfo<ARMFunctionInfo>();
436  int BOpc   = !AFI->isThumbFunction()
437    ? ARM::B : (AFI->isThumb2Function() ? ARM::t2B : ARM::tB);
438  int BccOpc = !AFI->isThumbFunction()
439    ? ARM::Bcc : (AFI->isThumb2Function() ? ARM::t2Bcc : ARM::tBcc);
440  bool isThumb = AFI->isThumbFunction() || AFI->isThumb2Function();
441
442  // Shouldn't be a fall through.
443  assert(TBB && "insertBranch must not be told to insert a fallthrough");
444  assert((Cond.size() == 2 || Cond.size() == 0) &&
445         "ARM branch conditions have two components!");
446
447  // For conditional branches, we use addOperand to preserve CPSR flags.
448
449  if (!FBB) {
450    if (Cond.empty()) { // Unconditional branch?
451      if (isThumb)
452        BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB).add(predOps(ARMCC::AL));
453      else
454        BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB);
455    } else
456      BuildMI(&MBB, DL, get(BccOpc))
457          .addMBB(TBB)
458          .addImm(Cond[0].getImm())
459          .add(Cond[1]);
460    return 1;
461  }
462
463  // Two-way conditional branch.
464  BuildMI(&MBB, DL, get(BccOpc))
465      .addMBB(TBB)
466      .addImm(Cond[0].getImm())
467      .add(Cond[1]);
468  if (isThumb)
469    BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB).add(predOps(ARMCC::AL));
470  else
471    BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB);
472  return 2;
473}
474
475bool ARMBaseInstrInfo::
476reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
477  ARMCC::CondCodes CC = (ARMCC::CondCodes)(int)Cond[0].getImm();
478  Cond[0].setImm(ARMCC::getOppositeCondition(CC));
479  return false;
480}
481
482bool ARMBaseInstrInfo::isPredicated(const MachineInstr &MI) const {
483  if (MI.isBundle()) {
484    MachineBasicBlock::const_instr_iterator I = MI.getIterator();
485    MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
486    while (++I != E && I->isInsideBundle()) {
487      int PIdx = I->findFirstPredOperandIdx();
488      if (PIdx != -1 && I->getOperand(PIdx).getImm() != ARMCC::AL)
489        return true;
490    }
491    return false;
492  }
493
494  int PIdx = MI.findFirstPredOperandIdx();
495  return PIdx != -1 && MI.getOperand(PIdx).getImm() != ARMCC::AL;
496}
497
498bool ARMBaseInstrInfo::PredicateInstruction(
499    MachineInstr &MI, ArrayRef<MachineOperand> Pred) const {
500  unsigned Opc = MI.getOpcode();
501  if (isUncondBranchOpcode(Opc)) {
502    MI.setDesc(get(getMatchingCondBranchOpcode(Opc)));
503    MachineInstrBuilder(*MI.getParent()->getParent(), MI)
504      .addImm(Pred[0].getImm())
505      .addReg(Pred[1].getReg());
506    return true;
507  }
508
509  int PIdx = MI.findFirstPredOperandIdx();
510  if (PIdx != -1) {
511    MachineOperand &PMO = MI.getOperand(PIdx);
512    PMO.setImm(Pred[0].getImm());
513    MI.getOperand(PIdx+1).setReg(Pred[1].getReg());
514    return true;
515  }
516  return false;
517}
518
519bool ARMBaseInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
520                                         ArrayRef<MachineOperand> Pred2) const {
521  if (Pred1.size() > 2 || Pred2.size() > 2)
522    return false;
523
524  ARMCC::CondCodes CC1 = (ARMCC::CondCodes)Pred1[0].getImm();
525  ARMCC::CondCodes CC2 = (ARMCC::CondCodes)Pred2[0].getImm();
526  if (CC1 == CC2)
527    return true;
528
529  switch (CC1) {
530  default:
531    return false;
532  case ARMCC::AL:
533    return true;
534  case ARMCC::HS:
535    return CC2 == ARMCC::HI;
536  case ARMCC::LS:
537    return CC2 == ARMCC::LO || CC2 == ARMCC::EQ;
538  case ARMCC::GE:
539    return CC2 == ARMCC::GT;
540  case ARMCC::LE:
541    return CC2 == ARMCC::LT;
542  }
543}
544
545bool ARMBaseInstrInfo::DefinesPredicate(
546    MachineInstr &MI, std::vector<MachineOperand> &Pred) const {
547  bool Found = false;
548  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
549    const MachineOperand &MO = MI.getOperand(i);
550    if ((MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) ||
551        (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR)) {
552      Pred.push_back(MO);
553      Found = true;
554    }
555  }
556
557  return Found;
558}
559
560bool ARMBaseInstrInfo::isCPSRDefined(const MachineInstr &MI) {
561  for (const auto &MO : MI.operands())
562    if (MO.isReg() && MO.getReg() == ARM::CPSR && MO.isDef() && !MO.isDead())
563      return true;
564  return false;
565}
566
567bool ARMBaseInstrInfo::isAddrMode3OpImm(const MachineInstr &MI,
568                                        unsigned Op) const {
569  const MachineOperand &Offset = MI.getOperand(Op + 1);
570  return Offset.getReg() != 0;
571}
572
573// Load with negative register offset requires additional 1cyc and +I unit
574// for Cortex A57
575bool ARMBaseInstrInfo::isAddrMode3OpMinusReg(const MachineInstr &MI,
576                                             unsigned Op) const {
577  const MachineOperand &Offset = MI.getOperand(Op + 1);
578  const MachineOperand &Opc = MI.getOperand(Op + 2);
579  assert(Opc.isImm());
580  assert(Offset.isReg());
581  int64_t OpcImm = Opc.getImm();
582
583  bool isSub = ARM_AM::getAM3Op(OpcImm) == ARM_AM::sub;
584  return (isSub && Offset.getReg() != 0);
585}
586
587bool ARMBaseInstrInfo::isLdstScaledReg(const MachineInstr &MI,
588                                       unsigned Op) const {
589  const MachineOperand &Opc = MI.getOperand(Op + 2);
590  unsigned OffImm = Opc.getImm();
591  return ARM_AM::getAM2ShiftOpc(OffImm) != ARM_AM::no_shift;
592}
593
594// Load, scaled register offset, not plus LSL2
595bool ARMBaseInstrInfo::isLdstScaledRegNotPlusLsl2(const MachineInstr &MI,
596                                                  unsigned Op) const {
597  const MachineOperand &Opc = MI.getOperand(Op + 2);
598  unsigned OffImm = Opc.getImm();
599
600  bool isAdd = ARM_AM::getAM2Op(OffImm) == ARM_AM::add;
601  unsigned Amt = ARM_AM::getAM2Offset(OffImm);
602  ARM_AM::ShiftOpc ShiftOpc = ARM_AM::getAM2ShiftOpc(OffImm);
603  if (ShiftOpc == ARM_AM::no_shift) return false; // not scaled
604  bool SimpleScaled = (isAdd && ShiftOpc == ARM_AM::lsl && Amt == 2);
605  return !SimpleScaled;
606}
607
608// Minus reg for ldstso addr mode
609bool ARMBaseInstrInfo::isLdstSoMinusReg(const MachineInstr &MI,
610                                        unsigned Op) const {
611  unsigned OffImm = MI.getOperand(Op + 2).getImm();
612  return ARM_AM::getAM2Op(OffImm) == ARM_AM::sub;
613}
614
615// Load, scaled register offset
616bool ARMBaseInstrInfo::isAm2ScaledReg(const MachineInstr &MI,
617                                      unsigned Op) const {
618  unsigned OffImm = MI.getOperand(Op + 2).getImm();
619  return ARM_AM::getAM2ShiftOpc(OffImm) != ARM_AM::no_shift;
620}
621
622static bool isEligibleForITBlock(const MachineInstr *MI) {
623  switch (MI->getOpcode()) {
624  default: return true;
625  case ARM::tADC:   // ADC (register) T1
626  case ARM::tADDi3: // ADD (immediate) T1
627  case ARM::tADDi8: // ADD (immediate) T2
628  case ARM::tADDrr: // ADD (register) T1
629  case ARM::tAND:   // AND (register) T1
630  case ARM::tASRri: // ASR (immediate) T1
631  case ARM::tASRrr: // ASR (register) T1
632  case ARM::tBIC:   // BIC (register) T1
633  case ARM::tEOR:   // EOR (register) T1
634  case ARM::tLSLri: // LSL (immediate) T1
635  case ARM::tLSLrr: // LSL (register) T1
636  case ARM::tLSRri: // LSR (immediate) T1
637  case ARM::tLSRrr: // LSR (register) T1
638  case ARM::tMUL:   // MUL T1
639  case ARM::tMVN:   // MVN (register) T1
640  case ARM::tORR:   // ORR (register) T1
641  case ARM::tROR:   // ROR (register) T1
642  case ARM::tRSB:   // RSB (immediate) T1
643  case ARM::tSBC:   // SBC (register) T1
644  case ARM::tSUBi3: // SUB (immediate) T1
645  case ARM::tSUBi8: // SUB (immediate) T2
646  case ARM::tSUBrr: // SUB (register) T1
647    return !ARMBaseInstrInfo::isCPSRDefined(*MI);
648  }
649}
650
651/// isPredicable - Return true if the specified instruction can be predicated.
652/// By default, this returns true for every instruction with a
653/// PredicateOperand.
654bool ARMBaseInstrInfo::isPredicable(const MachineInstr &MI) const {
655  if (!MI.isPredicable())
656    return false;
657
658  if (MI.isBundle())
659    return false;
660
661  if (!isEligibleForITBlock(&MI))
662    return false;
663
664  const ARMFunctionInfo *AFI =
665      MI.getParent()->getParent()->getInfo<ARMFunctionInfo>();
666
667  // Neon instructions in Thumb2 IT blocks are deprecated, see ARMARM.
668  // In their ARM encoding, they can't be encoded in a conditional form.
669  if ((MI.getDesc().TSFlags & ARMII::DomainMask) == ARMII::DomainNEON)
670    return false;
671
672  if (AFI->isThumb2Function()) {
673    if (getSubtarget().restrictIT())
674      return isV8EligibleForIT(&MI);
675  }
676
677  return true;
678}
679
680namespace llvm {
681
682template <> bool IsCPSRDead<MachineInstr>(const MachineInstr *MI) {
683  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
684    const MachineOperand &MO = MI->getOperand(i);
685    if (!MO.isReg() || MO.isUndef() || MO.isUse())
686      continue;
687    if (MO.getReg() != ARM::CPSR)
688      continue;
689    if (!MO.isDead())
690      return false;
691  }
692  // all definitions of CPSR are dead
693  return true;
694}
695
696} // end namespace llvm
697
698/// GetInstSize - Return the size of the specified MachineInstr.
699///
700unsigned ARMBaseInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
701  const MachineBasicBlock &MBB = *MI.getParent();
702  const MachineFunction *MF = MBB.getParent();
703  const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
704
705  const MCInstrDesc &MCID = MI.getDesc();
706  if (MCID.getSize())
707    return MCID.getSize();
708
709  switch (MI.getOpcode()) {
710  default:
711    // pseudo-instruction sizes are zero.
712    return 0;
713  case TargetOpcode::BUNDLE:
714    return getInstBundleLength(MI);
715  case ARM::MOVi16_ga_pcrel:
716  case ARM::MOVTi16_ga_pcrel:
717  case ARM::t2MOVi16_ga_pcrel:
718  case ARM::t2MOVTi16_ga_pcrel:
719    return 4;
720  case ARM::MOVi32imm:
721  case ARM::t2MOVi32imm:
722    return 8;
723  case ARM::CONSTPOOL_ENTRY:
724  case ARM::JUMPTABLE_INSTS:
725  case ARM::JUMPTABLE_ADDRS:
726  case ARM::JUMPTABLE_TBB:
727  case ARM::JUMPTABLE_TBH:
728    // If this machine instr is a constant pool entry, its size is recorded as
729    // operand #2.
730    return MI.getOperand(2).getImm();
731  case ARM::Int_eh_sjlj_longjmp:
732    return 16;
733  case ARM::tInt_eh_sjlj_longjmp:
734    return 10;
735  case ARM::tInt_WIN_eh_sjlj_longjmp:
736    return 12;
737  case ARM::Int_eh_sjlj_setjmp:
738  case ARM::Int_eh_sjlj_setjmp_nofp:
739    return 20;
740  case ARM::tInt_eh_sjlj_setjmp:
741  case ARM::t2Int_eh_sjlj_setjmp:
742  case ARM::t2Int_eh_sjlj_setjmp_nofp:
743    return 12;
744  case ARM::SPACE:
745    return MI.getOperand(1).getImm();
746  case ARM::INLINEASM:
747  case ARM::INLINEASM_BR: {
748    // If this machine instr is an inline asm, measure it.
749    unsigned Size = getInlineAsmLength(MI.getOperand(0).getSymbolName(), *MAI);
750    if (!MF->getInfo<ARMFunctionInfo>()->isThumbFunction())
751      Size = alignTo(Size, 4);
752    return Size;
753  }
754  }
755}
756
757unsigned ARMBaseInstrInfo::getInstBundleLength(const MachineInstr &MI) const {
758  unsigned Size = 0;
759  MachineBasicBlock::const_instr_iterator I = MI.getIterator();
760  MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
761  while (++I != E && I->isInsideBundle()) {
762    assert(!I->isBundle() && "No nested bundle!");
763    Size += getInstSizeInBytes(*I);
764  }
765  return Size;
766}
767
768void ARMBaseInstrInfo::copyFromCPSR(MachineBasicBlock &MBB,
769                                    MachineBasicBlock::iterator I,
770                                    unsigned DestReg, bool KillSrc,
771                                    const ARMSubtarget &Subtarget) const {
772  unsigned Opc = Subtarget.isThumb()
773                     ? (Subtarget.isMClass() ? ARM::t2MRS_M : ARM::t2MRS_AR)
774                     : ARM::MRS;
775
776  MachineInstrBuilder MIB =
777      BuildMI(MBB, I, I->getDebugLoc(), get(Opc), DestReg);
778
779  // There is only 1 A/R class MRS instruction, and it always refers to
780  // APSR. However, there are lots of other possibilities on M-class cores.
781  if (Subtarget.isMClass())
782    MIB.addImm(0x800);
783
784  MIB.add(predOps(ARMCC::AL))
785     .addReg(ARM::CPSR, RegState::Implicit | getKillRegState(KillSrc));
786}
787
788void ARMBaseInstrInfo::copyToCPSR(MachineBasicBlock &MBB,
789                                  MachineBasicBlock::iterator I,
790                                  unsigned SrcReg, bool KillSrc,
791                                  const ARMSubtarget &Subtarget) const {
792  unsigned Opc = Subtarget.isThumb()
793                     ? (Subtarget.isMClass() ? ARM::t2MSR_M : ARM::t2MSR_AR)
794                     : ARM::MSR;
795
796  MachineInstrBuilder MIB = BuildMI(MBB, I, I->getDebugLoc(), get(Opc));
797
798  if (Subtarget.isMClass())
799    MIB.addImm(0x800);
800  else
801    MIB.addImm(8);
802
803  MIB.addReg(SrcReg, getKillRegState(KillSrc))
804     .add(predOps(ARMCC::AL))
805     .addReg(ARM::CPSR, RegState::Implicit | RegState::Define);
806}
807
808void llvm::addUnpredicatedMveVpredNOp(MachineInstrBuilder &MIB) {
809  MIB.addImm(ARMVCC::None);
810  MIB.addReg(0);
811}
812
813void llvm::addUnpredicatedMveVpredROp(MachineInstrBuilder &MIB,
814                                      unsigned DestReg) {
815  addUnpredicatedMveVpredNOp(MIB);
816  MIB.addReg(DestReg, RegState::Undef);
817}
818
819void llvm::addPredicatedMveVpredNOp(MachineInstrBuilder &MIB, unsigned Cond) {
820  MIB.addImm(Cond);
821  MIB.addReg(ARM::VPR, RegState::Implicit);
822}
823
824void llvm::addPredicatedMveVpredROp(MachineInstrBuilder &MIB,
825                                    unsigned Cond, unsigned Inactive) {
826  addPredicatedMveVpredNOp(MIB, Cond);
827  MIB.addReg(Inactive);
828}
829
830void ARMBaseInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
831                                   MachineBasicBlock::iterator I,
832                                   const DebugLoc &DL, MCRegister DestReg,
833                                   MCRegister SrcReg, bool KillSrc) const {
834  bool GPRDest = ARM::GPRRegClass.contains(DestReg);
835  bool GPRSrc = ARM::GPRRegClass.contains(SrcReg);
836
837  if (GPRDest && GPRSrc) {
838    BuildMI(MBB, I, DL, get(ARM::MOVr), DestReg)
839        .addReg(SrcReg, getKillRegState(KillSrc))
840        .add(predOps(ARMCC::AL))
841        .add(condCodeOp());
842    return;
843  }
844
845  bool SPRDest = ARM::SPRRegClass.contains(DestReg);
846  bool SPRSrc = ARM::SPRRegClass.contains(SrcReg);
847
848  unsigned Opc = 0;
849  if (SPRDest && SPRSrc)
850    Opc = ARM::VMOVS;
851  else if (GPRDest && SPRSrc)
852    Opc = ARM::VMOVRS;
853  else if (SPRDest && GPRSrc)
854    Opc = ARM::VMOVSR;
855  else if (ARM::DPRRegClass.contains(DestReg, SrcReg) && Subtarget.hasFP64())
856    Opc = ARM::VMOVD;
857  else if (ARM::QPRRegClass.contains(DestReg, SrcReg))
858    Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR;
859
860  if (Opc) {
861    MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opc), DestReg);
862    MIB.addReg(SrcReg, getKillRegState(KillSrc));
863    if (Opc == ARM::VORRq || Opc == ARM::MVE_VORR)
864      MIB.addReg(SrcReg, getKillRegState(KillSrc));
865    if (Opc == ARM::MVE_VORR)
866      addUnpredicatedMveVpredROp(MIB, DestReg);
867    else
868      MIB.add(predOps(ARMCC::AL));
869    return;
870  }
871
872  // Handle register classes that require multiple instructions.
873  unsigned BeginIdx = 0;
874  unsigned SubRegs = 0;
875  int Spacing = 1;
876
877  // Use VORRq when possible.
878  if (ARM::QQPRRegClass.contains(DestReg, SrcReg)) {
879    Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR;
880    BeginIdx = ARM::qsub_0;
881    SubRegs = 2;
882  } else if (ARM::QQQQPRRegClass.contains(DestReg, SrcReg)) {
883    Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR;
884    BeginIdx = ARM::qsub_0;
885    SubRegs = 4;
886  // Fall back to VMOVD.
887  } else if (ARM::DPairRegClass.contains(DestReg, SrcReg)) {
888    Opc = ARM::VMOVD;
889    BeginIdx = ARM::dsub_0;
890    SubRegs = 2;
891  } else if (ARM::DTripleRegClass.contains(DestReg, SrcReg)) {
892    Opc = ARM::VMOVD;
893    BeginIdx = ARM::dsub_0;
894    SubRegs = 3;
895  } else if (ARM::DQuadRegClass.contains(DestReg, SrcReg)) {
896    Opc = ARM::VMOVD;
897    BeginIdx = ARM::dsub_0;
898    SubRegs = 4;
899  } else if (ARM::GPRPairRegClass.contains(DestReg, SrcReg)) {
900    Opc = Subtarget.isThumb2() ? ARM::tMOVr : ARM::MOVr;
901    BeginIdx = ARM::gsub_0;
902    SubRegs = 2;
903  } else if (ARM::DPairSpcRegClass.contains(DestReg, SrcReg)) {
904    Opc = ARM::VMOVD;
905    BeginIdx = ARM::dsub_0;
906    SubRegs = 2;
907    Spacing = 2;
908  } else if (ARM::DTripleSpcRegClass.contains(DestReg, SrcReg)) {
909    Opc = ARM::VMOVD;
910    BeginIdx = ARM::dsub_0;
911    SubRegs = 3;
912    Spacing = 2;
913  } else if (ARM::DQuadSpcRegClass.contains(DestReg, SrcReg)) {
914    Opc = ARM::VMOVD;
915    BeginIdx = ARM::dsub_0;
916    SubRegs = 4;
917    Spacing = 2;
918  } else if (ARM::DPRRegClass.contains(DestReg, SrcReg) &&
919             !Subtarget.hasFP64()) {
920    Opc = ARM::VMOVS;
921    BeginIdx = ARM::ssub_0;
922    SubRegs = 2;
923  } else if (SrcReg == ARM::CPSR) {
924    copyFromCPSR(MBB, I, DestReg, KillSrc, Subtarget);
925    return;
926  } else if (DestReg == ARM::CPSR) {
927    copyToCPSR(MBB, I, SrcReg, KillSrc, Subtarget);
928    return;
929  } else if (DestReg == ARM::VPR) {
930    assert(ARM::GPRRegClass.contains(SrcReg));
931    BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMSR_P0), DestReg)
932        .addReg(SrcReg, getKillRegState(KillSrc))
933        .add(predOps(ARMCC::AL));
934    return;
935  } else if (SrcReg == ARM::VPR) {
936    assert(ARM::GPRRegClass.contains(DestReg));
937    BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMRS_P0), DestReg)
938        .addReg(SrcReg, getKillRegState(KillSrc))
939        .add(predOps(ARMCC::AL));
940    return;
941  } else if (DestReg == ARM::FPSCR_NZCV) {
942    assert(ARM::GPRRegClass.contains(SrcReg));
943    BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMSR_FPSCR_NZCVQC), DestReg)
944        .addReg(SrcReg, getKillRegState(KillSrc))
945        .add(predOps(ARMCC::AL));
946    return;
947  } else if (SrcReg == ARM::FPSCR_NZCV) {
948    assert(ARM::GPRRegClass.contains(DestReg));
949    BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMRS_FPSCR_NZCVQC), DestReg)
950        .addReg(SrcReg, getKillRegState(KillSrc))
951        .add(predOps(ARMCC::AL));
952    return;
953  }
954
955  assert(Opc && "Impossible reg-to-reg copy");
956
957  const TargetRegisterInfo *TRI = &getRegisterInfo();
958  MachineInstrBuilder Mov;
959
960  // Copy register tuples backward when the first Dest reg overlaps with SrcReg.
961  if (TRI->regsOverlap(SrcReg, TRI->getSubReg(DestReg, BeginIdx))) {
962    BeginIdx = BeginIdx + ((SubRegs - 1) * Spacing);
963    Spacing = -Spacing;
964  }
965#ifndef NDEBUG
966  SmallSet<unsigned, 4> DstRegs;
967#endif
968  for (unsigned i = 0; i != SubRegs; ++i) {
969    Register Dst = TRI->getSubReg(DestReg, BeginIdx + i * Spacing);
970    Register Src = TRI->getSubReg(SrcReg, BeginIdx + i * Spacing);
971    assert(Dst && Src && "Bad sub-register");
972#ifndef NDEBUG
973    assert(!DstRegs.count(Src) && "destructive vector copy");
974    DstRegs.insert(Dst);
975#endif
976    Mov = BuildMI(MBB, I, I->getDebugLoc(), get(Opc), Dst).addReg(Src);
977    // VORR (NEON or MVE) takes two source operands.
978    if (Opc == ARM::VORRq || Opc == ARM::MVE_VORR) {
979      Mov.addReg(Src);
980    }
981    // MVE VORR takes predicate operands in place of an ordinary condition.
982    if (Opc == ARM::MVE_VORR)
983      addUnpredicatedMveVpredROp(Mov, Dst);
984    else
985      Mov = Mov.add(predOps(ARMCC::AL));
986    // MOVr can set CC.
987    if (Opc == ARM::MOVr)
988      Mov = Mov.add(condCodeOp());
989  }
990  // Add implicit super-register defs and kills to the last instruction.
991  Mov->addRegisterDefined(DestReg, TRI);
992  if (KillSrc)
993    Mov->addRegisterKilled(SrcReg, TRI);
994}
995
996Optional<DestSourcePair>
997ARMBaseInstrInfo::isCopyInstrImpl(const MachineInstr &MI) const {
998  // VMOVRRD is also a copy instruction but it requires
999  // special way of handling. It is more complex copy version
1000  // and since that we are not considering it. For recognition
1001  // of such instruction isExtractSubregLike MI interface fuction
1002  // could be used.
1003  // VORRq is considered as a move only if two inputs are
1004  // the same register.
1005  if (!MI.isMoveReg() ||
1006      (MI.getOpcode() == ARM::VORRq &&
1007       MI.getOperand(1).getReg() != MI.getOperand(2).getReg()))
1008    return None;
1009  return DestSourcePair{MI.getOperand(0), MI.getOperand(1)};
1010}
1011
1012const MachineInstrBuilder &
1013ARMBaseInstrInfo::AddDReg(MachineInstrBuilder &MIB, unsigned Reg,
1014                          unsigned SubIdx, unsigned State,
1015                          const TargetRegisterInfo *TRI) const {
1016  if (!SubIdx)
1017    return MIB.addReg(Reg, State);
1018
1019  if (Register::isPhysicalRegister(Reg))
1020    return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
1021  return MIB.addReg(Reg, State, SubIdx);
1022}
1023
1024void ARMBaseInstrInfo::
1025storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
1026                    unsigned SrcReg, bool isKill, int FI,
1027                    const TargetRegisterClass *RC,
1028                    const TargetRegisterInfo *TRI) const {
1029  MachineFunction &MF = *MBB.getParent();
1030  MachineFrameInfo &MFI = MF.getFrameInfo();
1031  unsigned Align = MFI.getObjectAlignment(FI);
1032
1033  MachineMemOperand *MMO = MF.getMachineMemOperand(
1034      MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOStore,
1035      MFI.getObjectSize(FI), Align);
1036
1037  switch (TRI->getSpillSize(*RC)) {
1038    case 2:
1039      if (ARM::HPRRegClass.hasSubClassEq(RC)) {
1040        BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRH))
1041            .addReg(SrcReg, getKillRegState(isKill))
1042            .addFrameIndex(FI)
1043            .addImm(0)
1044            .addMemOperand(MMO)
1045            .add(predOps(ARMCC::AL));
1046      } else
1047        llvm_unreachable("Unknown reg class!");
1048      break;
1049    case 4:
1050      if (ARM::GPRRegClass.hasSubClassEq(RC)) {
1051        BuildMI(MBB, I, DebugLoc(), get(ARM::STRi12))
1052            .addReg(SrcReg, getKillRegState(isKill))
1053            .addFrameIndex(FI)
1054            .addImm(0)
1055            .addMemOperand(MMO)
1056            .add(predOps(ARMCC::AL));
1057      } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
1058        BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRS))
1059            .addReg(SrcReg, getKillRegState(isKill))
1060            .addFrameIndex(FI)
1061            .addImm(0)
1062            .addMemOperand(MMO)
1063            .add(predOps(ARMCC::AL));
1064      } else if (ARM::VCCRRegClass.hasSubClassEq(RC)) {
1065        BuildMI(MBB, I, DebugLoc(), get(ARM::VSTR_P0_off))
1066            .addReg(SrcReg, getKillRegState(isKill))
1067            .addFrameIndex(FI)
1068            .addImm(0)
1069            .addMemOperand(MMO)
1070            .add(predOps(ARMCC::AL));
1071      } else
1072        llvm_unreachable("Unknown reg class!");
1073      break;
1074    case 8:
1075      if (ARM::DPRRegClass.hasSubClassEq(RC)) {
1076        BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRD))
1077            .addReg(SrcReg, getKillRegState(isKill))
1078            .addFrameIndex(FI)
1079            .addImm(0)
1080            .addMemOperand(MMO)
1081            .add(predOps(ARMCC::AL));
1082      } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) {
1083        if (Subtarget.hasV5TEOps()) {
1084          MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::STRD));
1085          AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI);
1086          AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI);
1087          MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO)
1088             .add(predOps(ARMCC::AL));
1089        } else {
1090          // Fallback to STM instruction, which has existed since the dawn of
1091          // time.
1092          MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::STMIA))
1093                                        .addFrameIndex(FI)
1094                                        .addMemOperand(MMO)
1095                                        .add(predOps(ARMCC::AL));
1096          AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI);
1097          AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI);
1098        }
1099      } else
1100        llvm_unreachable("Unknown reg class!");
1101      break;
1102    case 16:
1103      if (ARM::DPairRegClass.hasSubClassEq(RC) && Subtarget.hasNEON()) {
1104        // Use aligned spills if the stack can be realigned.
1105        if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
1106          BuildMI(MBB, I, DebugLoc(), get(ARM::VST1q64))
1107              .addFrameIndex(FI)
1108              .addImm(16)
1109              .addReg(SrcReg, getKillRegState(isKill))
1110              .addMemOperand(MMO)
1111              .add(predOps(ARMCC::AL));
1112        } else {
1113          BuildMI(MBB, I, DebugLoc(), get(ARM::VSTMQIA))
1114              .addReg(SrcReg, getKillRegState(isKill))
1115              .addFrameIndex(FI)
1116              .addMemOperand(MMO)
1117              .add(predOps(ARMCC::AL));
1118        }
1119      } else if (ARM::QPRRegClass.hasSubClassEq(RC) &&
1120                 Subtarget.hasMVEIntegerOps()) {
1121        auto MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::MVE_VSTRWU32));
1122        MIB.addReg(SrcReg, getKillRegState(isKill))
1123          .addFrameIndex(FI)
1124          .addImm(0)
1125          .addMemOperand(MMO);
1126        addUnpredicatedMveVpredNOp(MIB);
1127      } else
1128        llvm_unreachable("Unknown reg class!");
1129      break;
1130    case 24:
1131      if (ARM::DTripleRegClass.hasSubClassEq(RC)) {
1132        // Use aligned spills if the stack can be realigned.
1133        if (Align >= 16 && getRegisterInfo().canRealignStack(MF) &&
1134            Subtarget.hasNEON()) {
1135          BuildMI(MBB, I, DebugLoc(), get(ARM::VST1d64TPseudo))
1136              .addFrameIndex(FI)
1137              .addImm(16)
1138              .addReg(SrcReg, getKillRegState(isKill))
1139              .addMemOperand(MMO)
1140              .add(predOps(ARMCC::AL));
1141        } else {
1142          MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(),
1143                                            get(ARM::VSTMDIA))
1144                                        .addFrameIndex(FI)
1145                                        .add(predOps(ARMCC::AL))
1146                                        .addMemOperand(MMO);
1147          MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
1148          MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
1149          AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
1150        }
1151      } else
1152        llvm_unreachable("Unknown reg class!");
1153      break;
1154    case 32:
1155      if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) {
1156        if (Align >= 16 && getRegisterInfo().canRealignStack(MF) &&
1157            Subtarget.hasNEON()) {
1158          // FIXME: It's possible to only store part of the QQ register if the
1159          // spilled def has a sub-register index.
1160          BuildMI(MBB, I, DebugLoc(), get(ARM::VST1d64QPseudo))
1161              .addFrameIndex(FI)
1162              .addImm(16)
1163              .addReg(SrcReg, getKillRegState(isKill))
1164              .addMemOperand(MMO)
1165              .add(predOps(ARMCC::AL));
1166        } else {
1167          MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(),
1168                                            get(ARM::VSTMDIA))
1169                                        .addFrameIndex(FI)
1170                                        .add(predOps(ARMCC::AL))
1171                                        .addMemOperand(MMO);
1172          MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
1173          MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
1174          MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
1175                AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
1176        }
1177      } else
1178        llvm_unreachable("Unknown reg class!");
1179      break;
1180    case 64:
1181      if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
1182        MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::VSTMDIA))
1183                                      .addFrameIndex(FI)
1184                                      .add(predOps(ARMCC::AL))
1185                                      .addMemOperand(MMO);
1186        MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
1187        MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
1188        MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
1189        MIB = AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
1190        MIB = AddDReg(MIB, SrcReg, ARM::dsub_4, 0, TRI);
1191        MIB = AddDReg(MIB, SrcReg, ARM::dsub_5, 0, TRI);
1192        MIB = AddDReg(MIB, SrcReg, ARM::dsub_6, 0, TRI);
1193              AddDReg(MIB, SrcReg, ARM::dsub_7, 0, TRI);
1194      } else
1195        llvm_unreachable("Unknown reg class!");
1196      break;
1197    default:
1198      llvm_unreachable("Unknown reg class!");
1199  }
1200}
1201
1202unsigned ARMBaseInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
1203                                              int &FrameIndex) const {
1204  switch (MI.getOpcode()) {
1205  default: break;
1206  case ARM::STRrs:
1207  case ARM::t2STRs: // FIXME: don't use t2STRs to access frame.
1208    if (MI.getOperand(1).isFI() && MI.getOperand(2).isReg() &&
1209        MI.getOperand(3).isImm() && MI.getOperand(2).getReg() == 0 &&
1210        MI.getOperand(3).getImm() == 0) {
1211      FrameIndex = MI.getOperand(1).getIndex();
1212      return MI.getOperand(0).getReg();
1213    }
1214    break;
1215  case ARM::STRi12:
1216  case ARM::t2STRi12:
1217  case ARM::tSTRspi:
1218  case ARM::VSTRD:
1219  case ARM::VSTRS:
1220    if (MI.getOperand(1).isFI() && MI.getOperand(2).isImm() &&
1221        MI.getOperand(2).getImm() == 0) {
1222      FrameIndex = MI.getOperand(1).getIndex();
1223      return MI.getOperand(0).getReg();
1224    }
1225    break;
1226  case ARM::VSTR_P0_off:
1227    if (MI.getOperand(0).isFI() && MI.getOperand(1).isImm() &&
1228        MI.getOperand(1).getImm() == 0) {
1229      FrameIndex = MI.getOperand(0).getIndex();
1230      return ARM::P0;
1231    }
1232    break;
1233  case ARM::VST1q64:
1234  case ARM::VST1d64TPseudo:
1235  case ARM::VST1d64QPseudo:
1236    if (MI.getOperand(0).isFI() && MI.getOperand(2).getSubReg() == 0) {
1237      FrameIndex = MI.getOperand(0).getIndex();
1238      return MI.getOperand(2).getReg();
1239    }
1240    break;
1241  case ARM::VSTMQIA:
1242    if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) {
1243      FrameIndex = MI.getOperand(1).getIndex();
1244      return MI.getOperand(0).getReg();
1245    }
1246    break;
1247  }
1248
1249  return 0;
1250}
1251
1252unsigned ARMBaseInstrInfo::isStoreToStackSlotPostFE(const MachineInstr &MI,
1253                                                    int &FrameIndex) const {
1254  SmallVector<const MachineMemOperand *, 1> Accesses;
1255  if (MI.mayStore() && hasStoreToStackSlot(MI, Accesses) &&
1256      Accesses.size() == 1) {
1257    FrameIndex =
1258        cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
1259            ->getFrameIndex();
1260    return true;
1261  }
1262  return false;
1263}
1264
1265void ARMBaseInstrInfo::
1266loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
1267                     unsigned DestReg, int FI,
1268                     const TargetRegisterClass *RC,
1269                     const TargetRegisterInfo *TRI) const {
1270  DebugLoc DL;
1271  if (I != MBB.end()) DL = I->getDebugLoc();
1272  MachineFunction &MF = *MBB.getParent();
1273  MachineFrameInfo &MFI = MF.getFrameInfo();
1274  unsigned Align = MFI.getObjectAlignment(FI);
1275  MachineMemOperand *MMO = MF.getMachineMemOperand(
1276      MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOLoad,
1277      MFI.getObjectSize(FI), Align);
1278
1279  switch (TRI->getSpillSize(*RC)) {
1280  case 2:
1281    if (ARM::HPRRegClass.hasSubClassEq(RC)) {
1282      BuildMI(MBB, I, DL, get(ARM::VLDRH), DestReg)
1283          .addFrameIndex(FI)
1284          .addImm(0)
1285          .addMemOperand(MMO)
1286          .add(predOps(ARMCC::AL));
1287    } else
1288      llvm_unreachable("Unknown reg class!");
1289    break;
1290  case 4:
1291    if (ARM::GPRRegClass.hasSubClassEq(RC)) {
1292      BuildMI(MBB, I, DL, get(ARM::LDRi12), DestReg)
1293          .addFrameIndex(FI)
1294          .addImm(0)
1295          .addMemOperand(MMO)
1296          .add(predOps(ARMCC::AL));
1297    } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
1298      BuildMI(MBB, I, DL, get(ARM::VLDRS), DestReg)
1299          .addFrameIndex(FI)
1300          .addImm(0)
1301          .addMemOperand(MMO)
1302          .add(predOps(ARMCC::AL));
1303    } else if (ARM::VCCRRegClass.hasSubClassEq(RC)) {
1304      BuildMI(MBB, I, DL, get(ARM::VLDR_P0_off), DestReg)
1305          .addFrameIndex(FI)
1306          .addImm(0)
1307          .addMemOperand(MMO)
1308          .add(predOps(ARMCC::AL));
1309    } else
1310      llvm_unreachable("Unknown reg class!");
1311    break;
1312  case 8:
1313    if (ARM::DPRRegClass.hasSubClassEq(RC)) {
1314      BuildMI(MBB, I, DL, get(ARM::VLDRD), DestReg)
1315          .addFrameIndex(FI)
1316          .addImm(0)
1317          .addMemOperand(MMO)
1318          .add(predOps(ARMCC::AL));
1319    } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) {
1320      MachineInstrBuilder MIB;
1321
1322      if (Subtarget.hasV5TEOps()) {
1323        MIB = BuildMI(MBB, I, DL, get(ARM::LDRD));
1324        AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI);
1325        AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI);
1326        MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO)
1327           .add(predOps(ARMCC::AL));
1328      } else {
1329        // Fallback to LDM instruction, which has existed since the dawn of
1330        // time.
1331        MIB = BuildMI(MBB, I, DL, get(ARM::LDMIA))
1332                  .addFrameIndex(FI)
1333                  .addMemOperand(MMO)
1334                  .add(predOps(ARMCC::AL));
1335        MIB = AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI);
1336        MIB = AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI);
1337      }
1338
1339      if (Register::isPhysicalRegister(DestReg))
1340        MIB.addReg(DestReg, RegState::ImplicitDefine);
1341    } else
1342      llvm_unreachable("Unknown reg class!");
1343    break;
1344  case 16:
1345    if (ARM::DPairRegClass.hasSubClassEq(RC) && Subtarget.hasNEON()) {
1346      if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
1347        BuildMI(MBB, I, DL, get(ARM::VLD1q64), DestReg)
1348            .addFrameIndex(FI)
1349            .addImm(16)
1350            .addMemOperand(MMO)
1351            .add(predOps(ARMCC::AL));
1352      } else {
1353        BuildMI(MBB, I, DL, get(ARM::VLDMQIA), DestReg)
1354            .addFrameIndex(FI)
1355            .addMemOperand(MMO)
1356            .add(predOps(ARMCC::AL));
1357      }
1358    } else if (ARM::QPRRegClass.hasSubClassEq(RC) &&
1359               Subtarget.hasMVEIntegerOps()) {
1360      auto MIB = BuildMI(MBB, I, DL, get(ARM::MVE_VLDRWU32), DestReg);
1361      MIB.addFrameIndex(FI)
1362        .addImm(0)
1363        .addMemOperand(MMO);
1364      addUnpredicatedMveVpredNOp(MIB);
1365    } else
1366      llvm_unreachable("Unknown reg class!");
1367    break;
1368  case 24:
1369    if (ARM::DTripleRegClass.hasSubClassEq(RC)) {
1370      if (Align >= 16 && getRegisterInfo().canRealignStack(MF) &&
1371          Subtarget.hasNEON()) {
1372        BuildMI(MBB, I, DL, get(ARM::VLD1d64TPseudo), DestReg)
1373            .addFrameIndex(FI)
1374            .addImm(16)
1375            .addMemOperand(MMO)
1376            .add(predOps(ARMCC::AL));
1377      } else {
1378        MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1379                                      .addFrameIndex(FI)
1380                                      .addMemOperand(MMO)
1381                                      .add(predOps(ARMCC::AL));
1382        MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1383        MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1384        MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1385        if (Register::isPhysicalRegister(DestReg))
1386          MIB.addReg(DestReg, RegState::ImplicitDefine);
1387      }
1388    } else
1389      llvm_unreachable("Unknown reg class!");
1390    break;
1391   case 32:
1392    if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) {
1393      if (Align >= 16 && getRegisterInfo().canRealignStack(MF) &&
1394          Subtarget.hasNEON()) {
1395        BuildMI(MBB, I, DL, get(ARM::VLD1d64QPseudo), DestReg)
1396            .addFrameIndex(FI)
1397            .addImm(16)
1398            .addMemOperand(MMO)
1399            .add(predOps(ARMCC::AL));
1400      } else {
1401        MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1402                                      .addFrameIndex(FI)
1403                                      .add(predOps(ARMCC::AL))
1404                                      .addMemOperand(MMO);
1405        MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1406        MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1407        MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1408        MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI);
1409        if (Register::isPhysicalRegister(DestReg))
1410          MIB.addReg(DestReg, RegState::ImplicitDefine);
1411      }
1412    } else
1413      llvm_unreachable("Unknown reg class!");
1414    break;
1415  case 64:
1416    if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
1417      MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1418                                    .addFrameIndex(FI)
1419                                    .add(predOps(ARMCC::AL))
1420                                    .addMemOperand(MMO);
1421      MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1422      MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1423      MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1424      MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI);
1425      MIB = AddDReg(MIB, DestReg, ARM::dsub_4, RegState::DefineNoRead, TRI);
1426      MIB = AddDReg(MIB, DestReg, ARM::dsub_5, RegState::DefineNoRead, TRI);
1427      MIB = AddDReg(MIB, DestReg, ARM::dsub_6, RegState::DefineNoRead, TRI);
1428      MIB = AddDReg(MIB, DestReg, ARM::dsub_7, RegState::DefineNoRead, TRI);
1429      if (Register::isPhysicalRegister(DestReg))
1430        MIB.addReg(DestReg, RegState::ImplicitDefine);
1431    } else
1432      llvm_unreachable("Unknown reg class!");
1433    break;
1434  default:
1435    llvm_unreachable("Unknown regclass!");
1436  }
1437}
1438
1439unsigned ARMBaseInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
1440                                               int &FrameIndex) const {
1441  switch (MI.getOpcode()) {
1442  default: break;
1443  case ARM::LDRrs:
1444  case ARM::t2LDRs:  // FIXME: don't use t2LDRs to access frame.
1445    if (MI.getOperand(1).isFI() && MI.getOperand(2).isReg() &&
1446        MI.getOperand(3).isImm() && MI.getOperand(2).getReg() == 0 &&
1447        MI.getOperand(3).getImm() == 0) {
1448      FrameIndex = MI.getOperand(1).getIndex();
1449      return MI.getOperand(0).getReg();
1450    }
1451    break;
1452  case ARM::LDRi12:
1453  case ARM::t2LDRi12:
1454  case ARM::tLDRspi:
1455  case ARM::VLDRD:
1456  case ARM::VLDRS:
1457    if (MI.getOperand(1).isFI() && MI.getOperand(2).isImm() &&
1458        MI.getOperand(2).getImm() == 0) {
1459      FrameIndex = MI.getOperand(1).getIndex();
1460      return MI.getOperand(0).getReg();
1461    }
1462    break;
1463  case ARM::VLDR_P0_off:
1464    if (MI.getOperand(0).isFI() && MI.getOperand(1).isImm() &&
1465        MI.getOperand(1).getImm() == 0) {
1466      FrameIndex = MI.getOperand(0).getIndex();
1467      return ARM::P0;
1468    }
1469    break;
1470  case ARM::VLD1q64:
1471  case ARM::VLD1d8TPseudo:
1472  case ARM::VLD1d16TPseudo:
1473  case ARM::VLD1d32TPseudo:
1474  case ARM::VLD1d64TPseudo:
1475  case ARM::VLD1d8QPseudo:
1476  case ARM::VLD1d16QPseudo:
1477  case ARM::VLD1d32QPseudo:
1478  case ARM::VLD1d64QPseudo:
1479    if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) {
1480      FrameIndex = MI.getOperand(1).getIndex();
1481      return MI.getOperand(0).getReg();
1482    }
1483    break;
1484  case ARM::VLDMQIA:
1485    if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) {
1486      FrameIndex = MI.getOperand(1).getIndex();
1487      return MI.getOperand(0).getReg();
1488    }
1489    break;
1490  }
1491
1492  return 0;
1493}
1494
1495unsigned ARMBaseInstrInfo::isLoadFromStackSlotPostFE(const MachineInstr &MI,
1496                                                     int &FrameIndex) const {
1497  SmallVector<const MachineMemOperand *, 1> Accesses;
1498  if (MI.mayLoad() && hasLoadFromStackSlot(MI, Accesses) &&
1499      Accesses.size() == 1) {
1500    FrameIndex =
1501        cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
1502            ->getFrameIndex();
1503    return true;
1504  }
1505  return false;
1506}
1507
1508/// Expands MEMCPY to either LDMIA/STMIA or LDMIA_UPD/STMID_UPD
1509/// depending on whether the result is used.
1510void ARMBaseInstrInfo::expandMEMCPY(MachineBasicBlock::iterator MI) const {
1511  bool isThumb1 = Subtarget.isThumb1Only();
1512  bool isThumb2 = Subtarget.isThumb2();
1513  const ARMBaseInstrInfo *TII = Subtarget.getInstrInfo();
1514
1515  DebugLoc dl = MI->getDebugLoc();
1516  MachineBasicBlock *BB = MI->getParent();
1517
1518  MachineInstrBuilder LDM, STM;
1519  if (isThumb1 || !MI->getOperand(1).isDead()) {
1520    MachineOperand LDWb(MI->getOperand(1));
1521    LDM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2LDMIA_UPD
1522                                                 : isThumb1 ? ARM::tLDMIA_UPD
1523                                                            : ARM::LDMIA_UPD))
1524              .add(LDWb);
1525  } else {
1526    LDM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2LDMIA : ARM::LDMIA));
1527  }
1528
1529  if (isThumb1 || !MI->getOperand(0).isDead()) {
1530    MachineOperand STWb(MI->getOperand(0));
1531    STM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2STMIA_UPD
1532                                                 : isThumb1 ? ARM::tSTMIA_UPD
1533                                                            : ARM::STMIA_UPD))
1534              .add(STWb);
1535  } else {
1536    STM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2STMIA : ARM::STMIA));
1537  }
1538
1539  MachineOperand LDBase(MI->getOperand(3));
1540  LDM.add(LDBase).add(predOps(ARMCC::AL));
1541
1542  MachineOperand STBase(MI->getOperand(2));
1543  STM.add(STBase).add(predOps(ARMCC::AL));
1544
1545  // Sort the scratch registers into ascending order.
1546  const TargetRegisterInfo &TRI = getRegisterInfo();
1547  SmallVector<unsigned, 6> ScratchRegs;
1548  for(unsigned I = 5; I < MI->getNumOperands(); ++I)
1549    ScratchRegs.push_back(MI->getOperand(I).getReg());
1550  llvm::sort(ScratchRegs,
1551             [&TRI](const unsigned &Reg1, const unsigned &Reg2) -> bool {
1552               return TRI.getEncodingValue(Reg1) <
1553                      TRI.getEncodingValue(Reg2);
1554             });
1555
1556  for (const auto &Reg : ScratchRegs) {
1557    LDM.addReg(Reg, RegState::Define);
1558    STM.addReg(Reg, RegState::Kill);
1559  }
1560
1561  BB->erase(MI);
1562}
1563
1564bool ARMBaseInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
1565  if (MI.getOpcode() == TargetOpcode::LOAD_STACK_GUARD) {
1566    assert(getSubtarget().getTargetTriple().isOSBinFormatMachO() &&
1567           "LOAD_STACK_GUARD currently supported only for MachO.");
1568    expandLoadStackGuard(MI);
1569    MI.getParent()->erase(MI);
1570    return true;
1571  }
1572
1573  if (MI.getOpcode() == ARM::MEMCPY) {
1574    expandMEMCPY(MI);
1575    return true;
1576  }
1577
1578  // This hook gets to expand COPY instructions before they become
1579  // copyPhysReg() calls.  Look for VMOVS instructions that can legally be
1580  // widened to VMOVD.  We prefer the VMOVD when possible because it may be
1581  // changed into a VORR that can go down the NEON pipeline.
1582  if (!MI.isCopy() || Subtarget.dontWidenVMOVS() || !Subtarget.hasFP64())
1583    return false;
1584
1585  // Look for a copy between even S-registers.  That is where we keep floats
1586  // when using NEON v2f32 instructions for f32 arithmetic.
1587  Register DstRegS = MI.getOperand(0).getReg();
1588  Register SrcRegS = MI.getOperand(1).getReg();
1589  if (!ARM::SPRRegClass.contains(DstRegS, SrcRegS))
1590    return false;
1591
1592  const TargetRegisterInfo *TRI = &getRegisterInfo();
1593  unsigned DstRegD = TRI->getMatchingSuperReg(DstRegS, ARM::ssub_0,
1594                                              &ARM::DPRRegClass);
1595  unsigned SrcRegD = TRI->getMatchingSuperReg(SrcRegS, ARM::ssub_0,
1596                                              &ARM::DPRRegClass);
1597  if (!DstRegD || !SrcRegD)
1598    return false;
1599
1600  // We want to widen this into a DstRegD = VMOVD SrcRegD copy.  This is only
1601  // legal if the COPY already defines the full DstRegD, and it isn't a
1602  // sub-register insertion.
1603  if (!MI.definesRegister(DstRegD, TRI) || MI.readsRegister(DstRegD, TRI))
1604    return false;
1605
1606  // A dead copy shouldn't show up here, but reject it just in case.
1607  if (MI.getOperand(0).isDead())
1608    return false;
1609
1610  // All clear, widen the COPY.
1611  LLVM_DEBUG(dbgs() << "widening:    " << MI);
1612  MachineInstrBuilder MIB(*MI.getParent()->getParent(), MI);
1613
1614  // Get rid of the old implicit-def of DstRegD.  Leave it if it defines a Q-reg
1615  // or some other super-register.
1616  int ImpDefIdx = MI.findRegisterDefOperandIdx(DstRegD);
1617  if (ImpDefIdx != -1)
1618    MI.RemoveOperand(ImpDefIdx);
1619
1620  // Change the opcode and operands.
1621  MI.setDesc(get(ARM::VMOVD));
1622  MI.getOperand(0).setReg(DstRegD);
1623  MI.getOperand(1).setReg(SrcRegD);
1624  MIB.add(predOps(ARMCC::AL));
1625
1626  // We are now reading SrcRegD instead of SrcRegS.  This may upset the
1627  // register scavenger and machine verifier, so we need to indicate that we
1628  // are reading an undefined value from SrcRegD, but a proper value from
1629  // SrcRegS.
1630  MI.getOperand(1).setIsUndef();
1631  MIB.addReg(SrcRegS, RegState::Implicit);
1632
1633  // SrcRegD may actually contain an unrelated value in the ssub_1
1634  // sub-register.  Don't kill it.  Only kill the ssub_0 sub-register.
1635  if (MI.getOperand(1).isKill()) {
1636    MI.getOperand(1).setIsKill(false);
1637    MI.addRegisterKilled(SrcRegS, TRI, true);
1638  }
1639
1640  LLVM_DEBUG(dbgs() << "replaced by: " << MI);
1641  return true;
1642}
1643
1644/// Create a copy of a const pool value. Update CPI to the new index and return
1645/// the label UID.
1646static unsigned duplicateCPV(MachineFunction &MF, unsigned &CPI) {
1647  MachineConstantPool *MCP = MF.getConstantPool();
1648  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1649
1650  const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
1651  assert(MCPE.isMachineConstantPoolEntry() &&
1652         "Expecting a machine constantpool entry!");
1653  ARMConstantPoolValue *ACPV =
1654    static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
1655
1656  unsigned PCLabelId = AFI->createPICLabelUId();
1657  ARMConstantPoolValue *NewCPV = nullptr;
1658
1659  // FIXME: The below assumes PIC relocation model and that the function
1660  // is Thumb mode (t1 or t2). PCAdjustment would be 8 for ARM mode PIC, and
1661  // zero for non-PIC in ARM or Thumb. The callers are all of thumb LDR
1662  // instructions, so that's probably OK, but is PIC always correct when
1663  // we get here?
1664  if (ACPV->isGlobalValue())
1665    NewCPV = ARMConstantPoolConstant::Create(
1666        cast<ARMConstantPoolConstant>(ACPV)->getGV(), PCLabelId, ARMCP::CPValue,
1667        4, ACPV->getModifier(), ACPV->mustAddCurrentAddress());
1668  else if (ACPV->isExtSymbol())
1669    NewCPV = ARMConstantPoolSymbol::
1670      Create(MF.getFunction().getContext(),
1671             cast<ARMConstantPoolSymbol>(ACPV)->getSymbol(), PCLabelId, 4);
1672  else if (ACPV->isBlockAddress())
1673    NewCPV = ARMConstantPoolConstant::
1674      Create(cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress(), PCLabelId,
1675             ARMCP::CPBlockAddress, 4);
1676  else if (ACPV->isLSDA())
1677    NewCPV = ARMConstantPoolConstant::Create(&MF.getFunction(), PCLabelId,
1678                                             ARMCP::CPLSDA, 4);
1679  else if (ACPV->isMachineBasicBlock())
1680    NewCPV = ARMConstantPoolMBB::
1681      Create(MF.getFunction().getContext(),
1682             cast<ARMConstantPoolMBB>(ACPV)->getMBB(), PCLabelId, 4);
1683  else
1684    llvm_unreachable("Unexpected ARM constantpool value type!!");
1685  CPI = MCP->getConstantPoolIndex(NewCPV, MCPE.getAlignment());
1686  return PCLabelId;
1687}
1688
1689void ARMBaseInstrInfo::reMaterialize(MachineBasicBlock &MBB,
1690                                     MachineBasicBlock::iterator I,
1691                                     unsigned DestReg, unsigned SubIdx,
1692                                     const MachineInstr &Orig,
1693                                     const TargetRegisterInfo &TRI) const {
1694  unsigned Opcode = Orig.getOpcode();
1695  switch (Opcode) {
1696  default: {
1697    MachineInstr *MI = MBB.getParent()->CloneMachineInstr(&Orig);
1698    MI->substituteRegister(Orig.getOperand(0).getReg(), DestReg, SubIdx, TRI);
1699    MBB.insert(I, MI);
1700    break;
1701  }
1702  case ARM::tLDRpci_pic:
1703  case ARM::t2LDRpci_pic: {
1704    MachineFunction &MF = *MBB.getParent();
1705    unsigned CPI = Orig.getOperand(1).getIndex();
1706    unsigned PCLabelId = duplicateCPV(MF, CPI);
1707    BuildMI(MBB, I, Orig.getDebugLoc(), get(Opcode), DestReg)
1708        .addConstantPoolIndex(CPI)
1709        .addImm(PCLabelId)
1710        .cloneMemRefs(Orig);
1711    break;
1712  }
1713  }
1714}
1715
1716MachineInstr &
1717ARMBaseInstrInfo::duplicate(MachineBasicBlock &MBB,
1718    MachineBasicBlock::iterator InsertBefore,
1719    const MachineInstr &Orig) const {
1720  MachineInstr &Cloned = TargetInstrInfo::duplicate(MBB, InsertBefore, Orig);
1721  MachineBasicBlock::instr_iterator I = Cloned.getIterator();
1722  for (;;) {
1723    switch (I->getOpcode()) {
1724    case ARM::tLDRpci_pic:
1725    case ARM::t2LDRpci_pic: {
1726      MachineFunction &MF = *MBB.getParent();
1727      unsigned CPI = I->getOperand(1).getIndex();
1728      unsigned PCLabelId = duplicateCPV(MF, CPI);
1729      I->getOperand(1).setIndex(CPI);
1730      I->getOperand(2).setImm(PCLabelId);
1731      break;
1732    }
1733    }
1734    if (!I->isBundledWithSucc())
1735      break;
1736    ++I;
1737  }
1738  return Cloned;
1739}
1740
1741bool ARMBaseInstrInfo::produceSameValue(const MachineInstr &MI0,
1742                                        const MachineInstr &MI1,
1743                                        const MachineRegisterInfo *MRI) const {
1744  unsigned Opcode = MI0.getOpcode();
1745  if (Opcode == ARM::t2LDRpci ||
1746      Opcode == ARM::t2LDRpci_pic ||
1747      Opcode == ARM::tLDRpci ||
1748      Opcode == ARM::tLDRpci_pic ||
1749      Opcode == ARM::LDRLIT_ga_pcrel ||
1750      Opcode == ARM::LDRLIT_ga_pcrel_ldr ||
1751      Opcode == ARM::tLDRLIT_ga_pcrel ||
1752      Opcode == ARM::MOV_ga_pcrel ||
1753      Opcode == ARM::MOV_ga_pcrel_ldr ||
1754      Opcode == ARM::t2MOV_ga_pcrel) {
1755    if (MI1.getOpcode() != Opcode)
1756      return false;
1757    if (MI0.getNumOperands() != MI1.getNumOperands())
1758      return false;
1759
1760    const MachineOperand &MO0 = MI0.getOperand(1);
1761    const MachineOperand &MO1 = MI1.getOperand(1);
1762    if (MO0.getOffset() != MO1.getOffset())
1763      return false;
1764
1765    if (Opcode == ARM::LDRLIT_ga_pcrel ||
1766        Opcode == ARM::LDRLIT_ga_pcrel_ldr ||
1767        Opcode == ARM::tLDRLIT_ga_pcrel ||
1768        Opcode == ARM::MOV_ga_pcrel ||
1769        Opcode == ARM::MOV_ga_pcrel_ldr ||
1770        Opcode == ARM::t2MOV_ga_pcrel)
1771      // Ignore the PC labels.
1772      return MO0.getGlobal() == MO1.getGlobal();
1773
1774    const MachineFunction *MF = MI0.getParent()->getParent();
1775    const MachineConstantPool *MCP = MF->getConstantPool();
1776    int CPI0 = MO0.getIndex();
1777    int CPI1 = MO1.getIndex();
1778    const MachineConstantPoolEntry &MCPE0 = MCP->getConstants()[CPI0];
1779    const MachineConstantPoolEntry &MCPE1 = MCP->getConstants()[CPI1];
1780    bool isARMCP0 = MCPE0.isMachineConstantPoolEntry();
1781    bool isARMCP1 = MCPE1.isMachineConstantPoolEntry();
1782    if (isARMCP0 && isARMCP1) {
1783      ARMConstantPoolValue *ACPV0 =
1784        static_cast<ARMConstantPoolValue*>(MCPE0.Val.MachineCPVal);
1785      ARMConstantPoolValue *ACPV1 =
1786        static_cast<ARMConstantPoolValue*>(MCPE1.Val.MachineCPVal);
1787      return ACPV0->hasSameValue(ACPV1);
1788    } else if (!isARMCP0 && !isARMCP1) {
1789      return MCPE0.Val.ConstVal == MCPE1.Val.ConstVal;
1790    }
1791    return false;
1792  } else if (Opcode == ARM::PICLDR) {
1793    if (MI1.getOpcode() != Opcode)
1794      return false;
1795    if (MI0.getNumOperands() != MI1.getNumOperands())
1796      return false;
1797
1798    Register Addr0 = MI0.getOperand(1).getReg();
1799    Register Addr1 = MI1.getOperand(1).getReg();
1800    if (Addr0 != Addr1) {
1801      if (!MRI || !Register::isVirtualRegister(Addr0) ||
1802          !Register::isVirtualRegister(Addr1))
1803        return false;
1804
1805      // This assumes SSA form.
1806      MachineInstr *Def0 = MRI->getVRegDef(Addr0);
1807      MachineInstr *Def1 = MRI->getVRegDef(Addr1);
1808      // Check if the loaded value, e.g. a constantpool of a global address, are
1809      // the same.
1810      if (!produceSameValue(*Def0, *Def1, MRI))
1811        return false;
1812    }
1813
1814    for (unsigned i = 3, e = MI0.getNumOperands(); i != e; ++i) {
1815      // %12 = PICLDR %11, 0, 14, %noreg
1816      const MachineOperand &MO0 = MI0.getOperand(i);
1817      const MachineOperand &MO1 = MI1.getOperand(i);
1818      if (!MO0.isIdenticalTo(MO1))
1819        return false;
1820    }
1821    return true;
1822  }
1823
1824  return MI0.isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
1825}
1826
1827/// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler to
1828/// determine if two loads are loading from the same base address. It should
1829/// only return true if the base pointers are the same and the only differences
1830/// between the two addresses is the offset. It also returns the offsets by
1831/// reference.
1832///
1833/// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched
1834/// is permanently disabled.
1835bool ARMBaseInstrInfo::areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
1836                                               int64_t &Offset1,
1837                                               int64_t &Offset2) const {
1838  // Don't worry about Thumb: just ARM and Thumb2.
1839  if (Subtarget.isThumb1Only()) return false;
1840
1841  if (!Load1->isMachineOpcode() || !Load2->isMachineOpcode())
1842    return false;
1843
1844  switch (Load1->getMachineOpcode()) {
1845  default:
1846    return false;
1847  case ARM::LDRi12:
1848  case ARM::LDRBi12:
1849  case ARM::LDRD:
1850  case ARM::LDRH:
1851  case ARM::LDRSB:
1852  case ARM::LDRSH:
1853  case ARM::VLDRD:
1854  case ARM::VLDRS:
1855  case ARM::t2LDRi8:
1856  case ARM::t2LDRBi8:
1857  case ARM::t2LDRDi8:
1858  case ARM::t2LDRSHi8:
1859  case ARM::t2LDRi12:
1860  case ARM::t2LDRBi12:
1861  case ARM::t2LDRSHi12:
1862    break;
1863  }
1864
1865  switch (Load2->getMachineOpcode()) {
1866  default:
1867    return false;
1868  case ARM::LDRi12:
1869  case ARM::LDRBi12:
1870  case ARM::LDRD:
1871  case ARM::LDRH:
1872  case ARM::LDRSB:
1873  case ARM::LDRSH:
1874  case ARM::VLDRD:
1875  case ARM::VLDRS:
1876  case ARM::t2LDRi8:
1877  case ARM::t2LDRBi8:
1878  case ARM::t2LDRSHi8:
1879  case ARM::t2LDRi12:
1880  case ARM::t2LDRBi12:
1881  case ARM::t2LDRSHi12:
1882    break;
1883  }
1884
1885  // Check if base addresses and chain operands match.
1886  if (Load1->getOperand(0) != Load2->getOperand(0) ||
1887      Load1->getOperand(4) != Load2->getOperand(4))
1888    return false;
1889
1890  // Index should be Reg0.
1891  if (Load1->getOperand(3) != Load2->getOperand(3))
1892    return false;
1893
1894  // Determine the offsets.
1895  if (isa<ConstantSDNode>(Load1->getOperand(1)) &&
1896      isa<ConstantSDNode>(Load2->getOperand(1))) {
1897    Offset1 = cast<ConstantSDNode>(Load1->getOperand(1))->getSExtValue();
1898    Offset2 = cast<ConstantSDNode>(Load2->getOperand(1))->getSExtValue();
1899    return true;
1900  }
1901
1902  return false;
1903}
1904
1905/// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
1906/// determine (in conjunction with areLoadsFromSameBasePtr) if two loads should
1907/// be scheduled togther. On some targets if two loads are loading from
1908/// addresses in the same cache line, it's better if they are scheduled
1909/// together. This function takes two integers that represent the load offsets
1910/// from the common base address. It returns true if it decides it's desirable
1911/// to schedule the two loads together. "NumLoads" is the number of loads that
1912/// have already been scheduled after Load1.
1913///
1914/// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched
1915/// is permanently disabled.
1916bool ARMBaseInstrInfo::shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
1917                                               int64_t Offset1, int64_t Offset2,
1918                                               unsigned NumLoads) const {
1919  // Don't worry about Thumb: just ARM and Thumb2.
1920  if (Subtarget.isThumb1Only()) return false;
1921
1922  assert(Offset2 > Offset1);
1923
1924  if ((Offset2 - Offset1) / 8 > 64)
1925    return false;
1926
1927  // Check if the machine opcodes are different. If they are different
1928  // then we consider them to not be of the same base address,
1929  // EXCEPT in the case of Thumb2 byte loads where one is LDRBi8 and the other LDRBi12.
1930  // In this case, they are considered to be the same because they are different
1931  // encoding forms of the same basic instruction.
1932  if ((Load1->getMachineOpcode() != Load2->getMachineOpcode()) &&
1933      !((Load1->getMachineOpcode() == ARM::t2LDRBi8 &&
1934         Load2->getMachineOpcode() == ARM::t2LDRBi12) ||
1935        (Load1->getMachineOpcode() == ARM::t2LDRBi12 &&
1936         Load2->getMachineOpcode() == ARM::t2LDRBi8)))
1937    return false;  // FIXME: overly conservative?
1938
1939  // Four loads in a row should be sufficient.
1940  if (NumLoads >= 3)
1941    return false;
1942
1943  return true;
1944}
1945
1946bool ARMBaseInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
1947                                            const MachineBasicBlock *MBB,
1948                                            const MachineFunction &MF) const {
1949  // Debug info is never a scheduling boundary. It's necessary to be explicit
1950  // due to the special treatment of IT instructions below, otherwise a
1951  // dbg_value followed by an IT will result in the IT instruction being
1952  // considered a scheduling hazard, which is wrong. It should be the actual
1953  // instruction preceding the dbg_value instruction(s), just like it is
1954  // when debug info is not present.
1955  if (MI.isDebugInstr())
1956    return false;
1957
1958  // Terminators and labels can't be scheduled around.
1959  if (MI.isTerminator() || MI.isPosition())
1960    return true;
1961
1962  // Treat the start of the IT block as a scheduling boundary, but schedule
1963  // t2IT along with all instructions following it.
1964  // FIXME: This is a big hammer. But the alternative is to add all potential
1965  // true and anti dependencies to IT block instructions as implicit operands
1966  // to the t2IT instruction. The added compile time and complexity does not
1967  // seem worth it.
1968  MachineBasicBlock::const_iterator I = MI;
1969  // Make sure to skip any debug instructions
1970  while (++I != MBB->end() && I->isDebugInstr())
1971    ;
1972  if (I != MBB->end() && I->getOpcode() == ARM::t2IT)
1973    return true;
1974
1975  // Don't attempt to schedule around any instruction that defines
1976  // a stack-oriented pointer, as it's unlikely to be profitable. This
1977  // saves compile time, because it doesn't require every single
1978  // stack slot reference to depend on the instruction that does the
1979  // modification.
1980  // Calls don't actually change the stack pointer, even if they have imp-defs.
1981  // No ARM calling conventions change the stack pointer. (X86 calling
1982  // conventions sometimes do).
1983  if (!MI.isCall() && MI.definesRegister(ARM::SP))
1984    return true;
1985
1986  return false;
1987}
1988
1989bool ARMBaseInstrInfo::
1990isProfitableToIfCvt(MachineBasicBlock &MBB,
1991                    unsigned NumCycles, unsigned ExtraPredCycles,
1992                    BranchProbability Probability) const {
1993  if (!NumCycles)
1994    return false;
1995
1996  // If we are optimizing for size, see if the branch in the predecessor can be
1997  // lowered to cbn?z by the constant island lowering pass, and return false if
1998  // so. This results in a shorter instruction sequence.
1999  if (MBB.getParent()->getFunction().hasOptSize()) {
2000    MachineBasicBlock *Pred = *MBB.pred_begin();
2001    if (!Pred->empty()) {
2002      MachineInstr *LastMI = &*Pred->rbegin();
2003      if (LastMI->getOpcode() == ARM::t2Bcc) {
2004        const TargetRegisterInfo *TRI = &getRegisterInfo();
2005        MachineInstr *CmpMI = findCMPToFoldIntoCBZ(LastMI, TRI);
2006        if (CmpMI)
2007          return false;
2008      }
2009    }
2010  }
2011  return isProfitableToIfCvt(MBB, NumCycles, ExtraPredCycles,
2012                             MBB, 0, 0, Probability);
2013}
2014
2015bool ARMBaseInstrInfo::
2016isProfitableToIfCvt(MachineBasicBlock &TBB,
2017                    unsigned TCycles, unsigned TExtra,
2018                    MachineBasicBlock &FBB,
2019                    unsigned FCycles, unsigned FExtra,
2020                    BranchProbability Probability) const {
2021  if (!TCycles)
2022    return false;
2023
2024  // In thumb code we often end up trading one branch for a IT block, and
2025  // if we are cloning the instruction can increase code size. Prevent
2026  // blocks with multiple predecesors from being ifcvted to prevent this
2027  // cloning.
2028  if (Subtarget.isThumb2() && TBB.getParent()->getFunction().hasMinSize()) {
2029    if (TBB.pred_size() != 1 || FBB.pred_size() != 1)
2030      return false;
2031  }
2032
2033  // Attempt to estimate the relative costs of predication versus branching.
2034  // Here we scale up each component of UnpredCost to avoid precision issue when
2035  // scaling TCycles/FCycles by Probability.
2036  const unsigned ScalingUpFactor = 1024;
2037
2038  unsigned PredCost = (TCycles + FCycles + TExtra + FExtra) * ScalingUpFactor;
2039  unsigned UnpredCost;
2040  if (!Subtarget.hasBranchPredictor()) {
2041    // When we don't have a branch predictor it's always cheaper to not take a
2042    // branch than take it, so we have to take that into account.
2043    unsigned NotTakenBranchCost = 1;
2044    unsigned TakenBranchCost = Subtarget.getMispredictionPenalty();
2045    unsigned TUnpredCycles, FUnpredCycles;
2046    if (!FCycles) {
2047      // Triangle: TBB is the fallthrough
2048      TUnpredCycles = TCycles + NotTakenBranchCost;
2049      FUnpredCycles = TakenBranchCost;
2050    } else {
2051      // Diamond: TBB is the block that is branched to, FBB is the fallthrough
2052      TUnpredCycles = TCycles + TakenBranchCost;
2053      FUnpredCycles = FCycles + NotTakenBranchCost;
2054      // The branch at the end of FBB will disappear when it's predicated, so
2055      // discount it from PredCost.
2056      PredCost -= 1 * ScalingUpFactor;
2057    }
2058    // The total cost is the cost of each path scaled by their probabilites
2059    unsigned TUnpredCost = Probability.scale(TUnpredCycles * ScalingUpFactor);
2060    unsigned FUnpredCost = Probability.getCompl().scale(FUnpredCycles * ScalingUpFactor);
2061    UnpredCost = TUnpredCost + FUnpredCost;
2062    // When predicating assume that the first IT can be folded away but later
2063    // ones cost one cycle each
2064    if (Subtarget.isThumb2() && TCycles + FCycles > 4) {
2065      PredCost += ((TCycles + FCycles - 4) / 4) * ScalingUpFactor;
2066    }
2067  } else {
2068    unsigned TUnpredCost = Probability.scale(TCycles * ScalingUpFactor);
2069    unsigned FUnpredCost =
2070      Probability.getCompl().scale(FCycles * ScalingUpFactor);
2071    UnpredCost = TUnpredCost + FUnpredCost;
2072    UnpredCost += 1 * ScalingUpFactor; // The branch itself
2073    UnpredCost += Subtarget.getMispredictionPenalty() * ScalingUpFactor / 10;
2074  }
2075
2076  return PredCost <= UnpredCost;
2077}
2078
2079unsigned
2080ARMBaseInstrInfo::extraSizeToPredicateInstructions(const MachineFunction &MF,
2081                                                   unsigned NumInsts) const {
2082  // Thumb2 needs a 2-byte IT instruction to predicate up to 4 instructions.
2083  // ARM has a condition code field in every predicable instruction, using it
2084  // doesn't change code size.
2085  return Subtarget.isThumb2() ? divideCeil(NumInsts, 4) * 2 : 0;
2086}
2087
2088unsigned
2089ARMBaseInstrInfo::predictBranchSizeForIfCvt(MachineInstr &MI) const {
2090  // If this branch is likely to be folded into the comparison to form a
2091  // CB(N)Z, then removing it won't reduce code size at all, because that will
2092  // just replace the CB(N)Z with a CMP.
2093  if (MI.getOpcode() == ARM::t2Bcc &&
2094      findCMPToFoldIntoCBZ(&MI, &getRegisterInfo()))
2095    return 0;
2096
2097  unsigned Size = getInstSizeInBytes(MI);
2098
2099  // For Thumb2, all branches are 32-bit instructions during the if conversion
2100  // pass, but may be replaced with 16-bit instructions during size reduction.
2101  // Since the branches considered by if conversion tend to be forward branches
2102  // over small basic blocks, they are very likely to be in range for the
2103  // narrow instructions, so we assume the final code size will be half what it
2104  // currently is.
2105  if (Subtarget.isThumb2())
2106    Size /= 2;
2107
2108  return Size;
2109}
2110
2111bool
2112ARMBaseInstrInfo::isProfitableToUnpredicate(MachineBasicBlock &TMBB,
2113                                            MachineBasicBlock &FMBB) const {
2114  // Reduce false anti-dependencies to let the target's out-of-order execution
2115  // engine do its thing.
2116  return Subtarget.isProfitableToUnpredicate();
2117}
2118
2119/// getInstrPredicate - If instruction is predicated, returns its predicate
2120/// condition, otherwise returns AL. It also returns the condition code
2121/// register by reference.
2122ARMCC::CondCodes llvm::getInstrPredicate(const MachineInstr &MI,
2123                                         unsigned &PredReg) {
2124  int PIdx = MI.findFirstPredOperandIdx();
2125  if (PIdx == -1) {
2126    PredReg = 0;
2127    return ARMCC::AL;
2128  }
2129
2130  PredReg = MI.getOperand(PIdx+1).getReg();
2131  return (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
2132}
2133
2134unsigned llvm::getMatchingCondBranchOpcode(unsigned Opc) {
2135  if (Opc == ARM::B)
2136    return ARM::Bcc;
2137  if (Opc == ARM::tB)
2138    return ARM::tBcc;
2139  if (Opc == ARM::t2B)
2140    return ARM::t2Bcc;
2141
2142  llvm_unreachable("Unknown unconditional branch opcode!");
2143}
2144
2145MachineInstr *ARMBaseInstrInfo::commuteInstructionImpl(MachineInstr &MI,
2146                                                       bool NewMI,
2147                                                       unsigned OpIdx1,
2148                                                       unsigned OpIdx2) const {
2149  switch (MI.getOpcode()) {
2150  case ARM::MOVCCr:
2151  case ARM::t2MOVCCr: {
2152    // MOVCC can be commuted by inverting the condition.
2153    unsigned PredReg = 0;
2154    ARMCC::CondCodes CC = getInstrPredicate(MI, PredReg);
2155    // MOVCC AL can't be inverted. Shouldn't happen.
2156    if (CC == ARMCC::AL || PredReg != ARM::CPSR)
2157      return nullptr;
2158    MachineInstr *CommutedMI =
2159        TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
2160    if (!CommutedMI)
2161      return nullptr;
2162    // After swapping the MOVCC operands, also invert the condition.
2163    CommutedMI->getOperand(CommutedMI->findFirstPredOperandIdx())
2164        .setImm(ARMCC::getOppositeCondition(CC));
2165    return CommutedMI;
2166  }
2167  }
2168  return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
2169}
2170
2171/// Identify instructions that can be folded into a MOVCC instruction, and
2172/// return the defining instruction.
2173MachineInstr *
2174ARMBaseInstrInfo::canFoldIntoMOVCC(unsigned Reg, const MachineRegisterInfo &MRI,
2175                                   const TargetInstrInfo *TII) const {
2176  if (!Register::isVirtualRegister(Reg))
2177    return nullptr;
2178  if (!MRI.hasOneNonDBGUse(Reg))
2179    return nullptr;
2180  MachineInstr *MI = MRI.getVRegDef(Reg);
2181  if (!MI)
2182    return nullptr;
2183  // Check if MI can be predicated and folded into the MOVCC.
2184  if (!isPredicable(*MI))
2185    return nullptr;
2186  // Check if MI has any non-dead defs or physreg uses. This also detects
2187  // predicated instructions which will be reading CPSR.
2188  for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
2189    const MachineOperand &MO = MI->getOperand(i);
2190    // Reject frame index operands, PEI can't handle the predicated pseudos.
2191    if (MO.isFI() || MO.isCPI() || MO.isJTI())
2192      return nullptr;
2193    if (!MO.isReg())
2194      continue;
2195    // MI can't have any tied operands, that would conflict with predication.
2196    if (MO.isTied())
2197      return nullptr;
2198    if (Register::isPhysicalRegister(MO.getReg()))
2199      return nullptr;
2200    if (MO.isDef() && !MO.isDead())
2201      return nullptr;
2202  }
2203  bool DontMoveAcrossStores = true;
2204  if (!MI->isSafeToMove(/* AliasAnalysis = */ nullptr, DontMoveAcrossStores))
2205    return nullptr;
2206  return MI;
2207}
2208
2209bool ARMBaseInstrInfo::analyzeSelect(const MachineInstr &MI,
2210                                     SmallVectorImpl<MachineOperand> &Cond,
2211                                     unsigned &TrueOp, unsigned &FalseOp,
2212                                     bool &Optimizable) const {
2213  assert((MI.getOpcode() == ARM::MOVCCr || MI.getOpcode() == ARM::t2MOVCCr) &&
2214         "Unknown select instruction");
2215  // MOVCC operands:
2216  // 0: Def.
2217  // 1: True use.
2218  // 2: False use.
2219  // 3: Condition code.
2220  // 4: CPSR use.
2221  TrueOp = 1;
2222  FalseOp = 2;
2223  Cond.push_back(MI.getOperand(3));
2224  Cond.push_back(MI.getOperand(4));
2225  // We can always fold a def.
2226  Optimizable = true;
2227  return false;
2228}
2229
2230MachineInstr *
2231ARMBaseInstrInfo::optimizeSelect(MachineInstr &MI,
2232                                 SmallPtrSetImpl<MachineInstr *> &SeenMIs,
2233                                 bool PreferFalse) const {
2234  assert((MI.getOpcode() == ARM::MOVCCr || MI.getOpcode() == ARM::t2MOVCCr) &&
2235         "Unknown select instruction");
2236  MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
2237  MachineInstr *DefMI = canFoldIntoMOVCC(MI.getOperand(2).getReg(), MRI, this);
2238  bool Invert = !DefMI;
2239  if (!DefMI)
2240    DefMI = canFoldIntoMOVCC(MI.getOperand(1).getReg(), MRI, this);
2241  if (!DefMI)
2242    return nullptr;
2243
2244  // Find new register class to use.
2245  MachineOperand FalseReg = MI.getOperand(Invert ? 2 : 1);
2246  Register DestReg = MI.getOperand(0).getReg();
2247  const TargetRegisterClass *PreviousClass = MRI.getRegClass(FalseReg.getReg());
2248  if (!MRI.constrainRegClass(DestReg, PreviousClass))
2249    return nullptr;
2250
2251  // Create a new predicated version of DefMI.
2252  // Rfalse is the first use.
2253  MachineInstrBuilder NewMI =
2254      BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), DefMI->getDesc(), DestReg);
2255
2256  // Copy all the DefMI operands, excluding its (null) predicate.
2257  const MCInstrDesc &DefDesc = DefMI->getDesc();
2258  for (unsigned i = 1, e = DefDesc.getNumOperands();
2259       i != e && !DefDesc.OpInfo[i].isPredicate(); ++i)
2260    NewMI.add(DefMI->getOperand(i));
2261
2262  unsigned CondCode = MI.getOperand(3).getImm();
2263  if (Invert)
2264    NewMI.addImm(ARMCC::getOppositeCondition(ARMCC::CondCodes(CondCode)));
2265  else
2266    NewMI.addImm(CondCode);
2267  NewMI.add(MI.getOperand(4));
2268
2269  // DefMI is not the -S version that sets CPSR, so add an optional %noreg.
2270  if (NewMI->hasOptionalDef())
2271    NewMI.add(condCodeOp());
2272
2273  // The output register value when the predicate is false is an implicit
2274  // register operand tied to the first def.
2275  // The tie makes the register allocator ensure the FalseReg is allocated the
2276  // same register as operand 0.
2277  FalseReg.setImplicit();
2278  NewMI.add(FalseReg);
2279  NewMI->tieOperands(0, NewMI->getNumOperands() - 1);
2280
2281  // Update SeenMIs set: register newly created MI and erase removed DefMI.
2282  SeenMIs.insert(NewMI);
2283  SeenMIs.erase(DefMI);
2284
2285  // If MI is inside a loop, and DefMI is outside the loop, then kill flags on
2286  // DefMI would be invalid when tranferred inside the loop.  Checking for a
2287  // loop is expensive, but at least remove kill flags if they are in different
2288  // BBs.
2289  if (DefMI->getParent() != MI.getParent())
2290    NewMI->clearKillInfo();
2291
2292  // The caller will erase MI, but not DefMI.
2293  DefMI->eraseFromParent();
2294  return NewMI;
2295}
2296
2297/// Map pseudo instructions that imply an 'S' bit onto real opcodes. Whether the
2298/// instruction is encoded with an 'S' bit is determined by the optional CPSR
2299/// def operand.
2300///
2301/// This will go away once we can teach tblgen how to set the optional CPSR def
2302/// operand itself.
2303struct AddSubFlagsOpcodePair {
2304  uint16_t PseudoOpc;
2305  uint16_t MachineOpc;
2306};
2307
2308static const AddSubFlagsOpcodePair AddSubFlagsOpcodeMap[] = {
2309  {ARM::ADDSri, ARM::ADDri},
2310  {ARM::ADDSrr, ARM::ADDrr},
2311  {ARM::ADDSrsi, ARM::ADDrsi},
2312  {ARM::ADDSrsr, ARM::ADDrsr},
2313
2314  {ARM::SUBSri, ARM::SUBri},
2315  {ARM::SUBSrr, ARM::SUBrr},
2316  {ARM::SUBSrsi, ARM::SUBrsi},
2317  {ARM::SUBSrsr, ARM::SUBrsr},
2318
2319  {ARM::RSBSri, ARM::RSBri},
2320  {ARM::RSBSrsi, ARM::RSBrsi},
2321  {ARM::RSBSrsr, ARM::RSBrsr},
2322
2323  {ARM::tADDSi3, ARM::tADDi3},
2324  {ARM::tADDSi8, ARM::tADDi8},
2325  {ARM::tADDSrr, ARM::tADDrr},
2326  {ARM::tADCS, ARM::tADC},
2327
2328  {ARM::tSUBSi3, ARM::tSUBi3},
2329  {ARM::tSUBSi8, ARM::tSUBi8},
2330  {ARM::tSUBSrr, ARM::tSUBrr},
2331  {ARM::tSBCS, ARM::tSBC},
2332  {ARM::tRSBS, ARM::tRSB},
2333  {ARM::tLSLSri, ARM::tLSLri},
2334
2335  {ARM::t2ADDSri, ARM::t2ADDri},
2336  {ARM::t2ADDSrr, ARM::t2ADDrr},
2337  {ARM::t2ADDSrs, ARM::t2ADDrs},
2338
2339  {ARM::t2SUBSri, ARM::t2SUBri},
2340  {ARM::t2SUBSrr, ARM::t2SUBrr},
2341  {ARM::t2SUBSrs, ARM::t2SUBrs},
2342
2343  {ARM::t2RSBSri, ARM::t2RSBri},
2344  {ARM::t2RSBSrs, ARM::t2RSBrs},
2345};
2346
2347unsigned llvm::convertAddSubFlagsOpcode(unsigned OldOpc) {
2348  for (unsigned i = 0, e = array_lengthof(AddSubFlagsOpcodeMap); i != e; ++i)
2349    if (OldOpc == AddSubFlagsOpcodeMap[i].PseudoOpc)
2350      return AddSubFlagsOpcodeMap[i].MachineOpc;
2351  return 0;
2352}
2353
2354void llvm::emitARMRegPlusImmediate(MachineBasicBlock &MBB,
2355                                   MachineBasicBlock::iterator &MBBI,
2356                                   const DebugLoc &dl, unsigned DestReg,
2357                                   unsigned BaseReg, int NumBytes,
2358                                   ARMCC::CondCodes Pred, unsigned PredReg,
2359                                   const ARMBaseInstrInfo &TII,
2360                                   unsigned MIFlags) {
2361  if (NumBytes == 0 && DestReg != BaseReg) {
2362    BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), DestReg)
2363        .addReg(BaseReg, RegState::Kill)
2364        .add(predOps(Pred, PredReg))
2365        .add(condCodeOp())
2366        .setMIFlags(MIFlags);
2367    return;
2368  }
2369
2370  bool isSub = NumBytes < 0;
2371  if (isSub) NumBytes = -NumBytes;
2372
2373  while (NumBytes) {
2374    unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
2375    unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
2376    assert(ThisVal && "Didn't extract field correctly");
2377
2378    // We will handle these bits from offset, clear them.
2379    NumBytes &= ~ThisVal;
2380
2381    assert(ARM_AM::getSOImmVal(ThisVal) != -1 && "Bit extraction didn't work?");
2382
2383    // Build the new ADD / SUB.
2384    unsigned Opc = isSub ? ARM::SUBri : ARM::ADDri;
2385    BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg)
2386        .addReg(BaseReg, RegState::Kill)
2387        .addImm(ThisVal)
2388        .add(predOps(Pred, PredReg))
2389        .add(condCodeOp())
2390        .setMIFlags(MIFlags);
2391    BaseReg = DestReg;
2392  }
2393}
2394
2395bool llvm::tryFoldSPUpdateIntoPushPop(const ARMSubtarget &Subtarget,
2396                                      MachineFunction &MF, MachineInstr *MI,
2397                                      unsigned NumBytes) {
2398  // This optimisation potentially adds lots of load and store
2399  // micro-operations, it's only really a great benefit to code-size.
2400  if (!Subtarget.hasMinSize())
2401    return false;
2402
2403  // If only one register is pushed/popped, LLVM can use an LDR/STR
2404  // instead. We can't modify those so make sure we're dealing with an
2405  // instruction we understand.
2406  bool IsPop = isPopOpcode(MI->getOpcode());
2407  bool IsPush = isPushOpcode(MI->getOpcode());
2408  if (!IsPush && !IsPop)
2409    return false;
2410
2411  bool IsVFPPushPop = MI->getOpcode() == ARM::VSTMDDB_UPD ||
2412                      MI->getOpcode() == ARM::VLDMDIA_UPD;
2413  bool IsT1PushPop = MI->getOpcode() == ARM::tPUSH ||
2414                     MI->getOpcode() == ARM::tPOP ||
2415                     MI->getOpcode() == ARM::tPOP_RET;
2416
2417  assert((IsT1PushPop || (MI->getOperand(0).getReg() == ARM::SP &&
2418                          MI->getOperand(1).getReg() == ARM::SP)) &&
2419         "trying to fold sp update into non-sp-updating push/pop");
2420
2421  // The VFP push & pop act on D-registers, so we can only fold an adjustment
2422  // by a multiple of 8 bytes in correctly. Similarly rN is 4-bytes. Don't try
2423  // if this is violated.
2424  if (NumBytes % (IsVFPPushPop ? 8 : 4) != 0)
2425    return false;
2426
2427  // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
2428  // pred) so the list starts at 4. Thumb1 starts after the predicate.
2429  int RegListIdx = IsT1PushPop ? 2 : 4;
2430
2431  // Calculate the space we'll need in terms of registers.
2432  unsigned RegsNeeded;
2433  const TargetRegisterClass *RegClass;
2434  if (IsVFPPushPop) {
2435    RegsNeeded = NumBytes / 8;
2436    RegClass = &ARM::DPRRegClass;
2437  } else {
2438    RegsNeeded = NumBytes / 4;
2439    RegClass = &ARM::GPRRegClass;
2440  }
2441
2442  // We're going to have to strip all list operands off before
2443  // re-adding them since the order matters, so save the existing ones
2444  // for later.
2445  SmallVector<MachineOperand, 4> RegList;
2446
2447  // We're also going to need the first register transferred by this
2448  // instruction, which won't necessarily be the first register in the list.
2449  unsigned FirstRegEnc = -1;
2450
2451  const TargetRegisterInfo *TRI = MF.getRegInfo().getTargetRegisterInfo();
2452  for (int i = MI->getNumOperands() - 1; i >= RegListIdx; --i) {
2453    MachineOperand &MO = MI->getOperand(i);
2454    RegList.push_back(MO);
2455
2456    if (MO.isReg() && !MO.isImplicit() &&
2457        TRI->getEncodingValue(MO.getReg()) < FirstRegEnc)
2458      FirstRegEnc = TRI->getEncodingValue(MO.getReg());
2459  }
2460
2461  const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF);
2462
2463  // Now try to find enough space in the reglist to allocate NumBytes.
2464  for (int CurRegEnc = FirstRegEnc - 1; CurRegEnc >= 0 && RegsNeeded;
2465       --CurRegEnc) {
2466    unsigned CurReg = RegClass->getRegister(CurRegEnc);
2467    if (IsT1PushPop && CurRegEnc > TRI->getEncodingValue(ARM::R7))
2468      continue;
2469    if (!IsPop) {
2470      // Pushing any register is completely harmless, mark the register involved
2471      // as undef since we don't care about its value and must not restore it
2472      // during stack unwinding.
2473      RegList.push_back(MachineOperand::CreateReg(CurReg, false, false,
2474                                                  false, false, true));
2475      --RegsNeeded;
2476      continue;
2477    }
2478
2479    // However, we can only pop an extra register if it's not live. For
2480    // registers live within the function we might clobber a return value
2481    // register; the other way a register can be live here is if it's
2482    // callee-saved.
2483    if (isCalleeSavedRegister(CurReg, CSRegs) ||
2484        MI->getParent()->computeRegisterLiveness(TRI, CurReg, MI) !=
2485        MachineBasicBlock::LQR_Dead) {
2486      // VFP pops don't allow holes in the register list, so any skip is fatal
2487      // for our transformation. GPR pops do, so we should just keep looking.
2488      if (IsVFPPushPop)
2489        return false;
2490      else
2491        continue;
2492    }
2493
2494    // Mark the unimportant registers as <def,dead> in the POP.
2495    RegList.push_back(MachineOperand::CreateReg(CurReg, true, false, false,
2496                                                true));
2497    --RegsNeeded;
2498  }
2499
2500  if (RegsNeeded > 0)
2501    return false;
2502
2503  // Finally we know we can profitably perform the optimisation so go
2504  // ahead: strip all existing registers off and add them back again
2505  // in the right order.
2506  for (int i = MI->getNumOperands() - 1; i >= RegListIdx; --i)
2507    MI->RemoveOperand(i);
2508
2509  // Add the complete list back in.
2510  MachineInstrBuilder MIB(MF, &*MI);
2511  for (int i = RegList.size() - 1; i >= 0; --i)
2512    MIB.add(RegList[i]);
2513
2514  return true;
2515}
2516
2517bool llvm::rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
2518                                unsigned FrameReg, int &Offset,
2519                                const ARMBaseInstrInfo &TII) {
2520  unsigned Opcode = MI.getOpcode();
2521  const MCInstrDesc &Desc = MI.getDesc();
2522  unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
2523  bool isSub = false;
2524
2525  // Memory operands in inline assembly always use AddrMode2.
2526  if (Opcode == ARM::INLINEASM || Opcode == ARM::INLINEASM_BR)
2527    AddrMode = ARMII::AddrMode2;
2528
2529  if (Opcode == ARM::ADDri) {
2530    Offset += MI.getOperand(FrameRegIdx+1).getImm();
2531    if (Offset == 0) {
2532      // Turn it into a move.
2533      MI.setDesc(TII.get(ARM::MOVr));
2534      MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
2535      MI.RemoveOperand(FrameRegIdx+1);
2536      Offset = 0;
2537      return true;
2538    } else if (Offset < 0) {
2539      Offset = -Offset;
2540      isSub = true;
2541      MI.setDesc(TII.get(ARM::SUBri));
2542    }
2543
2544    // Common case: small offset, fits into instruction.
2545    if (ARM_AM::getSOImmVal(Offset) != -1) {
2546      // Replace the FrameIndex with sp / fp
2547      MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
2548      MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset);
2549      Offset = 0;
2550      return true;
2551    }
2552
2553    // Otherwise, pull as much of the immedidate into this ADDri/SUBri
2554    // as possible.
2555    unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
2556    unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
2557
2558    // We will handle these bits from offset, clear them.
2559    Offset &= ~ThisImmVal;
2560
2561    // Get the properly encoded SOImmVal field.
2562    assert(ARM_AM::getSOImmVal(ThisImmVal) != -1 &&
2563           "Bit extraction didn't work?");
2564    MI.getOperand(FrameRegIdx+1).ChangeToImmediate(ThisImmVal);
2565 } else {
2566    unsigned ImmIdx = 0;
2567    int InstrOffs = 0;
2568    unsigned NumBits = 0;
2569    unsigned Scale = 1;
2570    switch (AddrMode) {
2571    case ARMII::AddrMode_i12:
2572      ImmIdx = FrameRegIdx + 1;
2573      InstrOffs = MI.getOperand(ImmIdx).getImm();
2574      NumBits = 12;
2575      break;
2576    case ARMII::AddrMode2:
2577      ImmIdx = FrameRegIdx+2;
2578      InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
2579      if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
2580        InstrOffs *= -1;
2581      NumBits = 12;
2582      break;
2583    case ARMII::AddrMode3:
2584      ImmIdx = FrameRegIdx+2;
2585      InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
2586      if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
2587        InstrOffs *= -1;
2588      NumBits = 8;
2589      break;
2590    case ARMII::AddrMode4:
2591    case ARMII::AddrMode6:
2592      // Can't fold any offset even if it's zero.
2593      return false;
2594    case ARMII::AddrMode5:
2595      ImmIdx = FrameRegIdx+1;
2596      InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
2597      if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
2598        InstrOffs *= -1;
2599      NumBits = 8;
2600      Scale = 4;
2601      break;
2602    case ARMII::AddrMode5FP16:
2603      ImmIdx = FrameRegIdx+1;
2604      InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
2605      if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
2606        InstrOffs *= -1;
2607      NumBits = 8;
2608      Scale = 2;
2609      break;
2610    case ARMII::AddrModeT2_i7:
2611    case ARMII::AddrModeT2_i7s2:
2612    case ARMII::AddrModeT2_i7s4:
2613      ImmIdx = FrameRegIdx+1;
2614      InstrOffs = MI.getOperand(ImmIdx).getImm();
2615      NumBits = 7;
2616      Scale = (AddrMode == ARMII::AddrModeT2_i7s2 ? 2 :
2617               AddrMode == ARMII::AddrModeT2_i7s4 ? 4 : 1);
2618      break;
2619    default:
2620      llvm_unreachable("Unsupported addressing mode!");
2621    }
2622
2623    Offset += InstrOffs * Scale;
2624    assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
2625    if (Offset < 0) {
2626      Offset = -Offset;
2627      isSub = true;
2628    }
2629
2630    // Attempt to fold address comp. if opcode has offset bits
2631    if (NumBits > 0) {
2632      // Common case: small offset, fits into instruction.
2633      MachineOperand &ImmOp = MI.getOperand(ImmIdx);
2634      int ImmedOffset = Offset / Scale;
2635      unsigned Mask = (1 << NumBits) - 1;
2636      if ((unsigned)Offset <= Mask * Scale) {
2637        // Replace the FrameIndex with sp
2638        MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
2639        // FIXME: When addrmode2 goes away, this will simplify (like the
2640        // T2 version), as the LDR.i12 versions don't need the encoding
2641        // tricks for the offset value.
2642        if (isSub) {
2643          if (AddrMode == ARMII::AddrMode_i12)
2644            ImmedOffset = -ImmedOffset;
2645          else
2646            ImmedOffset |= 1 << NumBits;
2647        }
2648        ImmOp.ChangeToImmediate(ImmedOffset);
2649        Offset = 0;
2650        return true;
2651      }
2652
2653      // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
2654      ImmedOffset = ImmedOffset & Mask;
2655      if (isSub) {
2656        if (AddrMode == ARMII::AddrMode_i12)
2657          ImmedOffset = -ImmedOffset;
2658        else
2659          ImmedOffset |= 1 << NumBits;
2660      }
2661      ImmOp.ChangeToImmediate(ImmedOffset);
2662      Offset &= ~(Mask*Scale);
2663    }
2664  }
2665
2666  Offset = (isSub) ? -Offset : Offset;
2667  return Offset == 0;
2668}
2669
2670/// analyzeCompare - For a comparison instruction, return the source registers
2671/// in SrcReg and SrcReg2 if having two register operands, and the value it
2672/// compares against in CmpValue. Return true if the comparison instruction
2673/// can be analyzed.
2674bool ARMBaseInstrInfo::analyzeCompare(const MachineInstr &MI, unsigned &SrcReg,
2675                                      unsigned &SrcReg2, int &CmpMask,
2676                                      int &CmpValue) const {
2677  switch (MI.getOpcode()) {
2678  default: break;
2679  case ARM::CMPri:
2680  case ARM::t2CMPri:
2681  case ARM::tCMPi8:
2682    SrcReg = MI.getOperand(0).getReg();
2683    SrcReg2 = 0;
2684    CmpMask = ~0;
2685    CmpValue = MI.getOperand(1).getImm();
2686    return true;
2687  case ARM::CMPrr:
2688  case ARM::t2CMPrr:
2689  case ARM::tCMPr:
2690    SrcReg = MI.getOperand(0).getReg();
2691    SrcReg2 = MI.getOperand(1).getReg();
2692    CmpMask = ~0;
2693    CmpValue = 0;
2694    return true;
2695  case ARM::TSTri:
2696  case ARM::t2TSTri:
2697    SrcReg = MI.getOperand(0).getReg();
2698    SrcReg2 = 0;
2699    CmpMask = MI.getOperand(1).getImm();
2700    CmpValue = 0;
2701    return true;
2702  }
2703
2704  return false;
2705}
2706
2707/// isSuitableForMask - Identify a suitable 'and' instruction that
2708/// operates on the given source register and applies the same mask
2709/// as a 'tst' instruction. Provide a limited look-through for copies.
2710/// When successful, MI will hold the found instruction.
2711static bool isSuitableForMask(MachineInstr *&MI, unsigned SrcReg,
2712                              int CmpMask, bool CommonUse) {
2713  switch (MI->getOpcode()) {
2714    case ARM::ANDri:
2715    case ARM::t2ANDri:
2716      if (CmpMask != MI->getOperand(2).getImm())
2717        return false;
2718      if (SrcReg == MI->getOperand(CommonUse ? 1 : 0).getReg())
2719        return true;
2720      break;
2721  }
2722
2723  return false;
2724}
2725
2726/// getCmpToAddCondition - assume the flags are set by CMP(a,b), return
2727/// the condition code if we modify the instructions such that flags are
2728/// set by ADD(a,b,X).
2729inline static ARMCC::CondCodes getCmpToAddCondition(ARMCC::CondCodes CC) {
2730  switch (CC) {
2731  default: return ARMCC::AL;
2732  case ARMCC::HS: return ARMCC::LO;
2733  case ARMCC::LO: return ARMCC::HS;
2734  case ARMCC::VS: return ARMCC::VS;
2735  case ARMCC::VC: return ARMCC::VC;
2736  }
2737}
2738
2739/// isRedundantFlagInstr - check whether the first instruction, whose only
2740/// purpose is to update flags, can be made redundant.
2741/// CMPrr can be made redundant by SUBrr if the operands are the same.
2742/// CMPri can be made redundant by SUBri if the operands are the same.
2743/// CMPrr(r0, r1) can be made redundant by ADDr[ri](r0, r1, X).
2744/// This function can be extended later on.
2745inline static bool isRedundantFlagInstr(const MachineInstr *CmpI,
2746                                        unsigned SrcReg, unsigned SrcReg2,
2747                                        int ImmValue, const MachineInstr *OI,
2748                                        bool &IsThumb1) {
2749  if ((CmpI->getOpcode() == ARM::CMPrr || CmpI->getOpcode() == ARM::t2CMPrr) &&
2750      (OI->getOpcode() == ARM::SUBrr || OI->getOpcode() == ARM::t2SUBrr) &&
2751      ((OI->getOperand(1).getReg() == SrcReg &&
2752        OI->getOperand(2).getReg() == SrcReg2) ||
2753       (OI->getOperand(1).getReg() == SrcReg2 &&
2754        OI->getOperand(2).getReg() == SrcReg))) {
2755    IsThumb1 = false;
2756    return true;
2757  }
2758
2759  if (CmpI->getOpcode() == ARM::tCMPr && OI->getOpcode() == ARM::tSUBrr &&
2760      ((OI->getOperand(2).getReg() == SrcReg &&
2761        OI->getOperand(3).getReg() == SrcReg2) ||
2762       (OI->getOperand(2).getReg() == SrcReg2 &&
2763        OI->getOperand(3).getReg() == SrcReg))) {
2764    IsThumb1 = true;
2765    return true;
2766  }
2767
2768  if ((CmpI->getOpcode() == ARM::CMPri || CmpI->getOpcode() == ARM::t2CMPri) &&
2769      (OI->getOpcode() == ARM::SUBri || OI->getOpcode() == ARM::t2SUBri) &&
2770      OI->getOperand(1).getReg() == SrcReg &&
2771      OI->getOperand(2).getImm() == ImmValue) {
2772    IsThumb1 = false;
2773    return true;
2774  }
2775
2776  if (CmpI->getOpcode() == ARM::tCMPi8 &&
2777      (OI->getOpcode() == ARM::tSUBi8 || OI->getOpcode() == ARM::tSUBi3) &&
2778      OI->getOperand(2).getReg() == SrcReg &&
2779      OI->getOperand(3).getImm() == ImmValue) {
2780    IsThumb1 = true;
2781    return true;
2782  }
2783
2784  if ((CmpI->getOpcode() == ARM::CMPrr || CmpI->getOpcode() == ARM::t2CMPrr) &&
2785      (OI->getOpcode() == ARM::ADDrr || OI->getOpcode() == ARM::t2ADDrr ||
2786       OI->getOpcode() == ARM::ADDri || OI->getOpcode() == ARM::t2ADDri) &&
2787      OI->getOperand(0).isReg() && OI->getOperand(1).isReg() &&
2788      OI->getOperand(0).getReg() == SrcReg &&
2789      OI->getOperand(1).getReg() == SrcReg2) {
2790    IsThumb1 = false;
2791    return true;
2792  }
2793
2794  if (CmpI->getOpcode() == ARM::tCMPr &&
2795      (OI->getOpcode() == ARM::tADDi3 || OI->getOpcode() == ARM::tADDi8 ||
2796       OI->getOpcode() == ARM::tADDrr) &&
2797      OI->getOperand(0).getReg() == SrcReg &&
2798      OI->getOperand(2).getReg() == SrcReg2) {
2799    IsThumb1 = true;
2800    return true;
2801  }
2802
2803  return false;
2804}
2805
2806static bool isOptimizeCompareCandidate(MachineInstr *MI, bool &IsThumb1) {
2807  switch (MI->getOpcode()) {
2808  default: return false;
2809  case ARM::tLSLri:
2810  case ARM::tLSRri:
2811  case ARM::tLSLrr:
2812  case ARM::tLSRrr:
2813  case ARM::tSUBrr:
2814  case ARM::tADDrr:
2815  case ARM::tADDi3:
2816  case ARM::tADDi8:
2817  case ARM::tSUBi3:
2818  case ARM::tSUBi8:
2819  case ARM::tMUL:
2820  case ARM::tADC:
2821  case ARM::tSBC:
2822  case ARM::tRSB:
2823  case ARM::tAND:
2824  case ARM::tORR:
2825  case ARM::tEOR:
2826  case ARM::tBIC:
2827  case ARM::tMVN:
2828  case ARM::tASRri:
2829  case ARM::tASRrr:
2830  case ARM::tROR:
2831    IsThumb1 = true;
2832    LLVM_FALLTHROUGH;
2833  case ARM::RSBrr:
2834  case ARM::RSBri:
2835  case ARM::RSCrr:
2836  case ARM::RSCri:
2837  case ARM::ADDrr:
2838  case ARM::ADDri:
2839  case ARM::ADCrr:
2840  case ARM::ADCri:
2841  case ARM::SUBrr:
2842  case ARM::SUBri:
2843  case ARM::SBCrr:
2844  case ARM::SBCri:
2845  case ARM::t2RSBri:
2846  case ARM::t2ADDrr:
2847  case ARM::t2ADDri:
2848  case ARM::t2ADCrr:
2849  case ARM::t2ADCri:
2850  case ARM::t2SUBrr:
2851  case ARM::t2SUBri:
2852  case ARM::t2SBCrr:
2853  case ARM::t2SBCri:
2854  case ARM::ANDrr:
2855  case ARM::ANDri:
2856  case ARM::t2ANDrr:
2857  case ARM::t2ANDri:
2858  case ARM::ORRrr:
2859  case ARM::ORRri:
2860  case ARM::t2ORRrr:
2861  case ARM::t2ORRri:
2862  case ARM::EORrr:
2863  case ARM::EORri:
2864  case ARM::t2EORrr:
2865  case ARM::t2EORri:
2866  case ARM::t2LSRri:
2867  case ARM::t2LSRrr:
2868  case ARM::t2LSLri:
2869  case ARM::t2LSLrr:
2870    return true;
2871  }
2872}
2873
2874/// optimizeCompareInstr - Convert the instruction supplying the argument to the
2875/// comparison into one that sets the zero bit in the flags register;
2876/// Remove a redundant Compare instruction if an earlier instruction can set the
2877/// flags in the same way as Compare.
2878/// E.g. SUBrr(r1,r2) and CMPrr(r1,r2). We also handle the case where two
2879/// operands are swapped: SUBrr(r1,r2) and CMPrr(r2,r1), by updating the
2880/// condition code of instructions which use the flags.
2881bool ARMBaseInstrInfo::optimizeCompareInstr(
2882    MachineInstr &CmpInstr, unsigned SrcReg, unsigned SrcReg2, int CmpMask,
2883    int CmpValue, const MachineRegisterInfo *MRI) const {
2884  // Get the unique definition of SrcReg.
2885  MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
2886  if (!MI) return false;
2887
2888  // Masked compares sometimes use the same register as the corresponding 'and'.
2889  if (CmpMask != ~0) {
2890    if (!isSuitableForMask(MI, SrcReg, CmpMask, false) || isPredicated(*MI)) {
2891      MI = nullptr;
2892      for (MachineRegisterInfo::use_instr_iterator
2893           UI = MRI->use_instr_begin(SrcReg), UE = MRI->use_instr_end();
2894           UI != UE; ++UI) {
2895        if (UI->getParent() != CmpInstr.getParent())
2896          continue;
2897        MachineInstr *PotentialAND = &*UI;
2898        if (!isSuitableForMask(PotentialAND, SrcReg, CmpMask, true) ||
2899            isPredicated(*PotentialAND))
2900          continue;
2901        MI = PotentialAND;
2902        break;
2903      }
2904      if (!MI) return false;
2905    }
2906  }
2907
2908  // Get ready to iterate backward from CmpInstr.
2909  MachineBasicBlock::iterator I = CmpInstr, E = MI,
2910                              B = CmpInstr.getParent()->begin();
2911
2912  // Early exit if CmpInstr is at the beginning of the BB.
2913  if (I == B) return false;
2914
2915  // There are two possible candidates which can be changed to set CPSR:
2916  // One is MI, the other is a SUB or ADD instruction.
2917  // For CMPrr(r1,r2), we are looking for SUB(r1,r2), SUB(r2,r1), or
2918  // ADDr[ri](r1, r2, X).
2919  // For CMPri(r1, CmpValue), we are looking for SUBri(r1, CmpValue).
2920  MachineInstr *SubAdd = nullptr;
2921  if (SrcReg2 != 0)
2922    // MI is not a candidate for CMPrr.
2923    MI = nullptr;
2924  else if (MI->getParent() != CmpInstr.getParent() || CmpValue != 0) {
2925    // Conservatively refuse to convert an instruction which isn't in the same
2926    // BB as the comparison.
2927    // For CMPri w/ CmpValue != 0, a SubAdd may still be a candidate.
2928    // Thus we cannot return here.
2929    if (CmpInstr.getOpcode() == ARM::CMPri ||
2930        CmpInstr.getOpcode() == ARM::t2CMPri ||
2931        CmpInstr.getOpcode() == ARM::tCMPi8)
2932      MI = nullptr;
2933    else
2934      return false;
2935  }
2936
2937  bool IsThumb1 = false;
2938  if (MI && !isOptimizeCompareCandidate(MI, IsThumb1))
2939    return false;
2940
2941  // We also want to do this peephole for cases like this: if (a*b == 0),
2942  // and optimise away the CMP instruction from the generated code sequence:
2943  // MULS, MOVS, MOVS, CMP. Here the MOVS instructions load the boolean values
2944  // resulting from the select instruction, but these MOVS instructions for
2945  // Thumb1 (V6M) are flag setting and are thus preventing this optimisation.
2946  // However, if we only have MOVS instructions in between the CMP and the
2947  // other instruction (the MULS in this example), then the CPSR is dead so we
2948  // can safely reorder the sequence into: MOVS, MOVS, MULS, CMP. We do this
2949  // reordering and then continue the analysis hoping we can eliminate the
2950  // CMP. This peephole works on the vregs, so is still in SSA form. As a
2951  // consequence, the movs won't redefine/kill the MUL operands which would
2952  // make this reordering illegal.
2953  const TargetRegisterInfo *TRI = &getRegisterInfo();
2954  if (MI && IsThumb1) {
2955    --I;
2956    if (I != E && !MI->readsRegister(ARM::CPSR, TRI)) {
2957      bool CanReorder = true;
2958      for (; I != E; --I) {
2959        if (I->getOpcode() != ARM::tMOVi8) {
2960          CanReorder = false;
2961          break;
2962        }
2963      }
2964      if (CanReorder) {
2965        MI = MI->removeFromParent();
2966        E = CmpInstr;
2967        CmpInstr.getParent()->insert(E, MI);
2968      }
2969    }
2970    I = CmpInstr;
2971    E = MI;
2972  }
2973
2974  // Check that CPSR isn't set between the comparison instruction and the one we
2975  // want to change. At the same time, search for SubAdd.
2976  bool SubAddIsThumb1 = false;
2977  do {
2978    const MachineInstr &Instr = *--I;
2979
2980    // Check whether CmpInstr can be made redundant by the current instruction.
2981    if (isRedundantFlagInstr(&CmpInstr, SrcReg, SrcReg2, CmpValue, &Instr,
2982                             SubAddIsThumb1)) {
2983      SubAdd = &*I;
2984      break;
2985    }
2986
2987    // Allow E (which was initially MI) to be SubAdd but do not search before E.
2988    if (I == E)
2989      break;
2990
2991    if (Instr.modifiesRegister(ARM::CPSR, TRI) ||
2992        Instr.readsRegister(ARM::CPSR, TRI))
2993      // This instruction modifies or uses CPSR after the one we want to
2994      // change. We can't do this transformation.
2995      return false;
2996
2997    if (I == B) {
2998      // In some cases, we scan the use-list of an instruction for an AND;
2999      // that AND is in the same BB, but may not be scheduled before the
3000      // corresponding TST.  In that case, bail out.
3001      //
3002      // FIXME: We could try to reschedule the AND.
3003      return false;
3004    }
3005  } while (true);
3006
3007  // Return false if no candidates exist.
3008  if (!MI && !SubAdd)
3009    return false;
3010
3011  // If we found a SubAdd, use it as it will be closer to the CMP
3012  if (SubAdd) {
3013    MI = SubAdd;
3014    IsThumb1 = SubAddIsThumb1;
3015  }
3016
3017  // We can't use a predicated instruction - it doesn't always write the flags.
3018  if (isPredicated(*MI))
3019    return false;
3020
3021  // Scan forward for the use of CPSR
3022  // When checking against MI: if it's a conditional code that requires
3023  // checking of the V bit or C bit, then this is not safe to do.
3024  // It is safe to remove CmpInstr if CPSR is redefined or killed.
3025  // If we are done with the basic block, we need to check whether CPSR is
3026  // live-out.
3027  SmallVector<std::pair<MachineOperand*, ARMCC::CondCodes>, 4>
3028      OperandsToUpdate;
3029  bool isSafe = false;
3030  I = CmpInstr;
3031  E = CmpInstr.getParent()->end();
3032  while (!isSafe && ++I != E) {
3033    const MachineInstr &Instr = *I;
3034    for (unsigned IO = 0, EO = Instr.getNumOperands();
3035         !isSafe && IO != EO; ++IO) {
3036      const MachineOperand &MO = Instr.getOperand(IO);
3037      if (MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) {
3038        isSafe = true;
3039        break;
3040      }
3041      if (!MO.isReg() || MO.getReg() != ARM::CPSR)
3042        continue;
3043      if (MO.isDef()) {
3044        isSafe = true;
3045        break;
3046      }
3047      // Condition code is after the operand before CPSR except for VSELs.
3048      ARMCC::CondCodes CC;
3049      bool IsInstrVSel = true;
3050      switch (Instr.getOpcode()) {
3051      default:
3052        IsInstrVSel = false;
3053        CC = (ARMCC::CondCodes)Instr.getOperand(IO - 1).getImm();
3054        break;
3055      case ARM::VSELEQD:
3056      case ARM::VSELEQS:
3057      case ARM::VSELEQH:
3058        CC = ARMCC::EQ;
3059        break;
3060      case ARM::VSELGTD:
3061      case ARM::VSELGTS:
3062      case ARM::VSELGTH:
3063        CC = ARMCC::GT;
3064        break;
3065      case ARM::VSELGED:
3066      case ARM::VSELGES:
3067      case ARM::VSELGEH:
3068        CC = ARMCC::GE;
3069        break;
3070      case ARM::VSELVSD:
3071      case ARM::VSELVSS:
3072      case ARM::VSELVSH:
3073        CC = ARMCC::VS;
3074        break;
3075      }
3076
3077      if (SubAdd) {
3078        // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based
3079        // on CMP needs to be updated to be based on SUB.
3080        // If we have ADD(r1, r2, X) and CMP(r1, r2), the condition code also
3081        // needs to be modified.
3082        // Push the condition code operands to OperandsToUpdate.
3083        // If it is safe to remove CmpInstr, the condition code of these
3084        // operands will be modified.
3085        unsigned Opc = SubAdd->getOpcode();
3086        bool IsSub = Opc == ARM::SUBrr || Opc == ARM::t2SUBrr ||
3087                     Opc == ARM::SUBri || Opc == ARM::t2SUBri ||
3088                     Opc == ARM::tSUBrr || Opc == ARM::tSUBi3 ||
3089                     Opc == ARM::tSUBi8;
3090        unsigned OpI = Opc != ARM::tSUBrr ? 1 : 2;
3091        if (!IsSub ||
3092            (SrcReg2 != 0 && SubAdd->getOperand(OpI).getReg() == SrcReg2 &&
3093             SubAdd->getOperand(OpI + 1).getReg() == SrcReg)) {
3094          // VSel doesn't support condition code update.
3095          if (IsInstrVSel)
3096            return false;
3097          // Ensure we can swap the condition.
3098          ARMCC::CondCodes NewCC = (IsSub ? getSwappedCondition(CC) : getCmpToAddCondition(CC));
3099          if (NewCC == ARMCC::AL)
3100            return false;
3101          OperandsToUpdate.push_back(
3102              std::make_pair(&((*I).getOperand(IO - 1)), NewCC));
3103        }
3104      } else {
3105        // No SubAdd, so this is x = <op> y, z; cmp x, 0.
3106        switch (CC) {
3107        case ARMCC::EQ: // Z
3108        case ARMCC::NE: // Z
3109        case ARMCC::MI: // N
3110        case ARMCC::PL: // N
3111        case ARMCC::AL: // none
3112          // CPSR can be used multiple times, we should continue.
3113          break;
3114        case ARMCC::HS: // C
3115        case ARMCC::LO: // C
3116        case ARMCC::VS: // V
3117        case ARMCC::VC: // V
3118        case ARMCC::HI: // C Z
3119        case ARMCC::LS: // C Z
3120        case ARMCC::GE: // N V
3121        case ARMCC::LT: // N V
3122        case ARMCC::GT: // Z N V
3123        case ARMCC::LE: // Z N V
3124          // The instruction uses the V bit or C bit which is not safe.
3125          return false;
3126        }
3127      }
3128    }
3129  }
3130
3131  // If CPSR is not killed nor re-defined, we should check whether it is
3132  // live-out. If it is live-out, do not optimize.
3133  if (!isSafe) {
3134    MachineBasicBlock *MBB = CmpInstr.getParent();
3135    for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
3136             SE = MBB->succ_end(); SI != SE; ++SI)
3137      if ((*SI)->isLiveIn(ARM::CPSR))
3138        return false;
3139  }
3140
3141  // Toggle the optional operand to CPSR (if it exists - in Thumb1 we always
3142  // set CPSR so this is represented as an explicit output)
3143  if (!IsThumb1) {
3144    MI->getOperand(5).setReg(ARM::CPSR);
3145    MI->getOperand(5).setIsDef(true);
3146  }
3147  assert(!isPredicated(*MI) && "Can't use flags from predicated instruction");
3148  CmpInstr.eraseFromParent();
3149
3150  // Modify the condition code of operands in OperandsToUpdate.
3151  // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
3152  // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
3153  for (unsigned i = 0, e = OperandsToUpdate.size(); i < e; i++)
3154    OperandsToUpdate[i].first->setImm(OperandsToUpdate[i].second);
3155
3156  MI->clearRegisterDeads(ARM::CPSR);
3157
3158  return true;
3159}
3160
3161bool ARMBaseInstrInfo::shouldSink(const MachineInstr &MI) const {
3162  // Do not sink MI if it might be used to optimize a redundant compare.
3163  // We heuristically only look at the instruction immediately following MI to
3164  // avoid potentially searching the entire basic block.
3165  if (isPredicated(MI))
3166    return true;
3167  MachineBasicBlock::const_iterator Next = &MI;
3168  ++Next;
3169  unsigned SrcReg, SrcReg2;
3170  int CmpMask, CmpValue;
3171  bool IsThumb1;
3172  if (Next != MI.getParent()->end() &&
3173      analyzeCompare(*Next, SrcReg, SrcReg2, CmpMask, CmpValue) &&
3174      isRedundantFlagInstr(&*Next, SrcReg, SrcReg2, CmpValue, &MI, IsThumb1))
3175    return false;
3176  return true;
3177}
3178
3179bool ARMBaseInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
3180                                     unsigned Reg,
3181                                     MachineRegisterInfo *MRI) const {
3182  // Fold large immediates into add, sub, or, xor.
3183  unsigned DefOpc = DefMI.getOpcode();
3184  if (DefOpc != ARM::t2MOVi32imm && DefOpc != ARM::MOVi32imm)
3185    return false;
3186  if (!DefMI.getOperand(1).isImm())
3187    // Could be t2MOVi32imm @xx
3188    return false;
3189
3190  if (!MRI->hasOneNonDBGUse(Reg))
3191    return false;
3192
3193  const MCInstrDesc &DefMCID = DefMI.getDesc();
3194  if (DefMCID.hasOptionalDef()) {
3195    unsigned NumOps = DefMCID.getNumOperands();
3196    const MachineOperand &MO = DefMI.getOperand(NumOps - 1);
3197    if (MO.getReg() == ARM::CPSR && !MO.isDead())
3198      // If DefMI defines CPSR and it is not dead, it's obviously not safe
3199      // to delete DefMI.
3200      return false;
3201  }
3202
3203  const MCInstrDesc &UseMCID = UseMI.getDesc();
3204  if (UseMCID.hasOptionalDef()) {
3205    unsigned NumOps = UseMCID.getNumOperands();
3206    if (UseMI.getOperand(NumOps - 1).getReg() == ARM::CPSR)
3207      // If the instruction sets the flag, do not attempt this optimization
3208      // since it may change the semantics of the code.
3209      return false;
3210  }
3211
3212  unsigned UseOpc = UseMI.getOpcode();
3213  unsigned NewUseOpc = 0;
3214  uint32_t ImmVal = (uint32_t)DefMI.getOperand(1).getImm();
3215  uint32_t SOImmValV1 = 0, SOImmValV2 = 0;
3216  bool Commute = false;
3217  switch (UseOpc) {
3218  default: return false;
3219  case ARM::SUBrr:
3220  case ARM::ADDrr:
3221  case ARM::ORRrr:
3222  case ARM::EORrr:
3223  case ARM::t2SUBrr:
3224  case ARM::t2ADDrr:
3225  case ARM::t2ORRrr:
3226  case ARM::t2EORrr: {
3227    Commute = UseMI.getOperand(2).getReg() != Reg;
3228    switch (UseOpc) {
3229    default: break;
3230    case ARM::ADDrr:
3231    case ARM::SUBrr:
3232      if (UseOpc == ARM::SUBrr && Commute)
3233        return false;
3234
3235      // ADD/SUB are special because they're essentially the same operation, so
3236      // we can handle a larger range of immediates.
3237      if (ARM_AM::isSOImmTwoPartVal(ImmVal))
3238        NewUseOpc = UseOpc == ARM::ADDrr ? ARM::ADDri : ARM::SUBri;
3239      else if (ARM_AM::isSOImmTwoPartVal(-ImmVal)) {
3240        ImmVal = -ImmVal;
3241        NewUseOpc = UseOpc == ARM::ADDrr ? ARM::SUBri : ARM::ADDri;
3242      } else
3243        return false;
3244      SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal);
3245      SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal);
3246      break;
3247    case ARM::ORRrr:
3248    case ARM::EORrr:
3249      if (!ARM_AM::isSOImmTwoPartVal(ImmVal))
3250        return false;
3251      SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal);
3252      SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal);
3253      switch (UseOpc) {
3254      default: break;
3255      case ARM::ORRrr: NewUseOpc = ARM::ORRri; break;
3256      case ARM::EORrr: NewUseOpc = ARM::EORri; break;
3257      }
3258      break;
3259    case ARM::t2ADDrr:
3260    case ARM::t2SUBrr: {
3261      if (UseOpc == ARM::t2SUBrr && Commute)
3262        return false;
3263
3264      // ADD/SUB are special because they're essentially the same operation, so
3265      // we can handle a larger range of immediates.
3266      const bool ToSP = DefMI.getOperand(0).getReg() == ARM::SP;
3267      const unsigned t2ADD = ToSP ? ARM::t2ADDspImm : ARM::t2ADDri;
3268      const unsigned t2SUB = ToSP ? ARM::t2SUBspImm : ARM::t2SUBri;
3269      if (ARM_AM::isT2SOImmTwoPartVal(ImmVal))
3270        NewUseOpc = UseOpc == ARM::t2ADDrr ? t2ADD : t2SUB;
3271      else if (ARM_AM::isT2SOImmTwoPartVal(-ImmVal)) {
3272        ImmVal = -ImmVal;
3273        NewUseOpc = UseOpc == ARM::t2ADDrr ? t2SUB : t2ADD;
3274      } else
3275        return false;
3276      SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal);
3277      SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal);
3278      break;
3279    }
3280    case ARM::t2ORRrr:
3281    case ARM::t2EORrr:
3282      if (!ARM_AM::isT2SOImmTwoPartVal(ImmVal))
3283        return false;
3284      SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal);
3285      SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal);
3286      switch (UseOpc) {
3287      default: break;
3288      case ARM::t2ORRrr: NewUseOpc = ARM::t2ORRri; break;
3289      case ARM::t2EORrr: NewUseOpc = ARM::t2EORri; break;
3290      }
3291      break;
3292    }
3293  }
3294  }
3295
3296  unsigned OpIdx = Commute ? 2 : 1;
3297  Register Reg1 = UseMI.getOperand(OpIdx).getReg();
3298  bool isKill = UseMI.getOperand(OpIdx).isKill();
3299  const TargetRegisterClass *TRC = MRI->getRegClass(Reg);
3300  Register NewReg = MRI->createVirtualRegister(TRC);
3301  BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(), get(NewUseOpc),
3302          NewReg)
3303      .addReg(Reg1, getKillRegState(isKill))
3304      .addImm(SOImmValV1)
3305      .add(predOps(ARMCC::AL))
3306      .add(condCodeOp());
3307  UseMI.setDesc(get(NewUseOpc));
3308  UseMI.getOperand(1).setReg(NewReg);
3309  UseMI.getOperand(1).setIsKill();
3310  UseMI.getOperand(2).ChangeToImmediate(SOImmValV2);
3311  DefMI.eraseFromParent();
3312  // FIXME: t2ADDrr should be split, as different rulles apply when writing to SP.
3313  // Just as t2ADDri, that was split to [t2ADDri, t2ADDspImm].
3314  // Then the below code will not be needed, as the input/output register
3315  // classes will be rgpr or gprSP.
3316  // For now, we fix the UseMI operand explicitly here:
3317  switch(NewUseOpc){
3318    case ARM::t2ADDspImm:
3319    case ARM::t2SUBspImm:
3320    case ARM::t2ADDri:
3321    case ARM::t2SUBri:
3322      MRI->setRegClass(UseMI.getOperand(0).getReg(), TRC);
3323  }
3324  return true;
3325}
3326
3327static unsigned getNumMicroOpsSwiftLdSt(const InstrItineraryData *ItinData,
3328                                        const MachineInstr &MI) {
3329  switch (MI.getOpcode()) {
3330  default: {
3331    const MCInstrDesc &Desc = MI.getDesc();
3332    int UOps = ItinData->getNumMicroOps(Desc.getSchedClass());
3333    assert(UOps >= 0 && "bad # UOps");
3334    return UOps;
3335  }
3336
3337  case ARM::LDRrs:
3338  case ARM::LDRBrs:
3339  case ARM::STRrs:
3340  case ARM::STRBrs: {
3341    unsigned ShOpVal = MI.getOperand(3).getImm();
3342    bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3343    unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3344    if (!isSub &&
3345        (ShImm == 0 ||
3346         ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3347          ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3348      return 1;
3349    return 2;
3350  }
3351
3352  case ARM::LDRH:
3353  case ARM::STRH: {
3354    if (!MI.getOperand(2).getReg())
3355      return 1;
3356
3357    unsigned ShOpVal = MI.getOperand(3).getImm();
3358    bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3359    unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3360    if (!isSub &&
3361        (ShImm == 0 ||
3362         ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3363          ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3364      return 1;
3365    return 2;
3366  }
3367
3368  case ARM::LDRSB:
3369  case ARM::LDRSH:
3370    return (ARM_AM::getAM3Op(MI.getOperand(3).getImm()) == ARM_AM::sub) ? 3 : 2;
3371
3372  case ARM::LDRSB_POST:
3373  case ARM::LDRSH_POST: {
3374    Register Rt = MI.getOperand(0).getReg();
3375    Register Rm = MI.getOperand(3).getReg();
3376    return (Rt == Rm) ? 4 : 3;
3377  }
3378
3379  case ARM::LDR_PRE_REG:
3380  case ARM::LDRB_PRE_REG: {
3381    Register Rt = MI.getOperand(0).getReg();
3382    Register Rm = MI.getOperand(3).getReg();
3383    if (Rt == Rm)
3384      return 3;
3385    unsigned ShOpVal = MI.getOperand(4).getImm();
3386    bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3387    unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3388    if (!isSub &&
3389        (ShImm == 0 ||
3390         ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3391          ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3392      return 2;
3393    return 3;
3394  }
3395
3396  case ARM::STR_PRE_REG:
3397  case ARM::STRB_PRE_REG: {
3398    unsigned ShOpVal = MI.getOperand(4).getImm();
3399    bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3400    unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3401    if (!isSub &&
3402        (ShImm == 0 ||
3403         ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3404          ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3405      return 2;
3406    return 3;
3407  }
3408
3409  case ARM::LDRH_PRE:
3410  case ARM::STRH_PRE: {
3411    Register Rt = MI.getOperand(0).getReg();
3412    Register Rm = MI.getOperand(3).getReg();
3413    if (!Rm)
3414      return 2;
3415    if (Rt == Rm)
3416      return 3;
3417    return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 3 : 2;
3418  }
3419
3420  case ARM::LDR_POST_REG:
3421  case ARM::LDRB_POST_REG:
3422  case ARM::LDRH_POST: {
3423    Register Rt = MI.getOperand(0).getReg();
3424    Register Rm = MI.getOperand(3).getReg();
3425    return (Rt == Rm) ? 3 : 2;
3426  }
3427
3428  case ARM::LDR_PRE_IMM:
3429  case ARM::LDRB_PRE_IMM:
3430  case ARM::LDR_POST_IMM:
3431  case ARM::LDRB_POST_IMM:
3432  case ARM::STRB_POST_IMM:
3433  case ARM::STRB_POST_REG:
3434  case ARM::STRB_PRE_IMM:
3435  case ARM::STRH_POST:
3436  case ARM::STR_POST_IMM:
3437  case ARM::STR_POST_REG:
3438  case ARM::STR_PRE_IMM:
3439    return 2;
3440
3441  case ARM::LDRSB_PRE:
3442  case ARM::LDRSH_PRE: {
3443    Register Rm = MI.getOperand(3).getReg();
3444    if (Rm == 0)
3445      return 3;
3446    Register Rt = MI.getOperand(0).getReg();
3447    if (Rt == Rm)
3448      return 4;
3449    unsigned ShOpVal = MI.getOperand(4).getImm();
3450    bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3451    unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3452    if (!isSub &&
3453        (ShImm == 0 ||
3454         ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3455          ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3456      return 3;
3457    return 4;
3458  }
3459
3460  case ARM::LDRD: {
3461    Register Rt = MI.getOperand(0).getReg();
3462    Register Rn = MI.getOperand(2).getReg();
3463    Register Rm = MI.getOperand(3).getReg();
3464    if (Rm)
3465      return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 4
3466                                                                          : 3;
3467    return (Rt == Rn) ? 3 : 2;
3468  }
3469
3470  case ARM::STRD: {
3471    Register Rm = MI.getOperand(3).getReg();
3472    if (Rm)
3473      return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 4
3474                                                                          : 3;
3475    return 2;
3476  }
3477
3478  case ARM::LDRD_POST:
3479  case ARM::t2LDRD_POST:
3480    return 3;
3481
3482  case ARM::STRD_POST:
3483  case ARM::t2STRD_POST:
3484    return 4;
3485
3486  case ARM::LDRD_PRE: {
3487    Register Rt = MI.getOperand(0).getReg();
3488    Register Rn = MI.getOperand(3).getReg();
3489    Register Rm = MI.getOperand(4).getReg();
3490    if (Rm)
3491      return (ARM_AM::getAM3Op(MI.getOperand(5).getImm()) == ARM_AM::sub) ? 5
3492                                                                          : 4;
3493    return (Rt == Rn) ? 4 : 3;
3494  }
3495
3496  case ARM::t2LDRD_PRE: {
3497    Register Rt = MI.getOperand(0).getReg();
3498    Register Rn = MI.getOperand(3).getReg();
3499    return (Rt == Rn) ? 4 : 3;
3500  }
3501
3502  case ARM::STRD_PRE: {
3503    Register Rm = MI.getOperand(4).getReg();
3504    if (Rm)
3505      return (ARM_AM::getAM3Op(MI.getOperand(5).getImm()) == ARM_AM::sub) ? 5
3506                                                                          : 4;
3507    return 3;
3508  }
3509
3510  case ARM::t2STRD_PRE:
3511    return 3;
3512
3513  case ARM::t2LDR_POST:
3514  case ARM::t2LDRB_POST:
3515  case ARM::t2LDRB_PRE:
3516  case ARM::t2LDRSBi12:
3517  case ARM::t2LDRSBi8:
3518  case ARM::t2LDRSBpci:
3519  case ARM::t2LDRSBs:
3520  case ARM::t2LDRH_POST:
3521  case ARM::t2LDRH_PRE:
3522  case ARM::t2LDRSBT:
3523  case ARM::t2LDRSB_POST:
3524  case ARM::t2LDRSB_PRE:
3525  case ARM::t2LDRSH_POST:
3526  case ARM::t2LDRSH_PRE:
3527  case ARM::t2LDRSHi12:
3528  case ARM::t2LDRSHi8:
3529  case ARM::t2LDRSHpci:
3530  case ARM::t2LDRSHs:
3531    return 2;
3532
3533  case ARM::t2LDRDi8: {
3534    Register Rt = MI.getOperand(0).getReg();
3535    Register Rn = MI.getOperand(2).getReg();
3536    return (Rt == Rn) ? 3 : 2;
3537  }
3538
3539  case ARM::t2STRB_POST:
3540  case ARM::t2STRB_PRE:
3541  case ARM::t2STRBs:
3542  case ARM::t2STRDi8:
3543  case ARM::t2STRH_POST:
3544  case ARM::t2STRH_PRE:
3545  case ARM::t2STRHs:
3546  case ARM::t2STR_POST:
3547  case ARM::t2STR_PRE:
3548  case ARM::t2STRs:
3549    return 2;
3550  }
3551}
3552
3553// Return the number of 32-bit words loaded by LDM or stored by STM. If this
3554// can't be easily determined return 0 (missing MachineMemOperand).
3555//
3556// FIXME: The current MachineInstr design does not support relying on machine
3557// mem operands to determine the width of a memory access. Instead, we expect
3558// the target to provide this information based on the instruction opcode and
3559// operands. However, using MachineMemOperand is the best solution now for
3560// two reasons:
3561//
3562// 1) getNumMicroOps tries to infer LDM memory width from the total number of MI
3563// operands. This is much more dangerous than using the MachineMemOperand
3564// sizes because CodeGen passes can insert/remove optional machine operands. In
3565// fact, it's totally incorrect for preRA passes and appears to be wrong for
3566// postRA passes as well.
3567//
3568// 2) getNumLDMAddresses is only used by the scheduling machine model and any
3569// machine model that calls this should handle the unknown (zero size) case.
3570//
3571// Long term, we should require a target hook that verifies MachineMemOperand
3572// sizes during MC lowering. That target hook should be local to MC lowering
3573// because we can't ensure that it is aware of other MI forms. Doing this will
3574// ensure that MachineMemOperands are correctly propagated through all passes.
3575unsigned ARMBaseInstrInfo::getNumLDMAddresses(const MachineInstr &MI) const {
3576  unsigned Size = 0;
3577  for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
3578                                  E = MI.memoperands_end();
3579       I != E; ++I) {
3580    Size += (*I)->getSize();
3581  }
3582  // FIXME: The scheduler currently can't handle values larger than 16. But
3583  // the values can actually go up to 32 for floating-point load/store
3584  // multiple (VLDMIA etc.). Also, the way this code is reasoning about memory
3585  // operations isn't right; we could end up with "extra" memory operands for
3586  // various reasons, like tail merge merging two memory operations.
3587  return std::min(Size / 4, 16U);
3588}
3589
3590static unsigned getNumMicroOpsSingleIssuePlusExtras(unsigned Opc,
3591                                                    unsigned NumRegs) {
3592  unsigned UOps = 1 + NumRegs; // 1 for address computation.
3593  switch (Opc) {
3594  default:
3595    break;
3596  case ARM::VLDMDIA_UPD:
3597  case ARM::VLDMDDB_UPD:
3598  case ARM::VLDMSIA_UPD:
3599  case ARM::VLDMSDB_UPD:
3600  case ARM::VSTMDIA_UPD:
3601  case ARM::VSTMDDB_UPD:
3602  case ARM::VSTMSIA_UPD:
3603  case ARM::VSTMSDB_UPD:
3604  case ARM::LDMIA_UPD:
3605  case ARM::LDMDA_UPD:
3606  case ARM::LDMDB_UPD:
3607  case ARM::LDMIB_UPD:
3608  case ARM::STMIA_UPD:
3609  case ARM::STMDA_UPD:
3610  case ARM::STMDB_UPD:
3611  case ARM::STMIB_UPD:
3612  case ARM::tLDMIA_UPD:
3613  case ARM::tSTMIA_UPD:
3614  case ARM::t2LDMIA_UPD:
3615  case ARM::t2LDMDB_UPD:
3616  case ARM::t2STMIA_UPD:
3617  case ARM::t2STMDB_UPD:
3618    ++UOps; // One for base register writeback.
3619    break;
3620  case ARM::LDMIA_RET:
3621  case ARM::tPOP_RET:
3622  case ARM::t2LDMIA_RET:
3623    UOps += 2; // One for base reg wb, one for write to pc.
3624    break;
3625  }
3626  return UOps;
3627}
3628
3629unsigned ARMBaseInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
3630                                          const MachineInstr &MI) const {
3631  if (!ItinData || ItinData->isEmpty())
3632    return 1;
3633
3634  const MCInstrDesc &Desc = MI.getDesc();
3635  unsigned Class = Desc.getSchedClass();
3636  int ItinUOps = ItinData->getNumMicroOps(Class);
3637  if (ItinUOps >= 0) {
3638    if (Subtarget.isSwift() && (Desc.mayLoad() || Desc.mayStore()))
3639      return getNumMicroOpsSwiftLdSt(ItinData, MI);
3640
3641    return ItinUOps;
3642  }
3643
3644  unsigned Opc = MI.getOpcode();
3645  switch (Opc) {
3646  default:
3647    llvm_unreachable("Unexpected multi-uops instruction!");
3648  case ARM::VLDMQIA:
3649  case ARM::VSTMQIA:
3650    return 2;
3651
3652  // The number of uOps for load / store multiple are determined by the number
3653  // registers.
3654  //
3655  // On Cortex-A8, each pair of register loads / stores can be scheduled on the
3656  // same cycle. The scheduling for the first load / store must be done
3657  // separately by assuming the address is not 64-bit aligned.
3658  //
3659  // On Cortex-A9, the formula is simply (#reg / 2) + (#reg % 2). If the address
3660  // is not 64-bit aligned, then AGU would take an extra cycle.  For VFP / NEON
3661  // load / store multiple, the formula is (#reg / 2) + (#reg % 2) + 1.
3662  case ARM::VLDMDIA:
3663  case ARM::VLDMDIA_UPD:
3664  case ARM::VLDMDDB_UPD:
3665  case ARM::VLDMSIA:
3666  case ARM::VLDMSIA_UPD:
3667  case ARM::VLDMSDB_UPD:
3668  case ARM::VSTMDIA:
3669  case ARM::VSTMDIA_UPD:
3670  case ARM::VSTMDDB_UPD:
3671  case ARM::VSTMSIA:
3672  case ARM::VSTMSIA_UPD:
3673  case ARM::VSTMSDB_UPD: {
3674    unsigned NumRegs = MI.getNumOperands() - Desc.getNumOperands();
3675    return (NumRegs / 2) + (NumRegs % 2) + 1;
3676  }
3677
3678  case ARM::LDMIA_RET:
3679  case ARM::LDMIA:
3680  case ARM::LDMDA:
3681  case ARM::LDMDB:
3682  case ARM::LDMIB:
3683  case ARM::LDMIA_UPD:
3684  case ARM::LDMDA_UPD:
3685  case ARM::LDMDB_UPD:
3686  case ARM::LDMIB_UPD:
3687  case ARM::STMIA:
3688  case ARM::STMDA:
3689  case ARM::STMDB:
3690  case ARM::STMIB:
3691  case ARM::STMIA_UPD:
3692  case ARM::STMDA_UPD:
3693  case ARM::STMDB_UPD:
3694  case ARM::STMIB_UPD:
3695  case ARM::tLDMIA:
3696  case ARM::tLDMIA_UPD:
3697  case ARM::tSTMIA_UPD:
3698  case ARM::tPOP_RET:
3699  case ARM::tPOP:
3700  case ARM::tPUSH:
3701  case ARM::t2LDMIA_RET:
3702  case ARM::t2LDMIA:
3703  case ARM::t2LDMDB:
3704  case ARM::t2LDMIA_UPD:
3705  case ARM::t2LDMDB_UPD:
3706  case ARM::t2STMIA:
3707  case ARM::t2STMDB:
3708  case ARM::t2STMIA_UPD:
3709  case ARM::t2STMDB_UPD: {
3710    unsigned NumRegs = MI.getNumOperands() - Desc.getNumOperands() + 1;
3711    switch (Subtarget.getLdStMultipleTiming()) {
3712    case ARMSubtarget::SingleIssuePlusExtras:
3713      return getNumMicroOpsSingleIssuePlusExtras(Opc, NumRegs);
3714    case ARMSubtarget::SingleIssue:
3715      // Assume the worst.
3716      return NumRegs;
3717    case ARMSubtarget::DoubleIssue: {
3718      if (NumRegs < 4)
3719        return 2;
3720      // 4 registers would be issued: 2, 2.
3721      // 5 registers would be issued: 2, 2, 1.
3722      unsigned UOps = (NumRegs / 2);
3723      if (NumRegs % 2)
3724        ++UOps;
3725      return UOps;
3726    }
3727    case ARMSubtarget::DoubleIssueCheckUnalignedAccess: {
3728      unsigned UOps = (NumRegs / 2);
3729      // If there are odd number of registers or if it's not 64-bit aligned,
3730      // then it takes an extra AGU (Address Generation Unit) cycle.
3731      if ((NumRegs % 2) || !MI.hasOneMemOperand() ||
3732          (*MI.memoperands_begin())->getAlignment() < 8)
3733        ++UOps;
3734      return UOps;
3735      }
3736    }
3737  }
3738  }
3739  llvm_unreachable("Didn't find the number of microops");
3740}
3741
3742int
3743ARMBaseInstrInfo::getVLDMDefCycle(const InstrItineraryData *ItinData,
3744                                  const MCInstrDesc &DefMCID,
3745                                  unsigned DefClass,
3746                                  unsigned DefIdx, unsigned DefAlign) const {
3747  int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
3748  if (RegNo <= 0)
3749    // Def is the address writeback.
3750    return ItinData->getOperandCycle(DefClass, DefIdx);
3751
3752  int DefCycle;
3753  if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
3754    // (regno / 2) + (regno % 2) + 1
3755    DefCycle = RegNo / 2 + 1;
3756    if (RegNo % 2)
3757      ++DefCycle;
3758  } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3759    DefCycle = RegNo;
3760    bool isSLoad = false;
3761
3762    switch (DefMCID.getOpcode()) {
3763    default: break;
3764    case ARM::VLDMSIA:
3765    case ARM::VLDMSIA_UPD:
3766    case ARM::VLDMSDB_UPD:
3767      isSLoad = true;
3768      break;
3769    }
3770
3771    // If there are odd number of 'S' registers or if it's not 64-bit aligned,
3772    // then it takes an extra cycle.
3773    if ((isSLoad && (RegNo % 2)) || DefAlign < 8)
3774      ++DefCycle;
3775  } else {
3776    // Assume the worst.
3777    DefCycle = RegNo + 2;
3778  }
3779
3780  return DefCycle;
3781}
3782
3783bool ARMBaseInstrInfo::isLDMBaseRegInList(const MachineInstr &MI) const {
3784  Register BaseReg = MI.getOperand(0).getReg();
3785  for (unsigned i = 1, sz = MI.getNumOperands(); i < sz; ++i) {
3786    const auto &Op = MI.getOperand(i);
3787    if (Op.isReg() && Op.getReg() == BaseReg)
3788      return true;
3789  }
3790  return false;
3791}
3792unsigned
3793ARMBaseInstrInfo::getLDMVariableDefsSize(const MachineInstr &MI) const {
3794  // ins GPR:$Rn, $p (2xOp), reglist:$regs, variable_ops
3795  // (outs GPR:$wb), (ins GPR:$Rn, $p (2xOp), reglist:$regs, variable_ops)
3796  return MI.getNumOperands() + 1 - MI.getDesc().getNumOperands();
3797}
3798
3799int
3800ARMBaseInstrInfo::getLDMDefCycle(const InstrItineraryData *ItinData,
3801                                 const MCInstrDesc &DefMCID,
3802                                 unsigned DefClass,
3803                                 unsigned DefIdx, unsigned DefAlign) const {
3804  int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
3805  if (RegNo <= 0)
3806    // Def is the address writeback.
3807    return ItinData->getOperandCycle(DefClass, DefIdx);
3808
3809  int DefCycle;
3810  if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
3811    // 4 registers would be issued: 1, 2, 1.
3812    // 5 registers would be issued: 1, 2, 2.
3813    DefCycle = RegNo / 2;
3814    if (DefCycle < 1)
3815      DefCycle = 1;
3816    // Result latency is issue cycle + 2: E2.
3817    DefCycle += 2;
3818  } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3819    DefCycle = (RegNo / 2);
3820    // If there are odd number of registers or if it's not 64-bit aligned,
3821    // then it takes an extra AGU (Address Generation Unit) cycle.
3822    if ((RegNo % 2) || DefAlign < 8)
3823      ++DefCycle;
3824    // Result latency is AGU cycles + 2.
3825    DefCycle += 2;
3826  } else {
3827    // Assume the worst.
3828    DefCycle = RegNo + 2;
3829  }
3830
3831  return DefCycle;
3832}
3833
3834int
3835ARMBaseInstrInfo::getVSTMUseCycle(const InstrItineraryData *ItinData,
3836                                  const MCInstrDesc &UseMCID,
3837                                  unsigned UseClass,
3838                                  unsigned UseIdx, unsigned UseAlign) const {
3839  int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
3840  if (RegNo <= 0)
3841    return ItinData->getOperandCycle(UseClass, UseIdx);
3842
3843  int UseCycle;
3844  if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
3845    // (regno / 2) + (regno % 2) + 1
3846    UseCycle = RegNo / 2 + 1;
3847    if (RegNo % 2)
3848      ++UseCycle;
3849  } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3850    UseCycle = RegNo;
3851    bool isSStore = false;
3852
3853    switch (UseMCID.getOpcode()) {
3854    default: break;
3855    case ARM::VSTMSIA:
3856    case ARM::VSTMSIA_UPD:
3857    case ARM::VSTMSDB_UPD:
3858      isSStore = true;
3859      break;
3860    }
3861
3862    // If there are odd number of 'S' registers or if it's not 64-bit aligned,
3863    // then it takes an extra cycle.
3864    if ((isSStore && (RegNo % 2)) || UseAlign < 8)
3865      ++UseCycle;
3866  } else {
3867    // Assume the worst.
3868    UseCycle = RegNo + 2;
3869  }
3870
3871  return UseCycle;
3872}
3873
3874int
3875ARMBaseInstrInfo::getSTMUseCycle(const InstrItineraryData *ItinData,
3876                                 const MCInstrDesc &UseMCID,
3877                                 unsigned UseClass,
3878                                 unsigned UseIdx, unsigned UseAlign) const {
3879  int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
3880  if (RegNo <= 0)
3881    return ItinData->getOperandCycle(UseClass, UseIdx);
3882
3883  int UseCycle;
3884  if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
3885    UseCycle = RegNo / 2;
3886    if (UseCycle < 2)
3887      UseCycle = 2;
3888    // Read in E3.
3889    UseCycle += 2;
3890  } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3891    UseCycle = (RegNo / 2);
3892    // If there are odd number of registers or if it's not 64-bit aligned,
3893    // then it takes an extra AGU (Address Generation Unit) cycle.
3894    if ((RegNo % 2) || UseAlign < 8)
3895      ++UseCycle;
3896  } else {
3897    // Assume the worst.
3898    UseCycle = 1;
3899  }
3900  return UseCycle;
3901}
3902
3903int
3904ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
3905                                    const MCInstrDesc &DefMCID,
3906                                    unsigned DefIdx, unsigned DefAlign,
3907                                    const MCInstrDesc &UseMCID,
3908                                    unsigned UseIdx, unsigned UseAlign) const {
3909  unsigned DefClass = DefMCID.getSchedClass();
3910  unsigned UseClass = UseMCID.getSchedClass();
3911
3912  if (DefIdx < DefMCID.getNumDefs() && UseIdx < UseMCID.getNumOperands())
3913    return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
3914
3915  // This may be a def / use of a variable_ops instruction, the operand
3916  // latency might be determinable dynamically. Let the target try to
3917  // figure it out.
3918  int DefCycle = -1;
3919  bool LdmBypass = false;
3920  switch (DefMCID.getOpcode()) {
3921  default:
3922    DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
3923    break;
3924
3925  case ARM::VLDMDIA:
3926  case ARM::VLDMDIA_UPD:
3927  case ARM::VLDMDDB_UPD:
3928  case ARM::VLDMSIA:
3929  case ARM::VLDMSIA_UPD:
3930  case ARM::VLDMSDB_UPD:
3931    DefCycle = getVLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
3932    break;
3933
3934  case ARM::LDMIA_RET:
3935  case ARM::LDMIA:
3936  case ARM::LDMDA:
3937  case ARM::LDMDB:
3938  case ARM::LDMIB:
3939  case ARM::LDMIA_UPD:
3940  case ARM::LDMDA_UPD:
3941  case ARM::LDMDB_UPD:
3942  case ARM::LDMIB_UPD:
3943  case ARM::tLDMIA:
3944  case ARM::tLDMIA_UPD:
3945  case ARM::tPUSH:
3946  case ARM::t2LDMIA_RET:
3947  case ARM::t2LDMIA:
3948  case ARM::t2LDMDB:
3949  case ARM::t2LDMIA_UPD:
3950  case ARM::t2LDMDB_UPD:
3951    LdmBypass = true;
3952    DefCycle = getLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
3953    break;
3954  }
3955
3956  if (DefCycle == -1)
3957    // We can't seem to determine the result latency of the def, assume it's 2.
3958    DefCycle = 2;
3959
3960  int UseCycle = -1;
3961  switch (UseMCID.getOpcode()) {
3962  default:
3963    UseCycle = ItinData->getOperandCycle(UseClass, UseIdx);
3964    break;
3965
3966  case ARM::VSTMDIA:
3967  case ARM::VSTMDIA_UPD:
3968  case ARM::VSTMDDB_UPD:
3969  case ARM::VSTMSIA:
3970  case ARM::VSTMSIA_UPD:
3971  case ARM::VSTMSDB_UPD:
3972    UseCycle = getVSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
3973    break;
3974
3975  case ARM::STMIA:
3976  case ARM::STMDA:
3977  case ARM::STMDB:
3978  case ARM::STMIB:
3979  case ARM::STMIA_UPD:
3980  case ARM::STMDA_UPD:
3981  case ARM::STMDB_UPD:
3982  case ARM::STMIB_UPD:
3983  case ARM::tSTMIA_UPD:
3984  case ARM::tPOP_RET:
3985  case ARM::tPOP:
3986  case ARM::t2STMIA:
3987  case ARM::t2STMDB:
3988  case ARM::t2STMIA_UPD:
3989  case ARM::t2STMDB_UPD:
3990    UseCycle = getSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
3991    break;
3992  }
3993
3994  if (UseCycle == -1)
3995    // Assume it's read in the first stage.
3996    UseCycle = 1;
3997
3998  UseCycle = DefCycle - UseCycle + 1;
3999  if (UseCycle > 0) {
4000    if (LdmBypass) {
4001      // It's a variable_ops instruction so we can't use DefIdx here. Just use
4002      // first def operand.
4003      if (ItinData->hasPipelineForwarding(DefClass, DefMCID.getNumOperands()-1,
4004                                          UseClass, UseIdx))
4005        --UseCycle;
4006    } else if (ItinData->hasPipelineForwarding(DefClass, DefIdx,
4007                                               UseClass, UseIdx)) {
4008      --UseCycle;
4009    }
4010  }
4011
4012  return UseCycle;
4013}
4014
4015static const MachineInstr *getBundledDefMI(const TargetRegisterInfo *TRI,
4016                                           const MachineInstr *MI, unsigned Reg,
4017                                           unsigned &DefIdx, unsigned &Dist) {
4018  Dist = 0;
4019
4020  MachineBasicBlock::const_iterator I = MI; ++I;
4021  MachineBasicBlock::const_instr_iterator II = std::prev(I.getInstrIterator());
4022  assert(II->isInsideBundle() && "Empty bundle?");
4023
4024  int Idx = -1;
4025  while (II->isInsideBundle()) {
4026    Idx = II->findRegisterDefOperandIdx(Reg, false, true, TRI);
4027    if (Idx != -1)
4028      break;
4029    --II;
4030    ++Dist;
4031  }
4032
4033  assert(Idx != -1 && "Cannot find bundled definition!");
4034  DefIdx = Idx;
4035  return &*II;
4036}
4037
4038static const MachineInstr *getBundledUseMI(const TargetRegisterInfo *TRI,
4039                                           const MachineInstr &MI, unsigned Reg,
4040                                           unsigned &UseIdx, unsigned &Dist) {
4041  Dist = 0;
4042
4043  MachineBasicBlock::const_instr_iterator II = ++MI.getIterator();
4044  assert(II->isInsideBundle() && "Empty bundle?");
4045  MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
4046
4047  // FIXME: This doesn't properly handle multiple uses.
4048  int Idx = -1;
4049  while (II != E && II->isInsideBundle()) {
4050    Idx = II->findRegisterUseOperandIdx(Reg, false, TRI);
4051    if (Idx != -1)
4052      break;
4053    if (II->getOpcode() != ARM::t2IT)
4054      ++Dist;
4055    ++II;
4056  }
4057
4058  if (Idx == -1) {
4059    Dist = 0;
4060    return nullptr;
4061  }
4062
4063  UseIdx = Idx;
4064  return &*II;
4065}
4066
4067/// Return the number of cycles to add to (or subtract from) the static
4068/// itinerary based on the def opcode and alignment. The caller will ensure that
4069/// adjusted latency is at least one cycle.
4070static int adjustDefLatency(const ARMSubtarget &Subtarget,
4071                            const MachineInstr &DefMI,
4072                            const MCInstrDesc &DefMCID, unsigned DefAlign) {
4073  int Adjust = 0;
4074  if (Subtarget.isCortexA8() || Subtarget.isLikeA9() || Subtarget.isCortexA7()) {
4075    // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
4076    // variants are one cycle cheaper.
4077    switch (DefMCID.getOpcode()) {
4078    default: break;
4079    case ARM::LDRrs:
4080    case ARM::LDRBrs: {
4081      unsigned ShOpVal = DefMI.getOperand(3).getImm();
4082      unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
4083      if (ShImm == 0 ||
4084          (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
4085        --Adjust;
4086      break;
4087    }
4088    case ARM::t2LDRs:
4089    case ARM::t2LDRBs:
4090    case ARM::t2LDRHs:
4091    case ARM::t2LDRSHs: {
4092      // Thumb2 mode: lsl only.
4093      unsigned ShAmt = DefMI.getOperand(3).getImm();
4094      if (ShAmt == 0 || ShAmt == 2)
4095        --Adjust;
4096      break;
4097    }
4098    }
4099  } else if (Subtarget.isSwift()) {
4100    // FIXME: Properly handle all of the latency adjustments for address
4101    // writeback.
4102    switch (DefMCID.getOpcode()) {
4103    default: break;
4104    case ARM::LDRrs:
4105    case ARM::LDRBrs: {
4106      unsigned ShOpVal = DefMI.getOperand(3).getImm();
4107      bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
4108      unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
4109      if (!isSub &&
4110          (ShImm == 0 ||
4111           ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
4112            ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
4113        Adjust -= 2;
4114      else if (!isSub &&
4115               ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr)
4116        --Adjust;
4117      break;
4118    }
4119    case ARM::t2LDRs:
4120    case ARM::t2LDRBs:
4121    case ARM::t2LDRHs:
4122    case ARM::t2LDRSHs: {
4123      // Thumb2 mode: lsl only.
4124      unsigned ShAmt = DefMI.getOperand(3).getImm();
4125      if (ShAmt == 0 || ShAmt == 1 || ShAmt == 2 || ShAmt == 3)
4126        Adjust -= 2;
4127      break;
4128    }
4129    }
4130  }
4131
4132  if (DefAlign < 8 && Subtarget.checkVLDnAccessAlignment()) {
4133    switch (DefMCID.getOpcode()) {
4134    default: break;
4135    case ARM::VLD1q8:
4136    case ARM::VLD1q16:
4137    case ARM::VLD1q32:
4138    case ARM::VLD1q64:
4139    case ARM::VLD1q8wb_fixed:
4140    case ARM::VLD1q16wb_fixed:
4141    case ARM::VLD1q32wb_fixed:
4142    case ARM::VLD1q64wb_fixed:
4143    case ARM::VLD1q8wb_register:
4144    case ARM::VLD1q16wb_register:
4145    case ARM::VLD1q32wb_register:
4146    case ARM::VLD1q64wb_register:
4147    case ARM::VLD2d8:
4148    case ARM::VLD2d16:
4149    case ARM::VLD2d32:
4150    case ARM::VLD2q8:
4151    case ARM::VLD2q16:
4152    case ARM::VLD2q32:
4153    case ARM::VLD2d8wb_fixed:
4154    case ARM::VLD2d16wb_fixed:
4155    case ARM::VLD2d32wb_fixed:
4156    case ARM::VLD2q8wb_fixed:
4157    case ARM::VLD2q16wb_fixed:
4158    case ARM::VLD2q32wb_fixed:
4159    case ARM::VLD2d8wb_register:
4160    case ARM::VLD2d16wb_register:
4161    case ARM::VLD2d32wb_register:
4162    case ARM::VLD2q8wb_register:
4163    case ARM::VLD2q16wb_register:
4164    case ARM::VLD2q32wb_register:
4165    case ARM::VLD3d8:
4166    case ARM::VLD3d16:
4167    case ARM::VLD3d32:
4168    case ARM::VLD1d64T:
4169    case ARM::VLD3d8_UPD:
4170    case ARM::VLD3d16_UPD:
4171    case ARM::VLD3d32_UPD:
4172    case ARM::VLD1d64Twb_fixed:
4173    case ARM::VLD1d64Twb_register:
4174    case ARM::VLD3q8_UPD:
4175    case ARM::VLD3q16_UPD:
4176    case ARM::VLD3q32_UPD:
4177    case ARM::VLD4d8:
4178    case ARM::VLD4d16:
4179    case ARM::VLD4d32:
4180    case ARM::VLD1d64Q:
4181    case ARM::VLD4d8_UPD:
4182    case ARM::VLD4d16_UPD:
4183    case ARM::VLD4d32_UPD:
4184    case ARM::VLD1d64Qwb_fixed:
4185    case ARM::VLD1d64Qwb_register:
4186    case ARM::VLD4q8_UPD:
4187    case ARM::VLD4q16_UPD:
4188    case ARM::VLD4q32_UPD:
4189    case ARM::VLD1DUPq8:
4190    case ARM::VLD1DUPq16:
4191    case ARM::VLD1DUPq32:
4192    case ARM::VLD1DUPq8wb_fixed:
4193    case ARM::VLD1DUPq16wb_fixed:
4194    case ARM::VLD1DUPq32wb_fixed:
4195    case ARM::VLD1DUPq8wb_register:
4196    case ARM::VLD1DUPq16wb_register:
4197    case ARM::VLD1DUPq32wb_register:
4198    case ARM::VLD2DUPd8:
4199    case ARM::VLD2DUPd16:
4200    case ARM::VLD2DUPd32:
4201    case ARM::VLD2DUPd8wb_fixed:
4202    case ARM::VLD2DUPd16wb_fixed:
4203    case ARM::VLD2DUPd32wb_fixed:
4204    case ARM::VLD2DUPd8wb_register:
4205    case ARM::VLD2DUPd16wb_register:
4206    case ARM::VLD2DUPd32wb_register:
4207    case ARM::VLD4DUPd8:
4208    case ARM::VLD4DUPd16:
4209    case ARM::VLD4DUPd32:
4210    case ARM::VLD4DUPd8_UPD:
4211    case ARM::VLD4DUPd16_UPD:
4212    case ARM::VLD4DUPd32_UPD:
4213    case ARM::VLD1LNd8:
4214    case ARM::VLD1LNd16:
4215    case ARM::VLD1LNd32:
4216    case ARM::VLD1LNd8_UPD:
4217    case ARM::VLD1LNd16_UPD:
4218    case ARM::VLD1LNd32_UPD:
4219    case ARM::VLD2LNd8:
4220    case ARM::VLD2LNd16:
4221    case ARM::VLD2LNd32:
4222    case ARM::VLD2LNq16:
4223    case ARM::VLD2LNq32:
4224    case ARM::VLD2LNd8_UPD:
4225    case ARM::VLD2LNd16_UPD:
4226    case ARM::VLD2LNd32_UPD:
4227    case ARM::VLD2LNq16_UPD:
4228    case ARM::VLD2LNq32_UPD:
4229    case ARM::VLD4LNd8:
4230    case ARM::VLD4LNd16:
4231    case ARM::VLD4LNd32:
4232    case ARM::VLD4LNq16:
4233    case ARM::VLD4LNq32:
4234    case ARM::VLD4LNd8_UPD:
4235    case ARM::VLD4LNd16_UPD:
4236    case ARM::VLD4LNd32_UPD:
4237    case ARM::VLD4LNq16_UPD:
4238    case ARM::VLD4LNq32_UPD:
4239      // If the address is not 64-bit aligned, the latencies of these
4240      // instructions increases by one.
4241      ++Adjust;
4242      break;
4243    }
4244  }
4245  return Adjust;
4246}
4247
4248int ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
4249                                        const MachineInstr &DefMI,
4250                                        unsigned DefIdx,
4251                                        const MachineInstr &UseMI,
4252                                        unsigned UseIdx) const {
4253  // No operand latency. The caller may fall back to getInstrLatency.
4254  if (!ItinData || ItinData->isEmpty())
4255    return -1;
4256
4257  const MachineOperand &DefMO = DefMI.getOperand(DefIdx);
4258  Register Reg = DefMO.getReg();
4259
4260  const MachineInstr *ResolvedDefMI = &DefMI;
4261  unsigned DefAdj = 0;
4262  if (DefMI.isBundle())
4263    ResolvedDefMI =
4264        getBundledDefMI(&getRegisterInfo(), &DefMI, Reg, DefIdx, DefAdj);
4265  if (ResolvedDefMI->isCopyLike() || ResolvedDefMI->isInsertSubreg() ||
4266      ResolvedDefMI->isRegSequence() || ResolvedDefMI->isImplicitDef()) {
4267    return 1;
4268  }
4269
4270  const MachineInstr *ResolvedUseMI = &UseMI;
4271  unsigned UseAdj = 0;
4272  if (UseMI.isBundle()) {
4273    ResolvedUseMI =
4274        getBundledUseMI(&getRegisterInfo(), UseMI, Reg, UseIdx, UseAdj);
4275    if (!ResolvedUseMI)
4276      return -1;
4277  }
4278
4279  return getOperandLatencyImpl(
4280      ItinData, *ResolvedDefMI, DefIdx, ResolvedDefMI->getDesc(), DefAdj, DefMO,
4281      Reg, *ResolvedUseMI, UseIdx, ResolvedUseMI->getDesc(), UseAdj);
4282}
4283
4284int ARMBaseInstrInfo::getOperandLatencyImpl(
4285    const InstrItineraryData *ItinData, const MachineInstr &DefMI,
4286    unsigned DefIdx, const MCInstrDesc &DefMCID, unsigned DefAdj,
4287    const MachineOperand &DefMO, unsigned Reg, const MachineInstr &UseMI,
4288    unsigned UseIdx, const MCInstrDesc &UseMCID, unsigned UseAdj) const {
4289  if (Reg == ARM::CPSR) {
4290    if (DefMI.getOpcode() == ARM::FMSTAT) {
4291      // fpscr -> cpsr stalls over 20 cycles on A8 (and earlier?)
4292      return Subtarget.isLikeA9() ? 1 : 20;
4293    }
4294
4295    // CPSR set and branch can be paired in the same cycle.
4296    if (UseMI.isBranch())
4297      return 0;
4298
4299    // Otherwise it takes the instruction latency (generally one).
4300    unsigned Latency = getInstrLatency(ItinData, DefMI);
4301
4302    // For Thumb2 and -Os, prefer scheduling CPSR setting instruction close to
4303    // its uses. Instructions which are otherwise scheduled between them may
4304    // incur a code size penalty (not able to use the CPSR setting 16-bit
4305    // instructions).
4306    if (Latency > 0 && Subtarget.isThumb2()) {
4307      const MachineFunction *MF = DefMI.getParent()->getParent();
4308      // FIXME: Use Function::hasOptSize().
4309      if (MF->getFunction().hasFnAttribute(Attribute::OptimizeForSize))
4310        --Latency;
4311    }
4312    return Latency;
4313  }
4314
4315  if (DefMO.isImplicit() || UseMI.getOperand(UseIdx).isImplicit())
4316    return -1;
4317
4318  unsigned DefAlign = DefMI.hasOneMemOperand()
4319                          ? (*DefMI.memoperands_begin())->getAlignment()
4320                          : 0;
4321  unsigned UseAlign = UseMI.hasOneMemOperand()
4322                          ? (*UseMI.memoperands_begin())->getAlignment()
4323                          : 0;
4324
4325  // Get the itinerary's latency if possible, and handle variable_ops.
4326  int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign, UseMCID,
4327                                  UseIdx, UseAlign);
4328  // Unable to find operand latency. The caller may resort to getInstrLatency.
4329  if (Latency < 0)
4330    return Latency;
4331
4332  // Adjust for IT block position.
4333  int Adj = DefAdj + UseAdj;
4334
4335  // Adjust for dynamic def-side opcode variants not captured by the itinerary.
4336  Adj += adjustDefLatency(Subtarget, DefMI, DefMCID, DefAlign);
4337  if (Adj >= 0 || (int)Latency > -Adj) {
4338    return Latency + Adj;
4339  }
4340  // Return the itinerary latency, which may be zero but not less than zero.
4341  return Latency;
4342}
4343
4344int
4345ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
4346                                    SDNode *DefNode, unsigned DefIdx,
4347                                    SDNode *UseNode, unsigned UseIdx) const {
4348  if (!DefNode->isMachineOpcode())
4349    return 1;
4350
4351  const MCInstrDesc &DefMCID = get(DefNode->getMachineOpcode());
4352
4353  if (isZeroCost(DefMCID.Opcode))
4354    return 0;
4355
4356  if (!ItinData || ItinData->isEmpty())
4357    return DefMCID.mayLoad() ? 3 : 1;
4358
4359  if (!UseNode->isMachineOpcode()) {
4360    int Latency = ItinData->getOperandCycle(DefMCID.getSchedClass(), DefIdx);
4361    int Adj = Subtarget.getPreISelOperandLatencyAdjustment();
4362    int Threshold = 1 + Adj;
4363    return Latency <= Threshold ? 1 : Latency - Adj;
4364  }
4365
4366  const MCInstrDesc &UseMCID = get(UseNode->getMachineOpcode());
4367  auto *DefMN = cast<MachineSDNode>(DefNode);
4368  unsigned DefAlign = !DefMN->memoperands_empty()
4369    ? (*DefMN->memoperands_begin())->getAlignment() : 0;
4370  auto *UseMN = cast<MachineSDNode>(UseNode);
4371  unsigned UseAlign = !UseMN->memoperands_empty()
4372    ? (*UseMN->memoperands_begin())->getAlignment() : 0;
4373  int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign,
4374                                  UseMCID, UseIdx, UseAlign);
4375
4376  if (Latency > 1 &&
4377      (Subtarget.isCortexA8() || Subtarget.isLikeA9() ||
4378       Subtarget.isCortexA7())) {
4379    // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
4380    // variants are one cycle cheaper.
4381    switch (DefMCID.getOpcode()) {
4382    default: break;
4383    case ARM::LDRrs:
4384    case ARM::LDRBrs: {
4385      unsigned ShOpVal =
4386        cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
4387      unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
4388      if (ShImm == 0 ||
4389          (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
4390        --Latency;
4391      break;
4392    }
4393    case ARM::t2LDRs:
4394    case ARM::t2LDRBs:
4395    case ARM::t2LDRHs:
4396    case ARM::t2LDRSHs: {
4397      // Thumb2 mode: lsl only.
4398      unsigned ShAmt =
4399        cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
4400      if (ShAmt == 0 || ShAmt == 2)
4401        --Latency;
4402      break;
4403    }
4404    }
4405  } else if (DefIdx == 0 && Latency > 2 && Subtarget.isSwift()) {
4406    // FIXME: Properly handle all of the latency adjustments for address
4407    // writeback.
4408    switch (DefMCID.getOpcode()) {
4409    default: break;
4410    case ARM::LDRrs:
4411    case ARM::LDRBrs: {
4412      unsigned ShOpVal =
4413        cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
4414      unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
4415      if (ShImm == 0 ||
4416          ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
4417           ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
4418        Latency -= 2;
4419      else if (ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr)
4420        --Latency;
4421      break;
4422    }
4423    case ARM::t2LDRs:
4424    case ARM::t2LDRBs:
4425    case ARM::t2LDRHs:
4426    case ARM::t2LDRSHs:
4427      // Thumb2 mode: lsl 0-3 only.
4428      Latency -= 2;
4429      break;
4430    }
4431  }
4432
4433  if (DefAlign < 8 && Subtarget.checkVLDnAccessAlignment())
4434    switch (DefMCID.getOpcode()) {
4435    default: break;
4436    case ARM::VLD1q8:
4437    case ARM::VLD1q16:
4438    case ARM::VLD1q32:
4439    case ARM::VLD1q64:
4440    case ARM::VLD1q8wb_register:
4441    case ARM::VLD1q16wb_register:
4442    case ARM::VLD1q32wb_register:
4443    case ARM::VLD1q64wb_register:
4444    case ARM::VLD1q8wb_fixed:
4445    case ARM::VLD1q16wb_fixed:
4446    case ARM::VLD1q32wb_fixed:
4447    case ARM::VLD1q64wb_fixed:
4448    case ARM::VLD2d8:
4449    case ARM::VLD2d16:
4450    case ARM::VLD2d32:
4451    case ARM::VLD2q8Pseudo:
4452    case ARM::VLD2q16Pseudo:
4453    case ARM::VLD2q32Pseudo:
4454    case ARM::VLD2d8wb_fixed:
4455    case ARM::VLD2d16wb_fixed:
4456    case ARM::VLD2d32wb_fixed:
4457    case ARM::VLD2q8PseudoWB_fixed:
4458    case ARM::VLD2q16PseudoWB_fixed:
4459    case ARM::VLD2q32PseudoWB_fixed:
4460    case ARM::VLD2d8wb_register:
4461    case ARM::VLD2d16wb_register:
4462    case ARM::VLD2d32wb_register:
4463    case ARM::VLD2q8PseudoWB_register:
4464    case ARM::VLD2q16PseudoWB_register:
4465    case ARM::VLD2q32PseudoWB_register:
4466    case ARM::VLD3d8Pseudo:
4467    case ARM::VLD3d16Pseudo:
4468    case ARM::VLD3d32Pseudo:
4469    case ARM::VLD1d8TPseudo:
4470    case ARM::VLD1d16TPseudo:
4471    case ARM::VLD1d32TPseudo:
4472    case ARM::VLD1d64TPseudo:
4473    case ARM::VLD1d64TPseudoWB_fixed:
4474    case ARM::VLD1d64TPseudoWB_register:
4475    case ARM::VLD3d8Pseudo_UPD:
4476    case ARM::VLD3d16Pseudo_UPD:
4477    case ARM::VLD3d32Pseudo_UPD:
4478    case ARM::VLD3q8Pseudo_UPD:
4479    case ARM::VLD3q16Pseudo_UPD:
4480    case ARM::VLD3q32Pseudo_UPD:
4481    case ARM::VLD3q8oddPseudo:
4482    case ARM::VLD3q16oddPseudo:
4483    case ARM::VLD3q32oddPseudo:
4484    case ARM::VLD3q8oddPseudo_UPD:
4485    case ARM::VLD3q16oddPseudo_UPD:
4486    case ARM::VLD3q32oddPseudo_UPD:
4487    case ARM::VLD4d8Pseudo:
4488    case ARM::VLD4d16Pseudo:
4489    case ARM::VLD4d32Pseudo:
4490    case ARM::VLD1d8QPseudo:
4491    case ARM::VLD1d16QPseudo:
4492    case ARM::VLD1d32QPseudo:
4493    case ARM::VLD1d64QPseudo:
4494    case ARM::VLD1d64QPseudoWB_fixed:
4495    case ARM::VLD1d64QPseudoWB_register:
4496    case ARM::VLD1q8HighQPseudo:
4497    case ARM::VLD1q8LowQPseudo_UPD:
4498    case ARM::VLD1q8HighTPseudo:
4499    case ARM::VLD1q8LowTPseudo_UPD:
4500    case ARM::VLD1q16HighQPseudo:
4501    case ARM::VLD1q16LowQPseudo_UPD:
4502    case ARM::VLD1q16HighTPseudo:
4503    case ARM::VLD1q16LowTPseudo_UPD:
4504    case ARM::VLD1q32HighQPseudo:
4505    case ARM::VLD1q32LowQPseudo_UPD:
4506    case ARM::VLD1q32HighTPseudo:
4507    case ARM::VLD1q32LowTPseudo_UPD:
4508    case ARM::VLD1q64HighQPseudo:
4509    case ARM::VLD1q64LowQPseudo_UPD:
4510    case ARM::VLD1q64HighTPseudo:
4511    case ARM::VLD1q64LowTPseudo_UPD:
4512    case ARM::VLD4d8Pseudo_UPD:
4513    case ARM::VLD4d16Pseudo_UPD:
4514    case ARM::VLD4d32Pseudo_UPD:
4515    case ARM::VLD4q8Pseudo_UPD:
4516    case ARM::VLD4q16Pseudo_UPD:
4517    case ARM::VLD4q32Pseudo_UPD:
4518    case ARM::VLD4q8oddPseudo:
4519    case ARM::VLD4q16oddPseudo:
4520    case ARM::VLD4q32oddPseudo:
4521    case ARM::VLD4q8oddPseudo_UPD:
4522    case ARM::VLD4q16oddPseudo_UPD:
4523    case ARM::VLD4q32oddPseudo_UPD:
4524    case ARM::VLD1DUPq8:
4525    case ARM::VLD1DUPq16:
4526    case ARM::VLD1DUPq32:
4527    case ARM::VLD1DUPq8wb_fixed:
4528    case ARM::VLD1DUPq16wb_fixed:
4529    case ARM::VLD1DUPq32wb_fixed:
4530    case ARM::VLD1DUPq8wb_register:
4531    case ARM::VLD1DUPq16wb_register:
4532    case ARM::VLD1DUPq32wb_register:
4533    case ARM::VLD2DUPd8:
4534    case ARM::VLD2DUPd16:
4535    case ARM::VLD2DUPd32:
4536    case ARM::VLD2DUPd8wb_fixed:
4537    case ARM::VLD2DUPd16wb_fixed:
4538    case ARM::VLD2DUPd32wb_fixed:
4539    case ARM::VLD2DUPd8wb_register:
4540    case ARM::VLD2DUPd16wb_register:
4541    case ARM::VLD2DUPd32wb_register:
4542    case ARM::VLD2DUPq8EvenPseudo:
4543    case ARM::VLD2DUPq8OddPseudo:
4544    case ARM::VLD2DUPq16EvenPseudo:
4545    case ARM::VLD2DUPq16OddPseudo:
4546    case ARM::VLD2DUPq32EvenPseudo:
4547    case ARM::VLD2DUPq32OddPseudo:
4548    case ARM::VLD3DUPq8EvenPseudo:
4549    case ARM::VLD3DUPq8OddPseudo:
4550    case ARM::VLD3DUPq16EvenPseudo:
4551    case ARM::VLD3DUPq16OddPseudo:
4552    case ARM::VLD3DUPq32EvenPseudo:
4553    case ARM::VLD3DUPq32OddPseudo:
4554    case ARM::VLD4DUPd8Pseudo:
4555    case ARM::VLD4DUPd16Pseudo:
4556    case ARM::VLD4DUPd32Pseudo:
4557    case ARM::VLD4DUPd8Pseudo_UPD:
4558    case ARM::VLD4DUPd16Pseudo_UPD:
4559    case ARM::VLD4DUPd32Pseudo_UPD:
4560    case ARM::VLD4DUPq8EvenPseudo:
4561    case ARM::VLD4DUPq8OddPseudo:
4562    case ARM::VLD4DUPq16EvenPseudo:
4563    case ARM::VLD4DUPq16OddPseudo:
4564    case ARM::VLD4DUPq32EvenPseudo:
4565    case ARM::VLD4DUPq32OddPseudo:
4566    case ARM::VLD1LNq8Pseudo:
4567    case ARM::VLD1LNq16Pseudo:
4568    case ARM::VLD1LNq32Pseudo:
4569    case ARM::VLD1LNq8Pseudo_UPD:
4570    case ARM::VLD1LNq16Pseudo_UPD:
4571    case ARM::VLD1LNq32Pseudo_UPD:
4572    case ARM::VLD2LNd8Pseudo:
4573    case ARM::VLD2LNd16Pseudo:
4574    case ARM::VLD2LNd32Pseudo:
4575    case ARM::VLD2LNq16Pseudo:
4576    case ARM::VLD2LNq32Pseudo:
4577    case ARM::VLD2LNd8Pseudo_UPD:
4578    case ARM::VLD2LNd16Pseudo_UPD:
4579    case ARM::VLD2LNd32Pseudo_UPD:
4580    case ARM::VLD2LNq16Pseudo_UPD:
4581    case ARM::VLD2LNq32Pseudo_UPD:
4582    case ARM::VLD4LNd8Pseudo:
4583    case ARM::VLD4LNd16Pseudo:
4584    case ARM::VLD4LNd32Pseudo:
4585    case ARM::VLD4LNq16Pseudo:
4586    case ARM::VLD4LNq32Pseudo:
4587    case ARM::VLD4LNd8Pseudo_UPD:
4588    case ARM::VLD4LNd16Pseudo_UPD:
4589    case ARM::VLD4LNd32Pseudo_UPD:
4590    case ARM::VLD4LNq16Pseudo_UPD:
4591    case ARM::VLD4LNq32Pseudo_UPD:
4592      // If the address is not 64-bit aligned, the latencies of these
4593      // instructions increases by one.
4594      ++Latency;
4595      break;
4596    }
4597
4598  return Latency;
4599}
4600
4601unsigned ARMBaseInstrInfo::getPredicationCost(const MachineInstr &MI) const {
4602  if (MI.isCopyLike() || MI.isInsertSubreg() || MI.isRegSequence() ||
4603      MI.isImplicitDef())
4604    return 0;
4605
4606  if (MI.isBundle())
4607    return 0;
4608
4609  const MCInstrDesc &MCID = MI.getDesc();
4610
4611  if (MCID.isCall() || (MCID.hasImplicitDefOfPhysReg(ARM::CPSR) &&
4612                        !Subtarget.cheapPredicableCPSRDef())) {
4613    // When predicated, CPSR is an additional source operand for CPSR updating
4614    // instructions, this apparently increases their latencies.
4615    return 1;
4616  }
4617  return 0;
4618}
4619
4620unsigned ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
4621                                           const MachineInstr &MI,
4622                                           unsigned *PredCost) const {
4623  if (MI.isCopyLike() || MI.isInsertSubreg() || MI.isRegSequence() ||
4624      MI.isImplicitDef())
4625    return 1;
4626
4627  // An instruction scheduler typically runs on unbundled instructions, however
4628  // other passes may query the latency of a bundled instruction.
4629  if (MI.isBundle()) {
4630    unsigned Latency = 0;
4631    MachineBasicBlock::const_instr_iterator I = MI.getIterator();
4632    MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
4633    while (++I != E && I->isInsideBundle()) {
4634      if (I->getOpcode() != ARM::t2IT)
4635        Latency += getInstrLatency(ItinData, *I, PredCost);
4636    }
4637    return Latency;
4638  }
4639
4640  const MCInstrDesc &MCID = MI.getDesc();
4641  if (PredCost && (MCID.isCall() || (MCID.hasImplicitDefOfPhysReg(ARM::CPSR) &&
4642                                     !Subtarget.cheapPredicableCPSRDef()))) {
4643    // When predicated, CPSR is an additional source operand for CPSR updating
4644    // instructions, this apparently increases their latencies.
4645    *PredCost = 1;
4646  }
4647  // Be sure to call getStageLatency for an empty itinerary in case it has a
4648  // valid MinLatency property.
4649  if (!ItinData)
4650    return MI.mayLoad() ? 3 : 1;
4651
4652  unsigned Class = MCID.getSchedClass();
4653
4654  // For instructions with variable uops, use uops as latency.
4655  if (!ItinData->isEmpty() && ItinData->getNumMicroOps(Class) < 0)
4656    return getNumMicroOps(ItinData, MI);
4657
4658  // For the common case, fall back on the itinerary's latency.
4659  unsigned Latency = ItinData->getStageLatency(Class);
4660
4661  // Adjust for dynamic def-side opcode variants not captured by the itinerary.
4662  unsigned DefAlign =
4663      MI.hasOneMemOperand() ? (*MI.memoperands_begin())->getAlignment() : 0;
4664  int Adj = adjustDefLatency(Subtarget, MI, MCID, DefAlign);
4665  if (Adj >= 0 || (int)Latency > -Adj) {
4666    return Latency + Adj;
4667  }
4668  return Latency;
4669}
4670
4671int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
4672                                      SDNode *Node) const {
4673  if (!Node->isMachineOpcode())
4674    return 1;
4675
4676  if (!ItinData || ItinData->isEmpty())
4677    return 1;
4678
4679  unsigned Opcode = Node->getMachineOpcode();
4680  switch (Opcode) {
4681  default:
4682    return ItinData->getStageLatency(get(Opcode).getSchedClass());
4683  case ARM::VLDMQIA:
4684  case ARM::VSTMQIA:
4685    return 2;
4686  }
4687}
4688
4689bool ARMBaseInstrInfo::hasHighOperandLatency(const TargetSchedModel &SchedModel,
4690                                             const MachineRegisterInfo *MRI,
4691                                             const MachineInstr &DefMI,
4692                                             unsigned DefIdx,
4693                                             const MachineInstr &UseMI,
4694                                             unsigned UseIdx) const {
4695  unsigned DDomain = DefMI.getDesc().TSFlags & ARMII::DomainMask;
4696  unsigned UDomain = UseMI.getDesc().TSFlags & ARMII::DomainMask;
4697  if (Subtarget.nonpipelinedVFP() &&
4698      (DDomain == ARMII::DomainVFP || UDomain == ARMII::DomainVFP))
4699    return true;
4700
4701  // Hoist VFP / NEON instructions with 4 or higher latency.
4702  unsigned Latency =
4703      SchedModel.computeOperandLatency(&DefMI, DefIdx, &UseMI, UseIdx);
4704  if (Latency <= 3)
4705    return false;
4706  return DDomain == ARMII::DomainVFP || DDomain == ARMII::DomainNEON ||
4707         UDomain == ARMII::DomainVFP || UDomain == ARMII::DomainNEON;
4708}
4709
4710bool ARMBaseInstrInfo::hasLowDefLatency(const TargetSchedModel &SchedModel,
4711                                        const MachineInstr &DefMI,
4712                                        unsigned DefIdx) const {
4713  const InstrItineraryData *ItinData = SchedModel.getInstrItineraries();
4714  if (!ItinData || ItinData->isEmpty())
4715    return false;
4716
4717  unsigned DDomain = DefMI.getDesc().TSFlags & ARMII::DomainMask;
4718  if (DDomain == ARMII::DomainGeneral) {
4719    unsigned DefClass = DefMI.getDesc().getSchedClass();
4720    int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
4721    return (DefCycle != -1 && DefCycle <= 2);
4722  }
4723  return false;
4724}
4725
4726bool ARMBaseInstrInfo::verifyInstruction(const MachineInstr &MI,
4727                                         StringRef &ErrInfo) const {
4728  if (convertAddSubFlagsOpcode(MI.getOpcode())) {
4729    ErrInfo = "Pseudo flag setting opcodes only exist in Selection DAG";
4730    return false;
4731  }
4732  if (MI.getOpcode() == ARM::tMOVr && !Subtarget.hasV6Ops()) {
4733    // Make sure we don't generate a lo-lo mov that isn't supported.
4734    if (!ARM::hGPRRegClass.contains(MI.getOperand(0).getReg()) &&
4735        !ARM::hGPRRegClass.contains(MI.getOperand(1).getReg())) {
4736      ErrInfo = "Non-flag-setting Thumb1 mov is v6-only";
4737      return false;
4738    }
4739  }
4740  if (MI.getOpcode() == ARM::tPUSH ||
4741      MI.getOpcode() == ARM::tPOP ||
4742      MI.getOpcode() == ARM::tPOP_RET) {
4743    for (int i = 2, e = MI.getNumOperands(); i < e; ++i) {
4744      if (MI.getOperand(i).isImplicit() ||
4745          !MI.getOperand(i).isReg())
4746        continue;
4747      Register Reg = MI.getOperand(i).getReg();
4748      if (Reg < ARM::R0 || Reg > ARM::R7) {
4749        if (!(MI.getOpcode() == ARM::tPUSH && Reg == ARM::LR) &&
4750            !(MI.getOpcode() == ARM::tPOP_RET && Reg == ARM::PC)) {
4751          ErrInfo = "Unsupported register in Thumb1 push/pop";
4752          return false;
4753        }
4754      }
4755    }
4756  }
4757  return true;
4758}
4759
4760// LoadStackGuard has so far only been implemented for MachO. Different code
4761// sequence is needed for other targets.
4762void ARMBaseInstrInfo::expandLoadStackGuardBase(MachineBasicBlock::iterator MI,
4763                                                unsigned LoadImmOpc,
4764                                                unsigned LoadOpc) const {
4765  assert(!Subtarget.isROPI() && !Subtarget.isRWPI() &&
4766         "ROPI/RWPI not currently supported with stack guard");
4767
4768  MachineBasicBlock &MBB = *MI->getParent();
4769  DebugLoc DL = MI->getDebugLoc();
4770  Register Reg = MI->getOperand(0).getReg();
4771  const GlobalValue *GV =
4772      cast<GlobalValue>((*MI->memoperands_begin())->getValue());
4773  MachineInstrBuilder MIB;
4774
4775  BuildMI(MBB, MI, DL, get(LoadImmOpc), Reg)
4776      .addGlobalAddress(GV, 0, ARMII::MO_NONLAZY);
4777
4778  if (Subtarget.isGVIndirectSymbol(GV)) {
4779    MIB = BuildMI(MBB, MI, DL, get(LoadOpc), Reg);
4780    MIB.addReg(Reg, RegState::Kill).addImm(0);
4781    auto Flags = MachineMemOperand::MOLoad |
4782                 MachineMemOperand::MODereferenceable |
4783                 MachineMemOperand::MOInvariant;
4784    MachineMemOperand *MMO = MBB.getParent()->getMachineMemOperand(
4785        MachinePointerInfo::getGOT(*MBB.getParent()), Flags, 4, 4);
4786    MIB.addMemOperand(MMO).add(predOps(ARMCC::AL));
4787  }
4788
4789  MIB = BuildMI(MBB, MI, DL, get(LoadOpc), Reg);
4790  MIB.addReg(Reg, RegState::Kill)
4791      .addImm(0)
4792      .cloneMemRefs(*MI)
4793      .add(predOps(ARMCC::AL));
4794}
4795
4796bool
4797ARMBaseInstrInfo::isFpMLxInstruction(unsigned Opcode, unsigned &MulOpc,
4798                                     unsigned &AddSubOpc,
4799                                     bool &NegAcc, bool &HasLane) const {
4800  DenseMap<unsigned, unsigned>::const_iterator I = MLxEntryMap.find(Opcode);
4801  if (I == MLxEntryMap.end())
4802    return false;
4803
4804  const ARM_MLxEntry &Entry = ARM_MLxTable[I->second];
4805  MulOpc = Entry.MulOpc;
4806  AddSubOpc = Entry.AddSubOpc;
4807  NegAcc = Entry.NegAcc;
4808  HasLane = Entry.HasLane;
4809  return true;
4810}
4811
4812//===----------------------------------------------------------------------===//
4813// Execution domains.
4814//===----------------------------------------------------------------------===//
4815//
4816// Some instructions go down the NEON pipeline, some go down the VFP pipeline,
4817// and some can go down both.  The vmov instructions go down the VFP pipeline,
4818// but they can be changed to vorr equivalents that are executed by the NEON
4819// pipeline.
4820//
4821// We use the following execution domain numbering:
4822//
4823enum ARMExeDomain {
4824  ExeGeneric = 0,
4825  ExeVFP = 1,
4826  ExeNEON = 2
4827};
4828
4829//
4830// Also see ARMInstrFormats.td and Domain* enums in ARMBaseInfo.h
4831//
4832std::pair<uint16_t, uint16_t>
4833ARMBaseInstrInfo::getExecutionDomain(const MachineInstr &MI) const {
4834  // If we don't have access to NEON instructions then we won't be able
4835  // to swizzle anything to the NEON domain. Check to make sure.
4836  if (Subtarget.hasNEON()) {
4837    // VMOVD, VMOVRS and VMOVSR are VFP instructions, but can be changed to NEON
4838    // if they are not predicated.
4839    if (MI.getOpcode() == ARM::VMOVD && !isPredicated(MI))
4840      return std::make_pair(ExeVFP, (1 << ExeVFP) | (1 << ExeNEON));
4841
4842    // CortexA9 is particularly picky about mixing the two and wants these
4843    // converted.
4844    if (Subtarget.useNEONForFPMovs() && !isPredicated(MI) &&
4845        (MI.getOpcode() == ARM::VMOVRS || MI.getOpcode() == ARM::VMOVSR ||
4846         MI.getOpcode() == ARM::VMOVS))
4847      return std::make_pair(ExeVFP, (1 << ExeVFP) | (1 << ExeNEON));
4848  }
4849  // No other instructions can be swizzled, so just determine their domain.
4850  unsigned Domain = MI.getDesc().TSFlags & ARMII::DomainMask;
4851
4852  if (Domain & ARMII::DomainNEON)
4853    return std::make_pair(ExeNEON, 0);
4854
4855  // Certain instructions can go either way on Cortex-A8.
4856  // Treat them as NEON instructions.
4857  if ((Domain & ARMII::DomainNEONA8) && Subtarget.isCortexA8())
4858    return std::make_pair(ExeNEON, 0);
4859
4860  if (Domain & ARMII::DomainVFP)
4861    return std::make_pair(ExeVFP, 0);
4862
4863  return std::make_pair(ExeGeneric, 0);
4864}
4865
4866static unsigned getCorrespondingDRegAndLane(const TargetRegisterInfo *TRI,
4867                                            unsigned SReg, unsigned &Lane) {
4868  unsigned DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_0, &ARM::DPRRegClass);
4869  Lane = 0;
4870
4871  if (DReg != ARM::NoRegister)
4872   return DReg;
4873
4874  Lane = 1;
4875  DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_1, &ARM::DPRRegClass);
4876
4877  assert(DReg && "S-register with no D super-register?");
4878  return DReg;
4879}
4880
4881/// getImplicitSPRUseForDPRUse - Given a use of a DPR register and lane,
4882/// set ImplicitSReg to a register number that must be marked as implicit-use or
4883/// zero if no register needs to be defined as implicit-use.
4884///
4885/// If the function cannot determine if an SPR should be marked implicit use or
4886/// not, it returns false.
4887///
4888/// This function handles cases where an instruction is being modified from taking
4889/// an SPR to a DPR[Lane]. A use of the DPR is being added, which may conflict
4890/// with an earlier def of an SPR corresponding to DPR[Lane^1] (i.e. the other
4891/// lane of the DPR).
4892///
4893/// If the other SPR is defined, an implicit-use of it should be added. Else,
4894/// (including the case where the DPR itself is defined), it should not.
4895///
4896static bool getImplicitSPRUseForDPRUse(const TargetRegisterInfo *TRI,
4897                                       MachineInstr &MI, unsigned DReg,
4898                                       unsigned Lane, unsigned &ImplicitSReg) {
4899  // If the DPR is defined or used already, the other SPR lane will be chained
4900  // correctly, so there is nothing to be done.
4901  if (MI.definesRegister(DReg, TRI) || MI.readsRegister(DReg, TRI)) {
4902    ImplicitSReg = 0;
4903    return true;
4904  }
4905
4906  // Otherwise we need to go searching to see if the SPR is set explicitly.
4907  ImplicitSReg = TRI->getSubReg(DReg,
4908                                (Lane & 1) ? ARM::ssub_0 : ARM::ssub_1);
4909  MachineBasicBlock::LivenessQueryResult LQR =
4910      MI.getParent()->computeRegisterLiveness(TRI, ImplicitSReg, MI);
4911
4912  if (LQR == MachineBasicBlock::LQR_Live)
4913    return true;
4914  else if (LQR == MachineBasicBlock::LQR_Unknown)
4915    return false;
4916
4917  // If the register is known not to be live, there is no need to add an
4918  // implicit-use.
4919  ImplicitSReg = 0;
4920  return true;
4921}
4922
4923void ARMBaseInstrInfo::setExecutionDomain(MachineInstr &MI,
4924                                          unsigned Domain) const {
4925  unsigned DstReg, SrcReg, DReg;
4926  unsigned Lane;
4927  MachineInstrBuilder MIB(*MI.getParent()->getParent(), MI);
4928  const TargetRegisterInfo *TRI = &getRegisterInfo();
4929  switch (MI.getOpcode()) {
4930  default:
4931    llvm_unreachable("cannot handle opcode!");
4932    break;
4933  case ARM::VMOVD:
4934    if (Domain != ExeNEON)
4935      break;
4936
4937    // Zap the predicate operands.
4938    assert(!isPredicated(MI) && "Cannot predicate a VORRd");
4939
4940    // Make sure we've got NEON instructions.
4941    assert(Subtarget.hasNEON() && "VORRd requires NEON");
4942
4943    // Source instruction is %DDst = VMOVD %DSrc, 14, %noreg (; implicits)
4944    DstReg = MI.getOperand(0).getReg();
4945    SrcReg = MI.getOperand(1).getReg();
4946
4947    for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
4948      MI.RemoveOperand(i - 1);
4949
4950    // Change to a %DDst = VORRd %DSrc, %DSrc, 14, %noreg (; implicits)
4951    MI.setDesc(get(ARM::VORRd));
4952    MIB.addReg(DstReg, RegState::Define)
4953        .addReg(SrcReg)
4954        .addReg(SrcReg)
4955        .add(predOps(ARMCC::AL));
4956    break;
4957  case ARM::VMOVRS:
4958    if (Domain != ExeNEON)
4959      break;
4960    assert(!isPredicated(MI) && "Cannot predicate a VGETLN");
4961
4962    // Source instruction is %RDst = VMOVRS %SSrc, 14, %noreg (; implicits)
4963    DstReg = MI.getOperand(0).getReg();
4964    SrcReg = MI.getOperand(1).getReg();
4965
4966    for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
4967      MI.RemoveOperand(i - 1);
4968
4969    DReg = getCorrespondingDRegAndLane(TRI, SrcReg, Lane);
4970
4971    // Convert to %RDst = VGETLNi32 %DSrc, Lane, 14, %noreg (; imps)
4972    // Note that DSrc has been widened and the other lane may be undef, which
4973    // contaminates the entire register.
4974    MI.setDesc(get(ARM::VGETLNi32));
4975    MIB.addReg(DstReg, RegState::Define)
4976        .addReg(DReg, RegState::Undef)
4977        .addImm(Lane)
4978        .add(predOps(ARMCC::AL));
4979
4980    // The old source should be an implicit use, otherwise we might think it
4981    // was dead before here.
4982    MIB.addReg(SrcReg, RegState::Implicit);
4983    break;
4984  case ARM::VMOVSR: {
4985    if (Domain != ExeNEON)
4986      break;
4987    assert(!isPredicated(MI) && "Cannot predicate a VSETLN");
4988
4989    // Source instruction is %SDst = VMOVSR %RSrc, 14, %noreg (; implicits)
4990    DstReg = MI.getOperand(0).getReg();
4991    SrcReg = MI.getOperand(1).getReg();
4992
4993    DReg = getCorrespondingDRegAndLane(TRI, DstReg, Lane);
4994
4995    unsigned ImplicitSReg;
4996    if (!getImplicitSPRUseForDPRUse(TRI, MI, DReg, Lane, ImplicitSReg))
4997      break;
4998
4999    for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
5000      MI.RemoveOperand(i - 1);
5001
5002    // Convert to %DDst = VSETLNi32 %DDst, %RSrc, Lane, 14, %noreg (; imps)
5003    // Again DDst may be undefined at the beginning of this instruction.
5004    MI.setDesc(get(ARM::VSETLNi32));
5005    MIB.addReg(DReg, RegState::Define)
5006        .addReg(DReg, getUndefRegState(!MI.readsRegister(DReg, TRI)))
5007        .addReg(SrcReg)
5008        .addImm(Lane)
5009        .add(predOps(ARMCC::AL));
5010
5011    // The narrower destination must be marked as set to keep previous chains
5012    // in place.
5013    MIB.addReg(DstReg, RegState::Define | RegState::Implicit);
5014    if (ImplicitSReg != 0)
5015      MIB.addReg(ImplicitSReg, RegState::Implicit);
5016    break;
5017    }
5018    case ARM::VMOVS: {
5019      if (Domain != ExeNEON)
5020        break;
5021
5022      // Source instruction is %SDst = VMOVS %SSrc, 14, %noreg (; implicits)
5023      DstReg = MI.getOperand(0).getReg();
5024      SrcReg = MI.getOperand(1).getReg();
5025
5026      unsigned DstLane = 0, SrcLane = 0, DDst, DSrc;
5027      DDst = getCorrespondingDRegAndLane(TRI, DstReg, DstLane);
5028      DSrc = getCorrespondingDRegAndLane(TRI, SrcReg, SrcLane);
5029
5030      unsigned ImplicitSReg;
5031      if (!getImplicitSPRUseForDPRUse(TRI, MI, DSrc, SrcLane, ImplicitSReg))
5032        break;
5033
5034      for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
5035        MI.RemoveOperand(i - 1);
5036
5037      if (DSrc == DDst) {
5038        // Destination can be:
5039        //     %DDst = VDUPLN32d %DDst, Lane, 14, %noreg (; implicits)
5040        MI.setDesc(get(ARM::VDUPLN32d));
5041        MIB.addReg(DDst, RegState::Define)
5042            .addReg(DDst, getUndefRegState(!MI.readsRegister(DDst, TRI)))
5043            .addImm(SrcLane)
5044            .add(predOps(ARMCC::AL));
5045
5046        // Neither the source or the destination are naturally represented any
5047        // more, so add them in manually.
5048        MIB.addReg(DstReg, RegState::Implicit | RegState::Define);
5049        MIB.addReg(SrcReg, RegState::Implicit);
5050        if (ImplicitSReg != 0)
5051          MIB.addReg(ImplicitSReg, RegState::Implicit);
5052        break;
5053      }
5054
5055      // In general there's no single instruction that can perform an S <-> S
5056      // move in NEON space, but a pair of VEXT instructions *can* do the
5057      // job. It turns out that the VEXTs needed will only use DSrc once, with
5058      // the position based purely on the combination of lane-0 and lane-1
5059      // involved. For example
5060      //     vmov s0, s2 -> vext.32 d0, d0, d1, #1  vext.32 d0, d0, d0, #1
5061      //     vmov s1, s3 -> vext.32 d0, d1, d0, #1  vext.32 d0, d0, d0, #1
5062      //     vmov s0, s3 -> vext.32 d0, d0, d0, #1  vext.32 d0, d1, d0, #1
5063      //     vmov s1, s2 -> vext.32 d0, d0, d0, #1  vext.32 d0, d0, d1, #1
5064      //
5065      // Pattern of the MachineInstrs is:
5066      //     %DDst = VEXTd32 %DSrc1, %DSrc2, Lane, 14, %noreg (;implicits)
5067      MachineInstrBuilder NewMIB;
5068      NewMIB = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(ARM::VEXTd32),
5069                       DDst);
5070
5071      // On the first instruction, both DSrc and DDst may be undef if present.
5072      // Specifically when the original instruction didn't have them as an
5073      // <imp-use>.
5074      unsigned CurReg = SrcLane == 1 && DstLane == 1 ? DSrc : DDst;
5075      bool CurUndef = !MI.readsRegister(CurReg, TRI);
5076      NewMIB.addReg(CurReg, getUndefRegState(CurUndef));
5077
5078      CurReg = SrcLane == 0 && DstLane == 0 ? DSrc : DDst;
5079      CurUndef = !MI.readsRegister(CurReg, TRI);
5080      NewMIB.addReg(CurReg, getUndefRegState(CurUndef))
5081            .addImm(1)
5082            .add(predOps(ARMCC::AL));
5083
5084      if (SrcLane == DstLane)
5085        NewMIB.addReg(SrcReg, RegState::Implicit);
5086
5087      MI.setDesc(get(ARM::VEXTd32));
5088      MIB.addReg(DDst, RegState::Define);
5089
5090      // On the second instruction, DDst has definitely been defined above, so
5091      // it is not undef. DSrc, if present, can be undef as above.
5092      CurReg = SrcLane == 1 && DstLane == 0 ? DSrc : DDst;
5093      CurUndef = CurReg == DSrc && !MI.readsRegister(CurReg, TRI);
5094      MIB.addReg(CurReg, getUndefRegState(CurUndef));
5095
5096      CurReg = SrcLane == 0 && DstLane == 1 ? DSrc : DDst;
5097      CurUndef = CurReg == DSrc && !MI.readsRegister(CurReg, TRI);
5098      MIB.addReg(CurReg, getUndefRegState(CurUndef))
5099         .addImm(1)
5100         .add(predOps(ARMCC::AL));
5101
5102      if (SrcLane != DstLane)
5103        MIB.addReg(SrcReg, RegState::Implicit);
5104
5105      // As before, the original destination is no longer represented, add it
5106      // implicitly.
5107      MIB.addReg(DstReg, RegState::Define | RegState::Implicit);
5108      if (ImplicitSReg != 0)
5109        MIB.addReg(ImplicitSReg, RegState::Implicit);
5110      break;
5111    }
5112  }
5113}
5114
5115//===----------------------------------------------------------------------===//
5116// Partial register updates
5117//===----------------------------------------------------------------------===//
5118//
5119// Swift renames NEON registers with 64-bit granularity.  That means any
5120// instruction writing an S-reg implicitly reads the containing D-reg.  The
5121// problem is mostly avoided by translating f32 operations to v2f32 operations
5122// on D-registers, but f32 loads are still a problem.
5123//
5124// These instructions can load an f32 into a NEON register:
5125//
5126// VLDRS - Only writes S, partial D update.
5127// VLD1LNd32 - Writes all D-regs, explicit partial D update, 2 uops.
5128// VLD1DUPd32 - Writes all D-regs, no partial reg update, 2 uops.
5129//
5130// FCONSTD can be used as a dependency-breaking instruction.
5131unsigned ARMBaseInstrInfo::getPartialRegUpdateClearance(
5132    const MachineInstr &MI, unsigned OpNum,
5133    const TargetRegisterInfo *TRI) const {
5134  auto PartialUpdateClearance = Subtarget.getPartialUpdateClearance();
5135  if (!PartialUpdateClearance)
5136    return 0;
5137
5138  assert(TRI && "Need TRI instance");
5139
5140  const MachineOperand &MO = MI.getOperand(OpNum);
5141  if (MO.readsReg())
5142    return 0;
5143  Register Reg = MO.getReg();
5144  int UseOp = -1;
5145
5146  switch (MI.getOpcode()) {
5147  // Normal instructions writing only an S-register.
5148  case ARM::VLDRS:
5149  case ARM::FCONSTS:
5150  case ARM::VMOVSR:
5151  case ARM::VMOVv8i8:
5152  case ARM::VMOVv4i16:
5153  case ARM::VMOVv2i32:
5154  case ARM::VMOVv2f32:
5155  case ARM::VMOVv1i64:
5156    UseOp = MI.findRegisterUseOperandIdx(Reg, false, TRI);
5157    break;
5158
5159    // Explicitly reads the dependency.
5160  case ARM::VLD1LNd32:
5161    UseOp = 3;
5162    break;
5163  default:
5164    return 0;
5165  }
5166
5167  // If this instruction actually reads a value from Reg, there is no unwanted
5168  // dependency.
5169  if (UseOp != -1 && MI.getOperand(UseOp).readsReg())
5170    return 0;
5171
5172  // We must be able to clobber the whole D-reg.
5173  if (Register::isVirtualRegister(Reg)) {
5174    // Virtual register must be a def undef foo:ssub_0 operand.
5175    if (!MO.getSubReg() || MI.readsVirtualRegister(Reg))
5176      return 0;
5177  } else if (ARM::SPRRegClass.contains(Reg)) {
5178    // Physical register: MI must define the full D-reg.
5179    unsigned DReg = TRI->getMatchingSuperReg(Reg, ARM::ssub_0,
5180                                             &ARM::DPRRegClass);
5181    if (!DReg || !MI.definesRegister(DReg, TRI))
5182      return 0;
5183  }
5184
5185  // MI has an unwanted D-register dependency.
5186  // Avoid defs in the previous N instructrions.
5187  return PartialUpdateClearance;
5188}
5189
5190// Break a partial register dependency after getPartialRegUpdateClearance
5191// returned non-zero.
5192void ARMBaseInstrInfo::breakPartialRegDependency(
5193    MachineInstr &MI, unsigned OpNum, const TargetRegisterInfo *TRI) const {
5194  assert(OpNum < MI.getDesc().getNumDefs() && "OpNum is not a def");
5195  assert(TRI && "Need TRI instance");
5196
5197  const MachineOperand &MO = MI.getOperand(OpNum);
5198  Register Reg = MO.getReg();
5199  assert(Register::isPhysicalRegister(Reg) &&
5200         "Can't break virtual register dependencies.");
5201  unsigned DReg = Reg;
5202
5203  // If MI defines an S-reg, find the corresponding D super-register.
5204  if (ARM::SPRRegClass.contains(Reg)) {
5205    DReg = ARM::D0 + (Reg - ARM::S0) / 2;
5206    assert(TRI->isSuperRegister(Reg, DReg) && "Register enums broken");
5207  }
5208
5209  assert(ARM::DPRRegClass.contains(DReg) && "Can only break D-reg deps");
5210  assert(MI.definesRegister(DReg, TRI) && "MI doesn't clobber full D-reg");
5211
5212  // FIXME: In some cases, VLDRS can be changed to a VLD1DUPd32 which defines
5213  // the full D-register by loading the same value to both lanes.  The
5214  // instruction is micro-coded with 2 uops, so don't do this until we can
5215  // properly schedule micro-coded instructions.  The dispatcher stalls cause
5216  // too big regressions.
5217
5218  // Insert the dependency-breaking FCONSTD before MI.
5219  // 96 is the encoding of 0.5, but the actual value doesn't matter here.
5220  BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(ARM::FCONSTD), DReg)
5221      .addImm(96)
5222      .add(predOps(ARMCC::AL));
5223  MI.addRegisterKilled(DReg, TRI, true);
5224}
5225
5226bool ARMBaseInstrInfo::hasNOP() const {
5227  return Subtarget.getFeatureBits()[ARM::HasV6KOps];
5228}
5229
5230bool ARMBaseInstrInfo::isSwiftFastImmShift(const MachineInstr *MI) const {
5231  if (MI->getNumOperands() < 4)
5232    return true;
5233  unsigned ShOpVal = MI->getOperand(3).getImm();
5234  unsigned ShImm = ARM_AM::getSORegOffset(ShOpVal);
5235  // Swift supports faster shifts for: lsl 2, lsl 1, and lsr 1.
5236  if ((ShImm == 1 && ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsr) ||
5237      ((ShImm == 1 || ShImm == 2) &&
5238       ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsl))
5239    return true;
5240
5241  return false;
5242}
5243
5244bool ARMBaseInstrInfo::getRegSequenceLikeInputs(
5245    const MachineInstr &MI, unsigned DefIdx,
5246    SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
5247  assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index");
5248  assert(MI.isRegSequenceLike() && "Invalid kind of instruction");
5249
5250  switch (MI.getOpcode()) {
5251  case ARM::VMOVDRR:
5252    // dX = VMOVDRR rY, rZ
5253    // is the same as:
5254    // dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1
5255    // Populate the InputRegs accordingly.
5256    // rY
5257    const MachineOperand *MOReg = &MI.getOperand(1);
5258    if (!MOReg->isUndef())
5259      InputRegs.push_back(RegSubRegPairAndIdx(MOReg->getReg(),
5260                                              MOReg->getSubReg(), ARM::ssub_0));
5261    // rZ
5262    MOReg = &MI.getOperand(2);
5263    if (!MOReg->isUndef())
5264      InputRegs.push_back(RegSubRegPairAndIdx(MOReg->getReg(),
5265                                              MOReg->getSubReg(), ARM::ssub_1));
5266    return true;
5267  }
5268  llvm_unreachable("Target dependent opcode missing");
5269}
5270
5271bool ARMBaseInstrInfo::getExtractSubregLikeInputs(
5272    const MachineInstr &MI, unsigned DefIdx,
5273    RegSubRegPairAndIdx &InputReg) const {
5274  assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index");
5275  assert(MI.isExtractSubregLike() && "Invalid kind of instruction");
5276
5277  switch (MI.getOpcode()) {
5278  case ARM::VMOVRRD:
5279    // rX, rY = VMOVRRD dZ
5280    // is the same as:
5281    // rX = EXTRACT_SUBREG dZ, ssub_0
5282    // rY = EXTRACT_SUBREG dZ, ssub_1
5283    const MachineOperand &MOReg = MI.getOperand(2);
5284    if (MOReg.isUndef())
5285      return false;
5286    InputReg.Reg = MOReg.getReg();
5287    InputReg.SubReg = MOReg.getSubReg();
5288    InputReg.SubIdx = DefIdx == 0 ? ARM::ssub_0 : ARM::ssub_1;
5289    return true;
5290  }
5291  llvm_unreachable("Target dependent opcode missing");
5292}
5293
5294bool ARMBaseInstrInfo::getInsertSubregLikeInputs(
5295    const MachineInstr &MI, unsigned DefIdx, RegSubRegPair &BaseReg,
5296    RegSubRegPairAndIdx &InsertedReg) const {
5297  assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index");
5298  assert(MI.isInsertSubregLike() && "Invalid kind of instruction");
5299
5300  switch (MI.getOpcode()) {
5301  case ARM::VSETLNi32:
5302    // dX = VSETLNi32 dY, rZ, imm
5303    const MachineOperand &MOBaseReg = MI.getOperand(1);
5304    const MachineOperand &MOInsertedReg = MI.getOperand(2);
5305    if (MOInsertedReg.isUndef())
5306      return false;
5307    const MachineOperand &MOIndex = MI.getOperand(3);
5308    BaseReg.Reg = MOBaseReg.getReg();
5309    BaseReg.SubReg = MOBaseReg.getSubReg();
5310
5311    InsertedReg.Reg = MOInsertedReg.getReg();
5312    InsertedReg.SubReg = MOInsertedReg.getSubReg();
5313    InsertedReg.SubIdx = MOIndex.getImm() == 0 ? ARM::ssub_0 : ARM::ssub_1;
5314    return true;
5315  }
5316  llvm_unreachable("Target dependent opcode missing");
5317}
5318
5319std::pair<unsigned, unsigned>
5320ARMBaseInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
5321  const unsigned Mask = ARMII::MO_OPTION_MASK;
5322  return std::make_pair(TF & Mask, TF & ~Mask);
5323}
5324
5325ArrayRef<std::pair<unsigned, const char *>>
5326ARMBaseInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
5327  using namespace ARMII;
5328
5329  static const std::pair<unsigned, const char *> TargetFlags[] = {
5330      {MO_LO16, "arm-lo16"}, {MO_HI16, "arm-hi16"}};
5331  return makeArrayRef(TargetFlags);
5332}
5333
5334ArrayRef<std::pair<unsigned, const char *>>
5335ARMBaseInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
5336  using namespace ARMII;
5337
5338  static const std::pair<unsigned, const char *> TargetFlags[] = {
5339      {MO_COFFSTUB, "arm-coffstub"},
5340      {MO_GOT, "arm-got"},
5341      {MO_SBREL, "arm-sbrel"},
5342      {MO_DLLIMPORT, "arm-dllimport"},
5343      {MO_SECREL, "arm-secrel"},
5344      {MO_NONLAZY, "arm-nonlazy"}};
5345  return makeArrayRef(TargetFlags);
5346}
5347
5348Optional<RegImmPair> ARMBaseInstrInfo::isAddImmediate(const MachineInstr &MI,
5349                                                      Register Reg) const {
5350  int Sign = 1;
5351  unsigned Opcode = MI.getOpcode();
5352  int64_t Offset = 0;
5353
5354  // TODO: Handle cases where Reg is a super- or sub-register of the
5355  // destination register.
5356  if (Reg != MI.getOperand(0).getReg())
5357    return None;
5358
5359  // We describe SUBri or ADDri instructions.
5360  if (Opcode == ARM::SUBri)
5361    Sign = -1;
5362  else if (Opcode != ARM::ADDri)
5363    return None;
5364
5365  // TODO: Third operand can be global address (usually some string). Since
5366  //       strings can be relocated we cannot calculate their offsets for
5367  //       now.
5368  if (!MI.getOperand(0).isReg() || !MI.getOperand(1).isReg() ||
5369      !MI.getOperand(2).isImm())
5370    return None;
5371
5372  Offset = MI.getOperand(2).getImm() * Sign;
5373  return RegImmPair{MI.getOperand(1).getReg(), Offset};
5374}
5375
5376bool llvm::registerDefinedBetween(unsigned Reg,
5377                                  MachineBasicBlock::iterator From,
5378                                  MachineBasicBlock::iterator To,
5379                                  const TargetRegisterInfo *TRI) {
5380  for (auto I = From; I != To; ++I)
5381    if (I->modifiesRegister(Reg, TRI))
5382      return true;
5383  return false;
5384}
5385
5386MachineInstr *llvm::findCMPToFoldIntoCBZ(MachineInstr *Br,
5387                                         const TargetRegisterInfo *TRI) {
5388  // Search backwards to the instruction that defines CSPR. This may or not
5389  // be a CMP, we check that after this loop. If we find another instruction
5390  // that reads cpsr, we return nullptr.
5391  MachineBasicBlock::iterator CmpMI = Br;
5392  while (CmpMI != Br->getParent()->begin()) {
5393    --CmpMI;
5394    if (CmpMI->modifiesRegister(ARM::CPSR, TRI))
5395      break;
5396    if (CmpMI->readsRegister(ARM::CPSR, TRI))
5397      break;
5398  }
5399
5400  // Check that this inst is a CMP r[0-7], #0 and that the register
5401  // is not redefined between the cmp and the br.
5402  if (CmpMI->getOpcode() != ARM::tCMPi8 && CmpMI->getOpcode() != ARM::t2CMPri)
5403    return nullptr;
5404  Register Reg = CmpMI->getOperand(0).getReg();
5405  unsigned PredReg = 0;
5406  ARMCC::CondCodes Pred = getInstrPredicate(*CmpMI, PredReg);
5407  if (Pred != ARMCC::AL || CmpMI->getOperand(1).getImm() != 0)
5408    return nullptr;
5409  if (!isARMLowRegister(Reg))
5410    return nullptr;
5411  if (registerDefinedBetween(Reg, CmpMI->getNextNode(), Br, TRI))
5412    return nullptr;
5413
5414  return &*CmpMI;
5415}
5416
5417unsigned llvm::ConstantMaterializationCost(unsigned Val,
5418                                           const ARMSubtarget *Subtarget,
5419                                           bool ForCodesize) {
5420  if (Subtarget->isThumb()) {
5421    if (Val <= 255) // MOV
5422      return ForCodesize ? 2 : 1;
5423    if (Subtarget->hasV6T2Ops() && (Val <= 0xffff ||                    // MOV
5424                                    ARM_AM::getT2SOImmVal(Val) != -1 || // MOVW
5425                                    ARM_AM::getT2SOImmVal(~Val) != -1)) // MVN
5426      return ForCodesize ? 4 : 1;
5427    if (Val <= 510) // MOV + ADDi8
5428      return ForCodesize ? 4 : 2;
5429    if (~Val <= 255) // MOV + MVN
5430      return ForCodesize ? 4 : 2;
5431    if (ARM_AM::isThumbImmShiftedVal(Val)) // MOV + LSL
5432      return ForCodesize ? 4 : 2;
5433  } else {
5434    if (ARM_AM::getSOImmVal(Val) != -1) // MOV
5435      return ForCodesize ? 4 : 1;
5436    if (ARM_AM::getSOImmVal(~Val) != -1) // MVN
5437      return ForCodesize ? 4 : 1;
5438    if (Subtarget->hasV6T2Ops() && Val <= 0xffff) // MOVW
5439      return ForCodesize ? 4 : 1;
5440    if (ARM_AM::isSOImmTwoPartVal(Val)) // two instrs
5441      return ForCodesize ? 8 : 2;
5442  }
5443  if (Subtarget->useMovt()) // MOVW + MOVT
5444    return ForCodesize ? 8 : 2;
5445  return ForCodesize ? 8 : 3; // Literal pool load
5446}
5447
5448bool llvm::HasLowerConstantMaterializationCost(unsigned Val1, unsigned Val2,
5449                                               const ARMSubtarget *Subtarget,
5450                                               bool ForCodesize) {
5451  // Check with ForCodesize
5452  unsigned Cost1 = ConstantMaterializationCost(Val1, Subtarget, ForCodesize);
5453  unsigned Cost2 = ConstantMaterializationCost(Val2, Subtarget, ForCodesize);
5454  if (Cost1 < Cost2)
5455    return true;
5456  if (Cost1 > Cost2)
5457    return false;
5458
5459  // If they are equal, try with !ForCodesize
5460  return ConstantMaterializationCost(Val1, Subtarget, !ForCodesize) <
5461         ConstantMaterializationCost(Val2, Subtarget, !ForCodesize);
5462}
5463