1 //===-- ARMBaseInstrInfo.cpp - ARM Instruction Information ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the Base ARM implementation of the TargetInstrInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "ARMBaseInstrInfo.h"
14 #include "ARMBaseRegisterInfo.h"
15 #include "ARMConstantPoolValue.h"
16 #include "ARMFeatures.h"
17 #include "ARMHazardRecognizer.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMSubtarget.h"
20 #include "MCTargetDesc/ARMAddressingModes.h"
21 #include "MCTargetDesc/ARMBaseInfo.h"
22 #include "MVETailPredUtils.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/CodeGen/LiveVariables.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineConstantPool.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineMemOperand.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineOperand.h"
38 #include "llvm/CodeGen/MachineRegisterInfo.h"
39 #include "llvm/CodeGen/MachineScheduler.h"
40 #include "llvm/CodeGen/MultiHazardRecognizer.h"
41 #include "llvm/CodeGen/ScoreboardHazardRecognizer.h"
42 #include "llvm/CodeGen/SelectionDAGNodes.h"
43 #include "llvm/CodeGen/TargetInstrInfo.h"
44 #include "llvm/CodeGen/TargetRegisterInfo.h"
45 #include "llvm/CodeGen/TargetSchedule.h"
46 #include "llvm/IR/Attributes.h"
47 #include "llvm/IR/Constants.h"
48 #include "llvm/IR/DebugLoc.h"
49 #include "llvm/IR/Function.h"
50 #include "llvm/IR/GlobalValue.h"
51 #include "llvm/MC/MCAsmInfo.h"
52 #include "llvm/MC/MCInstrDesc.h"
53 #include "llvm/MC/MCInstrItineraries.h"
54 #include "llvm/Support/BranchProbability.h"
55 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/CommandLine.h"
57 #include "llvm/Support/Compiler.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/ErrorHandling.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include "llvm/Target/TargetMachine.h"
62 #include <algorithm>
63 #include <cassert>
64 #include <cstdint>
65 #include <iterator>
66 #include <new>
67 #include <utility>
68 #include <vector>
69 
70 using namespace llvm;
71 
72 #define DEBUG_TYPE "arm-instrinfo"
73 
74 #define GET_INSTRINFO_CTOR_DTOR
75 #include "ARMGenInstrInfo.inc"
76 
77 static cl::opt<bool>
78 EnableARM3Addr("enable-arm-3-addr-conv", cl::Hidden,
79                cl::desc("Enable ARM 2-addr to 3-addr conv"));
80 
81 /// ARM_MLxEntry - Record information about MLA / MLS instructions.
82 struct ARM_MLxEntry {
83   uint16_t MLxOpc;     // MLA / MLS opcode
84   uint16_t MulOpc;     // Expanded multiplication opcode
85   uint16_t AddSubOpc;  // Expanded add / sub opcode
86   bool NegAcc;         // True if the acc is negated before the add / sub.
87   bool HasLane;        // True if instruction has an extra "lane" operand.
88 };
89 
90 static const ARM_MLxEntry ARM_MLxTable[] = {
91   // MLxOpc,          MulOpc,           AddSubOpc,       NegAcc, HasLane
92   // fp scalar ops
93   { ARM::VMLAS,       ARM::VMULS,       ARM::VADDS,      false,  false },
94   { ARM::VMLSS,       ARM::VMULS,       ARM::VSUBS,      false,  false },
95   { ARM::VMLAD,       ARM::VMULD,       ARM::VADDD,      false,  false },
96   { ARM::VMLSD,       ARM::VMULD,       ARM::VSUBD,      false,  false },
97   { ARM::VNMLAS,      ARM::VNMULS,      ARM::VSUBS,      true,   false },
98   { ARM::VNMLSS,      ARM::VMULS,       ARM::VSUBS,      true,   false },
99   { ARM::VNMLAD,      ARM::VNMULD,      ARM::VSUBD,      true,   false },
100   { ARM::VNMLSD,      ARM::VMULD,       ARM::VSUBD,      true,   false },
101 
102   // fp SIMD ops
103   { ARM::VMLAfd,      ARM::VMULfd,      ARM::VADDfd,     false,  false },
104   { ARM::VMLSfd,      ARM::VMULfd,      ARM::VSUBfd,     false,  false },
105   { ARM::VMLAfq,      ARM::VMULfq,      ARM::VADDfq,     false,  false },
106   { ARM::VMLSfq,      ARM::VMULfq,      ARM::VSUBfq,     false,  false },
107   { ARM::VMLAslfd,    ARM::VMULslfd,    ARM::VADDfd,     false,  true  },
108   { ARM::VMLSslfd,    ARM::VMULslfd,    ARM::VSUBfd,     false,  true  },
109   { ARM::VMLAslfq,    ARM::VMULslfq,    ARM::VADDfq,     false,  true  },
110   { ARM::VMLSslfq,    ARM::VMULslfq,    ARM::VSUBfq,     false,  true  },
111 };
112 
113 ARMBaseInstrInfo::ARMBaseInstrInfo(const ARMSubtarget& STI)
114   : ARMGenInstrInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP),
115     Subtarget(STI) {
116   for (unsigned i = 0, e = array_lengthof(ARM_MLxTable); i != e; ++i) {
117     if (!MLxEntryMap.insert(std::make_pair(ARM_MLxTable[i].MLxOpc, i)).second)
118       llvm_unreachable("Duplicated entries?");
119     MLxHazardOpcodes.insert(ARM_MLxTable[i].AddSubOpc);
120     MLxHazardOpcodes.insert(ARM_MLxTable[i].MulOpc);
121   }
122 }
123 
124 // Use a ScoreboardHazardRecognizer for prepass ARM scheduling. TargetInstrImpl
125 // currently defaults to no prepass hazard recognizer.
126 ScheduleHazardRecognizer *
127 ARMBaseInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
128                                                const ScheduleDAG *DAG) const {
129   if (usePreRAHazardRecognizer()) {
130     const InstrItineraryData *II =
131         static_cast<const ARMSubtarget *>(STI)->getInstrItineraryData();
132     return new ScoreboardHazardRecognizer(II, DAG, "pre-RA-sched");
133   }
134   return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
135 }
136 
137 // Called during:
138 // - pre-RA scheduling
139 // - post-RA scheduling when FeatureUseMISched is set
140 ScheduleHazardRecognizer *ARMBaseInstrInfo::CreateTargetMIHazardRecognizer(
141     const InstrItineraryData *II, const ScheduleDAGMI *DAG) const {
142   MultiHazardRecognizer *MHR = new MultiHazardRecognizer();
143 
144   // We would like to restrict this hazard recognizer to only
145   // post-RA scheduling; we can tell that we're post-RA because we don't
146   // track VRegLiveness.
147   // Cortex-M7: TRM indicates that there is a single ITCM bank and two DTCM
148   //            banks banked on bit 2.  Assume that TCMs are in use.
149   if (Subtarget.isCortexM7() && !DAG->hasVRegLiveness())
150     MHR->AddHazardRecognizer(
151         std::make_unique<ARMBankConflictHazardRecognizer>(DAG, 0x4, true));
152 
153   // Not inserting ARMHazardRecognizerFPMLx because that would change
154   // legacy behavior
155 
156   auto BHR = TargetInstrInfo::CreateTargetMIHazardRecognizer(II, DAG);
157   MHR->AddHazardRecognizer(std::unique_ptr<ScheduleHazardRecognizer>(BHR));
158   return MHR;
159 }
160 
161 // Called during post-RA scheduling when FeatureUseMISched is not set
162 ScheduleHazardRecognizer *ARMBaseInstrInfo::
163 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
164                                    const ScheduleDAG *DAG) const {
165   MultiHazardRecognizer *MHR = new MultiHazardRecognizer();
166 
167   if (Subtarget.isThumb2() || Subtarget.hasVFP2Base())
168     MHR->AddHazardRecognizer(std::make_unique<ARMHazardRecognizerFPMLx>());
169 
170   auto BHR = TargetInstrInfo::CreateTargetPostRAHazardRecognizer(II, DAG);
171   if (BHR)
172     MHR->AddHazardRecognizer(std::unique_ptr<ScheduleHazardRecognizer>(BHR));
173   return MHR;
174 }
175 
176 MachineInstr *ARMBaseInstrInfo::convertToThreeAddress(
177     MachineFunction::iterator &MFI, MachineInstr &MI, LiveVariables *LV) const {
178   // FIXME: Thumb2 support.
179 
180   if (!EnableARM3Addr)
181     return nullptr;
182 
183   MachineFunction &MF = *MI.getParent()->getParent();
184   uint64_t TSFlags = MI.getDesc().TSFlags;
185   bool isPre = false;
186   switch ((TSFlags & ARMII::IndexModeMask) >> ARMII::IndexModeShift) {
187   default: return nullptr;
188   case ARMII::IndexModePre:
189     isPre = true;
190     break;
191   case ARMII::IndexModePost:
192     break;
193   }
194 
195   // Try splitting an indexed load/store to an un-indexed one plus an add/sub
196   // operation.
197   unsigned MemOpc = getUnindexedOpcode(MI.getOpcode());
198   if (MemOpc == 0)
199     return nullptr;
200 
201   MachineInstr *UpdateMI = nullptr;
202   MachineInstr *MemMI = nullptr;
203   unsigned AddrMode = (TSFlags & ARMII::AddrModeMask);
204   const MCInstrDesc &MCID = MI.getDesc();
205   unsigned NumOps = MCID.getNumOperands();
206   bool isLoad = !MI.mayStore();
207   const MachineOperand &WB = isLoad ? MI.getOperand(1) : MI.getOperand(0);
208   const MachineOperand &Base = MI.getOperand(2);
209   const MachineOperand &Offset = MI.getOperand(NumOps - 3);
210   Register WBReg = WB.getReg();
211   Register BaseReg = Base.getReg();
212   Register OffReg = Offset.getReg();
213   unsigned OffImm = MI.getOperand(NumOps - 2).getImm();
214   ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI.getOperand(NumOps - 1).getImm();
215   switch (AddrMode) {
216   default: llvm_unreachable("Unknown indexed op!");
217   case ARMII::AddrMode2: {
218     bool isSub = ARM_AM::getAM2Op(OffImm) == ARM_AM::sub;
219     unsigned Amt = ARM_AM::getAM2Offset(OffImm);
220     if (OffReg == 0) {
221       if (ARM_AM::getSOImmVal(Amt) == -1)
222         // Can't encode it in a so_imm operand. This transformation will
223         // add more than 1 instruction. Abandon!
224         return nullptr;
225       UpdateMI = BuildMI(MF, MI.getDebugLoc(),
226                          get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
227                      .addReg(BaseReg)
228                      .addImm(Amt)
229                      .add(predOps(Pred))
230                      .add(condCodeOp());
231     } else if (Amt != 0) {
232       ARM_AM::ShiftOpc ShOpc = ARM_AM::getAM2ShiftOpc(OffImm);
233       unsigned SOOpc = ARM_AM::getSORegOpc(ShOpc, Amt);
234       UpdateMI = BuildMI(MF, MI.getDebugLoc(),
235                          get(isSub ? ARM::SUBrsi : ARM::ADDrsi), WBReg)
236                      .addReg(BaseReg)
237                      .addReg(OffReg)
238                      .addReg(0)
239                      .addImm(SOOpc)
240                      .add(predOps(Pred))
241                      .add(condCodeOp());
242     } else
243       UpdateMI = BuildMI(MF, MI.getDebugLoc(),
244                          get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
245                      .addReg(BaseReg)
246                      .addReg(OffReg)
247                      .add(predOps(Pred))
248                      .add(condCodeOp());
249     break;
250   }
251   case ARMII::AddrMode3 : {
252     bool isSub = ARM_AM::getAM3Op(OffImm) == ARM_AM::sub;
253     unsigned Amt = ARM_AM::getAM3Offset(OffImm);
254     if (OffReg == 0)
255       // Immediate is 8-bits. It's guaranteed to fit in a so_imm operand.
256       UpdateMI = BuildMI(MF, MI.getDebugLoc(),
257                          get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
258                      .addReg(BaseReg)
259                      .addImm(Amt)
260                      .add(predOps(Pred))
261                      .add(condCodeOp());
262     else
263       UpdateMI = BuildMI(MF, MI.getDebugLoc(),
264                          get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
265                      .addReg(BaseReg)
266                      .addReg(OffReg)
267                      .add(predOps(Pred))
268                      .add(condCodeOp());
269     break;
270   }
271   }
272 
273   std::vector<MachineInstr*> NewMIs;
274   if (isPre) {
275     if (isLoad)
276       MemMI =
277           BuildMI(MF, MI.getDebugLoc(), get(MemOpc), MI.getOperand(0).getReg())
278               .addReg(WBReg)
279               .addImm(0)
280               .addImm(Pred);
281     else
282       MemMI = BuildMI(MF, MI.getDebugLoc(), get(MemOpc))
283                   .addReg(MI.getOperand(1).getReg())
284                   .addReg(WBReg)
285                   .addReg(0)
286                   .addImm(0)
287                   .addImm(Pred);
288     NewMIs.push_back(MemMI);
289     NewMIs.push_back(UpdateMI);
290   } else {
291     if (isLoad)
292       MemMI =
293           BuildMI(MF, MI.getDebugLoc(), get(MemOpc), MI.getOperand(0).getReg())
294               .addReg(BaseReg)
295               .addImm(0)
296               .addImm(Pred);
297     else
298       MemMI = BuildMI(MF, MI.getDebugLoc(), get(MemOpc))
299                   .addReg(MI.getOperand(1).getReg())
300                   .addReg(BaseReg)
301                   .addReg(0)
302                   .addImm(0)
303                   .addImm(Pred);
304     if (WB.isDead())
305       UpdateMI->getOperand(0).setIsDead();
306     NewMIs.push_back(UpdateMI);
307     NewMIs.push_back(MemMI);
308   }
309 
310   // Transfer LiveVariables states, kill / dead info.
311   if (LV) {
312     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
313       MachineOperand &MO = MI.getOperand(i);
314       if (MO.isReg() && Register::isVirtualRegister(MO.getReg())) {
315         Register Reg = MO.getReg();
316 
317         LiveVariables::VarInfo &VI = LV->getVarInfo(Reg);
318         if (MO.isDef()) {
319           MachineInstr *NewMI = (Reg == WBReg) ? UpdateMI : MemMI;
320           if (MO.isDead())
321             LV->addVirtualRegisterDead(Reg, *NewMI);
322         }
323         if (MO.isUse() && MO.isKill()) {
324           for (unsigned j = 0; j < 2; ++j) {
325             // Look at the two new MI's in reverse order.
326             MachineInstr *NewMI = NewMIs[j];
327             if (!NewMI->readsRegister(Reg))
328               continue;
329             LV->addVirtualRegisterKilled(Reg, *NewMI);
330             if (VI.removeKill(MI))
331               VI.Kills.push_back(NewMI);
332             break;
333           }
334         }
335       }
336     }
337   }
338 
339   MachineBasicBlock::iterator MBBI = MI.getIterator();
340   MFI->insert(MBBI, NewMIs[1]);
341   MFI->insert(MBBI, NewMIs[0]);
342   return NewMIs[0];
343 }
344 
345 // Branch analysis.
346 bool ARMBaseInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
347                                      MachineBasicBlock *&TBB,
348                                      MachineBasicBlock *&FBB,
349                                      SmallVectorImpl<MachineOperand> &Cond,
350                                      bool AllowModify) const {
351   TBB = nullptr;
352   FBB = nullptr;
353 
354   MachineBasicBlock::instr_iterator I = MBB.instr_end();
355   if (I == MBB.instr_begin())
356     return false; // Empty blocks are easy.
357   --I;
358 
359   // Walk backwards from the end of the basic block until the branch is
360   // analyzed or we give up.
361   while (isPredicated(*I) || I->isTerminator() || I->isDebugValue()) {
362     // Flag to be raised on unanalyzeable instructions. This is useful in cases
363     // where we want to clean up on the end of the basic block before we bail
364     // out.
365     bool CantAnalyze = false;
366 
367     // Skip over DEBUG values, predicated nonterminators and speculation
368     // barrier terminators.
369     while (I->isDebugInstr() || !I->isTerminator() ||
370            isSpeculationBarrierEndBBOpcode(I->getOpcode()) ){
371       if (I == MBB.instr_begin())
372         return false;
373       --I;
374     }
375 
376     if (isIndirectBranchOpcode(I->getOpcode()) ||
377         isJumpTableBranchOpcode(I->getOpcode())) {
378       // Indirect branches and jump tables can't be analyzed, but we still want
379       // to clean up any instructions at the tail of the basic block.
380       CantAnalyze = true;
381     } else if (isUncondBranchOpcode(I->getOpcode())) {
382       TBB = I->getOperand(0).getMBB();
383     } else if (isCondBranchOpcode(I->getOpcode())) {
384       // Bail out if we encounter multiple conditional branches.
385       if (!Cond.empty())
386         return true;
387 
388       assert(!FBB && "FBB should have been null.");
389       FBB = TBB;
390       TBB = I->getOperand(0).getMBB();
391       Cond.push_back(I->getOperand(1));
392       Cond.push_back(I->getOperand(2));
393     } else if (I->isReturn()) {
394       // Returns can't be analyzed, but we should run cleanup.
395       CantAnalyze = true;
396     } else {
397       // We encountered other unrecognized terminator. Bail out immediately.
398       return true;
399     }
400 
401     // Cleanup code - to be run for unpredicated unconditional branches and
402     //                returns.
403     if (!isPredicated(*I) &&
404           (isUncondBranchOpcode(I->getOpcode()) ||
405            isIndirectBranchOpcode(I->getOpcode()) ||
406            isJumpTableBranchOpcode(I->getOpcode()) ||
407            I->isReturn())) {
408       // Forget any previous condition branch information - it no longer applies.
409       Cond.clear();
410       FBB = nullptr;
411 
412       // If we can modify the function, delete everything below this
413       // unconditional branch.
414       if (AllowModify) {
415         MachineBasicBlock::iterator DI = std::next(I);
416         while (DI != MBB.instr_end()) {
417           MachineInstr &InstToDelete = *DI;
418           ++DI;
419           // Speculation barriers must not be deleted.
420           if (isSpeculationBarrierEndBBOpcode(InstToDelete.getOpcode()))
421             continue;
422           InstToDelete.eraseFromParent();
423         }
424       }
425     }
426 
427     if (CantAnalyze) {
428       // We may not be able to analyze the block, but we could still have
429       // an unconditional branch as the last instruction in the block, which
430       // just branches to layout successor. If this is the case, then just
431       // remove it if we're allowed to make modifications.
432       if (AllowModify && !isPredicated(MBB.back()) &&
433           isUncondBranchOpcode(MBB.back().getOpcode()) &&
434           TBB && MBB.isLayoutSuccessor(TBB))
435         removeBranch(MBB);
436       return true;
437     }
438 
439     if (I == MBB.instr_begin())
440       return false;
441 
442     --I;
443   }
444 
445   // We made it past the terminators without bailing out - we must have
446   // analyzed this branch successfully.
447   return false;
448 }
449 
450 unsigned ARMBaseInstrInfo::removeBranch(MachineBasicBlock &MBB,
451                                         int *BytesRemoved) const {
452   assert(!BytesRemoved && "code size not handled");
453 
454   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
455   if (I == MBB.end())
456     return 0;
457 
458   if (!isUncondBranchOpcode(I->getOpcode()) &&
459       !isCondBranchOpcode(I->getOpcode()))
460     return 0;
461 
462   // Remove the branch.
463   I->eraseFromParent();
464 
465   I = MBB.end();
466 
467   if (I == MBB.begin()) return 1;
468   --I;
469   if (!isCondBranchOpcode(I->getOpcode()))
470     return 1;
471 
472   // Remove the branch.
473   I->eraseFromParent();
474   return 2;
475 }
476 
477 unsigned ARMBaseInstrInfo::insertBranch(MachineBasicBlock &MBB,
478                                         MachineBasicBlock *TBB,
479                                         MachineBasicBlock *FBB,
480                                         ArrayRef<MachineOperand> Cond,
481                                         const DebugLoc &DL,
482                                         int *BytesAdded) const {
483   assert(!BytesAdded && "code size not handled");
484   ARMFunctionInfo *AFI = MBB.getParent()->getInfo<ARMFunctionInfo>();
485   int BOpc   = !AFI->isThumbFunction()
486     ? ARM::B : (AFI->isThumb2Function() ? ARM::t2B : ARM::tB);
487   int BccOpc = !AFI->isThumbFunction()
488     ? ARM::Bcc : (AFI->isThumb2Function() ? ARM::t2Bcc : ARM::tBcc);
489   bool isThumb = AFI->isThumbFunction() || AFI->isThumb2Function();
490 
491   // Shouldn't be a fall through.
492   assert(TBB && "insertBranch must not be told to insert a fallthrough");
493   assert((Cond.size() == 2 || Cond.size() == 0) &&
494          "ARM branch conditions have two components!");
495 
496   // For conditional branches, we use addOperand to preserve CPSR flags.
497 
498   if (!FBB) {
499     if (Cond.empty()) { // Unconditional branch?
500       if (isThumb)
501         BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB).add(predOps(ARMCC::AL));
502       else
503         BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB);
504     } else
505       BuildMI(&MBB, DL, get(BccOpc))
506           .addMBB(TBB)
507           .addImm(Cond[0].getImm())
508           .add(Cond[1]);
509     return 1;
510   }
511 
512   // Two-way conditional branch.
513   BuildMI(&MBB, DL, get(BccOpc))
514       .addMBB(TBB)
515       .addImm(Cond[0].getImm())
516       .add(Cond[1]);
517   if (isThumb)
518     BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB).add(predOps(ARMCC::AL));
519   else
520     BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB);
521   return 2;
522 }
523 
524 bool ARMBaseInstrInfo::
525 reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
526   ARMCC::CondCodes CC = (ARMCC::CondCodes)(int)Cond[0].getImm();
527   Cond[0].setImm(ARMCC::getOppositeCondition(CC));
528   return false;
529 }
530 
531 bool ARMBaseInstrInfo::isPredicated(const MachineInstr &MI) const {
532   if (MI.isBundle()) {
533     MachineBasicBlock::const_instr_iterator I = MI.getIterator();
534     MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
535     while (++I != E && I->isInsideBundle()) {
536       int PIdx = I->findFirstPredOperandIdx();
537       if (PIdx != -1 && I->getOperand(PIdx).getImm() != ARMCC::AL)
538         return true;
539     }
540     return false;
541   }
542 
543   int PIdx = MI.findFirstPredOperandIdx();
544   return PIdx != -1 && MI.getOperand(PIdx).getImm() != ARMCC::AL;
545 }
546 
547 std::string ARMBaseInstrInfo::createMIROperandComment(
548     const MachineInstr &MI, const MachineOperand &Op, unsigned OpIdx,
549     const TargetRegisterInfo *TRI) const {
550 
551   // First, let's see if there is a generic comment for this operand
552   std::string GenericComment =
553       TargetInstrInfo::createMIROperandComment(MI, Op, OpIdx, TRI);
554   if (!GenericComment.empty())
555     return GenericComment;
556 
557   // If not, check if we have an immediate operand.
558   if (Op.getType() != MachineOperand::MO_Immediate)
559     return std::string();
560 
561   // And print its corresponding condition code if the immediate is a
562   // predicate.
563   int FirstPredOp = MI.findFirstPredOperandIdx();
564   if (FirstPredOp != (int) OpIdx)
565     return std::string();
566 
567   std::string CC = "CC::";
568   CC += ARMCondCodeToString((ARMCC::CondCodes)Op.getImm());
569   return CC;
570 }
571 
572 bool ARMBaseInstrInfo::PredicateInstruction(
573     MachineInstr &MI, ArrayRef<MachineOperand> Pred) const {
574   unsigned Opc = MI.getOpcode();
575   if (isUncondBranchOpcode(Opc)) {
576     MI.setDesc(get(getMatchingCondBranchOpcode(Opc)));
577     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
578       .addImm(Pred[0].getImm())
579       .addReg(Pred[1].getReg());
580     return true;
581   }
582 
583   int PIdx = MI.findFirstPredOperandIdx();
584   if (PIdx != -1) {
585     MachineOperand &PMO = MI.getOperand(PIdx);
586     PMO.setImm(Pred[0].getImm());
587     MI.getOperand(PIdx+1).setReg(Pred[1].getReg());
588 
589     // Thumb 1 arithmetic instructions do not set CPSR when executed inside an
590     // IT block. This affects how they are printed.
591     const MCInstrDesc &MCID = MI.getDesc();
592     if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
593       assert(MCID.OpInfo[1].isOptionalDef() && "CPSR def isn't expected operand");
594       assert((MI.getOperand(1).isDead() ||
595               MI.getOperand(1).getReg() != ARM::CPSR) &&
596              "if conversion tried to stop defining used CPSR");
597       MI.getOperand(1).setReg(ARM::NoRegister);
598     }
599 
600     return true;
601   }
602   return false;
603 }
604 
605 bool ARMBaseInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
606                                          ArrayRef<MachineOperand> Pred2) const {
607   if (Pred1.size() > 2 || Pred2.size() > 2)
608     return false;
609 
610   ARMCC::CondCodes CC1 = (ARMCC::CondCodes)Pred1[0].getImm();
611   ARMCC::CondCodes CC2 = (ARMCC::CondCodes)Pred2[0].getImm();
612   if (CC1 == CC2)
613     return true;
614 
615   switch (CC1) {
616   default:
617     return false;
618   case ARMCC::AL:
619     return true;
620   case ARMCC::HS:
621     return CC2 == ARMCC::HI;
622   case ARMCC::LS:
623     return CC2 == ARMCC::LO || CC2 == ARMCC::EQ;
624   case ARMCC::GE:
625     return CC2 == ARMCC::GT;
626   case ARMCC::LE:
627     return CC2 == ARMCC::LT;
628   }
629 }
630 
631 bool ARMBaseInstrInfo::ClobbersPredicate(MachineInstr &MI,
632                                          std::vector<MachineOperand> &Pred,
633                                          bool SkipDead) const {
634   bool Found = false;
635   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
636     const MachineOperand &MO = MI.getOperand(i);
637     bool ClobbersCPSR = MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR);
638     bool IsCPSR = MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR;
639     if (ClobbersCPSR || IsCPSR) {
640 
641       // Filter out T1 instructions that have a dead CPSR,
642       // allowing IT blocks to be generated containing T1 instructions
643       const MCInstrDesc &MCID = MI.getDesc();
644       if (MCID.TSFlags & ARMII::ThumbArithFlagSetting && MO.isDead() &&
645           SkipDead)
646         continue;
647 
648       Pred.push_back(MO);
649       Found = true;
650     }
651   }
652 
653   return Found;
654 }
655 
656 bool ARMBaseInstrInfo::isCPSRDefined(const MachineInstr &MI) {
657   for (const auto &MO : MI.operands())
658     if (MO.isReg() && MO.getReg() == ARM::CPSR && MO.isDef() && !MO.isDead())
659       return true;
660   return false;
661 }
662 
663 static bool isEligibleForITBlock(const MachineInstr *MI) {
664   switch (MI->getOpcode()) {
665   default: return true;
666   case ARM::tADC:   // ADC (register) T1
667   case ARM::tADDi3: // ADD (immediate) T1
668   case ARM::tADDi8: // ADD (immediate) T2
669   case ARM::tADDrr: // ADD (register) T1
670   case ARM::tAND:   // AND (register) T1
671   case ARM::tASRri: // ASR (immediate) T1
672   case ARM::tASRrr: // ASR (register) T1
673   case ARM::tBIC:   // BIC (register) T1
674   case ARM::tEOR:   // EOR (register) T1
675   case ARM::tLSLri: // LSL (immediate) T1
676   case ARM::tLSLrr: // LSL (register) T1
677   case ARM::tLSRri: // LSR (immediate) T1
678   case ARM::tLSRrr: // LSR (register) T1
679   case ARM::tMUL:   // MUL T1
680   case ARM::tMVN:   // MVN (register) T1
681   case ARM::tORR:   // ORR (register) T1
682   case ARM::tROR:   // ROR (register) T1
683   case ARM::tRSB:   // RSB (immediate) T1
684   case ARM::tSBC:   // SBC (register) T1
685   case ARM::tSUBi3: // SUB (immediate) T1
686   case ARM::tSUBi8: // SUB (immediate) T2
687   case ARM::tSUBrr: // SUB (register) T1
688     return !ARMBaseInstrInfo::isCPSRDefined(*MI);
689   }
690 }
691 
692 /// isPredicable - Return true if the specified instruction can be predicated.
693 /// By default, this returns true for every instruction with a
694 /// PredicateOperand.
695 bool ARMBaseInstrInfo::isPredicable(const MachineInstr &MI) const {
696   if (!MI.isPredicable())
697     return false;
698 
699   if (MI.isBundle())
700     return false;
701 
702   if (!isEligibleForITBlock(&MI))
703     return false;
704 
705   const MachineFunction *MF = MI.getParent()->getParent();
706   const ARMFunctionInfo *AFI =
707       MF->getInfo<ARMFunctionInfo>();
708 
709   // Neon instructions in Thumb2 IT blocks are deprecated, see ARMARM.
710   // In their ARM encoding, they can't be encoded in a conditional form.
711   if ((MI.getDesc().TSFlags & ARMII::DomainMask) == ARMII::DomainNEON)
712     return false;
713 
714   // Make indirect control flow changes unpredicable when SLS mitigation is
715   // enabled.
716   const ARMSubtarget &ST = MF->getSubtarget<ARMSubtarget>();
717   if (ST.hardenSlsRetBr() && isIndirectControlFlowNotComingBack(MI))
718     return false;
719   if (ST.hardenSlsBlr() && isIndirectCall(MI))
720     return false;
721 
722   if (AFI->isThumb2Function()) {
723     if (getSubtarget().restrictIT())
724       return isV8EligibleForIT(&MI);
725   }
726 
727   return true;
728 }
729 
730 namespace llvm {
731 
732 template <> bool IsCPSRDead<MachineInstr>(const MachineInstr *MI) {
733   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
734     const MachineOperand &MO = MI->getOperand(i);
735     if (!MO.isReg() || MO.isUndef() || MO.isUse())
736       continue;
737     if (MO.getReg() != ARM::CPSR)
738       continue;
739     if (!MO.isDead())
740       return false;
741   }
742   // all definitions of CPSR are dead
743   return true;
744 }
745 
746 } // end namespace llvm
747 
748 /// GetInstSize - Return the size of the specified MachineInstr.
749 ///
750 unsigned ARMBaseInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
751   const MachineBasicBlock &MBB = *MI.getParent();
752   const MachineFunction *MF = MBB.getParent();
753   const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
754 
755   const MCInstrDesc &MCID = MI.getDesc();
756   if (MCID.getSize())
757     return MCID.getSize();
758 
759   switch (MI.getOpcode()) {
760   default:
761     // pseudo-instruction sizes are zero.
762     return 0;
763   case TargetOpcode::BUNDLE:
764     return getInstBundleLength(MI);
765   case ARM::MOVi16_ga_pcrel:
766   case ARM::MOVTi16_ga_pcrel:
767   case ARM::t2MOVi16_ga_pcrel:
768   case ARM::t2MOVTi16_ga_pcrel:
769     return 4;
770   case ARM::MOVi32imm:
771   case ARM::t2MOVi32imm:
772     return 8;
773   case ARM::CONSTPOOL_ENTRY:
774   case ARM::JUMPTABLE_INSTS:
775   case ARM::JUMPTABLE_ADDRS:
776   case ARM::JUMPTABLE_TBB:
777   case ARM::JUMPTABLE_TBH:
778     // If this machine instr is a constant pool entry, its size is recorded as
779     // operand #2.
780     return MI.getOperand(2).getImm();
781   case ARM::Int_eh_sjlj_longjmp:
782     return 16;
783   case ARM::tInt_eh_sjlj_longjmp:
784     return 10;
785   case ARM::tInt_WIN_eh_sjlj_longjmp:
786     return 12;
787   case ARM::Int_eh_sjlj_setjmp:
788   case ARM::Int_eh_sjlj_setjmp_nofp:
789     return 20;
790   case ARM::tInt_eh_sjlj_setjmp:
791   case ARM::t2Int_eh_sjlj_setjmp:
792   case ARM::t2Int_eh_sjlj_setjmp_nofp:
793     return 12;
794   case ARM::SPACE:
795     return MI.getOperand(1).getImm();
796   case ARM::INLINEASM:
797   case ARM::INLINEASM_BR: {
798     // If this machine instr is an inline asm, measure it.
799     unsigned Size = getInlineAsmLength(MI.getOperand(0).getSymbolName(), *MAI);
800     if (!MF->getInfo<ARMFunctionInfo>()->isThumbFunction())
801       Size = alignTo(Size, 4);
802     return Size;
803   }
804   case ARM::SpeculationBarrierISBDSBEndBB:
805   case ARM::t2SpeculationBarrierISBDSBEndBB:
806     // This gets lowered to 2 4-byte instructions.
807     return 8;
808   case ARM::SpeculationBarrierSBEndBB:
809   case ARM::t2SpeculationBarrierSBEndBB:
810     // This gets lowered to 1 4-byte instructions.
811     return 4;
812   }
813 }
814 
815 unsigned ARMBaseInstrInfo::getInstBundleLength(const MachineInstr &MI) const {
816   unsigned Size = 0;
817   MachineBasicBlock::const_instr_iterator I = MI.getIterator();
818   MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
819   while (++I != E && I->isInsideBundle()) {
820     assert(!I->isBundle() && "No nested bundle!");
821     Size += getInstSizeInBytes(*I);
822   }
823   return Size;
824 }
825 
826 void ARMBaseInstrInfo::copyFromCPSR(MachineBasicBlock &MBB,
827                                     MachineBasicBlock::iterator I,
828                                     unsigned DestReg, bool KillSrc,
829                                     const ARMSubtarget &Subtarget) const {
830   unsigned Opc = Subtarget.isThumb()
831                      ? (Subtarget.isMClass() ? ARM::t2MRS_M : ARM::t2MRS_AR)
832                      : ARM::MRS;
833 
834   MachineInstrBuilder MIB =
835       BuildMI(MBB, I, I->getDebugLoc(), get(Opc), DestReg);
836 
837   // There is only 1 A/R class MRS instruction, and it always refers to
838   // APSR. However, there are lots of other possibilities on M-class cores.
839   if (Subtarget.isMClass())
840     MIB.addImm(0x800);
841 
842   MIB.add(predOps(ARMCC::AL))
843      .addReg(ARM::CPSR, RegState::Implicit | getKillRegState(KillSrc));
844 }
845 
846 void ARMBaseInstrInfo::copyToCPSR(MachineBasicBlock &MBB,
847                                   MachineBasicBlock::iterator I,
848                                   unsigned SrcReg, bool KillSrc,
849                                   const ARMSubtarget &Subtarget) const {
850   unsigned Opc = Subtarget.isThumb()
851                      ? (Subtarget.isMClass() ? ARM::t2MSR_M : ARM::t2MSR_AR)
852                      : ARM::MSR;
853 
854   MachineInstrBuilder MIB = BuildMI(MBB, I, I->getDebugLoc(), get(Opc));
855 
856   if (Subtarget.isMClass())
857     MIB.addImm(0x800);
858   else
859     MIB.addImm(8);
860 
861   MIB.addReg(SrcReg, getKillRegState(KillSrc))
862      .add(predOps(ARMCC::AL))
863      .addReg(ARM::CPSR, RegState::Implicit | RegState::Define);
864 }
865 
866 void llvm::addUnpredicatedMveVpredNOp(MachineInstrBuilder &MIB) {
867   MIB.addImm(ARMVCC::None);
868   MIB.addReg(0);
869 }
870 
871 void llvm::addUnpredicatedMveVpredROp(MachineInstrBuilder &MIB,
872                                       Register DestReg) {
873   addUnpredicatedMveVpredNOp(MIB);
874   MIB.addReg(DestReg, RegState::Undef);
875 }
876 
877 void llvm::addPredicatedMveVpredNOp(MachineInstrBuilder &MIB, unsigned Cond) {
878   MIB.addImm(Cond);
879   MIB.addReg(ARM::VPR, RegState::Implicit);
880 }
881 
882 void llvm::addPredicatedMveVpredROp(MachineInstrBuilder &MIB,
883                                     unsigned Cond, unsigned Inactive) {
884   addPredicatedMveVpredNOp(MIB, Cond);
885   MIB.addReg(Inactive);
886 }
887 
888 void ARMBaseInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
889                                    MachineBasicBlock::iterator I,
890                                    const DebugLoc &DL, MCRegister DestReg,
891                                    MCRegister SrcReg, bool KillSrc) const {
892   bool GPRDest = ARM::GPRRegClass.contains(DestReg);
893   bool GPRSrc = ARM::GPRRegClass.contains(SrcReg);
894 
895   if (GPRDest && GPRSrc) {
896     BuildMI(MBB, I, DL, get(ARM::MOVr), DestReg)
897         .addReg(SrcReg, getKillRegState(KillSrc))
898         .add(predOps(ARMCC::AL))
899         .add(condCodeOp());
900     return;
901   }
902 
903   bool SPRDest = ARM::SPRRegClass.contains(DestReg);
904   bool SPRSrc = ARM::SPRRegClass.contains(SrcReg);
905 
906   unsigned Opc = 0;
907   if (SPRDest && SPRSrc)
908     Opc = ARM::VMOVS;
909   else if (GPRDest && SPRSrc)
910     Opc = ARM::VMOVRS;
911   else if (SPRDest && GPRSrc)
912     Opc = ARM::VMOVSR;
913   else if (ARM::DPRRegClass.contains(DestReg, SrcReg) && Subtarget.hasFP64())
914     Opc = ARM::VMOVD;
915   else if (ARM::QPRRegClass.contains(DestReg, SrcReg))
916     Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR;
917 
918   if (Opc) {
919     MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opc), DestReg);
920     MIB.addReg(SrcReg, getKillRegState(KillSrc));
921     if (Opc == ARM::VORRq || Opc == ARM::MVE_VORR)
922       MIB.addReg(SrcReg, getKillRegState(KillSrc));
923     if (Opc == ARM::MVE_VORR)
924       addUnpredicatedMveVpredROp(MIB, DestReg);
925     else
926       MIB.add(predOps(ARMCC::AL));
927     return;
928   }
929 
930   // Handle register classes that require multiple instructions.
931   unsigned BeginIdx = 0;
932   unsigned SubRegs = 0;
933   int Spacing = 1;
934 
935   // Use VORRq when possible.
936   if (ARM::QQPRRegClass.contains(DestReg, SrcReg)) {
937     Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR;
938     BeginIdx = ARM::qsub_0;
939     SubRegs = 2;
940   } else if (ARM::QQQQPRRegClass.contains(DestReg, SrcReg)) {
941     Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR;
942     BeginIdx = ARM::qsub_0;
943     SubRegs = 4;
944   // Fall back to VMOVD.
945   } else if (ARM::DPairRegClass.contains(DestReg, SrcReg)) {
946     Opc = ARM::VMOVD;
947     BeginIdx = ARM::dsub_0;
948     SubRegs = 2;
949   } else if (ARM::DTripleRegClass.contains(DestReg, SrcReg)) {
950     Opc = ARM::VMOVD;
951     BeginIdx = ARM::dsub_0;
952     SubRegs = 3;
953   } else if (ARM::DQuadRegClass.contains(DestReg, SrcReg)) {
954     Opc = ARM::VMOVD;
955     BeginIdx = ARM::dsub_0;
956     SubRegs = 4;
957   } else if (ARM::GPRPairRegClass.contains(DestReg, SrcReg)) {
958     Opc = Subtarget.isThumb2() ? ARM::tMOVr : ARM::MOVr;
959     BeginIdx = ARM::gsub_0;
960     SubRegs = 2;
961   } else if (ARM::DPairSpcRegClass.contains(DestReg, SrcReg)) {
962     Opc = ARM::VMOVD;
963     BeginIdx = ARM::dsub_0;
964     SubRegs = 2;
965     Spacing = 2;
966   } else if (ARM::DTripleSpcRegClass.contains(DestReg, SrcReg)) {
967     Opc = ARM::VMOVD;
968     BeginIdx = ARM::dsub_0;
969     SubRegs = 3;
970     Spacing = 2;
971   } else if (ARM::DQuadSpcRegClass.contains(DestReg, SrcReg)) {
972     Opc = ARM::VMOVD;
973     BeginIdx = ARM::dsub_0;
974     SubRegs = 4;
975     Spacing = 2;
976   } else if (ARM::DPRRegClass.contains(DestReg, SrcReg) &&
977              !Subtarget.hasFP64()) {
978     Opc = ARM::VMOVS;
979     BeginIdx = ARM::ssub_0;
980     SubRegs = 2;
981   } else if (SrcReg == ARM::CPSR) {
982     copyFromCPSR(MBB, I, DestReg, KillSrc, Subtarget);
983     return;
984   } else if (DestReg == ARM::CPSR) {
985     copyToCPSR(MBB, I, SrcReg, KillSrc, Subtarget);
986     return;
987   } else if (DestReg == ARM::VPR) {
988     assert(ARM::GPRRegClass.contains(SrcReg));
989     BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMSR_P0), DestReg)
990         .addReg(SrcReg, getKillRegState(KillSrc))
991         .add(predOps(ARMCC::AL));
992     return;
993   } else if (SrcReg == ARM::VPR) {
994     assert(ARM::GPRRegClass.contains(DestReg));
995     BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMRS_P0), DestReg)
996         .addReg(SrcReg, getKillRegState(KillSrc))
997         .add(predOps(ARMCC::AL));
998     return;
999   } else if (DestReg == ARM::FPSCR_NZCV) {
1000     assert(ARM::GPRRegClass.contains(SrcReg));
1001     BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMSR_FPSCR_NZCVQC), DestReg)
1002         .addReg(SrcReg, getKillRegState(KillSrc))
1003         .add(predOps(ARMCC::AL));
1004     return;
1005   } else if (SrcReg == ARM::FPSCR_NZCV) {
1006     assert(ARM::GPRRegClass.contains(DestReg));
1007     BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMRS_FPSCR_NZCVQC), DestReg)
1008         .addReg(SrcReg, getKillRegState(KillSrc))
1009         .add(predOps(ARMCC::AL));
1010     return;
1011   }
1012 
1013   assert(Opc && "Impossible reg-to-reg copy");
1014 
1015   const TargetRegisterInfo *TRI = &getRegisterInfo();
1016   MachineInstrBuilder Mov;
1017 
1018   // Copy register tuples backward when the first Dest reg overlaps with SrcReg.
1019   if (TRI->regsOverlap(SrcReg, TRI->getSubReg(DestReg, BeginIdx))) {
1020     BeginIdx = BeginIdx + ((SubRegs - 1) * Spacing);
1021     Spacing = -Spacing;
1022   }
1023 #ifndef NDEBUG
1024   SmallSet<unsigned, 4> DstRegs;
1025 #endif
1026   for (unsigned i = 0; i != SubRegs; ++i) {
1027     Register Dst = TRI->getSubReg(DestReg, BeginIdx + i * Spacing);
1028     Register Src = TRI->getSubReg(SrcReg, BeginIdx + i * Spacing);
1029     assert(Dst && Src && "Bad sub-register");
1030 #ifndef NDEBUG
1031     assert(!DstRegs.count(Src) && "destructive vector copy");
1032     DstRegs.insert(Dst);
1033 #endif
1034     Mov = BuildMI(MBB, I, I->getDebugLoc(), get(Opc), Dst).addReg(Src);
1035     // VORR (NEON or MVE) takes two source operands.
1036     if (Opc == ARM::VORRq || Opc == ARM::MVE_VORR) {
1037       Mov.addReg(Src);
1038     }
1039     // MVE VORR takes predicate operands in place of an ordinary condition.
1040     if (Opc == ARM::MVE_VORR)
1041       addUnpredicatedMveVpredROp(Mov, Dst);
1042     else
1043       Mov = Mov.add(predOps(ARMCC::AL));
1044     // MOVr can set CC.
1045     if (Opc == ARM::MOVr)
1046       Mov = Mov.add(condCodeOp());
1047   }
1048   // Add implicit super-register defs and kills to the last instruction.
1049   Mov->addRegisterDefined(DestReg, TRI);
1050   if (KillSrc)
1051     Mov->addRegisterKilled(SrcReg, TRI);
1052 }
1053 
1054 Optional<DestSourcePair>
1055 ARMBaseInstrInfo::isCopyInstrImpl(const MachineInstr &MI) const {
1056   // VMOVRRD is also a copy instruction but it requires
1057   // special way of handling. It is more complex copy version
1058   // and since that we are not considering it. For recognition
1059   // of such instruction isExtractSubregLike MI interface fuction
1060   // could be used.
1061   // VORRq is considered as a move only if two inputs are
1062   // the same register.
1063   if (!MI.isMoveReg() ||
1064       (MI.getOpcode() == ARM::VORRq &&
1065        MI.getOperand(1).getReg() != MI.getOperand(2).getReg()))
1066     return None;
1067   return DestSourcePair{MI.getOperand(0), MI.getOperand(1)};
1068 }
1069 
1070 Optional<ParamLoadedValue>
1071 ARMBaseInstrInfo::describeLoadedValue(const MachineInstr &MI,
1072                                       Register Reg) const {
1073   if (auto DstSrcPair = isCopyInstrImpl(MI)) {
1074     Register DstReg = DstSrcPair->Destination->getReg();
1075 
1076     // TODO: We don't handle cases where the forwarding reg is narrower/wider
1077     // than the copy registers. Consider for example:
1078     //
1079     //   s16 = VMOVS s0
1080     //   s17 = VMOVS s1
1081     //   call @callee(d0)
1082     //
1083     // We'd like to describe the call site value of d0 as d8, but this requires
1084     // gathering and merging the descriptions for the two VMOVS instructions.
1085     //
1086     // We also don't handle the reverse situation, where the forwarding reg is
1087     // narrower than the copy destination:
1088     //
1089     //   d8 = VMOVD d0
1090     //   call @callee(s1)
1091     //
1092     // We need to produce a fragment description (the call site value of s1 is
1093     // /not/ just d8).
1094     if (DstReg != Reg)
1095       return None;
1096   }
1097   return TargetInstrInfo::describeLoadedValue(MI, Reg);
1098 }
1099 
1100 const MachineInstrBuilder &
1101 ARMBaseInstrInfo::AddDReg(MachineInstrBuilder &MIB, unsigned Reg,
1102                           unsigned SubIdx, unsigned State,
1103                           const TargetRegisterInfo *TRI) const {
1104   if (!SubIdx)
1105     return MIB.addReg(Reg, State);
1106 
1107   if (Register::isPhysicalRegister(Reg))
1108     return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
1109   return MIB.addReg(Reg, State, SubIdx);
1110 }
1111 
1112 void ARMBaseInstrInfo::
1113 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
1114                     Register SrcReg, bool isKill, int FI,
1115                     const TargetRegisterClass *RC,
1116                     const TargetRegisterInfo *TRI) const {
1117   MachineFunction &MF = *MBB.getParent();
1118   MachineFrameInfo &MFI = MF.getFrameInfo();
1119   Align Alignment = MFI.getObjectAlign(FI);
1120 
1121   MachineMemOperand *MMO = MF.getMachineMemOperand(
1122       MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOStore,
1123       MFI.getObjectSize(FI), Alignment);
1124 
1125   switch (TRI->getSpillSize(*RC)) {
1126     case 2:
1127       if (ARM::HPRRegClass.hasSubClassEq(RC)) {
1128         BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRH))
1129             .addReg(SrcReg, getKillRegState(isKill))
1130             .addFrameIndex(FI)
1131             .addImm(0)
1132             .addMemOperand(MMO)
1133             .add(predOps(ARMCC::AL));
1134       } else
1135         llvm_unreachable("Unknown reg class!");
1136       break;
1137     case 4:
1138       if (ARM::GPRRegClass.hasSubClassEq(RC)) {
1139         BuildMI(MBB, I, DebugLoc(), get(ARM::STRi12))
1140             .addReg(SrcReg, getKillRegState(isKill))
1141             .addFrameIndex(FI)
1142             .addImm(0)
1143             .addMemOperand(MMO)
1144             .add(predOps(ARMCC::AL));
1145       } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
1146         BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRS))
1147             .addReg(SrcReg, getKillRegState(isKill))
1148             .addFrameIndex(FI)
1149             .addImm(0)
1150             .addMemOperand(MMO)
1151             .add(predOps(ARMCC::AL));
1152       } else if (ARM::VCCRRegClass.hasSubClassEq(RC)) {
1153         BuildMI(MBB, I, DebugLoc(), get(ARM::VSTR_P0_off))
1154             .addReg(SrcReg, getKillRegState(isKill))
1155             .addFrameIndex(FI)
1156             .addImm(0)
1157             .addMemOperand(MMO)
1158             .add(predOps(ARMCC::AL));
1159       } else
1160         llvm_unreachable("Unknown reg class!");
1161       break;
1162     case 8:
1163       if (ARM::DPRRegClass.hasSubClassEq(RC)) {
1164         BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRD))
1165             .addReg(SrcReg, getKillRegState(isKill))
1166             .addFrameIndex(FI)
1167             .addImm(0)
1168             .addMemOperand(MMO)
1169             .add(predOps(ARMCC::AL));
1170       } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) {
1171         if (Subtarget.hasV5TEOps()) {
1172           MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::STRD));
1173           AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI);
1174           AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI);
1175           MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO)
1176              .add(predOps(ARMCC::AL));
1177         } else {
1178           // Fallback to STM instruction, which has existed since the dawn of
1179           // time.
1180           MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::STMIA))
1181                                         .addFrameIndex(FI)
1182                                         .addMemOperand(MMO)
1183                                         .add(predOps(ARMCC::AL));
1184           AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI);
1185           AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI);
1186         }
1187       } else
1188         llvm_unreachable("Unknown reg class!");
1189       break;
1190     case 16:
1191       if (ARM::DPairRegClass.hasSubClassEq(RC) && Subtarget.hasNEON()) {
1192         // Use aligned spills if the stack can be realigned.
1193         if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF)) {
1194           BuildMI(MBB, I, DebugLoc(), get(ARM::VST1q64))
1195               .addFrameIndex(FI)
1196               .addImm(16)
1197               .addReg(SrcReg, getKillRegState(isKill))
1198               .addMemOperand(MMO)
1199               .add(predOps(ARMCC::AL));
1200         } else {
1201           BuildMI(MBB, I, DebugLoc(), get(ARM::VSTMQIA))
1202               .addReg(SrcReg, getKillRegState(isKill))
1203               .addFrameIndex(FI)
1204               .addMemOperand(MMO)
1205               .add(predOps(ARMCC::AL));
1206         }
1207       } else if (ARM::QPRRegClass.hasSubClassEq(RC) &&
1208                  Subtarget.hasMVEIntegerOps()) {
1209         auto MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::MVE_VSTRWU32));
1210         MIB.addReg(SrcReg, getKillRegState(isKill))
1211           .addFrameIndex(FI)
1212           .addImm(0)
1213           .addMemOperand(MMO);
1214         addUnpredicatedMveVpredNOp(MIB);
1215       } else
1216         llvm_unreachable("Unknown reg class!");
1217       break;
1218     case 24:
1219       if (ARM::DTripleRegClass.hasSubClassEq(RC)) {
1220         // Use aligned spills if the stack can be realigned.
1221         if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) &&
1222             Subtarget.hasNEON()) {
1223           BuildMI(MBB, I, DebugLoc(), get(ARM::VST1d64TPseudo))
1224               .addFrameIndex(FI)
1225               .addImm(16)
1226               .addReg(SrcReg, getKillRegState(isKill))
1227               .addMemOperand(MMO)
1228               .add(predOps(ARMCC::AL));
1229         } else {
1230           MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(),
1231                                             get(ARM::VSTMDIA))
1232                                         .addFrameIndex(FI)
1233                                         .add(predOps(ARMCC::AL))
1234                                         .addMemOperand(MMO);
1235           MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
1236           MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
1237           AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
1238         }
1239       } else
1240         llvm_unreachable("Unknown reg class!");
1241       break;
1242     case 32:
1243       if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) {
1244         if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) &&
1245             Subtarget.hasNEON()) {
1246           // FIXME: It's possible to only store part of the QQ register if the
1247           // spilled def has a sub-register index.
1248           BuildMI(MBB, I, DebugLoc(), get(ARM::VST1d64QPseudo))
1249               .addFrameIndex(FI)
1250               .addImm(16)
1251               .addReg(SrcReg, getKillRegState(isKill))
1252               .addMemOperand(MMO)
1253               .add(predOps(ARMCC::AL));
1254         } else {
1255           MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(),
1256                                             get(ARM::VSTMDIA))
1257                                         .addFrameIndex(FI)
1258                                         .add(predOps(ARMCC::AL))
1259                                         .addMemOperand(MMO);
1260           MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
1261           MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
1262           MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
1263                 AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
1264         }
1265       } else
1266         llvm_unreachable("Unknown reg class!");
1267       break;
1268     case 64:
1269       if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
1270         MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::VSTMDIA))
1271                                       .addFrameIndex(FI)
1272                                       .add(predOps(ARMCC::AL))
1273                                       .addMemOperand(MMO);
1274         MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
1275         MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
1276         MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
1277         MIB = AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
1278         MIB = AddDReg(MIB, SrcReg, ARM::dsub_4, 0, TRI);
1279         MIB = AddDReg(MIB, SrcReg, ARM::dsub_5, 0, TRI);
1280         MIB = AddDReg(MIB, SrcReg, ARM::dsub_6, 0, TRI);
1281               AddDReg(MIB, SrcReg, ARM::dsub_7, 0, TRI);
1282       } else
1283         llvm_unreachable("Unknown reg class!");
1284       break;
1285     default:
1286       llvm_unreachable("Unknown reg class!");
1287   }
1288 }
1289 
1290 unsigned ARMBaseInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
1291                                               int &FrameIndex) const {
1292   switch (MI.getOpcode()) {
1293   default: break;
1294   case ARM::STRrs:
1295   case ARM::t2STRs: // FIXME: don't use t2STRs to access frame.
1296     if (MI.getOperand(1).isFI() && MI.getOperand(2).isReg() &&
1297         MI.getOperand(3).isImm() && MI.getOperand(2).getReg() == 0 &&
1298         MI.getOperand(3).getImm() == 0) {
1299       FrameIndex = MI.getOperand(1).getIndex();
1300       return MI.getOperand(0).getReg();
1301     }
1302     break;
1303   case ARM::STRi12:
1304   case ARM::t2STRi12:
1305   case ARM::tSTRspi:
1306   case ARM::VSTRD:
1307   case ARM::VSTRS:
1308     if (MI.getOperand(1).isFI() && MI.getOperand(2).isImm() &&
1309         MI.getOperand(2).getImm() == 0) {
1310       FrameIndex = MI.getOperand(1).getIndex();
1311       return MI.getOperand(0).getReg();
1312     }
1313     break;
1314   case ARM::VSTR_P0_off:
1315     if (MI.getOperand(0).isFI() && MI.getOperand(1).isImm() &&
1316         MI.getOperand(1).getImm() == 0) {
1317       FrameIndex = MI.getOperand(0).getIndex();
1318       return ARM::P0;
1319     }
1320     break;
1321   case ARM::VST1q64:
1322   case ARM::VST1d64TPseudo:
1323   case ARM::VST1d64QPseudo:
1324     if (MI.getOperand(0).isFI() && MI.getOperand(2).getSubReg() == 0) {
1325       FrameIndex = MI.getOperand(0).getIndex();
1326       return MI.getOperand(2).getReg();
1327     }
1328     break;
1329   case ARM::VSTMQIA:
1330     if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) {
1331       FrameIndex = MI.getOperand(1).getIndex();
1332       return MI.getOperand(0).getReg();
1333     }
1334     break;
1335   }
1336 
1337   return 0;
1338 }
1339 
1340 unsigned ARMBaseInstrInfo::isStoreToStackSlotPostFE(const MachineInstr &MI,
1341                                                     int &FrameIndex) const {
1342   SmallVector<const MachineMemOperand *, 1> Accesses;
1343   if (MI.mayStore() && hasStoreToStackSlot(MI, Accesses) &&
1344       Accesses.size() == 1) {
1345     FrameIndex =
1346         cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
1347             ->getFrameIndex();
1348     return true;
1349   }
1350   return false;
1351 }
1352 
1353 void ARMBaseInstrInfo::
1354 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
1355                      Register DestReg, int FI,
1356                      const TargetRegisterClass *RC,
1357                      const TargetRegisterInfo *TRI) const {
1358   DebugLoc DL;
1359   if (I != MBB.end()) DL = I->getDebugLoc();
1360   MachineFunction &MF = *MBB.getParent();
1361   MachineFrameInfo &MFI = MF.getFrameInfo();
1362   const Align Alignment = MFI.getObjectAlign(FI);
1363   MachineMemOperand *MMO = MF.getMachineMemOperand(
1364       MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOLoad,
1365       MFI.getObjectSize(FI), Alignment);
1366 
1367   switch (TRI->getSpillSize(*RC)) {
1368   case 2:
1369     if (ARM::HPRRegClass.hasSubClassEq(RC)) {
1370       BuildMI(MBB, I, DL, get(ARM::VLDRH), DestReg)
1371           .addFrameIndex(FI)
1372           .addImm(0)
1373           .addMemOperand(MMO)
1374           .add(predOps(ARMCC::AL));
1375     } else
1376       llvm_unreachable("Unknown reg class!");
1377     break;
1378   case 4:
1379     if (ARM::GPRRegClass.hasSubClassEq(RC)) {
1380       BuildMI(MBB, I, DL, get(ARM::LDRi12), DestReg)
1381           .addFrameIndex(FI)
1382           .addImm(0)
1383           .addMemOperand(MMO)
1384           .add(predOps(ARMCC::AL));
1385     } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
1386       BuildMI(MBB, I, DL, get(ARM::VLDRS), DestReg)
1387           .addFrameIndex(FI)
1388           .addImm(0)
1389           .addMemOperand(MMO)
1390           .add(predOps(ARMCC::AL));
1391     } else if (ARM::VCCRRegClass.hasSubClassEq(RC)) {
1392       BuildMI(MBB, I, DL, get(ARM::VLDR_P0_off), DestReg)
1393           .addFrameIndex(FI)
1394           .addImm(0)
1395           .addMemOperand(MMO)
1396           .add(predOps(ARMCC::AL));
1397     } else
1398       llvm_unreachable("Unknown reg class!");
1399     break;
1400   case 8:
1401     if (ARM::DPRRegClass.hasSubClassEq(RC)) {
1402       BuildMI(MBB, I, DL, get(ARM::VLDRD), DestReg)
1403           .addFrameIndex(FI)
1404           .addImm(0)
1405           .addMemOperand(MMO)
1406           .add(predOps(ARMCC::AL));
1407     } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) {
1408       MachineInstrBuilder MIB;
1409 
1410       if (Subtarget.hasV5TEOps()) {
1411         MIB = BuildMI(MBB, I, DL, get(ARM::LDRD));
1412         AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI);
1413         AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI);
1414         MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO)
1415            .add(predOps(ARMCC::AL));
1416       } else {
1417         // Fallback to LDM instruction, which has existed since the dawn of
1418         // time.
1419         MIB = BuildMI(MBB, I, DL, get(ARM::LDMIA))
1420                   .addFrameIndex(FI)
1421                   .addMemOperand(MMO)
1422                   .add(predOps(ARMCC::AL));
1423         MIB = AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI);
1424         MIB = AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI);
1425       }
1426 
1427       if (Register::isPhysicalRegister(DestReg))
1428         MIB.addReg(DestReg, RegState::ImplicitDefine);
1429     } else
1430       llvm_unreachable("Unknown reg class!");
1431     break;
1432   case 16:
1433     if (ARM::DPairRegClass.hasSubClassEq(RC) && Subtarget.hasNEON()) {
1434       if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF)) {
1435         BuildMI(MBB, I, DL, get(ARM::VLD1q64), DestReg)
1436             .addFrameIndex(FI)
1437             .addImm(16)
1438             .addMemOperand(MMO)
1439             .add(predOps(ARMCC::AL));
1440       } else {
1441         BuildMI(MBB, I, DL, get(ARM::VLDMQIA), DestReg)
1442             .addFrameIndex(FI)
1443             .addMemOperand(MMO)
1444             .add(predOps(ARMCC::AL));
1445       }
1446     } else if (ARM::QPRRegClass.hasSubClassEq(RC) &&
1447                Subtarget.hasMVEIntegerOps()) {
1448       auto MIB = BuildMI(MBB, I, DL, get(ARM::MVE_VLDRWU32), DestReg);
1449       MIB.addFrameIndex(FI)
1450         .addImm(0)
1451         .addMemOperand(MMO);
1452       addUnpredicatedMveVpredNOp(MIB);
1453     } else
1454       llvm_unreachable("Unknown reg class!");
1455     break;
1456   case 24:
1457     if (ARM::DTripleRegClass.hasSubClassEq(RC)) {
1458       if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) &&
1459           Subtarget.hasNEON()) {
1460         BuildMI(MBB, I, DL, get(ARM::VLD1d64TPseudo), DestReg)
1461             .addFrameIndex(FI)
1462             .addImm(16)
1463             .addMemOperand(MMO)
1464             .add(predOps(ARMCC::AL));
1465       } else {
1466         MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1467                                       .addFrameIndex(FI)
1468                                       .addMemOperand(MMO)
1469                                       .add(predOps(ARMCC::AL));
1470         MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1471         MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1472         MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1473         if (Register::isPhysicalRegister(DestReg))
1474           MIB.addReg(DestReg, RegState::ImplicitDefine);
1475       }
1476     } else
1477       llvm_unreachable("Unknown reg class!");
1478     break;
1479    case 32:
1480     if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) {
1481       if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) &&
1482           Subtarget.hasNEON()) {
1483         BuildMI(MBB, I, DL, get(ARM::VLD1d64QPseudo), DestReg)
1484             .addFrameIndex(FI)
1485             .addImm(16)
1486             .addMemOperand(MMO)
1487             .add(predOps(ARMCC::AL));
1488       } else {
1489         MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1490                                       .addFrameIndex(FI)
1491                                       .add(predOps(ARMCC::AL))
1492                                       .addMemOperand(MMO);
1493         MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1494         MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1495         MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1496         MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI);
1497         if (Register::isPhysicalRegister(DestReg))
1498           MIB.addReg(DestReg, RegState::ImplicitDefine);
1499       }
1500     } else
1501       llvm_unreachable("Unknown reg class!");
1502     break;
1503   case 64:
1504     if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
1505       MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1506                                     .addFrameIndex(FI)
1507                                     .add(predOps(ARMCC::AL))
1508                                     .addMemOperand(MMO);
1509       MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1510       MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1511       MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1512       MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI);
1513       MIB = AddDReg(MIB, DestReg, ARM::dsub_4, RegState::DefineNoRead, TRI);
1514       MIB = AddDReg(MIB, DestReg, ARM::dsub_5, RegState::DefineNoRead, TRI);
1515       MIB = AddDReg(MIB, DestReg, ARM::dsub_6, RegState::DefineNoRead, TRI);
1516       MIB = AddDReg(MIB, DestReg, ARM::dsub_7, RegState::DefineNoRead, TRI);
1517       if (Register::isPhysicalRegister(DestReg))
1518         MIB.addReg(DestReg, RegState::ImplicitDefine);
1519     } else
1520       llvm_unreachable("Unknown reg class!");
1521     break;
1522   default:
1523     llvm_unreachable("Unknown regclass!");
1524   }
1525 }
1526 
1527 unsigned ARMBaseInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
1528                                                int &FrameIndex) const {
1529   switch (MI.getOpcode()) {
1530   default: break;
1531   case ARM::LDRrs:
1532   case ARM::t2LDRs:  // FIXME: don't use t2LDRs to access frame.
1533     if (MI.getOperand(1).isFI() && MI.getOperand(2).isReg() &&
1534         MI.getOperand(3).isImm() && MI.getOperand(2).getReg() == 0 &&
1535         MI.getOperand(3).getImm() == 0) {
1536       FrameIndex = MI.getOperand(1).getIndex();
1537       return MI.getOperand(0).getReg();
1538     }
1539     break;
1540   case ARM::LDRi12:
1541   case ARM::t2LDRi12:
1542   case ARM::tLDRspi:
1543   case ARM::VLDRD:
1544   case ARM::VLDRS:
1545     if (MI.getOperand(1).isFI() && MI.getOperand(2).isImm() &&
1546         MI.getOperand(2).getImm() == 0) {
1547       FrameIndex = MI.getOperand(1).getIndex();
1548       return MI.getOperand(0).getReg();
1549     }
1550     break;
1551   case ARM::VLDR_P0_off:
1552     if (MI.getOperand(0).isFI() && MI.getOperand(1).isImm() &&
1553         MI.getOperand(1).getImm() == 0) {
1554       FrameIndex = MI.getOperand(0).getIndex();
1555       return ARM::P0;
1556     }
1557     break;
1558   case ARM::VLD1q64:
1559   case ARM::VLD1d8TPseudo:
1560   case ARM::VLD1d16TPseudo:
1561   case ARM::VLD1d32TPseudo:
1562   case ARM::VLD1d64TPseudo:
1563   case ARM::VLD1d8QPseudo:
1564   case ARM::VLD1d16QPseudo:
1565   case ARM::VLD1d32QPseudo:
1566   case ARM::VLD1d64QPseudo:
1567     if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) {
1568       FrameIndex = MI.getOperand(1).getIndex();
1569       return MI.getOperand(0).getReg();
1570     }
1571     break;
1572   case ARM::VLDMQIA:
1573     if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) {
1574       FrameIndex = MI.getOperand(1).getIndex();
1575       return MI.getOperand(0).getReg();
1576     }
1577     break;
1578   }
1579 
1580   return 0;
1581 }
1582 
1583 unsigned ARMBaseInstrInfo::isLoadFromStackSlotPostFE(const MachineInstr &MI,
1584                                                      int &FrameIndex) const {
1585   SmallVector<const MachineMemOperand *, 1> Accesses;
1586   if (MI.mayLoad() && hasLoadFromStackSlot(MI, Accesses) &&
1587       Accesses.size() == 1) {
1588     FrameIndex =
1589         cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
1590             ->getFrameIndex();
1591     return true;
1592   }
1593   return false;
1594 }
1595 
1596 /// Expands MEMCPY to either LDMIA/STMIA or LDMIA_UPD/STMID_UPD
1597 /// depending on whether the result is used.
1598 void ARMBaseInstrInfo::expandMEMCPY(MachineBasicBlock::iterator MI) const {
1599   bool isThumb1 = Subtarget.isThumb1Only();
1600   bool isThumb2 = Subtarget.isThumb2();
1601   const ARMBaseInstrInfo *TII = Subtarget.getInstrInfo();
1602 
1603   DebugLoc dl = MI->getDebugLoc();
1604   MachineBasicBlock *BB = MI->getParent();
1605 
1606   MachineInstrBuilder LDM, STM;
1607   if (isThumb1 || !MI->getOperand(1).isDead()) {
1608     MachineOperand LDWb(MI->getOperand(1));
1609     LDM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2LDMIA_UPD
1610                                                  : isThumb1 ? ARM::tLDMIA_UPD
1611                                                             : ARM::LDMIA_UPD))
1612               .add(LDWb);
1613   } else {
1614     LDM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2LDMIA : ARM::LDMIA));
1615   }
1616 
1617   if (isThumb1 || !MI->getOperand(0).isDead()) {
1618     MachineOperand STWb(MI->getOperand(0));
1619     STM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2STMIA_UPD
1620                                                  : isThumb1 ? ARM::tSTMIA_UPD
1621                                                             : ARM::STMIA_UPD))
1622               .add(STWb);
1623   } else {
1624     STM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2STMIA : ARM::STMIA));
1625   }
1626 
1627   MachineOperand LDBase(MI->getOperand(3));
1628   LDM.add(LDBase).add(predOps(ARMCC::AL));
1629 
1630   MachineOperand STBase(MI->getOperand(2));
1631   STM.add(STBase).add(predOps(ARMCC::AL));
1632 
1633   // Sort the scratch registers into ascending order.
1634   const TargetRegisterInfo &TRI = getRegisterInfo();
1635   SmallVector<unsigned, 6> ScratchRegs;
1636   for(unsigned I = 5; I < MI->getNumOperands(); ++I)
1637     ScratchRegs.push_back(MI->getOperand(I).getReg());
1638   llvm::sort(ScratchRegs,
1639              [&TRI](const unsigned &Reg1, const unsigned &Reg2) -> bool {
1640                return TRI.getEncodingValue(Reg1) <
1641                       TRI.getEncodingValue(Reg2);
1642              });
1643 
1644   for (const auto &Reg : ScratchRegs) {
1645     LDM.addReg(Reg, RegState::Define);
1646     STM.addReg(Reg, RegState::Kill);
1647   }
1648 
1649   BB->erase(MI);
1650 }
1651 
1652 bool ARMBaseInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
1653   if (MI.getOpcode() == TargetOpcode::LOAD_STACK_GUARD) {
1654     assert(getSubtarget().getTargetTriple().isOSBinFormatMachO() &&
1655            "LOAD_STACK_GUARD currently supported only for MachO.");
1656     expandLoadStackGuard(MI);
1657     MI.getParent()->erase(MI);
1658     return true;
1659   }
1660 
1661   if (MI.getOpcode() == ARM::MEMCPY) {
1662     expandMEMCPY(MI);
1663     return true;
1664   }
1665 
1666   // This hook gets to expand COPY instructions before they become
1667   // copyPhysReg() calls.  Look for VMOVS instructions that can legally be
1668   // widened to VMOVD.  We prefer the VMOVD when possible because it may be
1669   // changed into a VORR that can go down the NEON pipeline.
1670   if (!MI.isCopy() || Subtarget.dontWidenVMOVS() || !Subtarget.hasFP64())
1671     return false;
1672 
1673   // Look for a copy between even S-registers.  That is where we keep floats
1674   // when using NEON v2f32 instructions for f32 arithmetic.
1675   Register DstRegS = MI.getOperand(0).getReg();
1676   Register SrcRegS = MI.getOperand(1).getReg();
1677   if (!ARM::SPRRegClass.contains(DstRegS, SrcRegS))
1678     return false;
1679 
1680   const TargetRegisterInfo *TRI = &getRegisterInfo();
1681   unsigned DstRegD = TRI->getMatchingSuperReg(DstRegS, ARM::ssub_0,
1682                                               &ARM::DPRRegClass);
1683   unsigned SrcRegD = TRI->getMatchingSuperReg(SrcRegS, ARM::ssub_0,
1684                                               &ARM::DPRRegClass);
1685   if (!DstRegD || !SrcRegD)
1686     return false;
1687 
1688   // We want to widen this into a DstRegD = VMOVD SrcRegD copy.  This is only
1689   // legal if the COPY already defines the full DstRegD, and it isn't a
1690   // sub-register insertion.
1691   if (!MI.definesRegister(DstRegD, TRI) || MI.readsRegister(DstRegD, TRI))
1692     return false;
1693 
1694   // A dead copy shouldn't show up here, but reject it just in case.
1695   if (MI.getOperand(0).isDead())
1696     return false;
1697 
1698   // All clear, widen the COPY.
1699   LLVM_DEBUG(dbgs() << "widening:    " << MI);
1700   MachineInstrBuilder MIB(*MI.getParent()->getParent(), MI);
1701 
1702   // Get rid of the old implicit-def of DstRegD.  Leave it if it defines a Q-reg
1703   // or some other super-register.
1704   int ImpDefIdx = MI.findRegisterDefOperandIdx(DstRegD);
1705   if (ImpDefIdx != -1)
1706     MI.RemoveOperand(ImpDefIdx);
1707 
1708   // Change the opcode and operands.
1709   MI.setDesc(get(ARM::VMOVD));
1710   MI.getOperand(0).setReg(DstRegD);
1711   MI.getOperand(1).setReg(SrcRegD);
1712   MIB.add(predOps(ARMCC::AL));
1713 
1714   // We are now reading SrcRegD instead of SrcRegS.  This may upset the
1715   // register scavenger and machine verifier, so we need to indicate that we
1716   // are reading an undefined value from SrcRegD, but a proper value from
1717   // SrcRegS.
1718   MI.getOperand(1).setIsUndef();
1719   MIB.addReg(SrcRegS, RegState::Implicit);
1720 
1721   // SrcRegD may actually contain an unrelated value in the ssub_1
1722   // sub-register.  Don't kill it.  Only kill the ssub_0 sub-register.
1723   if (MI.getOperand(1).isKill()) {
1724     MI.getOperand(1).setIsKill(false);
1725     MI.addRegisterKilled(SrcRegS, TRI, true);
1726   }
1727 
1728   LLVM_DEBUG(dbgs() << "replaced by: " << MI);
1729   return true;
1730 }
1731 
1732 /// Create a copy of a const pool value. Update CPI to the new index and return
1733 /// the label UID.
1734 static unsigned duplicateCPV(MachineFunction &MF, unsigned &CPI) {
1735   MachineConstantPool *MCP = MF.getConstantPool();
1736   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1737 
1738   const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
1739   assert(MCPE.isMachineConstantPoolEntry() &&
1740          "Expecting a machine constantpool entry!");
1741   ARMConstantPoolValue *ACPV =
1742     static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
1743 
1744   unsigned PCLabelId = AFI->createPICLabelUId();
1745   ARMConstantPoolValue *NewCPV = nullptr;
1746 
1747   // FIXME: The below assumes PIC relocation model and that the function
1748   // is Thumb mode (t1 or t2). PCAdjustment would be 8 for ARM mode PIC, and
1749   // zero for non-PIC in ARM or Thumb. The callers are all of thumb LDR
1750   // instructions, so that's probably OK, but is PIC always correct when
1751   // we get here?
1752   if (ACPV->isGlobalValue())
1753     NewCPV = ARMConstantPoolConstant::Create(
1754         cast<ARMConstantPoolConstant>(ACPV)->getGV(), PCLabelId, ARMCP::CPValue,
1755         4, ACPV->getModifier(), ACPV->mustAddCurrentAddress());
1756   else if (ACPV->isExtSymbol())
1757     NewCPV = ARMConstantPoolSymbol::
1758       Create(MF.getFunction().getContext(),
1759              cast<ARMConstantPoolSymbol>(ACPV)->getSymbol(), PCLabelId, 4);
1760   else if (ACPV->isBlockAddress())
1761     NewCPV = ARMConstantPoolConstant::
1762       Create(cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress(), PCLabelId,
1763              ARMCP::CPBlockAddress, 4);
1764   else if (ACPV->isLSDA())
1765     NewCPV = ARMConstantPoolConstant::Create(&MF.getFunction(), PCLabelId,
1766                                              ARMCP::CPLSDA, 4);
1767   else if (ACPV->isMachineBasicBlock())
1768     NewCPV = ARMConstantPoolMBB::
1769       Create(MF.getFunction().getContext(),
1770              cast<ARMConstantPoolMBB>(ACPV)->getMBB(), PCLabelId, 4);
1771   else
1772     llvm_unreachable("Unexpected ARM constantpool value type!!");
1773   CPI = MCP->getConstantPoolIndex(NewCPV, MCPE.getAlign());
1774   return PCLabelId;
1775 }
1776 
1777 void ARMBaseInstrInfo::reMaterialize(MachineBasicBlock &MBB,
1778                                      MachineBasicBlock::iterator I,
1779                                      Register DestReg, unsigned SubIdx,
1780                                      const MachineInstr &Orig,
1781                                      const TargetRegisterInfo &TRI) const {
1782   unsigned Opcode = Orig.getOpcode();
1783   switch (Opcode) {
1784   default: {
1785     MachineInstr *MI = MBB.getParent()->CloneMachineInstr(&Orig);
1786     MI->substituteRegister(Orig.getOperand(0).getReg(), DestReg, SubIdx, TRI);
1787     MBB.insert(I, MI);
1788     break;
1789   }
1790   case ARM::tLDRpci_pic:
1791   case ARM::t2LDRpci_pic: {
1792     MachineFunction &MF = *MBB.getParent();
1793     unsigned CPI = Orig.getOperand(1).getIndex();
1794     unsigned PCLabelId = duplicateCPV(MF, CPI);
1795     BuildMI(MBB, I, Orig.getDebugLoc(), get(Opcode), DestReg)
1796         .addConstantPoolIndex(CPI)
1797         .addImm(PCLabelId)
1798         .cloneMemRefs(Orig);
1799     break;
1800   }
1801   }
1802 }
1803 
1804 MachineInstr &
1805 ARMBaseInstrInfo::duplicate(MachineBasicBlock &MBB,
1806     MachineBasicBlock::iterator InsertBefore,
1807     const MachineInstr &Orig) const {
1808   MachineInstr &Cloned = TargetInstrInfo::duplicate(MBB, InsertBefore, Orig);
1809   MachineBasicBlock::instr_iterator I = Cloned.getIterator();
1810   for (;;) {
1811     switch (I->getOpcode()) {
1812     case ARM::tLDRpci_pic:
1813     case ARM::t2LDRpci_pic: {
1814       MachineFunction &MF = *MBB.getParent();
1815       unsigned CPI = I->getOperand(1).getIndex();
1816       unsigned PCLabelId = duplicateCPV(MF, CPI);
1817       I->getOperand(1).setIndex(CPI);
1818       I->getOperand(2).setImm(PCLabelId);
1819       break;
1820     }
1821     }
1822     if (!I->isBundledWithSucc())
1823       break;
1824     ++I;
1825   }
1826   return Cloned;
1827 }
1828 
1829 bool ARMBaseInstrInfo::produceSameValue(const MachineInstr &MI0,
1830                                         const MachineInstr &MI1,
1831                                         const MachineRegisterInfo *MRI) const {
1832   unsigned Opcode = MI0.getOpcode();
1833   if (Opcode == ARM::t2LDRpci ||
1834       Opcode == ARM::t2LDRpci_pic ||
1835       Opcode == ARM::tLDRpci ||
1836       Opcode == ARM::tLDRpci_pic ||
1837       Opcode == ARM::LDRLIT_ga_pcrel ||
1838       Opcode == ARM::LDRLIT_ga_pcrel_ldr ||
1839       Opcode == ARM::tLDRLIT_ga_pcrel ||
1840       Opcode == ARM::MOV_ga_pcrel ||
1841       Opcode == ARM::MOV_ga_pcrel_ldr ||
1842       Opcode == ARM::t2MOV_ga_pcrel) {
1843     if (MI1.getOpcode() != Opcode)
1844       return false;
1845     if (MI0.getNumOperands() != MI1.getNumOperands())
1846       return false;
1847 
1848     const MachineOperand &MO0 = MI0.getOperand(1);
1849     const MachineOperand &MO1 = MI1.getOperand(1);
1850     if (MO0.getOffset() != MO1.getOffset())
1851       return false;
1852 
1853     if (Opcode == ARM::LDRLIT_ga_pcrel ||
1854         Opcode == ARM::LDRLIT_ga_pcrel_ldr ||
1855         Opcode == ARM::tLDRLIT_ga_pcrel ||
1856         Opcode == ARM::MOV_ga_pcrel ||
1857         Opcode == ARM::MOV_ga_pcrel_ldr ||
1858         Opcode == ARM::t2MOV_ga_pcrel)
1859       // Ignore the PC labels.
1860       return MO0.getGlobal() == MO1.getGlobal();
1861 
1862     const MachineFunction *MF = MI0.getParent()->getParent();
1863     const MachineConstantPool *MCP = MF->getConstantPool();
1864     int CPI0 = MO0.getIndex();
1865     int CPI1 = MO1.getIndex();
1866     const MachineConstantPoolEntry &MCPE0 = MCP->getConstants()[CPI0];
1867     const MachineConstantPoolEntry &MCPE1 = MCP->getConstants()[CPI1];
1868     bool isARMCP0 = MCPE0.isMachineConstantPoolEntry();
1869     bool isARMCP1 = MCPE1.isMachineConstantPoolEntry();
1870     if (isARMCP0 && isARMCP1) {
1871       ARMConstantPoolValue *ACPV0 =
1872         static_cast<ARMConstantPoolValue*>(MCPE0.Val.MachineCPVal);
1873       ARMConstantPoolValue *ACPV1 =
1874         static_cast<ARMConstantPoolValue*>(MCPE1.Val.MachineCPVal);
1875       return ACPV0->hasSameValue(ACPV1);
1876     } else if (!isARMCP0 && !isARMCP1) {
1877       return MCPE0.Val.ConstVal == MCPE1.Val.ConstVal;
1878     }
1879     return false;
1880   } else if (Opcode == ARM::PICLDR) {
1881     if (MI1.getOpcode() != Opcode)
1882       return false;
1883     if (MI0.getNumOperands() != MI1.getNumOperands())
1884       return false;
1885 
1886     Register Addr0 = MI0.getOperand(1).getReg();
1887     Register Addr1 = MI1.getOperand(1).getReg();
1888     if (Addr0 != Addr1) {
1889       if (!MRI || !Register::isVirtualRegister(Addr0) ||
1890           !Register::isVirtualRegister(Addr1))
1891         return false;
1892 
1893       // This assumes SSA form.
1894       MachineInstr *Def0 = MRI->getVRegDef(Addr0);
1895       MachineInstr *Def1 = MRI->getVRegDef(Addr1);
1896       // Check if the loaded value, e.g. a constantpool of a global address, are
1897       // the same.
1898       if (!produceSameValue(*Def0, *Def1, MRI))
1899         return false;
1900     }
1901 
1902     for (unsigned i = 3, e = MI0.getNumOperands(); i != e; ++i) {
1903       // %12 = PICLDR %11, 0, 14, %noreg
1904       const MachineOperand &MO0 = MI0.getOperand(i);
1905       const MachineOperand &MO1 = MI1.getOperand(i);
1906       if (!MO0.isIdenticalTo(MO1))
1907         return false;
1908     }
1909     return true;
1910   }
1911 
1912   return MI0.isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
1913 }
1914 
1915 /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler to
1916 /// determine if two loads are loading from the same base address. It should
1917 /// only return true if the base pointers are the same and the only differences
1918 /// between the two addresses is the offset. It also returns the offsets by
1919 /// reference.
1920 ///
1921 /// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched
1922 /// is permanently disabled.
1923 bool ARMBaseInstrInfo::areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
1924                                                int64_t &Offset1,
1925                                                int64_t &Offset2) const {
1926   // Don't worry about Thumb: just ARM and Thumb2.
1927   if (Subtarget.isThumb1Only()) return false;
1928 
1929   if (!Load1->isMachineOpcode() || !Load2->isMachineOpcode())
1930     return false;
1931 
1932   switch (Load1->getMachineOpcode()) {
1933   default:
1934     return false;
1935   case ARM::LDRi12:
1936   case ARM::LDRBi12:
1937   case ARM::LDRD:
1938   case ARM::LDRH:
1939   case ARM::LDRSB:
1940   case ARM::LDRSH:
1941   case ARM::VLDRD:
1942   case ARM::VLDRS:
1943   case ARM::t2LDRi8:
1944   case ARM::t2LDRBi8:
1945   case ARM::t2LDRDi8:
1946   case ARM::t2LDRSHi8:
1947   case ARM::t2LDRi12:
1948   case ARM::t2LDRBi12:
1949   case ARM::t2LDRSHi12:
1950     break;
1951   }
1952 
1953   switch (Load2->getMachineOpcode()) {
1954   default:
1955     return false;
1956   case ARM::LDRi12:
1957   case ARM::LDRBi12:
1958   case ARM::LDRD:
1959   case ARM::LDRH:
1960   case ARM::LDRSB:
1961   case ARM::LDRSH:
1962   case ARM::VLDRD:
1963   case ARM::VLDRS:
1964   case ARM::t2LDRi8:
1965   case ARM::t2LDRBi8:
1966   case ARM::t2LDRSHi8:
1967   case ARM::t2LDRi12:
1968   case ARM::t2LDRBi12:
1969   case ARM::t2LDRSHi12:
1970     break;
1971   }
1972 
1973   // Check if base addresses and chain operands match.
1974   if (Load1->getOperand(0) != Load2->getOperand(0) ||
1975       Load1->getOperand(4) != Load2->getOperand(4))
1976     return false;
1977 
1978   // Index should be Reg0.
1979   if (Load1->getOperand(3) != Load2->getOperand(3))
1980     return false;
1981 
1982   // Determine the offsets.
1983   if (isa<ConstantSDNode>(Load1->getOperand(1)) &&
1984       isa<ConstantSDNode>(Load2->getOperand(1))) {
1985     Offset1 = cast<ConstantSDNode>(Load1->getOperand(1))->getSExtValue();
1986     Offset2 = cast<ConstantSDNode>(Load2->getOperand(1))->getSExtValue();
1987     return true;
1988   }
1989 
1990   return false;
1991 }
1992 
1993 /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
1994 /// determine (in conjunction with areLoadsFromSameBasePtr) if two loads should
1995 /// be scheduled togther. On some targets if two loads are loading from
1996 /// addresses in the same cache line, it's better if they are scheduled
1997 /// together. This function takes two integers that represent the load offsets
1998 /// from the common base address. It returns true if it decides it's desirable
1999 /// to schedule the two loads together. "NumLoads" is the number of loads that
2000 /// have already been scheduled after Load1.
2001 ///
2002 /// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched
2003 /// is permanently disabled.
2004 bool ARMBaseInstrInfo::shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
2005                                                int64_t Offset1, int64_t Offset2,
2006                                                unsigned NumLoads) const {
2007   // Don't worry about Thumb: just ARM and Thumb2.
2008   if (Subtarget.isThumb1Only()) return false;
2009 
2010   assert(Offset2 > Offset1);
2011 
2012   if ((Offset2 - Offset1) / 8 > 64)
2013     return false;
2014 
2015   // Check if the machine opcodes are different. If they are different
2016   // then we consider them to not be of the same base address,
2017   // EXCEPT in the case of Thumb2 byte loads where one is LDRBi8 and the other LDRBi12.
2018   // In this case, they are considered to be the same because they are different
2019   // encoding forms of the same basic instruction.
2020   if ((Load1->getMachineOpcode() != Load2->getMachineOpcode()) &&
2021       !((Load1->getMachineOpcode() == ARM::t2LDRBi8 &&
2022          Load2->getMachineOpcode() == ARM::t2LDRBi12) ||
2023         (Load1->getMachineOpcode() == ARM::t2LDRBi12 &&
2024          Load2->getMachineOpcode() == ARM::t2LDRBi8)))
2025     return false;  // FIXME: overly conservative?
2026 
2027   // Four loads in a row should be sufficient.
2028   if (NumLoads >= 3)
2029     return false;
2030 
2031   return true;
2032 }
2033 
2034 bool ARMBaseInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
2035                                             const MachineBasicBlock *MBB,
2036                                             const MachineFunction &MF) const {
2037   // Debug info is never a scheduling boundary. It's necessary to be explicit
2038   // due to the special treatment of IT instructions below, otherwise a
2039   // dbg_value followed by an IT will result in the IT instruction being
2040   // considered a scheduling hazard, which is wrong. It should be the actual
2041   // instruction preceding the dbg_value instruction(s), just like it is
2042   // when debug info is not present.
2043   if (MI.isDebugInstr())
2044     return false;
2045 
2046   // Terminators and labels can't be scheduled around.
2047   if (MI.isTerminator() || MI.isPosition())
2048     return true;
2049 
2050   // INLINEASM_BR can jump to another block
2051   if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
2052     return true;
2053 
2054   // Treat the start of the IT block as a scheduling boundary, but schedule
2055   // t2IT along with all instructions following it.
2056   // FIXME: This is a big hammer. But the alternative is to add all potential
2057   // true and anti dependencies to IT block instructions as implicit operands
2058   // to the t2IT instruction. The added compile time and complexity does not
2059   // seem worth it.
2060   MachineBasicBlock::const_iterator I = MI;
2061   // Make sure to skip any debug instructions
2062   while (++I != MBB->end() && I->isDebugInstr())
2063     ;
2064   if (I != MBB->end() && I->getOpcode() == ARM::t2IT)
2065     return true;
2066 
2067   // Don't attempt to schedule around any instruction that defines
2068   // a stack-oriented pointer, as it's unlikely to be profitable. This
2069   // saves compile time, because it doesn't require every single
2070   // stack slot reference to depend on the instruction that does the
2071   // modification.
2072   // Calls don't actually change the stack pointer, even if they have imp-defs.
2073   // No ARM calling conventions change the stack pointer. (X86 calling
2074   // conventions sometimes do).
2075   if (!MI.isCall() && MI.definesRegister(ARM::SP))
2076     return true;
2077 
2078   return false;
2079 }
2080 
2081 bool ARMBaseInstrInfo::
2082 isProfitableToIfCvt(MachineBasicBlock &MBB,
2083                     unsigned NumCycles, unsigned ExtraPredCycles,
2084                     BranchProbability Probability) const {
2085   if (!NumCycles)
2086     return false;
2087 
2088   // If we are optimizing for size, see if the branch in the predecessor can be
2089   // lowered to cbn?z by the constant island lowering pass, and return false if
2090   // so. This results in a shorter instruction sequence.
2091   if (MBB.getParent()->getFunction().hasOptSize()) {
2092     MachineBasicBlock *Pred = *MBB.pred_begin();
2093     if (!Pred->empty()) {
2094       MachineInstr *LastMI = &*Pred->rbegin();
2095       if (LastMI->getOpcode() == ARM::t2Bcc) {
2096         const TargetRegisterInfo *TRI = &getRegisterInfo();
2097         MachineInstr *CmpMI = findCMPToFoldIntoCBZ(LastMI, TRI);
2098         if (CmpMI)
2099           return false;
2100       }
2101     }
2102   }
2103   return isProfitableToIfCvt(MBB, NumCycles, ExtraPredCycles,
2104                              MBB, 0, 0, Probability);
2105 }
2106 
2107 bool ARMBaseInstrInfo::
2108 isProfitableToIfCvt(MachineBasicBlock &TBB,
2109                     unsigned TCycles, unsigned TExtra,
2110                     MachineBasicBlock &FBB,
2111                     unsigned FCycles, unsigned FExtra,
2112                     BranchProbability Probability) const {
2113   if (!TCycles)
2114     return false;
2115 
2116   // In thumb code we often end up trading one branch for a IT block, and
2117   // if we are cloning the instruction can increase code size. Prevent
2118   // blocks with multiple predecesors from being ifcvted to prevent this
2119   // cloning.
2120   if (Subtarget.isThumb2() && TBB.getParent()->getFunction().hasMinSize()) {
2121     if (TBB.pred_size() != 1 || FBB.pred_size() != 1)
2122       return false;
2123   }
2124 
2125   // Attempt to estimate the relative costs of predication versus branching.
2126   // Here we scale up each component of UnpredCost to avoid precision issue when
2127   // scaling TCycles/FCycles by Probability.
2128   const unsigned ScalingUpFactor = 1024;
2129 
2130   unsigned PredCost = (TCycles + FCycles + TExtra + FExtra) * ScalingUpFactor;
2131   unsigned UnpredCost;
2132   if (!Subtarget.hasBranchPredictor()) {
2133     // When we don't have a branch predictor it's always cheaper to not take a
2134     // branch than take it, so we have to take that into account.
2135     unsigned NotTakenBranchCost = 1;
2136     unsigned TakenBranchCost = Subtarget.getMispredictionPenalty();
2137     unsigned TUnpredCycles, FUnpredCycles;
2138     if (!FCycles) {
2139       // Triangle: TBB is the fallthrough
2140       TUnpredCycles = TCycles + NotTakenBranchCost;
2141       FUnpredCycles = TakenBranchCost;
2142     } else {
2143       // Diamond: TBB is the block that is branched to, FBB is the fallthrough
2144       TUnpredCycles = TCycles + TakenBranchCost;
2145       FUnpredCycles = FCycles + NotTakenBranchCost;
2146       // The branch at the end of FBB will disappear when it's predicated, so
2147       // discount it from PredCost.
2148       PredCost -= 1 * ScalingUpFactor;
2149     }
2150     // The total cost is the cost of each path scaled by their probabilites
2151     unsigned TUnpredCost = Probability.scale(TUnpredCycles * ScalingUpFactor);
2152     unsigned FUnpredCost = Probability.getCompl().scale(FUnpredCycles * ScalingUpFactor);
2153     UnpredCost = TUnpredCost + FUnpredCost;
2154     // When predicating assume that the first IT can be folded away but later
2155     // ones cost one cycle each
2156     if (Subtarget.isThumb2() && TCycles + FCycles > 4) {
2157       PredCost += ((TCycles + FCycles - 4) / 4) * ScalingUpFactor;
2158     }
2159   } else {
2160     unsigned TUnpredCost = Probability.scale(TCycles * ScalingUpFactor);
2161     unsigned FUnpredCost =
2162       Probability.getCompl().scale(FCycles * ScalingUpFactor);
2163     UnpredCost = TUnpredCost + FUnpredCost;
2164     UnpredCost += 1 * ScalingUpFactor; // The branch itself
2165     UnpredCost += Subtarget.getMispredictionPenalty() * ScalingUpFactor / 10;
2166   }
2167 
2168   return PredCost <= UnpredCost;
2169 }
2170 
2171 unsigned
2172 ARMBaseInstrInfo::extraSizeToPredicateInstructions(const MachineFunction &MF,
2173                                                    unsigned NumInsts) const {
2174   // Thumb2 needs a 2-byte IT instruction to predicate up to 4 instructions.
2175   // ARM has a condition code field in every predicable instruction, using it
2176   // doesn't change code size.
2177   if (!Subtarget.isThumb2())
2178     return 0;
2179 
2180   // It's possible that the size of the IT is restricted to a single block.
2181   unsigned MaxInsts = Subtarget.restrictIT() ? 1 : 4;
2182   return divideCeil(NumInsts, MaxInsts) * 2;
2183 }
2184 
2185 unsigned
2186 ARMBaseInstrInfo::predictBranchSizeForIfCvt(MachineInstr &MI) const {
2187   // If this branch is likely to be folded into the comparison to form a
2188   // CB(N)Z, then removing it won't reduce code size at all, because that will
2189   // just replace the CB(N)Z with a CMP.
2190   if (MI.getOpcode() == ARM::t2Bcc &&
2191       findCMPToFoldIntoCBZ(&MI, &getRegisterInfo()))
2192     return 0;
2193 
2194   unsigned Size = getInstSizeInBytes(MI);
2195 
2196   // For Thumb2, all branches are 32-bit instructions during the if conversion
2197   // pass, but may be replaced with 16-bit instructions during size reduction.
2198   // Since the branches considered by if conversion tend to be forward branches
2199   // over small basic blocks, they are very likely to be in range for the
2200   // narrow instructions, so we assume the final code size will be half what it
2201   // currently is.
2202   if (Subtarget.isThumb2())
2203     Size /= 2;
2204 
2205   return Size;
2206 }
2207 
2208 bool
2209 ARMBaseInstrInfo::isProfitableToUnpredicate(MachineBasicBlock &TMBB,
2210                                             MachineBasicBlock &FMBB) const {
2211   // Reduce false anti-dependencies to let the target's out-of-order execution
2212   // engine do its thing.
2213   return Subtarget.isProfitableToUnpredicate();
2214 }
2215 
2216 /// getInstrPredicate - If instruction is predicated, returns its predicate
2217 /// condition, otherwise returns AL. It also returns the condition code
2218 /// register by reference.
2219 ARMCC::CondCodes llvm::getInstrPredicate(const MachineInstr &MI,
2220                                          Register &PredReg) {
2221   int PIdx = MI.findFirstPredOperandIdx();
2222   if (PIdx == -1) {
2223     PredReg = 0;
2224     return ARMCC::AL;
2225   }
2226 
2227   PredReg = MI.getOperand(PIdx+1).getReg();
2228   return (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
2229 }
2230 
2231 unsigned llvm::getMatchingCondBranchOpcode(unsigned Opc) {
2232   if (Opc == ARM::B)
2233     return ARM::Bcc;
2234   if (Opc == ARM::tB)
2235     return ARM::tBcc;
2236   if (Opc == ARM::t2B)
2237     return ARM::t2Bcc;
2238 
2239   llvm_unreachable("Unknown unconditional branch opcode!");
2240 }
2241 
2242 MachineInstr *ARMBaseInstrInfo::commuteInstructionImpl(MachineInstr &MI,
2243                                                        bool NewMI,
2244                                                        unsigned OpIdx1,
2245                                                        unsigned OpIdx2) const {
2246   switch (MI.getOpcode()) {
2247   case ARM::MOVCCr:
2248   case ARM::t2MOVCCr: {
2249     // MOVCC can be commuted by inverting the condition.
2250     Register PredReg;
2251     ARMCC::CondCodes CC = getInstrPredicate(MI, PredReg);
2252     // MOVCC AL can't be inverted. Shouldn't happen.
2253     if (CC == ARMCC::AL || PredReg != ARM::CPSR)
2254       return nullptr;
2255     MachineInstr *CommutedMI =
2256         TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
2257     if (!CommutedMI)
2258       return nullptr;
2259     // After swapping the MOVCC operands, also invert the condition.
2260     CommutedMI->getOperand(CommutedMI->findFirstPredOperandIdx())
2261         .setImm(ARMCC::getOppositeCondition(CC));
2262     return CommutedMI;
2263   }
2264   }
2265   return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
2266 }
2267 
2268 /// Identify instructions that can be folded into a MOVCC instruction, and
2269 /// return the defining instruction.
2270 MachineInstr *
2271 ARMBaseInstrInfo::canFoldIntoMOVCC(Register Reg, const MachineRegisterInfo &MRI,
2272                                    const TargetInstrInfo *TII) const {
2273   if (!Reg.isVirtual())
2274     return nullptr;
2275   if (!MRI.hasOneNonDBGUse(Reg))
2276     return nullptr;
2277   MachineInstr *MI = MRI.getVRegDef(Reg);
2278   if (!MI)
2279     return nullptr;
2280   // Check if MI can be predicated and folded into the MOVCC.
2281   if (!isPredicable(*MI))
2282     return nullptr;
2283   // Check if MI has any non-dead defs or physreg uses. This also detects
2284   // predicated instructions which will be reading CPSR.
2285   for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
2286     const MachineOperand &MO = MI->getOperand(i);
2287     // Reject frame index operands, PEI can't handle the predicated pseudos.
2288     if (MO.isFI() || MO.isCPI() || MO.isJTI())
2289       return nullptr;
2290     if (!MO.isReg())
2291       continue;
2292     // MI can't have any tied operands, that would conflict with predication.
2293     if (MO.isTied())
2294       return nullptr;
2295     if (Register::isPhysicalRegister(MO.getReg()))
2296       return nullptr;
2297     if (MO.isDef() && !MO.isDead())
2298       return nullptr;
2299   }
2300   bool DontMoveAcrossStores = true;
2301   if (!MI->isSafeToMove(/* AliasAnalysis = */ nullptr, DontMoveAcrossStores))
2302     return nullptr;
2303   return MI;
2304 }
2305 
2306 bool ARMBaseInstrInfo::analyzeSelect(const MachineInstr &MI,
2307                                      SmallVectorImpl<MachineOperand> &Cond,
2308                                      unsigned &TrueOp, unsigned &FalseOp,
2309                                      bool &Optimizable) const {
2310   assert((MI.getOpcode() == ARM::MOVCCr || MI.getOpcode() == ARM::t2MOVCCr) &&
2311          "Unknown select instruction");
2312   // MOVCC operands:
2313   // 0: Def.
2314   // 1: True use.
2315   // 2: False use.
2316   // 3: Condition code.
2317   // 4: CPSR use.
2318   TrueOp = 1;
2319   FalseOp = 2;
2320   Cond.push_back(MI.getOperand(3));
2321   Cond.push_back(MI.getOperand(4));
2322   // We can always fold a def.
2323   Optimizable = true;
2324   return false;
2325 }
2326 
2327 MachineInstr *
2328 ARMBaseInstrInfo::optimizeSelect(MachineInstr &MI,
2329                                  SmallPtrSetImpl<MachineInstr *> &SeenMIs,
2330                                  bool PreferFalse) const {
2331   assert((MI.getOpcode() == ARM::MOVCCr || MI.getOpcode() == ARM::t2MOVCCr) &&
2332          "Unknown select instruction");
2333   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
2334   MachineInstr *DefMI = canFoldIntoMOVCC(MI.getOperand(2).getReg(), MRI, this);
2335   bool Invert = !DefMI;
2336   if (!DefMI)
2337     DefMI = canFoldIntoMOVCC(MI.getOperand(1).getReg(), MRI, this);
2338   if (!DefMI)
2339     return nullptr;
2340 
2341   // Find new register class to use.
2342   MachineOperand FalseReg = MI.getOperand(Invert ? 2 : 1);
2343   Register DestReg = MI.getOperand(0).getReg();
2344   const TargetRegisterClass *PreviousClass = MRI.getRegClass(FalseReg.getReg());
2345   if (!MRI.constrainRegClass(DestReg, PreviousClass))
2346     return nullptr;
2347 
2348   // Create a new predicated version of DefMI.
2349   // Rfalse is the first use.
2350   MachineInstrBuilder NewMI =
2351       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), DefMI->getDesc(), DestReg);
2352 
2353   // Copy all the DefMI operands, excluding its (null) predicate.
2354   const MCInstrDesc &DefDesc = DefMI->getDesc();
2355   for (unsigned i = 1, e = DefDesc.getNumOperands();
2356        i != e && !DefDesc.OpInfo[i].isPredicate(); ++i)
2357     NewMI.add(DefMI->getOperand(i));
2358 
2359   unsigned CondCode = MI.getOperand(3).getImm();
2360   if (Invert)
2361     NewMI.addImm(ARMCC::getOppositeCondition(ARMCC::CondCodes(CondCode)));
2362   else
2363     NewMI.addImm(CondCode);
2364   NewMI.add(MI.getOperand(4));
2365 
2366   // DefMI is not the -S version that sets CPSR, so add an optional %noreg.
2367   if (NewMI->hasOptionalDef())
2368     NewMI.add(condCodeOp());
2369 
2370   // The output register value when the predicate is false is an implicit
2371   // register operand tied to the first def.
2372   // The tie makes the register allocator ensure the FalseReg is allocated the
2373   // same register as operand 0.
2374   FalseReg.setImplicit();
2375   NewMI.add(FalseReg);
2376   NewMI->tieOperands(0, NewMI->getNumOperands() - 1);
2377 
2378   // Update SeenMIs set: register newly created MI and erase removed DefMI.
2379   SeenMIs.insert(NewMI);
2380   SeenMIs.erase(DefMI);
2381 
2382   // If MI is inside a loop, and DefMI is outside the loop, then kill flags on
2383   // DefMI would be invalid when tranferred inside the loop.  Checking for a
2384   // loop is expensive, but at least remove kill flags if they are in different
2385   // BBs.
2386   if (DefMI->getParent() != MI.getParent())
2387     NewMI->clearKillInfo();
2388 
2389   // The caller will erase MI, but not DefMI.
2390   DefMI->eraseFromParent();
2391   return NewMI;
2392 }
2393 
2394 /// Map pseudo instructions that imply an 'S' bit onto real opcodes. Whether the
2395 /// instruction is encoded with an 'S' bit is determined by the optional CPSR
2396 /// def operand.
2397 ///
2398 /// This will go away once we can teach tblgen how to set the optional CPSR def
2399 /// operand itself.
2400 struct AddSubFlagsOpcodePair {
2401   uint16_t PseudoOpc;
2402   uint16_t MachineOpc;
2403 };
2404 
2405 static const AddSubFlagsOpcodePair AddSubFlagsOpcodeMap[] = {
2406   {ARM::ADDSri, ARM::ADDri},
2407   {ARM::ADDSrr, ARM::ADDrr},
2408   {ARM::ADDSrsi, ARM::ADDrsi},
2409   {ARM::ADDSrsr, ARM::ADDrsr},
2410 
2411   {ARM::SUBSri, ARM::SUBri},
2412   {ARM::SUBSrr, ARM::SUBrr},
2413   {ARM::SUBSrsi, ARM::SUBrsi},
2414   {ARM::SUBSrsr, ARM::SUBrsr},
2415 
2416   {ARM::RSBSri, ARM::RSBri},
2417   {ARM::RSBSrsi, ARM::RSBrsi},
2418   {ARM::RSBSrsr, ARM::RSBrsr},
2419 
2420   {ARM::tADDSi3, ARM::tADDi3},
2421   {ARM::tADDSi8, ARM::tADDi8},
2422   {ARM::tADDSrr, ARM::tADDrr},
2423   {ARM::tADCS, ARM::tADC},
2424 
2425   {ARM::tSUBSi3, ARM::tSUBi3},
2426   {ARM::tSUBSi8, ARM::tSUBi8},
2427   {ARM::tSUBSrr, ARM::tSUBrr},
2428   {ARM::tSBCS, ARM::tSBC},
2429   {ARM::tRSBS, ARM::tRSB},
2430   {ARM::tLSLSri, ARM::tLSLri},
2431 
2432   {ARM::t2ADDSri, ARM::t2ADDri},
2433   {ARM::t2ADDSrr, ARM::t2ADDrr},
2434   {ARM::t2ADDSrs, ARM::t2ADDrs},
2435 
2436   {ARM::t2SUBSri, ARM::t2SUBri},
2437   {ARM::t2SUBSrr, ARM::t2SUBrr},
2438   {ARM::t2SUBSrs, ARM::t2SUBrs},
2439 
2440   {ARM::t2RSBSri, ARM::t2RSBri},
2441   {ARM::t2RSBSrs, ARM::t2RSBrs},
2442 };
2443 
2444 unsigned llvm::convertAddSubFlagsOpcode(unsigned OldOpc) {
2445   for (unsigned i = 0, e = array_lengthof(AddSubFlagsOpcodeMap); i != e; ++i)
2446     if (OldOpc == AddSubFlagsOpcodeMap[i].PseudoOpc)
2447       return AddSubFlagsOpcodeMap[i].MachineOpc;
2448   return 0;
2449 }
2450 
2451 void llvm::emitARMRegPlusImmediate(MachineBasicBlock &MBB,
2452                                    MachineBasicBlock::iterator &MBBI,
2453                                    const DebugLoc &dl, Register DestReg,
2454                                    Register BaseReg, int NumBytes,
2455                                    ARMCC::CondCodes Pred, Register PredReg,
2456                                    const ARMBaseInstrInfo &TII,
2457                                    unsigned MIFlags) {
2458   if (NumBytes == 0 && DestReg != BaseReg) {
2459     BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), DestReg)
2460         .addReg(BaseReg, RegState::Kill)
2461         .add(predOps(Pred, PredReg))
2462         .add(condCodeOp())
2463         .setMIFlags(MIFlags);
2464     return;
2465   }
2466 
2467   bool isSub = NumBytes < 0;
2468   if (isSub) NumBytes = -NumBytes;
2469 
2470   while (NumBytes) {
2471     unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
2472     unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
2473     assert(ThisVal && "Didn't extract field correctly");
2474 
2475     // We will handle these bits from offset, clear them.
2476     NumBytes &= ~ThisVal;
2477 
2478     assert(ARM_AM::getSOImmVal(ThisVal) != -1 && "Bit extraction didn't work?");
2479 
2480     // Build the new ADD / SUB.
2481     unsigned Opc = isSub ? ARM::SUBri : ARM::ADDri;
2482     BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg)
2483         .addReg(BaseReg, RegState::Kill)
2484         .addImm(ThisVal)
2485         .add(predOps(Pred, PredReg))
2486         .add(condCodeOp())
2487         .setMIFlags(MIFlags);
2488     BaseReg = DestReg;
2489   }
2490 }
2491 
2492 bool llvm::tryFoldSPUpdateIntoPushPop(const ARMSubtarget &Subtarget,
2493                                       MachineFunction &MF, MachineInstr *MI,
2494                                       unsigned NumBytes) {
2495   // This optimisation potentially adds lots of load and store
2496   // micro-operations, it's only really a great benefit to code-size.
2497   if (!Subtarget.hasMinSize())
2498     return false;
2499 
2500   // If only one register is pushed/popped, LLVM can use an LDR/STR
2501   // instead. We can't modify those so make sure we're dealing with an
2502   // instruction we understand.
2503   bool IsPop = isPopOpcode(MI->getOpcode());
2504   bool IsPush = isPushOpcode(MI->getOpcode());
2505   if (!IsPush && !IsPop)
2506     return false;
2507 
2508   bool IsVFPPushPop = MI->getOpcode() == ARM::VSTMDDB_UPD ||
2509                       MI->getOpcode() == ARM::VLDMDIA_UPD;
2510   bool IsT1PushPop = MI->getOpcode() == ARM::tPUSH ||
2511                      MI->getOpcode() == ARM::tPOP ||
2512                      MI->getOpcode() == ARM::tPOP_RET;
2513 
2514   assert((IsT1PushPop || (MI->getOperand(0).getReg() == ARM::SP &&
2515                           MI->getOperand(1).getReg() == ARM::SP)) &&
2516          "trying to fold sp update into non-sp-updating push/pop");
2517 
2518   // The VFP push & pop act on D-registers, so we can only fold an adjustment
2519   // by a multiple of 8 bytes in correctly. Similarly rN is 4-bytes. Don't try
2520   // if this is violated.
2521   if (NumBytes % (IsVFPPushPop ? 8 : 4) != 0)
2522     return false;
2523 
2524   // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
2525   // pred) so the list starts at 4. Thumb1 starts after the predicate.
2526   int RegListIdx = IsT1PushPop ? 2 : 4;
2527 
2528   // Calculate the space we'll need in terms of registers.
2529   unsigned RegsNeeded;
2530   const TargetRegisterClass *RegClass;
2531   if (IsVFPPushPop) {
2532     RegsNeeded = NumBytes / 8;
2533     RegClass = &ARM::DPRRegClass;
2534   } else {
2535     RegsNeeded = NumBytes / 4;
2536     RegClass = &ARM::GPRRegClass;
2537   }
2538 
2539   // We're going to have to strip all list operands off before
2540   // re-adding them since the order matters, so save the existing ones
2541   // for later.
2542   SmallVector<MachineOperand, 4> RegList;
2543 
2544   // We're also going to need the first register transferred by this
2545   // instruction, which won't necessarily be the first register in the list.
2546   unsigned FirstRegEnc = -1;
2547 
2548   const TargetRegisterInfo *TRI = MF.getRegInfo().getTargetRegisterInfo();
2549   for (int i = MI->getNumOperands() - 1; i >= RegListIdx; --i) {
2550     MachineOperand &MO = MI->getOperand(i);
2551     RegList.push_back(MO);
2552 
2553     if (MO.isReg() && !MO.isImplicit() &&
2554         TRI->getEncodingValue(MO.getReg()) < FirstRegEnc)
2555       FirstRegEnc = TRI->getEncodingValue(MO.getReg());
2556   }
2557 
2558   const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF);
2559 
2560   // Now try to find enough space in the reglist to allocate NumBytes.
2561   for (int CurRegEnc = FirstRegEnc - 1; CurRegEnc >= 0 && RegsNeeded;
2562        --CurRegEnc) {
2563     unsigned CurReg = RegClass->getRegister(CurRegEnc);
2564     if (IsT1PushPop && CurRegEnc > TRI->getEncodingValue(ARM::R7))
2565       continue;
2566     if (!IsPop) {
2567       // Pushing any register is completely harmless, mark the register involved
2568       // as undef since we don't care about its value and must not restore it
2569       // during stack unwinding.
2570       RegList.push_back(MachineOperand::CreateReg(CurReg, false, false,
2571                                                   false, false, true));
2572       --RegsNeeded;
2573       continue;
2574     }
2575 
2576     // However, we can only pop an extra register if it's not live. For
2577     // registers live within the function we might clobber a return value
2578     // register; the other way a register can be live here is if it's
2579     // callee-saved.
2580     if (isCalleeSavedRegister(CurReg, CSRegs) ||
2581         MI->getParent()->computeRegisterLiveness(TRI, CurReg, MI) !=
2582         MachineBasicBlock::LQR_Dead) {
2583       // VFP pops don't allow holes in the register list, so any skip is fatal
2584       // for our transformation. GPR pops do, so we should just keep looking.
2585       if (IsVFPPushPop)
2586         return false;
2587       else
2588         continue;
2589     }
2590 
2591     // Mark the unimportant registers as <def,dead> in the POP.
2592     RegList.push_back(MachineOperand::CreateReg(CurReg, true, false, false,
2593                                                 true));
2594     --RegsNeeded;
2595   }
2596 
2597   if (RegsNeeded > 0)
2598     return false;
2599 
2600   // Finally we know we can profitably perform the optimisation so go
2601   // ahead: strip all existing registers off and add them back again
2602   // in the right order.
2603   for (int i = MI->getNumOperands() - 1; i >= RegListIdx; --i)
2604     MI->RemoveOperand(i);
2605 
2606   // Add the complete list back in.
2607   MachineInstrBuilder MIB(MF, &*MI);
2608   for (int i = RegList.size() - 1; i >= 0; --i)
2609     MIB.add(RegList[i]);
2610 
2611   return true;
2612 }
2613 
2614 bool llvm::rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
2615                                 Register FrameReg, int &Offset,
2616                                 const ARMBaseInstrInfo &TII) {
2617   unsigned Opcode = MI.getOpcode();
2618   const MCInstrDesc &Desc = MI.getDesc();
2619   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
2620   bool isSub = false;
2621 
2622   // Memory operands in inline assembly always use AddrMode2.
2623   if (Opcode == ARM::INLINEASM || Opcode == ARM::INLINEASM_BR)
2624     AddrMode = ARMII::AddrMode2;
2625 
2626   if (Opcode == ARM::ADDri) {
2627     Offset += MI.getOperand(FrameRegIdx+1).getImm();
2628     if (Offset == 0) {
2629       // Turn it into a move.
2630       MI.setDesc(TII.get(ARM::MOVr));
2631       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
2632       MI.RemoveOperand(FrameRegIdx+1);
2633       Offset = 0;
2634       return true;
2635     } else if (Offset < 0) {
2636       Offset = -Offset;
2637       isSub = true;
2638       MI.setDesc(TII.get(ARM::SUBri));
2639     }
2640 
2641     // Common case: small offset, fits into instruction.
2642     if (ARM_AM::getSOImmVal(Offset) != -1) {
2643       // Replace the FrameIndex with sp / fp
2644       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
2645       MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset);
2646       Offset = 0;
2647       return true;
2648     }
2649 
2650     // Otherwise, pull as much of the immedidate into this ADDri/SUBri
2651     // as possible.
2652     unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
2653     unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
2654 
2655     // We will handle these bits from offset, clear them.
2656     Offset &= ~ThisImmVal;
2657 
2658     // Get the properly encoded SOImmVal field.
2659     assert(ARM_AM::getSOImmVal(ThisImmVal) != -1 &&
2660            "Bit extraction didn't work?");
2661     MI.getOperand(FrameRegIdx+1).ChangeToImmediate(ThisImmVal);
2662  } else {
2663     unsigned ImmIdx = 0;
2664     int InstrOffs = 0;
2665     unsigned NumBits = 0;
2666     unsigned Scale = 1;
2667     switch (AddrMode) {
2668     case ARMII::AddrMode_i12:
2669       ImmIdx = FrameRegIdx + 1;
2670       InstrOffs = MI.getOperand(ImmIdx).getImm();
2671       NumBits = 12;
2672       break;
2673     case ARMII::AddrMode2:
2674       ImmIdx = FrameRegIdx+2;
2675       InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
2676       if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
2677         InstrOffs *= -1;
2678       NumBits = 12;
2679       break;
2680     case ARMII::AddrMode3:
2681       ImmIdx = FrameRegIdx+2;
2682       InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
2683       if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
2684         InstrOffs *= -1;
2685       NumBits = 8;
2686       break;
2687     case ARMII::AddrMode4:
2688     case ARMII::AddrMode6:
2689       // Can't fold any offset even if it's zero.
2690       return false;
2691     case ARMII::AddrMode5:
2692       ImmIdx = FrameRegIdx+1;
2693       InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
2694       if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
2695         InstrOffs *= -1;
2696       NumBits = 8;
2697       Scale = 4;
2698       break;
2699     case ARMII::AddrMode5FP16:
2700       ImmIdx = FrameRegIdx+1;
2701       InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
2702       if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
2703         InstrOffs *= -1;
2704       NumBits = 8;
2705       Scale = 2;
2706       break;
2707     case ARMII::AddrModeT2_i7:
2708     case ARMII::AddrModeT2_i7s2:
2709     case ARMII::AddrModeT2_i7s4:
2710       ImmIdx = FrameRegIdx+1;
2711       InstrOffs = MI.getOperand(ImmIdx).getImm();
2712       NumBits = 7;
2713       Scale = (AddrMode == ARMII::AddrModeT2_i7s2 ? 2 :
2714                AddrMode == ARMII::AddrModeT2_i7s4 ? 4 : 1);
2715       break;
2716     default:
2717       llvm_unreachable("Unsupported addressing mode!");
2718     }
2719 
2720     Offset += InstrOffs * Scale;
2721     assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
2722     if (Offset < 0) {
2723       Offset = -Offset;
2724       isSub = true;
2725     }
2726 
2727     // Attempt to fold address comp. if opcode has offset bits
2728     if (NumBits > 0) {
2729       // Common case: small offset, fits into instruction.
2730       MachineOperand &ImmOp = MI.getOperand(ImmIdx);
2731       int ImmedOffset = Offset / Scale;
2732       unsigned Mask = (1 << NumBits) - 1;
2733       if ((unsigned)Offset <= Mask * Scale) {
2734         // Replace the FrameIndex with sp
2735         MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
2736         // FIXME: When addrmode2 goes away, this will simplify (like the
2737         // T2 version), as the LDR.i12 versions don't need the encoding
2738         // tricks for the offset value.
2739         if (isSub) {
2740           if (AddrMode == ARMII::AddrMode_i12)
2741             ImmedOffset = -ImmedOffset;
2742           else
2743             ImmedOffset |= 1 << NumBits;
2744         }
2745         ImmOp.ChangeToImmediate(ImmedOffset);
2746         Offset = 0;
2747         return true;
2748       }
2749 
2750       // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
2751       ImmedOffset = ImmedOffset & Mask;
2752       if (isSub) {
2753         if (AddrMode == ARMII::AddrMode_i12)
2754           ImmedOffset = -ImmedOffset;
2755         else
2756           ImmedOffset |= 1 << NumBits;
2757       }
2758       ImmOp.ChangeToImmediate(ImmedOffset);
2759       Offset &= ~(Mask*Scale);
2760     }
2761   }
2762 
2763   Offset = (isSub) ? -Offset : Offset;
2764   return Offset == 0;
2765 }
2766 
2767 /// analyzeCompare - For a comparison instruction, return the source registers
2768 /// in SrcReg and SrcReg2 if having two register operands, and the value it
2769 /// compares against in CmpValue. Return true if the comparison instruction
2770 /// can be analyzed.
2771 bool ARMBaseInstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg,
2772                                       Register &SrcReg2, int &CmpMask,
2773                                       int &CmpValue) const {
2774   switch (MI.getOpcode()) {
2775   default: break;
2776   case ARM::CMPri:
2777   case ARM::t2CMPri:
2778   case ARM::tCMPi8:
2779     SrcReg = MI.getOperand(0).getReg();
2780     SrcReg2 = 0;
2781     CmpMask = ~0;
2782     CmpValue = MI.getOperand(1).getImm();
2783     return true;
2784   case ARM::CMPrr:
2785   case ARM::t2CMPrr:
2786   case ARM::tCMPr:
2787     SrcReg = MI.getOperand(0).getReg();
2788     SrcReg2 = MI.getOperand(1).getReg();
2789     CmpMask = ~0;
2790     CmpValue = 0;
2791     return true;
2792   case ARM::TSTri:
2793   case ARM::t2TSTri:
2794     SrcReg = MI.getOperand(0).getReg();
2795     SrcReg2 = 0;
2796     CmpMask = MI.getOperand(1).getImm();
2797     CmpValue = 0;
2798     return true;
2799   }
2800 
2801   return false;
2802 }
2803 
2804 /// isSuitableForMask - Identify a suitable 'and' instruction that
2805 /// operates on the given source register and applies the same mask
2806 /// as a 'tst' instruction. Provide a limited look-through for copies.
2807 /// When successful, MI will hold the found instruction.
2808 static bool isSuitableForMask(MachineInstr *&MI, Register SrcReg,
2809                               int CmpMask, bool CommonUse) {
2810   switch (MI->getOpcode()) {
2811     case ARM::ANDri:
2812     case ARM::t2ANDri:
2813       if (CmpMask != MI->getOperand(2).getImm())
2814         return false;
2815       if (SrcReg == MI->getOperand(CommonUse ? 1 : 0).getReg())
2816         return true;
2817       break;
2818   }
2819 
2820   return false;
2821 }
2822 
2823 /// getCmpToAddCondition - assume the flags are set by CMP(a,b), return
2824 /// the condition code if we modify the instructions such that flags are
2825 /// set by ADD(a,b,X).
2826 inline static ARMCC::CondCodes getCmpToAddCondition(ARMCC::CondCodes CC) {
2827   switch (CC) {
2828   default: return ARMCC::AL;
2829   case ARMCC::HS: return ARMCC::LO;
2830   case ARMCC::LO: return ARMCC::HS;
2831   case ARMCC::VS: return ARMCC::VS;
2832   case ARMCC::VC: return ARMCC::VC;
2833   }
2834 }
2835 
2836 /// isRedundantFlagInstr - check whether the first instruction, whose only
2837 /// purpose is to update flags, can be made redundant.
2838 /// CMPrr can be made redundant by SUBrr if the operands are the same.
2839 /// CMPri can be made redundant by SUBri if the operands are the same.
2840 /// CMPrr(r0, r1) can be made redundant by ADDr[ri](r0, r1, X).
2841 /// This function can be extended later on.
2842 inline static bool isRedundantFlagInstr(const MachineInstr *CmpI,
2843                                         Register SrcReg, Register SrcReg2,
2844                                         int ImmValue, const MachineInstr *OI,
2845                                         bool &IsThumb1) {
2846   if ((CmpI->getOpcode() == ARM::CMPrr || CmpI->getOpcode() == ARM::t2CMPrr) &&
2847       (OI->getOpcode() == ARM::SUBrr || OI->getOpcode() == ARM::t2SUBrr) &&
2848       ((OI->getOperand(1).getReg() == SrcReg &&
2849         OI->getOperand(2).getReg() == SrcReg2) ||
2850        (OI->getOperand(1).getReg() == SrcReg2 &&
2851         OI->getOperand(2).getReg() == SrcReg))) {
2852     IsThumb1 = false;
2853     return true;
2854   }
2855 
2856   if (CmpI->getOpcode() == ARM::tCMPr && OI->getOpcode() == ARM::tSUBrr &&
2857       ((OI->getOperand(2).getReg() == SrcReg &&
2858         OI->getOperand(3).getReg() == SrcReg2) ||
2859        (OI->getOperand(2).getReg() == SrcReg2 &&
2860         OI->getOperand(3).getReg() == SrcReg))) {
2861     IsThumb1 = true;
2862     return true;
2863   }
2864 
2865   if ((CmpI->getOpcode() == ARM::CMPri || CmpI->getOpcode() == ARM::t2CMPri) &&
2866       (OI->getOpcode() == ARM::SUBri || OI->getOpcode() == ARM::t2SUBri) &&
2867       OI->getOperand(1).getReg() == SrcReg &&
2868       OI->getOperand(2).getImm() == ImmValue) {
2869     IsThumb1 = false;
2870     return true;
2871   }
2872 
2873   if (CmpI->getOpcode() == ARM::tCMPi8 &&
2874       (OI->getOpcode() == ARM::tSUBi8 || OI->getOpcode() == ARM::tSUBi3) &&
2875       OI->getOperand(2).getReg() == SrcReg &&
2876       OI->getOperand(3).getImm() == ImmValue) {
2877     IsThumb1 = true;
2878     return true;
2879   }
2880 
2881   if ((CmpI->getOpcode() == ARM::CMPrr || CmpI->getOpcode() == ARM::t2CMPrr) &&
2882       (OI->getOpcode() == ARM::ADDrr || OI->getOpcode() == ARM::t2ADDrr ||
2883        OI->getOpcode() == ARM::ADDri || OI->getOpcode() == ARM::t2ADDri) &&
2884       OI->getOperand(0).isReg() && OI->getOperand(1).isReg() &&
2885       OI->getOperand(0).getReg() == SrcReg &&
2886       OI->getOperand(1).getReg() == SrcReg2) {
2887     IsThumb1 = false;
2888     return true;
2889   }
2890 
2891   if (CmpI->getOpcode() == ARM::tCMPr &&
2892       (OI->getOpcode() == ARM::tADDi3 || OI->getOpcode() == ARM::tADDi8 ||
2893        OI->getOpcode() == ARM::tADDrr) &&
2894       OI->getOperand(0).getReg() == SrcReg &&
2895       OI->getOperand(2).getReg() == SrcReg2) {
2896     IsThumb1 = true;
2897     return true;
2898   }
2899 
2900   return false;
2901 }
2902 
2903 static bool isOptimizeCompareCandidate(MachineInstr *MI, bool &IsThumb1) {
2904   switch (MI->getOpcode()) {
2905   default: return false;
2906   case ARM::tLSLri:
2907   case ARM::tLSRri:
2908   case ARM::tLSLrr:
2909   case ARM::tLSRrr:
2910   case ARM::tSUBrr:
2911   case ARM::tADDrr:
2912   case ARM::tADDi3:
2913   case ARM::tADDi8:
2914   case ARM::tSUBi3:
2915   case ARM::tSUBi8:
2916   case ARM::tMUL:
2917   case ARM::tADC:
2918   case ARM::tSBC:
2919   case ARM::tRSB:
2920   case ARM::tAND:
2921   case ARM::tORR:
2922   case ARM::tEOR:
2923   case ARM::tBIC:
2924   case ARM::tMVN:
2925   case ARM::tASRri:
2926   case ARM::tASRrr:
2927   case ARM::tROR:
2928     IsThumb1 = true;
2929     LLVM_FALLTHROUGH;
2930   case ARM::RSBrr:
2931   case ARM::RSBri:
2932   case ARM::RSCrr:
2933   case ARM::RSCri:
2934   case ARM::ADDrr:
2935   case ARM::ADDri:
2936   case ARM::ADCrr:
2937   case ARM::ADCri:
2938   case ARM::SUBrr:
2939   case ARM::SUBri:
2940   case ARM::SBCrr:
2941   case ARM::SBCri:
2942   case ARM::t2RSBri:
2943   case ARM::t2ADDrr:
2944   case ARM::t2ADDri:
2945   case ARM::t2ADCrr:
2946   case ARM::t2ADCri:
2947   case ARM::t2SUBrr:
2948   case ARM::t2SUBri:
2949   case ARM::t2SBCrr:
2950   case ARM::t2SBCri:
2951   case ARM::ANDrr:
2952   case ARM::ANDri:
2953   case ARM::t2ANDrr:
2954   case ARM::t2ANDri:
2955   case ARM::ORRrr:
2956   case ARM::ORRri:
2957   case ARM::t2ORRrr:
2958   case ARM::t2ORRri:
2959   case ARM::EORrr:
2960   case ARM::EORri:
2961   case ARM::t2EORrr:
2962   case ARM::t2EORri:
2963   case ARM::t2LSRri:
2964   case ARM::t2LSRrr:
2965   case ARM::t2LSLri:
2966   case ARM::t2LSLrr:
2967     return true;
2968   }
2969 }
2970 
2971 /// optimizeCompareInstr - Convert the instruction supplying the argument to the
2972 /// comparison into one that sets the zero bit in the flags register;
2973 /// Remove a redundant Compare instruction if an earlier instruction can set the
2974 /// flags in the same way as Compare.
2975 /// E.g. SUBrr(r1,r2) and CMPrr(r1,r2). We also handle the case where two
2976 /// operands are swapped: SUBrr(r1,r2) and CMPrr(r2,r1), by updating the
2977 /// condition code of instructions which use the flags.
2978 bool ARMBaseInstrInfo::optimizeCompareInstr(
2979     MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2, int CmpMask,
2980     int CmpValue, const MachineRegisterInfo *MRI) const {
2981   // Get the unique definition of SrcReg.
2982   MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
2983   if (!MI) return false;
2984 
2985   // Masked compares sometimes use the same register as the corresponding 'and'.
2986   if (CmpMask != ~0) {
2987     if (!isSuitableForMask(MI, SrcReg, CmpMask, false) || isPredicated(*MI)) {
2988       MI = nullptr;
2989       for (MachineRegisterInfo::use_instr_iterator
2990            UI = MRI->use_instr_begin(SrcReg), UE = MRI->use_instr_end();
2991            UI != UE; ++UI) {
2992         if (UI->getParent() != CmpInstr.getParent())
2993           continue;
2994         MachineInstr *PotentialAND = &*UI;
2995         if (!isSuitableForMask(PotentialAND, SrcReg, CmpMask, true) ||
2996             isPredicated(*PotentialAND))
2997           continue;
2998         MI = PotentialAND;
2999         break;
3000       }
3001       if (!MI) return false;
3002     }
3003   }
3004 
3005   // Get ready to iterate backward from CmpInstr.
3006   MachineBasicBlock::iterator I = CmpInstr, E = MI,
3007                               B = CmpInstr.getParent()->begin();
3008 
3009   // Early exit if CmpInstr is at the beginning of the BB.
3010   if (I == B) return false;
3011 
3012   // There are two possible candidates which can be changed to set CPSR:
3013   // One is MI, the other is a SUB or ADD instruction.
3014   // For CMPrr(r1,r2), we are looking for SUB(r1,r2), SUB(r2,r1), or
3015   // ADDr[ri](r1, r2, X).
3016   // For CMPri(r1, CmpValue), we are looking for SUBri(r1, CmpValue).
3017   MachineInstr *SubAdd = nullptr;
3018   if (SrcReg2 != 0)
3019     // MI is not a candidate for CMPrr.
3020     MI = nullptr;
3021   else if (MI->getParent() != CmpInstr.getParent() || CmpValue != 0) {
3022     // Conservatively refuse to convert an instruction which isn't in the same
3023     // BB as the comparison.
3024     // For CMPri w/ CmpValue != 0, a SubAdd may still be a candidate.
3025     // Thus we cannot return here.
3026     if (CmpInstr.getOpcode() == ARM::CMPri ||
3027         CmpInstr.getOpcode() == ARM::t2CMPri ||
3028         CmpInstr.getOpcode() == ARM::tCMPi8)
3029       MI = nullptr;
3030     else
3031       return false;
3032   }
3033 
3034   bool IsThumb1 = false;
3035   if (MI && !isOptimizeCompareCandidate(MI, IsThumb1))
3036     return false;
3037 
3038   // We also want to do this peephole for cases like this: if (a*b == 0),
3039   // and optimise away the CMP instruction from the generated code sequence:
3040   // MULS, MOVS, MOVS, CMP. Here the MOVS instructions load the boolean values
3041   // resulting from the select instruction, but these MOVS instructions for
3042   // Thumb1 (V6M) are flag setting and are thus preventing this optimisation.
3043   // However, if we only have MOVS instructions in between the CMP and the
3044   // other instruction (the MULS in this example), then the CPSR is dead so we
3045   // can safely reorder the sequence into: MOVS, MOVS, MULS, CMP. We do this
3046   // reordering and then continue the analysis hoping we can eliminate the
3047   // CMP. This peephole works on the vregs, so is still in SSA form. As a
3048   // consequence, the movs won't redefine/kill the MUL operands which would
3049   // make this reordering illegal.
3050   const TargetRegisterInfo *TRI = &getRegisterInfo();
3051   if (MI && IsThumb1) {
3052     --I;
3053     if (I != E && !MI->readsRegister(ARM::CPSR, TRI)) {
3054       bool CanReorder = true;
3055       for (; I != E; --I) {
3056         if (I->getOpcode() != ARM::tMOVi8) {
3057           CanReorder = false;
3058           break;
3059         }
3060       }
3061       if (CanReorder) {
3062         MI = MI->removeFromParent();
3063         E = CmpInstr;
3064         CmpInstr.getParent()->insert(E, MI);
3065       }
3066     }
3067     I = CmpInstr;
3068     E = MI;
3069   }
3070 
3071   // Check that CPSR isn't set between the comparison instruction and the one we
3072   // want to change. At the same time, search for SubAdd.
3073   bool SubAddIsThumb1 = false;
3074   do {
3075     const MachineInstr &Instr = *--I;
3076 
3077     // Check whether CmpInstr can be made redundant by the current instruction.
3078     if (isRedundantFlagInstr(&CmpInstr, SrcReg, SrcReg2, CmpValue, &Instr,
3079                              SubAddIsThumb1)) {
3080       SubAdd = &*I;
3081       break;
3082     }
3083 
3084     // Allow E (which was initially MI) to be SubAdd but do not search before E.
3085     if (I == E)
3086       break;
3087 
3088     if (Instr.modifiesRegister(ARM::CPSR, TRI) ||
3089         Instr.readsRegister(ARM::CPSR, TRI))
3090       // This instruction modifies or uses CPSR after the one we want to
3091       // change. We can't do this transformation.
3092       return false;
3093 
3094     if (I == B) {
3095       // In some cases, we scan the use-list of an instruction for an AND;
3096       // that AND is in the same BB, but may not be scheduled before the
3097       // corresponding TST.  In that case, bail out.
3098       //
3099       // FIXME: We could try to reschedule the AND.
3100       return false;
3101     }
3102   } while (true);
3103 
3104   // Return false if no candidates exist.
3105   if (!MI && !SubAdd)
3106     return false;
3107 
3108   // If we found a SubAdd, use it as it will be closer to the CMP
3109   if (SubAdd) {
3110     MI = SubAdd;
3111     IsThumb1 = SubAddIsThumb1;
3112   }
3113 
3114   // We can't use a predicated instruction - it doesn't always write the flags.
3115   if (isPredicated(*MI))
3116     return false;
3117 
3118   // Scan forward for the use of CPSR
3119   // When checking against MI: if it's a conditional code that requires
3120   // checking of the V bit or C bit, then this is not safe to do.
3121   // It is safe to remove CmpInstr if CPSR is redefined or killed.
3122   // If we are done with the basic block, we need to check whether CPSR is
3123   // live-out.
3124   SmallVector<std::pair<MachineOperand*, ARMCC::CondCodes>, 4>
3125       OperandsToUpdate;
3126   bool isSafe = false;
3127   I = CmpInstr;
3128   E = CmpInstr.getParent()->end();
3129   while (!isSafe && ++I != E) {
3130     const MachineInstr &Instr = *I;
3131     for (unsigned IO = 0, EO = Instr.getNumOperands();
3132          !isSafe && IO != EO; ++IO) {
3133       const MachineOperand &MO = Instr.getOperand(IO);
3134       if (MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) {
3135         isSafe = true;
3136         break;
3137       }
3138       if (!MO.isReg() || MO.getReg() != ARM::CPSR)
3139         continue;
3140       if (MO.isDef()) {
3141         isSafe = true;
3142         break;
3143       }
3144       // Condition code is after the operand before CPSR except for VSELs.
3145       ARMCC::CondCodes CC;
3146       bool IsInstrVSel = true;
3147       switch (Instr.getOpcode()) {
3148       default:
3149         IsInstrVSel = false;
3150         CC = (ARMCC::CondCodes)Instr.getOperand(IO - 1).getImm();
3151         break;
3152       case ARM::VSELEQD:
3153       case ARM::VSELEQS:
3154       case ARM::VSELEQH:
3155         CC = ARMCC::EQ;
3156         break;
3157       case ARM::VSELGTD:
3158       case ARM::VSELGTS:
3159       case ARM::VSELGTH:
3160         CC = ARMCC::GT;
3161         break;
3162       case ARM::VSELGED:
3163       case ARM::VSELGES:
3164       case ARM::VSELGEH:
3165         CC = ARMCC::GE;
3166         break;
3167       case ARM::VSELVSD:
3168       case ARM::VSELVSS:
3169       case ARM::VSELVSH:
3170         CC = ARMCC::VS;
3171         break;
3172       }
3173 
3174       if (SubAdd) {
3175         // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based
3176         // on CMP needs to be updated to be based on SUB.
3177         // If we have ADD(r1, r2, X) and CMP(r1, r2), the condition code also
3178         // needs to be modified.
3179         // Push the condition code operands to OperandsToUpdate.
3180         // If it is safe to remove CmpInstr, the condition code of these
3181         // operands will be modified.
3182         unsigned Opc = SubAdd->getOpcode();
3183         bool IsSub = Opc == ARM::SUBrr || Opc == ARM::t2SUBrr ||
3184                      Opc == ARM::SUBri || Opc == ARM::t2SUBri ||
3185                      Opc == ARM::tSUBrr || Opc == ARM::tSUBi3 ||
3186                      Opc == ARM::tSUBi8;
3187         unsigned OpI = Opc != ARM::tSUBrr ? 1 : 2;
3188         if (!IsSub ||
3189             (SrcReg2 != 0 && SubAdd->getOperand(OpI).getReg() == SrcReg2 &&
3190              SubAdd->getOperand(OpI + 1).getReg() == SrcReg)) {
3191           // VSel doesn't support condition code update.
3192           if (IsInstrVSel)
3193             return false;
3194           // Ensure we can swap the condition.
3195           ARMCC::CondCodes NewCC = (IsSub ? getSwappedCondition(CC) : getCmpToAddCondition(CC));
3196           if (NewCC == ARMCC::AL)
3197             return false;
3198           OperandsToUpdate.push_back(
3199               std::make_pair(&((*I).getOperand(IO - 1)), NewCC));
3200         }
3201       } else {
3202         // No SubAdd, so this is x = <op> y, z; cmp x, 0.
3203         switch (CC) {
3204         case ARMCC::EQ: // Z
3205         case ARMCC::NE: // Z
3206         case ARMCC::MI: // N
3207         case ARMCC::PL: // N
3208         case ARMCC::AL: // none
3209           // CPSR can be used multiple times, we should continue.
3210           break;
3211         case ARMCC::HS: // C
3212         case ARMCC::LO: // C
3213         case ARMCC::VS: // V
3214         case ARMCC::VC: // V
3215         case ARMCC::HI: // C Z
3216         case ARMCC::LS: // C Z
3217         case ARMCC::GE: // N V
3218         case ARMCC::LT: // N V
3219         case ARMCC::GT: // Z N V
3220         case ARMCC::LE: // Z N V
3221           // The instruction uses the V bit or C bit which is not safe.
3222           return false;
3223         }
3224       }
3225     }
3226   }
3227 
3228   // If CPSR is not killed nor re-defined, we should check whether it is
3229   // live-out. If it is live-out, do not optimize.
3230   if (!isSafe) {
3231     MachineBasicBlock *MBB = CmpInstr.getParent();
3232     for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
3233              SE = MBB->succ_end(); SI != SE; ++SI)
3234       if ((*SI)->isLiveIn(ARM::CPSR))
3235         return false;
3236   }
3237 
3238   // Toggle the optional operand to CPSR (if it exists - in Thumb1 we always
3239   // set CPSR so this is represented as an explicit output)
3240   if (!IsThumb1) {
3241     MI->getOperand(5).setReg(ARM::CPSR);
3242     MI->getOperand(5).setIsDef(true);
3243   }
3244   assert(!isPredicated(*MI) && "Can't use flags from predicated instruction");
3245   CmpInstr.eraseFromParent();
3246 
3247   // Modify the condition code of operands in OperandsToUpdate.
3248   // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
3249   // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
3250   for (unsigned i = 0, e = OperandsToUpdate.size(); i < e; i++)
3251     OperandsToUpdate[i].first->setImm(OperandsToUpdate[i].second);
3252 
3253   MI->clearRegisterDeads(ARM::CPSR);
3254 
3255   return true;
3256 }
3257 
3258 bool ARMBaseInstrInfo::shouldSink(const MachineInstr &MI) const {
3259   // Do not sink MI if it might be used to optimize a redundant compare.
3260   // We heuristically only look at the instruction immediately following MI to
3261   // avoid potentially searching the entire basic block.
3262   if (isPredicated(MI))
3263     return true;
3264   MachineBasicBlock::const_iterator Next = &MI;
3265   ++Next;
3266   Register SrcReg, SrcReg2;
3267   int CmpMask, CmpValue;
3268   bool IsThumb1;
3269   if (Next != MI.getParent()->end() &&
3270       analyzeCompare(*Next, SrcReg, SrcReg2, CmpMask, CmpValue) &&
3271       isRedundantFlagInstr(&*Next, SrcReg, SrcReg2, CmpValue, &MI, IsThumb1))
3272     return false;
3273   return true;
3274 }
3275 
3276 bool ARMBaseInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
3277                                      Register Reg,
3278                                      MachineRegisterInfo *MRI) const {
3279   // Fold large immediates into add, sub, or, xor.
3280   unsigned DefOpc = DefMI.getOpcode();
3281   if (DefOpc != ARM::t2MOVi32imm && DefOpc != ARM::MOVi32imm)
3282     return false;
3283   if (!DefMI.getOperand(1).isImm())
3284     // Could be t2MOVi32imm @xx
3285     return false;
3286 
3287   if (!MRI->hasOneNonDBGUse(Reg))
3288     return false;
3289 
3290   const MCInstrDesc &DefMCID = DefMI.getDesc();
3291   if (DefMCID.hasOptionalDef()) {
3292     unsigned NumOps = DefMCID.getNumOperands();
3293     const MachineOperand &MO = DefMI.getOperand(NumOps - 1);
3294     if (MO.getReg() == ARM::CPSR && !MO.isDead())
3295       // If DefMI defines CPSR and it is not dead, it's obviously not safe
3296       // to delete DefMI.
3297       return false;
3298   }
3299 
3300   const MCInstrDesc &UseMCID = UseMI.getDesc();
3301   if (UseMCID.hasOptionalDef()) {
3302     unsigned NumOps = UseMCID.getNumOperands();
3303     if (UseMI.getOperand(NumOps - 1).getReg() == ARM::CPSR)
3304       // If the instruction sets the flag, do not attempt this optimization
3305       // since it may change the semantics of the code.
3306       return false;
3307   }
3308 
3309   unsigned UseOpc = UseMI.getOpcode();
3310   unsigned NewUseOpc = 0;
3311   uint32_t ImmVal = (uint32_t)DefMI.getOperand(1).getImm();
3312   uint32_t SOImmValV1 = 0, SOImmValV2 = 0;
3313   bool Commute = false;
3314   switch (UseOpc) {
3315   default: return false;
3316   case ARM::SUBrr:
3317   case ARM::ADDrr:
3318   case ARM::ORRrr:
3319   case ARM::EORrr:
3320   case ARM::t2SUBrr:
3321   case ARM::t2ADDrr:
3322   case ARM::t2ORRrr:
3323   case ARM::t2EORrr: {
3324     Commute = UseMI.getOperand(2).getReg() != Reg;
3325     switch (UseOpc) {
3326     default: break;
3327     case ARM::ADDrr:
3328     case ARM::SUBrr:
3329       if (UseOpc == ARM::SUBrr && Commute)
3330         return false;
3331 
3332       // ADD/SUB are special because they're essentially the same operation, so
3333       // we can handle a larger range of immediates.
3334       if (ARM_AM::isSOImmTwoPartVal(ImmVal))
3335         NewUseOpc = UseOpc == ARM::ADDrr ? ARM::ADDri : ARM::SUBri;
3336       else if (ARM_AM::isSOImmTwoPartVal(-ImmVal)) {
3337         ImmVal = -ImmVal;
3338         NewUseOpc = UseOpc == ARM::ADDrr ? ARM::SUBri : ARM::ADDri;
3339       } else
3340         return false;
3341       SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal);
3342       SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal);
3343       break;
3344     case ARM::ORRrr:
3345     case ARM::EORrr:
3346       if (!ARM_AM::isSOImmTwoPartVal(ImmVal))
3347         return false;
3348       SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal);
3349       SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal);
3350       switch (UseOpc) {
3351       default: break;
3352       case ARM::ORRrr: NewUseOpc = ARM::ORRri; break;
3353       case ARM::EORrr: NewUseOpc = ARM::EORri; break;
3354       }
3355       break;
3356     case ARM::t2ADDrr:
3357     case ARM::t2SUBrr: {
3358       if (UseOpc == ARM::t2SUBrr && Commute)
3359         return false;
3360 
3361       // ADD/SUB are special because they're essentially the same operation, so
3362       // we can handle a larger range of immediates.
3363       const bool ToSP = DefMI.getOperand(0).getReg() == ARM::SP;
3364       const unsigned t2ADD = ToSP ? ARM::t2ADDspImm : ARM::t2ADDri;
3365       const unsigned t2SUB = ToSP ? ARM::t2SUBspImm : ARM::t2SUBri;
3366       if (ARM_AM::isT2SOImmTwoPartVal(ImmVal))
3367         NewUseOpc = UseOpc == ARM::t2ADDrr ? t2ADD : t2SUB;
3368       else if (ARM_AM::isT2SOImmTwoPartVal(-ImmVal)) {
3369         ImmVal = -ImmVal;
3370         NewUseOpc = UseOpc == ARM::t2ADDrr ? t2SUB : t2ADD;
3371       } else
3372         return false;
3373       SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal);
3374       SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal);
3375       break;
3376     }
3377     case ARM::t2ORRrr:
3378     case ARM::t2EORrr:
3379       if (!ARM_AM::isT2SOImmTwoPartVal(ImmVal))
3380         return false;
3381       SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal);
3382       SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal);
3383       switch (UseOpc) {
3384       default: break;
3385       case ARM::t2ORRrr: NewUseOpc = ARM::t2ORRri; break;
3386       case ARM::t2EORrr: NewUseOpc = ARM::t2EORri; break;
3387       }
3388       break;
3389     }
3390   }
3391   }
3392 
3393   unsigned OpIdx = Commute ? 2 : 1;
3394   Register Reg1 = UseMI.getOperand(OpIdx).getReg();
3395   bool isKill = UseMI.getOperand(OpIdx).isKill();
3396   const TargetRegisterClass *TRC = MRI->getRegClass(Reg);
3397   Register NewReg = MRI->createVirtualRegister(TRC);
3398   BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(), get(NewUseOpc),
3399           NewReg)
3400       .addReg(Reg1, getKillRegState(isKill))
3401       .addImm(SOImmValV1)
3402       .add(predOps(ARMCC::AL))
3403       .add(condCodeOp());
3404   UseMI.setDesc(get(NewUseOpc));
3405   UseMI.getOperand(1).setReg(NewReg);
3406   UseMI.getOperand(1).setIsKill();
3407   UseMI.getOperand(2).ChangeToImmediate(SOImmValV2);
3408   DefMI.eraseFromParent();
3409   // FIXME: t2ADDrr should be split, as different rulles apply when writing to SP.
3410   // Just as t2ADDri, that was split to [t2ADDri, t2ADDspImm].
3411   // Then the below code will not be needed, as the input/output register
3412   // classes will be rgpr or gprSP.
3413   // For now, we fix the UseMI operand explicitly here:
3414   switch(NewUseOpc){
3415     case ARM::t2ADDspImm:
3416     case ARM::t2SUBspImm:
3417     case ARM::t2ADDri:
3418     case ARM::t2SUBri:
3419       MRI->constrainRegClass(UseMI.getOperand(0).getReg(), TRC);
3420   }
3421   return true;
3422 }
3423 
3424 static unsigned getNumMicroOpsSwiftLdSt(const InstrItineraryData *ItinData,
3425                                         const MachineInstr &MI) {
3426   switch (MI.getOpcode()) {
3427   default: {
3428     const MCInstrDesc &Desc = MI.getDesc();
3429     int UOps = ItinData->getNumMicroOps(Desc.getSchedClass());
3430     assert(UOps >= 0 && "bad # UOps");
3431     return UOps;
3432   }
3433 
3434   case ARM::LDRrs:
3435   case ARM::LDRBrs:
3436   case ARM::STRrs:
3437   case ARM::STRBrs: {
3438     unsigned ShOpVal = MI.getOperand(3).getImm();
3439     bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3440     unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3441     if (!isSub &&
3442         (ShImm == 0 ||
3443          ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3444           ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3445       return 1;
3446     return 2;
3447   }
3448 
3449   case ARM::LDRH:
3450   case ARM::STRH: {
3451     if (!MI.getOperand(2).getReg())
3452       return 1;
3453 
3454     unsigned ShOpVal = MI.getOperand(3).getImm();
3455     bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3456     unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3457     if (!isSub &&
3458         (ShImm == 0 ||
3459          ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3460           ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3461       return 1;
3462     return 2;
3463   }
3464 
3465   case ARM::LDRSB:
3466   case ARM::LDRSH:
3467     return (ARM_AM::getAM3Op(MI.getOperand(3).getImm()) == ARM_AM::sub) ? 3 : 2;
3468 
3469   case ARM::LDRSB_POST:
3470   case ARM::LDRSH_POST: {
3471     Register Rt = MI.getOperand(0).getReg();
3472     Register Rm = MI.getOperand(3).getReg();
3473     return (Rt == Rm) ? 4 : 3;
3474   }
3475 
3476   case ARM::LDR_PRE_REG:
3477   case ARM::LDRB_PRE_REG: {
3478     Register Rt = MI.getOperand(0).getReg();
3479     Register Rm = MI.getOperand(3).getReg();
3480     if (Rt == Rm)
3481       return 3;
3482     unsigned ShOpVal = MI.getOperand(4).getImm();
3483     bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3484     unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3485     if (!isSub &&
3486         (ShImm == 0 ||
3487          ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3488           ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3489       return 2;
3490     return 3;
3491   }
3492 
3493   case ARM::STR_PRE_REG:
3494   case ARM::STRB_PRE_REG: {
3495     unsigned ShOpVal = MI.getOperand(4).getImm();
3496     bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3497     unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3498     if (!isSub &&
3499         (ShImm == 0 ||
3500          ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3501           ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3502       return 2;
3503     return 3;
3504   }
3505 
3506   case ARM::LDRH_PRE:
3507   case ARM::STRH_PRE: {
3508     Register Rt = MI.getOperand(0).getReg();
3509     Register Rm = MI.getOperand(3).getReg();
3510     if (!Rm)
3511       return 2;
3512     if (Rt == Rm)
3513       return 3;
3514     return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 3 : 2;
3515   }
3516 
3517   case ARM::LDR_POST_REG:
3518   case ARM::LDRB_POST_REG:
3519   case ARM::LDRH_POST: {
3520     Register Rt = MI.getOperand(0).getReg();
3521     Register Rm = MI.getOperand(3).getReg();
3522     return (Rt == Rm) ? 3 : 2;
3523   }
3524 
3525   case ARM::LDR_PRE_IMM:
3526   case ARM::LDRB_PRE_IMM:
3527   case ARM::LDR_POST_IMM:
3528   case ARM::LDRB_POST_IMM:
3529   case ARM::STRB_POST_IMM:
3530   case ARM::STRB_POST_REG:
3531   case ARM::STRB_PRE_IMM:
3532   case ARM::STRH_POST:
3533   case ARM::STR_POST_IMM:
3534   case ARM::STR_POST_REG:
3535   case ARM::STR_PRE_IMM:
3536     return 2;
3537 
3538   case ARM::LDRSB_PRE:
3539   case ARM::LDRSH_PRE: {
3540     Register Rm = MI.getOperand(3).getReg();
3541     if (Rm == 0)
3542       return 3;
3543     Register Rt = MI.getOperand(0).getReg();
3544     if (Rt == Rm)
3545       return 4;
3546     unsigned ShOpVal = MI.getOperand(4).getImm();
3547     bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3548     unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3549     if (!isSub &&
3550         (ShImm == 0 ||
3551          ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3552           ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3553       return 3;
3554     return 4;
3555   }
3556 
3557   case ARM::LDRD: {
3558     Register Rt = MI.getOperand(0).getReg();
3559     Register Rn = MI.getOperand(2).getReg();
3560     Register Rm = MI.getOperand(3).getReg();
3561     if (Rm)
3562       return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 4
3563                                                                           : 3;
3564     return (Rt == Rn) ? 3 : 2;
3565   }
3566 
3567   case ARM::STRD: {
3568     Register Rm = MI.getOperand(3).getReg();
3569     if (Rm)
3570       return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 4
3571                                                                           : 3;
3572     return 2;
3573   }
3574 
3575   case ARM::LDRD_POST:
3576   case ARM::t2LDRD_POST:
3577     return 3;
3578 
3579   case ARM::STRD_POST:
3580   case ARM::t2STRD_POST:
3581     return 4;
3582 
3583   case ARM::LDRD_PRE: {
3584     Register Rt = MI.getOperand(0).getReg();
3585     Register Rn = MI.getOperand(3).getReg();
3586     Register Rm = MI.getOperand(4).getReg();
3587     if (Rm)
3588       return (ARM_AM::getAM3Op(MI.getOperand(5).getImm()) == ARM_AM::sub) ? 5
3589                                                                           : 4;
3590     return (Rt == Rn) ? 4 : 3;
3591   }
3592 
3593   case ARM::t2LDRD_PRE: {
3594     Register Rt = MI.getOperand(0).getReg();
3595     Register Rn = MI.getOperand(3).getReg();
3596     return (Rt == Rn) ? 4 : 3;
3597   }
3598 
3599   case ARM::STRD_PRE: {
3600     Register Rm = MI.getOperand(4).getReg();
3601     if (Rm)
3602       return (ARM_AM::getAM3Op(MI.getOperand(5).getImm()) == ARM_AM::sub) ? 5
3603                                                                           : 4;
3604     return 3;
3605   }
3606 
3607   case ARM::t2STRD_PRE:
3608     return 3;
3609 
3610   case ARM::t2LDR_POST:
3611   case ARM::t2LDRB_POST:
3612   case ARM::t2LDRB_PRE:
3613   case ARM::t2LDRSBi12:
3614   case ARM::t2LDRSBi8:
3615   case ARM::t2LDRSBpci:
3616   case ARM::t2LDRSBs:
3617   case ARM::t2LDRH_POST:
3618   case ARM::t2LDRH_PRE:
3619   case ARM::t2LDRSBT:
3620   case ARM::t2LDRSB_POST:
3621   case ARM::t2LDRSB_PRE:
3622   case ARM::t2LDRSH_POST:
3623   case ARM::t2LDRSH_PRE:
3624   case ARM::t2LDRSHi12:
3625   case ARM::t2LDRSHi8:
3626   case ARM::t2LDRSHpci:
3627   case ARM::t2LDRSHs:
3628     return 2;
3629 
3630   case ARM::t2LDRDi8: {
3631     Register Rt = MI.getOperand(0).getReg();
3632     Register Rn = MI.getOperand(2).getReg();
3633     return (Rt == Rn) ? 3 : 2;
3634   }
3635 
3636   case ARM::t2STRB_POST:
3637   case ARM::t2STRB_PRE:
3638   case ARM::t2STRBs:
3639   case ARM::t2STRDi8:
3640   case ARM::t2STRH_POST:
3641   case ARM::t2STRH_PRE:
3642   case ARM::t2STRHs:
3643   case ARM::t2STR_POST:
3644   case ARM::t2STR_PRE:
3645   case ARM::t2STRs:
3646     return 2;
3647   }
3648 }
3649 
3650 // Return the number of 32-bit words loaded by LDM or stored by STM. If this
3651 // can't be easily determined return 0 (missing MachineMemOperand).
3652 //
3653 // FIXME: The current MachineInstr design does not support relying on machine
3654 // mem operands to determine the width of a memory access. Instead, we expect
3655 // the target to provide this information based on the instruction opcode and
3656 // operands. However, using MachineMemOperand is the best solution now for
3657 // two reasons:
3658 //
3659 // 1) getNumMicroOps tries to infer LDM memory width from the total number of MI
3660 // operands. This is much more dangerous than using the MachineMemOperand
3661 // sizes because CodeGen passes can insert/remove optional machine operands. In
3662 // fact, it's totally incorrect for preRA passes and appears to be wrong for
3663 // postRA passes as well.
3664 //
3665 // 2) getNumLDMAddresses is only used by the scheduling machine model and any
3666 // machine model that calls this should handle the unknown (zero size) case.
3667 //
3668 // Long term, we should require a target hook that verifies MachineMemOperand
3669 // sizes during MC lowering. That target hook should be local to MC lowering
3670 // because we can't ensure that it is aware of other MI forms. Doing this will
3671 // ensure that MachineMemOperands are correctly propagated through all passes.
3672 unsigned ARMBaseInstrInfo::getNumLDMAddresses(const MachineInstr &MI) const {
3673   unsigned Size = 0;
3674   for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
3675                                   E = MI.memoperands_end();
3676        I != E; ++I) {
3677     Size += (*I)->getSize();
3678   }
3679   // FIXME: The scheduler currently can't handle values larger than 16. But
3680   // the values can actually go up to 32 for floating-point load/store
3681   // multiple (VLDMIA etc.). Also, the way this code is reasoning about memory
3682   // operations isn't right; we could end up with "extra" memory operands for
3683   // various reasons, like tail merge merging two memory operations.
3684   return std::min(Size / 4, 16U);
3685 }
3686 
3687 static unsigned getNumMicroOpsSingleIssuePlusExtras(unsigned Opc,
3688                                                     unsigned NumRegs) {
3689   unsigned UOps = 1 + NumRegs; // 1 for address computation.
3690   switch (Opc) {
3691   default:
3692     break;
3693   case ARM::VLDMDIA_UPD:
3694   case ARM::VLDMDDB_UPD:
3695   case ARM::VLDMSIA_UPD:
3696   case ARM::VLDMSDB_UPD:
3697   case ARM::VSTMDIA_UPD:
3698   case ARM::VSTMDDB_UPD:
3699   case ARM::VSTMSIA_UPD:
3700   case ARM::VSTMSDB_UPD:
3701   case ARM::LDMIA_UPD:
3702   case ARM::LDMDA_UPD:
3703   case ARM::LDMDB_UPD:
3704   case ARM::LDMIB_UPD:
3705   case ARM::STMIA_UPD:
3706   case ARM::STMDA_UPD:
3707   case ARM::STMDB_UPD:
3708   case ARM::STMIB_UPD:
3709   case ARM::tLDMIA_UPD:
3710   case ARM::tSTMIA_UPD:
3711   case ARM::t2LDMIA_UPD:
3712   case ARM::t2LDMDB_UPD:
3713   case ARM::t2STMIA_UPD:
3714   case ARM::t2STMDB_UPD:
3715     ++UOps; // One for base register writeback.
3716     break;
3717   case ARM::LDMIA_RET:
3718   case ARM::tPOP_RET:
3719   case ARM::t2LDMIA_RET:
3720     UOps += 2; // One for base reg wb, one for write to pc.
3721     break;
3722   }
3723   return UOps;
3724 }
3725 
3726 unsigned ARMBaseInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
3727                                           const MachineInstr &MI) const {
3728   if (!ItinData || ItinData->isEmpty())
3729     return 1;
3730 
3731   const MCInstrDesc &Desc = MI.getDesc();
3732   unsigned Class = Desc.getSchedClass();
3733   int ItinUOps = ItinData->getNumMicroOps(Class);
3734   if (ItinUOps >= 0) {
3735     if (Subtarget.isSwift() && (Desc.mayLoad() || Desc.mayStore()))
3736       return getNumMicroOpsSwiftLdSt(ItinData, MI);
3737 
3738     return ItinUOps;
3739   }
3740 
3741   unsigned Opc = MI.getOpcode();
3742   switch (Opc) {
3743   default:
3744     llvm_unreachable("Unexpected multi-uops instruction!");
3745   case ARM::VLDMQIA:
3746   case ARM::VSTMQIA:
3747     return 2;
3748 
3749   // The number of uOps for load / store multiple are determined by the number
3750   // registers.
3751   //
3752   // On Cortex-A8, each pair of register loads / stores can be scheduled on the
3753   // same cycle. The scheduling for the first load / store must be done
3754   // separately by assuming the address is not 64-bit aligned.
3755   //
3756   // On Cortex-A9, the formula is simply (#reg / 2) + (#reg % 2). If the address
3757   // is not 64-bit aligned, then AGU would take an extra cycle.  For VFP / NEON
3758   // load / store multiple, the formula is (#reg / 2) + (#reg % 2) + 1.
3759   case ARM::VLDMDIA:
3760   case ARM::VLDMDIA_UPD:
3761   case ARM::VLDMDDB_UPD:
3762   case ARM::VLDMSIA:
3763   case ARM::VLDMSIA_UPD:
3764   case ARM::VLDMSDB_UPD:
3765   case ARM::VSTMDIA:
3766   case ARM::VSTMDIA_UPD:
3767   case ARM::VSTMDDB_UPD:
3768   case ARM::VSTMSIA:
3769   case ARM::VSTMSIA_UPD:
3770   case ARM::VSTMSDB_UPD: {
3771     unsigned NumRegs = MI.getNumOperands() - Desc.getNumOperands();
3772     return (NumRegs / 2) + (NumRegs % 2) + 1;
3773   }
3774 
3775   case ARM::LDMIA_RET:
3776   case ARM::LDMIA:
3777   case ARM::LDMDA:
3778   case ARM::LDMDB:
3779   case ARM::LDMIB:
3780   case ARM::LDMIA_UPD:
3781   case ARM::LDMDA_UPD:
3782   case ARM::LDMDB_UPD:
3783   case ARM::LDMIB_UPD:
3784   case ARM::STMIA:
3785   case ARM::STMDA:
3786   case ARM::STMDB:
3787   case ARM::STMIB:
3788   case ARM::STMIA_UPD:
3789   case ARM::STMDA_UPD:
3790   case ARM::STMDB_UPD:
3791   case ARM::STMIB_UPD:
3792   case ARM::tLDMIA:
3793   case ARM::tLDMIA_UPD:
3794   case ARM::tSTMIA_UPD:
3795   case ARM::tPOP_RET:
3796   case ARM::tPOP:
3797   case ARM::tPUSH:
3798   case ARM::t2LDMIA_RET:
3799   case ARM::t2LDMIA:
3800   case ARM::t2LDMDB:
3801   case ARM::t2LDMIA_UPD:
3802   case ARM::t2LDMDB_UPD:
3803   case ARM::t2STMIA:
3804   case ARM::t2STMDB:
3805   case ARM::t2STMIA_UPD:
3806   case ARM::t2STMDB_UPD: {
3807     unsigned NumRegs = MI.getNumOperands() - Desc.getNumOperands() + 1;
3808     switch (Subtarget.getLdStMultipleTiming()) {
3809     case ARMSubtarget::SingleIssuePlusExtras:
3810       return getNumMicroOpsSingleIssuePlusExtras(Opc, NumRegs);
3811     case ARMSubtarget::SingleIssue:
3812       // Assume the worst.
3813       return NumRegs;
3814     case ARMSubtarget::DoubleIssue: {
3815       if (NumRegs < 4)
3816         return 2;
3817       // 4 registers would be issued: 2, 2.
3818       // 5 registers would be issued: 2, 2, 1.
3819       unsigned UOps = (NumRegs / 2);
3820       if (NumRegs % 2)
3821         ++UOps;
3822       return UOps;
3823     }
3824     case ARMSubtarget::DoubleIssueCheckUnalignedAccess: {
3825       unsigned UOps = (NumRegs / 2);
3826       // If there are odd number of registers or if it's not 64-bit aligned,
3827       // then it takes an extra AGU (Address Generation Unit) cycle.
3828       if ((NumRegs % 2) || !MI.hasOneMemOperand() ||
3829           (*MI.memoperands_begin())->getAlign() < Align(8))
3830         ++UOps;
3831       return UOps;
3832       }
3833     }
3834   }
3835   }
3836   llvm_unreachable("Didn't find the number of microops");
3837 }
3838 
3839 int
3840 ARMBaseInstrInfo::getVLDMDefCycle(const InstrItineraryData *ItinData,
3841                                   const MCInstrDesc &DefMCID,
3842                                   unsigned DefClass,
3843                                   unsigned DefIdx, unsigned DefAlign) const {
3844   int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
3845   if (RegNo <= 0)
3846     // Def is the address writeback.
3847     return ItinData->getOperandCycle(DefClass, DefIdx);
3848 
3849   int DefCycle;
3850   if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
3851     // (regno / 2) + (regno % 2) + 1
3852     DefCycle = RegNo / 2 + 1;
3853     if (RegNo % 2)
3854       ++DefCycle;
3855   } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3856     DefCycle = RegNo;
3857     bool isSLoad = false;
3858 
3859     switch (DefMCID.getOpcode()) {
3860     default: break;
3861     case ARM::VLDMSIA:
3862     case ARM::VLDMSIA_UPD:
3863     case ARM::VLDMSDB_UPD:
3864       isSLoad = true;
3865       break;
3866     }
3867 
3868     // If there are odd number of 'S' registers or if it's not 64-bit aligned,
3869     // then it takes an extra cycle.
3870     if ((isSLoad && (RegNo % 2)) || DefAlign < 8)
3871       ++DefCycle;
3872   } else {
3873     // Assume the worst.
3874     DefCycle = RegNo + 2;
3875   }
3876 
3877   return DefCycle;
3878 }
3879 
3880 int
3881 ARMBaseInstrInfo::getLDMDefCycle(const InstrItineraryData *ItinData,
3882                                  const MCInstrDesc &DefMCID,
3883                                  unsigned DefClass,
3884                                  unsigned DefIdx, unsigned DefAlign) const {
3885   int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
3886   if (RegNo <= 0)
3887     // Def is the address writeback.
3888     return ItinData->getOperandCycle(DefClass, DefIdx);
3889 
3890   int DefCycle;
3891   if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
3892     // 4 registers would be issued: 1, 2, 1.
3893     // 5 registers would be issued: 1, 2, 2.
3894     DefCycle = RegNo / 2;
3895     if (DefCycle < 1)
3896       DefCycle = 1;
3897     // Result latency is issue cycle + 2: E2.
3898     DefCycle += 2;
3899   } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3900     DefCycle = (RegNo / 2);
3901     // If there are odd number of registers or if it's not 64-bit aligned,
3902     // then it takes an extra AGU (Address Generation Unit) cycle.
3903     if ((RegNo % 2) || DefAlign < 8)
3904       ++DefCycle;
3905     // Result latency is AGU cycles + 2.
3906     DefCycle += 2;
3907   } else {
3908     // Assume the worst.
3909     DefCycle = RegNo + 2;
3910   }
3911 
3912   return DefCycle;
3913 }
3914 
3915 int
3916 ARMBaseInstrInfo::getVSTMUseCycle(const InstrItineraryData *ItinData,
3917                                   const MCInstrDesc &UseMCID,
3918                                   unsigned UseClass,
3919                                   unsigned UseIdx, unsigned UseAlign) const {
3920   int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
3921   if (RegNo <= 0)
3922     return ItinData->getOperandCycle(UseClass, UseIdx);
3923 
3924   int UseCycle;
3925   if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
3926     // (regno / 2) + (regno % 2) + 1
3927     UseCycle = RegNo / 2 + 1;
3928     if (RegNo % 2)
3929       ++UseCycle;
3930   } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3931     UseCycle = RegNo;
3932     bool isSStore = false;
3933 
3934     switch (UseMCID.getOpcode()) {
3935     default: break;
3936     case ARM::VSTMSIA:
3937     case ARM::VSTMSIA_UPD:
3938     case ARM::VSTMSDB_UPD:
3939       isSStore = true;
3940       break;
3941     }
3942 
3943     // If there are odd number of 'S' registers or if it's not 64-bit aligned,
3944     // then it takes an extra cycle.
3945     if ((isSStore && (RegNo % 2)) || UseAlign < 8)
3946       ++UseCycle;
3947   } else {
3948     // Assume the worst.
3949     UseCycle = RegNo + 2;
3950   }
3951 
3952   return UseCycle;
3953 }
3954 
3955 int
3956 ARMBaseInstrInfo::getSTMUseCycle(const InstrItineraryData *ItinData,
3957                                  const MCInstrDesc &UseMCID,
3958                                  unsigned UseClass,
3959                                  unsigned UseIdx, unsigned UseAlign) const {
3960   int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
3961   if (RegNo <= 0)
3962     return ItinData->getOperandCycle(UseClass, UseIdx);
3963 
3964   int UseCycle;
3965   if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
3966     UseCycle = RegNo / 2;
3967     if (UseCycle < 2)
3968       UseCycle = 2;
3969     // Read in E3.
3970     UseCycle += 2;
3971   } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3972     UseCycle = (RegNo / 2);
3973     // If there are odd number of registers or if it's not 64-bit aligned,
3974     // then it takes an extra AGU (Address Generation Unit) cycle.
3975     if ((RegNo % 2) || UseAlign < 8)
3976       ++UseCycle;
3977   } else {
3978     // Assume the worst.
3979     UseCycle = 1;
3980   }
3981   return UseCycle;
3982 }
3983 
3984 int
3985 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
3986                                     const MCInstrDesc &DefMCID,
3987                                     unsigned DefIdx, unsigned DefAlign,
3988                                     const MCInstrDesc &UseMCID,
3989                                     unsigned UseIdx, unsigned UseAlign) const {
3990   unsigned DefClass = DefMCID.getSchedClass();
3991   unsigned UseClass = UseMCID.getSchedClass();
3992 
3993   if (DefIdx < DefMCID.getNumDefs() && UseIdx < UseMCID.getNumOperands())
3994     return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
3995 
3996   // This may be a def / use of a variable_ops instruction, the operand
3997   // latency might be determinable dynamically. Let the target try to
3998   // figure it out.
3999   int DefCycle = -1;
4000   bool LdmBypass = false;
4001   switch (DefMCID.getOpcode()) {
4002   default:
4003     DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
4004     break;
4005 
4006   case ARM::VLDMDIA:
4007   case ARM::VLDMDIA_UPD:
4008   case ARM::VLDMDDB_UPD:
4009   case ARM::VLDMSIA:
4010   case ARM::VLDMSIA_UPD:
4011   case ARM::VLDMSDB_UPD:
4012     DefCycle = getVLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
4013     break;
4014 
4015   case ARM::LDMIA_RET:
4016   case ARM::LDMIA:
4017   case ARM::LDMDA:
4018   case ARM::LDMDB:
4019   case ARM::LDMIB:
4020   case ARM::LDMIA_UPD:
4021   case ARM::LDMDA_UPD:
4022   case ARM::LDMDB_UPD:
4023   case ARM::LDMIB_UPD:
4024   case ARM::tLDMIA:
4025   case ARM::tLDMIA_UPD:
4026   case ARM::tPUSH:
4027   case ARM::t2LDMIA_RET:
4028   case ARM::t2LDMIA:
4029   case ARM::t2LDMDB:
4030   case ARM::t2LDMIA_UPD:
4031   case ARM::t2LDMDB_UPD:
4032     LdmBypass = true;
4033     DefCycle = getLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
4034     break;
4035   }
4036 
4037   if (DefCycle == -1)
4038     // We can't seem to determine the result latency of the def, assume it's 2.
4039     DefCycle = 2;
4040 
4041   int UseCycle = -1;
4042   switch (UseMCID.getOpcode()) {
4043   default:
4044     UseCycle = ItinData->getOperandCycle(UseClass, UseIdx);
4045     break;
4046 
4047   case ARM::VSTMDIA:
4048   case ARM::VSTMDIA_UPD:
4049   case ARM::VSTMDDB_UPD:
4050   case ARM::VSTMSIA:
4051   case ARM::VSTMSIA_UPD:
4052   case ARM::VSTMSDB_UPD:
4053     UseCycle = getVSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
4054     break;
4055 
4056   case ARM::STMIA:
4057   case ARM::STMDA:
4058   case ARM::STMDB:
4059   case ARM::STMIB:
4060   case ARM::STMIA_UPD:
4061   case ARM::STMDA_UPD:
4062   case ARM::STMDB_UPD:
4063   case ARM::STMIB_UPD:
4064   case ARM::tSTMIA_UPD:
4065   case ARM::tPOP_RET:
4066   case ARM::tPOP:
4067   case ARM::t2STMIA:
4068   case ARM::t2STMDB:
4069   case ARM::t2STMIA_UPD:
4070   case ARM::t2STMDB_UPD:
4071     UseCycle = getSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
4072     break;
4073   }
4074 
4075   if (UseCycle == -1)
4076     // Assume it's read in the first stage.
4077     UseCycle = 1;
4078 
4079   UseCycle = DefCycle - UseCycle + 1;
4080   if (UseCycle > 0) {
4081     if (LdmBypass) {
4082       // It's a variable_ops instruction so we can't use DefIdx here. Just use
4083       // first def operand.
4084       if (ItinData->hasPipelineForwarding(DefClass, DefMCID.getNumOperands()-1,
4085                                           UseClass, UseIdx))
4086         --UseCycle;
4087     } else if (ItinData->hasPipelineForwarding(DefClass, DefIdx,
4088                                                UseClass, UseIdx)) {
4089       --UseCycle;
4090     }
4091   }
4092 
4093   return UseCycle;
4094 }
4095 
4096 static const MachineInstr *getBundledDefMI(const TargetRegisterInfo *TRI,
4097                                            const MachineInstr *MI, unsigned Reg,
4098                                            unsigned &DefIdx, unsigned &Dist) {
4099   Dist = 0;
4100 
4101   MachineBasicBlock::const_iterator I = MI; ++I;
4102   MachineBasicBlock::const_instr_iterator II = std::prev(I.getInstrIterator());
4103   assert(II->isInsideBundle() && "Empty bundle?");
4104 
4105   int Idx = -1;
4106   while (II->isInsideBundle()) {
4107     Idx = II->findRegisterDefOperandIdx(Reg, false, true, TRI);
4108     if (Idx != -1)
4109       break;
4110     --II;
4111     ++Dist;
4112   }
4113 
4114   assert(Idx != -1 && "Cannot find bundled definition!");
4115   DefIdx = Idx;
4116   return &*II;
4117 }
4118 
4119 static const MachineInstr *getBundledUseMI(const TargetRegisterInfo *TRI,
4120                                            const MachineInstr &MI, unsigned Reg,
4121                                            unsigned &UseIdx, unsigned &Dist) {
4122   Dist = 0;
4123 
4124   MachineBasicBlock::const_instr_iterator II = ++MI.getIterator();
4125   assert(II->isInsideBundle() && "Empty bundle?");
4126   MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
4127 
4128   // FIXME: This doesn't properly handle multiple uses.
4129   int Idx = -1;
4130   while (II != E && II->isInsideBundle()) {
4131     Idx = II->findRegisterUseOperandIdx(Reg, false, TRI);
4132     if (Idx != -1)
4133       break;
4134     if (II->getOpcode() != ARM::t2IT)
4135       ++Dist;
4136     ++II;
4137   }
4138 
4139   if (Idx == -1) {
4140     Dist = 0;
4141     return nullptr;
4142   }
4143 
4144   UseIdx = Idx;
4145   return &*II;
4146 }
4147 
4148 /// Return the number of cycles to add to (or subtract from) the static
4149 /// itinerary based on the def opcode and alignment. The caller will ensure that
4150 /// adjusted latency is at least one cycle.
4151 static int adjustDefLatency(const ARMSubtarget &Subtarget,
4152                             const MachineInstr &DefMI,
4153                             const MCInstrDesc &DefMCID, unsigned DefAlign) {
4154   int Adjust = 0;
4155   if (Subtarget.isCortexA8() || Subtarget.isLikeA9() || Subtarget.isCortexA7()) {
4156     // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
4157     // variants are one cycle cheaper.
4158     switch (DefMCID.getOpcode()) {
4159     default: break;
4160     case ARM::LDRrs:
4161     case ARM::LDRBrs: {
4162       unsigned ShOpVal = DefMI.getOperand(3).getImm();
4163       unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
4164       if (ShImm == 0 ||
4165           (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
4166         --Adjust;
4167       break;
4168     }
4169     case ARM::t2LDRs:
4170     case ARM::t2LDRBs:
4171     case ARM::t2LDRHs:
4172     case ARM::t2LDRSHs: {
4173       // Thumb2 mode: lsl only.
4174       unsigned ShAmt = DefMI.getOperand(3).getImm();
4175       if (ShAmt == 0 || ShAmt == 2)
4176         --Adjust;
4177       break;
4178     }
4179     }
4180   } else if (Subtarget.isSwift()) {
4181     // FIXME: Properly handle all of the latency adjustments for address
4182     // writeback.
4183     switch (DefMCID.getOpcode()) {
4184     default: break;
4185     case ARM::LDRrs:
4186     case ARM::LDRBrs: {
4187       unsigned ShOpVal = DefMI.getOperand(3).getImm();
4188       bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
4189       unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
4190       if (!isSub &&
4191           (ShImm == 0 ||
4192            ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
4193             ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
4194         Adjust -= 2;
4195       else if (!isSub &&
4196                ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr)
4197         --Adjust;
4198       break;
4199     }
4200     case ARM::t2LDRs:
4201     case ARM::t2LDRBs:
4202     case ARM::t2LDRHs:
4203     case ARM::t2LDRSHs: {
4204       // Thumb2 mode: lsl only.
4205       unsigned ShAmt = DefMI.getOperand(3).getImm();
4206       if (ShAmt == 0 || ShAmt == 1 || ShAmt == 2 || ShAmt == 3)
4207         Adjust -= 2;
4208       break;
4209     }
4210     }
4211   }
4212 
4213   if (DefAlign < 8 && Subtarget.checkVLDnAccessAlignment()) {
4214     switch (DefMCID.getOpcode()) {
4215     default: break;
4216     case ARM::VLD1q8:
4217     case ARM::VLD1q16:
4218     case ARM::VLD1q32:
4219     case ARM::VLD1q64:
4220     case ARM::VLD1q8wb_fixed:
4221     case ARM::VLD1q16wb_fixed:
4222     case ARM::VLD1q32wb_fixed:
4223     case ARM::VLD1q64wb_fixed:
4224     case ARM::VLD1q8wb_register:
4225     case ARM::VLD1q16wb_register:
4226     case ARM::VLD1q32wb_register:
4227     case ARM::VLD1q64wb_register:
4228     case ARM::VLD2d8:
4229     case ARM::VLD2d16:
4230     case ARM::VLD2d32:
4231     case ARM::VLD2q8:
4232     case ARM::VLD2q16:
4233     case ARM::VLD2q32:
4234     case ARM::VLD2d8wb_fixed:
4235     case ARM::VLD2d16wb_fixed:
4236     case ARM::VLD2d32wb_fixed:
4237     case ARM::VLD2q8wb_fixed:
4238     case ARM::VLD2q16wb_fixed:
4239     case ARM::VLD2q32wb_fixed:
4240     case ARM::VLD2d8wb_register:
4241     case ARM::VLD2d16wb_register:
4242     case ARM::VLD2d32wb_register:
4243     case ARM::VLD2q8wb_register:
4244     case ARM::VLD2q16wb_register:
4245     case ARM::VLD2q32wb_register:
4246     case ARM::VLD3d8:
4247     case ARM::VLD3d16:
4248     case ARM::VLD3d32:
4249     case ARM::VLD1d64T:
4250     case ARM::VLD3d8_UPD:
4251     case ARM::VLD3d16_UPD:
4252     case ARM::VLD3d32_UPD:
4253     case ARM::VLD1d64Twb_fixed:
4254     case ARM::VLD1d64Twb_register:
4255     case ARM::VLD3q8_UPD:
4256     case ARM::VLD3q16_UPD:
4257     case ARM::VLD3q32_UPD:
4258     case ARM::VLD4d8:
4259     case ARM::VLD4d16:
4260     case ARM::VLD4d32:
4261     case ARM::VLD1d64Q:
4262     case ARM::VLD4d8_UPD:
4263     case ARM::VLD4d16_UPD:
4264     case ARM::VLD4d32_UPD:
4265     case ARM::VLD1d64Qwb_fixed:
4266     case ARM::VLD1d64Qwb_register:
4267     case ARM::VLD4q8_UPD:
4268     case ARM::VLD4q16_UPD:
4269     case ARM::VLD4q32_UPD:
4270     case ARM::VLD1DUPq8:
4271     case ARM::VLD1DUPq16:
4272     case ARM::VLD1DUPq32:
4273     case ARM::VLD1DUPq8wb_fixed:
4274     case ARM::VLD1DUPq16wb_fixed:
4275     case ARM::VLD1DUPq32wb_fixed:
4276     case ARM::VLD1DUPq8wb_register:
4277     case ARM::VLD1DUPq16wb_register:
4278     case ARM::VLD1DUPq32wb_register:
4279     case ARM::VLD2DUPd8:
4280     case ARM::VLD2DUPd16:
4281     case ARM::VLD2DUPd32:
4282     case ARM::VLD2DUPd8wb_fixed:
4283     case ARM::VLD2DUPd16wb_fixed:
4284     case ARM::VLD2DUPd32wb_fixed:
4285     case ARM::VLD2DUPd8wb_register:
4286     case ARM::VLD2DUPd16wb_register:
4287     case ARM::VLD2DUPd32wb_register:
4288     case ARM::VLD4DUPd8:
4289     case ARM::VLD4DUPd16:
4290     case ARM::VLD4DUPd32:
4291     case ARM::VLD4DUPd8_UPD:
4292     case ARM::VLD4DUPd16_UPD:
4293     case ARM::VLD4DUPd32_UPD:
4294     case ARM::VLD1LNd8:
4295     case ARM::VLD1LNd16:
4296     case ARM::VLD1LNd32:
4297     case ARM::VLD1LNd8_UPD:
4298     case ARM::VLD1LNd16_UPD:
4299     case ARM::VLD1LNd32_UPD:
4300     case ARM::VLD2LNd8:
4301     case ARM::VLD2LNd16:
4302     case ARM::VLD2LNd32:
4303     case ARM::VLD2LNq16:
4304     case ARM::VLD2LNq32:
4305     case ARM::VLD2LNd8_UPD:
4306     case ARM::VLD2LNd16_UPD:
4307     case ARM::VLD2LNd32_UPD:
4308     case ARM::VLD2LNq16_UPD:
4309     case ARM::VLD2LNq32_UPD:
4310     case ARM::VLD4LNd8:
4311     case ARM::VLD4LNd16:
4312     case ARM::VLD4LNd32:
4313     case ARM::VLD4LNq16:
4314     case ARM::VLD4LNq32:
4315     case ARM::VLD4LNd8_UPD:
4316     case ARM::VLD4LNd16_UPD:
4317     case ARM::VLD4LNd32_UPD:
4318     case ARM::VLD4LNq16_UPD:
4319     case ARM::VLD4LNq32_UPD:
4320       // If the address is not 64-bit aligned, the latencies of these
4321       // instructions increases by one.
4322       ++Adjust;
4323       break;
4324     }
4325   }
4326   return Adjust;
4327 }
4328 
4329 int ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
4330                                         const MachineInstr &DefMI,
4331                                         unsigned DefIdx,
4332                                         const MachineInstr &UseMI,
4333                                         unsigned UseIdx) const {
4334   // No operand latency. The caller may fall back to getInstrLatency.
4335   if (!ItinData || ItinData->isEmpty())
4336     return -1;
4337 
4338   const MachineOperand &DefMO = DefMI.getOperand(DefIdx);
4339   Register Reg = DefMO.getReg();
4340 
4341   const MachineInstr *ResolvedDefMI = &DefMI;
4342   unsigned DefAdj = 0;
4343   if (DefMI.isBundle())
4344     ResolvedDefMI =
4345         getBundledDefMI(&getRegisterInfo(), &DefMI, Reg, DefIdx, DefAdj);
4346   if (ResolvedDefMI->isCopyLike() || ResolvedDefMI->isInsertSubreg() ||
4347       ResolvedDefMI->isRegSequence() || ResolvedDefMI->isImplicitDef()) {
4348     return 1;
4349   }
4350 
4351   const MachineInstr *ResolvedUseMI = &UseMI;
4352   unsigned UseAdj = 0;
4353   if (UseMI.isBundle()) {
4354     ResolvedUseMI =
4355         getBundledUseMI(&getRegisterInfo(), UseMI, Reg, UseIdx, UseAdj);
4356     if (!ResolvedUseMI)
4357       return -1;
4358   }
4359 
4360   return getOperandLatencyImpl(
4361       ItinData, *ResolvedDefMI, DefIdx, ResolvedDefMI->getDesc(), DefAdj, DefMO,
4362       Reg, *ResolvedUseMI, UseIdx, ResolvedUseMI->getDesc(), UseAdj);
4363 }
4364 
4365 int ARMBaseInstrInfo::getOperandLatencyImpl(
4366     const InstrItineraryData *ItinData, const MachineInstr &DefMI,
4367     unsigned DefIdx, const MCInstrDesc &DefMCID, unsigned DefAdj,
4368     const MachineOperand &DefMO, unsigned Reg, const MachineInstr &UseMI,
4369     unsigned UseIdx, const MCInstrDesc &UseMCID, unsigned UseAdj) const {
4370   if (Reg == ARM::CPSR) {
4371     if (DefMI.getOpcode() == ARM::FMSTAT) {
4372       // fpscr -> cpsr stalls over 20 cycles on A8 (and earlier?)
4373       return Subtarget.isLikeA9() ? 1 : 20;
4374     }
4375 
4376     // CPSR set and branch can be paired in the same cycle.
4377     if (UseMI.isBranch())
4378       return 0;
4379 
4380     // Otherwise it takes the instruction latency (generally one).
4381     unsigned Latency = getInstrLatency(ItinData, DefMI);
4382 
4383     // For Thumb2 and -Os, prefer scheduling CPSR setting instruction close to
4384     // its uses. Instructions which are otherwise scheduled between them may
4385     // incur a code size penalty (not able to use the CPSR setting 16-bit
4386     // instructions).
4387     if (Latency > 0 && Subtarget.isThumb2()) {
4388       const MachineFunction *MF = DefMI.getParent()->getParent();
4389       // FIXME: Use Function::hasOptSize().
4390       if (MF->getFunction().hasFnAttribute(Attribute::OptimizeForSize))
4391         --Latency;
4392     }
4393     return Latency;
4394   }
4395 
4396   if (DefMO.isImplicit() || UseMI.getOperand(UseIdx).isImplicit())
4397     return -1;
4398 
4399   unsigned DefAlign = DefMI.hasOneMemOperand()
4400                           ? (*DefMI.memoperands_begin())->getAlign().value()
4401                           : 0;
4402   unsigned UseAlign = UseMI.hasOneMemOperand()
4403                           ? (*UseMI.memoperands_begin())->getAlign().value()
4404                           : 0;
4405 
4406   // Get the itinerary's latency if possible, and handle variable_ops.
4407   int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign, UseMCID,
4408                                   UseIdx, UseAlign);
4409   // Unable to find operand latency. The caller may resort to getInstrLatency.
4410   if (Latency < 0)
4411     return Latency;
4412 
4413   // Adjust for IT block position.
4414   int Adj = DefAdj + UseAdj;
4415 
4416   // Adjust for dynamic def-side opcode variants not captured by the itinerary.
4417   Adj += adjustDefLatency(Subtarget, DefMI, DefMCID, DefAlign);
4418   if (Adj >= 0 || (int)Latency > -Adj) {
4419     return Latency + Adj;
4420   }
4421   // Return the itinerary latency, which may be zero but not less than zero.
4422   return Latency;
4423 }
4424 
4425 int
4426 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
4427                                     SDNode *DefNode, unsigned DefIdx,
4428                                     SDNode *UseNode, unsigned UseIdx) const {
4429   if (!DefNode->isMachineOpcode())
4430     return 1;
4431 
4432   const MCInstrDesc &DefMCID = get(DefNode->getMachineOpcode());
4433 
4434   if (isZeroCost(DefMCID.Opcode))
4435     return 0;
4436 
4437   if (!ItinData || ItinData->isEmpty())
4438     return DefMCID.mayLoad() ? 3 : 1;
4439 
4440   if (!UseNode->isMachineOpcode()) {
4441     int Latency = ItinData->getOperandCycle(DefMCID.getSchedClass(), DefIdx);
4442     int Adj = Subtarget.getPreISelOperandLatencyAdjustment();
4443     int Threshold = 1 + Adj;
4444     return Latency <= Threshold ? 1 : Latency - Adj;
4445   }
4446 
4447   const MCInstrDesc &UseMCID = get(UseNode->getMachineOpcode());
4448   auto *DefMN = cast<MachineSDNode>(DefNode);
4449   unsigned DefAlign = !DefMN->memoperands_empty()
4450                           ? (*DefMN->memoperands_begin())->getAlign().value()
4451                           : 0;
4452   auto *UseMN = cast<MachineSDNode>(UseNode);
4453   unsigned UseAlign = !UseMN->memoperands_empty()
4454                           ? (*UseMN->memoperands_begin())->getAlign().value()
4455                           : 0;
4456   int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign,
4457                                   UseMCID, UseIdx, UseAlign);
4458 
4459   if (Latency > 1 &&
4460       (Subtarget.isCortexA8() || Subtarget.isLikeA9() ||
4461        Subtarget.isCortexA7())) {
4462     // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
4463     // variants are one cycle cheaper.
4464     switch (DefMCID.getOpcode()) {
4465     default: break;
4466     case ARM::LDRrs:
4467     case ARM::LDRBrs: {
4468       unsigned ShOpVal =
4469         cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
4470       unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
4471       if (ShImm == 0 ||
4472           (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
4473         --Latency;
4474       break;
4475     }
4476     case ARM::t2LDRs:
4477     case ARM::t2LDRBs:
4478     case ARM::t2LDRHs:
4479     case ARM::t2LDRSHs: {
4480       // Thumb2 mode: lsl only.
4481       unsigned ShAmt =
4482         cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
4483       if (ShAmt == 0 || ShAmt == 2)
4484         --Latency;
4485       break;
4486     }
4487     }
4488   } else if (DefIdx == 0 && Latency > 2 && Subtarget.isSwift()) {
4489     // FIXME: Properly handle all of the latency adjustments for address
4490     // writeback.
4491     switch (DefMCID.getOpcode()) {
4492     default: break;
4493     case ARM::LDRrs:
4494     case ARM::LDRBrs: {
4495       unsigned ShOpVal =
4496         cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
4497       unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
4498       if (ShImm == 0 ||
4499           ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
4500            ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
4501         Latency -= 2;
4502       else if (ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr)
4503         --Latency;
4504       break;
4505     }
4506     case ARM::t2LDRs:
4507     case ARM::t2LDRBs:
4508     case ARM::t2LDRHs:
4509     case ARM::t2LDRSHs:
4510       // Thumb2 mode: lsl 0-3 only.
4511       Latency -= 2;
4512       break;
4513     }
4514   }
4515 
4516   if (DefAlign < 8 && Subtarget.checkVLDnAccessAlignment())
4517     switch (DefMCID.getOpcode()) {
4518     default: break;
4519     case ARM::VLD1q8:
4520     case ARM::VLD1q16:
4521     case ARM::VLD1q32:
4522     case ARM::VLD1q64:
4523     case ARM::VLD1q8wb_register:
4524     case ARM::VLD1q16wb_register:
4525     case ARM::VLD1q32wb_register:
4526     case ARM::VLD1q64wb_register:
4527     case ARM::VLD1q8wb_fixed:
4528     case ARM::VLD1q16wb_fixed:
4529     case ARM::VLD1q32wb_fixed:
4530     case ARM::VLD1q64wb_fixed:
4531     case ARM::VLD2d8:
4532     case ARM::VLD2d16:
4533     case ARM::VLD2d32:
4534     case ARM::VLD2q8Pseudo:
4535     case ARM::VLD2q16Pseudo:
4536     case ARM::VLD2q32Pseudo:
4537     case ARM::VLD2d8wb_fixed:
4538     case ARM::VLD2d16wb_fixed:
4539     case ARM::VLD2d32wb_fixed:
4540     case ARM::VLD2q8PseudoWB_fixed:
4541     case ARM::VLD2q16PseudoWB_fixed:
4542     case ARM::VLD2q32PseudoWB_fixed:
4543     case ARM::VLD2d8wb_register:
4544     case ARM::VLD2d16wb_register:
4545     case ARM::VLD2d32wb_register:
4546     case ARM::VLD2q8PseudoWB_register:
4547     case ARM::VLD2q16PseudoWB_register:
4548     case ARM::VLD2q32PseudoWB_register:
4549     case ARM::VLD3d8Pseudo:
4550     case ARM::VLD3d16Pseudo:
4551     case ARM::VLD3d32Pseudo:
4552     case ARM::VLD1d8TPseudo:
4553     case ARM::VLD1d16TPseudo:
4554     case ARM::VLD1d32TPseudo:
4555     case ARM::VLD1d64TPseudo:
4556     case ARM::VLD1d64TPseudoWB_fixed:
4557     case ARM::VLD1d64TPseudoWB_register:
4558     case ARM::VLD3d8Pseudo_UPD:
4559     case ARM::VLD3d16Pseudo_UPD:
4560     case ARM::VLD3d32Pseudo_UPD:
4561     case ARM::VLD3q8Pseudo_UPD:
4562     case ARM::VLD3q16Pseudo_UPD:
4563     case ARM::VLD3q32Pseudo_UPD:
4564     case ARM::VLD3q8oddPseudo:
4565     case ARM::VLD3q16oddPseudo:
4566     case ARM::VLD3q32oddPseudo:
4567     case ARM::VLD3q8oddPseudo_UPD:
4568     case ARM::VLD3q16oddPseudo_UPD:
4569     case ARM::VLD3q32oddPseudo_UPD:
4570     case ARM::VLD4d8Pseudo:
4571     case ARM::VLD4d16Pseudo:
4572     case ARM::VLD4d32Pseudo:
4573     case ARM::VLD1d8QPseudo:
4574     case ARM::VLD1d16QPseudo:
4575     case ARM::VLD1d32QPseudo:
4576     case ARM::VLD1d64QPseudo:
4577     case ARM::VLD1d64QPseudoWB_fixed:
4578     case ARM::VLD1d64QPseudoWB_register:
4579     case ARM::VLD1q8HighQPseudo:
4580     case ARM::VLD1q8LowQPseudo_UPD:
4581     case ARM::VLD1q8HighTPseudo:
4582     case ARM::VLD1q8LowTPseudo_UPD:
4583     case ARM::VLD1q16HighQPseudo:
4584     case ARM::VLD1q16LowQPseudo_UPD:
4585     case ARM::VLD1q16HighTPseudo:
4586     case ARM::VLD1q16LowTPseudo_UPD:
4587     case ARM::VLD1q32HighQPseudo:
4588     case ARM::VLD1q32LowQPseudo_UPD:
4589     case ARM::VLD1q32HighTPseudo:
4590     case ARM::VLD1q32LowTPseudo_UPD:
4591     case ARM::VLD1q64HighQPseudo:
4592     case ARM::VLD1q64LowQPseudo_UPD:
4593     case ARM::VLD1q64HighTPseudo:
4594     case ARM::VLD1q64LowTPseudo_UPD:
4595     case ARM::VLD4d8Pseudo_UPD:
4596     case ARM::VLD4d16Pseudo_UPD:
4597     case ARM::VLD4d32Pseudo_UPD:
4598     case ARM::VLD4q8Pseudo_UPD:
4599     case ARM::VLD4q16Pseudo_UPD:
4600     case ARM::VLD4q32Pseudo_UPD:
4601     case ARM::VLD4q8oddPseudo:
4602     case ARM::VLD4q16oddPseudo:
4603     case ARM::VLD4q32oddPseudo:
4604     case ARM::VLD4q8oddPseudo_UPD:
4605     case ARM::VLD4q16oddPseudo_UPD:
4606     case ARM::VLD4q32oddPseudo_UPD:
4607     case ARM::VLD1DUPq8:
4608     case ARM::VLD1DUPq16:
4609     case ARM::VLD1DUPq32:
4610     case ARM::VLD1DUPq8wb_fixed:
4611     case ARM::VLD1DUPq16wb_fixed:
4612     case ARM::VLD1DUPq32wb_fixed:
4613     case ARM::VLD1DUPq8wb_register:
4614     case ARM::VLD1DUPq16wb_register:
4615     case ARM::VLD1DUPq32wb_register:
4616     case ARM::VLD2DUPd8:
4617     case ARM::VLD2DUPd16:
4618     case ARM::VLD2DUPd32:
4619     case ARM::VLD2DUPd8wb_fixed:
4620     case ARM::VLD2DUPd16wb_fixed:
4621     case ARM::VLD2DUPd32wb_fixed:
4622     case ARM::VLD2DUPd8wb_register:
4623     case ARM::VLD2DUPd16wb_register:
4624     case ARM::VLD2DUPd32wb_register:
4625     case ARM::VLD2DUPq8EvenPseudo:
4626     case ARM::VLD2DUPq8OddPseudo:
4627     case ARM::VLD2DUPq16EvenPseudo:
4628     case ARM::VLD2DUPq16OddPseudo:
4629     case ARM::VLD2DUPq32EvenPseudo:
4630     case ARM::VLD2DUPq32OddPseudo:
4631     case ARM::VLD3DUPq8EvenPseudo:
4632     case ARM::VLD3DUPq8OddPseudo:
4633     case ARM::VLD3DUPq16EvenPseudo:
4634     case ARM::VLD3DUPq16OddPseudo:
4635     case ARM::VLD3DUPq32EvenPseudo:
4636     case ARM::VLD3DUPq32OddPseudo:
4637     case ARM::VLD4DUPd8Pseudo:
4638     case ARM::VLD4DUPd16Pseudo:
4639     case ARM::VLD4DUPd32Pseudo:
4640     case ARM::VLD4DUPd8Pseudo_UPD:
4641     case ARM::VLD4DUPd16Pseudo_UPD:
4642     case ARM::VLD4DUPd32Pseudo_UPD:
4643     case ARM::VLD4DUPq8EvenPseudo:
4644     case ARM::VLD4DUPq8OddPseudo:
4645     case ARM::VLD4DUPq16EvenPseudo:
4646     case ARM::VLD4DUPq16OddPseudo:
4647     case ARM::VLD4DUPq32EvenPseudo:
4648     case ARM::VLD4DUPq32OddPseudo:
4649     case ARM::VLD1LNq8Pseudo:
4650     case ARM::VLD1LNq16Pseudo:
4651     case ARM::VLD1LNq32Pseudo:
4652     case ARM::VLD1LNq8Pseudo_UPD:
4653     case ARM::VLD1LNq16Pseudo_UPD:
4654     case ARM::VLD1LNq32Pseudo_UPD:
4655     case ARM::VLD2LNd8Pseudo:
4656     case ARM::VLD2LNd16Pseudo:
4657     case ARM::VLD2LNd32Pseudo:
4658     case ARM::VLD2LNq16Pseudo:
4659     case ARM::VLD2LNq32Pseudo:
4660     case ARM::VLD2LNd8Pseudo_UPD:
4661     case ARM::VLD2LNd16Pseudo_UPD:
4662     case ARM::VLD2LNd32Pseudo_UPD:
4663     case ARM::VLD2LNq16Pseudo_UPD:
4664     case ARM::VLD2LNq32Pseudo_UPD:
4665     case ARM::VLD4LNd8Pseudo:
4666     case ARM::VLD4LNd16Pseudo:
4667     case ARM::VLD4LNd32Pseudo:
4668     case ARM::VLD4LNq16Pseudo:
4669     case ARM::VLD4LNq32Pseudo:
4670     case ARM::VLD4LNd8Pseudo_UPD:
4671     case ARM::VLD4LNd16Pseudo_UPD:
4672     case ARM::VLD4LNd32Pseudo_UPD:
4673     case ARM::VLD4LNq16Pseudo_UPD:
4674     case ARM::VLD4LNq32Pseudo_UPD:
4675       // If the address is not 64-bit aligned, the latencies of these
4676       // instructions increases by one.
4677       ++Latency;
4678       break;
4679     }
4680 
4681   return Latency;
4682 }
4683 
4684 unsigned ARMBaseInstrInfo::getPredicationCost(const MachineInstr &MI) const {
4685   if (MI.isCopyLike() || MI.isInsertSubreg() || MI.isRegSequence() ||
4686       MI.isImplicitDef())
4687     return 0;
4688 
4689   if (MI.isBundle())
4690     return 0;
4691 
4692   const MCInstrDesc &MCID = MI.getDesc();
4693 
4694   if (MCID.isCall() || (MCID.hasImplicitDefOfPhysReg(ARM::CPSR) &&
4695                         !Subtarget.cheapPredicableCPSRDef())) {
4696     // When predicated, CPSR is an additional source operand for CPSR updating
4697     // instructions, this apparently increases their latencies.
4698     return 1;
4699   }
4700   return 0;
4701 }
4702 
4703 unsigned ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
4704                                            const MachineInstr &MI,
4705                                            unsigned *PredCost) const {
4706   if (MI.isCopyLike() || MI.isInsertSubreg() || MI.isRegSequence() ||
4707       MI.isImplicitDef())
4708     return 1;
4709 
4710   // An instruction scheduler typically runs on unbundled instructions, however
4711   // other passes may query the latency of a bundled instruction.
4712   if (MI.isBundle()) {
4713     unsigned Latency = 0;
4714     MachineBasicBlock::const_instr_iterator I = MI.getIterator();
4715     MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
4716     while (++I != E && I->isInsideBundle()) {
4717       if (I->getOpcode() != ARM::t2IT)
4718         Latency += getInstrLatency(ItinData, *I, PredCost);
4719     }
4720     return Latency;
4721   }
4722 
4723   const MCInstrDesc &MCID = MI.getDesc();
4724   if (PredCost && (MCID.isCall() || (MCID.hasImplicitDefOfPhysReg(ARM::CPSR) &&
4725                                      !Subtarget.cheapPredicableCPSRDef()))) {
4726     // When predicated, CPSR is an additional source operand for CPSR updating
4727     // instructions, this apparently increases their latencies.
4728     *PredCost = 1;
4729   }
4730   // Be sure to call getStageLatency for an empty itinerary in case it has a
4731   // valid MinLatency property.
4732   if (!ItinData)
4733     return MI.mayLoad() ? 3 : 1;
4734 
4735   unsigned Class = MCID.getSchedClass();
4736 
4737   // For instructions with variable uops, use uops as latency.
4738   if (!ItinData->isEmpty() && ItinData->getNumMicroOps(Class) < 0)
4739     return getNumMicroOps(ItinData, MI);
4740 
4741   // For the common case, fall back on the itinerary's latency.
4742   unsigned Latency = ItinData->getStageLatency(Class);
4743 
4744   // Adjust for dynamic def-side opcode variants not captured by the itinerary.
4745   unsigned DefAlign =
4746       MI.hasOneMemOperand() ? (*MI.memoperands_begin())->getAlign().value() : 0;
4747   int Adj = adjustDefLatency(Subtarget, MI, MCID, DefAlign);
4748   if (Adj >= 0 || (int)Latency > -Adj) {
4749     return Latency + Adj;
4750   }
4751   return Latency;
4752 }
4753 
4754 int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
4755                                       SDNode *Node) const {
4756   if (!Node->isMachineOpcode())
4757     return 1;
4758 
4759   if (!ItinData || ItinData->isEmpty())
4760     return 1;
4761 
4762   unsigned Opcode = Node->getMachineOpcode();
4763   switch (Opcode) {
4764   default:
4765     return ItinData->getStageLatency(get(Opcode).getSchedClass());
4766   case ARM::VLDMQIA:
4767   case ARM::VSTMQIA:
4768     return 2;
4769   }
4770 }
4771 
4772 bool ARMBaseInstrInfo::hasHighOperandLatency(const TargetSchedModel &SchedModel,
4773                                              const MachineRegisterInfo *MRI,
4774                                              const MachineInstr &DefMI,
4775                                              unsigned DefIdx,
4776                                              const MachineInstr &UseMI,
4777                                              unsigned UseIdx) const {
4778   unsigned DDomain = DefMI.getDesc().TSFlags & ARMII::DomainMask;
4779   unsigned UDomain = UseMI.getDesc().TSFlags & ARMII::DomainMask;
4780   if (Subtarget.nonpipelinedVFP() &&
4781       (DDomain == ARMII::DomainVFP || UDomain == ARMII::DomainVFP))
4782     return true;
4783 
4784   // Hoist VFP / NEON instructions with 4 or higher latency.
4785   unsigned Latency =
4786       SchedModel.computeOperandLatency(&DefMI, DefIdx, &UseMI, UseIdx);
4787   if (Latency <= 3)
4788     return false;
4789   return DDomain == ARMII::DomainVFP || DDomain == ARMII::DomainNEON ||
4790          UDomain == ARMII::DomainVFP || UDomain == ARMII::DomainNEON;
4791 }
4792 
4793 bool ARMBaseInstrInfo::hasLowDefLatency(const TargetSchedModel &SchedModel,
4794                                         const MachineInstr &DefMI,
4795                                         unsigned DefIdx) const {
4796   const InstrItineraryData *ItinData = SchedModel.getInstrItineraries();
4797   if (!ItinData || ItinData->isEmpty())
4798     return false;
4799 
4800   unsigned DDomain = DefMI.getDesc().TSFlags & ARMII::DomainMask;
4801   if (DDomain == ARMII::DomainGeneral) {
4802     unsigned DefClass = DefMI.getDesc().getSchedClass();
4803     int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
4804     return (DefCycle != -1 && DefCycle <= 2);
4805   }
4806   return false;
4807 }
4808 
4809 bool ARMBaseInstrInfo::verifyInstruction(const MachineInstr &MI,
4810                                          StringRef &ErrInfo) const {
4811   if (convertAddSubFlagsOpcode(MI.getOpcode())) {
4812     ErrInfo = "Pseudo flag setting opcodes only exist in Selection DAG";
4813     return false;
4814   }
4815   if (MI.getOpcode() == ARM::tMOVr && !Subtarget.hasV6Ops()) {
4816     // Make sure we don't generate a lo-lo mov that isn't supported.
4817     if (!ARM::hGPRRegClass.contains(MI.getOperand(0).getReg()) &&
4818         !ARM::hGPRRegClass.contains(MI.getOperand(1).getReg())) {
4819       ErrInfo = "Non-flag-setting Thumb1 mov is v6-only";
4820       return false;
4821     }
4822   }
4823   if (MI.getOpcode() == ARM::tPUSH ||
4824       MI.getOpcode() == ARM::tPOP ||
4825       MI.getOpcode() == ARM::tPOP_RET) {
4826     for (int i = 2, e = MI.getNumOperands(); i < e; ++i) {
4827       if (MI.getOperand(i).isImplicit() ||
4828           !MI.getOperand(i).isReg())
4829         continue;
4830       Register Reg = MI.getOperand(i).getReg();
4831       if (Reg < ARM::R0 || Reg > ARM::R7) {
4832         if (!(MI.getOpcode() == ARM::tPUSH && Reg == ARM::LR) &&
4833             !(MI.getOpcode() == ARM::tPOP_RET && Reg == ARM::PC)) {
4834           ErrInfo = "Unsupported register in Thumb1 push/pop";
4835           return false;
4836         }
4837       }
4838     }
4839   }
4840   if (MI.getOpcode() == ARM::MVE_VMOV_q_rr) {
4841     assert(MI.getOperand(4).isImm() && MI.getOperand(5).isImm());
4842     if ((MI.getOperand(4).getImm() != 2 && MI.getOperand(4).getImm() != 3) ||
4843         MI.getOperand(4).getImm() != MI.getOperand(5).getImm() + 2) {
4844       ErrInfo = "Incorrect array index for MVE_VMOV_q_rr";
4845       return false;
4846     }
4847   }
4848   return true;
4849 }
4850 
4851 // LoadStackGuard has so far only been implemented for MachO. Different code
4852 // sequence is needed for other targets.
4853 void ARMBaseInstrInfo::expandLoadStackGuardBase(MachineBasicBlock::iterator MI,
4854                                                 unsigned LoadImmOpc,
4855                                                 unsigned LoadOpc) const {
4856   assert(!Subtarget.isROPI() && !Subtarget.isRWPI() &&
4857          "ROPI/RWPI not currently supported with stack guard");
4858 
4859   MachineBasicBlock &MBB = *MI->getParent();
4860   DebugLoc DL = MI->getDebugLoc();
4861   Register Reg = MI->getOperand(0).getReg();
4862   const GlobalValue *GV =
4863       cast<GlobalValue>((*MI->memoperands_begin())->getValue());
4864   MachineInstrBuilder MIB;
4865 
4866   BuildMI(MBB, MI, DL, get(LoadImmOpc), Reg)
4867       .addGlobalAddress(GV, 0, ARMII::MO_NONLAZY);
4868 
4869   if (Subtarget.isGVIndirectSymbol(GV)) {
4870     MIB = BuildMI(MBB, MI, DL, get(LoadOpc), Reg);
4871     MIB.addReg(Reg, RegState::Kill).addImm(0);
4872     auto Flags = MachineMemOperand::MOLoad |
4873                  MachineMemOperand::MODereferenceable |
4874                  MachineMemOperand::MOInvariant;
4875     MachineMemOperand *MMO = MBB.getParent()->getMachineMemOperand(
4876         MachinePointerInfo::getGOT(*MBB.getParent()), Flags, 4, Align(4));
4877     MIB.addMemOperand(MMO).add(predOps(ARMCC::AL));
4878   }
4879 
4880   MIB = BuildMI(MBB, MI, DL, get(LoadOpc), Reg);
4881   MIB.addReg(Reg, RegState::Kill)
4882       .addImm(0)
4883       .cloneMemRefs(*MI)
4884       .add(predOps(ARMCC::AL));
4885 }
4886 
4887 bool
4888 ARMBaseInstrInfo::isFpMLxInstruction(unsigned Opcode, unsigned &MulOpc,
4889                                      unsigned &AddSubOpc,
4890                                      bool &NegAcc, bool &HasLane) const {
4891   DenseMap<unsigned, unsigned>::const_iterator I = MLxEntryMap.find(Opcode);
4892   if (I == MLxEntryMap.end())
4893     return false;
4894 
4895   const ARM_MLxEntry &Entry = ARM_MLxTable[I->second];
4896   MulOpc = Entry.MulOpc;
4897   AddSubOpc = Entry.AddSubOpc;
4898   NegAcc = Entry.NegAcc;
4899   HasLane = Entry.HasLane;
4900   return true;
4901 }
4902 
4903 //===----------------------------------------------------------------------===//
4904 // Execution domains.
4905 //===----------------------------------------------------------------------===//
4906 //
4907 // Some instructions go down the NEON pipeline, some go down the VFP pipeline,
4908 // and some can go down both.  The vmov instructions go down the VFP pipeline,
4909 // but they can be changed to vorr equivalents that are executed by the NEON
4910 // pipeline.
4911 //
4912 // We use the following execution domain numbering:
4913 //
4914 enum ARMExeDomain {
4915   ExeGeneric = 0,
4916   ExeVFP = 1,
4917   ExeNEON = 2
4918 };
4919 
4920 //
4921 // Also see ARMInstrFormats.td and Domain* enums in ARMBaseInfo.h
4922 //
4923 std::pair<uint16_t, uint16_t>
4924 ARMBaseInstrInfo::getExecutionDomain(const MachineInstr &MI) const {
4925   // If we don't have access to NEON instructions then we won't be able
4926   // to swizzle anything to the NEON domain. Check to make sure.
4927   if (Subtarget.hasNEON()) {
4928     // VMOVD, VMOVRS and VMOVSR are VFP instructions, but can be changed to NEON
4929     // if they are not predicated.
4930     if (MI.getOpcode() == ARM::VMOVD && !isPredicated(MI))
4931       return std::make_pair(ExeVFP, (1 << ExeVFP) | (1 << ExeNEON));
4932 
4933     // CortexA9 is particularly picky about mixing the two and wants these
4934     // converted.
4935     if (Subtarget.useNEONForFPMovs() && !isPredicated(MI) &&
4936         (MI.getOpcode() == ARM::VMOVRS || MI.getOpcode() == ARM::VMOVSR ||
4937          MI.getOpcode() == ARM::VMOVS))
4938       return std::make_pair(ExeVFP, (1 << ExeVFP) | (1 << ExeNEON));
4939   }
4940   // No other instructions can be swizzled, so just determine their domain.
4941   unsigned Domain = MI.getDesc().TSFlags & ARMII::DomainMask;
4942 
4943   if (Domain & ARMII::DomainNEON)
4944     return std::make_pair(ExeNEON, 0);
4945 
4946   // Certain instructions can go either way on Cortex-A8.
4947   // Treat them as NEON instructions.
4948   if ((Domain & ARMII::DomainNEONA8) && Subtarget.isCortexA8())
4949     return std::make_pair(ExeNEON, 0);
4950 
4951   if (Domain & ARMII::DomainVFP)
4952     return std::make_pair(ExeVFP, 0);
4953 
4954   return std::make_pair(ExeGeneric, 0);
4955 }
4956 
4957 static unsigned getCorrespondingDRegAndLane(const TargetRegisterInfo *TRI,
4958                                             unsigned SReg, unsigned &Lane) {
4959   unsigned DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_0, &ARM::DPRRegClass);
4960   Lane = 0;
4961 
4962   if (DReg != ARM::NoRegister)
4963    return DReg;
4964 
4965   Lane = 1;
4966   DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_1, &ARM::DPRRegClass);
4967 
4968   assert(DReg && "S-register with no D super-register?");
4969   return DReg;
4970 }
4971 
4972 /// getImplicitSPRUseForDPRUse - Given a use of a DPR register and lane,
4973 /// set ImplicitSReg to a register number that must be marked as implicit-use or
4974 /// zero if no register needs to be defined as implicit-use.
4975 ///
4976 /// If the function cannot determine if an SPR should be marked implicit use or
4977 /// not, it returns false.
4978 ///
4979 /// This function handles cases where an instruction is being modified from taking
4980 /// an SPR to a DPR[Lane]. A use of the DPR is being added, which may conflict
4981 /// with an earlier def of an SPR corresponding to DPR[Lane^1] (i.e. the other
4982 /// lane of the DPR).
4983 ///
4984 /// If the other SPR is defined, an implicit-use of it should be added. Else,
4985 /// (including the case where the DPR itself is defined), it should not.
4986 ///
4987 static bool getImplicitSPRUseForDPRUse(const TargetRegisterInfo *TRI,
4988                                        MachineInstr &MI, unsigned DReg,
4989                                        unsigned Lane, unsigned &ImplicitSReg) {
4990   // If the DPR is defined or used already, the other SPR lane will be chained
4991   // correctly, so there is nothing to be done.
4992   if (MI.definesRegister(DReg, TRI) || MI.readsRegister(DReg, TRI)) {
4993     ImplicitSReg = 0;
4994     return true;
4995   }
4996 
4997   // Otherwise we need to go searching to see if the SPR is set explicitly.
4998   ImplicitSReg = TRI->getSubReg(DReg,
4999                                 (Lane & 1) ? ARM::ssub_0 : ARM::ssub_1);
5000   MachineBasicBlock::LivenessQueryResult LQR =
5001       MI.getParent()->computeRegisterLiveness(TRI, ImplicitSReg, MI);
5002 
5003   if (LQR == MachineBasicBlock::LQR_Live)
5004     return true;
5005   else if (LQR == MachineBasicBlock::LQR_Unknown)
5006     return false;
5007 
5008   // If the register is known not to be live, there is no need to add an
5009   // implicit-use.
5010   ImplicitSReg = 0;
5011   return true;
5012 }
5013 
5014 void ARMBaseInstrInfo::setExecutionDomain(MachineInstr &MI,
5015                                           unsigned Domain) const {
5016   unsigned DstReg, SrcReg, DReg;
5017   unsigned Lane;
5018   MachineInstrBuilder MIB(*MI.getParent()->getParent(), MI);
5019   const TargetRegisterInfo *TRI = &getRegisterInfo();
5020   switch (MI.getOpcode()) {
5021   default:
5022     llvm_unreachable("cannot handle opcode!");
5023     break;
5024   case ARM::VMOVD:
5025     if (Domain != ExeNEON)
5026       break;
5027 
5028     // Zap the predicate operands.
5029     assert(!isPredicated(MI) && "Cannot predicate a VORRd");
5030 
5031     // Make sure we've got NEON instructions.
5032     assert(Subtarget.hasNEON() && "VORRd requires NEON");
5033 
5034     // Source instruction is %DDst = VMOVD %DSrc, 14, %noreg (; implicits)
5035     DstReg = MI.getOperand(0).getReg();
5036     SrcReg = MI.getOperand(1).getReg();
5037 
5038     for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
5039       MI.RemoveOperand(i - 1);
5040 
5041     // Change to a %DDst = VORRd %DSrc, %DSrc, 14, %noreg (; implicits)
5042     MI.setDesc(get(ARM::VORRd));
5043     MIB.addReg(DstReg, RegState::Define)
5044         .addReg(SrcReg)
5045         .addReg(SrcReg)
5046         .add(predOps(ARMCC::AL));
5047     break;
5048   case ARM::VMOVRS:
5049     if (Domain != ExeNEON)
5050       break;
5051     assert(!isPredicated(MI) && "Cannot predicate a VGETLN");
5052 
5053     // Source instruction is %RDst = VMOVRS %SSrc, 14, %noreg (; implicits)
5054     DstReg = MI.getOperand(0).getReg();
5055     SrcReg = MI.getOperand(1).getReg();
5056 
5057     for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
5058       MI.RemoveOperand(i - 1);
5059 
5060     DReg = getCorrespondingDRegAndLane(TRI, SrcReg, Lane);
5061 
5062     // Convert to %RDst = VGETLNi32 %DSrc, Lane, 14, %noreg (; imps)
5063     // Note that DSrc has been widened and the other lane may be undef, which
5064     // contaminates the entire register.
5065     MI.setDesc(get(ARM::VGETLNi32));
5066     MIB.addReg(DstReg, RegState::Define)
5067         .addReg(DReg, RegState::Undef)
5068         .addImm(Lane)
5069         .add(predOps(ARMCC::AL));
5070 
5071     // The old source should be an implicit use, otherwise we might think it
5072     // was dead before here.
5073     MIB.addReg(SrcReg, RegState::Implicit);
5074     break;
5075   case ARM::VMOVSR: {
5076     if (Domain != ExeNEON)
5077       break;
5078     assert(!isPredicated(MI) && "Cannot predicate a VSETLN");
5079 
5080     // Source instruction is %SDst = VMOVSR %RSrc, 14, %noreg (; implicits)
5081     DstReg = MI.getOperand(0).getReg();
5082     SrcReg = MI.getOperand(1).getReg();
5083 
5084     DReg = getCorrespondingDRegAndLane(TRI, DstReg, Lane);
5085 
5086     unsigned ImplicitSReg;
5087     if (!getImplicitSPRUseForDPRUse(TRI, MI, DReg, Lane, ImplicitSReg))
5088       break;
5089 
5090     for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
5091       MI.RemoveOperand(i - 1);
5092 
5093     // Convert to %DDst = VSETLNi32 %DDst, %RSrc, Lane, 14, %noreg (; imps)
5094     // Again DDst may be undefined at the beginning of this instruction.
5095     MI.setDesc(get(ARM::VSETLNi32));
5096     MIB.addReg(DReg, RegState::Define)
5097         .addReg(DReg, getUndefRegState(!MI.readsRegister(DReg, TRI)))
5098         .addReg(SrcReg)
5099         .addImm(Lane)
5100         .add(predOps(ARMCC::AL));
5101 
5102     // The narrower destination must be marked as set to keep previous chains
5103     // in place.
5104     MIB.addReg(DstReg, RegState::Define | RegState::Implicit);
5105     if (ImplicitSReg != 0)
5106       MIB.addReg(ImplicitSReg, RegState::Implicit);
5107     break;
5108     }
5109     case ARM::VMOVS: {
5110       if (Domain != ExeNEON)
5111         break;
5112 
5113       // Source instruction is %SDst = VMOVS %SSrc, 14, %noreg (; implicits)
5114       DstReg = MI.getOperand(0).getReg();
5115       SrcReg = MI.getOperand(1).getReg();
5116 
5117       unsigned DstLane = 0, SrcLane = 0, DDst, DSrc;
5118       DDst = getCorrespondingDRegAndLane(TRI, DstReg, DstLane);
5119       DSrc = getCorrespondingDRegAndLane(TRI, SrcReg, SrcLane);
5120 
5121       unsigned ImplicitSReg;
5122       if (!getImplicitSPRUseForDPRUse(TRI, MI, DSrc, SrcLane, ImplicitSReg))
5123         break;
5124 
5125       for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
5126         MI.RemoveOperand(i - 1);
5127 
5128       if (DSrc == DDst) {
5129         // Destination can be:
5130         //     %DDst = VDUPLN32d %DDst, Lane, 14, %noreg (; implicits)
5131         MI.setDesc(get(ARM::VDUPLN32d));
5132         MIB.addReg(DDst, RegState::Define)
5133             .addReg(DDst, getUndefRegState(!MI.readsRegister(DDst, TRI)))
5134             .addImm(SrcLane)
5135             .add(predOps(ARMCC::AL));
5136 
5137         // Neither the source or the destination are naturally represented any
5138         // more, so add them in manually.
5139         MIB.addReg(DstReg, RegState::Implicit | RegState::Define);
5140         MIB.addReg(SrcReg, RegState::Implicit);
5141         if (ImplicitSReg != 0)
5142           MIB.addReg(ImplicitSReg, RegState::Implicit);
5143         break;
5144       }
5145 
5146       // In general there's no single instruction that can perform an S <-> S
5147       // move in NEON space, but a pair of VEXT instructions *can* do the
5148       // job. It turns out that the VEXTs needed will only use DSrc once, with
5149       // the position based purely on the combination of lane-0 and lane-1
5150       // involved. For example
5151       //     vmov s0, s2 -> vext.32 d0, d0, d1, #1  vext.32 d0, d0, d0, #1
5152       //     vmov s1, s3 -> vext.32 d0, d1, d0, #1  vext.32 d0, d0, d0, #1
5153       //     vmov s0, s3 -> vext.32 d0, d0, d0, #1  vext.32 d0, d1, d0, #1
5154       //     vmov s1, s2 -> vext.32 d0, d0, d0, #1  vext.32 d0, d0, d1, #1
5155       //
5156       // Pattern of the MachineInstrs is:
5157       //     %DDst = VEXTd32 %DSrc1, %DSrc2, Lane, 14, %noreg (;implicits)
5158       MachineInstrBuilder NewMIB;
5159       NewMIB = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(ARM::VEXTd32),
5160                        DDst);
5161 
5162       // On the first instruction, both DSrc and DDst may be undef if present.
5163       // Specifically when the original instruction didn't have them as an
5164       // <imp-use>.
5165       unsigned CurReg = SrcLane == 1 && DstLane == 1 ? DSrc : DDst;
5166       bool CurUndef = !MI.readsRegister(CurReg, TRI);
5167       NewMIB.addReg(CurReg, getUndefRegState(CurUndef));
5168 
5169       CurReg = SrcLane == 0 && DstLane == 0 ? DSrc : DDst;
5170       CurUndef = !MI.readsRegister(CurReg, TRI);
5171       NewMIB.addReg(CurReg, getUndefRegState(CurUndef))
5172             .addImm(1)
5173             .add(predOps(ARMCC::AL));
5174 
5175       if (SrcLane == DstLane)
5176         NewMIB.addReg(SrcReg, RegState::Implicit);
5177 
5178       MI.setDesc(get(ARM::VEXTd32));
5179       MIB.addReg(DDst, RegState::Define);
5180 
5181       // On the second instruction, DDst has definitely been defined above, so
5182       // it is not undef. DSrc, if present, can be undef as above.
5183       CurReg = SrcLane == 1 && DstLane == 0 ? DSrc : DDst;
5184       CurUndef = CurReg == DSrc && !MI.readsRegister(CurReg, TRI);
5185       MIB.addReg(CurReg, getUndefRegState(CurUndef));
5186 
5187       CurReg = SrcLane == 0 && DstLane == 1 ? DSrc : DDst;
5188       CurUndef = CurReg == DSrc && !MI.readsRegister(CurReg, TRI);
5189       MIB.addReg(CurReg, getUndefRegState(CurUndef))
5190          .addImm(1)
5191          .add(predOps(ARMCC::AL));
5192 
5193       if (SrcLane != DstLane)
5194         MIB.addReg(SrcReg, RegState::Implicit);
5195 
5196       // As before, the original destination is no longer represented, add it
5197       // implicitly.
5198       MIB.addReg(DstReg, RegState::Define | RegState::Implicit);
5199       if (ImplicitSReg != 0)
5200         MIB.addReg(ImplicitSReg, RegState::Implicit);
5201       break;
5202     }
5203   }
5204 }
5205 
5206 //===----------------------------------------------------------------------===//
5207 // Partial register updates
5208 //===----------------------------------------------------------------------===//
5209 //
5210 // Swift renames NEON registers with 64-bit granularity.  That means any
5211 // instruction writing an S-reg implicitly reads the containing D-reg.  The
5212 // problem is mostly avoided by translating f32 operations to v2f32 operations
5213 // on D-registers, but f32 loads are still a problem.
5214 //
5215 // These instructions can load an f32 into a NEON register:
5216 //
5217 // VLDRS - Only writes S, partial D update.
5218 // VLD1LNd32 - Writes all D-regs, explicit partial D update, 2 uops.
5219 // VLD1DUPd32 - Writes all D-regs, no partial reg update, 2 uops.
5220 //
5221 // FCONSTD can be used as a dependency-breaking instruction.
5222 unsigned ARMBaseInstrInfo::getPartialRegUpdateClearance(
5223     const MachineInstr &MI, unsigned OpNum,
5224     const TargetRegisterInfo *TRI) const {
5225   auto PartialUpdateClearance = Subtarget.getPartialUpdateClearance();
5226   if (!PartialUpdateClearance)
5227     return 0;
5228 
5229   assert(TRI && "Need TRI instance");
5230 
5231   const MachineOperand &MO = MI.getOperand(OpNum);
5232   if (MO.readsReg())
5233     return 0;
5234   Register Reg = MO.getReg();
5235   int UseOp = -1;
5236 
5237   switch (MI.getOpcode()) {
5238   // Normal instructions writing only an S-register.
5239   case ARM::VLDRS:
5240   case ARM::FCONSTS:
5241   case ARM::VMOVSR:
5242   case ARM::VMOVv8i8:
5243   case ARM::VMOVv4i16:
5244   case ARM::VMOVv2i32:
5245   case ARM::VMOVv2f32:
5246   case ARM::VMOVv1i64:
5247     UseOp = MI.findRegisterUseOperandIdx(Reg, false, TRI);
5248     break;
5249 
5250     // Explicitly reads the dependency.
5251   case ARM::VLD1LNd32:
5252     UseOp = 3;
5253     break;
5254   default:
5255     return 0;
5256   }
5257 
5258   // If this instruction actually reads a value from Reg, there is no unwanted
5259   // dependency.
5260   if (UseOp != -1 && MI.getOperand(UseOp).readsReg())
5261     return 0;
5262 
5263   // We must be able to clobber the whole D-reg.
5264   if (Register::isVirtualRegister(Reg)) {
5265     // Virtual register must be a def undef foo:ssub_0 operand.
5266     if (!MO.getSubReg() || MI.readsVirtualRegister(Reg))
5267       return 0;
5268   } else if (ARM::SPRRegClass.contains(Reg)) {
5269     // Physical register: MI must define the full D-reg.
5270     unsigned DReg = TRI->getMatchingSuperReg(Reg, ARM::ssub_0,
5271                                              &ARM::DPRRegClass);
5272     if (!DReg || !MI.definesRegister(DReg, TRI))
5273       return 0;
5274   }
5275 
5276   // MI has an unwanted D-register dependency.
5277   // Avoid defs in the previous N instructrions.
5278   return PartialUpdateClearance;
5279 }
5280 
5281 // Break a partial register dependency after getPartialRegUpdateClearance
5282 // returned non-zero.
5283 void ARMBaseInstrInfo::breakPartialRegDependency(
5284     MachineInstr &MI, unsigned OpNum, const TargetRegisterInfo *TRI) const {
5285   assert(OpNum < MI.getDesc().getNumDefs() && "OpNum is not a def");
5286   assert(TRI && "Need TRI instance");
5287 
5288   const MachineOperand &MO = MI.getOperand(OpNum);
5289   Register Reg = MO.getReg();
5290   assert(Register::isPhysicalRegister(Reg) &&
5291          "Can't break virtual register dependencies.");
5292   unsigned DReg = Reg;
5293 
5294   // If MI defines an S-reg, find the corresponding D super-register.
5295   if (ARM::SPRRegClass.contains(Reg)) {
5296     DReg = ARM::D0 + (Reg - ARM::S0) / 2;
5297     assert(TRI->isSuperRegister(Reg, DReg) && "Register enums broken");
5298   }
5299 
5300   assert(ARM::DPRRegClass.contains(DReg) && "Can only break D-reg deps");
5301   assert(MI.definesRegister(DReg, TRI) && "MI doesn't clobber full D-reg");
5302 
5303   // FIXME: In some cases, VLDRS can be changed to a VLD1DUPd32 which defines
5304   // the full D-register by loading the same value to both lanes.  The
5305   // instruction is micro-coded with 2 uops, so don't do this until we can
5306   // properly schedule micro-coded instructions.  The dispatcher stalls cause
5307   // too big regressions.
5308 
5309   // Insert the dependency-breaking FCONSTD before MI.
5310   // 96 is the encoding of 0.5, but the actual value doesn't matter here.
5311   BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(ARM::FCONSTD), DReg)
5312       .addImm(96)
5313       .add(predOps(ARMCC::AL));
5314   MI.addRegisterKilled(DReg, TRI, true);
5315 }
5316 
5317 bool ARMBaseInstrInfo::hasNOP() const {
5318   return Subtarget.getFeatureBits()[ARM::HasV6KOps];
5319 }
5320 
5321 bool ARMBaseInstrInfo::isSwiftFastImmShift(const MachineInstr *MI) const {
5322   if (MI->getNumOperands() < 4)
5323     return true;
5324   unsigned ShOpVal = MI->getOperand(3).getImm();
5325   unsigned ShImm = ARM_AM::getSORegOffset(ShOpVal);
5326   // Swift supports faster shifts for: lsl 2, lsl 1, and lsr 1.
5327   if ((ShImm == 1 && ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsr) ||
5328       ((ShImm == 1 || ShImm == 2) &&
5329        ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsl))
5330     return true;
5331 
5332   return false;
5333 }
5334 
5335 bool ARMBaseInstrInfo::getRegSequenceLikeInputs(
5336     const MachineInstr &MI, unsigned DefIdx,
5337     SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
5338   assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index");
5339   assert(MI.isRegSequenceLike() && "Invalid kind of instruction");
5340 
5341   switch (MI.getOpcode()) {
5342   case ARM::VMOVDRR:
5343     // dX = VMOVDRR rY, rZ
5344     // is the same as:
5345     // dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1
5346     // Populate the InputRegs accordingly.
5347     // rY
5348     const MachineOperand *MOReg = &MI.getOperand(1);
5349     if (!MOReg->isUndef())
5350       InputRegs.push_back(RegSubRegPairAndIdx(MOReg->getReg(),
5351                                               MOReg->getSubReg(), ARM::ssub_0));
5352     // rZ
5353     MOReg = &MI.getOperand(2);
5354     if (!MOReg->isUndef())
5355       InputRegs.push_back(RegSubRegPairAndIdx(MOReg->getReg(),
5356                                               MOReg->getSubReg(), ARM::ssub_1));
5357     return true;
5358   }
5359   llvm_unreachable("Target dependent opcode missing");
5360 }
5361 
5362 bool ARMBaseInstrInfo::getExtractSubregLikeInputs(
5363     const MachineInstr &MI, unsigned DefIdx,
5364     RegSubRegPairAndIdx &InputReg) const {
5365   assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index");
5366   assert(MI.isExtractSubregLike() && "Invalid kind of instruction");
5367 
5368   switch (MI.getOpcode()) {
5369   case ARM::VMOVRRD:
5370     // rX, rY = VMOVRRD dZ
5371     // is the same as:
5372     // rX = EXTRACT_SUBREG dZ, ssub_0
5373     // rY = EXTRACT_SUBREG dZ, ssub_1
5374     const MachineOperand &MOReg = MI.getOperand(2);
5375     if (MOReg.isUndef())
5376       return false;
5377     InputReg.Reg = MOReg.getReg();
5378     InputReg.SubReg = MOReg.getSubReg();
5379     InputReg.SubIdx = DefIdx == 0 ? ARM::ssub_0 : ARM::ssub_1;
5380     return true;
5381   }
5382   llvm_unreachable("Target dependent opcode missing");
5383 }
5384 
5385 bool ARMBaseInstrInfo::getInsertSubregLikeInputs(
5386     const MachineInstr &MI, unsigned DefIdx, RegSubRegPair &BaseReg,
5387     RegSubRegPairAndIdx &InsertedReg) const {
5388   assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index");
5389   assert(MI.isInsertSubregLike() && "Invalid kind of instruction");
5390 
5391   switch (MI.getOpcode()) {
5392   case ARM::VSETLNi32:
5393     // dX = VSETLNi32 dY, rZ, imm
5394     const MachineOperand &MOBaseReg = MI.getOperand(1);
5395     const MachineOperand &MOInsertedReg = MI.getOperand(2);
5396     if (MOInsertedReg.isUndef())
5397       return false;
5398     const MachineOperand &MOIndex = MI.getOperand(3);
5399     BaseReg.Reg = MOBaseReg.getReg();
5400     BaseReg.SubReg = MOBaseReg.getSubReg();
5401 
5402     InsertedReg.Reg = MOInsertedReg.getReg();
5403     InsertedReg.SubReg = MOInsertedReg.getSubReg();
5404     InsertedReg.SubIdx = MOIndex.getImm() == 0 ? ARM::ssub_0 : ARM::ssub_1;
5405     return true;
5406   }
5407   llvm_unreachable("Target dependent opcode missing");
5408 }
5409 
5410 std::pair<unsigned, unsigned>
5411 ARMBaseInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
5412   const unsigned Mask = ARMII::MO_OPTION_MASK;
5413   return std::make_pair(TF & Mask, TF & ~Mask);
5414 }
5415 
5416 ArrayRef<std::pair<unsigned, const char *>>
5417 ARMBaseInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
5418   using namespace ARMII;
5419 
5420   static const std::pair<unsigned, const char *> TargetFlags[] = {
5421       {MO_LO16, "arm-lo16"}, {MO_HI16, "arm-hi16"}};
5422   return makeArrayRef(TargetFlags);
5423 }
5424 
5425 ArrayRef<std::pair<unsigned, const char *>>
5426 ARMBaseInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
5427   using namespace ARMII;
5428 
5429   static const std::pair<unsigned, const char *> TargetFlags[] = {
5430       {MO_COFFSTUB, "arm-coffstub"},
5431       {MO_GOT, "arm-got"},
5432       {MO_SBREL, "arm-sbrel"},
5433       {MO_DLLIMPORT, "arm-dllimport"},
5434       {MO_SECREL, "arm-secrel"},
5435       {MO_NONLAZY, "arm-nonlazy"}};
5436   return makeArrayRef(TargetFlags);
5437 }
5438 
5439 Optional<RegImmPair> ARMBaseInstrInfo::isAddImmediate(const MachineInstr &MI,
5440                                                       Register Reg) const {
5441   int Sign = 1;
5442   unsigned Opcode = MI.getOpcode();
5443   int64_t Offset = 0;
5444 
5445   // TODO: Handle cases where Reg is a super- or sub-register of the
5446   // destination register.
5447   const MachineOperand &Op0 = MI.getOperand(0);
5448   if (!Op0.isReg() || Reg != Op0.getReg())
5449     return None;
5450 
5451   // We describe SUBri or ADDri instructions.
5452   if (Opcode == ARM::SUBri)
5453     Sign = -1;
5454   else if (Opcode != ARM::ADDri)
5455     return None;
5456 
5457   // TODO: Third operand can be global address (usually some string). Since
5458   //       strings can be relocated we cannot calculate their offsets for
5459   //       now.
5460   if (!MI.getOperand(1).isReg() || !MI.getOperand(2).isImm())
5461     return None;
5462 
5463   Offset = MI.getOperand(2).getImm() * Sign;
5464   return RegImmPair{MI.getOperand(1).getReg(), Offset};
5465 }
5466 
5467 bool llvm::registerDefinedBetween(unsigned Reg,
5468                                   MachineBasicBlock::iterator From,
5469                                   MachineBasicBlock::iterator To,
5470                                   const TargetRegisterInfo *TRI) {
5471   for (auto I = From; I != To; ++I)
5472     if (I->modifiesRegister(Reg, TRI))
5473       return true;
5474   return false;
5475 }
5476 
5477 MachineInstr *llvm::findCMPToFoldIntoCBZ(MachineInstr *Br,
5478                                          const TargetRegisterInfo *TRI) {
5479   // Search backwards to the instruction that defines CSPR. This may or not
5480   // be a CMP, we check that after this loop. If we find another instruction
5481   // that reads cpsr, we return nullptr.
5482   MachineBasicBlock::iterator CmpMI = Br;
5483   while (CmpMI != Br->getParent()->begin()) {
5484     --CmpMI;
5485     if (CmpMI->modifiesRegister(ARM::CPSR, TRI))
5486       break;
5487     if (CmpMI->readsRegister(ARM::CPSR, TRI))
5488       break;
5489   }
5490 
5491   // Check that this inst is a CMP r[0-7], #0 and that the register
5492   // is not redefined between the cmp and the br.
5493   if (CmpMI->getOpcode() != ARM::tCMPi8 && CmpMI->getOpcode() != ARM::t2CMPri)
5494     return nullptr;
5495   Register Reg = CmpMI->getOperand(0).getReg();
5496   Register PredReg;
5497   ARMCC::CondCodes Pred = getInstrPredicate(*CmpMI, PredReg);
5498   if (Pred != ARMCC::AL || CmpMI->getOperand(1).getImm() != 0)
5499     return nullptr;
5500   if (!isARMLowRegister(Reg))
5501     return nullptr;
5502   if (registerDefinedBetween(Reg, CmpMI->getNextNode(), Br, TRI))
5503     return nullptr;
5504 
5505   return &*CmpMI;
5506 }
5507 
5508 unsigned llvm::ConstantMaterializationCost(unsigned Val,
5509                                            const ARMSubtarget *Subtarget,
5510                                            bool ForCodesize) {
5511   if (Subtarget->isThumb()) {
5512     if (Val <= 255) // MOV
5513       return ForCodesize ? 2 : 1;
5514     if (Subtarget->hasV6T2Ops() && (Val <= 0xffff ||                    // MOV
5515                                     ARM_AM::getT2SOImmVal(Val) != -1 || // MOVW
5516                                     ARM_AM::getT2SOImmVal(~Val) != -1)) // MVN
5517       return ForCodesize ? 4 : 1;
5518     if (Val <= 510) // MOV + ADDi8
5519       return ForCodesize ? 4 : 2;
5520     if (~Val <= 255) // MOV + MVN
5521       return ForCodesize ? 4 : 2;
5522     if (ARM_AM::isThumbImmShiftedVal(Val)) // MOV + LSL
5523       return ForCodesize ? 4 : 2;
5524   } else {
5525     if (ARM_AM::getSOImmVal(Val) != -1) // MOV
5526       return ForCodesize ? 4 : 1;
5527     if (ARM_AM::getSOImmVal(~Val) != -1) // MVN
5528       return ForCodesize ? 4 : 1;
5529     if (Subtarget->hasV6T2Ops() && Val <= 0xffff) // MOVW
5530       return ForCodesize ? 4 : 1;
5531     if (ARM_AM::isSOImmTwoPartVal(Val)) // two instrs
5532       return ForCodesize ? 8 : 2;
5533     if (ARM_AM::isSOImmTwoPartValNeg(Val)) // two instrs
5534       return ForCodesize ? 8 : 2;
5535   }
5536   if (Subtarget->useMovt()) // MOVW + MOVT
5537     return ForCodesize ? 8 : 2;
5538   return ForCodesize ? 8 : 3; // Literal pool load
5539 }
5540 
5541 bool llvm::HasLowerConstantMaterializationCost(unsigned Val1, unsigned Val2,
5542                                                const ARMSubtarget *Subtarget,
5543                                                bool ForCodesize) {
5544   // Check with ForCodesize
5545   unsigned Cost1 = ConstantMaterializationCost(Val1, Subtarget, ForCodesize);
5546   unsigned Cost2 = ConstantMaterializationCost(Val2, Subtarget, ForCodesize);
5547   if (Cost1 < Cost2)
5548     return true;
5549   if (Cost1 > Cost2)
5550     return false;
5551 
5552   // If they are equal, try with !ForCodesize
5553   return ConstantMaterializationCost(Val1, Subtarget, !ForCodesize) <
5554          ConstantMaterializationCost(Val2, Subtarget, !ForCodesize);
5555 }
5556 
5557 /// Constants defining how certain sequences should be outlined.
5558 /// This encompasses how an outlined function should be called, and what kind of
5559 /// frame should be emitted for that outlined function.
5560 ///
5561 /// \p MachineOutlinerTailCall implies that the function is being created from
5562 /// a sequence of instructions ending in a return.
5563 ///
5564 /// That is,
5565 ///
5566 /// I1                                OUTLINED_FUNCTION:
5567 /// I2    --> B OUTLINED_FUNCTION     I1
5568 /// BX LR                             I2
5569 ///                                   BX LR
5570 ///
5571 /// +-------------------------+--------+-----+
5572 /// |                         | Thumb2 | ARM |
5573 /// +-------------------------+--------+-----+
5574 /// | Call overhead in Bytes  |      4 |   4 |
5575 /// | Frame overhead in Bytes |      0 |   0 |
5576 /// | Stack fixup required    |     No |  No |
5577 /// +-------------------------+--------+-----+
5578 ///
5579 /// \p MachineOutlinerThunk implies that the function is being created from
5580 /// a sequence of instructions ending in a call. The outlined function is
5581 /// called with a BL instruction, and the outlined function tail-calls the
5582 /// original call destination.
5583 ///
5584 /// That is,
5585 ///
5586 /// I1                                OUTLINED_FUNCTION:
5587 /// I2   --> BL OUTLINED_FUNCTION     I1
5588 /// BL f                              I2
5589 ///                                   B f
5590 ///
5591 /// +-------------------------+--------+-----+
5592 /// |                         | Thumb2 | ARM |
5593 /// +-------------------------+--------+-----+
5594 /// | Call overhead in Bytes  |      4 |   4 |
5595 /// | Frame overhead in Bytes |      0 |   0 |
5596 /// | Stack fixup required    |     No |  No |
5597 /// +-------------------------+--------+-----+
5598 ///
5599 /// \p MachineOutlinerNoLRSave implies that the function should be called using
5600 /// a BL instruction, but doesn't require LR to be saved and restored. This
5601 /// happens when LR is known to be dead.
5602 ///
5603 /// That is,
5604 ///
5605 /// I1                                OUTLINED_FUNCTION:
5606 /// I2 --> BL OUTLINED_FUNCTION       I1
5607 /// I3                                I2
5608 ///                                   I3
5609 ///                                   BX LR
5610 ///
5611 /// +-------------------------+--------+-----+
5612 /// |                         | Thumb2 | ARM |
5613 /// +-------------------------+--------+-----+
5614 /// | Call overhead in Bytes  |      4 |   4 |
5615 /// | Frame overhead in Bytes |      4 |   4 |
5616 /// | Stack fixup required    |     No |  No |
5617 /// +-------------------------+--------+-----+
5618 ///
5619 /// \p MachineOutlinerRegSave implies that the function should be called with a
5620 /// save and restore of LR to an available register. This allows us to avoid
5621 /// stack fixups. Note that this outlining variant is compatible with the
5622 /// NoLRSave case.
5623 ///
5624 /// That is,
5625 ///
5626 /// I1     Save LR                    OUTLINED_FUNCTION:
5627 /// I2 --> BL OUTLINED_FUNCTION       I1
5628 /// I3     Restore LR                 I2
5629 ///                                   I3
5630 ///                                   BX LR
5631 ///
5632 /// +-------------------------+--------+-----+
5633 /// |                         | Thumb2 | ARM |
5634 /// +-------------------------+--------+-----+
5635 /// | Call overhead in Bytes  |      8 |  12 |
5636 /// | Frame overhead in Bytes |      2 |   4 |
5637 /// | Stack fixup required    |     No |  No |
5638 /// +-------------------------+--------+-----+
5639 ///
5640 /// \p MachineOutlinerDefault implies that the function should be called with
5641 /// a save and restore of LR to the stack.
5642 ///
5643 /// That is,
5644 ///
5645 /// I1     Save LR                    OUTLINED_FUNCTION:
5646 /// I2 --> BL OUTLINED_FUNCTION       I1
5647 /// I3     Restore LR                 I2
5648 ///                                   I3
5649 ///                                   BX LR
5650 ///
5651 /// +-------------------------+--------+-----+
5652 /// |                         | Thumb2 | ARM |
5653 /// +-------------------------+--------+-----+
5654 /// | Call overhead in Bytes  |      8 |  12 |
5655 /// | Frame overhead in Bytes |      2 |   4 |
5656 /// | Stack fixup required    |    Yes | Yes |
5657 /// +-------------------------+--------+-----+
5658 
5659 enum MachineOutlinerClass {
5660   MachineOutlinerTailCall,
5661   MachineOutlinerThunk,
5662   MachineOutlinerNoLRSave,
5663   MachineOutlinerRegSave,
5664   MachineOutlinerDefault
5665 };
5666 
5667 enum MachineOutlinerMBBFlags {
5668   LRUnavailableSomewhere = 0x2,
5669   HasCalls = 0x4,
5670   UnsafeRegsDead = 0x8
5671 };
5672 
5673 struct OutlinerCosts {
5674   const int CallTailCall;
5675   const int FrameTailCall;
5676   const int CallThunk;
5677   const int FrameThunk;
5678   const int CallNoLRSave;
5679   const int FrameNoLRSave;
5680   const int CallRegSave;
5681   const int FrameRegSave;
5682   const int CallDefault;
5683   const int FrameDefault;
5684   const int SaveRestoreLROnStack;
5685 
5686   OutlinerCosts(const ARMSubtarget &target)
5687       : CallTailCall(target.isThumb() ? 4 : 4),
5688         FrameTailCall(target.isThumb() ? 0 : 0),
5689         CallThunk(target.isThumb() ? 4 : 4),
5690         FrameThunk(target.isThumb() ? 0 : 0),
5691         CallNoLRSave(target.isThumb() ? 4 : 4),
5692         FrameNoLRSave(target.isThumb() ? 4 : 4),
5693         CallRegSave(target.isThumb() ? 8 : 12),
5694         FrameRegSave(target.isThumb() ? 2 : 4),
5695         CallDefault(target.isThumb() ? 8 : 12),
5696         FrameDefault(target.isThumb() ? 2 : 4),
5697         SaveRestoreLROnStack(target.isThumb() ? 8 : 8) {}
5698 };
5699 
5700 unsigned
5701 ARMBaseInstrInfo::findRegisterToSaveLRTo(const outliner::Candidate &C) const {
5702   assert(C.LRUWasSet && "LRU wasn't set?");
5703   MachineFunction *MF = C.getMF();
5704   const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo *>(
5705       MF->getSubtarget().getRegisterInfo());
5706 
5707   BitVector regsReserved = ARI->getReservedRegs(*MF);
5708   // Check if there is an available register across the sequence that we can
5709   // use.
5710   for (unsigned Reg : ARM::rGPRRegClass) {
5711     if (!(Reg < regsReserved.size() && regsReserved.test(Reg)) &&
5712         Reg != ARM::LR &&  // LR is not reserved, but don't use it.
5713         Reg != ARM::R12 && // R12 is not guaranteed to be preserved.
5714         C.LRU.available(Reg) && C.UsedInSequence.available(Reg))
5715       return Reg;
5716   }
5717 
5718   // No suitable register. Return 0.
5719   return 0u;
5720 }
5721 
5722 // Compute liveness of LR at the point after the interval [I, E), which
5723 // denotes a *backward* iteration through instructions. Used only for return
5724 // basic blocks, which do not end with a tail call.
5725 static bool isLRAvailable(const TargetRegisterInfo &TRI,
5726                           MachineBasicBlock::reverse_iterator I,
5727                           MachineBasicBlock::reverse_iterator E) {
5728   // At the end of the function LR dead.
5729   bool Live = false;
5730   for (; I != E; ++I) {
5731     const MachineInstr &MI = *I;
5732 
5733     // Check defs of LR.
5734     if (MI.modifiesRegister(ARM::LR, &TRI))
5735       Live = false;
5736 
5737     // Check uses of LR.
5738     unsigned Opcode = MI.getOpcode();
5739     if (Opcode == ARM::BX_RET || Opcode == ARM::MOVPCLR ||
5740         Opcode == ARM::SUBS_PC_LR || Opcode == ARM::tBX_RET ||
5741         Opcode == ARM::tBXNS_RET) {
5742       // These instructions use LR, but it's not an (explicit or implicit)
5743       // operand.
5744       Live = true;
5745       continue;
5746     }
5747     if (MI.readsRegister(ARM::LR, &TRI))
5748       Live = true;
5749   }
5750   return !Live;
5751 }
5752 
5753 outliner::OutlinedFunction ARMBaseInstrInfo::getOutliningCandidateInfo(
5754     std::vector<outliner::Candidate> &RepeatedSequenceLocs) const {
5755   outliner::Candidate &FirstCand = RepeatedSequenceLocs[0];
5756   unsigned SequenceSize =
5757       std::accumulate(FirstCand.front(), std::next(FirstCand.back()), 0,
5758                       [this](unsigned Sum, const MachineInstr &MI) {
5759                         return Sum + getInstSizeInBytes(MI);
5760                       });
5761 
5762   // Properties about candidate MBBs that hold for all of them.
5763   unsigned FlagsSetInAll = 0xF;
5764 
5765   // Compute liveness information for each candidate, and set FlagsSetInAll.
5766   const TargetRegisterInfo &TRI = getRegisterInfo();
5767   std::for_each(
5768       RepeatedSequenceLocs.begin(), RepeatedSequenceLocs.end(),
5769       [&FlagsSetInAll](outliner::Candidate &C) { FlagsSetInAll &= C.Flags; });
5770 
5771   // According to the ARM Procedure Call Standard, the following are
5772   // undefined on entry/exit from a function call:
5773   //
5774   // * Register R12(IP),
5775   // * Condition codes (and thus the CPSR register)
5776   //
5777   // Since we control the instructions which are part of the outlined regions
5778   // we don't need to be fully compliant with the AAPCS, but we have to
5779   // guarantee that if a veneer is inserted at link time the code is still
5780   // correct.  Because of this, we can't outline any sequence of instructions
5781   // where one of these registers is live into/across it. Thus, we need to
5782   // delete those candidates.
5783   auto CantGuaranteeValueAcrossCall = [&TRI](outliner::Candidate &C) {
5784     // If the unsafe registers in this block are all dead, then we don't need
5785     // to compute liveness here.
5786     if (C.Flags & UnsafeRegsDead)
5787       return false;
5788     C.initLRU(TRI);
5789     LiveRegUnits LRU = C.LRU;
5790     return (!LRU.available(ARM::R12) || !LRU.available(ARM::CPSR));
5791   };
5792 
5793   // Are there any candidates where those registers are live?
5794   if (!(FlagsSetInAll & UnsafeRegsDead)) {
5795     // Erase every candidate that violates the restrictions above. (It could be
5796     // true that we have viable candidates, so it's not worth bailing out in
5797     // the case that, say, 1 out of 20 candidates violate the restructions.)
5798     llvm::erase_if(RepeatedSequenceLocs, CantGuaranteeValueAcrossCall);
5799 
5800     // If the sequence doesn't have enough candidates left, then we're done.
5801     if (RepeatedSequenceLocs.size() < 2)
5802       return outliner::OutlinedFunction();
5803   }
5804 
5805   // At this point, we have only "safe" candidates to outline. Figure out
5806   // frame + call instruction information.
5807 
5808   unsigned LastInstrOpcode = RepeatedSequenceLocs[0].back()->getOpcode();
5809 
5810   // Helper lambda which sets call information for every candidate.
5811   auto SetCandidateCallInfo =
5812       [&RepeatedSequenceLocs](unsigned CallID, unsigned NumBytesForCall) {
5813         for (outliner::Candidate &C : RepeatedSequenceLocs)
5814           C.setCallInfo(CallID, NumBytesForCall);
5815       };
5816 
5817   OutlinerCosts Costs(Subtarget);
5818   unsigned FrameID = MachineOutlinerDefault;
5819   unsigned NumBytesToCreateFrame = Costs.FrameDefault;
5820 
5821   // If the last instruction in any candidate is a terminator, then we should
5822   // tail call all of the candidates.
5823   if (RepeatedSequenceLocs[0].back()->isTerminator()) {
5824     FrameID = MachineOutlinerTailCall;
5825     NumBytesToCreateFrame = Costs.FrameTailCall;
5826     SetCandidateCallInfo(MachineOutlinerTailCall, Costs.CallTailCall);
5827   } else if (LastInstrOpcode == ARM::BL || LastInstrOpcode == ARM::BLX ||
5828              LastInstrOpcode == ARM::BLX_noip || LastInstrOpcode == ARM::tBL ||
5829              LastInstrOpcode == ARM::tBLXr ||
5830              LastInstrOpcode == ARM::tBLXr_noip ||
5831              LastInstrOpcode == ARM::tBLXi) {
5832     FrameID = MachineOutlinerThunk;
5833     NumBytesToCreateFrame = Costs.FrameThunk;
5834     SetCandidateCallInfo(MachineOutlinerThunk, Costs.CallThunk);
5835   } else {
5836     // We need to decide how to emit calls + frames. We can always emit the same
5837     // frame if we don't need to save to the stack. If we have to save to the
5838     // stack, then we need a different frame.
5839     unsigned NumBytesNoStackCalls = 0;
5840     std::vector<outliner::Candidate> CandidatesWithoutStackFixups;
5841 
5842     for (outliner::Candidate &C : RepeatedSequenceLocs) {
5843       C.initLRU(TRI);
5844       // LR liveness is overestimated in return blocks, unless they end with a
5845       // tail call.
5846       const auto Last = C.getMBB()->rbegin();
5847       const bool LRIsAvailable =
5848           C.getMBB()->isReturnBlock() && !Last->isCall()
5849               ? isLRAvailable(TRI, Last,
5850                               (MachineBasicBlock::reverse_iterator)C.front())
5851               : C.LRU.available(ARM::LR);
5852       if (LRIsAvailable) {
5853         FrameID = MachineOutlinerNoLRSave;
5854         NumBytesNoStackCalls += Costs.CallNoLRSave;
5855         C.setCallInfo(MachineOutlinerNoLRSave, Costs.CallNoLRSave);
5856         CandidatesWithoutStackFixups.push_back(C);
5857       }
5858 
5859       // Is an unused register available? If so, we won't modify the stack, so
5860       // we can outline with the same frame type as those that don't save LR.
5861       else if (findRegisterToSaveLRTo(C)) {
5862         FrameID = MachineOutlinerRegSave;
5863         NumBytesNoStackCalls += Costs.CallRegSave;
5864         C.setCallInfo(MachineOutlinerRegSave, Costs.CallRegSave);
5865         CandidatesWithoutStackFixups.push_back(C);
5866       }
5867 
5868       // Is SP used in the sequence at all? If not, we don't have to modify
5869       // the stack, so we are guaranteed to get the same frame.
5870       else if (C.UsedInSequence.available(ARM::SP)) {
5871         NumBytesNoStackCalls += Costs.CallDefault;
5872         C.setCallInfo(MachineOutlinerDefault, Costs.CallDefault);
5873         CandidatesWithoutStackFixups.push_back(C);
5874       }
5875 
5876       // If we outline this, we need to modify the stack. Pretend we don't
5877       // outline this by saving all of its bytes.
5878       else
5879         NumBytesNoStackCalls += SequenceSize;
5880     }
5881 
5882     // If there are no places where we have to save LR, then note that we don't
5883     // have to update the stack. Otherwise, give every candidate the default
5884     // call type
5885     if (NumBytesNoStackCalls <=
5886         RepeatedSequenceLocs.size() * Costs.CallDefault) {
5887       RepeatedSequenceLocs = CandidatesWithoutStackFixups;
5888       FrameID = MachineOutlinerNoLRSave;
5889     } else
5890       SetCandidateCallInfo(MachineOutlinerDefault, Costs.CallDefault);
5891   }
5892 
5893   // Does every candidate's MBB contain a call?  If so, then we might have a
5894   // call in the range.
5895   if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) {
5896     // check if the range contains a call.  These require a save + restore of
5897     // the link register.
5898     if (std::any_of(FirstCand.front(), FirstCand.back(),
5899                     [](const MachineInstr &MI) { return MI.isCall(); }))
5900       NumBytesToCreateFrame += Costs.SaveRestoreLROnStack;
5901 
5902     // Handle the last instruction separately.  If it is tail call, then the
5903     // last instruction is a call, we don't want to save + restore in this
5904     // case.  However, it could be possible that the last instruction is a
5905     // call without it being valid to tail call this sequence.  We should
5906     // consider this as well.
5907     else if (FrameID != MachineOutlinerThunk &&
5908              FrameID != MachineOutlinerTailCall && FirstCand.back()->isCall())
5909       NumBytesToCreateFrame += Costs.SaveRestoreLROnStack;
5910   }
5911 
5912   return outliner::OutlinedFunction(RepeatedSequenceLocs, SequenceSize,
5913                                     NumBytesToCreateFrame, FrameID);
5914 }
5915 
5916 bool ARMBaseInstrInfo::isFunctionSafeToOutlineFrom(
5917     MachineFunction &MF, bool OutlineFromLinkOnceODRs) const {
5918   const Function &F = MF.getFunction();
5919 
5920   // Can F be deduplicated by the linker? If it can, don't outline from it.
5921   if (!OutlineFromLinkOnceODRs && F.hasLinkOnceODRLinkage())
5922     return false;
5923 
5924   // Don't outline from functions with section markings; the program could
5925   // expect that all the code is in the named section.
5926   // FIXME: Allow outlining from multiple functions with the same section
5927   // marking.
5928   if (F.hasSection())
5929     return false;
5930 
5931   // FIXME: Thumb1 outlining is not handled
5932   if (MF.getInfo<ARMFunctionInfo>()->isThumb1OnlyFunction())
5933     return false;
5934 
5935   // It's safe to outline from MF.
5936   return true;
5937 }
5938 
5939 bool ARMBaseInstrInfo::isMBBSafeToOutlineFrom(MachineBasicBlock &MBB,
5940                                               unsigned &Flags) const {
5941   // Check if LR is available through all of the MBB. If it's not, then set
5942   // a flag.
5943   assert(MBB.getParent()->getRegInfo().tracksLiveness() &&
5944          "Suitable Machine Function for outlining must track liveness");
5945 
5946   LiveRegUnits LRU(getRegisterInfo());
5947 
5948   std::for_each(MBB.rbegin(), MBB.rend(),
5949                 [&LRU](MachineInstr &MI) { LRU.accumulate(MI); });
5950 
5951   // Check if each of the unsafe registers are available...
5952   bool R12AvailableInBlock = LRU.available(ARM::R12);
5953   bool CPSRAvailableInBlock = LRU.available(ARM::CPSR);
5954 
5955   // If all of these are dead (and not live out), we know we don't have to check
5956   // them later.
5957   if (R12AvailableInBlock && CPSRAvailableInBlock)
5958     Flags |= MachineOutlinerMBBFlags::UnsafeRegsDead;
5959 
5960   // Now, add the live outs to the set.
5961   LRU.addLiveOuts(MBB);
5962 
5963   // If any of these registers is available in the MBB, but also a live out of
5964   // the block, then we know outlining is unsafe.
5965   if (R12AvailableInBlock && !LRU.available(ARM::R12))
5966     return false;
5967   if (CPSRAvailableInBlock && !LRU.available(ARM::CPSR))
5968     return false;
5969 
5970   // Check if there's a call inside this MachineBasicBlock.  If there is, then
5971   // set a flag.
5972   if (any_of(MBB, [](MachineInstr &MI) { return MI.isCall(); }))
5973     Flags |= MachineOutlinerMBBFlags::HasCalls;
5974 
5975   // LR liveness is overestimated in return blocks.
5976 
5977   bool LRIsAvailable =
5978       MBB.isReturnBlock() && !MBB.back().isCall()
5979           ? isLRAvailable(getRegisterInfo(), MBB.rbegin(), MBB.rend())
5980           : LRU.available(ARM::LR);
5981   if (!LRIsAvailable)
5982     Flags |= MachineOutlinerMBBFlags::LRUnavailableSomewhere;
5983 
5984   return true;
5985 }
5986 
5987 outliner::InstrType
5988 ARMBaseInstrInfo::getOutliningType(MachineBasicBlock::iterator &MIT,
5989                                    unsigned Flags) const {
5990   MachineInstr &MI = *MIT;
5991   const TargetRegisterInfo *TRI = &getRegisterInfo();
5992 
5993   // Be conservative with inline ASM
5994   if (MI.isInlineAsm())
5995     return outliner::InstrType::Illegal;
5996 
5997   // Don't allow debug values to impact outlining type.
5998   if (MI.isDebugInstr() || MI.isIndirectDebugValue())
5999     return outliner::InstrType::Invisible;
6000 
6001   // At this point, KILL or IMPLICIT_DEF instructions don't really tell us much
6002   // so we can go ahead and skip over them.
6003   if (MI.isKill() || MI.isImplicitDef())
6004     return outliner::InstrType::Invisible;
6005 
6006   // PIC instructions contain labels, outlining them would break offset
6007   // computing.  unsigned Opc = MI.getOpcode();
6008   unsigned Opc = MI.getOpcode();
6009   if (Opc == ARM::tPICADD || Opc == ARM::PICADD || Opc == ARM::PICSTR ||
6010       Opc == ARM::PICSTRB || Opc == ARM::PICSTRH || Opc == ARM::PICLDR ||
6011       Opc == ARM::PICLDRB || Opc == ARM::PICLDRH || Opc == ARM::PICLDRSB ||
6012       Opc == ARM::PICLDRSH || Opc == ARM::t2LDRpci_pic ||
6013       Opc == ARM::t2MOVi16_ga_pcrel || Opc == ARM::t2MOVTi16_ga_pcrel ||
6014       Opc == ARM::t2MOV_ga_pcrel)
6015     return outliner::InstrType::Illegal;
6016 
6017   // Be conservative with ARMv8.1 MVE instructions.
6018   if (Opc == ARM::t2BF_LabelPseudo || Opc == ARM::t2DoLoopStart ||
6019       Opc == ARM::t2DoLoopStartTP || Opc == ARM::t2WhileLoopStart ||
6020       Opc == ARM::t2LoopDec || Opc == ARM::t2LoopEnd ||
6021       Opc == ARM::t2LoopEndDec)
6022     return outliner::InstrType::Illegal;
6023 
6024   const MCInstrDesc &MCID = MI.getDesc();
6025   uint64_t MIFlags = MCID.TSFlags;
6026   if ((MIFlags & ARMII::DomainMask) == ARMII::DomainMVE)
6027     return outliner::InstrType::Illegal;
6028 
6029   // Is this a terminator for a basic block?
6030   if (MI.isTerminator()) {
6031     // Don't outline if the branch is not unconditional.
6032     if (isPredicated(MI))
6033       return outliner::InstrType::Illegal;
6034 
6035     // Is this the end of a function?
6036     if (MI.getParent()->succ_empty())
6037       return outliner::InstrType::Legal;
6038 
6039     // It's not, so don't outline it.
6040     return outliner::InstrType::Illegal;
6041   }
6042 
6043   // Make sure none of the operands are un-outlinable.
6044   for (const MachineOperand &MOP : MI.operands()) {
6045     if (MOP.isCPI() || MOP.isJTI() || MOP.isCFIIndex() || MOP.isFI() ||
6046         MOP.isTargetIndex())
6047       return outliner::InstrType::Illegal;
6048   }
6049 
6050   // Don't outline if link register or program counter value are used.
6051   if (MI.readsRegister(ARM::LR, TRI) || MI.readsRegister(ARM::PC, TRI))
6052     return outliner::InstrType::Illegal;
6053 
6054   if (MI.isCall()) {
6055     // Get the function associated with the call.  Look at each operand and find
6056     // the one that represents the calle and get its name.
6057     const Function *Callee = nullptr;
6058     for (const MachineOperand &MOP : MI.operands()) {
6059       if (MOP.isGlobal()) {
6060         Callee = dyn_cast<Function>(MOP.getGlobal());
6061         break;
6062       }
6063     }
6064 
6065     // Dont't outline calls to "mcount" like functions, in particular Linux
6066     // kernel function tracing relies on it.
6067     if (Callee &&
6068         (Callee->getName() == "\01__gnu_mcount_nc" ||
6069          Callee->getName() == "\01mcount" || Callee->getName() == "__mcount"))
6070       return outliner::InstrType::Illegal;
6071 
6072     // If we don't know anything about the callee, assume it depends on the
6073     // stack layout of the caller. In that case, it's only legal to outline
6074     // as a tail-call. Explicitly list the call instructions we know about so
6075     // we don't get unexpected results with call pseudo-instructions.
6076     auto UnknownCallOutlineType = outliner::InstrType::Illegal;
6077     if (Opc == ARM::BL || Opc == ARM::tBL || Opc == ARM::BLX ||
6078         Opc == ARM::BLX_noip || Opc == ARM::tBLXr || Opc == ARM::tBLXr_noip ||
6079         Opc == ARM::tBLXi)
6080       UnknownCallOutlineType = outliner::InstrType::LegalTerminator;
6081 
6082     if (!Callee)
6083       return UnknownCallOutlineType;
6084 
6085     // We have a function we have information about.  Check if it's something we
6086     // can safely outline.
6087     MachineFunction *MF = MI.getParent()->getParent();
6088     MachineFunction *CalleeMF = MF->getMMI().getMachineFunction(*Callee);
6089 
6090     // We don't know what's going on with the callee at all.  Don't touch it.
6091     if (!CalleeMF)
6092       return UnknownCallOutlineType;
6093 
6094     // Check if we know anything about the callee saves on the function. If we
6095     // don't, then don't touch it, since that implies that we haven't computed
6096     // anything about its stack frame yet.
6097     MachineFrameInfo &MFI = CalleeMF->getFrameInfo();
6098     if (!MFI.isCalleeSavedInfoValid() || MFI.getStackSize() > 0 ||
6099         MFI.getNumObjects() > 0)
6100       return UnknownCallOutlineType;
6101 
6102     // At this point, we can say that CalleeMF ought to not pass anything on the
6103     // stack. Therefore, we can outline it.
6104     return outliner::InstrType::Legal;
6105   }
6106 
6107   // Since calls are handled, don't touch LR or PC
6108   if (MI.modifiesRegister(ARM::LR, TRI) || MI.modifiesRegister(ARM::PC, TRI))
6109     return outliner::InstrType::Illegal;
6110 
6111   // Does this use the stack?
6112   if (MI.modifiesRegister(ARM::SP, TRI) || MI.readsRegister(ARM::SP, TRI)) {
6113     // True if there is no chance that any outlined candidate from this range
6114     // could require stack fixups. That is, both
6115     // * LR is available in the range (No save/restore around call)
6116     // * The range doesn't include calls (No save/restore in outlined frame)
6117     // are true.
6118     // FIXME: This is very restrictive; the flags check the whole block,
6119     // not just the bit we will try to outline.
6120     bool MightNeedStackFixUp =
6121         (Flags & (MachineOutlinerMBBFlags::LRUnavailableSomewhere |
6122                   MachineOutlinerMBBFlags::HasCalls));
6123 
6124     if (!MightNeedStackFixUp)
6125       return outliner::InstrType::Legal;
6126 
6127     return outliner::InstrType::Illegal;
6128   }
6129 
6130   // Be conservative with IT blocks.
6131   if (MI.readsRegister(ARM::ITSTATE, TRI) ||
6132       MI.modifiesRegister(ARM::ITSTATE, TRI))
6133     return outliner::InstrType::Illegal;
6134 
6135   // Don't outline positions.
6136   if (MI.isPosition())
6137     return outliner::InstrType::Illegal;
6138 
6139   return outliner::InstrType::Legal;
6140 }
6141 
6142 void ARMBaseInstrInfo::saveLROnStack(MachineBasicBlock &MBB,
6143                                      MachineBasicBlock::iterator It) const {
6144   unsigned Opc = Subtarget.isThumb() ? ARM::t2STR_PRE : ARM::STR_PRE_IMM;
6145   int Align = -Subtarget.getStackAlignment().value();
6146   BuildMI(MBB, It, DebugLoc(), get(Opc), ARM::SP)
6147     .addReg(ARM::LR, RegState::Kill)
6148     .addReg(ARM::SP)
6149     .addImm(Align)
6150     .add(predOps(ARMCC::AL));
6151 }
6152 
6153 void ARMBaseInstrInfo::emitCFIForLRSaveOnStack(
6154     MachineBasicBlock &MBB, MachineBasicBlock::iterator It) const {
6155   MachineFunction &MF = *MBB.getParent();
6156   const MCRegisterInfo *MRI = Subtarget.getRegisterInfo();
6157   unsigned DwarfLR = MRI->getDwarfRegNum(ARM::LR, true);
6158   int Align = Subtarget.getStackAlignment().value();
6159   // Add a CFI saying the stack was moved down.
6160   int64_t StackPosEntry =
6161       MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, Align));
6162   BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
6163       .addCFIIndex(StackPosEntry)
6164       .setMIFlags(MachineInstr::FrameSetup);
6165 
6166   // Add a CFI saying that the LR that we want to find is now higher than
6167   // before.
6168   int64_t LRPosEntry =
6169       MF.addFrameInst(MCCFIInstruction::createOffset(nullptr, DwarfLR, -Align));
6170   BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
6171       .addCFIIndex(LRPosEntry)
6172       .setMIFlags(MachineInstr::FrameSetup);
6173 }
6174 
6175 void ARMBaseInstrInfo::emitCFIForLRSaveToReg(MachineBasicBlock &MBB,
6176                                              MachineBasicBlock::iterator It,
6177                                              Register Reg) const {
6178   MachineFunction &MF = *MBB.getParent();
6179   const MCRegisterInfo *MRI = Subtarget.getRegisterInfo();
6180   unsigned DwarfLR = MRI->getDwarfRegNum(ARM::LR, true);
6181   unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
6182 
6183   int64_t LRPosEntry = MF.addFrameInst(
6184       MCCFIInstruction::createRegister(nullptr, DwarfLR, DwarfReg));
6185   BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
6186       .addCFIIndex(LRPosEntry)
6187       .setMIFlags(MachineInstr::FrameSetup);
6188 }
6189 
6190 void ARMBaseInstrInfo::restoreLRFromStack(
6191     MachineBasicBlock &MBB, MachineBasicBlock::iterator It) const {
6192   unsigned Opc = Subtarget.isThumb() ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6193   MachineInstrBuilder MIB = BuildMI(MBB, It, DebugLoc(), get(Opc), ARM::LR)
6194     .addReg(ARM::SP, RegState::Define)
6195     .addReg(ARM::SP);
6196   if (!Subtarget.isThumb())
6197     MIB.addReg(0);
6198   MIB.addImm(Subtarget.getStackAlignment().value()).add(predOps(ARMCC::AL));
6199 }
6200 
6201 void ARMBaseInstrInfo::emitCFIForLRRestoreFromStack(
6202     MachineBasicBlock &MBB, MachineBasicBlock::iterator It) const {
6203   // Now stack has moved back up...
6204   MachineFunction &MF = *MBB.getParent();
6205   const MCRegisterInfo *MRI = Subtarget.getRegisterInfo();
6206   unsigned DwarfLR = MRI->getDwarfRegNum(ARM::LR, true);
6207   int64_t StackPosEntry =
6208       MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 0));
6209   BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
6210       .addCFIIndex(StackPosEntry)
6211       .setMIFlags(MachineInstr::FrameDestroy);
6212 
6213   // ... and we have restored LR.
6214   int64_t LRPosEntry =
6215       MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, DwarfLR));
6216   BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
6217       .addCFIIndex(LRPosEntry)
6218       .setMIFlags(MachineInstr::FrameDestroy);
6219 }
6220 
6221 void ARMBaseInstrInfo::emitCFIForLRRestoreFromReg(
6222     MachineBasicBlock &MBB, MachineBasicBlock::iterator It) const {
6223   MachineFunction &MF = *MBB.getParent();
6224   const MCRegisterInfo *MRI = Subtarget.getRegisterInfo();
6225   unsigned DwarfLR = MRI->getDwarfRegNum(ARM::LR, true);
6226 
6227   int64_t LRPosEntry =
6228       MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, DwarfLR));
6229   BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
6230       .addCFIIndex(LRPosEntry)
6231       .setMIFlags(MachineInstr::FrameDestroy);
6232 }
6233 
6234 void ARMBaseInstrInfo::buildOutlinedFrame(
6235     MachineBasicBlock &MBB, MachineFunction &MF,
6236     const outliner::OutlinedFunction &OF) const {
6237   // For thunk outlining, rewrite the last instruction from a call to a
6238   // tail-call.
6239   if (OF.FrameConstructionID == MachineOutlinerThunk) {
6240     MachineInstr *Call = &*--MBB.instr_end();
6241     bool isThumb = Subtarget.isThumb();
6242     unsigned FuncOp = isThumb ? 2 : 0;
6243     unsigned Opc = Call->getOperand(FuncOp).isReg()
6244                        ? isThumb ? ARM::tTAILJMPr : ARM::TAILJMPr
6245                        : isThumb ? Subtarget.isTargetMachO() ? ARM::tTAILJMPd
6246                                                              : ARM::tTAILJMPdND
6247                                  : ARM::TAILJMPd;
6248     MachineInstrBuilder MIB = BuildMI(MBB, MBB.end(), DebugLoc(), get(Opc))
6249                                   .add(Call->getOperand(FuncOp));
6250     if (isThumb && !Call->getOperand(FuncOp).isReg())
6251       MIB.add(predOps(ARMCC::AL));
6252     Call->eraseFromParent();
6253   }
6254 
6255   // Is there a call in the outlined range?
6256   auto IsNonTailCall = [](MachineInstr &MI) {
6257     return MI.isCall() && !MI.isReturn();
6258   };
6259   if (std::any_of(MBB.instr_begin(), MBB.instr_end(), IsNonTailCall)) {
6260     MachineBasicBlock::iterator It = MBB.begin();
6261     MachineBasicBlock::iterator Et = MBB.end();
6262 
6263     if (OF.FrameConstructionID == MachineOutlinerTailCall ||
6264         OF.FrameConstructionID == MachineOutlinerThunk)
6265       Et = std::prev(MBB.end());
6266 
6267     // We have to save and restore LR, we need to add it to the liveins if it
6268     // is not already part of the set.  This is suffient since outlined
6269     // functions only have one block.
6270     if (!MBB.isLiveIn(ARM::LR))
6271       MBB.addLiveIn(ARM::LR);
6272 
6273     // Insert a save before the outlined region
6274     saveLROnStack(MBB, It);
6275     emitCFIForLRSaveOnStack(MBB, It);
6276 
6277     // Insert a restore before the terminator for the function.  Restore LR.
6278     restoreLRFromStack(MBB, Et);
6279     emitCFIForLRRestoreFromStack(MBB, Et);
6280   }
6281 
6282   // If this is a tail call outlined function, then there's already a return.
6283   if (OF.FrameConstructionID == MachineOutlinerTailCall ||
6284       OF.FrameConstructionID == MachineOutlinerThunk)
6285     return;
6286 
6287   // Here we have to insert the return ourselves.  Get the correct opcode from
6288   // current feature set.
6289   BuildMI(MBB, MBB.end(), DebugLoc(), get(Subtarget.getReturnOpcode()))
6290       .add(predOps(ARMCC::AL));
6291 }
6292 
6293 MachineBasicBlock::iterator ARMBaseInstrInfo::insertOutlinedCall(
6294     Module &M, MachineBasicBlock &MBB, MachineBasicBlock::iterator &It,
6295     MachineFunction &MF, const outliner::Candidate &C) const {
6296   MachineInstrBuilder MIB;
6297   MachineBasicBlock::iterator CallPt;
6298   unsigned Opc;
6299   bool isThumb = Subtarget.isThumb();
6300 
6301   // Are we tail calling?
6302   if (C.CallConstructionID == MachineOutlinerTailCall) {
6303     // If yes, then we can just branch to the label.
6304     Opc = isThumb
6305               ? Subtarget.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND
6306               : ARM::TAILJMPd;
6307     MIB = BuildMI(MF, DebugLoc(), get(Opc))
6308               .addGlobalAddress(M.getNamedValue(MF.getName()));
6309     if (isThumb)
6310       MIB.add(predOps(ARMCC::AL));
6311     It = MBB.insert(It, MIB);
6312     return It;
6313   }
6314 
6315   // Create the call instruction.
6316   Opc = isThumb ? ARM::tBL : ARM::BL;
6317   MachineInstrBuilder CallMIB = BuildMI(MF, DebugLoc(), get(Opc));
6318   if (isThumb)
6319     CallMIB.add(predOps(ARMCC::AL));
6320   CallMIB.addGlobalAddress(M.getNamedValue(MF.getName()));
6321 
6322   if (C.CallConstructionID == MachineOutlinerNoLRSave ||
6323       C.CallConstructionID == MachineOutlinerThunk) {
6324     // No, so just insert the call.
6325     It = MBB.insert(It, CallMIB);
6326     return It;
6327   }
6328 
6329   const ARMFunctionInfo &AFI = *C.getMF()->getInfo<ARMFunctionInfo>();
6330   // Can we save to a register?
6331   if (C.CallConstructionID == MachineOutlinerRegSave) {
6332     unsigned Reg = findRegisterToSaveLRTo(C);
6333     assert(Reg != 0 && "No callee-saved register available?");
6334 
6335     // Save and restore LR from that register.
6336     copyPhysReg(MBB, It, DebugLoc(), Reg, ARM::LR, true);
6337     if (!AFI.isLRSpilled())
6338       emitCFIForLRSaveToReg(MBB, It, Reg);
6339     CallPt = MBB.insert(It, CallMIB);
6340     copyPhysReg(MBB, It, DebugLoc(), ARM::LR, Reg, true);
6341     if (!AFI.isLRSpilled())
6342       emitCFIForLRRestoreFromReg(MBB, It);
6343     It--;
6344     return CallPt;
6345   }
6346   // We have the default case. Save and restore from SP.
6347   saveLROnStack(MBB, It);
6348   if (!AFI.isLRSpilled())
6349     emitCFIForLRSaveOnStack(MBB, It);
6350   CallPt = MBB.insert(It, CallMIB);
6351   restoreLRFromStack(MBB, It);
6352   if (!AFI.isLRSpilled())
6353     emitCFIForLRRestoreFromStack(MBB, It);
6354   It--;
6355   return CallPt;
6356 }
6357 
6358 bool ARMBaseInstrInfo::shouldOutlineFromFunctionByDefault(
6359     MachineFunction &MF) const {
6360   return Subtarget.isMClass() && MF.getFunction().hasMinSize();
6361 }
6362 
6363 bool ARMBaseInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI,
6364                                                          AAResults *AA) const {
6365   // Try hard to rematerialize any VCTPs because if we spill P0, it will block
6366   // the tail predication conversion. This means that the element count
6367   // register has to be live for longer, but that has to be better than
6368   // spill/restore and VPT predication.
6369   return isVCTP(&MI) && !isPredicated(MI);
6370 }
6371 
6372 unsigned llvm::getBLXOpcode(const MachineFunction &MF) {
6373   return (MF.getSubtarget<ARMSubtarget>().hardenSlsBlr()) ? ARM::BLX_noip
6374                                                           : ARM::BLX;
6375 }
6376 
6377 unsigned llvm::gettBLXrOpcode(const MachineFunction &MF) {
6378   return (MF.getSubtarget<ARMSubtarget>().hardenSlsBlr()) ? ARM::tBLXr_noip
6379                                                           : ARM::tBLXr;
6380 }
6381 
6382 unsigned llvm::getBLXpredOpcode(const MachineFunction &MF) {
6383   return (MF.getSubtarget<ARMSubtarget>().hardenSlsBlr()) ? ARM::BLX_pred_noip
6384                                                           : ARM::BLX_pred;
6385 }
6386 
6387