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