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