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