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