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