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