[ARM] MVE big endian bitcasts
[llvm-complete.git] / lib / Target / ARM / ARMBaseInstrInfo.cpp
blob763722cbf1df343d857498ddde0a6b2c33d0580e
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.
11 //===----------------------------------------------------------------------===//
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 "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/CodeGen/LiveVariables.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineConstantPool.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineMemOperand.h"
35 #include "llvm/CodeGen/MachineOperand.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/ScoreboardHazardRecognizer.h"
38 #include "llvm/CodeGen/SelectionDAGNodes.h"
39 #include "llvm/CodeGen/TargetInstrInfo.h"
40 #include "llvm/CodeGen/TargetRegisterInfo.h"
41 #include "llvm/CodeGen/TargetSchedule.h"
42 #include "llvm/IR/Attributes.h"
43 #include "llvm/IR/Constants.h"
44 #include "llvm/IR/DebugLoc.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/GlobalValue.h"
47 #include "llvm/MC/MCAsmInfo.h"
48 #include "llvm/MC/MCInstrDesc.h"
49 #include "llvm/MC/MCInstrItineraries.h"
50 #include "llvm/Support/BranchProbability.h"
51 #include "llvm/Support/Casting.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Compiler.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include "llvm/Target/TargetMachine.h"
58 #include <algorithm>
59 #include <cassert>
60 #include <cstdint>
61 #include <iterator>
62 #include <new>
63 #include <utility>
64 #include <vector>
66 using namespace llvm;
68 #define DEBUG_TYPE "arm-instrinfo"
70 #define GET_INSTRINFO_CTOR_DTOR
71 #include "ARMGenInstrInfo.inc"
73 static cl::opt<bool>
74 EnableARM3Addr("enable-arm-3-addr-conv", cl::Hidden,
75 cl::desc("Enable ARM 2-addr to 3-addr conv"));
77 /// ARM_MLxEntry - Record information about MLA / MLS instructions.
78 struct ARM_MLxEntry {
79 uint16_t MLxOpc; // MLA / MLS opcode
80 uint16_t MulOpc; // Expanded multiplication opcode
81 uint16_t AddSubOpc; // Expanded add / sub opcode
82 bool NegAcc; // True if the acc is negated before the add / sub.
83 bool HasLane; // True if instruction has an extra "lane" operand.
86 static const ARM_MLxEntry ARM_MLxTable[] = {
87 // MLxOpc, MulOpc, AddSubOpc, NegAcc, HasLane
88 // fp scalar ops
89 { ARM::VMLAS, ARM::VMULS, ARM::VADDS, false, false },
90 { ARM::VMLSS, ARM::VMULS, ARM::VSUBS, false, false },
91 { ARM::VMLAD, ARM::VMULD, ARM::VADDD, false, false },
92 { ARM::VMLSD, ARM::VMULD, ARM::VSUBD, false, false },
93 { ARM::VNMLAS, ARM::VNMULS, ARM::VSUBS, true, false },
94 { ARM::VNMLSS, ARM::VMULS, ARM::VSUBS, true, false },
95 { ARM::VNMLAD, ARM::VNMULD, ARM::VSUBD, true, false },
96 { ARM::VNMLSD, ARM::VMULD, ARM::VSUBD, true, false },
98 // fp SIMD ops
99 { ARM::VMLAfd, ARM::VMULfd, ARM::VADDfd, false, false },
100 { ARM::VMLSfd, ARM::VMULfd, ARM::VSUBfd, false, false },
101 { ARM::VMLAfq, ARM::VMULfq, ARM::VADDfq, false, false },
102 { ARM::VMLSfq, ARM::VMULfq, ARM::VSUBfq, false, false },
103 { ARM::VMLAslfd, ARM::VMULslfd, ARM::VADDfd, false, true },
104 { ARM::VMLSslfd, ARM::VMULslfd, ARM::VSUBfd, false, true },
105 { ARM::VMLAslfq, ARM::VMULslfq, ARM::VADDfq, false, true },
106 { ARM::VMLSslfq, ARM::VMULslfq, ARM::VSUBfq, false, true },
109 ARMBaseInstrInfo::ARMBaseInstrInfo(const ARMSubtarget& STI)
110 : ARMGenInstrInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP),
111 Subtarget(STI) {
112 for (unsigned i = 0, e = array_lengthof(ARM_MLxTable); i != e; ++i) {
113 if (!MLxEntryMap.insert(std::make_pair(ARM_MLxTable[i].MLxOpc, i)).second)
114 llvm_unreachable("Duplicated entries?");
115 MLxHazardOpcodes.insert(ARM_MLxTable[i].AddSubOpc);
116 MLxHazardOpcodes.insert(ARM_MLxTable[i].MulOpc);
120 // Use a ScoreboardHazardRecognizer for prepass ARM scheduling. TargetInstrImpl
121 // currently defaults to no prepass hazard recognizer.
122 ScheduleHazardRecognizer *
123 ARMBaseInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
124 const ScheduleDAG *DAG) const {
125 if (usePreRAHazardRecognizer()) {
126 const InstrItineraryData *II =
127 static_cast<const ARMSubtarget *>(STI)->getInstrItineraryData();
128 return new ScoreboardHazardRecognizer(II, DAG, "pre-RA-sched");
130 return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
133 ScheduleHazardRecognizer *ARMBaseInstrInfo::
134 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
135 const ScheduleDAG *DAG) const {
136 if (Subtarget.isThumb2() || Subtarget.hasVFP2Base())
137 return (ScheduleHazardRecognizer *)new ARMHazardRecognizer(II, DAG);
138 return TargetInstrInfo::CreateTargetPostRAHazardRecognizer(II, DAG);
141 MachineInstr *ARMBaseInstrInfo::convertToThreeAddress(
142 MachineFunction::iterator &MFI, MachineInstr &MI, LiveVariables *LV) const {
143 // FIXME: Thumb2 support.
145 if (!EnableARM3Addr)
146 return nullptr;
148 MachineFunction &MF = *MI.getParent()->getParent();
149 uint64_t TSFlags = MI.getDesc().TSFlags;
150 bool isPre = false;
151 switch ((TSFlags & ARMII::IndexModeMask) >> ARMII::IndexModeShift) {
152 default: return nullptr;
153 case ARMII::IndexModePre:
154 isPre = true;
155 break;
156 case ARMII::IndexModePost:
157 break;
160 // Try splitting an indexed load/store to an un-indexed one plus an add/sub
161 // operation.
162 unsigned MemOpc = getUnindexedOpcode(MI.getOpcode());
163 if (MemOpc == 0)
164 return nullptr;
166 MachineInstr *UpdateMI = nullptr;
167 MachineInstr *MemMI = nullptr;
168 unsigned AddrMode = (TSFlags & ARMII::AddrModeMask);
169 const MCInstrDesc &MCID = MI.getDesc();
170 unsigned NumOps = MCID.getNumOperands();
171 bool isLoad = !MI.mayStore();
172 const MachineOperand &WB = isLoad ? MI.getOperand(1) : MI.getOperand(0);
173 const MachineOperand &Base = MI.getOperand(2);
174 const MachineOperand &Offset = MI.getOperand(NumOps - 3);
175 unsigned WBReg = WB.getReg();
176 unsigned BaseReg = Base.getReg();
177 unsigned OffReg = Offset.getReg();
178 unsigned OffImm = MI.getOperand(NumOps - 2).getImm();
179 ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI.getOperand(NumOps - 1).getImm();
180 switch (AddrMode) {
181 default: llvm_unreachable("Unknown indexed op!");
182 case ARMII::AddrMode2: {
183 bool isSub = ARM_AM::getAM2Op(OffImm) == ARM_AM::sub;
184 unsigned Amt = ARM_AM::getAM2Offset(OffImm);
185 if (OffReg == 0) {
186 if (ARM_AM::getSOImmVal(Amt) == -1)
187 // Can't encode it in a so_imm operand. This transformation will
188 // add more than 1 instruction. Abandon!
189 return nullptr;
190 UpdateMI = BuildMI(MF, MI.getDebugLoc(),
191 get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
192 .addReg(BaseReg)
193 .addImm(Amt)
194 .add(predOps(Pred))
195 .add(condCodeOp());
196 } else if (Amt != 0) {
197 ARM_AM::ShiftOpc ShOpc = ARM_AM::getAM2ShiftOpc(OffImm);
198 unsigned SOOpc = ARM_AM::getSORegOpc(ShOpc, Amt);
199 UpdateMI = BuildMI(MF, MI.getDebugLoc(),
200 get(isSub ? ARM::SUBrsi : ARM::ADDrsi), WBReg)
201 .addReg(BaseReg)
202 .addReg(OffReg)
203 .addReg(0)
204 .addImm(SOOpc)
205 .add(predOps(Pred))
206 .add(condCodeOp());
207 } else
208 UpdateMI = BuildMI(MF, MI.getDebugLoc(),
209 get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
210 .addReg(BaseReg)
211 .addReg(OffReg)
212 .add(predOps(Pred))
213 .add(condCodeOp());
214 break;
216 case ARMII::AddrMode3 : {
217 bool isSub = ARM_AM::getAM3Op(OffImm) == ARM_AM::sub;
218 unsigned Amt = ARM_AM::getAM3Offset(OffImm);
219 if (OffReg == 0)
220 // Immediate is 8-bits. It's guaranteed to fit in a so_imm operand.
221 UpdateMI = BuildMI(MF, MI.getDebugLoc(),
222 get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
223 .addReg(BaseReg)
224 .addImm(Amt)
225 .add(predOps(Pred))
226 .add(condCodeOp());
227 else
228 UpdateMI = BuildMI(MF, MI.getDebugLoc(),
229 get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
230 .addReg(BaseReg)
231 .addReg(OffReg)
232 .add(predOps(Pred))
233 .add(condCodeOp());
234 break;
238 std::vector<MachineInstr*> NewMIs;
239 if (isPre) {
240 if (isLoad)
241 MemMI =
242 BuildMI(MF, MI.getDebugLoc(), get(MemOpc), MI.getOperand(0).getReg())
243 .addReg(WBReg)
244 .addImm(0)
245 .addImm(Pred);
246 else
247 MemMI = BuildMI(MF, MI.getDebugLoc(), get(MemOpc))
248 .addReg(MI.getOperand(1).getReg())
249 .addReg(WBReg)
250 .addReg(0)
251 .addImm(0)
252 .addImm(Pred);
253 NewMIs.push_back(MemMI);
254 NewMIs.push_back(UpdateMI);
255 } else {
256 if (isLoad)
257 MemMI =
258 BuildMI(MF, MI.getDebugLoc(), get(MemOpc), MI.getOperand(0).getReg())
259 .addReg(BaseReg)
260 .addImm(0)
261 .addImm(Pred);
262 else
263 MemMI = BuildMI(MF, MI.getDebugLoc(), get(MemOpc))
264 .addReg(MI.getOperand(1).getReg())
265 .addReg(BaseReg)
266 .addReg(0)
267 .addImm(0)
268 .addImm(Pred);
269 if (WB.isDead())
270 UpdateMI->getOperand(0).setIsDead();
271 NewMIs.push_back(UpdateMI);
272 NewMIs.push_back(MemMI);
275 // Transfer LiveVariables states, kill / dead info.
276 if (LV) {
277 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
278 MachineOperand &MO = MI.getOperand(i);
279 if (MO.isReg() && Register::isVirtualRegister(MO.getReg())) {
280 unsigned Reg = MO.getReg();
282 LiveVariables::VarInfo &VI = LV->getVarInfo(Reg);
283 if (MO.isDef()) {
284 MachineInstr *NewMI = (Reg == WBReg) ? UpdateMI : MemMI;
285 if (MO.isDead())
286 LV->addVirtualRegisterDead(Reg, *NewMI);
288 if (MO.isUse() && MO.isKill()) {
289 for (unsigned j = 0; j < 2; ++j) {
290 // Look at the two new MI's in reverse order.
291 MachineInstr *NewMI = NewMIs[j];
292 if (!NewMI->readsRegister(Reg))
293 continue;
294 LV->addVirtualRegisterKilled(Reg, *NewMI);
295 if (VI.removeKill(MI))
296 VI.Kills.push_back(NewMI);
297 break;
304 MachineBasicBlock::iterator MBBI = MI.getIterator();
305 MFI->insert(MBBI, NewMIs[1]);
306 MFI->insert(MBBI, NewMIs[0]);
307 return NewMIs[0];
310 // Branch analysis.
311 bool ARMBaseInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
312 MachineBasicBlock *&TBB,
313 MachineBasicBlock *&FBB,
314 SmallVectorImpl<MachineOperand> &Cond,
315 bool AllowModify) const {
316 TBB = nullptr;
317 FBB = nullptr;
319 MachineBasicBlock::iterator I = MBB.end();
320 if (I == MBB.begin())
321 return false; // Empty blocks are easy.
322 --I;
324 // Walk backwards from the end of the basic block until the branch is
325 // analyzed or we give up.
326 while (isPredicated(*I) || I->isTerminator() || I->isDebugValue()) {
327 // Flag to be raised on unanalyzeable instructions. This is useful in cases
328 // where we want to clean up on the end of the basic block before we bail
329 // out.
330 bool CantAnalyze = false;
332 // Skip over DEBUG values and predicated nonterminators.
333 while (I->isDebugInstr() || !I->isTerminator()) {
334 if (I == MBB.begin())
335 return false;
336 --I;
339 if (isIndirectBranchOpcode(I->getOpcode()) ||
340 isJumpTableBranchOpcode(I->getOpcode())) {
341 // Indirect branches and jump tables can't be analyzed, but we still want
342 // to clean up any instructions at the tail of the basic block.
343 CantAnalyze = true;
344 } else if (isUncondBranchOpcode(I->getOpcode())) {
345 TBB = I->getOperand(0).getMBB();
346 } else if (isCondBranchOpcode(I->getOpcode())) {
347 // Bail out if we encounter multiple conditional branches.
348 if (!Cond.empty())
349 return true;
351 assert(!FBB && "FBB should have been null.");
352 FBB = TBB;
353 TBB = I->getOperand(0).getMBB();
354 Cond.push_back(I->getOperand(1));
355 Cond.push_back(I->getOperand(2));
356 } else if (I->isReturn()) {
357 // Returns can't be analyzed, but we should run cleanup.
358 CantAnalyze = !isPredicated(*I);
359 } else {
360 // We encountered other unrecognized terminator. Bail out immediately.
361 return true;
364 // Cleanup code - to be run for unpredicated unconditional branches and
365 // returns.
366 if (!isPredicated(*I) &&
367 (isUncondBranchOpcode(I->getOpcode()) ||
368 isIndirectBranchOpcode(I->getOpcode()) ||
369 isJumpTableBranchOpcode(I->getOpcode()) ||
370 I->isReturn())) {
371 // Forget any previous condition branch information - it no longer applies.
372 Cond.clear();
373 FBB = nullptr;
375 // If we can modify the function, delete everything below this
376 // unconditional branch.
377 if (AllowModify) {
378 MachineBasicBlock::iterator DI = std::next(I);
379 while (DI != MBB.end()) {
380 MachineInstr &InstToDelete = *DI;
381 ++DI;
382 InstToDelete.eraseFromParent();
387 if (CantAnalyze)
388 return true;
390 if (I == MBB.begin())
391 return false;
393 --I;
396 // We made it past the terminators without bailing out - we must have
397 // analyzed this branch successfully.
398 return false;
401 unsigned ARMBaseInstrInfo::removeBranch(MachineBasicBlock &MBB,
402 int *BytesRemoved) const {
403 assert(!BytesRemoved && "code size not handled");
405 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
406 if (I == MBB.end())
407 return 0;
409 if (!isUncondBranchOpcode(I->getOpcode()) &&
410 !isCondBranchOpcode(I->getOpcode()))
411 return 0;
413 // Remove the branch.
414 I->eraseFromParent();
416 I = MBB.end();
418 if (I == MBB.begin()) return 1;
419 --I;
420 if (!isCondBranchOpcode(I->getOpcode()))
421 return 1;
423 // Remove the branch.
424 I->eraseFromParent();
425 return 2;
428 unsigned ARMBaseInstrInfo::insertBranch(MachineBasicBlock &MBB,
429 MachineBasicBlock *TBB,
430 MachineBasicBlock *FBB,
431 ArrayRef<MachineOperand> Cond,
432 const DebugLoc &DL,
433 int *BytesAdded) const {
434 assert(!BytesAdded && "code size not handled");
435 ARMFunctionInfo *AFI = MBB.getParent()->getInfo<ARMFunctionInfo>();
436 int BOpc = !AFI->isThumbFunction()
437 ? ARM::B : (AFI->isThumb2Function() ? ARM::t2B : ARM::tB);
438 int BccOpc = !AFI->isThumbFunction()
439 ? ARM::Bcc : (AFI->isThumb2Function() ? ARM::t2Bcc : ARM::tBcc);
440 bool isThumb = AFI->isThumbFunction() || AFI->isThumb2Function();
442 // Shouldn't be a fall through.
443 assert(TBB && "insertBranch must not be told to insert a fallthrough");
444 assert((Cond.size() == 2 || Cond.size() == 0) &&
445 "ARM branch conditions have two components!");
447 // For conditional branches, we use addOperand to preserve CPSR flags.
449 if (!FBB) {
450 if (Cond.empty()) { // Unconditional branch?
451 if (isThumb)
452 BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB).add(predOps(ARMCC::AL));
453 else
454 BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB);
455 } else
456 BuildMI(&MBB, DL, get(BccOpc))
457 .addMBB(TBB)
458 .addImm(Cond[0].getImm())
459 .add(Cond[1]);
460 return 1;
463 // Two-way conditional branch.
464 BuildMI(&MBB, DL, get(BccOpc))
465 .addMBB(TBB)
466 .addImm(Cond[0].getImm())
467 .add(Cond[1]);
468 if (isThumb)
469 BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB).add(predOps(ARMCC::AL));
470 else
471 BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB);
472 return 2;
475 bool ARMBaseInstrInfo::
476 reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
477 ARMCC::CondCodes CC = (ARMCC::CondCodes)(int)Cond[0].getImm();
478 Cond[0].setImm(ARMCC::getOppositeCondition(CC));
479 return false;
482 bool ARMBaseInstrInfo::isPredicated(const MachineInstr &MI) const {
483 if (MI.isBundle()) {
484 MachineBasicBlock::const_instr_iterator I = MI.getIterator();
485 MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
486 while (++I != E && I->isInsideBundle()) {
487 int PIdx = I->findFirstPredOperandIdx();
488 if (PIdx != -1 && I->getOperand(PIdx).getImm() != ARMCC::AL)
489 return true;
491 return false;
494 int PIdx = MI.findFirstPredOperandIdx();
495 return PIdx != -1 && MI.getOperand(PIdx).getImm() != ARMCC::AL;
498 bool ARMBaseInstrInfo::PredicateInstruction(
499 MachineInstr &MI, ArrayRef<MachineOperand> Pred) const {
500 unsigned Opc = MI.getOpcode();
501 if (isUncondBranchOpcode(Opc)) {
502 MI.setDesc(get(getMatchingCondBranchOpcode(Opc)));
503 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
504 .addImm(Pred[0].getImm())
505 .addReg(Pred[1].getReg());
506 return true;
509 int PIdx = MI.findFirstPredOperandIdx();
510 if (PIdx != -1) {
511 MachineOperand &PMO = MI.getOperand(PIdx);
512 PMO.setImm(Pred[0].getImm());
513 MI.getOperand(PIdx+1).setReg(Pred[1].getReg());
514 return true;
516 return false;
519 bool ARMBaseInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
520 ArrayRef<MachineOperand> Pred2) const {
521 if (Pred1.size() > 2 || Pred2.size() > 2)
522 return false;
524 ARMCC::CondCodes CC1 = (ARMCC::CondCodes)Pred1[0].getImm();
525 ARMCC::CondCodes CC2 = (ARMCC::CondCodes)Pred2[0].getImm();
526 if (CC1 == CC2)
527 return true;
529 switch (CC1) {
530 default:
531 return false;
532 case ARMCC::AL:
533 return true;
534 case ARMCC::HS:
535 return CC2 == ARMCC::HI;
536 case ARMCC::LS:
537 return CC2 == ARMCC::LO || CC2 == ARMCC::EQ;
538 case ARMCC::GE:
539 return CC2 == ARMCC::GT;
540 case ARMCC::LE:
541 return CC2 == ARMCC::LT;
545 bool ARMBaseInstrInfo::DefinesPredicate(
546 MachineInstr &MI, std::vector<MachineOperand> &Pred) const {
547 bool Found = false;
548 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
549 const MachineOperand &MO = MI.getOperand(i);
550 if ((MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) ||
551 (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR)) {
552 Pred.push_back(MO);
553 Found = true;
557 return Found;
560 bool ARMBaseInstrInfo::isCPSRDefined(const MachineInstr &MI) {
561 for (const auto &MO : MI.operands())
562 if (MO.isReg() && MO.getReg() == ARM::CPSR && MO.isDef() && !MO.isDead())
563 return true;
564 return false;
567 bool ARMBaseInstrInfo::isAddrMode3OpImm(const MachineInstr &MI,
568 unsigned Op) const {
569 const MachineOperand &Offset = MI.getOperand(Op + 1);
570 return Offset.getReg() != 0;
573 // Load with negative register offset requires additional 1cyc and +I unit
574 // for Cortex A57
575 bool ARMBaseInstrInfo::isAddrMode3OpMinusReg(const MachineInstr &MI,
576 unsigned Op) const {
577 const MachineOperand &Offset = MI.getOperand(Op + 1);
578 const MachineOperand &Opc = MI.getOperand(Op + 2);
579 assert(Opc.isImm());
580 assert(Offset.isReg());
581 int64_t OpcImm = Opc.getImm();
583 bool isSub = ARM_AM::getAM3Op(OpcImm) == ARM_AM::sub;
584 return (isSub && Offset.getReg() != 0);
587 bool ARMBaseInstrInfo::isLdstScaledReg(const MachineInstr &MI,
588 unsigned Op) const {
589 const MachineOperand &Opc = MI.getOperand(Op + 2);
590 unsigned OffImm = Opc.getImm();
591 return ARM_AM::getAM2ShiftOpc(OffImm) != ARM_AM::no_shift;
594 // Load, scaled register offset, not plus LSL2
595 bool ARMBaseInstrInfo::isLdstScaledRegNotPlusLsl2(const MachineInstr &MI,
596 unsigned Op) const {
597 const MachineOperand &Opc = MI.getOperand(Op + 2);
598 unsigned OffImm = Opc.getImm();
600 bool isAdd = ARM_AM::getAM2Op(OffImm) == ARM_AM::add;
601 unsigned Amt = ARM_AM::getAM2Offset(OffImm);
602 ARM_AM::ShiftOpc ShiftOpc = ARM_AM::getAM2ShiftOpc(OffImm);
603 if (ShiftOpc == ARM_AM::no_shift) return false; // not scaled
604 bool SimpleScaled = (isAdd && ShiftOpc == ARM_AM::lsl && Amt == 2);
605 return !SimpleScaled;
608 // Minus reg for ldstso addr mode
609 bool ARMBaseInstrInfo::isLdstSoMinusReg(const MachineInstr &MI,
610 unsigned Op) const {
611 unsigned OffImm = MI.getOperand(Op + 2).getImm();
612 return ARM_AM::getAM2Op(OffImm) == ARM_AM::sub;
615 // Load, scaled register offset
616 bool ARMBaseInstrInfo::isAm2ScaledReg(const MachineInstr &MI,
617 unsigned Op) const {
618 unsigned OffImm = MI.getOperand(Op + 2).getImm();
619 return ARM_AM::getAM2ShiftOpc(OffImm) != ARM_AM::no_shift;
622 static bool isEligibleForITBlock(const MachineInstr *MI) {
623 switch (MI->getOpcode()) {
624 default: return true;
625 case ARM::tADC: // ADC (register) T1
626 case ARM::tADDi3: // ADD (immediate) T1
627 case ARM::tADDi8: // ADD (immediate) T2
628 case ARM::tADDrr: // ADD (register) T1
629 case ARM::tAND: // AND (register) T1
630 case ARM::tASRri: // ASR (immediate) T1
631 case ARM::tASRrr: // ASR (register) T1
632 case ARM::tBIC: // BIC (register) T1
633 case ARM::tEOR: // EOR (register) T1
634 case ARM::tLSLri: // LSL (immediate) T1
635 case ARM::tLSLrr: // LSL (register) T1
636 case ARM::tLSRri: // LSR (immediate) T1
637 case ARM::tLSRrr: // LSR (register) T1
638 case ARM::tMUL: // MUL T1
639 case ARM::tMVN: // MVN (register) T1
640 case ARM::tORR: // ORR (register) T1
641 case ARM::tROR: // ROR (register) T1
642 case ARM::tRSB: // RSB (immediate) T1
643 case ARM::tSBC: // SBC (register) T1
644 case ARM::tSUBi3: // SUB (immediate) T1
645 case ARM::tSUBi8: // SUB (immediate) T2
646 case ARM::tSUBrr: // SUB (register) T1
647 return !ARMBaseInstrInfo::isCPSRDefined(*MI);
651 /// isPredicable - Return true if the specified instruction can be predicated.
652 /// By default, this returns true for every instruction with a
653 /// PredicateOperand.
654 bool ARMBaseInstrInfo::isPredicable(const MachineInstr &MI) const {
655 if (!MI.isPredicable())
656 return false;
658 if (MI.isBundle())
659 return false;
661 if (!isEligibleForITBlock(&MI))
662 return false;
664 const ARMFunctionInfo *AFI =
665 MI.getParent()->getParent()->getInfo<ARMFunctionInfo>();
667 // Neon instructions in Thumb2 IT blocks are deprecated, see ARMARM.
668 // In their ARM encoding, they can't be encoded in a conditional form.
669 if ((MI.getDesc().TSFlags & ARMII::DomainMask) == ARMII::DomainNEON)
670 return false;
672 if (AFI->isThumb2Function()) {
673 if (getSubtarget().restrictIT())
674 return isV8EligibleForIT(&MI);
677 return true;
680 namespace llvm {
682 template <> bool IsCPSRDead<MachineInstr>(const MachineInstr *MI) {
683 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
684 const MachineOperand &MO = MI->getOperand(i);
685 if (!MO.isReg() || MO.isUndef() || MO.isUse())
686 continue;
687 if (MO.getReg() != ARM::CPSR)
688 continue;
689 if (!MO.isDead())
690 return false;
692 // all definitions of CPSR are dead
693 return true;
696 } // end namespace llvm
698 /// GetInstSize - Return the size of the specified MachineInstr.
700 unsigned ARMBaseInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
701 const MachineBasicBlock &MBB = *MI.getParent();
702 const MachineFunction *MF = MBB.getParent();
703 const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
705 const MCInstrDesc &MCID = MI.getDesc();
706 if (MCID.getSize())
707 return MCID.getSize();
709 switch (MI.getOpcode()) {
710 default:
711 // pseudo-instruction sizes are zero.
712 return 0;
713 case TargetOpcode::BUNDLE:
714 return getInstBundleLength(MI);
715 case ARM::MOVi16_ga_pcrel:
716 case ARM::MOVTi16_ga_pcrel:
717 case ARM::t2MOVi16_ga_pcrel:
718 case ARM::t2MOVTi16_ga_pcrel:
719 return 4;
720 case ARM::MOVi32imm:
721 case ARM::t2MOVi32imm:
722 return 8;
723 case ARM::CONSTPOOL_ENTRY:
724 case ARM::JUMPTABLE_INSTS:
725 case ARM::JUMPTABLE_ADDRS:
726 case ARM::JUMPTABLE_TBB:
727 case ARM::JUMPTABLE_TBH:
728 // If this machine instr is a constant pool entry, its size is recorded as
729 // operand #2.
730 return MI.getOperand(2).getImm();
731 case ARM::Int_eh_sjlj_longjmp:
732 return 16;
733 case ARM::tInt_eh_sjlj_longjmp:
734 return 10;
735 case ARM::tInt_WIN_eh_sjlj_longjmp:
736 return 12;
737 case ARM::Int_eh_sjlj_setjmp:
738 case ARM::Int_eh_sjlj_setjmp_nofp:
739 return 20;
740 case ARM::tInt_eh_sjlj_setjmp:
741 case ARM::t2Int_eh_sjlj_setjmp:
742 case ARM::t2Int_eh_sjlj_setjmp_nofp:
743 return 12;
744 case ARM::SPACE:
745 return MI.getOperand(1).getImm();
746 case ARM::INLINEASM:
747 case ARM::INLINEASM_BR: {
748 // If this machine instr is an inline asm, measure it.
749 unsigned Size = getInlineAsmLength(MI.getOperand(0).getSymbolName(), *MAI);
750 if (!MF->getInfo<ARMFunctionInfo>()->isThumbFunction())
751 Size = alignTo(Size, 4);
752 return Size;
757 unsigned ARMBaseInstrInfo::getInstBundleLength(const MachineInstr &MI) const {
758 unsigned Size = 0;
759 MachineBasicBlock::const_instr_iterator I = MI.getIterator();
760 MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
761 while (++I != E && I->isInsideBundle()) {
762 assert(!I->isBundle() && "No nested bundle!");
763 Size += getInstSizeInBytes(*I);
765 return Size;
768 void ARMBaseInstrInfo::copyFromCPSR(MachineBasicBlock &MBB,
769 MachineBasicBlock::iterator I,
770 unsigned DestReg, bool KillSrc,
771 const ARMSubtarget &Subtarget) const {
772 unsigned Opc = Subtarget.isThumb()
773 ? (Subtarget.isMClass() ? ARM::t2MRS_M : ARM::t2MRS_AR)
774 : ARM::MRS;
776 MachineInstrBuilder MIB =
777 BuildMI(MBB, I, I->getDebugLoc(), get(Opc), DestReg);
779 // There is only 1 A/R class MRS instruction, and it always refers to
780 // APSR. However, there are lots of other possibilities on M-class cores.
781 if (Subtarget.isMClass())
782 MIB.addImm(0x800);
784 MIB.add(predOps(ARMCC::AL))
785 .addReg(ARM::CPSR, RegState::Implicit | getKillRegState(KillSrc));
788 void ARMBaseInstrInfo::copyToCPSR(MachineBasicBlock &MBB,
789 MachineBasicBlock::iterator I,
790 unsigned SrcReg, bool KillSrc,
791 const ARMSubtarget &Subtarget) const {
792 unsigned Opc = Subtarget.isThumb()
793 ? (Subtarget.isMClass() ? ARM::t2MSR_M : ARM::t2MSR_AR)
794 : ARM::MSR;
796 MachineInstrBuilder MIB = BuildMI(MBB, I, I->getDebugLoc(), get(Opc));
798 if (Subtarget.isMClass())
799 MIB.addImm(0x800);
800 else
801 MIB.addImm(8);
803 MIB.addReg(SrcReg, getKillRegState(KillSrc))
804 .add(predOps(ARMCC::AL))
805 .addReg(ARM::CPSR, RegState::Implicit | RegState::Define);
808 void llvm::addUnpredicatedMveVpredNOp(MachineInstrBuilder &MIB) {
809 MIB.addImm(ARMVCC::None);
810 MIB.addReg(0);
813 void llvm::addUnpredicatedMveVpredROp(MachineInstrBuilder &MIB,
814 unsigned DestReg) {
815 addUnpredicatedMveVpredNOp(MIB);
816 MIB.addReg(DestReg, RegState::Undef);
819 void llvm::addPredicatedMveVpredNOp(MachineInstrBuilder &MIB, unsigned Cond) {
820 MIB.addImm(Cond);
821 MIB.addReg(ARM::VPR, RegState::Implicit);
824 void llvm::addPredicatedMveVpredROp(MachineInstrBuilder &MIB,
825 unsigned Cond, unsigned Inactive) {
826 addPredicatedMveVpredNOp(MIB, Cond);
827 MIB.addReg(Inactive);
830 void ARMBaseInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
831 MachineBasicBlock::iterator I,
832 const DebugLoc &DL, unsigned DestReg,
833 unsigned SrcReg, bool KillSrc) const {
834 bool GPRDest = ARM::GPRRegClass.contains(DestReg);
835 bool GPRSrc = ARM::GPRRegClass.contains(SrcReg);
837 if (GPRDest && GPRSrc) {
838 BuildMI(MBB, I, DL, get(ARM::MOVr), DestReg)
839 .addReg(SrcReg, getKillRegState(KillSrc))
840 .add(predOps(ARMCC::AL))
841 .add(condCodeOp());
842 return;
845 bool SPRDest = ARM::SPRRegClass.contains(DestReg);
846 bool SPRSrc = ARM::SPRRegClass.contains(SrcReg);
848 unsigned Opc = 0;
849 if (SPRDest && SPRSrc)
850 Opc = ARM::VMOVS;
851 else if (GPRDest && SPRSrc)
852 Opc = ARM::VMOVRS;
853 else if (SPRDest && GPRSrc)
854 Opc = ARM::VMOVSR;
855 else if (ARM::DPRRegClass.contains(DestReg, SrcReg) && Subtarget.hasFP64())
856 Opc = ARM::VMOVD;
857 else if (ARM::QPRRegClass.contains(DestReg, SrcReg))
858 Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR;
860 if (Opc) {
861 MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opc), DestReg);
862 MIB.addReg(SrcReg, getKillRegState(KillSrc));
863 if (Opc == ARM::VORRq || Opc == ARM::MVE_VORR)
864 MIB.addReg(SrcReg, getKillRegState(KillSrc));
865 if (Opc == ARM::MVE_VORR)
866 addUnpredicatedMveVpredROp(MIB, DestReg);
867 else
868 MIB.add(predOps(ARMCC::AL));
869 return;
872 // Handle register classes that require multiple instructions.
873 unsigned BeginIdx = 0;
874 unsigned SubRegs = 0;
875 int Spacing = 1;
877 // Use VORRq when possible.
878 if (ARM::QQPRRegClass.contains(DestReg, SrcReg)) {
879 Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR;
880 BeginIdx = ARM::qsub_0;
881 SubRegs = 2;
882 } else if (ARM::QQQQPRRegClass.contains(DestReg, SrcReg)) {
883 Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR;
884 BeginIdx = ARM::qsub_0;
885 SubRegs = 4;
886 // Fall back to VMOVD.
887 } else if (ARM::DPairRegClass.contains(DestReg, SrcReg)) {
888 Opc = ARM::VMOVD;
889 BeginIdx = ARM::dsub_0;
890 SubRegs = 2;
891 } else if (ARM::DTripleRegClass.contains(DestReg, SrcReg)) {
892 Opc = ARM::VMOVD;
893 BeginIdx = ARM::dsub_0;
894 SubRegs = 3;
895 } else if (ARM::DQuadRegClass.contains(DestReg, SrcReg)) {
896 Opc = ARM::VMOVD;
897 BeginIdx = ARM::dsub_0;
898 SubRegs = 4;
899 } else if (ARM::GPRPairRegClass.contains(DestReg, SrcReg)) {
900 Opc = Subtarget.isThumb2() ? ARM::tMOVr : ARM::MOVr;
901 BeginIdx = ARM::gsub_0;
902 SubRegs = 2;
903 } else if (ARM::DPairSpcRegClass.contains(DestReg, SrcReg)) {
904 Opc = ARM::VMOVD;
905 BeginIdx = ARM::dsub_0;
906 SubRegs = 2;
907 Spacing = 2;
908 } else if (ARM::DTripleSpcRegClass.contains(DestReg, SrcReg)) {
909 Opc = ARM::VMOVD;
910 BeginIdx = ARM::dsub_0;
911 SubRegs = 3;
912 Spacing = 2;
913 } else if (ARM::DQuadSpcRegClass.contains(DestReg, SrcReg)) {
914 Opc = ARM::VMOVD;
915 BeginIdx = ARM::dsub_0;
916 SubRegs = 4;
917 Spacing = 2;
918 } else if (ARM::DPRRegClass.contains(DestReg, SrcReg) &&
919 !Subtarget.hasFP64()) {
920 Opc = ARM::VMOVS;
921 BeginIdx = ARM::ssub_0;
922 SubRegs = 2;
923 } else if (SrcReg == ARM::CPSR) {
924 copyFromCPSR(MBB, I, DestReg, KillSrc, Subtarget);
925 return;
926 } else if (DestReg == ARM::CPSR) {
927 copyToCPSR(MBB, I, SrcReg, KillSrc, Subtarget);
928 return;
929 } else if (DestReg == ARM::VPR) {
930 assert(ARM::GPRRegClass.contains(SrcReg));
931 BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMSR_P0), DestReg)
932 .addReg(SrcReg, getKillRegState(KillSrc))
933 .add(predOps(ARMCC::AL));
934 return;
935 } else if (SrcReg == ARM::VPR) {
936 assert(ARM::GPRRegClass.contains(DestReg));
937 BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMRS_P0), DestReg)
938 .addReg(SrcReg, getKillRegState(KillSrc))
939 .add(predOps(ARMCC::AL));
940 return;
941 } else if (DestReg == ARM::FPSCR_NZCV) {
942 assert(ARM::GPRRegClass.contains(SrcReg));
943 BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMSR_FPSCR_NZCVQC), DestReg)
944 .addReg(SrcReg, getKillRegState(KillSrc))
945 .add(predOps(ARMCC::AL));
946 return;
947 } else if (SrcReg == ARM::FPSCR_NZCV) {
948 assert(ARM::GPRRegClass.contains(DestReg));
949 BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMRS_FPSCR_NZCVQC), DestReg)
950 .addReg(SrcReg, getKillRegState(KillSrc))
951 .add(predOps(ARMCC::AL));
952 return;
955 assert(Opc && "Impossible reg-to-reg copy");
957 const TargetRegisterInfo *TRI = &getRegisterInfo();
958 MachineInstrBuilder Mov;
960 // Copy register tuples backward when the first Dest reg overlaps with SrcReg.
961 if (TRI->regsOverlap(SrcReg, TRI->getSubReg(DestReg, BeginIdx))) {
962 BeginIdx = BeginIdx + ((SubRegs - 1) * Spacing);
963 Spacing = -Spacing;
965 #ifndef NDEBUG
966 SmallSet<unsigned, 4> DstRegs;
967 #endif
968 for (unsigned i = 0; i != SubRegs; ++i) {
969 unsigned Dst = TRI->getSubReg(DestReg, BeginIdx + i * Spacing);
970 unsigned Src = TRI->getSubReg(SrcReg, BeginIdx + i * Spacing);
971 assert(Dst && Src && "Bad sub-register");
972 #ifndef NDEBUG
973 assert(!DstRegs.count(Src) && "destructive vector copy");
974 DstRegs.insert(Dst);
975 #endif
976 Mov = BuildMI(MBB, I, I->getDebugLoc(), get(Opc), Dst).addReg(Src);
977 // VORR (NEON or MVE) takes two source operands.
978 if (Opc == ARM::VORRq || Opc == ARM::MVE_VORR) {
979 Mov.addReg(Src);
981 // MVE VORR takes predicate operands in place of an ordinary condition.
982 if (Opc == ARM::MVE_VORR)
983 addUnpredicatedMveVpredROp(Mov, Dst);
984 else
985 Mov = Mov.add(predOps(ARMCC::AL));
986 // MOVr can set CC.
987 if (Opc == ARM::MOVr)
988 Mov = Mov.add(condCodeOp());
990 // Add implicit super-register defs and kills to the last instruction.
991 Mov->addRegisterDefined(DestReg, TRI);
992 if (KillSrc)
993 Mov->addRegisterKilled(SrcReg, TRI);
996 bool ARMBaseInstrInfo::isCopyInstrImpl(const MachineInstr &MI,
997 const MachineOperand *&Src,
998 const MachineOperand *&Dest) const {
999 // VMOVRRD is also a copy instruction but it requires
1000 // special way of handling. It is more complex copy version
1001 // and since that we are not considering it. For recognition
1002 // of such instruction isExtractSubregLike MI interface fuction
1003 // could be used.
1004 // VORRq is considered as a move only if two inputs are
1005 // the same register.
1006 if (!MI.isMoveReg() ||
1007 (MI.getOpcode() == ARM::VORRq &&
1008 MI.getOperand(1).getReg() != MI.getOperand(2).getReg()))
1009 return false;
1010 Dest = &MI.getOperand(0);
1011 Src = &MI.getOperand(1);
1012 return true;
1015 const MachineInstrBuilder &
1016 ARMBaseInstrInfo::AddDReg(MachineInstrBuilder &MIB, unsigned Reg,
1017 unsigned SubIdx, unsigned State,
1018 const TargetRegisterInfo *TRI) const {
1019 if (!SubIdx)
1020 return MIB.addReg(Reg, State);
1022 if (Register::isPhysicalRegister(Reg))
1023 return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
1024 return MIB.addReg(Reg, State, SubIdx);
1027 void ARMBaseInstrInfo::
1028 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
1029 unsigned SrcReg, bool isKill, int FI,
1030 const TargetRegisterClass *RC,
1031 const TargetRegisterInfo *TRI) const {
1032 MachineFunction &MF = *MBB.getParent();
1033 MachineFrameInfo &MFI = MF.getFrameInfo();
1034 unsigned Align = MFI.getObjectAlignment(FI);
1036 MachineMemOperand *MMO = MF.getMachineMemOperand(
1037 MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOStore,
1038 MFI.getObjectSize(FI), Align);
1040 switch (TRI->getSpillSize(*RC)) {
1041 case 2:
1042 if (ARM::HPRRegClass.hasSubClassEq(RC)) {
1043 BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRH))
1044 .addReg(SrcReg, getKillRegState(isKill))
1045 .addFrameIndex(FI)
1046 .addImm(0)
1047 .addMemOperand(MMO)
1048 .add(predOps(ARMCC::AL));
1049 } else
1050 llvm_unreachable("Unknown reg class!");
1051 break;
1052 case 4:
1053 if (ARM::GPRRegClass.hasSubClassEq(RC)) {
1054 BuildMI(MBB, I, DebugLoc(), get(ARM::STRi12))
1055 .addReg(SrcReg, getKillRegState(isKill))
1056 .addFrameIndex(FI)
1057 .addImm(0)
1058 .addMemOperand(MMO)
1059 .add(predOps(ARMCC::AL));
1060 } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
1061 BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRS))
1062 .addReg(SrcReg, getKillRegState(isKill))
1063 .addFrameIndex(FI)
1064 .addImm(0)
1065 .addMemOperand(MMO)
1066 .add(predOps(ARMCC::AL));
1067 } else if (ARM::VCCRRegClass.hasSubClassEq(RC)) {
1068 BuildMI(MBB, I, DebugLoc(), get(ARM::VSTR_P0_off))
1069 .addReg(SrcReg, getKillRegState(isKill))
1070 .addFrameIndex(FI)
1071 .addImm(0)
1072 .addMemOperand(MMO)
1073 .add(predOps(ARMCC::AL));
1074 } else
1075 llvm_unreachable("Unknown reg class!");
1076 break;
1077 case 8:
1078 if (ARM::DPRRegClass.hasSubClassEq(RC)) {
1079 BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRD))
1080 .addReg(SrcReg, getKillRegState(isKill))
1081 .addFrameIndex(FI)
1082 .addImm(0)
1083 .addMemOperand(MMO)
1084 .add(predOps(ARMCC::AL));
1085 } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) {
1086 if (Subtarget.hasV5TEOps()) {
1087 MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::STRD));
1088 AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI);
1089 AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI);
1090 MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO)
1091 .add(predOps(ARMCC::AL));
1092 } else {
1093 // Fallback to STM instruction, which has existed since the dawn of
1094 // time.
1095 MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::STMIA))
1096 .addFrameIndex(FI)
1097 .addMemOperand(MMO)
1098 .add(predOps(ARMCC::AL));
1099 AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI);
1100 AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI);
1102 } else
1103 llvm_unreachable("Unknown reg class!");
1104 break;
1105 case 16:
1106 if (ARM::DPairRegClass.hasSubClassEq(RC) && Subtarget.hasNEON()) {
1107 // Use aligned spills if the stack can be realigned.
1108 if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
1109 BuildMI(MBB, I, DebugLoc(), get(ARM::VST1q64))
1110 .addFrameIndex(FI)
1111 .addImm(16)
1112 .addReg(SrcReg, getKillRegState(isKill))
1113 .addMemOperand(MMO)
1114 .add(predOps(ARMCC::AL));
1115 } else {
1116 BuildMI(MBB, I, DebugLoc(), get(ARM::VSTMQIA))
1117 .addReg(SrcReg, getKillRegState(isKill))
1118 .addFrameIndex(FI)
1119 .addMemOperand(MMO)
1120 .add(predOps(ARMCC::AL));
1122 } else if (ARM::QPRRegClass.hasSubClassEq(RC) &&
1123 Subtarget.hasMVEIntegerOps()) {
1124 auto MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::MVE_VSTRWU32));
1125 MIB.addReg(SrcReg, getKillRegState(isKill))
1126 .addFrameIndex(FI)
1127 .addImm(0)
1128 .addMemOperand(MMO);
1129 addUnpredicatedMveVpredNOp(MIB);
1130 } else
1131 llvm_unreachable("Unknown reg class!");
1132 break;
1133 case 24:
1134 if (ARM::DTripleRegClass.hasSubClassEq(RC)) {
1135 // Use aligned spills if the stack can be realigned.
1136 if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
1137 BuildMI(MBB, I, DebugLoc(), get(ARM::VST1d64TPseudo))
1138 .addFrameIndex(FI)
1139 .addImm(16)
1140 .addReg(SrcReg, getKillRegState(isKill))
1141 .addMemOperand(MMO)
1142 .add(predOps(ARMCC::AL));
1143 } else {
1144 MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(),
1145 get(ARM::VSTMDIA))
1146 .addFrameIndex(FI)
1147 .add(predOps(ARMCC::AL))
1148 .addMemOperand(MMO);
1149 MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
1150 MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
1151 AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
1153 } else
1154 llvm_unreachable("Unknown reg class!");
1155 break;
1156 case 32:
1157 if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) {
1158 if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
1159 // FIXME: It's possible to only store part of the QQ register if the
1160 // spilled def has a sub-register index.
1161 BuildMI(MBB, I, DebugLoc(), get(ARM::VST1d64QPseudo))
1162 .addFrameIndex(FI)
1163 .addImm(16)
1164 .addReg(SrcReg, getKillRegState(isKill))
1165 .addMemOperand(MMO)
1166 .add(predOps(ARMCC::AL));
1167 } else {
1168 MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(),
1169 get(ARM::VSTMDIA))
1170 .addFrameIndex(FI)
1171 .add(predOps(ARMCC::AL))
1172 .addMemOperand(MMO);
1173 MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
1174 MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
1175 MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
1176 AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
1178 } else
1179 llvm_unreachable("Unknown reg class!");
1180 break;
1181 case 64:
1182 if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
1183 MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::VSTMDIA))
1184 .addFrameIndex(FI)
1185 .add(predOps(ARMCC::AL))
1186 .addMemOperand(MMO);
1187 MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
1188 MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
1189 MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
1190 MIB = AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
1191 MIB = AddDReg(MIB, SrcReg, ARM::dsub_4, 0, TRI);
1192 MIB = AddDReg(MIB, SrcReg, ARM::dsub_5, 0, TRI);
1193 MIB = AddDReg(MIB, SrcReg, ARM::dsub_6, 0, TRI);
1194 AddDReg(MIB, SrcReg, ARM::dsub_7, 0, TRI);
1195 } else
1196 llvm_unreachable("Unknown reg class!");
1197 break;
1198 default:
1199 llvm_unreachable("Unknown reg class!");
1203 unsigned ARMBaseInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
1204 int &FrameIndex) const {
1205 switch (MI.getOpcode()) {
1206 default: break;
1207 case ARM::STRrs:
1208 case ARM::t2STRs: // FIXME: don't use t2STRs to access frame.
1209 if (MI.getOperand(1).isFI() && MI.getOperand(2).isReg() &&
1210 MI.getOperand(3).isImm() && MI.getOperand(2).getReg() == 0 &&
1211 MI.getOperand(3).getImm() == 0) {
1212 FrameIndex = MI.getOperand(1).getIndex();
1213 return MI.getOperand(0).getReg();
1215 break;
1216 case ARM::STRi12:
1217 case ARM::t2STRi12:
1218 case ARM::tSTRspi:
1219 case ARM::VSTRD:
1220 case ARM::VSTRS:
1221 if (MI.getOperand(1).isFI() && MI.getOperand(2).isImm() &&
1222 MI.getOperand(2).getImm() == 0) {
1223 FrameIndex = MI.getOperand(1).getIndex();
1224 return MI.getOperand(0).getReg();
1226 break;
1227 case ARM::VSTR_P0_off:
1228 if (MI.getOperand(0).isFI() && MI.getOperand(1).isImm() &&
1229 MI.getOperand(1).getImm() == 0) {
1230 FrameIndex = MI.getOperand(0).getIndex();
1231 return ARM::P0;
1233 break;
1234 case ARM::VST1q64:
1235 case ARM::VST1d64TPseudo:
1236 case ARM::VST1d64QPseudo:
1237 if (MI.getOperand(0).isFI() && MI.getOperand(2).getSubReg() == 0) {
1238 FrameIndex = MI.getOperand(0).getIndex();
1239 return MI.getOperand(2).getReg();
1241 break;
1242 case ARM::VSTMQIA:
1243 if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) {
1244 FrameIndex = MI.getOperand(1).getIndex();
1245 return MI.getOperand(0).getReg();
1247 break;
1250 return 0;
1253 unsigned ARMBaseInstrInfo::isStoreToStackSlotPostFE(const MachineInstr &MI,
1254 int &FrameIndex) const {
1255 SmallVector<const MachineMemOperand *, 1> Accesses;
1256 if (MI.mayStore() && hasStoreToStackSlot(MI, Accesses) &&
1257 Accesses.size() == 1) {
1258 FrameIndex =
1259 cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
1260 ->getFrameIndex();
1261 return true;
1263 return false;
1266 void ARMBaseInstrInfo::
1267 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
1268 unsigned DestReg, int FI,
1269 const TargetRegisterClass *RC,
1270 const TargetRegisterInfo *TRI) const {
1271 DebugLoc DL;
1272 if (I != MBB.end()) DL = I->getDebugLoc();
1273 MachineFunction &MF = *MBB.getParent();
1274 MachineFrameInfo &MFI = MF.getFrameInfo();
1275 unsigned Align = MFI.getObjectAlignment(FI);
1276 MachineMemOperand *MMO = MF.getMachineMemOperand(
1277 MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOLoad,
1278 MFI.getObjectSize(FI), Align);
1280 switch (TRI->getSpillSize(*RC)) {
1281 case 2:
1282 if (ARM::HPRRegClass.hasSubClassEq(RC)) {
1283 BuildMI(MBB, I, DL, get(ARM::VLDRH), DestReg)
1284 .addFrameIndex(FI)
1285 .addImm(0)
1286 .addMemOperand(MMO)
1287 .add(predOps(ARMCC::AL));
1288 } else
1289 llvm_unreachable("Unknown reg class!");
1290 break;
1291 case 4:
1292 if (ARM::GPRRegClass.hasSubClassEq(RC)) {
1293 BuildMI(MBB, I, DL, get(ARM::LDRi12), DestReg)
1294 .addFrameIndex(FI)
1295 .addImm(0)
1296 .addMemOperand(MMO)
1297 .add(predOps(ARMCC::AL));
1298 } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
1299 BuildMI(MBB, I, DL, get(ARM::VLDRS), DestReg)
1300 .addFrameIndex(FI)
1301 .addImm(0)
1302 .addMemOperand(MMO)
1303 .add(predOps(ARMCC::AL));
1304 } else if (ARM::VCCRRegClass.hasSubClassEq(RC)) {
1305 BuildMI(MBB, I, DL, get(ARM::VLDR_P0_off), DestReg)
1306 .addFrameIndex(FI)
1307 .addImm(0)
1308 .addMemOperand(MMO)
1309 .add(predOps(ARMCC::AL));
1310 } else
1311 llvm_unreachable("Unknown reg class!");
1312 break;
1313 case 8:
1314 if (ARM::DPRRegClass.hasSubClassEq(RC)) {
1315 BuildMI(MBB, I, DL, get(ARM::VLDRD), DestReg)
1316 .addFrameIndex(FI)
1317 .addImm(0)
1318 .addMemOperand(MMO)
1319 .add(predOps(ARMCC::AL));
1320 } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) {
1321 MachineInstrBuilder MIB;
1323 if (Subtarget.hasV5TEOps()) {
1324 MIB = BuildMI(MBB, I, DL, get(ARM::LDRD));
1325 AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI);
1326 AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI);
1327 MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO)
1328 .add(predOps(ARMCC::AL));
1329 } else {
1330 // Fallback to LDM instruction, which has existed since the dawn of
1331 // time.
1332 MIB = BuildMI(MBB, I, DL, get(ARM::LDMIA))
1333 .addFrameIndex(FI)
1334 .addMemOperand(MMO)
1335 .add(predOps(ARMCC::AL));
1336 MIB = AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI);
1337 MIB = AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI);
1340 if (Register::isPhysicalRegister(DestReg))
1341 MIB.addReg(DestReg, RegState::ImplicitDefine);
1342 } else
1343 llvm_unreachable("Unknown reg class!");
1344 break;
1345 case 16:
1346 if (ARM::DPairRegClass.hasSubClassEq(RC) && Subtarget.hasNEON()) {
1347 if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
1348 BuildMI(MBB, I, DL, get(ARM::VLD1q64), DestReg)
1349 .addFrameIndex(FI)
1350 .addImm(16)
1351 .addMemOperand(MMO)
1352 .add(predOps(ARMCC::AL));
1353 } else {
1354 BuildMI(MBB, I, DL, get(ARM::VLDMQIA), DestReg)
1355 .addFrameIndex(FI)
1356 .addMemOperand(MMO)
1357 .add(predOps(ARMCC::AL));
1359 } else if (ARM::QPRRegClass.hasSubClassEq(RC) &&
1360 Subtarget.hasMVEIntegerOps()) {
1361 auto MIB = BuildMI(MBB, I, DL, get(ARM::MVE_VLDRWU32), DestReg);
1362 MIB.addFrameIndex(FI)
1363 .addImm(0)
1364 .addMemOperand(MMO);
1365 addUnpredicatedMveVpredNOp(MIB);
1366 } else
1367 llvm_unreachable("Unknown reg class!");
1368 break;
1369 case 24:
1370 if (ARM::DTripleRegClass.hasSubClassEq(RC)) {
1371 if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
1372 BuildMI(MBB, I, DL, get(ARM::VLD1d64TPseudo), DestReg)
1373 .addFrameIndex(FI)
1374 .addImm(16)
1375 .addMemOperand(MMO)
1376 .add(predOps(ARMCC::AL));
1377 } else {
1378 MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1379 .addFrameIndex(FI)
1380 .addMemOperand(MMO)
1381 .add(predOps(ARMCC::AL));
1382 MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1383 MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1384 MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1385 if (Register::isPhysicalRegister(DestReg))
1386 MIB.addReg(DestReg, RegState::ImplicitDefine);
1388 } else
1389 llvm_unreachable("Unknown reg class!");
1390 break;
1391 case 32:
1392 if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) {
1393 if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
1394 BuildMI(MBB, I, DL, get(ARM::VLD1d64QPseudo), DestReg)
1395 .addFrameIndex(FI)
1396 .addImm(16)
1397 .addMemOperand(MMO)
1398 .add(predOps(ARMCC::AL));
1399 } else {
1400 MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1401 .addFrameIndex(FI)
1402 .add(predOps(ARMCC::AL))
1403 .addMemOperand(MMO);
1404 MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1405 MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1406 MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1407 MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI);
1408 if (Register::isPhysicalRegister(DestReg))
1409 MIB.addReg(DestReg, RegState::ImplicitDefine);
1411 } else
1412 llvm_unreachable("Unknown reg class!");
1413 break;
1414 case 64:
1415 if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
1416 MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1417 .addFrameIndex(FI)
1418 .add(predOps(ARMCC::AL))
1419 .addMemOperand(MMO);
1420 MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1421 MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1422 MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1423 MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI);
1424 MIB = AddDReg(MIB, DestReg, ARM::dsub_4, RegState::DefineNoRead, TRI);
1425 MIB = AddDReg(MIB, DestReg, ARM::dsub_5, RegState::DefineNoRead, TRI);
1426 MIB = AddDReg(MIB, DestReg, ARM::dsub_6, RegState::DefineNoRead, TRI);
1427 MIB = AddDReg(MIB, DestReg, ARM::dsub_7, RegState::DefineNoRead, TRI);
1428 if (Register::isPhysicalRegister(DestReg))
1429 MIB.addReg(DestReg, RegState::ImplicitDefine);
1430 } else
1431 llvm_unreachable("Unknown reg class!");
1432 break;
1433 default:
1434 llvm_unreachable("Unknown regclass!");
1438 unsigned ARMBaseInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
1439 int &FrameIndex) const {
1440 switch (MI.getOpcode()) {
1441 default: break;
1442 case ARM::LDRrs:
1443 case ARM::t2LDRs: // FIXME: don't use t2LDRs to access frame.
1444 if (MI.getOperand(1).isFI() && MI.getOperand(2).isReg() &&
1445 MI.getOperand(3).isImm() && MI.getOperand(2).getReg() == 0 &&
1446 MI.getOperand(3).getImm() == 0) {
1447 FrameIndex = MI.getOperand(1).getIndex();
1448 return MI.getOperand(0).getReg();
1450 break;
1451 case ARM::LDRi12:
1452 case ARM::t2LDRi12:
1453 case ARM::tLDRspi:
1454 case ARM::VLDRD:
1455 case ARM::VLDRS:
1456 if (MI.getOperand(1).isFI() && MI.getOperand(2).isImm() &&
1457 MI.getOperand(2).getImm() == 0) {
1458 FrameIndex = MI.getOperand(1).getIndex();
1459 return MI.getOperand(0).getReg();
1461 break;
1462 case ARM::VLDR_P0_off:
1463 if (MI.getOperand(0).isFI() && MI.getOperand(1).isImm() &&
1464 MI.getOperand(1).getImm() == 0) {
1465 FrameIndex = MI.getOperand(0).getIndex();
1466 return ARM::P0;
1468 break;
1469 case ARM::VLD1q64:
1470 case ARM::VLD1d8TPseudo:
1471 case ARM::VLD1d16TPseudo:
1472 case ARM::VLD1d32TPseudo:
1473 case ARM::VLD1d64TPseudo:
1474 case ARM::VLD1d8QPseudo:
1475 case ARM::VLD1d16QPseudo:
1476 case ARM::VLD1d32QPseudo:
1477 case ARM::VLD1d64QPseudo:
1478 if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) {
1479 FrameIndex = MI.getOperand(1).getIndex();
1480 return MI.getOperand(0).getReg();
1482 break;
1483 case ARM::VLDMQIA:
1484 if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) {
1485 FrameIndex = MI.getOperand(1).getIndex();
1486 return MI.getOperand(0).getReg();
1488 break;
1491 return 0;
1494 unsigned ARMBaseInstrInfo::isLoadFromStackSlotPostFE(const MachineInstr &MI,
1495 int &FrameIndex) const {
1496 SmallVector<const MachineMemOperand *, 1> Accesses;
1497 if (MI.mayLoad() && hasLoadFromStackSlot(MI, Accesses) &&
1498 Accesses.size() == 1) {
1499 FrameIndex =
1500 cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
1501 ->getFrameIndex();
1502 return true;
1504 return false;
1507 /// Expands MEMCPY to either LDMIA/STMIA or LDMIA_UPD/STMID_UPD
1508 /// depending on whether the result is used.
1509 void ARMBaseInstrInfo::expandMEMCPY(MachineBasicBlock::iterator MI) const {
1510 bool isThumb1 = Subtarget.isThumb1Only();
1511 bool isThumb2 = Subtarget.isThumb2();
1512 const ARMBaseInstrInfo *TII = Subtarget.getInstrInfo();
1514 DebugLoc dl = MI->getDebugLoc();
1515 MachineBasicBlock *BB = MI->getParent();
1517 MachineInstrBuilder LDM, STM;
1518 if (isThumb1 || !MI->getOperand(1).isDead()) {
1519 MachineOperand LDWb(MI->getOperand(1));
1520 LDM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2LDMIA_UPD
1521 : isThumb1 ? ARM::tLDMIA_UPD
1522 : ARM::LDMIA_UPD))
1523 .add(LDWb);
1524 } else {
1525 LDM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2LDMIA : ARM::LDMIA));
1528 if (isThumb1 || !MI->getOperand(0).isDead()) {
1529 MachineOperand STWb(MI->getOperand(0));
1530 STM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2STMIA_UPD
1531 : isThumb1 ? ARM::tSTMIA_UPD
1532 : ARM::STMIA_UPD))
1533 .add(STWb);
1534 } else {
1535 STM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2STMIA : ARM::STMIA));
1538 MachineOperand LDBase(MI->getOperand(3));
1539 LDM.add(LDBase).add(predOps(ARMCC::AL));
1541 MachineOperand STBase(MI->getOperand(2));
1542 STM.add(STBase).add(predOps(ARMCC::AL));
1544 // Sort the scratch registers into ascending order.
1545 const TargetRegisterInfo &TRI = getRegisterInfo();
1546 SmallVector<unsigned, 6> ScratchRegs;
1547 for(unsigned I = 5; I < MI->getNumOperands(); ++I)
1548 ScratchRegs.push_back(MI->getOperand(I).getReg());
1549 llvm::sort(ScratchRegs,
1550 [&TRI](const unsigned &Reg1, const unsigned &Reg2) -> bool {
1551 return TRI.getEncodingValue(Reg1) <
1552 TRI.getEncodingValue(Reg2);
1555 for (const auto &Reg : ScratchRegs) {
1556 LDM.addReg(Reg, RegState::Define);
1557 STM.addReg(Reg, RegState::Kill);
1560 BB->erase(MI);
1563 bool ARMBaseInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
1564 if (MI.getOpcode() == TargetOpcode::LOAD_STACK_GUARD) {
1565 assert(getSubtarget().getTargetTriple().isOSBinFormatMachO() &&
1566 "LOAD_STACK_GUARD currently supported only for MachO.");
1567 expandLoadStackGuard(MI);
1568 MI.getParent()->erase(MI);
1569 return true;
1572 if (MI.getOpcode() == ARM::MEMCPY) {
1573 expandMEMCPY(MI);
1574 return true;
1577 // This hook gets to expand COPY instructions before they become
1578 // copyPhysReg() calls. Look for VMOVS instructions that can legally be
1579 // widened to VMOVD. We prefer the VMOVD when possible because it may be
1580 // changed into a VORR that can go down the NEON pipeline.
1581 if (!MI.isCopy() || Subtarget.dontWidenVMOVS() || !Subtarget.hasFP64())
1582 return false;
1584 // Look for a copy between even S-registers. That is where we keep floats
1585 // when using NEON v2f32 instructions for f32 arithmetic.
1586 unsigned DstRegS = MI.getOperand(0).getReg();
1587 unsigned SrcRegS = MI.getOperand(1).getReg();
1588 if (!ARM::SPRRegClass.contains(DstRegS, SrcRegS))
1589 return false;
1591 const TargetRegisterInfo *TRI = &getRegisterInfo();
1592 unsigned DstRegD = TRI->getMatchingSuperReg(DstRegS, ARM::ssub_0,
1593 &ARM::DPRRegClass);
1594 unsigned SrcRegD = TRI->getMatchingSuperReg(SrcRegS, ARM::ssub_0,
1595 &ARM::DPRRegClass);
1596 if (!DstRegD || !SrcRegD)
1597 return false;
1599 // We want to widen this into a DstRegD = VMOVD SrcRegD copy. This is only
1600 // legal if the COPY already defines the full DstRegD, and it isn't a
1601 // sub-register insertion.
1602 if (!MI.definesRegister(DstRegD, TRI) || MI.readsRegister(DstRegD, TRI))
1603 return false;
1605 // A dead copy shouldn't show up here, but reject it just in case.
1606 if (MI.getOperand(0).isDead())
1607 return false;
1609 // All clear, widen the COPY.
1610 LLVM_DEBUG(dbgs() << "widening: " << MI);
1611 MachineInstrBuilder MIB(*MI.getParent()->getParent(), MI);
1613 // Get rid of the old implicit-def of DstRegD. Leave it if it defines a Q-reg
1614 // or some other super-register.
1615 int ImpDefIdx = MI.findRegisterDefOperandIdx(DstRegD);
1616 if (ImpDefIdx != -1)
1617 MI.RemoveOperand(ImpDefIdx);
1619 // Change the opcode and operands.
1620 MI.setDesc(get(ARM::VMOVD));
1621 MI.getOperand(0).setReg(DstRegD);
1622 MI.getOperand(1).setReg(SrcRegD);
1623 MIB.add(predOps(ARMCC::AL));
1625 // We are now reading SrcRegD instead of SrcRegS. This may upset the
1626 // register scavenger and machine verifier, so we need to indicate that we
1627 // are reading an undefined value from SrcRegD, but a proper value from
1628 // SrcRegS.
1629 MI.getOperand(1).setIsUndef();
1630 MIB.addReg(SrcRegS, RegState::Implicit);
1632 // SrcRegD may actually contain an unrelated value in the ssub_1
1633 // sub-register. Don't kill it. Only kill the ssub_0 sub-register.
1634 if (MI.getOperand(1).isKill()) {
1635 MI.getOperand(1).setIsKill(false);
1636 MI.addRegisterKilled(SrcRegS, TRI, true);
1639 LLVM_DEBUG(dbgs() << "replaced by: " << MI);
1640 return true;
1643 /// Create a copy of a const pool value. Update CPI to the new index and return
1644 /// the label UID.
1645 static unsigned duplicateCPV(MachineFunction &MF, unsigned &CPI) {
1646 MachineConstantPool *MCP = MF.getConstantPool();
1647 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1649 const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
1650 assert(MCPE.isMachineConstantPoolEntry() &&
1651 "Expecting a machine constantpool entry!");
1652 ARMConstantPoolValue *ACPV =
1653 static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
1655 unsigned PCLabelId = AFI->createPICLabelUId();
1656 ARMConstantPoolValue *NewCPV = nullptr;
1658 // FIXME: The below assumes PIC relocation model and that the function
1659 // is Thumb mode (t1 or t2). PCAdjustment would be 8 for ARM mode PIC, and
1660 // zero for non-PIC in ARM or Thumb. The callers are all of thumb LDR
1661 // instructions, so that's probably OK, but is PIC always correct when
1662 // we get here?
1663 if (ACPV->isGlobalValue())
1664 NewCPV = ARMConstantPoolConstant::Create(
1665 cast<ARMConstantPoolConstant>(ACPV)->getGV(), PCLabelId, ARMCP::CPValue,
1666 4, ACPV->getModifier(), ACPV->mustAddCurrentAddress());
1667 else if (ACPV->isExtSymbol())
1668 NewCPV = ARMConstantPoolSymbol::
1669 Create(MF.getFunction().getContext(),
1670 cast<ARMConstantPoolSymbol>(ACPV)->getSymbol(), PCLabelId, 4);
1671 else if (ACPV->isBlockAddress())
1672 NewCPV = ARMConstantPoolConstant::
1673 Create(cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress(), PCLabelId,
1674 ARMCP::CPBlockAddress, 4);
1675 else if (ACPV->isLSDA())
1676 NewCPV = ARMConstantPoolConstant::Create(&MF.getFunction(), PCLabelId,
1677 ARMCP::CPLSDA, 4);
1678 else if (ACPV->isMachineBasicBlock())
1679 NewCPV = ARMConstantPoolMBB::
1680 Create(MF.getFunction().getContext(),
1681 cast<ARMConstantPoolMBB>(ACPV)->getMBB(), PCLabelId, 4);
1682 else
1683 llvm_unreachable("Unexpected ARM constantpool value type!!");
1684 CPI = MCP->getConstantPoolIndex(NewCPV, MCPE.getAlignment());
1685 return PCLabelId;
1688 void ARMBaseInstrInfo::reMaterialize(MachineBasicBlock &MBB,
1689 MachineBasicBlock::iterator I,
1690 unsigned DestReg, unsigned SubIdx,
1691 const MachineInstr &Orig,
1692 const TargetRegisterInfo &TRI) const {
1693 unsigned Opcode = Orig.getOpcode();
1694 switch (Opcode) {
1695 default: {
1696 MachineInstr *MI = MBB.getParent()->CloneMachineInstr(&Orig);
1697 MI->substituteRegister(Orig.getOperand(0).getReg(), DestReg, SubIdx, TRI);
1698 MBB.insert(I, MI);
1699 break;
1701 case ARM::tLDRpci_pic:
1702 case ARM::t2LDRpci_pic: {
1703 MachineFunction &MF = *MBB.getParent();
1704 unsigned CPI = Orig.getOperand(1).getIndex();
1705 unsigned PCLabelId = duplicateCPV(MF, CPI);
1706 BuildMI(MBB, I, Orig.getDebugLoc(), get(Opcode), DestReg)
1707 .addConstantPoolIndex(CPI)
1708 .addImm(PCLabelId)
1709 .cloneMemRefs(Orig);
1710 break;
1715 MachineInstr &
1716 ARMBaseInstrInfo::duplicate(MachineBasicBlock &MBB,
1717 MachineBasicBlock::iterator InsertBefore,
1718 const MachineInstr &Orig) const {
1719 MachineInstr &Cloned = TargetInstrInfo::duplicate(MBB, InsertBefore, Orig);
1720 MachineBasicBlock::instr_iterator I = Cloned.getIterator();
1721 for (;;) {
1722 switch (I->getOpcode()) {
1723 case ARM::tLDRpci_pic:
1724 case ARM::t2LDRpci_pic: {
1725 MachineFunction &MF = *MBB.getParent();
1726 unsigned CPI = I->getOperand(1).getIndex();
1727 unsigned PCLabelId = duplicateCPV(MF, CPI);
1728 I->getOperand(1).setIndex(CPI);
1729 I->getOperand(2).setImm(PCLabelId);
1730 break;
1733 if (!I->isBundledWithSucc())
1734 break;
1735 ++I;
1737 return Cloned;
1740 bool ARMBaseInstrInfo::produceSameValue(const MachineInstr &MI0,
1741 const MachineInstr &MI1,
1742 const MachineRegisterInfo *MRI) const {
1743 unsigned Opcode = MI0.getOpcode();
1744 if (Opcode == ARM::t2LDRpci ||
1745 Opcode == ARM::t2LDRpci_pic ||
1746 Opcode == ARM::tLDRpci ||
1747 Opcode == ARM::tLDRpci_pic ||
1748 Opcode == ARM::LDRLIT_ga_pcrel ||
1749 Opcode == ARM::LDRLIT_ga_pcrel_ldr ||
1750 Opcode == ARM::tLDRLIT_ga_pcrel ||
1751 Opcode == ARM::MOV_ga_pcrel ||
1752 Opcode == ARM::MOV_ga_pcrel_ldr ||
1753 Opcode == ARM::t2MOV_ga_pcrel) {
1754 if (MI1.getOpcode() != Opcode)
1755 return false;
1756 if (MI0.getNumOperands() != MI1.getNumOperands())
1757 return false;
1759 const MachineOperand &MO0 = MI0.getOperand(1);
1760 const MachineOperand &MO1 = MI1.getOperand(1);
1761 if (MO0.getOffset() != MO1.getOffset())
1762 return false;
1764 if (Opcode == ARM::LDRLIT_ga_pcrel ||
1765 Opcode == ARM::LDRLIT_ga_pcrel_ldr ||
1766 Opcode == ARM::tLDRLIT_ga_pcrel ||
1767 Opcode == ARM::MOV_ga_pcrel ||
1768 Opcode == ARM::MOV_ga_pcrel_ldr ||
1769 Opcode == ARM::t2MOV_ga_pcrel)
1770 // Ignore the PC labels.
1771 return MO0.getGlobal() == MO1.getGlobal();
1773 const MachineFunction *MF = MI0.getParent()->getParent();
1774 const MachineConstantPool *MCP = MF->getConstantPool();
1775 int CPI0 = MO0.getIndex();
1776 int CPI1 = MO1.getIndex();
1777 const MachineConstantPoolEntry &MCPE0 = MCP->getConstants()[CPI0];
1778 const MachineConstantPoolEntry &MCPE1 = MCP->getConstants()[CPI1];
1779 bool isARMCP0 = MCPE0.isMachineConstantPoolEntry();
1780 bool isARMCP1 = MCPE1.isMachineConstantPoolEntry();
1781 if (isARMCP0 && isARMCP1) {
1782 ARMConstantPoolValue *ACPV0 =
1783 static_cast<ARMConstantPoolValue*>(MCPE0.Val.MachineCPVal);
1784 ARMConstantPoolValue *ACPV1 =
1785 static_cast<ARMConstantPoolValue*>(MCPE1.Val.MachineCPVal);
1786 return ACPV0->hasSameValue(ACPV1);
1787 } else if (!isARMCP0 && !isARMCP1) {
1788 return MCPE0.Val.ConstVal == MCPE1.Val.ConstVal;
1790 return false;
1791 } else if (Opcode == ARM::PICLDR) {
1792 if (MI1.getOpcode() != Opcode)
1793 return false;
1794 if (MI0.getNumOperands() != MI1.getNumOperands())
1795 return false;
1797 unsigned Addr0 = MI0.getOperand(1).getReg();
1798 unsigned Addr1 = MI1.getOperand(1).getReg();
1799 if (Addr0 != Addr1) {
1800 if (!MRI || !Register::isVirtualRegister(Addr0) ||
1801 !Register::isVirtualRegister(Addr1))
1802 return false;
1804 // This assumes SSA form.
1805 MachineInstr *Def0 = MRI->getVRegDef(Addr0);
1806 MachineInstr *Def1 = MRI->getVRegDef(Addr1);
1807 // Check if the loaded value, e.g. a constantpool of a global address, are
1808 // the same.
1809 if (!produceSameValue(*Def0, *Def1, MRI))
1810 return false;
1813 for (unsigned i = 3, e = MI0.getNumOperands(); i != e; ++i) {
1814 // %12 = PICLDR %11, 0, 14, %noreg
1815 const MachineOperand &MO0 = MI0.getOperand(i);
1816 const MachineOperand &MO1 = MI1.getOperand(i);
1817 if (!MO0.isIdenticalTo(MO1))
1818 return false;
1820 return true;
1823 return MI0.isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
1826 /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler to
1827 /// determine if two loads are loading from the same base address. It should
1828 /// only return true if the base pointers are the same and the only differences
1829 /// between the two addresses is the offset. It also returns the offsets by
1830 /// reference.
1832 /// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched
1833 /// is permanently disabled.
1834 bool ARMBaseInstrInfo::areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
1835 int64_t &Offset1,
1836 int64_t &Offset2) const {
1837 // Don't worry about Thumb: just ARM and Thumb2.
1838 if (Subtarget.isThumb1Only()) return false;
1840 if (!Load1->isMachineOpcode() || !Load2->isMachineOpcode())
1841 return false;
1843 switch (Load1->getMachineOpcode()) {
1844 default:
1845 return false;
1846 case ARM::LDRi12:
1847 case ARM::LDRBi12:
1848 case ARM::LDRD:
1849 case ARM::LDRH:
1850 case ARM::LDRSB:
1851 case ARM::LDRSH:
1852 case ARM::VLDRD:
1853 case ARM::VLDRS:
1854 case ARM::t2LDRi8:
1855 case ARM::t2LDRBi8:
1856 case ARM::t2LDRDi8:
1857 case ARM::t2LDRSHi8:
1858 case ARM::t2LDRi12:
1859 case ARM::t2LDRBi12:
1860 case ARM::t2LDRSHi12:
1861 break;
1864 switch (Load2->getMachineOpcode()) {
1865 default:
1866 return false;
1867 case ARM::LDRi12:
1868 case ARM::LDRBi12:
1869 case ARM::LDRD:
1870 case ARM::LDRH:
1871 case ARM::LDRSB:
1872 case ARM::LDRSH:
1873 case ARM::VLDRD:
1874 case ARM::VLDRS:
1875 case ARM::t2LDRi8:
1876 case ARM::t2LDRBi8:
1877 case ARM::t2LDRSHi8:
1878 case ARM::t2LDRi12:
1879 case ARM::t2LDRBi12:
1880 case ARM::t2LDRSHi12:
1881 break;
1884 // Check if base addresses and chain operands match.
1885 if (Load1->getOperand(0) != Load2->getOperand(0) ||
1886 Load1->getOperand(4) != Load2->getOperand(4))
1887 return false;
1889 // Index should be Reg0.
1890 if (Load1->getOperand(3) != Load2->getOperand(3))
1891 return false;
1893 // Determine the offsets.
1894 if (isa<ConstantSDNode>(Load1->getOperand(1)) &&
1895 isa<ConstantSDNode>(Load2->getOperand(1))) {
1896 Offset1 = cast<ConstantSDNode>(Load1->getOperand(1))->getSExtValue();
1897 Offset2 = cast<ConstantSDNode>(Load2->getOperand(1))->getSExtValue();
1898 return true;
1901 return false;
1904 /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
1905 /// determine (in conjunction with areLoadsFromSameBasePtr) if two loads should
1906 /// be scheduled togther. On some targets if two loads are loading from
1907 /// addresses in the same cache line, it's better if they are scheduled
1908 /// together. This function takes two integers that represent the load offsets
1909 /// from the common base address. It returns true if it decides it's desirable
1910 /// to schedule the two loads together. "NumLoads" is the number of loads that
1911 /// have already been scheduled after Load1.
1913 /// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched
1914 /// is permanently disabled.
1915 bool ARMBaseInstrInfo::shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
1916 int64_t Offset1, int64_t Offset2,
1917 unsigned NumLoads) const {
1918 // Don't worry about Thumb: just ARM and Thumb2.
1919 if (Subtarget.isThumb1Only()) return false;
1921 assert(Offset2 > Offset1);
1923 if ((Offset2 - Offset1) / 8 > 64)
1924 return false;
1926 // Check if the machine opcodes are different. If they are different
1927 // then we consider them to not be of the same base address,
1928 // EXCEPT in the case of Thumb2 byte loads where one is LDRBi8 and the other LDRBi12.
1929 // In this case, they are considered to be the same because they are different
1930 // encoding forms of the same basic instruction.
1931 if ((Load1->getMachineOpcode() != Load2->getMachineOpcode()) &&
1932 !((Load1->getMachineOpcode() == ARM::t2LDRBi8 &&
1933 Load2->getMachineOpcode() == ARM::t2LDRBi12) ||
1934 (Load1->getMachineOpcode() == ARM::t2LDRBi12 &&
1935 Load2->getMachineOpcode() == ARM::t2LDRBi8)))
1936 return false; // FIXME: overly conservative?
1938 // Four loads in a row should be sufficient.
1939 if (NumLoads >= 3)
1940 return false;
1942 return true;
1945 bool ARMBaseInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
1946 const MachineBasicBlock *MBB,
1947 const MachineFunction &MF) const {
1948 // Debug info is never a scheduling boundary. It's necessary to be explicit
1949 // due to the special treatment of IT instructions below, otherwise a
1950 // dbg_value followed by an IT will result in the IT instruction being
1951 // considered a scheduling hazard, which is wrong. It should be the actual
1952 // instruction preceding the dbg_value instruction(s), just like it is
1953 // when debug info is not present.
1954 if (MI.isDebugInstr())
1955 return false;
1957 // Terminators and labels can't be scheduled around.
1958 if (MI.isTerminator() || MI.isPosition())
1959 return true;
1961 // Treat the start of the IT block as a scheduling boundary, but schedule
1962 // t2IT along with all instructions following it.
1963 // FIXME: This is a big hammer. But the alternative is to add all potential
1964 // true and anti dependencies to IT block instructions as implicit operands
1965 // to the t2IT instruction. The added compile time and complexity does not
1966 // seem worth it.
1967 MachineBasicBlock::const_iterator I = MI;
1968 // Make sure to skip any debug instructions
1969 while (++I != MBB->end() && I->isDebugInstr())
1971 if (I != MBB->end() && I->getOpcode() == ARM::t2IT)
1972 return true;
1974 // Don't attempt to schedule around any instruction that defines
1975 // a stack-oriented pointer, as it's unlikely to be profitable. This
1976 // saves compile time, because it doesn't require every single
1977 // stack slot reference to depend on the instruction that does the
1978 // modification.
1979 // Calls don't actually change the stack pointer, even if they have imp-defs.
1980 // No ARM calling conventions change the stack pointer. (X86 calling
1981 // conventions sometimes do).
1982 if (!MI.isCall() && MI.definesRegister(ARM::SP))
1983 return true;
1985 return false;
1988 bool ARMBaseInstrInfo::
1989 isProfitableToIfCvt(MachineBasicBlock &MBB,
1990 unsigned NumCycles, unsigned ExtraPredCycles,
1991 BranchProbability Probability) const {
1992 if (!NumCycles)
1993 return false;
1995 // If we are optimizing for size, see if the branch in the predecessor can be
1996 // lowered to cbn?z by the constant island lowering pass, and return false if
1997 // so. This results in a shorter instruction sequence.
1998 if (MBB.getParent()->getFunction().hasOptSize()) {
1999 MachineBasicBlock *Pred = *MBB.pred_begin();
2000 if (!Pred->empty()) {
2001 MachineInstr *LastMI = &*Pred->rbegin();
2002 if (LastMI->getOpcode() == ARM::t2Bcc) {
2003 const TargetRegisterInfo *TRI = &getRegisterInfo();
2004 MachineInstr *CmpMI = findCMPToFoldIntoCBZ(LastMI, TRI);
2005 if (CmpMI)
2006 return false;
2010 return isProfitableToIfCvt(MBB, NumCycles, ExtraPredCycles,
2011 MBB, 0, 0, Probability);
2014 bool ARMBaseInstrInfo::
2015 isProfitableToIfCvt(MachineBasicBlock &TBB,
2016 unsigned TCycles, unsigned TExtra,
2017 MachineBasicBlock &FBB,
2018 unsigned FCycles, unsigned FExtra,
2019 BranchProbability Probability) const {
2020 if (!TCycles)
2021 return false;
2023 // In thumb code we often end up trading one branch for a IT block, and
2024 // if we are cloning the instruction can increase code size. Prevent
2025 // blocks with multiple predecesors from being ifcvted to prevent this
2026 // cloning.
2027 if (Subtarget.isThumb2() && TBB.getParent()->getFunction().hasMinSize()) {
2028 if (TBB.pred_size() != 1 || FBB.pred_size() != 1)
2029 return false;
2032 // Attempt to estimate the relative costs of predication versus branching.
2033 // Here we scale up each component of UnpredCost to avoid precision issue when
2034 // scaling TCycles/FCycles by Probability.
2035 const unsigned ScalingUpFactor = 1024;
2037 unsigned PredCost = (TCycles + FCycles + TExtra + FExtra) * ScalingUpFactor;
2038 unsigned UnpredCost;
2039 if (!Subtarget.hasBranchPredictor()) {
2040 // When we don't have a branch predictor it's always cheaper to not take a
2041 // branch than take it, so we have to take that into account.
2042 unsigned NotTakenBranchCost = 1;
2043 unsigned TakenBranchCost = Subtarget.getMispredictionPenalty();
2044 unsigned TUnpredCycles, FUnpredCycles;
2045 if (!FCycles) {
2046 // Triangle: TBB is the fallthrough
2047 TUnpredCycles = TCycles + NotTakenBranchCost;
2048 FUnpredCycles = TakenBranchCost;
2049 } else {
2050 // Diamond: TBB is the block that is branched to, FBB is the fallthrough
2051 TUnpredCycles = TCycles + TakenBranchCost;
2052 FUnpredCycles = FCycles + NotTakenBranchCost;
2053 // The branch at the end of FBB will disappear when it's predicated, so
2054 // discount it from PredCost.
2055 PredCost -= 1 * ScalingUpFactor;
2057 // The total cost is the cost of each path scaled by their probabilites
2058 unsigned TUnpredCost = Probability.scale(TUnpredCycles * ScalingUpFactor);
2059 unsigned FUnpredCost = Probability.getCompl().scale(FUnpredCycles * ScalingUpFactor);
2060 UnpredCost = TUnpredCost + FUnpredCost;
2061 // When predicating assume that the first IT can be folded away but later
2062 // ones cost one cycle each
2063 if (Subtarget.isThumb2() && TCycles + FCycles > 4) {
2064 PredCost += ((TCycles + FCycles - 4) / 4) * ScalingUpFactor;
2066 } else {
2067 unsigned TUnpredCost = Probability.scale(TCycles * ScalingUpFactor);
2068 unsigned FUnpredCost =
2069 Probability.getCompl().scale(FCycles * ScalingUpFactor);
2070 UnpredCost = TUnpredCost + FUnpredCost;
2071 UnpredCost += 1 * ScalingUpFactor; // The branch itself
2072 UnpredCost += Subtarget.getMispredictionPenalty() * ScalingUpFactor / 10;
2075 return PredCost <= UnpredCost;
2078 bool
2079 ARMBaseInstrInfo::isProfitableToUnpredicate(MachineBasicBlock &TMBB,
2080 MachineBasicBlock &FMBB) const {
2081 // Reduce false anti-dependencies to let the target's out-of-order execution
2082 // engine do its thing.
2083 return Subtarget.isProfitableToUnpredicate();
2086 /// getInstrPredicate - If instruction is predicated, returns its predicate
2087 /// condition, otherwise returns AL. It also returns the condition code
2088 /// register by reference.
2089 ARMCC::CondCodes llvm::getInstrPredicate(const MachineInstr &MI,
2090 unsigned &PredReg) {
2091 int PIdx = MI.findFirstPredOperandIdx();
2092 if (PIdx == -1) {
2093 PredReg = 0;
2094 return ARMCC::AL;
2097 PredReg = MI.getOperand(PIdx+1).getReg();
2098 return (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
2101 unsigned llvm::getMatchingCondBranchOpcode(unsigned Opc) {
2102 if (Opc == ARM::B)
2103 return ARM::Bcc;
2104 if (Opc == ARM::tB)
2105 return ARM::tBcc;
2106 if (Opc == ARM::t2B)
2107 return ARM::t2Bcc;
2109 llvm_unreachable("Unknown unconditional branch opcode!");
2112 MachineInstr *ARMBaseInstrInfo::commuteInstructionImpl(MachineInstr &MI,
2113 bool NewMI,
2114 unsigned OpIdx1,
2115 unsigned OpIdx2) const {
2116 switch (MI.getOpcode()) {
2117 case ARM::MOVCCr:
2118 case ARM::t2MOVCCr: {
2119 // MOVCC can be commuted by inverting the condition.
2120 unsigned PredReg = 0;
2121 ARMCC::CondCodes CC = getInstrPredicate(MI, PredReg);
2122 // MOVCC AL can't be inverted. Shouldn't happen.
2123 if (CC == ARMCC::AL || PredReg != ARM::CPSR)
2124 return nullptr;
2125 MachineInstr *CommutedMI =
2126 TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
2127 if (!CommutedMI)
2128 return nullptr;
2129 // After swapping the MOVCC operands, also invert the condition.
2130 CommutedMI->getOperand(CommutedMI->findFirstPredOperandIdx())
2131 .setImm(ARMCC::getOppositeCondition(CC));
2132 return CommutedMI;
2135 return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
2138 /// Identify instructions that can be folded into a MOVCC instruction, and
2139 /// return the defining instruction.
2140 MachineInstr *
2141 ARMBaseInstrInfo::canFoldIntoMOVCC(unsigned Reg, const MachineRegisterInfo &MRI,
2142 const TargetInstrInfo *TII) const {
2143 if (!Register::isVirtualRegister(Reg))
2144 return nullptr;
2145 if (!MRI.hasOneNonDBGUse(Reg))
2146 return nullptr;
2147 MachineInstr *MI = MRI.getVRegDef(Reg);
2148 if (!MI)
2149 return nullptr;
2150 // Check if MI can be predicated and folded into the MOVCC.
2151 if (!isPredicable(*MI))
2152 return nullptr;
2153 // Check if MI has any non-dead defs or physreg uses. This also detects
2154 // predicated instructions which will be reading CPSR.
2155 for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
2156 const MachineOperand &MO = MI->getOperand(i);
2157 // Reject frame index operands, PEI can't handle the predicated pseudos.
2158 if (MO.isFI() || MO.isCPI() || MO.isJTI())
2159 return nullptr;
2160 if (!MO.isReg())
2161 continue;
2162 // MI can't have any tied operands, that would conflict with predication.
2163 if (MO.isTied())
2164 return nullptr;
2165 if (Register::isPhysicalRegister(MO.getReg()))
2166 return nullptr;
2167 if (MO.isDef() && !MO.isDead())
2168 return nullptr;
2170 bool DontMoveAcrossStores = true;
2171 if (!MI->isSafeToMove(/* AliasAnalysis = */ nullptr, DontMoveAcrossStores))
2172 return nullptr;
2173 return MI;
2176 bool ARMBaseInstrInfo::analyzeSelect(const MachineInstr &MI,
2177 SmallVectorImpl<MachineOperand> &Cond,
2178 unsigned &TrueOp, unsigned &FalseOp,
2179 bool &Optimizable) const {
2180 assert((MI.getOpcode() == ARM::MOVCCr || MI.getOpcode() == ARM::t2MOVCCr) &&
2181 "Unknown select instruction");
2182 // MOVCC operands:
2183 // 0: Def.
2184 // 1: True use.
2185 // 2: False use.
2186 // 3: Condition code.
2187 // 4: CPSR use.
2188 TrueOp = 1;
2189 FalseOp = 2;
2190 Cond.push_back(MI.getOperand(3));
2191 Cond.push_back(MI.getOperand(4));
2192 // We can always fold a def.
2193 Optimizable = true;
2194 return false;
2197 MachineInstr *
2198 ARMBaseInstrInfo::optimizeSelect(MachineInstr &MI,
2199 SmallPtrSetImpl<MachineInstr *> &SeenMIs,
2200 bool PreferFalse) const {
2201 assert((MI.getOpcode() == ARM::MOVCCr || MI.getOpcode() == ARM::t2MOVCCr) &&
2202 "Unknown select instruction");
2203 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
2204 MachineInstr *DefMI = canFoldIntoMOVCC(MI.getOperand(2).getReg(), MRI, this);
2205 bool Invert = !DefMI;
2206 if (!DefMI)
2207 DefMI = canFoldIntoMOVCC(MI.getOperand(1).getReg(), MRI, this);
2208 if (!DefMI)
2209 return nullptr;
2211 // Find new register class to use.
2212 MachineOperand FalseReg = MI.getOperand(Invert ? 2 : 1);
2213 unsigned DestReg = MI.getOperand(0).getReg();
2214 const TargetRegisterClass *PreviousClass = MRI.getRegClass(FalseReg.getReg());
2215 if (!MRI.constrainRegClass(DestReg, PreviousClass))
2216 return nullptr;
2218 // Create a new predicated version of DefMI.
2219 // Rfalse is the first use.
2220 MachineInstrBuilder NewMI =
2221 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), DefMI->getDesc(), DestReg);
2223 // Copy all the DefMI operands, excluding its (null) predicate.
2224 const MCInstrDesc &DefDesc = DefMI->getDesc();
2225 for (unsigned i = 1, e = DefDesc.getNumOperands();
2226 i != e && !DefDesc.OpInfo[i].isPredicate(); ++i)
2227 NewMI.add(DefMI->getOperand(i));
2229 unsigned CondCode = MI.getOperand(3).getImm();
2230 if (Invert)
2231 NewMI.addImm(ARMCC::getOppositeCondition(ARMCC::CondCodes(CondCode)));
2232 else
2233 NewMI.addImm(CondCode);
2234 NewMI.add(MI.getOperand(4));
2236 // DefMI is not the -S version that sets CPSR, so add an optional %noreg.
2237 if (NewMI->hasOptionalDef())
2238 NewMI.add(condCodeOp());
2240 // The output register value when the predicate is false is an implicit
2241 // register operand tied to the first def.
2242 // The tie makes the register allocator ensure the FalseReg is allocated the
2243 // same register as operand 0.
2244 FalseReg.setImplicit();
2245 NewMI.add(FalseReg);
2246 NewMI->tieOperands(0, NewMI->getNumOperands() - 1);
2248 // Update SeenMIs set: register newly created MI and erase removed DefMI.
2249 SeenMIs.insert(NewMI);
2250 SeenMIs.erase(DefMI);
2252 // If MI is inside a loop, and DefMI is outside the loop, then kill flags on
2253 // DefMI would be invalid when tranferred inside the loop. Checking for a
2254 // loop is expensive, but at least remove kill flags if they are in different
2255 // BBs.
2256 if (DefMI->getParent() != MI.getParent())
2257 NewMI->clearKillInfo();
2259 // The caller will erase MI, but not DefMI.
2260 DefMI->eraseFromParent();
2261 return NewMI;
2264 /// Map pseudo instructions that imply an 'S' bit onto real opcodes. Whether the
2265 /// instruction is encoded with an 'S' bit is determined by the optional CPSR
2266 /// def operand.
2268 /// This will go away once we can teach tblgen how to set the optional CPSR def
2269 /// operand itself.
2270 struct AddSubFlagsOpcodePair {
2271 uint16_t PseudoOpc;
2272 uint16_t MachineOpc;
2275 static const AddSubFlagsOpcodePair AddSubFlagsOpcodeMap[] = {
2276 {ARM::ADDSri, ARM::ADDri},
2277 {ARM::ADDSrr, ARM::ADDrr},
2278 {ARM::ADDSrsi, ARM::ADDrsi},
2279 {ARM::ADDSrsr, ARM::ADDrsr},
2281 {ARM::SUBSri, ARM::SUBri},
2282 {ARM::SUBSrr, ARM::SUBrr},
2283 {ARM::SUBSrsi, ARM::SUBrsi},
2284 {ARM::SUBSrsr, ARM::SUBrsr},
2286 {ARM::RSBSri, ARM::RSBri},
2287 {ARM::RSBSrsi, ARM::RSBrsi},
2288 {ARM::RSBSrsr, ARM::RSBrsr},
2290 {ARM::tADDSi3, ARM::tADDi3},
2291 {ARM::tADDSi8, ARM::tADDi8},
2292 {ARM::tADDSrr, ARM::tADDrr},
2293 {ARM::tADCS, ARM::tADC},
2295 {ARM::tSUBSi3, ARM::tSUBi3},
2296 {ARM::tSUBSi8, ARM::tSUBi8},
2297 {ARM::tSUBSrr, ARM::tSUBrr},
2298 {ARM::tSBCS, ARM::tSBC},
2299 {ARM::tRSBS, ARM::tRSB},
2300 {ARM::tLSLSri, ARM::tLSLri},
2302 {ARM::t2ADDSri, ARM::t2ADDri},
2303 {ARM::t2ADDSrr, ARM::t2ADDrr},
2304 {ARM::t2ADDSrs, ARM::t2ADDrs},
2306 {ARM::t2SUBSri, ARM::t2SUBri},
2307 {ARM::t2SUBSrr, ARM::t2SUBrr},
2308 {ARM::t2SUBSrs, ARM::t2SUBrs},
2310 {ARM::t2RSBSri, ARM::t2RSBri},
2311 {ARM::t2RSBSrs, ARM::t2RSBrs},
2314 unsigned llvm::convertAddSubFlagsOpcode(unsigned OldOpc) {
2315 for (unsigned i = 0, e = array_lengthof(AddSubFlagsOpcodeMap); i != e; ++i)
2316 if (OldOpc == AddSubFlagsOpcodeMap[i].PseudoOpc)
2317 return AddSubFlagsOpcodeMap[i].MachineOpc;
2318 return 0;
2321 void llvm::emitARMRegPlusImmediate(MachineBasicBlock &MBB,
2322 MachineBasicBlock::iterator &MBBI,
2323 const DebugLoc &dl, unsigned DestReg,
2324 unsigned BaseReg, int NumBytes,
2325 ARMCC::CondCodes Pred, unsigned PredReg,
2326 const ARMBaseInstrInfo &TII,
2327 unsigned MIFlags) {
2328 if (NumBytes == 0 && DestReg != BaseReg) {
2329 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), DestReg)
2330 .addReg(BaseReg, RegState::Kill)
2331 .add(predOps(Pred, PredReg))
2332 .add(condCodeOp())
2333 .setMIFlags(MIFlags);
2334 return;
2337 bool isSub = NumBytes < 0;
2338 if (isSub) NumBytes = -NumBytes;
2340 while (NumBytes) {
2341 unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
2342 unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
2343 assert(ThisVal && "Didn't extract field correctly");
2345 // We will handle these bits from offset, clear them.
2346 NumBytes &= ~ThisVal;
2348 assert(ARM_AM::getSOImmVal(ThisVal) != -1 && "Bit extraction didn't work?");
2350 // Build the new ADD / SUB.
2351 unsigned Opc = isSub ? ARM::SUBri : ARM::ADDri;
2352 BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg)
2353 .addReg(BaseReg, RegState::Kill)
2354 .addImm(ThisVal)
2355 .add(predOps(Pred, PredReg))
2356 .add(condCodeOp())
2357 .setMIFlags(MIFlags);
2358 BaseReg = DestReg;
2362 bool llvm::tryFoldSPUpdateIntoPushPop(const ARMSubtarget &Subtarget,
2363 MachineFunction &MF, MachineInstr *MI,
2364 unsigned NumBytes) {
2365 // This optimisation potentially adds lots of load and store
2366 // micro-operations, it's only really a great benefit to code-size.
2367 if (!Subtarget.hasMinSize())
2368 return false;
2370 // If only one register is pushed/popped, LLVM can use an LDR/STR
2371 // instead. We can't modify those so make sure we're dealing with an
2372 // instruction we understand.
2373 bool IsPop = isPopOpcode(MI->getOpcode());
2374 bool IsPush = isPushOpcode(MI->getOpcode());
2375 if (!IsPush && !IsPop)
2376 return false;
2378 bool IsVFPPushPop = MI->getOpcode() == ARM::VSTMDDB_UPD ||
2379 MI->getOpcode() == ARM::VLDMDIA_UPD;
2380 bool IsT1PushPop = MI->getOpcode() == ARM::tPUSH ||
2381 MI->getOpcode() == ARM::tPOP ||
2382 MI->getOpcode() == ARM::tPOP_RET;
2384 assert((IsT1PushPop || (MI->getOperand(0).getReg() == ARM::SP &&
2385 MI->getOperand(1).getReg() == ARM::SP)) &&
2386 "trying to fold sp update into non-sp-updating push/pop");
2388 // The VFP push & pop act on D-registers, so we can only fold an adjustment
2389 // by a multiple of 8 bytes in correctly. Similarly rN is 4-bytes. Don't try
2390 // if this is violated.
2391 if (NumBytes % (IsVFPPushPop ? 8 : 4) != 0)
2392 return false;
2394 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
2395 // pred) so the list starts at 4. Thumb1 starts after the predicate.
2396 int RegListIdx = IsT1PushPop ? 2 : 4;
2398 // Calculate the space we'll need in terms of registers.
2399 unsigned RegsNeeded;
2400 const TargetRegisterClass *RegClass;
2401 if (IsVFPPushPop) {
2402 RegsNeeded = NumBytes / 8;
2403 RegClass = &ARM::DPRRegClass;
2404 } else {
2405 RegsNeeded = NumBytes / 4;
2406 RegClass = &ARM::GPRRegClass;
2409 // We're going to have to strip all list operands off before
2410 // re-adding them since the order matters, so save the existing ones
2411 // for later.
2412 SmallVector<MachineOperand, 4> RegList;
2414 // We're also going to need the first register transferred by this
2415 // instruction, which won't necessarily be the first register in the list.
2416 unsigned FirstRegEnc = -1;
2418 const TargetRegisterInfo *TRI = MF.getRegInfo().getTargetRegisterInfo();
2419 for (int i = MI->getNumOperands() - 1; i >= RegListIdx; --i) {
2420 MachineOperand &MO = MI->getOperand(i);
2421 RegList.push_back(MO);
2423 if (MO.isReg() && TRI->getEncodingValue(MO.getReg()) < FirstRegEnc)
2424 FirstRegEnc = TRI->getEncodingValue(MO.getReg());
2427 const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF);
2429 // Now try to find enough space in the reglist to allocate NumBytes.
2430 for (int CurRegEnc = FirstRegEnc - 1; CurRegEnc >= 0 && RegsNeeded;
2431 --CurRegEnc) {
2432 unsigned CurReg = RegClass->getRegister(CurRegEnc);
2433 if (IsT1PushPop && CurReg > ARM::R7)
2434 continue;
2435 if (!IsPop) {
2436 // Pushing any register is completely harmless, mark the register involved
2437 // as undef since we don't care about its value and must not restore it
2438 // during stack unwinding.
2439 RegList.push_back(MachineOperand::CreateReg(CurReg, false, false,
2440 false, false, true));
2441 --RegsNeeded;
2442 continue;
2445 // However, we can only pop an extra register if it's not live. For
2446 // registers live within the function we might clobber a return value
2447 // register; the other way a register can be live here is if it's
2448 // callee-saved.
2449 if (isCalleeSavedRegister(CurReg, CSRegs) ||
2450 MI->getParent()->computeRegisterLiveness(TRI, CurReg, MI) !=
2451 MachineBasicBlock::LQR_Dead) {
2452 // VFP pops don't allow holes in the register list, so any skip is fatal
2453 // for our transformation. GPR pops do, so we should just keep looking.
2454 if (IsVFPPushPop)
2455 return false;
2456 else
2457 continue;
2460 // Mark the unimportant registers as <def,dead> in the POP.
2461 RegList.push_back(MachineOperand::CreateReg(CurReg, true, false, false,
2462 true));
2463 --RegsNeeded;
2466 if (RegsNeeded > 0)
2467 return false;
2469 // Finally we know we can profitably perform the optimisation so go
2470 // ahead: strip all existing registers off and add them back again
2471 // in the right order.
2472 for (int i = MI->getNumOperands() - 1; i >= RegListIdx; --i)
2473 MI->RemoveOperand(i);
2475 // Add the complete list back in.
2476 MachineInstrBuilder MIB(MF, &*MI);
2477 for (int i = RegList.size() - 1; i >= 0; --i)
2478 MIB.add(RegList[i]);
2480 return true;
2483 bool llvm::rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
2484 unsigned FrameReg, int &Offset,
2485 const ARMBaseInstrInfo &TII) {
2486 unsigned Opcode = MI.getOpcode();
2487 const MCInstrDesc &Desc = MI.getDesc();
2488 unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
2489 bool isSub = false;
2491 // Memory operands in inline assembly always use AddrMode2.
2492 if (Opcode == ARM::INLINEASM || Opcode == ARM::INLINEASM_BR)
2493 AddrMode = ARMII::AddrMode2;
2495 if (Opcode == ARM::ADDri) {
2496 Offset += MI.getOperand(FrameRegIdx+1).getImm();
2497 if (Offset == 0) {
2498 // Turn it into a move.
2499 MI.setDesc(TII.get(ARM::MOVr));
2500 MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
2501 MI.RemoveOperand(FrameRegIdx+1);
2502 Offset = 0;
2503 return true;
2504 } else if (Offset < 0) {
2505 Offset = -Offset;
2506 isSub = true;
2507 MI.setDesc(TII.get(ARM::SUBri));
2510 // Common case: small offset, fits into instruction.
2511 if (ARM_AM::getSOImmVal(Offset) != -1) {
2512 // Replace the FrameIndex with sp / fp
2513 MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
2514 MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset);
2515 Offset = 0;
2516 return true;
2519 // Otherwise, pull as much of the immedidate into this ADDri/SUBri
2520 // as possible.
2521 unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
2522 unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
2524 // We will handle these bits from offset, clear them.
2525 Offset &= ~ThisImmVal;
2527 // Get the properly encoded SOImmVal field.
2528 assert(ARM_AM::getSOImmVal(ThisImmVal) != -1 &&
2529 "Bit extraction didn't work?");
2530 MI.getOperand(FrameRegIdx+1).ChangeToImmediate(ThisImmVal);
2531 } else {
2532 unsigned ImmIdx = 0;
2533 int InstrOffs = 0;
2534 unsigned NumBits = 0;
2535 unsigned Scale = 1;
2536 switch (AddrMode) {
2537 case ARMII::AddrMode_i12:
2538 ImmIdx = FrameRegIdx + 1;
2539 InstrOffs = MI.getOperand(ImmIdx).getImm();
2540 NumBits = 12;
2541 break;
2542 case ARMII::AddrMode2:
2543 ImmIdx = FrameRegIdx+2;
2544 InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
2545 if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
2546 InstrOffs *= -1;
2547 NumBits = 12;
2548 break;
2549 case ARMII::AddrMode3:
2550 ImmIdx = FrameRegIdx+2;
2551 InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
2552 if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
2553 InstrOffs *= -1;
2554 NumBits = 8;
2555 break;
2556 case ARMII::AddrMode4:
2557 case ARMII::AddrMode6:
2558 // Can't fold any offset even if it's zero.
2559 return false;
2560 case ARMII::AddrMode5:
2561 ImmIdx = FrameRegIdx+1;
2562 InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
2563 if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
2564 InstrOffs *= -1;
2565 NumBits = 8;
2566 Scale = 4;
2567 break;
2568 case ARMII::AddrMode5FP16:
2569 ImmIdx = FrameRegIdx+1;
2570 InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
2571 if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
2572 InstrOffs *= -1;
2573 NumBits = 8;
2574 Scale = 2;
2575 break;
2576 case ARMII::AddrModeT2_i7:
2577 case ARMII::AddrModeT2_i7s2:
2578 case ARMII::AddrModeT2_i7s4:
2579 ImmIdx = FrameRegIdx+1;
2580 InstrOffs = MI.getOperand(ImmIdx).getImm();
2581 NumBits = 7;
2582 Scale = (AddrMode == ARMII::AddrModeT2_i7s2 ? 2 :
2583 AddrMode == ARMII::AddrModeT2_i7s4 ? 4 : 1);
2584 break;
2585 default:
2586 llvm_unreachable("Unsupported addressing mode!");
2589 Offset += InstrOffs * Scale;
2590 assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
2591 if (Offset < 0) {
2592 Offset = -Offset;
2593 isSub = true;
2596 // Attempt to fold address comp. if opcode has offset bits
2597 if (NumBits > 0) {
2598 // Common case: small offset, fits into instruction.
2599 MachineOperand &ImmOp = MI.getOperand(ImmIdx);
2600 int ImmedOffset = Offset / Scale;
2601 unsigned Mask = (1 << NumBits) - 1;
2602 if ((unsigned)Offset <= Mask * Scale) {
2603 // Replace the FrameIndex with sp
2604 MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
2605 // FIXME: When addrmode2 goes away, this will simplify (like the
2606 // T2 version), as the LDR.i12 versions don't need the encoding
2607 // tricks for the offset value.
2608 if (isSub) {
2609 if (AddrMode == ARMII::AddrMode_i12)
2610 ImmedOffset = -ImmedOffset;
2611 else
2612 ImmedOffset |= 1 << NumBits;
2614 ImmOp.ChangeToImmediate(ImmedOffset);
2615 Offset = 0;
2616 return true;
2619 // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
2620 ImmedOffset = ImmedOffset & Mask;
2621 if (isSub) {
2622 if (AddrMode == ARMII::AddrMode_i12)
2623 ImmedOffset = -ImmedOffset;
2624 else
2625 ImmedOffset |= 1 << NumBits;
2627 ImmOp.ChangeToImmediate(ImmedOffset);
2628 Offset &= ~(Mask*Scale);
2632 Offset = (isSub) ? -Offset : Offset;
2633 return Offset == 0;
2636 /// analyzeCompare - For a comparison instruction, return the source registers
2637 /// in SrcReg and SrcReg2 if having two register operands, and the value it
2638 /// compares against in CmpValue. Return true if the comparison instruction
2639 /// can be analyzed.
2640 bool ARMBaseInstrInfo::analyzeCompare(const MachineInstr &MI, unsigned &SrcReg,
2641 unsigned &SrcReg2, int &CmpMask,
2642 int &CmpValue) const {
2643 switch (MI.getOpcode()) {
2644 default: break;
2645 case ARM::CMPri:
2646 case ARM::t2CMPri:
2647 case ARM::tCMPi8:
2648 SrcReg = MI.getOperand(0).getReg();
2649 SrcReg2 = 0;
2650 CmpMask = ~0;
2651 CmpValue = MI.getOperand(1).getImm();
2652 return true;
2653 case ARM::CMPrr:
2654 case ARM::t2CMPrr:
2655 case ARM::tCMPr:
2656 SrcReg = MI.getOperand(0).getReg();
2657 SrcReg2 = MI.getOperand(1).getReg();
2658 CmpMask = ~0;
2659 CmpValue = 0;
2660 return true;
2661 case ARM::TSTri:
2662 case ARM::t2TSTri:
2663 SrcReg = MI.getOperand(0).getReg();
2664 SrcReg2 = 0;
2665 CmpMask = MI.getOperand(1).getImm();
2666 CmpValue = 0;
2667 return true;
2670 return false;
2673 /// isSuitableForMask - Identify a suitable 'and' instruction that
2674 /// operates on the given source register and applies the same mask
2675 /// as a 'tst' instruction. Provide a limited look-through for copies.
2676 /// When successful, MI will hold the found instruction.
2677 static bool isSuitableForMask(MachineInstr *&MI, unsigned SrcReg,
2678 int CmpMask, bool CommonUse) {
2679 switch (MI->getOpcode()) {
2680 case ARM::ANDri:
2681 case ARM::t2ANDri:
2682 if (CmpMask != MI->getOperand(2).getImm())
2683 return false;
2684 if (SrcReg == MI->getOperand(CommonUse ? 1 : 0).getReg())
2685 return true;
2686 break;
2689 return false;
2692 /// getSwappedCondition - assume the flags are set by MI(a,b), return
2693 /// the condition code if we modify the instructions such that flags are
2694 /// set by MI(b,a).
2695 inline static ARMCC::CondCodes getSwappedCondition(ARMCC::CondCodes CC) {
2696 switch (CC) {
2697 default: return ARMCC::AL;
2698 case ARMCC::EQ: return ARMCC::EQ;
2699 case ARMCC::NE: return ARMCC::NE;
2700 case ARMCC::HS: return ARMCC::LS;
2701 case ARMCC::LO: return ARMCC::HI;
2702 case ARMCC::HI: return ARMCC::LO;
2703 case ARMCC::LS: return ARMCC::HS;
2704 case ARMCC::GE: return ARMCC::LE;
2705 case ARMCC::LT: return ARMCC::GT;
2706 case ARMCC::GT: return ARMCC::LT;
2707 case ARMCC::LE: return ARMCC::GE;
2711 /// getCmpToAddCondition - assume the flags are set by CMP(a,b), return
2712 /// the condition code if we modify the instructions such that flags are
2713 /// set by ADD(a,b,X).
2714 inline static ARMCC::CondCodes getCmpToAddCondition(ARMCC::CondCodes CC) {
2715 switch (CC) {
2716 default: return ARMCC::AL;
2717 case ARMCC::HS: return ARMCC::LO;
2718 case ARMCC::LO: return ARMCC::HS;
2719 case ARMCC::VS: return ARMCC::VS;
2720 case ARMCC::VC: return ARMCC::VC;
2724 /// isRedundantFlagInstr - check whether the first instruction, whose only
2725 /// purpose is to update flags, can be made redundant.
2726 /// CMPrr can be made redundant by SUBrr if the operands are the same.
2727 /// CMPri can be made redundant by SUBri if the operands are the same.
2728 /// CMPrr(r0, r1) can be made redundant by ADDr[ri](r0, r1, X).
2729 /// This function can be extended later on.
2730 inline static bool isRedundantFlagInstr(const MachineInstr *CmpI,
2731 unsigned SrcReg, unsigned SrcReg2,
2732 int ImmValue, const MachineInstr *OI,
2733 bool &IsThumb1) {
2734 if ((CmpI->getOpcode() == ARM::CMPrr || CmpI->getOpcode() == ARM::t2CMPrr) &&
2735 (OI->getOpcode() == ARM::SUBrr || OI->getOpcode() == ARM::t2SUBrr) &&
2736 ((OI->getOperand(1).getReg() == SrcReg &&
2737 OI->getOperand(2).getReg() == SrcReg2) ||
2738 (OI->getOperand(1).getReg() == SrcReg2 &&
2739 OI->getOperand(2).getReg() == SrcReg))) {
2740 IsThumb1 = false;
2741 return true;
2744 if (CmpI->getOpcode() == ARM::tCMPr && OI->getOpcode() == ARM::tSUBrr &&
2745 ((OI->getOperand(2).getReg() == SrcReg &&
2746 OI->getOperand(3).getReg() == SrcReg2) ||
2747 (OI->getOperand(2).getReg() == SrcReg2 &&
2748 OI->getOperand(3).getReg() == SrcReg))) {
2749 IsThumb1 = true;
2750 return true;
2753 if ((CmpI->getOpcode() == ARM::CMPri || CmpI->getOpcode() == ARM::t2CMPri) &&
2754 (OI->getOpcode() == ARM::SUBri || OI->getOpcode() == ARM::t2SUBri) &&
2755 OI->getOperand(1).getReg() == SrcReg &&
2756 OI->getOperand(2).getImm() == ImmValue) {
2757 IsThumb1 = false;
2758 return true;
2761 if (CmpI->getOpcode() == ARM::tCMPi8 &&
2762 (OI->getOpcode() == ARM::tSUBi8 || OI->getOpcode() == ARM::tSUBi3) &&
2763 OI->getOperand(2).getReg() == SrcReg &&
2764 OI->getOperand(3).getImm() == ImmValue) {
2765 IsThumb1 = true;
2766 return true;
2769 if ((CmpI->getOpcode() == ARM::CMPrr || CmpI->getOpcode() == ARM::t2CMPrr) &&
2770 (OI->getOpcode() == ARM::ADDrr || OI->getOpcode() == ARM::t2ADDrr ||
2771 OI->getOpcode() == ARM::ADDri || OI->getOpcode() == ARM::t2ADDri) &&
2772 OI->getOperand(0).isReg() && OI->getOperand(1).isReg() &&
2773 OI->getOperand(0).getReg() == SrcReg &&
2774 OI->getOperand(1).getReg() == SrcReg2) {
2775 IsThumb1 = false;
2776 return true;
2779 if (CmpI->getOpcode() == ARM::tCMPr &&
2780 (OI->getOpcode() == ARM::tADDi3 || OI->getOpcode() == ARM::tADDi8 ||
2781 OI->getOpcode() == ARM::tADDrr) &&
2782 OI->getOperand(0).getReg() == SrcReg &&
2783 OI->getOperand(2).getReg() == SrcReg2) {
2784 IsThumb1 = true;
2785 return true;
2788 return false;
2791 static bool isOptimizeCompareCandidate(MachineInstr *MI, bool &IsThumb1) {
2792 switch (MI->getOpcode()) {
2793 default: return false;
2794 case ARM::tLSLri:
2795 case ARM::tLSRri:
2796 case ARM::tLSLrr:
2797 case ARM::tLSRrr:
2798 case ARM::tSUBrr:
2799 case ARM::tADDrr:
2800 case ARM::tADDi3:
2801 case ARM::tADDi8:
2802 case ARM::tSUBi3:
2803 case ARM::tSUBi8:
2804 case ARM::tMUL:
2805 case ARM::tADC:
2806 case ARM::tSBC:
2807 case ARM::tRSB:
2808 case ARM::tAND:
2809 case ARM::tORR:
2810 case ARM::tEOR:
2811 case ARM::tBIC:
2812 case ARM::tMVN:
2813 case ARM::tASRri:
2814 case ARM::tASRrr:
2815 case ARM::tROR:
2816 IsThumb1 = true;
2817 LLVM_FALLTHROUGH;
2818 case ARM::RSBrr:
2819 case ARM::RSBri:
2820 case ARM::RSCrr:
2821 case ARM::RSCri:
2822 case ARM::ADDrr:
2823 case ARM::ADDri:
2824 case ARM::ADCrr:
2825 case ARM::ADCri:
2826 case ARM::SUBrr:
2827 case ARM::SUBri:
2828 case ARM::SBCrr:
2829 case ARM::SBCri:
2830 case ARM::t2RSBri:
2831 case ARM::t2ADDrr:
2832 case ARM::t2ADDri:
2833 case ARM::t2ADCrr:
2834 case ARM::t2ADCri:
2835 case ARM::t2SUBrr:
2836 case ARM::t2SUBri:
2837 case ARM::t2SBCrr:
2838 case ARM::t2SBCri:
2839 case ARM::ANDrr:
2840 case ARM::ANDri:
2841 case ARM::t2ANDrr:
2842 case ARM::t2ANDri:
2843 case ARM::ORRrr:
2844 case ARM::ORRri:
2845 case ARM::t2ORRrr:
2846 case ARM::t2ORRri:
2847 case ARM::EORrr:
2848 case ARM::EORri:
2849 case ARM::t2EORrr:
2850 case ARM::t2EORri:
2851 case ARM::t2LSRri:
2852 case ARM::t2LSRrr:
2853 case ARM::t2LSLri:
2854 case ARM::t2LSLrr:
2855 return true;
2859 /// optimizeCompareInstr - Convert the instruction supplying the argument to the
2860 /// comparison into one that sets the zero bit in the flags register;
2861 /// Remove a redundant Compare instruction if an earlier instruction can set the
2862 /// flags in the same way as Compare.
2863 /// E.g. SUBrr(r1,r2) and CMPrr(r1,r2). We also handle the case where two
2864 /// operands are swapped: SUBrr(r1,r2) and CMPrr(r2,r1), by updating the
2865 /// condition code of instructions which use the flags.
2866 bool ARMBaseInstrInfo::optimizeCompareInstr(
2867 MachineInstr &CmpInstr, unsigned SrcReg, unsigned SrcReg2, int CmpMask,
2868 int CmpValue, const MachineRegisterInfo *MRI) const {
2869 // Get the unique definition of SrcReg.
2870 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
2871 if (!MI) return false;
2873 // Masked compares sometimes use the same register as the corresponding 'and'.
2874 if (CmpMask != ~0) {
2875 if (!isSuitableForMask(MI, SrcReg, CmpMask, false) || isPredicated(*MI)) {
2876 MI = nullptr;
2877 for (MachineRegisterInfo::use_instr_iterator
2878 UI = MRI->use_instr_begin(SrcReg), UE = MRI->use_instr_end();
2879 UI != UE; ++UI) {
2880 if (UI->getParent() != CmpInstr.getParent())
2881 continue;
2882 MachineInstr *PotentialAND = &*UI;
2883 if (!isSuitableForMask(PotentialAND, SrcReg, CmpMask, true) ||
2884 isPredicated(*PotentialAND))
2885 continue;
2886 MI = PotentialAND;
2887 break;
2889 if (!MI) return false;
2893 // Get ready to iterate backward from CmpInstr.
2894 MachineBasicBlock::iterator I = CmpInstr, E = MI,
2895 B = CmpInstr.getParent()->begin();
2897 // Early exit if CmpInstr is at the beginning of the BB.
2898 if (I == B) return false;
2900 // There are two possible candidates which can be changed to set CPSR:
2901 // One is MI, the other is a SUB or ADD instruction.
2902 // For CMPrr(r1,r2), we are looking for SUB(r1,r2), SUB(r2,r1), or
2903 // ADDr[ri](r1, r2, X).
2904 // For CMPri(r1, CmpValue), we are looking for SUBri(r1, CmpValue).
2905 MachineInstr *SubAdd = nullptr;
2906 if (SrcReg2 != 0)
2907 // MI is not a candidate for CMPrr.
2908 MI = nullptr;
2909 else if (MI->getParent() != CmpInstr.getParent() || CmpValue != 0) {
2910 // Conservatively refuse to convert an instruction which isn't in the same
2911 // BB as the comparison.
2912 // For CMPri w/ CmpValue != 0, a SubAdd may still be a candidate.
2913 // Thus we cannot return here.
2914 if (CmpInstr.getOpcode() == ARM::CMPri ||
2915 CmpInstr.getOpcode() == ARM::t2CMPri ||
2916 CmpInstr.getOpcode() == ARM::tCMPi8)
2917 MI = nullptr;
2918 else
2919 return false;
2922 bool IsThumb1 = false;
2923 if (MI && !isOptimizeCompareCandidate(MI, IsThumb1))
2924 return false;
2926 // We also want to do this peephole for cases like this: if (a*b == 0),
2927 // and optimise away the CMP instruction from the generated code sequence:
2928 // MULS, MOVS, MOVS, CMP. Here the MOVS instructions load the boolean values
2929 // resulting from the select instruction, but these MOVS instructions for
2930 // Thumb1 (V6M) are flag setting and are thus preventing this optimisation.
2931 // However, if we only have MOVS instructions in between the CMP and the
2932 // other instruction (the MULS in this example), then the CPSR is dead so we
2933 // can safely reorder the sequence into: MOVS, MOVS, MULS, CMP. We do this
2934 // reordering and then continue the analysis hoping we can eliminate the
2935 // CMP. This peephole works on the vregs, so is still in SSA form. As a
2936 // consequence, the movs won't redefine/kill the MUL operands which would
2937 // make this reordering illegal.
2938 const TargetRegisterInfo *TRI = &getRegisterInfo();
2939 if (MI && IsThumb1) {
2940 --I;
2941 if (I != E && !MI->readsRegister(ARM::CPSR, TRI)) {
2942 bool CanReorder = true;
2943 for (; I != E; --I) {
2944 if (I->getOpcode() != ARM::tMOVi8) {
2945 CanReorder = false;
2946 break;
2949 if (CanReorder) {
2950 MI = MI->removeFromParent();
2951 E = CmpInstr;
2952 CmpInstr.getParent()->insert(E, MI);
2955 I = CmpInstr;
2956 E = MI;
2959 // Check that CPSR isn't set between the comparison instruction and the one we
2960 // want to change. At the same time, search for SubAdd.
2961 bool SubAddIsThumb1 = false;
2962 do {
2963 const MachineInstr &Instr = *--I;
2965 // Check whether CmpInstr can be made redundant by the current instruction.
2966 if (isRedundantFlagInstr(&CmpInstr, SrcReg, SrcReg2, CmpValue, &Instr,
2967 SubAddIsThumb1)) {
2968 SubAdd = &*I;
2969 break;
2972 // Allow E (which was initially MI) to be SubAdd but do not search before E.
2973 if (I == E)
2974 break;
2976 if (Instr.modifiesRegister(ARM::CPSR, TRI) ||
2977 Instr.readsRegister(ARM::CPSR, TRI))
2978 // This instruction modifies or uses CPSR after the one we want to
2979 // change. We can't do this transformation.
2980 return false;
2982 if (I == B) {
2983 // In some cases, we scan the use-list of an instruction for an AND;
2984 // that AND is in the same BB, but may not be scheduled before the
2985 // corresponding TST. In that case, bail out.
2987 // FIXME: We could try to reschedule the AND.
2988 return false;
2990 } while (true);
2992 // Return false if no candidates exist.
2993 if (!MI && !SubAdd)
2994 return false;
2996 // If we found a SubAdd, use it as it will be closer to the CMP
2997 if (SubAdd) {
2998 MI = SubAdd;
2999 IsThumb1 = SubAddIsThumb1;
3002 // We can't use a predicated instruction - it doesn't always write the flags.
3003 if (isPredicated(*MI))
3004 return false;
3006 // Scan forward for the use of CPSR
3007 // When checking against MI: if it's a conditional code that requires
3008 // checking of the V bit or C bit, then this is not safe to do.
3009 // It is safe to remove CmpInstr if CPSR is redefined or killed.
3010 // If we are done with the basic block, we need to check whether CPSR is
3011 // live-out.
3012 SmallVector<std::pair<MachineOperand*, ARMCC::CondCodes>, 4>
3013 OperandsToUpdate;
3014 bool isSafe = false;
3015 I = CmpInstr;
3016 E = CmpInstr.getParent()->end();
3017 while (!isSafe && ++I != E) {
3018 const MachineInstr &Instr = *I;
3019 for (unsigned IO = 0, EO = Instr.getNumOperands();
3020 !isSafe && IO != EO; ++IO) {
3021 const MachineOperand &MO = Instr.getOperand(IO);
3022 if (MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) {
3023 isSafe = true;
3024 break;
3026 if (!MO.isReg() || MO.getReg() != ARM::CPSR)
3027 continue;
3028 if (MO.isDef()) {
3029 isSafe = true;
3030 break;
3032 // Condition code is after the operand before CPSR except for VSELs.
3033 ARMCC::CondCodes CC;
3034 bool IsInstrVSel = true;
3035 switch (Instr.getOpcode()) {
3036 default:
3037 IsInstrVSel = false;
3038 CC = (ARMCC::CondCodes)Instr.getOperand(IO - 1).getImm();
3039 break;
3040 case ARM::VSELEQD:
3041 case ARM::VSELEQS:
3042 CC = ARMCC::EQ;
3043 break;
3044 case ARM::VSELGTD:
3045 case ARM::VSELGTS:
3046 CC = ARMCC::GT;
3047 break;
3048 case ARM::VSELGED:
3049 case ARM::VSELGES:
3050 CC = ARMCC::GE;
3051 break;
3052 case ARM::VSELVSS:
3053 case ARM::VSELVSD:
3054 CC = ARMCC::VS;
3055 break;
3058 if (SubAdd) {
3059 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based
3060 // on CMP needs to be updated to be based on SUB.
3061 // If we have ADD(r1, r2, X) and CMP(r1, r2), the condition code also
3062 // needs to be modified.
3063 // Push the condition code operands to OperandsToUpdate.
3064 // If it is safe to remove CmpInstr, the condition code of these
3065 // operands will be modified.
3066 unsigned Opc = SubAdd->getOpcode();
3067 bool IsSub = Opc == ARM::SUBrr || Opc == ARM::t2SUBrr ||
3068 Opc == ARM::SUBri || Opc == ARM::t2SUBri ||
3069 Opc == ARM::tSUBrr || Opc == ARM::tSUBi3 ||
3070 Opc == ARM::tSUBi8;
3071 unsigned OpI = Opc != ARM::tSUBrr ? 1 : 2;
3072 if (!IsSub ||
3073 (SrcReg2 != 0 && SubAdd->getOperand(OpI).getReg() == SrcReg2 &&
3074 SubAdd->getOperand(OpI + 1).getReg() == SrcReg)) {
3075 // VSel doesn't support condition code update.
3076 if (IsInstrVSel)
3077 return false;
3078 // Ensure we can swap the condition.
3079 ARMCC::CondCodes NewCC = (IsSub ? getSwappedCondition(CC) : getCmpToAddCondition(CC));
3080 if (NewCC == ARMCC::AL)
3081 return false;
3082 OperandsToUpdate.push_back(
3083 std::make_pair(&((*I).getOperand(IO - 1)), NewCC));
3085 } else {
3086 // No SubAdd, so this is x = <op> y, z; cmp x, 0.
3087 switch (CC) {
3088 case ARMCC::EQ: // Z
3089 case ARMCC::NE: // Z
3090 case ARMCC::MI: // N
3091 case ARMCC::PL: // N
3092 case ARMCC::AL: // none
3093 // CPSR can be used multiple times, we should continue.
3094 break;
3095 case ARMCC::HS: // C
3096 case ARMCC::LO: // C
3097 case ARMCC::VS: // V
3098 case ARMCC::VC: // V
3099 case ARMCC::HI: // C Z
3100 case ARMCC::LS: // C Z
3101 case ARMCC::GE: // N V
3102 case ARMCC::LT: // N V
3103 case ARMCC::GT: // Z N V
3104 case ARMCC::LE: // Z N V
3105 // The instruction uses the V bit or C bit which is not safe.
3106 return false;
3112 // If CPSR is not killed nor re-defined, we should check whether it is
3113 // live-out. If it is live-out, do not optimize.
3114 if (!isSafe) {
3115 MachineBasicBlock *MBB = CmpInstr.getParent();
3116 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
3117 SE = MBB->succ_end(); SI != SE; ++SI)
3118 if ((*SI)->isLiveIn(ARM::CPSR))
3119 return false;
3122 // Toggle the optional operand to CPSR (if it exists - in Thumb1 we always
3123 // set CPSR so this is represented as an explicit output)
3124 if (!IsThumb1) {
3125 MI->getOperand(5).setReg(ARM::CPSR);
3126 MI->getOperand(5).setIsDef(true);
3128 assert(!isPredicated(*MI) && "Can't use flags from predicated instruction");
3129 CmpInstr.eraseFromParent();
3131 // Modify the condition code of operands in OperandsToUpdate.
3132 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
3133 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
3134 for (unsigned i = 0, e = OperandsToUpdate.size(); i < e; i++)
3135 OperandsToUpdate[i].first->setImm(OperandsToUpdate[i].second);
3137 MI->clearRegisterDeads(ARM::CPSR);
3139 return true;
3142 bool ARMBaseInstrInfo::shouldSink(const MachineInstr &MI) const {
3143 // Do not sink MI if it might be used to optimize a redundant compare.
3144 // We heuristically only look at the instruction immediately following MI to
3145 // avoid potentially searching the entire basic block.
3146 if (isPredicated(MI))
3147 return true;
3148 MachineBasicBlock::const_iterator Next = &MI;
3149 ++Next;
3150 unsigned SrcReg, SrcReg2;
3151 int CmpMask, CmpValue;
3152 bool IsThumb1;
3153 if (Next != MI.getParent()->end() &&
3154 analyzeCompare(*Next, SrcReg, SrcReg2, CmpMask, CmpValue) &&
3155 isRedundantFlagInstr(&*Next, SrcReg, SrcReg2, CmpValue, &MI, IsThumb1))
3156 return false;
3157 return true;
3160 bool ARMBaseInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
3161 unsigned Reg,
3162 MachineRegisterInfo *MRI) const {
3163 // Fold large immediates into add, sub, or, xor.
3164 unsigned DefOpc = DefMI.getOpcode();
3165 if (DefOpc != ARM::t2MOVi32imm && DefOpc != ARM::MOVi32imm)
3166 return false;
3167 if (!DefMI.getOperand(1).isImm())
3168 // Could be t2MOVi32imm @xx
3169 return false;
3171 if (!MRI->hasOneNonDBGUse(Reg))
3172 return false;
3174 const MCInstrDesc &DefMCID = DefMI.getDesc();
3175 if (DefMCID.hasOptionalDef()) {
3176 unsigned NumOps = DefMCID.getNumOperands();
3177 const MachineOperand &MO = DefMI.getOperand(NumOps - 1);
3178 if (MO.getReg() == ARM::CPSR && !MO.isDead())
3179 // If DefMI defines CPSR and it is not dead, it's obviously not safe
3180 // to delete DefMI.
3181 return false;
3184 const MCInstrDesc &UseMCID = UseMI.getDesc();
3185 if (UseMCID.hasOptionalDef()) {
3186 unsigned NumOps = UseMCID.getNumOperands();
3187 if (UseMI.getOperand(NumOps - 1).getReg() == ARM::CPSR)
3188 // If the instruction sets the flag, do not attempt this optimization
3189 // since it may change the semantics of the code.
3190 return false;
3193 unsigned UseOpc = UseMI.getOpcode();
3194 unsigned NewUseOpc = 0;
3195 uint32_t ImmVal = (uint32_t)DefMI.getOperand(1).getImm();
3196 uint32_t SOImmValV1 = 0, SOImmValV2 = 0;
3197 bool Commute = false;
3198 switch (UseOpc) {
3199 default: return false;
3200 case ARM::SUBrr:
3201 case ARM::ADDrr:
3202 case ARM::ORRrr:
3203 case ARM::EORrr:
3204 case ARM::t2SUBrr:
3205 case ARM::t2ADDrr:
3206 case ARM::t2ORRrr:
3207 case ARM::t2EORrr: {
3208 Commute = UseMI.getOperand(2).getReg() != Reg;
3209 switch (UseOpc) {
3210 default: break;
3211 case ARM::ADDrr:
3212 case ARM::SUBrr:
3213 if (UseOpc == ARM::SUBrr && Commute)
3214 return false;
3216 // ADD/SUB are special because they're essentially the same operation, so
3217 // we can handle a larger range of immediates.
3218 if (ARM_AM::isSOImmTwoPartVal(ImmVal))
3219 NewUseOpc = UseOpc == ARM::ADDrr ? ARM::ADDri : ARM::SUBri;
3220 else if (ARM_AM::isSOImmTwoPartVal(-ImmVal)) {
3221 ImmVal = -ImmVal;
3222 NewUseOpc = UseOpc == ARM::ADDrr ? ARM::SUBri : ARM::ADDri;
3223 } else
3224 return false;
3225 SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal);
3226 SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal);
3227 break;
3228 case ARM::ORRrr:
3229 case ARM::EORrr:
3230 if (!ARM_AM::isSOImmTwoPartVal(ImmVal))
3231 return false;
3232 SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal);
3233 SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal);
3234 switch (UseOpc) {
3235 default: break;
3236 case ARM::ORRrr: NewUseOpc = ARM::ORRri; break;
3237 case ARM::EORrr: NewUseOpc = ARM::EORri; break;
3239 break;
3240 case ARM::t2ADDrr:
3241 case ARM::t2SUBrr:
3242 if (UseOpc == ARM::t2SUBrr && Commute)
3243 return false;
3245 // ADD/SUB are special because they're essentially the same operation, so
3246 // we can handle a larger range of immediates.
3247 if (ARM_AM::isT2SOImmTwoPartVal(ImmVal))
3248 NewUseOpc = UseOpc == ARM::t2ADDrr ? ARM::t2ADDri : ARM::t2SUBri;
3249 else if (ARM_AM::isT2SOImmTwoPartVal(-ImmVal)) {
3250 ImmVal = -ImmVal;
3251 NewUseOpc = UseOpc == ARM::t2ADDrr ? ARM::t2SUBri : ARM::t2ADDri;
3252 } else
3253 return false;
3254 SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal);
3255 SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal);
3256 break;
3257 case ARM::t2ORRrr:
3258 case ARM::t2EORrr:
3259 if (!ARM_AM::isT2SOImmTwoPartVal(ImmVal))
3260 return false;
3261 SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal);
3262 SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal);
3263 switch (UseOpc) {
3264 default: break;
3265 case ARM::t2ORRrr: NewUseOpc = ARM::t2ORRri; break;
3266 case ARM::t2EORrr: NewUseOpc = ARM::t2EORri; break;
3268 break;
3273 unsigned OpIdx = Commute ? 2 : 1;
3274 unsigned Reg1 = UseMI.getOperand(OpIdx).getReg();
3275 bool isKill = UseMI.getOperand(OpIdx).isKill();
3276 unsigned NewReg = MRI->createVirtualRegister(MRI->getRegClass(Reg));
3277 BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(), get(NewUseOpc),
3278 NewReg)
3279 .addReg(Reg1, getKillRegState(isKill))
3280 .addImm(SOImmValV1)
3281 .add(predOps(ARMCC::AL))
3282 .add(condCodeOp());
3283 UseMI.setDesc(get(NewUseOpc));
3284 UseMI.getOperand(1).setReg(NewReg);
3285 UseMI.getOperand(1).setIsKill();
3286 UseMI.getOperand(2).ChangeToImmediate(SOImmValV2);
3287 DefMI.eraseFromParent();
3288 return true;
3291 static unsigned getNumMicroOpsSwiftLdSt(const InstrItineraryData *ItinData,
3292 const MachineInstr &MI) {
3293 switch (MI.getOpcode()) {
3294 default: {
3295 const MCInstrDesc &Desc = MI.getDesc();
3296 int UOps = ItinData->getNumMicroOps(Desc.getSchedClass());
3297 assert(UOps >= 0 && "bad # UOps");
3298 return UOps;
3301 case ARM::LDRrs:
3302 case ARM::LDRBrs:
3303 case ARM::STRrs:
3304 case ARM::STRBrs: {
3305 unsigned ShOpVal = MI.getOperand(3).getImm();
3306 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3307 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3308 if (!isSub &&
3309 (ShImm == 0 ||
3310 ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3311 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3312 return 1;
3313 return 2;
3316 case ARM::LDRH:
3317 case ARM::STRH: {
3318 if (!MI.getOperand(2).getReg())
3319 return 1;
3321 unsigned ShOpVal = MI.getOperand(3).getImm();
3322 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3323 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3324 if (!isSub &&
3325 (ShImm == 0 ||
3326 ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3327 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3328 return 1;
3329 return 2;
3332 case ARM::LDRSB:
3333 case ARM::LDRSH:
3334 return (ARM_AM::getAM3Op(MI.getOperand(3).getImm()) == ARM_AM::sub) ? 3 : 2;
3336 case ARM::LDRSB_POST:
3337 case ARM::LDRSH_POST: {
3338 unsigned Rt = MI.getOperand(0).getReg();
3339 unsigned Rm = MI.getOperand(3).getReg();
3340 return (Rt == Rm) ? 4 : 3;
3343 case ARM::LDR_PRE_REG:
3344 case ARM::LDRB_PRE_REG: {
3345 unsigned Rt = MI.getOperand(0).getReg();
3346 unsigned Rm = MI.getOperand(3).getReg();
3347 if (Rt == Rm)
3348 return 3;
3349 unsigned ShOpVal = MI.getOperand(4).getImm();
3350 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3351 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3352 if (!isSub &&
3353 (ShImm == 0 ||
3354 ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3355 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3356 return 2;
3357 return 3;
3360 case ARM::STR_PRE_REG:
3361 case ARM::STRB_PRE_REG: {
3362 unsigned ShOpVal = MI.getOperand(4).getImm();
3363 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3364 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3365 if (!isSub &&
3366 (ShImm == 0 ||
3367 ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3368 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3369 return 2;
3370 return 3;
3373 case ARM::LDRH_PRE:
3374 case ARM::STRH_PRE: {
3375 unsigned Rt = MI.getOperand(0).getReg();
3376 unsigned Rm = MI.getOperand(3).getReg();
3377 if (!Rm)
3378 return 2;
3379 if (Rt == Rm)
3380 return 3;
3381 return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 3 : 2;
3384 case ARM::LDR_POST_REG:
3385 case ARM::LDRB_POST_REG:
3386 case ARM::LDRH_POST: {
3387 unsigned Rt = MI.getOperand(0).getReg();
3388 unsigned Rm = MI.getOperand(3).getReg();
3389 return (Rt == Rm) ? 3 : 2;
3392 case ARM::LDR_PRE_IMM:
3393 case ARM::LDRB_PRE_IMM:
3394 case ARM::LDR_POST_IMM:
3395 case ARM::LDRB_POST_IMM:
3396 case ARM::STRB_POST_IMM:
3397 case ARM::STRB_POST_REG:
3398 case ARM::STRB_PRE_IMM:
3399 case ARM::STRH_POST:
3400 case ARM::STR_POST_IMM:
3401 case ARM::STR_POST_REG:
3402 case ARM::STR_PRE_IMM:
3403 return 2;
3405 case ARM::LDRSB_PRE:
3406 case ARM::LDRSH_PRE: {
3407 unsigned Rm = MI.getOperand(3).getReg();
3408 if (Rm == 0)
3409 return 3;
3410 unsigned Rt = MI.getOperand(0).getReg();
3411 if (Rt == Rm)
3412 return 4;
3413 unsigned ShOpVal = MI.getOperand(4).getImm();
3414 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3415 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3416 if (!isSub &&
3417 (ShImm == 0 ||
3418 ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3419 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3420 return 3;
3421 return 4;
3424 case ARM::LDRD: {
3425 unsigned Rt = MI.getOperand(0).getReg();
3426 unsigned Rn = MI.getOperand(2).getReg();
3427 unsigned Rm = MI.getOperand(3).getReg();
3428 if (Rm)
3429 return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 4
3430 : 3;
3431 return (Rt == Rn) ? 3 : 2;
3434 case ARM::STRD: {
3435 unsigned Rm = MI.getOperand(3).getReg();
3436 if (Rm)
3437 return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 4
3438 : 3;
3439 return 2;
3442 case ARM::LDRD_POST:
3443 case ARM::t2LDRD_POST:
3444 return 3;
3446 case ARM::STRD_POST:
3447 case ARM::t2STRD_POST:
3448 return 4;
3450 case ARM::LDRD_PRE: {
3451 unsigned Rt = MI.getOperand(0).getReg();
3452 unsigned Rn = MI.getOperand(3).getReg();
3453 unsigned Rm = MI.getOperand(4).getReg();
3454 if (Rm)
3455 return (ARM_AM::getAM3Op(MI.getOperand(5).getImm()) == ARM_AM::sub) ? 5
3456 : 4;
3457 return (Rt == Rn) ? 4 : 3;
3460 case ARM::t2LDRD_PRE: {
3461 unsigned Rt = MI.getOperand(0).getReg();
3462 unsigned Rn = MI.getOperand(3).getReg();
3463 return (Rt == Rn) ? 4 : 3;
3466 case ARM::STRD_PRE: {
3467 unsigned Rm = MI.getOperand(4).getReg();
3468 if (Rm)
3469 return (ARM_AM::getAM3Op(MI.getOperand(5).getImm()) == ARM_AM::sub) ? 5
3470 : 4;
3471 return 3;
3474 case ARM::t2STRD_PRE:
3475 return 3;
3477 case ARM::t2LDR_POST:
3478 case ARM::t2LDRB_POST:
3479 case ARM::t2LDRB_PRE:
3480 case ARM::t2LDRSBi12:
3481 case ARM::t2LDRSBi8:
3482 case ARM::t2LDRSBpci:
3483 case ARM::t2LDRSBs:
3484 case ARM::t2LDRH_POST:
3485 case ARM::t2LDRH_PRE:
3486 case ARM::t2LDRSBT:
3487 case ARM::t2LDRSB_POST:
3488 case ARM::t2LDRSB_PRE:
3489 case ARM::t2LDRSH_POST:
3490 case ARM::t2LDRSH_PRE:
3491 case ARM::t2LDRSHi12:
3492 case ARM::t2LDRSHi8:
3493 case ARM::t2LDRSHpci:
3494 case ARM::t2LDRSHs:
3495 return 2;
3497 case ARM::t2LDRDi8: {
3498 unsigned Rt = MI.getOperand(0).getReg();
3499 unsigned Rn = MI.getOperand(2).getReg();
3500 return (Rt == Rn) ? 3 : 2;
3503 case ARM::t2STRB_POST:
3504 case ARM::t2STRB_PRE:
3505 case ARM::t2STRBs:
3506 case ARM::t2STRDi8:
3507 case ARM::t2STRH_POST:
3508 case ARM::t2STRH_PRE:
3509 case ARM::t2STRHs:
3510 case ARM::t2STR_POST:
3511 case ARM::t2STR_PRE:
3512 case ARM::t2STRs:
3513 return 2;
3517 // Return the number of 32-bit words loaded by LDM or stored by STM. If this
3518 // can't be easily determined return 0 (missing MachineMemOperand).
3520 // FIXME: The current MachineInstr design does not support relying on machine
3521 // mem operands to determine the width of a memory access. Instead, we expect
3522 // the target to provide this information based on the instruction opcode and
3523 // operands. However, using MachineMemOperand is the best solution now for
3524 // two reasons:
3526 // 1) getNumMicroOps tries to infer LDM memory width from the total number of MI
3527 // operands. This is much more dangerous than using the MachineMemOperand
3528 // sizes because CodeGen passes can insert/remove optional machine operands. In
3529 // fact, it's totally incorrect for preRA passes and appears to be wrong for
3530 // postRA passes as well.
3532 // 2) getNumLDMAddresses is only used by the scheduling machine model and any
3533 // machine model that calls this should handle the unknown (zero size) case.
3535 // Long term, we should require a target hook that verifies MachineMemOperand
3536 // sizes during MC lowering. That target hook should be local to MC lowering
3537 // because we can't ensure that it is aware of other MI forms. Doing this will
3538 // ensure that MachineMemOperands are correctly propagated through all passes.
3539 unsigned ARMBaseInstrInfo::getNumLDMAddresses(const MachineInstr &MI) const {
3540 unsigned Size = 0;
3541 for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
3542 E = MI.memoperands_end();
3543 I != E; ++I) {
3544 Size += (*I)->getSize();
3546 // FIXME: The scheduler currently can't handle values larger than 16. But
3547 // the values can actually go up to 32 for floating-point load/store
3548 // multiple (VLDMIA etc.). Also, the way this code is reasoning about memory
3549 // operations isn't right; we could end up with "extra" memory operands for
3550 // various reasons, like tail merge merging two memory operations.
3551 return std::min(Size / 4, 16U);
3554 static unsigned getNumMicroOpsSingleIssuePlusExtras(unsigned Opc,
3555 unsigned NumRegs) {
3556 unsigned UOps = 1 + NumRegs; // 1 for address computation.
3557 switch (Opc) {
3558 default:
3559 break;
3560 case ARM::VLDMDIA_UPD:
3561 case ARM::VLDMDDB_UPD:
3562 case ARM::VLDMSIA_UPD:
3563 case ARM::VLDMSDB_UPD:
3564 case ARM::VSTMDIA_UPD:
3565 case ARM::VSTMDDB_UPD:
3566 case ARM::VSTMSIA_UPD:
3567 case ARM::VSTMSDB_UPD:
3568 case ARM::LDMIA_UPD:
3569 case ARM::LDMDA_UPD:
3570 case ARM::LDMDB_UPD:
3571 case ARM::LDMIB_UPD:
3572 case ARM::STMIA_UPD:
3573 case ARM::STMDA_UPD:
3574 case ARM::STMDB_UPD:
3575 case ARM::STMIB_UPD:
3576 case ARM::tLDMIA_UPD:
3577 case ARM::tSTMIA_UPD:
3578 case ARM::t2LDMIA_UPD:
3579 case ARM::t2LDMDB_UPD:
3580 case ARM::t2STMIA_UPD:
3581 case ARM::t2STMDB_UPD:
3582 ++UOps; // One for base register writeback.
3583 break;
3584 case ARM::LDMIA_RET:
3585 case ARM::tPOP_RET:
3586 case ARM::t2LDMIA_RET:
3587 UOps += 2; // One for base reg wb, one for write to pc.
3588 break;
3590 return UOps;
3593 unsigned ARMBaseInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
3594 const MachineInstr &MI) const {
3595 if (!ItinData || ItinData->isEmpty())
3596 return 1;
3598 const MCInstrDesc &Desc = MI.getDesc();
3599 unsigned Class = Desc.getSchedClass();
3600 int ItinUOps = ItinData->getNumMicroOps(Class);
3601 if (ItinUOps >= 0) {
3602 if (Subtarget.isSwift() && (Desc.mayLoad() || Desc.mayStore()))
3603 return getNumMicroOpsSwiftLdSt(ItinData, MI);
3605 return ItinUOps;
3608 unsigned Opc = MI.getOpcode();
3609 switch (Opc) {
3610 default:
3611 llvm_unreachable("Unexpected multi-uops instruction!");
3612 case ARM::VLDMQIA:
3613 case ARM::VSTMQIA:
3614 return 2;
3616 // The number of uOps for load / store multiple are determined by the number
3617 // registers.
3619 // On Cortex-A8, each pair of register loads / stores can be scheduled on the
3620 // same cycle. The scheduling for the first load / store must be done
3621 // separately by assuming the address is not 64-bit aligned.
3623 // On Cortex-A9, the formula is simply (#reg / 2) + (#reg % 2). If the address
3624 // is not 64-bit aligned, then AGU would take an extra cycle. For VFP / NEON
3625 // load / store multiple, the formula is (#reg / 2) + (#reg % 2) + 1.
3626 case ARM::VLDMDIA:
3627 case ARM::VLDMDIA_UPD:
3628 case ARM::VLDMDDB_UPD:
3629 case ARM::VLDMSIA:
3630 case ARM::VLDMSIA_UPD:
3631 case ARM::VLDMSDB_UPD:
3632 case ARM::VSTMDIA:
3633 case ARM::VSTMDIA_UPD:
3634 case ARM::VSTMDDB_UPD:
3635 case ARM::VSTMSIA:
3636 case ARM::VSTMSIA_UPD:
3637 case ARM::VSTMSDB_UPD: {
3638 unsigned NumRegs = MI.getNumOperands() - Desc.getNumOperands();
3639 return (NumRegs / 2) + (NumRegs % 2) + 1;
3642 case ARM::LDMIA_RET:
3643 case ARM::LDMIA:
3644 case ARM::LDMDA:
3645 case ARM::LDMDB:
3646 case ARM::LDMIB:
3647 case ARM::LDMIA_UPD:
3648 case ARM::LDMDA_UPD:
3649 case ARM::LDMDB_UPD:
3650 case ARM::LDMIB_UPD:
3651 case ARM::STMIA:
3652 case ARM::STMDA:
3653 case ARM::STMDB:
3654 case ARM::STMIB:
3655 case ARM::STMIA_UPD:
3656 case ARM::STMDA_UPD:
3657 case ARM::STMDB_UPD:
3658 case ARM::STMIB_UPD:
3659 case ARM::tLDMIA:
3660 case ARM::tLDMIA_UPD:
3661 case ARM::tSTMIA_UPD:
3662 case ARM::tPOP_RET:
3663 case ARM::tPOP:
3664 case ARM::tPUSH:
3665 case ARM::t2LDMIA_RET:
3666 case ARM::t2LDMIA:
3667 case ARM::t2LDMDB:
3668 case ARM::t2LDMIA_UPD:
3669 case ARM::t2LDMDB_UPD:
3670 case ARM::t2STMIA:
3671 case ARM::t2STMDB:
3672 case ARM::t2STMIA_UPD:
3673 case ARM::t2STMDB_UPD: {
3674 unsigned NumRegs = MI.getNumOperands() - Desc.getNumOperands() + 1;
3675 switch (Subtarget.getLdStMultipleTiming()) {
3676 case ARMSubtarget::SingleIssuePlusExtras:
3677 return getNumMicroOpsSingleIssuePlusExtras(Opc, NumRegs);
3678 case ARMSubtarget::SingleIssue:
3679 // Assume the worst.
3680 return NumRegs;
3681 case ARMSubtarget::DoubleIssue: {
3682 if (NumRegs < 4)
3683 return 2;
3684 // 4 registers would be issued: 2, 2.
3685 // 5 registers would be issued: 2, 2, 1.
3686 unsigned UOps = (NumRegs / 2);
3687 if (NumRegs % 2)
3688 ++UOps;
3689 return UOps;
3691 case ARMSubtarget::DoubleIssueCheckUnalignedAccess: {
3692 unsigned UOps = (NumRegs / 2);
3693 // If there are odd number of registers or if it's not 64-bit aligned,
3694 // then it takes an extra AGU (Address Generation Unit) cycle.
3695 if ((NumRegs % 2) || !MI.hasOneMemOperand() ||
3696 (*MI.memoperands_begin())->getAlignment() < 8)
3697 ++UOps;
3698 return UOps;
3703 llvm_unreachable("Didn't find the number of microops");
3707 ARMBaseInstrInfo::getVLDMDefCycle(const InstrItineraryData *ItinData,
3708 const MCInstrDesc &DefMCID,
3709 unsigned DefClass,
3710 unsigned DefIdx, unsigned DefAlign) const {
3711 int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
3712 if (RegNo <= 0)
3713 // Def is the address writeback.
3714 return ItinData->getOperandCycle(DefClass, DefIdx);
3716 int DefCycle;
3717 if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
3718 // (regno / 2) + (regno % 2) + 1
3719 DefCycle = RegNo / 2 + 1;
3720 if (RegNo % 2)
3721 ++DefCycle;
3722 } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3723 DefCycle = RegNo;
3724 bool isSLoad = false;
3726 switch (DefMCID.getOpcode()) {
3727 default: break;
3728 case ARM::VLDMSIA:
3729 case ARM::VLDMSIA_UPD:
3730 case ARM::VLDMSDB_UPD:
3731 isSLoad = true;
3732 break;
3735 // If there are odd number of 'S' registers or if it's not 64-bit aligned,
3736 // then it takes an extra cycle.
3737 if ((isSLoad && (RegNo % 2)) || DefAlign < 8)
3738 ++DefCycle;
3739 } else {
3740 // Assume the worst.
3741 DefCycle = RegNo + 2;
3744 return DefCycle;
3747 bool ARMBaseInstrInfo::isLDMBaseRegInList(const MachineInstr &MI) const {
3748 unsigned BaseReg = MI.getOperand(0).getReg();
3749 for (unsigned i = 1, sz = MI.getNumOperands(); i < sz; ++i) {
3750 const auto &Op = MI.getOperand(i);
3751 if (Op.isReg() && Op.getReg() == BaseReg)
3752 return true;
3754 return false;
3756 unsigned
3757 ARMBaseInstrInfo::getLDMVariableDefsSize(const MachineInstr &MI) const {
3758 // ins GPR:$Rn, $p (2xOp), reglist:$regs, variable_ops
3759 // (outs GPR:$wb), (ins GPR:$Rn, $p (2xOp), reglist:$regs, variable_ops)
3760 return MI.getNumOperands() + 1 - MI.getDesc().getNumOperands();
3764 ARMBaseInstrInfo::getLDMDefCycle(const InstrItineraryData *ItinData,
3765 const MCInstrDesc &DefMCID,
3766 unsigned DefClass,
3767 unsigned DefIdx, unsigned DefAlign) const {
3768 int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
3769 if (RegNo <= 0)
3770 // Def is the address writeback.
3771 return ItinData->getOperandCycle(DefClass, DefIdx);
3773 int DefCycle;
3774 if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
3775 // 4 registers would be issued: 1, 2, 1.
3776 // 5 registers would be issued: 1, 2, 2.
3777 DefCycle = RegNo / 2;
3778 if (DefCycle < 1)
3779 DefCycle = 1;
3780 // Result latency is issue cycle + 2: E2.
3781 DefCycle += 2;
3782 } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3783 DefCycle = (RegNo / 2);
3784 // If there are odd number of registers or if it's not 64-bit aligned,
3785 // then it takes an extra AGU (Address Generation Unit) cycle.
3786 if ((RegNo % 2) || DefAlign < 8)
3787 ++DefCycle;
3788 // Result latency is AGU cycles + 2.
3789 DefCycle += 2;
3790 } else {
3791 // Assume the worst.
3792 DefCycle = RegNo + 2;
3795 return DefCycle;
3799 ARMBaseInstrInfo::getVSTMUseCycle(const InstrItineraryData *ItinData,
3800 const MCInstrDesc &UseMCID,
3801 unsigned UseClass,
3802 unsigned UseIdx, unsigned UseAlign) const {
3803 int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
3804 if (RegNo <= 0)
3805 return ItinData->getOperandCycle(UseClass, UseIdx);
3807 int UseCycle;
3808 if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
3809 // (regno / 2) + (regno % 2) + 1
3810 UseCycle = RegNo / 2 + 1;
3811 if (RegNo % 2)
3812 ++UseCycle;
3813 } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3814 UseCycle = RegNo;
3815 bool isSStore = false;
3817 switch (UseMCID.getOpcode()) {
3818 default: break;
3819 case ARM::VSTMSIA:
3820 case ARM::VSTMSIA_UPD:
3821 case ARM::VSTMSDB_UPD:
3822 isSStore = true;
3823 break;
3826 // If there are odd number of 'S' registers or if it's not 64-bit aligned,
3827 // then it takes an extra cycle.
3828 if ((isSStore && (RegNo % 2)) || UseAlign < 8)
3829 ++UseCycle;
3830 } else {
3831 // Assume the worst.
3832 UseCycle = RegNo + 2;
3835 return UseCycle;
3839 ARMBaseInstrInfo::getSTMUseCycle(const InstrItineraryData *ItinData,
3840 const MCInstrDesc &UseMCID,
3841 unsigned UseClass,
3842 unsigned UseIdx, unsigned UseAlign) const {
3843 int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
3844 if (RegNo <= 0)
3845 return ItinData->getOperandCycle(UseClass, UseIdx);
3847 int UseCycle;
3848 if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
3849 UseCycle = RegNo / 2;
3850 if (UseCycle < 2)
3851 UseCycle = 2;
3852 // Read in E3.
3853 UseCycle += 2;
3854 } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3855 UseCycle = (RegNo / 2);
3856 // If there are odd number of registers or if it's not 64-bit aligned,
3857 // then it takes an extra AGU (Address Generation Unit) cycle.
3858 if ((RegNo % 2) || UseAlign < 8)
3859 ++UseCycle;
3860 } else {
3861 // Assume the worst.
3862 UseCycle = 1;
3864 return UseCycle;
3868 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
3869 const MCInstrDesc &DefMCID,
3870 unsigned DefIdx, unsigned DefAlign,
3871 const MCInstrDesc &UseMCID,
3872 unsigned UseIdx, unsigned UseAlign) const {
3873 unsigned DefClass = DefMCID.getSchedClass();
3874 unsigned UseClass = UseMCID.getSchedClass();
3876 if (DefIdx < DefMCID.getNumDefs() && UseIdx < UseMCID.getNumOperands())
3877 return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
3879 // This may be a def / use of a variable_ops instruction, the operand
3880 // latency might be determinable dynamically. Let the target try to
3881 // figure it out.
3882 int DefCycle = -1;
3883 bool LdmBypass = false;
3884 switch (DefMCID.getOpcode()) {
3885 default:
3886 DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
3887 break;
3889 case ARM::VLDMDIA:
3890 case ARM::VLDMDIA_UPD:
3891 case ARM::VLDMDDB_UPD:
3892 case ARM::VLDMSIA:
3893 case ARM::VLDMSIA_UPD:
3894 case ARM::VLDMSDB_UPD:
3895 DefCycle = getVLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
3896 break;
3898 case ARM::LDMIA_RET:
3899 case ARM::LDMIA:
3900 case ARM::LDMDA:
3901 case ARM::LDMDB:
3902 case ARM::LDMIB:
3903 case ARM::LDMIA_UPD:
3904 case ARM::LDMDA_UPD:
3905 case ARM::LDMDB_UPD:
3906 case ARM::LDMIB_UPD:
3907 case ARM::tLDMIA:
3908 case ARM::tLDMIA_UPD:
3909 case ARM::tPUSH:
3910 case ARM::t2LDMIA_RET:
3911 case ARM::t2LDMIA:
3912 case ARM::t2LDMDB:
3913 case ARM::t2LDMIA_UPD:
3914 case ARM::t2LDMDB_UPD:
3915 LdmBypass = true;
3916 DefCycle = getLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
3917 break;
3920 if (DefCycle == -1)
3921 // We can't seem to determine the result latency of the def, assume it's 2.
3922 DefCycle = 2;
3924 int UseCycle = -1;
3925 switch (UseMCID.getOpcode()) {
3926 default:
3927 UseCycle = ItinData->getOperandCycle(UseClass, UseIdx);
3928 break;
3930 case ARM::VSTMDIA:
3931 case ARM::VSTMDIA_UPD:
3932 case ARM::VSTMDDB_UPD:
3933 case ARM::VSTMSIA:
3934 case ARM::VSTMSIA_UPD:
3935 case ARM::VSTMSDB_UPD:
3936 UseCycle = getVSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
3937 break;
3939 case ARM::STMIA:
3940 case ARM::STMDA:
3941 case ARM::STMDB:
3942 case ARM::STMIB:
3943 case ARM::STMIA_UPD:
3944 case ARM::STMDA_UPD:
3945 case ARM::STMDB_UPD:
3946 case ARM::STMIB_UPD:
3947 case ARM::tSTMIA_UPD:
3948 case ARM::tPOP_RET:
3949 case ARM::tPOP:
3950 case ARM::t2STMIA:
3951 case ARM::t2STMDB:
3952 case ARM::t2STMIA_UPD:
3953 case ARM::t2STMDB_UPD:
3954 UseCycle = getSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
3955 break;
3958 if (UseCycle == -1)
3959 // Assume it's read in the first stage.
3960 UseCycle = 1;
3962 UseCycle = DefCycle - UseCycle + 1;
3963 if (UseCycle > 0) {
3964 if (LdmBypass) {
3965 // It's a variable_ops instruction so we can't use DefIdx here. Just use
3966 // first def operand.
3967 if (ItinData->hasPipelineForwarding(DefClass, DefMCID.getNumOperands()-1,
3968 UseClass, UseIdx))
3969 --UseCycle;
3970 } else if (ItinData->hasPipelineForwarding(DefClass, DefIdx,
3971 UseClass, UseIdx)) {
3972 --UseCycle;
3976 return UseCycle;
3979 static const MachineInstr *getBundledDefMI(const TargetRegisterInfo *TRI,
3980 const MachineInstr *MI, unsigned Reg,
3981 unsigned &DefIdx, unsigned &Dist) {
3982 Dist = 0;
3984 MachineBasicBlock::const_iterator I = MI; ++I;
3985 MachineBasicBlock::const_instr_iterator II = std::prev(I.getInstrIterator());
3986 assert(II->isInsideBundle() && "Empty bundle?");
3988 int Idx = -1;
3989 while (II->isInsideBundle()) {
3990 Idx = II->findRegisterDefOperandIdx(Reg, false, true, TRI);
3991 if (Idx != -1)
3992 break;
3993 --II;
3994 ++Dist;
3997 assert(Idx != -1 && "Cannot find bundled definition!");
3998 DefIdx = Idx;
3999 return &*II;
4002 static const MachineInstr *getBundledUseMI(const TargetRegisterInfo *TRI,
4003 const MachineInstr &MI, unsigned Reg,
4004 unsigned &UseIdx, unsigned &Dist) {
4005 Dist = 0;
4007 MachineBasicBlock::const_instr_iterator II = ++MI.getIterator();
4008 assert(II->isInsideBundle() && "Empty bundle?");
4009 MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
4011 // FIXME: This doesn't properly handle multiple uses.
4012 int Idx = -1;
4013 while (II != E && II->isInsideBundle()) {
4014 Idx = II->findRegisterUseOperandIdx(Reg, false, TRI);
4015 if (Idx != -1)
4016 break;
4017 if (II->getOpcode() != ARM::t2IT)
4018 ++Dist;
4019 ++II;
4022 if (Idx == -1) {
4023 Dist = 0;
4024 return nullptr;
4027 UseIdx = Idx;
4028 return &*II;
4031 /// Return the number of cycles to add to (or subtract from) the static
4032 /// itinerary based on the def opcode and alignment. The caller will ensure that
4033 /// adjusted latency is at least one cycle.
4034 static int adjustDefLatency(const ARMSubtarget &Subtarget,
4035 const MachineInstr &DefMI,
4036 const MCInstrDesc &DefMCID, unsigned DefAlign) {
4037 int Adjust = 0;
4038 if (Subtarget.isCortexA8() || Subtarget.isLikeA9() || Subtarget.isCortexA7()) {
4039 // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
4040 // variants are one cycle cheaper.
4041 switch (DefMCID.getOpcode()) {
4042 default: break;
4043 case ARM::LDRrs:
4044 case ARM::LDRBrs: {
4045 unsigned ShOpVal = DefMI.getOperand(3).getImm();
4046 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
4047 if (ShImm == 0 ||
4048 (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
4049 --Adjust;
4050 break;
4052 case ARM::t2LDRs:
4053 case ARM::t2LDRBs:
4054 case ARM::t2LDRHs:
4055 case ARM::t2LDRSHs: {
4056 // Thumb2 mode: lsl only.
4057 unsigned ShAmt = DefMI.getOperand(3).getImm();
4058 if (ShAmt == 0 || ShAmt == 2)
4059 --Adjust;
4060 break;
4063 } else if (Subtarget.isSwift()) {
4064 // FIXME: Properly handle all of the latency adjustments for address
4065 // writeback.
4066 switch (DefMCID.getOpcode()) {
4067 default: break;
4068 case ARM::LDRrs:
4069 case ARM::LDRBrs: {
4070 unsigned ShOpVal = DefMI.getOperand(3).getImm();
4071 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
4072 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
4073 if (!isSub &&
4074 (ShImm == 0 ||
4075 ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
4076 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
4077 Adjust -= 2;
4078 else if (!isSub &&
4079 ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr)
4080 --Adjust;
4081 break;
4083 case ARM::t2LDRs:
4084 case ARM::t2LDRBs:
4085 case ARM::t2LDRHs:
4086 case ARM::t2LDRSHs: {
4087 // Thumb2 mode: lsl only.
4088 unsigned ShAmt = DefMI.getOperand(3).getImm();
4089 if (ShAmt == 0 || ShAmt == 1 || ShAmt == 2 || ShAmt == 3)
4090 Adjust -= 2;
4091 break;
4096 if (DefAlign < 8 && Subtarget.checkVLDnAccessAlignment()) {
4097 switch (DefMCID.getOpcode()) {
4098 default: break;
4099 case ARM::VLD1q8:
4100 case ARM::VLD1q16:
4101 case ARM::VLD1q32:
4102 case ARM::VLD1q64:
4103 case ARM::VLD1q8wb_fixed:
4104 case ARM::VLD1q16wb_fixed:
4105 case ARM::VLD1q32wb_fixed:
4106 case ARM::VLD1q64wb_fixed:
4107 case ARM::VLD1q8wb_register:
4108 case ARM::VLD1q16wb_register:
4109 case ARM::VLD1q32wb_register:
4110 case ARM::VLD1q64wb_register:
4111 case ARM::VLD2d8:
4112 case ARM::VLD2d16:
4113 case ARM::VLD2d32:
4114 case ARM::VLD2q8:
4115 case ARM::VLD2q16:
4116 case ARM::VLD2q32:
4117 case ARM::VLD2d8wb_fixed:
4118 case ARM::VLD2d16wb_fixed:
4119 case ARM::VLD2d32wb_fixed:
4120 case ARM::VLD2q8wb_fixed:
4121 case ARM::VLD2q16wb_fixed:
4122 case ARM::VLD2q32wb_fixed:
4123 case ARM::VLD2d8wb_register:
4124 case ARM::VLD2d16wb_register:
4125 case ARM::VLD2d32wb_register:
4126 case ARM::VLD2q8wb_register:
4127 case ARM::VLD2q16wb_register:
4128 case ARM::VLD2q32wb_register:
4129 case ARM::VLD3d8:
4130 case ARM::VLD3d16:
4131 case ARM::VLD3d32:
4132 case ARM::VLD1d64T:
4133 case ARM::VLD3d8_UPD:
4134 case ARM::VLD3d16_UPD:
4135 case ARM::VLD3d32_UPD:
4136 case ARM::VLD1d64Twb_fixed:
4137 case ARM::VLD1d64Twb_register:
4138 case ARM::VLD3q8_UPD:
4139 case ARM::VLD3q16_UPD:
4140 case ARM::VLD3q32_UPD:
4141 case ARM::VLD4d8:
4142 case ARM::VLD4d16:
4143 case ARM::VLD4d32:
4144 case ARM::VLD1d64Q:
4145 case ARM::VLD4d8_UPD:
4146 case ARM::VLD4d16_UPD:
4147 case ARM::VLD4d32_UPD:
4148 case ARM::VLD1d64Qwb_fixed:
4149 case ARM::VLD1d64Qwb_register:
4150 case ARM::VLD4q8_UPD:
4151 case ARM::VLD4q16_UPD:
4152 case ARM::VLD4q32_UPD:
4153 case ARM::VLD1DUPq8:
4154 case ARM::VLD1DUPq16:
4155 case ARM::VLD1DUPq32:
4156 case ARM::VLD1DUPq8wb_fixed:
4157 case ARM::VLD1DUPq16wb_fixed:
4158 case ARM::VLD1DUPq32wb_fixed:
4159 case ARM::VLD1DUPq8wb_register:
4160 case ARM::VLD1DUPq16wb_register:
4161 case ARM::VLD1DUPq32wb_register:
4162 case ARM::VLD2DUPd8:
4163 case ARM::VLD2DUPd16:
4164 case ARM::VLD2DUPd32:
4165 case ARM::VLD2DUPd8wb_fixed:
4166 case ARM::VLD2DUPd16wb_fixed:
4167 case ARM::VLD2DUPd32wb_fixed:
4168 case ARM::VLD2DUPd8wb_register:
4169 case ARM::VLD2DUPd16wb_register:
4170 case ARM::VLD2DUPd32wb_register:
4171 case ARM::VLD4DUPd8:
4172 case ARM::VLD4DUPd16:
4173 case ARM::VLD4DUPd32:
4174 case ARM::VLD4DUPd8_UPD:
4175 case ARM::VLD4DUPd16_UPD:
4176 case ARM::VLD4DUPd32_UPD:
4177 case ARM::VLD1LNd8:
4178 case ARM::VLD1LNd16:
4179 case ARM::VLD1LNd32:
4180 case ARM::VLD1LNd8_UPD:
4181 case ARM::VLD1LNd16_UPD:
4182 case ARM::VLD1LNd32_UPD:
4183 case ARM::VLD2LNd8:
4184 case ARM::VLD2LNd16:
4185 case ARM::VLD2LNd32:
4186 case ARM::VLD2LNq16:
4187 case ARM::VLD2LNq32:
4188 case ARM::VLD2LNd8_UPD:
4189 case ARM::VLD2LNd16_UPD:
4190 case ARM::VLD2LNd32_UPD:
4191 case ARM::VLD2LNq16_UPD:
4192 case ARM::VLD2LNq32_UPD:
4193 case ARM::VLD4LNd8:
4194 case ARM::VLD4LNd16:
4195 case ARM::VLD4LNd32:
4196 case ARM::VLD4LNq16:
4197 case ARM::VLD4LNq32:
4198 case ARM::VLD4LNd8_UPD:
4199 case ARM::VLD4LNd16_UPD:
4200 case ARM::VLD4LNd32_UPD:
4201 case ARM::VLD4LNq16_UPD:
4202 case ARM::VLD4LNq32_UPD:
4203 // If the address is not 64-bit aligned, the latencies of these
4204 // instructions increases by one.
4205 ++Adjust;
4206 break;
4209 return Adjust;
4212 int ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
4213 const MachineInstr &DefMI,
4214 unsigned DefIdx,
4215 const MachineInstr &UseMI,
4216 unsigned UseIdx) const {
4217 // No operand latency. The caller may fall back to getInstrLatency.
4218 if (!ItinData || ItinData->isEmpty())
4219 return -1;
4221 const MachineOperand &DefMO = DefMI.getOperand(DefIdx);
4222 unsigned Reg = DefMO.getReg();
4224 const MachineInstr *ResolvedDefMI = &DefMI;
4225 unsigned DefAdj = 0;
4226 if (DefMI.isBundle())
4227 ResolvedDefMI =
4228 getBundledDefMI(&getRegisterInfo(), &DefMI, Reg, DefIdx, DefAdj);
4229 if (ResolvedDefMI->isCopyLike() || ResolvedDefMI->isInsertSubreg() ||
4230 ResolvedDefMI->isRegSequence() || ResolvedDefMI->isImplicitDef()) {
4231 return 1;
4234 const MachineInstr *ResolvedUseMI = &UseMI;
4235 unsigned UseAdj = 0;
4236 if (UseMI.isBundle()) {
4237 ResolvedUseMI =
4238 getBundledUseMI(&getRegisterInfo(), UseMI, Reg, UseIdx, UseAdj);
4239 if (!ResolvedUseMI)
4240 return -1;
4243 return getOperandLatencyImpl(
4244 ItinData, *ResolvedDefMI, DefIdx, ResolvedDefMI->getDesc(), DefAdj, DefMO,
4245 Reg, *ResolvedUseMI, UseIdx, ResolvedUseMI->getDesc(), UseAdj);
4248 int ARMBaseInstrInfo::getOperandLatencyImpl(
4249 const InstrItineraryData *ItinData, const MachineInstr &DefMI,
4250 unsigned DefIdx, const MCInstrDesc &DefMCID, unsigned DefAdj,
4251 const MachineOperand &DefMO, unsigned Reg, const MachineInstr &UseMI,
4252 unsigned UseIdx, const MCInstrDesc &UseMCID, unsigned UseAdj) const {
4253 if (Reg == ARM::CPSR) {
4254 if (DefMI.getOpcode() == ARM::FMSTAT) {
4255 // fpscr -> cpsr stalls over 20 cycles on A8 (and earlier?)
4256 return Subtarget.isLikeA9() ? 1 : 20;
4259 // CPSR set and branch can be paired in the same cycle.
4260 if (UseMI.isBranch())
4261 return 0;
4263 // Otherwise it takes the instruction latency (generally one).
4264 unsigned Latency = getInstrLatency(ItinData, DefMI);
4266 // For Thumb2 and -Os, prefer scheduling CPSR setting instruction close to
4267 // its uses. Instructions which are otherwise scheduled between them may
4268 // incur a code size penalty (not able to use the CPSR setting 16-bit
4269 // instructions).
4270 if (Latency > 0 && Subtarget.isThumb2()) {
4271 const MachineFunction *MF = DefMI.getParent()->getParent();
4272 // FIXME: Use Function::hasOptSize().
4273 if (MF->getFunction().hasFnAttribute(Attribute::OptimizeForSize))
4274 --Latency;
4276 return Latency;
4279 if (DefMO.isImplicit() || UseMI.getOperand(UseIdx).isImplicit())
4280 return -1;
4282 unsigned DefAlign = DefMI.hasOneMemOperand()
4283 ? (*DefMI.memoperands_begin())->getAlignment()
4284 : 0;
4285 unsigned UseAlign = UseMI.hasOneMemOperand()
4286 ? (*UseMI.memoperands_begin())->getAlignment()
4287 : 0;
4289 // Get the itinerary's latency if possible, and handle variable_ops.
4290 int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign, UseMCID,
4291 UseIdx, UseAlign);
4292 // Unable to find operand latency. The caller may resort to getInstrLatency.
4293 if (Latency < 0)
4294 return Latency;
4296 // Adjust for IT block position.
4297 int Adj = DefAdj + UseAdj;
4299 // Adjust for dynamic def-side opcode variants not captured by the itinerary.
4300 Adj += adjustDefLatency(Subtarget, DefMI, DefMCID, DefAlign);
4301 if (Adj >= 0 || (int)Latency > -Adj) {
4302 return Latency + Adj;
4304 // Return the itinerary latency, which may be zero but not less than zero.
4305 return Latency;
4309 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
4310 SDNode *DefNode, unsigned DefIdx,
4311 SDNode *UseNode, unsigned UseIdx) const {
4312 if (!DefNode->isMachineOpcode())
4313 return 1;
4315 const MCInstrDesc &DefMCID = get(DefNode->getMachineOpcode());
4317 if (isZeroCost(DefMCID.Opcode))
4318 return 0;
4320 if (!ItinData || ItinData->isEmpty())
4321 return DefMCID.mayLoad() ? 3 : 1;
4323 if (!UseNode->isMachineOpcode()) {
4324 int Latency = ItinData->getOperandCycle(DefMCID.getSchedClass(), DefIdx);
4325 int Adj = Subtarget.getPreISelOperandLatencyAdjustment();
4326 int Threshold = 1 + Adj;
4327 return Latency <= Threshold ? 1 : Latency - Adj;
4330 const MCInstrDesc &UseMCID = get(UseNode->getMachineOpcode());
4331 const MachineSDNode *DefMN = dyn_cast<MachineSDNode>(DefNode);
4332 unsigned DefAlign = !DefMN->memoperands_empty()
4333 ? (*DefMN->memoperands_begin())->getAlignment() : 0;
4334 const MachineSDNode *UseMN = dyn_cast<MachineSDNode>(UseNode);
4335 unsigned UseAlign = !UseMN->memoperands_empty()
4336 ? (*UseMN->memoperands_begin())->getAlignment() : 0;
4337 int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign,
4338 UseMCID, UseIdx, UseAlign);
4340 if (Latency > 1 &&
4341 (Subtarget.isCortexA8() || Subtarget.isLikeA9() ||
4342 Subtarget.isCortexA7())) {
4343 // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
4344 // variants are one cycle cheaper.
4345 switch (DefMCID.getOpcode()) {
4346 default: break;
4347 case ARM::LDRrs:
4348 case ARM::LDRBrs: {
4349 unsigned ShOpVal =
4350 cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
4351 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
4352 if (ShImm == 0 ||
4353 (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
4354 --Latency;
4355 break;
4357 case ARM::t2LDRs:
4358 case ARM::t2LDRBs:
4359 case ARM::t2LDRHs:
4360 case ARM::t2LDRSHs: {
4361 // Thumb2 mode: lsl only.
4362 unsigned ShAmt =
4363 cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
4364 if (ShAmt == 0 || ShAmt == 2)
4365 --Latency;
4366 break;
4369 } else if (DefIdx == 0 && Latency > 2 && Subtarget.isSwift()) {
4370 // FIXME: Properly handle all of the latency adjustments for address
4371 // writeback.
4372 switch (DefMCID.getOpcode()) {
4373 default: break;
4374 case ARM::LDRrs:
4375 case ARM::LDRBrs: {
4376 unsigned ShOpVal =
4377 cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
4378 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
4379 if (ShImm == 0 ||
4380 ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
4381 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
4382 Latency -= 2;
4383 else if (ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr)
4384 --Latency;
4385 break;
4387 case ARM::t2LDRs:
4388 case ARM::t2LDRBs:
4389 case ARM::t2LDRHs:
4390 case ARM::t2LDRSHs:
4391 // Thumb2 mode: lsl 0-3 only.
4392 Latency -= 2;
4393 break;
4397 if (DefAlign < 8 && Subtarget.checkVLDnAccessAlignment())
4398 switch (DefMCID.getOpcode()) {
4399 default: break;
4400 case ARM::VLD1q8:
4401 case ARM::VLD1q16:
4402 case ARM::VLD1q32:
4403 case ARM::VLD1q64:
4404 case ARM::VLD1q8wb_register:
4405 case ARM::VLD1q16wb_register:
4406 case ARM::VLD1q32wb_register:
4407 case ARM::VLD1q64wb_register:
4408 case ARM::VLD1q8wb_fixed:
4409 case ARM::VLD1q16wb_fixed:
4410 case ARM::VLD1q32wb_fixed:
4411 case ARM::VLD1q64wb_fixed:
4412 case ARM::VLD2d8:
4413 case ARM::VLD2d16:
4414 case ARM::VLD2d32:
4415 case ARM::VLD2q8Pseudo:
4416 case ARM::VLD2q16Pseudo:
4417 case ARM::VLD2q32Pseudo:
4418 case ARM::VLD2d8wb_fixed:
4419 case ARM::VLD2d16wb_fixed:
4420 case ARM::VLD2d32wb_fixed:
4421 case ARM::VLD2q8PseudoWB_fixed:
4422 case ARM::VLD2q16PseudoWB_fixed:
4423 case ARM::VLD2q32PseudoWB_fixed:
4424 case ARM::VLD2d8wb_register:
4425 case ARM::VLD2d16wb_register:
4426 case ARM::VLD2d32wb_register:
4427 case ARM::VLD2q8PseudoWB_register:
4428 case ARM::VLD2q16PseudoWB_register:
4429 case ARM::VLD2q32PseudoWB_register:
4430 case ARM::VLD3d8Pseudo:
4431 case ARM::VLD3d16Pseudo:
4432 case ARM::VLD3d32Pseudo:
4433 case ARM::VLD1d8TPseudo:
4434 case ARM::VLD1d16TPseudo:
4435 case ARM::VLD1d32TPseudo:
4436 case ARM::VLD1d64TPseudo:
4437 case ARM::VLD1d64TPseudoWB_fixed:
4438 case ARM::VLD1d64TPseudoWB_register:
4439 case ARM::VLD3d8Pseudo_UPD:
4440 case ARM::VLD3d16Pseudo_UPD:
4441 case ARM::VLD3d32Pseudo_UPD:
4442 case ARM::VLD3q8Pseudo_UPD:
4443 case ARM::VLD3q16Pseudo_UPD:
4444 case ARM::VLD3q32Pseudo_UPD:
4445 case ARM::VLD3q8oddPseudo:
4446 case ARM::VLD3q16oddPseudo:
4447 case ARM::VLD3q32oddPseudo:
4448 case ARM::VLD3q8oddPseudo_UPD:
4449 case ARM::VLD3q16oddPseudo_UPD:
4450 case ARM::VLD3q32oddPseudo_UPD:
4451 case ARM::VLD4d8Pseudo:
4452 case ARM::VLD4d16Pseudo:
4453 case ARM::VLD4d32Pseudo:
4454 case ARM::VLD1d8QPseudo:
4455 case ARM::VLD1d16QPseudo:
4456 case ARM::VLD1d32QPseudo:
4457 case ARM::VLD1d64QPseudo:
4458 case ARM::VLD1d64QPseudoWB_fixed:
4459 case ARM::VLD1d64QPseudoWB_register:
4460 case ARM::VLD1q8HighQPseudo:
4461 case ARM::VLD1q8LowQPseudo_UPD:
4462 case ARM::VLD1q8HighTPseudo:
4463 case ARM::VLD1q8LowTPseudo_UPD:
4464 case ARM::VLD1q16HighQPseudo:
4465 case ARM::VLD1q16LowQPseudo_UPD:
4466 case ARM::VLD1q16HighTPseudo:
4467 case ARM::VLD1q16LowTPseudo_UPD:
4468 case ARM::VLD1q32HighQPseudo:
4469 case ARM::VLD1q32LowQPseudo_UPD:
4470 case ARM::VLD1q32HighTPseudo:
4471 case ARM::VLD1q32LowTPseudo_UPD:
4472 case ARM::VLD1q64HighQPseudo:
4473 case ARM::VLD1q64LowQPseudo_UPD:
4474 case ARM::VLD1q64HighTPseudo:
4475 case ARM::VLD1q64LowTPseudo_UPD:
4476 case ARM::VLD4d8Pseudo_UPD:
4477 case ARM::VLD4d16Pseudo_UPD:
4478 case ARM::VLD4d32Pseudo_UPD:
4479 case ARM::VLD4q8Pseudo_UPD:
4480 case ARM::VLD4q16Pseudo_UPD:
4481 case ARM::VLD4q32Pseudo_UPD:
4482 case ARM::VLD4q8oddPseudo:
4483 case ARM::VLD4q16oddPseudo:
4484 case ARM::VLD4q32oddPseudo:
4485 case ARM::VLD4q8oddPseudo_UPD:
4486 case ARM::VLD4q16oddPseudo_UPD:
4487 case ARM::VLD4q32oddPseudo_UPD:
4488 case ARM::VLD1DUPq8:
4489 case ARM::VLD1DUPq16:
4490 case ARM::VLD1DUPq32:
4491 case ARM::VLD1DUPq8wb_fixed:
4492 case ARM::VLD1DUPq16wb_fixed:
4493 case ARM::VLD1DUPq32wb_fixed:
4494 case ARM::VLD1DUPq8wb_register:
4495 case ARM::VLD1DUPq16wb_register:
4496 case ARM::VLD1DUPq32wb_register:
4497 case ARM::VLD2DUPd8:
4498 case ARM::VLD2DUPd16:
4499 case ARM::VLD2DUPd32:
4500 case ARM::VLD2DUPd8wb_fixed:
4501 case ARM::VLD2DUPd16wb_fixed:
4502 case ARM::VLD2DUPd32wb_fixed:
4503 case ARM::VLD2DUPd8wb_register:
4504 case ARM::VLD2DUPd16wb_register:
4505 case ARM::VLD2DUPd32wb_register:
4506 case ARM::VLD2DUPq8EvenPseudo:
4507 case ARM::VLD2DUPq8OddPseudo:
4508 case ARM::VLD2DUPq16EvenPseudo:
4509 case ARM::VLD2DUPq16OddPseudo:
4510 case ARM::VLD2DUPq32EvenPseudo:
4511 case ARM::VLD2DUPq32OddPseudo:
4512 case ARM::VLD3DUPq8EvenPseudo:
4513 case ARM::VLD3DUPq8OddPseudo:
4514 case ARM::VLD3DUPq16EvenPseudo:
4515 case ARM::VLD3DUPq16OddPseudo:
4516 case ARM::VLD3DUPq32EvenPseudo:
4517 case ARM::VLD3DUPq32OddPseudo:
4518 case ARM::VLD4DUPd8Pseudo:
4519 case ARM::VLD4DUPd16Pseudo:
4520 case ARM::VLD4DUPd32Pseudo:
4521 case ARM::VLD4DUPd8Pseudo_UPD:
4522 case ARM::VLD4DUPd16Pseudo_UPD:
4523 case ARM::VLD4DUPd32Pseudo_UPD:
4524 case ARM::VLD4DUPq8EvenPseudo:
4525 case ARM::VLD4DUPq8OddPseudo:
4526 case ARM::VLD4DUPq16EvenPseudo:
4527 case ARM::VLD4DUPq16OddPseudo:
4528 case ARM::VLD4DUPq32EvenPseudo:
4529 case ARM::VLD4DUPq32OddPseudo:
4530 case ARM::VLD1LNq8Pseudo:
4531 case ARM::VLD1LNq16Pseudo:
4532 case ARM::VLD1LNq32Pseudo:
4533 case ARM::VLD1LNq8Pseudo_UPD:
4534 case ARM::VLD1LNq16Pseudo_UPD:
4535 case ARM::VLD1LNq32Pseudo_UPD:
4536 case ARM::VLD2LNd8Pseudo:
4537 case ARM::VLD2LNd16Pseudo:
4538 case ARM::VLD2LNd32Pseudo:
4539 case ARM::VLD2LNq16Pseudo:
4540 case ARM::VLD2LNq32Pseudo:
4541 case ARM::VLD2LNd8Pseudo_UPD:
4542 case ARM::VLD2LNd16Pseudo_UPD:
4543 case ARM::VLD2LNd32Pseudo_UPD:
4544 case ARM::VLD2LNq16Pseudo_UPD:
4545 case ARM::VLD2LNq32Pseudo_UPD:
4546 case ARM::VLD4LNd8Pseudo:
4547 case ARM::VLD4LNd16Pseudo:
4548 case ARM::VLD4LNd32Pseudo:
4549 case ARM::VLD4LNq16Pseudo:
4550 case ARM::VLD4LNq32Pseudo:
4551 case ARM::VLD4LNd8Pseudo_UPD:
4552 case ARM::VLD4LNd16Pseudo_UPD:
4553 case ARM::VLD4LNd32Pseudo_UPD:
4554 case ARM::VLD4LNq16Pseudo_UPD:
4555 case ARM::VLD4LNq32Pseudo_UPD:
4556 // If the address is not 64-bit aligned, the latencies of these
4557 // instructions increases by one.
4558 ++Latency;
4559 break;
4562 return Latency;
4565 unsigned ARMBaseInstrInfo::getPredicationCost(const MachineInstr &MI) const {
4566 if (MI.isCopyLike() || MI.isInsertSubreg() || MI.isRegSequence() ||
4567 MI.isImplicitDef())
4568 return 0;
4570 if (MI.isBundle())
4571 return 0;
4573 const MCInstrDesc &MCID = MI.getDesc();
4575 if (MCID.isCall() || (MCID.hasImplicitDefOfPhysReg(ARM::CPSR) &&
4576 !Subtarget.cheapPredicableCPSRDef())) {
4577 // When predicated, CPSR is an additional source operand for CPSR updating
4578 // instructions, this apparently increases their latencies.
4579 return 1;
4581 return 0;
4584 unsigned ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
4585 const MachineInstr &MI,
4586 unsigned *PredCost) const {
4587 if (MI.isCopyLike() || MI.isInsertSubreg() || MI.isRegSequence() ||
4588 MI.isImplicitDef())
4589 return 1;
4591 // An instruction scheduler typically runs on unbundled instructions, however
4592 // other passes may query the latency of a bundled instruction.
4593 if (MI.isBundle()) {
4594 unsigned Latency = 0;
4595 MachineBasicBlock::const_instr_iterator I = MI.getIterator();
4596 MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
4597 while (++I != E && I->isInsideBundle()) {
4598 if (I->getOpcode() != ARM::t2IT)
4599 Latency += getInstrLatency(ItinData, *I, PredCost);
4601 return Latency;
4604 const MCInstrDesc &MCID = MI.getDesc();
4605 if (PredCost && (MCID.isCall() || (MCID.hasImplicitDefOfPhysReg(ARM::CPSR) &&
4606 !Subtarget.cheapPredicableCPSRDef()))) {
4607 // When predicated, CPSR is an additional source operand for CPSR updating
4608 // instructions, this apparently increases their latencies.
4609 *PredCost = 1;
4611 // Be sure to call getStageLatency for an empty itinerary in case it has a
4612 // valid MinLatency property.
4613 if (!ItinData)
4614 return MI.mayLoad() ? 3 : 1;
4616 unsigned Class = MCID.getSchedClass();
4618 // For instructions with variable uops, use uops as latency.
4619 if (!ItinData->isEmpty() && ItinData->getNumMicroOps(Class) < 0)
4620 return getNumMicroOps(ItinData, MI);
4622 // For the common case, fall back on the itinerary's latency.
4623 unsigned Latency = ItinData->getStageLatency(Class);
4625 // Adjust for dynamic def-side opcode variants not captured by the itinerary.
4626 unsigned DefAlign =
4627 MI.hasOneMemOperand() ? (*MI.memoperands_begin())->getAlignment() : 0;
4628 int Adj = adjustDefLatency(Subtarget, MI, MCID, DefAlign);
4629 if (Adj >= 0 || (int)Latency > -Adj) {
4630 return Latency + Adj;
4632 return Latency;
4635 int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
4636 SDNode *Node) const {
4637 if (!Node->isMachineOpcode())
4638 return 1;
4640 if (!ItinData || ItinData->isEmpty())
4641 return 1;
4643 unsigned Opcode = Node->getMachineOpcode();
4644 switch (Opcode) {
4645 default:
4646 return ItinData->getStageLatency(get(Opcode).getSchedClass());
4647 case ARM::VLDMQIA:
4648 case ARM::VSTMQIA:
4649 return 2;
4653 bool ARMBaseInstrInfo::hasHighOperandLatency(const TargetSchedModel &SchedModel,
4654 const MachineRegisterInfo *MRI,
4655 const MachineInstr &DefMI,
4656 unsigned DefIdx,
4657 const MachineInstr &UseMI,
4658 unsigned UseIdx) const {
4659 unsigned DDomain = DefMI.getDesc().TSFlags & ARMII::DomainMask;
4660 unsigned UDomain = UseMI.getDesc().TSFlags & ARMII::DomainMask;
4661 if (Subtarget.nonpipelinedVFP() &&
4662 (DDomain == ARMII::DomainVFP || UDomain == ARMII::DomainVFP))
4663 return true;
4665 // Hoist VFP / NEON instructions with 4 or higher latency.
4666 unsigned Latency =
4667 SchedModel.computeOperandLatency(&DefMI, DefIdx, &UseMI, UseIdx);
4668 if (Latency <= 3)
4669 return false;
4670 return DDomain == ARMII::DomainVFP || DDomain == ARMII::DomainNEON ||
4671 UDomain == ARMII::DomainVFP || UDomain == ARMII::DomainNEON;
4674 bool ARMBaseInstrInfo::hasLowDefLatency(const TargetSchedModel &SchedModel,
4675 const MachineInstr &DefMI,
4676 unsigned DefIdx) const {
4677 const InstrItineraryData *ItinData = SchedModel.getInstrItineraries();
4678 if (!ItinData || ItinData->isEmpty())
4679 return false;
4681 unsigned DDomain = DefMI.getDesc().TSFlags & ARMII::DomainMask;
4682 if (DDomain == ARMII::DomainGeneral) {
4683 unsigned DefClass = DefMI.getDesc().getSchedClass();
4684 int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
4685 return (DefCycle != -1 && DefCycle <= 2);
4687 return false;
4690 bool ARMBaseInstrInfo::verifyInstruction(const MachineInstr &MI,
4691 StringRef &ErrInfo) const {
4692 if (convertAddSubFlagsOpcode(MI.getOpcode())) {
4693 ErrInfo = "Pseudo flag setting opcodes only exist in Selection DAG";
4694 return false;
4696 if (MI.getOpcode() == ARM::tMOVr && !Subtarget.hasV6Ops()) {
4697 // Make sure we don't generate a lo-lo mov that isn't supported.
4698 if (!ARM::hGPRRegClass.contains(MI.getOperand(0).getReg()) &&
4699 !ARM::hGPRRegClass.contains(MI.getOperand(1).getReg())) {
4700 ErrInfo = "Non-flag-setting Thumb1 mov is v6-only";
4701 return false;
4704 if (MI.getOpcode() == ARM::tPUSH ||
4705 MI.getOpcode() == ARM::tPOP ||
4706 MI.getOpcode() == ARM::tPOP_RET) {
4707 for (int i = 2, e = MI.getNumOperands(); i < e; ++i) {
4708 if (MI.getOperand(i).isImplicit() ||
4709 !MI.getOperand(i).isReg())
4710 continue;
4711 unsigned Reg = MI.getOperand(i).getReg();
4712 if (Reg < ARM::R0 || Reg > ARM::R7) {
4713 if (!(MI.getOpcode() == ARM::tPUSH && Reg == ARM::LR) &&
4714 !(MI.getOpcode() == ARM::tPOP_RET && Reg == ARM::PC)) {
4715 ErrInfo = "Unsupported register in Thumb1 push/pop";
4716 return false;
4721 return true;
4724 // LoadStackGuard has so far only been implemented for MachO. Different code
4725 // sequence is needed for other targets.
4726 void ARMBaseInstrInfo::expandLoadStackGuardBase(MachineBasicBlock::iterator MI,
4727 unsigned LoadImmOpc,
4728 unsigned LoadOpc) const {
4729 assert(!Subtarget.isROPI() && !Subtarget.isRWPI() &&
4730 "ROPI/RWPI not currently supported with stack guard");
4732 MachineBasicBlock &MBB = *MI->getParent();
4733 DebugLoc DL = MI->getDebugLoc();
4734 unsigned Reg = MI->getOperand(0).getReg();
4735 const GlobalValue *GV =
4736 cast<GlobalValue>((*MI->memoperands_begin())->getValue());
4737 MachineInstrBuilder MIB;
4739 BuildMI(MBB, MI, DL, get(LoadImmOpc), Reg)
4740 .addGlobalAddress(GV, 0, ARMII::MO_NONLAZY);
4742 if (Subtarget.isGVIndirectSymbol(GV)) {
4743 MIB = BuildMI(MBB, MI, DL, get(LoadOpc), Reg);
4744 MIB.addReg(Reg, RegState::Kill).addImm(0);
4745 auto Flags = MachineMemOperand::MOLoad |
4746 MachineMemOperand::MODereferenceable |
4747 MachineMemOperand::MOInvariant;
4748 MachineMemOperand *MMO = MBB.getParent()->getMachineMemOperand(
4749 MachinePointerInfo::getGOT(*MBB.getParent()), Flags, 4, 4);
4750 MIB.addMemOperand(MMO).add(predOps(ARMCC::AL));
4753 MIB = BuildMI(MBB, MI, DL, get(LoadOpc), Reg);
4754 MIB.addReg(Reg, RegState::Kill)
4755 .addImm(0)
4756 .cloneMemRefs(*MI)
4757 .add(predOps(ARMCC::AL));
4760 bool
4761 ARMBaseInstrInfo::isFpMLxInstruction(unsigned Opcode, unsigned &MulOpc,
4762 unsigned &AddSubOpc,
4763 bool &NegAcc, bool &HasLane) const {
4764 DenseMap<unsigned, unsigned>::const_iterator I = MLxEntryMap.find(Opcode);
4765 if (I == MLxEntryMap.end())
4766 return false;
4768 const ARM_MLxEntry &Entry = ARM_MLxTable[I->second];
4769 MulOpc = Entry.MulOpc;
4770 AddSubOpc = Entry.AddSubOpc;
4771 NegAcc = Entry.NegAcc;
4772 HasLane = Entry.HasLane;
4773 return true;
4776 //===----------------------------------------------------------------------===//
4777 // Execution domains.
4778 //===----------------------------------------------------------------------===//
4780 // Some instructions go down the NEON pipeline, some go down the VFP pipeline,
4781 // and some can go down both. The vmov instructions go down the VFP pipeline,
4782 // but they can be changed to vorr equivalents that are executed by the NEON
4783 // pipeline.
4785 // We use the following execution domain numbering:
4787 enum ARMExeDomain {
4788 ExeGeneric = 0,
4789 ExeVFP = 1,
4790 ExeNEON = 2
4794 // Also see ARMInstrFormats.td and Domain* enums in ARMBaseInfo.h
4796 std::pair<uint16_t, uint16_t>
4797 ARMBaseInstrInfo::getExecutionDomain(const MachineInstr &MI) const {
4798 // If we don't have access to NEON instructions then we won't be able
4799 // to swizzle anything to the NEON domain. Check to make sure.
4800 if (Subtarget.hasNEON()) {
4801 // VMOVD, VMOVRS and VMOVSR are VFP instructions, but can be changed to NEON
4802 // if they are not predicated.
4803 if (MI.getOpcode() == ARM::VMOVD && !isPredicated(MI))
4804 return std::make_pair(ExeVFP, (1 << ExeVFP) | (1 << ExeNEON));
4806 // CortexA9 is particularly picky about mixing the two and wants these
4807 // converted.
4808 if (Subtarget.useNEONForFPMovs() && !isPredicated(MI) &&
4809 (MI.getOpcode() == ARM::VMOVRS || MI.getOpcode() == ARM::VMOVSR ||
4810 MI.getOpcode() == ARM::VMOVS))
4811 return std::make_pair(ExeVFP, (1 << ExeVFP) | (1 << ExeNEON));
4813 // No other instructions can be swizzled, so just determine their domain.
4814 unsigned Domain = MI.getDesc().TSFlags & ARMII::DomainMask;
4816 if (Domain & ARMII::DomainNEON)
4817 return std::make_pair(ExeNEON, 0);
4819 // Certain instructions can go either way on Cortex-A8.
4820 // Treat them as NEON instructions.
4821 if ((Domain & ARMII::DomainNEONA8) && Subtarget.isCortexA8())
4822 return std::make_pair(ExeNEON, 0);
4824 if (Domain & ARMII::DomainVFP)
4825 return std::make_pair(ExeVFP, 0);
4827 return std::make_pair(ExeGeneric, 0);
4830 static unsigned getCorrespondingDRegAndLane(const TargetRegisterInfo *TRI,
4831 unsigned SReg, unsigned &Lane) {
4832 unsigned DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_0, &ARM::DPRRegClass);
4833 Lane = 0;
4835 if (DReg != ARM::NoRegister)
4836 return DReg;
4838 Lane = 1;
4839 DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_1, &ARM::DPRRegClass);
4841 assert(DReg && "S-register with no D super-register?");
4842 return DReg;
4845 /// getImplicitSPRUseForDPRUse - Given a use of a DPR register and lane,
4846 /// set ImplicitSReg to a register number that must be marked as implicit-use or
4847 /// zero if no register needs to be defined as implicit-use.
4849 /// If the function cannot determine if an SPR should be marked implicit use or
4850 /// not, it returns false.
4852 /// This function handles cases where an instruction is being modified from taking
4853 /// an SPR to a DPR[Lane]. A use of the DPR is being added, which may conflict
4854 /// with an earlier def of an SPR corresponding to DPR[Lane^1] (i.e. the other
4855 /// lane of the DPR).
4857 /// If the other SPR is defined, an implicit-use of it should be added. Else,
4858 /// (including the case where the DPR itself is defined), it should not.
4860 static bool getImplicitSPRUseForDPRUse(const TargetRegisterInfo *TRI,
4861 MachineInstr &MI, unsigned DReg,
4862 unsigned Lane, unsigned &ImplicitSReg) {
4863 // If the DPR is defined or used already, the other SPR lane will be chained
4864 // correctly, so there is nothing to be done.
4865 if (MI.definesRegister(DReg, TRI) || MI.readsRegister(DReg, TRI)) {
4866 ImplicitSReg = 0;
4867 return true;
4870 // Otherwise we need to go searching to see if the SPR is set explicitly.
4871 ImplicitSReg = TRI->getSubReg(DReg,
4872 (Lane & 1) ? ARM::ssub_0 : ARM::ssub_1);
4873 MachineBasicBlock::LivenessQueryResult LQR =
4874 MI.getParent()->computeRegisterLiveness(TRI, ImplicitSReg, MI);
4876 if (LQR == MachineBasicBlock::LQR_Live)
4877 return true;
4878 else if (LQR == MachineBasicBlock::LQR_Unknown)
4879 return false;
4881 // If the register is known not to be live, there is no need to add an
4882 // implicit-use.
4883 ImplicitSReg = 0;
4884 return true;
4887 void ARMBaseInstrInfo::setExecutionDomain(MachineInstr &MI,
4888 unsigned Domain) const {
4889 unsigned DstReg, SrcReg, DReg;
4890 unsigned Lane;
4891 MachineInstrBuilder MIB(*MI.getParent()->getParent(), MI);
4892 const TargetRegisterInfo *TRI = &getRegisterInfo();
4893 switch (MI.getOpcode()) {
4894 default:
4895 llvm_unreachable("cannot handle opcode!");
4896 break;
4897 case ARM::VMOVD:
4898 if (Domain != ExeNEON)
4899 break;
4901 // Zap the predicate operands.
4902 assert(!isPredicated(MI) && "Cannot predicate a VORRd");
4904 // Make sure we've got NEON instructions.
4905 assert(Subtarget.hasNEON() && "VORRd requires NEON");
4907 // Source instruction is %DDst = VMOVD %DSrc, 14, %noreg (; implicits)
4908 DstReg = MI.getOperand(0).getReg();
4909 SrcReg = MI.getOperand(1).getReg();
4911 for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
4912 MI.RemoveOperand(i - 1);
4914 // Change to a %DDst = VORRd %DSrc, %DSrc, 14, %noreg (; implicits)
4915 MI.setDesc(get(ARM::VORRd));
4916 MIB.addReg(DstReg, RegState::Define)
4917 .addReg(SrcReg)
4918 .addReg(SrcReg)
4919 .add(predOps(ARMCC::AL));
4920 break;
4921 case ARM::VMOVRS:
4922 if (Domain != ExeNEON)
4923 break;
4924 assert(!isPredicated(MI) && "Cannot predicate a VGETLN");
4926 // Source instruction is %RDst = VMOVRS %SSrc, 14, %noreg (; implicits)
4927 DstReg = MI.getOperand(0).getReg();
4928 SrcReg = MI.getOperand(1).getReg();
4930 for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
4931 MI.RemoveOperand(i - 1);
4933 DReg = getCorrespondingDRegAndLane(TRI, SrcReg, Lane);
4935 // Convert to %RDst = VGETLNi32 %DSrc, Lane, 14, %noreg (; imps)
4936 // Note that DSrc has been widened and the other lane may be undef, which
4937 // contaminates the entire register.
4938 MI.setDesc(get(ARM::VGETLNi32));
4939 MIB.addReg(DstReg, RegState::Define)
4940 .addReg(DReg, RegState::Undef)
4941 .addImm(Lane)
4942 .add(predOps(ARMCC::AL));
4944 // The old source should be an implicit use, otherwise we might think it
4945 // was dead before here.
4946 MIB.addReg(SrcReg, RegState::Implicit);
4947 break;
4948 case ARM::VMOVSR: {
4949 if (Domain != ExeNEON)
4950 break;
4951 assert(!isPredicated(MI) && "Cannot predicate a VSETLN");
4953 // Source instruction is %SDst = VMOVSR %RSrc, 14, %noreg (; implicits)
4954 DstReg = MI.getOperand(0).getReg();
4955 SrcReg = MI.getOperand(1).getReg();
4957 DReg = getCorrespondingDRegAndLane(TRI, DstReg, Lane);
4959 unsigned ImplicitSReg;
4960 if (!getImplicitSPRUseForDPRUse(TRI, MI, DReg, Lane, ImplicitSReg))
4961 break;
4963 for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
4964 MI.RemoveOperand(i - 1);
4966 // Convert to %DDst = VSETLNi32 %DDst, %RSrc, Lane, 14, %noreg (; imps)
4967 // Again DDst may be undefined at the beginning of this instruction.
4968 MI.setDesc(get(ARM::VSETLNi32));
4969 MIB.addReg(DReg, RegState::Define)
4970 .addReg(DReg, getUndefRegState(!MI.readsRegister(DReg, TRI)))
4971 .addReg(SrcReg)
4972 .addImm(Lane)
4973 .add(predOps(ARMCC::AL));
4975 // The narrower destination must be marked as set to keep previous chains
4976 // in place.
4977 MIB.addReg(DstReg, RegState::Define | RegState::Implicit);
4978 if (ImplicitSReg != 0)
4979 MIB.addReg(ImplicitSReg, RegState::Implicit);
4980 break;
4982 case ARM::VMOVS: {
4983 if (Domain != ExeNEON)
4984 break;
4986 // Source instruction is %SDst = VMOVS %SSrc, 14, %noreg (; implicits)
4987 DstReg = MI.getOperand(0).getReg();
4988 SrcReg = MI.getOperand(1).getReg();
4990 unsigned DstLane = 0, SrcLane = 0, DDst, DSrc;
4991 DDst = getCorrespondingDRegAndLane(TRI, DstReg, DstLane);
4992 DSrc = getCorrespondingDRegAndLane(TRI, SrcReg, SrcLane);
4994 unsigned ImplicitSReg;
4995 if (!getImplicitSPRUseForDPRUse(TRI, MI, DSrc, SrcLane, ImplicitSReg))
4996 break;
4998 for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
4999 MI.RemoveOperand(i - 1);
5001 if (DSrc == DDst) {
5002 // Destination can be:
5003 // %DDst = VDUPLN32d %DDst, Lane, 14, %noreg (; implicits)
5004 MI.setDesc(get(ARM::VDUPLN32d));
5005 MIB.addReg(DDst, RegState::Define)
5006 .addReg(DDst, getUndefRegState(!MI.readsRegister(DDst, TRI)))
5007 .addImm(SrcLane)
5008 .add(predOps(ARMCC::AL));
5010 // Neither the source or the destination are naturally represented any
5011 // more, so add them in manually.
5012 MIB.addReg(DstReg, RegState::Implicit | RegState::Define);
5013 MIB.addReg(SrcReg, RegState::Implicit);
5014 if (ImplicitSReg != 0)
5015 MIB.addReg(ImplicitSReg, RegState::Implicit);
5016 break;
5019 // In general there's no single instruction that can perform an S <-> S
5020 // move in NEON space, but a pair of VEXT instructions *can* do the
5021 // job. It turns out that the VEXTs needed will only use DSrc once, with
5022 // the position based purely on the combination of lane-0 and lane-1
5023 // involved. For example
5024 // vmov s0, s2 -> vext.32 d0, d0, d1, #1 vext.32 d0, d0, d0, #1
5025 // vmov s1, s3 -> vext.32 d0, d1, d0, #1 vext.32 d0, d0, d0, #1
5026 // vmov s0, s3 -> vext.32 d0, d0, d0, #1 vext.32 d0, d1, d0, #1
5027 // vmov s1, s2 -> vext.32 d0, d0, d0, #1 vext.32 d0, d0, d1, #1
5029 // Pattern of the MachineInstrs is:
5030 // %DDst = VEXTd32 %DSrc1, %DSrc2, Lane, 14, %noreg (;implicits)
5031 MachineInstrBuilder NewMIB;
5032 NewMIB = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(ARM::VEXTd32),
5033 DDst);
5035 // On the first instruction, both DSrc and DDst may be undef if present.
5036 // Specifically when the original instruction didn't have them as an
5037 // <imp-use>.
5038 unsigned CurReg = SrcLane == 1 && DstLane == 1 ? DSrc : DDst;
5039 bool CurUndef = !MI.readsRegister(CurReg, TRI);
5040 NewMIB.addReg(CurReg, getUndefRegState(CurUndef));
5042 CurReg = SrcLane == 0 && DstLane == 0 ? DSrc : DDst;
5043 CurUndef = !MI.readsRegister(CurReg, TRI);
5044 NewMIB.addReg(CurReg, getUndefRegState(CurUndef))
5045 .addImm(1)
5046 .add(predOps(ARMCC::AL));
5048 if (SrcLane == DstLane)
5049 NewMIB.addReg(SrcReg, RegState::Implicit);
5051 MI.setDesc(get(ARM::VEXTd32));
5052 MIB.addReg(DDst, RegState::Define);
5054 // On the second instruction, DDst has definitely been defined above, so
5055 // it is not undef. DSrc, if present, can be undef as above.
5056 CurReg = SrcLane == 1 && DstLane == 0 ? DSrc : DDst;
5057 CurUndef = CurReg == DSrc && !MI.readsRegister(CurReg, TRI);
5058 MIB.addReg(CurReg, getUndefRegState(CurUndef));
5060 CurReg = SrcLane == 0 && DstLane == 1 ? DSrc : DDst;
5061 CurUndef = CurReg == DSrc && !MI.readsRegister(CurReg, TRI);
5062 MIB.addReg(CurReg, getUndefRegState(CurUndef))
5063 .addImm(1)
5064 .add(predOps(ARMCC::AL));
5066 if (SrcLane != DstLane)
5067 MIB.addReg(SrcReg, RegState::Implicit);
5069 // As before, the original destination is no longer represented, add it
5070 // implicitly.
5071 MIB.addReg(DstReg, RegState::Define | RegState::Implicit);
5072 if (ImplicitSReg != 0)
5073 MIB.addReg(ImplicitSReg, RegState::Implicit);
5074 break;
5079 //===----------------------------------------------------------------------===//
5080 // Partial register updates
5081 //===----------------------------------------------------------------------===//
5083 // Swift renames NEON registers with 64-bit granularity. That means any
5084 // instruction writing an S-reg implicitly reads the containing D-reg. The
5085 // problem is mostly avoided by translating f32 operations to v2f32 operations
5086 // on D-registers, but f32 loads are still a problem.
5088 // These instructions can load an f32 into a NEON register:
5090 // VLDRS - Only writes S, partial D update.
5091 // VLD1LNd32 - Writes all D-regs, explicit partial D update, 2 uops.
5092 // VLD1DUPd32 - Writes all D-regs, no partial reg update, 2 uops.
5094 // FCONSTD can be used as a dependency-breaking instruction.
5095 unsigned ARMBaseInstrInfo::getPartialRegUpdateClearance(
5096 const MachineInstr &MI, unsigned OpNum,
5097 const TargetRegisterInfo *TRI) const {
5098 auto PartialUpdateClearance = Subtarget.getPartialUpdateClearance();
5099 if (!PartialUpdateClearance)
5100 return 0;
5102 assert(TRI && "Need TRI instance");
5104 const MachineOperand &MO = MI.getOperand(OpNum);
5105 if (MO.readsReg())
5106 return 0;
5107 unsigned Reg = MO.getReg();
5108 int UseOp = -1;
5110 switch (MI.getOpcode()) {
5111 // Normal instructions writing only an S-register.
5112 case ARM::VLDRS:
5113 case ARM::FCONSTS:
5114 case ARM::VMOVSR:
5115 case ARM::VMOVv8i8:
5116 case ARM::VMOVv4i16:
5117 case ARM::VMOVv2i32:
5118 case ARM::VMOVv2f32:
5119 case ARM::VMOVv1i64:
5120 UseOp = MI.findRegisterUseOperandIdx(Reg, false, TRI);
5121 break;
5123 // Explicitly reads the dependency.
5124 case ARM::VLD1LNd32:
5125 UseOp = 3;
5126 break;
5127 default:
5128 return 0;
5131 // If this instruction actually reads a value from Reg, there is no unwanted
5132 // dependency.
5133 if (UseOp != -1 && MI.getOperand(UseOp).readsReg())
5134 return 0;
5136 // We must be able to clobber the whole D-reg.
5137 if (Register::isVirtualRegister(Reg)) {
5138 // Virtual register must be a def undef foo:ssub_0 operand.
5139 if (!MO.getSubReg() || MI.readsVirtualRegister(Reg))
5140 return 0;
5141 } else if (ARM::SPRRegClass.contains(Reg)) {
5142 // Physical register: MI must define the full D-reg.
5143 unsigned DReg = TRI->getMatchingSuperReg(Reg, ARM::ssub_0,
5144 &ARM::DPRRegClass);
5145 if (!DReg || !MI.definesRegister(DReg, TRI))
5146 return 0;
5149 // MI has an unwanted D-register dependency.
5150 // Avoid defs in the previous N instructrions.
5151 return PartialUpdateClearance;
5154 // Break a partial register dependency after getPartialRegUpdateClearance
5155 // returned non-zero.
5156 void ARMBaseInstrInfo::breakPartialRegDependency(
5157 MachineInstr &MI, unsigned OpNum, const TargetRegisterInfo *TRI) const {
5158 assert(OpNum < MI.getDesc().getNumDefs() && "OpNum is not a def");
5159 assert(TRI && "Need TRI instance");
5161 const MachineOperand &MO = MI.getOperand(OpNum);
5162 unsigned Reg = MO.getReg();
5163 assert(Register::isPhysicalRegister(Reg) &&
5164 "Can't break virtual register dependencies.");
5165 unsigned DReg = Reg;
5167 // If MI defines an S-reg, find the corresponding D super-register.
5168 if (ARM::SPRRegClass.contains(Reg)) {
5169 DReg = ARM::D0 + (Reg - ARM::S0) / 2;
5170 assert(TRI->isSuperRegister(Reg, DReg) && "Register enums broken");
5173 assert(ARM::DPRRegClass.contains(DReg) && "Can only break D-reg deps");
5174 assert(MI.definesRegister(DReg, TRI) && "MI doesn't clobber full D-reg");
5176 // FIXME: In some cases, VLDRS can be changed to a VLD1DUPd32 which defines
5177 // the full D-register by loading the same value to both lanes. The
5178 // instruction is micro-coded with 2 uops, so don't do this until we can
5179 // properly schedule micro-coded instructions. The dispatcher stalls cause
5180 // too big regressions.
5182 // Insert the dependency-breaking FCONSTD before MI.
5183 // 96 is the encoding of 0.5, but the actual value doesn't matter here.
5184 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(ARM::FCONSTD), DReg)
5185 .addImm(96)
5186 .add(predOps(ARMCC::AL));
5187 MI.addRegisterKilled(DReg, TRI, true);
5190 bool ARMBaseInstrInfo::hasNOP() const {
5191 return Subtarget.getFeatureBits()[ARM::HasV6KOps];
5194 bool ARMBaseInstrInfo::isSwiftFastImmShift(const MachineInstr *MI) const {
5195 if (MI->getNumOperands() < 4)
5196 return true;
5197 unsigned ShOpVal = MI->getOperand(3).getImm();
5198 unsigned ShImm = ARM_AM::getSORegOffset(ShOpVal);
5199 // Swift supports faster shifts for: lsl 2, lsl 1, and lsr 1.
5200 if ((ShImm == 1 && ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsr) ||
5201 ((ShImm == 1 || ShImm == 2) &&
5202 ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsl))
5203 return true;
5205 return false;
5208 bool ARMBaseInstrInfo::getRegSequenceLikeInputs(
5209 const MachineInstr &MI, unsigned DefIdx,
5210 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
5211 assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index");
5212 assert(MI.isRegSequenceLike() && "Invalid kind of instruction");
5214 switch (MI.getOpcode()) {
5215 case ARM::VMOVDRR:
5216 // dX = VMOVDRR rY, rZ
5217 // is the same as:
5218 // dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1
5219 // Populate the InputRegs accordingly.
5220 // rY
5221 const MachineOperand *MOReg = &MI.getOperand(1);
5222 if (!MOReg->isUndef())
5223 InputRegs.push_back(RegSubRegPairAndIdx(MOReg->getReg(),
5224 MOReg->getSubReg(), ARM::ssub_0));
5225 // rZ
5226 MOReg = &MI.getOperand(2);
5227 if (!MOReg->isUndef())
5228 InputRegs.push_back(RegSubRegPairAndIdx(MOReg->getReg(),
5229 MOReg->getSubReg(), ARM::ssub_1));
5230 return true;
5232 llvm_unreachable("Target dependent opcode missing");
5235 bool ARMBaseInstrInfo::getExtractSubregLikeInputs(
5236 const MachineInstr &MI, unsigned DefIdx,
5237 RegSubRegPairAndIdx &InputReg) const {
5238 assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index");
5239 assert(MI.isExtractSubregLike() && "Invalid kind of instruction");
5241 switch (MI.getOpcode()) {
5242 case ARM::VMOVRRD:
5243 // rX, rY = VMOVRRD dZ
5244 // is the same as:
5245 // rX = EXTRACT_SUBREG dZ, ssub_0
5246 // rY = EXTRACT_SUBREG dZ, ssub_1
5247 const MachineOperand &MOReg = MI.getOperand(2);
5248 if (MOReg.isUndef())
5249 return false;
5250 InputReg.Reg = MOReg.getReg();
5251 InputReg.SubReg = MOReg.getSubReg();
5252 InputReg.SubIdx = DefIdx == 0 ? ARM::ssub_0 : ARM::ssub_1;
5253 return true;
5255 llvm_unreachable("Target dependent opcode missing");
5258 bool ARMBaseInstrInfo::getInsertSubregLikeInputs(
5259 const MachineInstr &MI, unsigned DefIdx, RegSubRegPair &BaseReg,
5260 RegSubRegPairAndIdx &InsertedReg) const {
5261 assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index");
5262 assert(MI.isInsertSubregLike() && "Invalid kind of instruction");
5264 switch (MI.getOpcode()) {
5265 case ARM::VSETLNi32:
5266 // dX = VSETLNi32 dY, rZ, imm
5267 const MachineOperand &MOBaseReg = MI.getOperand(1);
5268 const MachineOperand &MOInsertedReg = MI.getOperand(2);
5269 if (MOInsertedReg.isUndef())
5270 return false;
5271 const MachineOperand &MOIndex = MI.getOperand(3);
5272 BaseReg.Reg = MOBaseReg.getReg();
5273 BaseReg.SubReg = MOBaseReg.getSubReg();
5275 InsertedReg.Reg = MOInsertedReg.getReg();
5276 InsertedReg.SubReg = MOInsertedReg.getSubReg();
5277 InsertedReg.SubIdx = MOIndex.getImm() == 0 ? ARM::ssub_0 : ARM::ssub_1;
5278 return true;
5280 llvm_unreachable("Target dependent opcode missing");
5283 std::pair<unsigned, unsigned>
5284 ARMBaseInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
5285 const unsigned Mask = ARMII::MO_OPTION_MASK;
5286 return std::make_pair(TF & Mask, TF & ~Mask);
5289 ArrayRef<std::pair<unsigned, const char *>>
5290 ARMBaseInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
5291 using namespace ARMII;
5293 static const std::pair<unsigned, const char *> TargetFlags[] = {
5294 {MO_LO16, "arm-lo16"}, {MO_HI16, "arm-hi16"}};
5295 return makeArrayRef(TargetFlags);
5298 ArrayRef<std::pair<unsigned, const char *>>
5299 ARMBaseInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
5300 using namespace ARMII;
5302 static const std::pair<unsigned, const char *> TargetFlags[] = {
5303 {MO_COFFSTUB, "arm-coffstub"},
5304 {MO_GOT, "arm-got"},
5305 {MO_SBREL, "arm-sbrel"},
5306 {MO_DLLIMPORT, "arm-dllimport"},
5307 {MO_SECREL, "arm-secrel"},
5308 {MO_NONLAZY, "arm-nonlazy"}};
5309 return makeArrayRef(TargetFlags);
5312 bool llvm::registerDefinedBetween(unsigned Reg,
5313 MachineBasicBlock::iterator From,
5314 MachineBasicBlock::iterator To,
5315 const TargetRegisterInfo *TRI) {
5316 for (auto I = From; I != To; ++I)
5317 if (I->modifiesRegister(Reg, TRI))
5318 return true;
5319 return false;
5322 MachineInstr *llvm::findCMPToFoldIntoCBZ(MachineInstr *Br,
5323 const TargetRegisterInfo *TRI) {
5324 // Search backwards to the instruction that defines CSPR. This may or not
5325 // be a CMP, we check that after this loop. If we find another instruction
5326 // that reads cpsr, we return nullptr.
5327 MachineBasicBlock::iterator CmpMI = Br;
5328 while (CmpMI != Br->getParent()->begin()) {
5329 --CmpMI;
5330 if (CmpMI->modifiesRegister(ARM::CPSR, TRI))
5331 break;
5332 if (CmpMI->readsRegister(ARM::CPSR, TRI))
5333 break;
5336 // Check that this inst is a CMP r[0-7], #0 and that the register
5337 // is not redefined between the cmp and the br.
5338 if (CmpMI->getOpcode() != ARM::tCMPi8 && CmpMI->getOpcode() != ARM::t2CMPri)
5339 return nullptr;
5340 unsigned Reg = CmpMI->getOperand(0).getReg();
5341 unsigned PredReg = 0;
5342 ARMCC::CondCodes Pred = getInstrPredicate(*CmpMI, PredReg);
5343 if (Pred != ARMCC::AL || CmpMI->getOperand(1).getImm() != 0)
5344 return nullptr;
5345 if (!isARMLowRegister(Reg))
5346 return nullptr;
5347 if (registerDefinedBetween(Reg, CmpMI->getNextNode(), Br, TRI))
5348 return nullptr;
5350 return &*CmpMI;