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