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