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