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