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