LLVM 23.0.0git
AArch64InstrInfo.cpp
Go to the documentation of this file.
1//===- AArch64InstrInfo.cpp - AArch64 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 AArch64 implementation of the TargetInstrInfo class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "AArch64InstrInfo.h"
14#include "AArch64ExpandImm.h"
16#include "AArch64PointerAuth.h"
17#include "AArch64Subtarget.h"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/SmallSet.h"
26#include "llvm/ADT/Statistic.h"
45#include "llvm/IR/DebugLoc.h"
46#include "llvm/IR/GlobalValue.h"
47#include "llvm/IR/Module.h"
48#include "llvm/MC/MCAsmInfo.h"
49#include "llvm/MC/MCInst.h"
51#include "llvm/MC/MCInstrDesc.h"
56#include "llvm/Support/LEB128.h"
60#include <cassert>
61#include <cstdint>
62#include <iterator>
63#include <utility>
64
65using namespace llvm;
66
67#define GET_INSTRINFO_CTOR_DTOR
68#include "AArch64GenInstrInfo.inc"
69
70#define DEBUG_TYPE "AArch64InstrInfo"
71
72STATISTIC(NumCopyInstrs, "Number of COPY instructions expanded");
73STATISTIC(NumZCRegMoveInstrsGPR, "Number of zero-cycle GPR register move "
74 "instructions expanded from canonical COPY");
75STATISTIC(NumZCRegMoveInstrsFPR, "Number of zero-cycle FPR register move "
76 "instructions expanded from canonical COPY");
77STATISTIC(NumZCZeroingInstrsGPR, "Number of zero-cycle GPR zeroing "
78 "instructions expanded from canonical COPY");
79// NumZCZeroingInstrsFPR is counted at AArch64AsmPrinter
80
82 CBDisplacementBits("aarch64-cb-offset-bits", cl::Hidden, cl::init(9),
83 cl::desc("Restrict range of CB instructions (DEBUG)"));
84
86 "aarch64-tbz-offset-bits", cl::Hidden, cl::init(14),
87 cl::desc("Restrict range of TB[N]Z instructions (DEBUG)"));
88
90 "aarch64-cbz-offset-bits", cl::Hidden, cl::init(19),
91 cl::desc("Restrict range of CB[N]Z instructions (DEBUG)"));
92
94 BCCDisplacementBits("aarch64-bcc-offset-bits", cl::Hidden, cl::init(19),
95 cl::desc("Restrict range of Bcc instructions (DEBUG)"));
96
98 BDisplacementBits("aarch64-b-offset-bits", cl::Hidden, cl::init(26),
99 cl::desc("Restrict range of B instructions (DEBUG)"));
100
102 "aarch64-search-limit", cl::Hidden, cl::init(2048),
103 cl::desc("Restrict range of instructions to search for the "
104 "machine-combiner gather pattern optimization"));
105
107 : AArch64GenInstrInfo(STI, RI, AArch64::ADJCALLSTACKDOWN,
108 AArch64::ADJCALLSTACKUP, AArch64::CATCHRET),
109 RI(STI.getTargetTriple(), STI.getHwMode()), Subtarget(STI) {}
110
111/// Return the maximum number of bytes of code the specified instruction may be
112/// after LFI rewriting. If the instruction is not rewritten, std::nullopt is
113/// returned (use default sizing).
114///
115/// NOTE: the size estimates here must be kept in sync with the rewrites in
116/// AArch64MCLFIRewriter.cpp. Sizes may be overestimates of the rewritten
117/// instruction sequences.
118static std::optional<unsigned> getLFIInstSizeInBytes(const MachineInstr &MI) {
119 switch (MI.getOpcode()) {
120 case AArch64::SVC:
121 // SVC expands to 4 instructions.
122 return 16;
123 case AArch64::BR:
124 case AArch64::BLR:
125 // Indirect branches/calls expand to 2 instructions (guard + br/blr).
126 return 8;
127 case AArch64::RET:
128 // RET through LR is not rewritten, but RET through another register
129 // expands to 2 instructions (guard + ret).
130 if (MI.getOperand(0).getReg() != AArch64::LR)
131 return 8;
132 return 4;
133 case AArch64::SYSxt:
134 // VA-based DC/IC ops (op1=3, Cn=7, op2=1) expand to 2 instructions.
135 if (MI.getOperand(0).getImm() == 3 && MI.getOperand(1).getImm() == 7 &&
136 MI.getOperand(3).getImm() == 1)
137 return 8;
138 return std::nullopt;
139 default:
140 break;
141 }
142
143 // Detect instructions that explicitly define SP or LR.
144 bool ModifiesLR = false;
145 bool ModifiesSP = false;
146 for (const MachineOperand &MO : MI.defs()) {
147 if (!MO.isReg())
148 continue;
149 if (MO.getReg() == AArch64::LR)
150 ModifiesLR = true;
151 else if (MO.getReg() == AArch64::SP)
152 ModifiesSP = true;
153 }
154
155 // Memory accesses expand to a base-register guard plus the rewritten access
156 // (8 bytes), with an extra base-register update for pre/post-index forms (12
157 // bytes total). If the access also defines LR, an LR mask is appended (+4
158 // bytes). Depending on additional optimizations that the rewriter performs,
159 // this may be an overestimate.
160 if (MI.mayLoadOrStore()) {
161 unsigned Size = isLFIPrePostMemAccess(MI.getOpcode()) ? 12 : 8;
162 if (ModifiesLR)
163 Size += 4;
164 return Size;
165 }
166
167 // Non memory operations that modify LR or SP expand to 2 instructions.
168 if (ModifiesSP || ModifiesLR)
169 return 8;
170
171 // Default case: instructions that don't cause expansion.
172 // - TP accesses in LFI are a single load/store, so no expansion.
173 // - All remaining instructions are not rewritten.
174 return std::nullopt;
175}
176
177/// GetInstSize - Return the number of bytes of code the specified
178/// instruction may be. This returns the maximum number of bytes.
180 const MachineBasicBlock &MBB = *MI.getParent();
181 const MachineFunction *MF = MBB.getParent();
182 const Function &F = MF->getFunction();
183 const MCAsmInfo &MAI = MF->getTarget().getMCAsmInfo();
184
185 {
186 auto Op = MI.getOpcode();
187 if (Op == AArch64::INLINEASM || Op == AArch64::INLINEASM_BR)
188 return getInlineAsmLength(MI.getOperand(0).getSymbolName(), MAI);
189 }
190
191 // Meta-instructions emit no code.
192 if (MI.isMetaInstruction())
193 return 0;
194
195 // FIXME: We currently only handle pseudoinstructions that don't get expanded
196 // before the assembly printer.
197 unsigned NumBytes = 0;
198 const MCInstrDesc &Desc = MI.getDesc();
199
200 // LFI rewriter expansions that supersede normal sizing.
201 const auto &STI = MF->getSubtarget<AArch64Subtarget>();
202 if (STI.isLFI())
203 if (auto Size = getLFIInstSizeInBytes(MI))
204 return *Size;
205
206 if (!MI.isBundle() && isTailCallReturnInst(MI)) {
207 NumBytes = Desc.getSize() ? Desc.getSize() : 4;
208
209 const auto *MFI = MF->getInfo<AArch64FunctionInfo>();
210 if (!MFI->shouldSignReturnAddress(*MF))
211 return NumBytes;
212
213 auto Method = STI.getAuthenticatedLRCheckMethod(*MF);
214 NumBytes += AArch64PAuth::getCheckerSizeInBytes(Method);
215 return NumBytes;
216 }
217
218 // Size should be preferably set in
219 // llvm/lib/Target/AArch64/AArch64InstrInfo.td (default case).
220 // Specific cases handle instructions of variable sizes
221 switch (Desc.getOpcode()) {
222 default:
223 if (Desc.getSize())
224 return Desc.getSize();
225
226 // Anything not explicitly designated otherwise (i.e. pseudo-instructions
227 // with fixed constant size but not specified in .td file) is a normal
228 // 4-byte insn.
229 NumBytes = 4;
230 break;
231 case TargetOpcode::STACKMAP:
232 // The upper bound for a stackmap intrinsic is the full length of its shadow
233 NumBytes = StackMapOpers(&MI).getNumPatchBytes();
234 assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
235 break;
236 case TargetOpcode::PATCHPOINT:
237 // The size of the patchpoint intrinsic is the number of bytes requested
238 NumBytes = PatchPointOpers(&MI).getNumPatchBytes();
239 assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
240 break;
241 case TargetOpcode::STATEPOINT:
242 NumBytes = StatepointOpers(&MI).getNumPatchBytes();
243 assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
244 // No patch bytes means a normal call inst is emitted
245 if (NumBytes == 0)
246 NumBytes = 4;
247 break;
248 case TargetOpcode::PATCHABLE_FUNCTION_ENTER:
249 // If `patchable-function-entry` is set, PATCHABLE_FUNCTION_ENTER
250 // instructions are expanded to the specified number of NOPs. Otherwise,
251 // they are expanded to 36-byte XRay sleds.
252 NumBytes =
253 F.getFnAttributeAsParsedInteger("patchable-function-entry", 9) * 4;
254 break;
255 case TargetOpcode::PATCHABLE_FUNCTION_EXIT:
256 case TargetOpcode::PATCHABLE_TAIL_CALL:
257 case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
258 // An XRay sled can be 4 bytes of alignment plus a 32-byte block.
259 NumBytes = 36;
260 break;
261 case TargetOpcode::PATCHABLE_EVENT_CALL:
262 // EVENT_CALL XRay sleds are exactly 6 instructions long (no alignment).
263 NumBytes = 24;
264 break;
265
266 case AArch64::SPACE:
267 NumBytes = MI.getOperand(1).getImm();
268 break;
269 case AArch64::MOVaddr:
270 case AArch64::MOVaddrJT:
271 case AArch64::MOVaddrCP:
272 case AArch64::MOVaddrBA:
273 case AArch64::MOVaddrTLS:
274 case AArch64::MOVaddrEXT: {
275 // Use the same logic as the pseudo expansion to count instructions.
278 MI.getOperand(1).getTargetFlags(),
279 Subtarget.isTargetMachO(), Insn);
280 NumBytes = Insn.size() * 4;
281 break;
282 }
283
284 case AArch64::MOVi32imm:
285 case AArch64::MOVi64imm: {
286 // Use the same logic as the pseudo expansion to count instructions.
287 unsigned BitSize = Desc.getOpcode() == AArch64::MOVi32imm ? 32 : 64;
289 AArch64_IMM::expandMOVImm(MI.getOperand(1).getImm(), BitSize, Insn);
290 NumBytes = Insn.size() * 4;
291 break;
292 }
293
294 case TargetOpcode::BUNDLE:
295 NumBytes = getInstBundleSize(MI);
296 break;
297 }
298
299 return NumBytes;
300}
301
304 // Block ends with fall-through condbranch.
305 switch (LastInst->getOpcode()) {
306 default:
307 llvm_unreachable("Unknown branch instruction?");
308 case AArch64::Bcc:
309 Target = LastInst->getOperand(1).getMBB();
310 Cond.push_back(LastInst->getOperand(0));
311 break;
312 case AArch64::CBZW:
313 case AArch64::CBZX:
314 case AArch64::CBNZW:
315 case AArch64::CBNZX:
316 Target = LastInst->getOperand(1).getMBB();
317 Cond.push_back(MachineOperand::CreateImm(-1));
318 Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
319 Cond.push_back(LastInst->getOperand(0));
320 break;
321 case AArch64::TBZW:
322 case AArch64::TBZX:
323 case AArch64::TBNZW:
324 case AArch64::TBNZX:
325 Target = LastInst->getOperand(2).getMBB();
326 Cond.push_back(MachineOperand::CreateImm(-1));
327 Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
328 Cond.push_back(LastInst->getOperand(0));
329 Cond.push_back(LastInst->getOperand(1));
330 break;
331 case AArch64::CBWPri:
332 case AArch64::CBXPri:
333 case AArch64::CBWPrr:
334 case AArch64::CBXPrr:
335 Target = LastInst->getOperand(3).getMBB();
336 Cond.push_back(MachineOperand::CreateImm(-1));
337 Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
338 Cond.push_back(LastInst->getOperand(0));
339 Cond.push_back(LastInst->getOperand(1));
340 Cond.push_back(LastInst->getOperand(2));
341 break;
342 case AArch64::CBBAssertExt:
343 case AArch64::CBHAssertExt:
344 Target = LastInst->getOperand(3).getMBB();
345 Cond.push_back(MachineOperand::CreateImm(-1)); // -1
346 Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode())); // Opc
347 Cond.push_back(LastInst->getOperand(0)); // Cond
348 Cond.push_back(LastInst->getOperand(1)); // Op0
349 Cond.push_back(LastInst->getOperand(2)); // Op1
350 Cond.push_back(LastInst->getOperand(4)); // Ext0
351 Cond.push_back(LastInst->getOperand(5)); // Ext1
352 break;
353 }
354}
355
356static unsigned getBranchDisplacementBits(unsigned Opc) {
357 switch (Opc) {
358 default:
359 llvm_unreachable("unexpected opcode!");
360 case AArch64::B:
361 return BDisplacementBits;
362 case AArch64::TBNZW:
363 case AArch64::TBZW:
364 case AArch64::TBNZX:
365 case AArch64::TBZX:
366 return TBZDisplacementBits;
367 case AArch64::CBNZW:
368 case AArch64::CBZW:
369 case AArch64::CBNZX:
370 case AArch64::CBZX:
371 return CBZDisplacementBits;
372 case AArch64::Bcc:
373 return BCCDisplacementBits;
374 case AArch64::CBWPri:
375 case AArch64::CBXPri:
376 case AArch64::CBBAssertExt:
377 case AArch64::CBHAssertExt:
378 case AArch64::CBWPrr:
379 case AArch64::CBXPrr:
380 return CBDisplacementBits;
381 }
382}
383
385 int64_t BrOffset) const {
386 unsigned Bits = getBranchDisplacementBits(BranchOp);
387 assert(Bits >= 3 && "max branch displacement must be enough to jump"
388 "over conditional branch expansion");
389 return isIntN(Bits, BrOffset / 4);
390}
391
394 switch (MI.getOpcode()) {
395 default:
396 llvm_unreachable("unexpected opcode!");
397 case AArch64::B:
398 return MI.getOperand(0).getMBB();
399 case AArch64::TBZW:
400 case AArch64::TBNZW:
401 case AArch64::TBZX:
402 case AArch64::TBNZX:
403 return MI.getOperand(2).getMBB();
404 case AArch64::CBZW:
405 case AArch64::CBNZW:
406 case AArch64::CBZX:
407 case AArch64::CBNZX:
408 case AArch64::Bcc:
409 return MI.getOperand(1).getMBB();
410 case AArch64::CBWPri:
411 case AArch64::CBXPri:
412 case AArch64::CBBAssertExt:
413 case AArch64::CBHAssertExt:
414 case AArch64::CBWPrr:
415 case AArch64::CBXPrr:
416 return MI.getOperand(3).getMBB();
417 }
418}
419
421 MachineBasicBlock &NewDestBB,
422 MachineBasicBlock &RestoreBB,
423 const DebugLoc &DL,
424 int64_t BrOffset,
425 RegScavenger *RS) const {
426 assert(RS && "RegScavenger required for long branching");
427 assert(MBB.empty() &&
428 "new block should be inserted for expanding unconditional branch");
429 assert(MBB.pred_size() == 1);
430 assert(RestoreBB.empty() &&
431 "restore block should be inserted for restoring clobbered registers");
432
433 auto buildIndirectBranch = [&](Register Reg, MachineBasicBlock &DestBB) {
434 // Offsets outside of the signed 33-bit range are not supported for ADRP +
435 // ADD.
436 if (!isInt<33>(BrOffset))
438 "Branch offsets outside of the signed 33-bit range not supported");
439
440 BuildMI(MBB, MBB.end(), DL, get(AArch64::ADRP), Reg)
441 .addSym(DestBB.getSymbol(), AArch64II::MO_PAGE);
442 BuildMI(MBB, MBB.end(), DL, get(AArch64::ADDXri), Reg)
443 .addReg(Reg)
444 .addSym(DestBB.getSymbol(), AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
445 .addImm(0);
446 BuildMI(MBB, MBB.end(), DL, get(AArch64::BR)).addReg(Reg);
447 };
448
449 RS->enterBasicBlockEnd(MBB);
450 // If X16 is unused, we can rely on the linker to insert a range extension
451 // thunk if NewDestBB is out of range of a single B instruction.
452 constexpr Register Reg = AArch64::X16;
453 if (!RS->isRegUsed(Reg)) {
454 insertUnconditionalBranch(MBB, &NewDestBB, DL);
455 RS->setRegUsed(Reg);
456 return;
457 }
458
459 // In a cold block without BTI, insert the indirect branch if a register is
460 // free. Skip this if BTI is enabled to avoid inserting a BTI at the target,
461 // prioritizing a dynamic cost in cold code over a static cost in hot code.
462 AArch64FunctionInfo *AFI = MBB.getParent()->getInfo<AArch64FunctionInfo>();
463 bool HasBTI = AFI && AFI->branchTargetEnforcement();
464 if (MBB.getSectionID() == MBBSectionID::ColdSectionID && !HasBTI) {
465 Register Scavenged = RS->FindUnusedReg(&AArch64::GPR64RegClass);
466 if (Scavenged != AArch64::NoRegister) {
467 buildIndirectBranch(Scavenged, NewDestBB);
468 RS->setRegUsed(Scavenged);
469 return;
470 }
471 }
472
473 // Note: Spilling X16 briefly moves the stack pointer, making it incompatible
474 // with red zones.
475 if (!AFI || AFI->hasRedZone().value_or(true))
477 "Unable to insert indirect branch inside function that has red zone");
478
479 // Otherwise, spill X16 and defer range extension to the linker.
480 BuildMI(MBB, MBB.end(), DL, get(AArch64::STRXpre))
481 .addReg(AArch64::SP, RegState::Define)
482 .addReg(Reg)
483 .addReg(AArch64::SP)
484 .addImm(-16);
485
486 BuildMI(MBB, MBB.end(), DL, get(AArch64::B)).addMBB(&RestoreBB);
487
488 BuildMI(RestoreBB, RestoreBB.end(), DL, get(AArch64::LDRXpost))
489 .addReg(AArch64::SP, RegState::Define)
491 .addReg(AArch64::SP)
492 .addImm(16);
493}
494
495// Branch analysis.
498 MachineBasicBlock *&FBB,
500 bool AllowModify) const {
501 // If the block has no terminators, it just falls into the block after it.
502 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
503 if (I == MBB.end())
504 return false;
505
506 // Skip over SpeculationBarrierEndBB terminators
507 if (I->getOpcode() == AArch64::SpeculationBarrierISBDSBEndBB ||
508 I->getOpcode() == AArch64::SpeculationBarrierSBEndBB) {
509 --I;
510 }
511
512 if (!isUnpredicatedTerminator(*I))
513 return false;
514
515 // Get the last instruction in the block.
516 MachineInstr *LastInst = &*I;
517
518 // If there is only one terminator instruction, process it.
519 unsigned LastOpc = LastInst->getOpcode();
520 if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
521 if (isUncondBranchOpcode(LastOpc)) {
522 TBB = LastInst->getOperand(0).getMBB();
523 return false;
524 }
525 if (isCondBranchOpcode(LastOpc)) {
526 // Block ends with fall-through condbranch.
527 parseCondBranch(LastInst, TBB, Cond);
528 return false;
529 }
530 return true; // Can't handle indirect branch.
531 }
532
533 // Get the instruction before it if it is a terminator.
534 MachineInstr *SecondLastInst = &*I;
535 unsigned SecondLastOpc = SecondLastInst->getOpcode();
536
537 // If AllowModify is true and the block ends with two or more unconditional
538 // branches, delete all but the first unconditional branch.
539 if (AllowModify && isUncondBranchOpcode(LastOpc)) {
540 while (isUncondBranchOpcode(SecondLastOpc)) {
541 LastInst->eraseFromParent();
542 LastInst = SecondLastInst;
543 LastOpc = LastInst->getOpcode();
544 if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
545 // Return now the only terminator is an unconditional branch.
546 TBB = LastInst->getOperand(0).getMBB();
547 return false;
548 }
549 SecondLastInst = &*I;
550 SecondLastOpc = SecondLastInst->getOpcode();
551 }
552 }
553
554 // If we're allowed to modify and the block ends in a unconditional branch
555 // which could simply fallthrough, remove the branch. (Note: This case only
556 // matters when we can't understand the whole sequence, otherwise it's also
557 // handled by BranchFolding.cpp.)
558 if (AllowModify && isUncondBranchOpcode(LastOpc) &&
559 MBB.isLayoutSuccessor(getBranchDestBlock(*LastInst))) {
560 LastInst->eraseFromParent();
561 LastInst = SecondLastInst;
562 LastOpc = LastInst->getOpcode();
563 if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
564 assert(!isUncondBranchOpcode(LastOpc) &&
565 "unreachable unconditional branches removed above");
566
567 if (isCondBranchOpcode(LastOpc)) {
568 // Block ends with fall-through condbranch.
569 parseCondBranch(LastInst, TBB, Cond);
570 return false;
571 }
572 return true; // Can't handle indirect branch.
573 }
574 SecondLastInst = &*I;
575 SecondLastOpc = SecondLastInst->getOpcode();
576 }
577
578 // If there are three terminators, we don't know what sort of block this is.
579 if (SecondLastInst && I != MBB.begin() && isUnpredicatedTerminator(*--I))
580 return true;
581
582 // If the block ends with a B and a Bcc, handle it.
583 if (isCondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
584 parseCondBranch(SecondLastInst, TBB, Cond);
585 FBB = LastInst->getOperand(0).getMBB();
586 return false;
587 }
588
589 // If the block ends with two unconditional branches, handle it. The second
590 // one is not executed, so remove it.
591 if (isUncondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
592 TBB = SecondLastInst->getOperand(0).getMBB();
593 I = LastInst;
594 if (AllowModify)
595 I->eraseFromParent();
596 return false;
597 }
598
599 // ...likewise if it ends with an indirect branch followed by an unconditional
600 // branch.
601 if (isIndirectBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
602 I = LastInst;
603 if (AllowModify)
604 I->eraseFromParent();
605 return true;
606 }
607
608 // Otherwise, can't handle this.
609 return true;
610}
611
613 MachineBranchPredicate &MBP,
614 bool AllowModify) const {
615 // Use analyzeBranch to validate the branch pattern.
616 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
618 if (analyzeBranch(MBB, TBB, FBB, Cond, AllowModify))
619 return true;
620
621 // analyzeBranch returns success with empty Cond for unconditional branches.
622 if (Cond.empty())
623 return true;
624
625 MBP.TrueDest = TBB;
626 assert(MBP.TrueDest && "expected!");
627 MBP.FalseDest = FBB ? FBB : MBB.getNextNode();
628
629 MBP.ConditionDef = nullptr;
630 MBP.SingleUseCondition = false;
631
632 // Find the conditional branch. After analyzeBranch succeeds with non-empty
633 // Cond, there's exactly one conditional branch - either last (fallthrough)
634 // or second-to-last (followed by unconditional B).
635 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
636 if (I == MBB.end())
637 return true;
638
639 if (isUncondBranchOpcode(I->getOpcode())) {
640 if (I == MBB.begin())
641 return true;
642 --I;
643 }
644
645 MachineInstr *CondBranch = &*I;
646 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
647
648 switch (CondBranch->getOpcode()) {
649 default:
650 return true;
651
652 case AArch64::Bcc:
653 // Bcc takes the NZCV flag as the operand to branch on, walk up the
654 // instruction stream to find the last instruction to define NZCV.
656 if (MI.modifiesRegister(AArch64::NZCV, /*TRI=*/nullptr)) {
657 MBP.ConditionDef = &MI;
658 break;
659 }
660 }
661 return false;
662
663 case AArch64::CBZW:
664 case AArch64::CBZX:
665 case AArch64::CBNZW:
666 case AArch64::CBNZX: {
667 MBP.LHS = CondBranch->getOperand(0);
668 MBP.RHS = MachineOperand::CreateImm(0);
669 unsigned Opc = CondBranch->getOpcode();
670 MBP.Predicate = (Opc == AArch64::CBNZX || Opc == AArch64::CBNZW)
671 ? MachineBranchPredicate::PRED_NE
672 : MachineBranchPredicate::PRED_EQ;
673 Register CondReg = MBP.LHS.getReg();
674 if (CondReg.isVirtual())
675 MBP.ConditionDef = MRI.getVRegDef(CondReg);
676 return false;
677 }
678
679 case AArch64::TBZW:
680 case AArch64::TBZX:
681 case AArch64::TBNZW:
682 case AArch64::TBNZX: {
683 Register CondReg = CondBranch->getOperand(0).getReg();
684 if (CondReg.isVirtual())
685 MBP.ConditionDef = MRI.getVRegDef(CondReg);
686 return false;
687 }
688 }
689}
690
693 if (Cond[0].getImm() != -1) {
694 // Regular Bcc
695 AArch64CC::CondCode CC = (AArch64CC::CondCode)(int)Cond[0].getImm();
697 } else {
698 // Folded compare-and-branch
699 switch (Cond[1].getImm()) {
700 default:
701 llvm_unreachable("Unknown conditional branch!");
702 case AArch64::CBZW:
703 Cond[1].setImm(AArch64::CBNZW);
704 break;
705 case AArch64::CBNZW:
706 Cond[1].setImm(AArch64::CBZW);
707 break;
708 case AArch64::CBZX:
709 Cond[1].setImm(AArch64::CBNZX);
710 break;
711 case AArch64::CBNZX:
712 Cond[1].setImm(AArch64::CBZX);
713 break;
714 case AArch64::TBZW:
715 Cond[1].setImm(AArch64::TBNZW);
716 break;
717 case AArch64::TBNZW:
718 Cond[1].setImm(AArch64::TBZW);
719 break;
720 case AArch64::TBZX:
721 Cond[1].setImm(AArch64::TBNZX);
722 break;
723 case AArch64::TBNZX:
724 Cond[1].setImm(AArch64::TBZX);
725 break;
726
727 // Cond is { -1, Opcode, CC, Op0, Op1, ... }
728 case AArch64::CBWPri:
729 case AArch64::CBXPri:
730 case AArch64::CBBAssertExt:
731 case AArch64::CBHAssertExt:
732 case AArch64::CBWPrr:
733 case AArch64::CBXPrr: {
734 // Pseudos using standard 4bit Arm condition codes
736 static_cast<AArch64CC::CondCode>(Cond[2].getImm());
738 }
739 }
740 }
741
742 return false;
743}
744
746 int *BytesRemoved) const {
747 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
748 if (I == MBB.end())
749 return 0;
750
751 if (!isUncondBranchOpcode(I->getOpcode()) &&
752 !isCondBranchOpcode(I->getOpcode()))
753 return 0;
754
755 // Remove the branch.
756 I->eraseFromParent();
757
758 I = MBB.end();
759
760 if (I == MBB.begin()) {
761 if (BytesRemoved)
762 *BytesRemoved = 4;
763 return 1;
764 }
765 --I;
766 if (!isCondBranchOpcode(I->getOpcode())) {
767 if (BytesRemoved)
768 *BytesRemoved = 4;
769 return 1;
770 }
771
772 // Remove the branch.
773 I->eraseFromParent();
774 if (BytesRemoved)
775 *BytesRemoved = 8;
776
777 return 2;
778}
779
780void AArch64InstrInfo::instantiateCondBranch(
783 if (Cond[0].getImm() != -1) {
784 // Regular Bcc
785 BuildMI(&MBB, DL, get(AArch64::Bcc)).addImm(Cond[0].getImm()).addMBB(TBB);
786 } else {
787 // Folded compare-and-branch
788 // Note that we use addOperand instead of addReg to keep the flags.
789
790 // cbz, cbnz
791 const MachineInstrBuilder MIB =
792 BuildMI(&MBB, DL, get(Cond[1].getImm())).add(Cond[2]);
793
794 // tbz/tbnz
795 if (Cond.size() > 3)
796 MIB.add(Cond[3]);
797
798 // cb
799 if (Cond.size() > 4)
800 MIB.add(Cond[4]);
801
802 MIB.addMBB(TBB);
803
804 // cb[b,h]
805 if (Cond.size() > 5) {
806 MIB.addImm(Cond[5].getImm());
807 MIB.addImm(Cond[6].getImm());
808 }
809 }
810}
811
814 ArrayRef<MachineOperand> Cond, const DebugLoc &DL, int *BytesAdded) const {
815 // Shouldn't be a fall through.
816 assert(TBB && "insertBranch must not be told to insert a fallthrough");
817
818 if (!FBB) {
819 if (Cond.empty()) // Unconditional branch?
820 BuildMI(&MBB, DL, get(AArch64::B)).addMBB(TBB);
821 else
822 instantiateCondBranch(MBB, DL, TBB, Cond);
823
824 if (BytesAdded)
825 *BytesAdded = 4;
826
827 return 1;
828 }
829
830 // Two-way conditional branch.
831 instantiateCondBranch(MBB, DL, TBB, Cond);
832 BuildMI(&MBB, DL, get(AArch64::B)).addMBB(FBB);
833
834 if (BytesAdded)
835 *BytesAdded = 8;
836
837 return 2;
838}
839
841 const TargetInstrInfo &TII) {
842 for (MachineInstr &MI : MBB->terminators()) {
843 unsigned Opc = MI.getOpcode();
844 switch (Opc) {
845 case AArch64::CBZW:
846 case AArch64::CBZX:
847 case AArch64::TBZW:
848 case AArch64::TBZX:
849 // CBZ/TBZ with WZR/XZR -> unconditional B
850 if (MI.getOperand(0).getReg() == AArch64::WZR ||
851 MI.getOperand(0).getReg() == AArch64::XZR) {
852 DEBUG_WITH_TYPE("optimizeTerminators",
853 dbgs() << "Removing always taken branch: " << MI);
854 MachineBasicBlock *Target = TII.getBranchDestBlock(MI);
855 SmallVector<MachineBasicBlock *> Succs(MBB->successors());
856 for (auto *S : Succs)
857 if (S != Target)
858 MBB->removeSuccessor(S);
859 DebugLoc DL = MI.getDebugLoc();
860 while (MBB->rbegin() != &MI)
861 MBB->rbegin()->eraseFromParent();
862 MI.eraseFromParent();
863 BuildMI(MBB, DL, TII.get(AArch64::B)).addMBB(Target);
864 return true;
865 }
866 break;
867 case AArch64::CBNZW:
868 case AArch64::CBNZX:
869 case AArch64::TBNZW:
870 case AArch64::TBNZX:
871 // CBNZ/TBNZ with WZR/XZR -> never taken, remove branch and successor
872 if (MI.getOperand(0).getReg() == AArch64::WZR ||
873 MI.getOperand(0).getReg() == AArch64::XZR) {
874 DEBUG_WITH_TYPE("optimizeTerminators",
875 dbgs() << "Removing never taken branch: " << MI);
876 MachineBasicBlock *Target = TII.getBranchDestBlock(MI);
877 MI.getParent()->removeSuccessor(Target);
878 MI.eraseFromParent();
879 return true;
880 }
881 break;
882 }
883 }
884 return false;
885}
886
887// Find the original register that VReg is copied from.
888static unsigned removeCopies(const MachineRegisterInfo &MRI, unsigned VReg) {
889 while (Register::isVirtualRegister(VReg)) {
890 const MachineInstr *DefMI = MRI.getVRegDef(VReg);
891 if (!DefMI->isFullCopy())
892 return VReg;
893 VReg = DefMI->getOperand(1).getReg();
894 }
895 return VReg;
896}
897
898// Determine if VReg is defined by an instruction that can be folded into a
899// csel instruction. If so, return the folded opcode, and the replacement
900// register.
901static unsigned canFoldIntoCSel(const MachineRegisterInfo &MRI, unsigned VReg,
902 unsigned *NewReg = nullptr) {
903 VReg = removeCopies(MRI, VReg);
905 return 0;
906
907 bool Is64Bit = AArch64::GPR64allRegClass.hasSubClassEq(MRI.getRegClass(VReg));
908 const MachineInstr *DefMI = MRI.getVRegDef(VReg);
909 unsigned Opc = 0;
910 unsigned SrcReg = 0;
911 switch (DefMI->getOpcode()) {
912 case AArch64::SUBREG_TO_REG:
913 // Check for the following way to define an 64-bit immediate:
914 // %0:gpr32 = MOVi32imm 1
915 // %1:gpr64 = SUBREG_TO_REG %0:gpr32, %subreg.sub_32
916 if (!DefMI->getOperand(1).isReg())
917 return 0;
918 if (!DefMI->getOperand(2).isImm() ||
919 DefMI->getOperand(2).getImm() != AArch64::sub_32)
920 return 0;
921 DefMI = MRI.getVRegDef(DefMI->getOperand(1).getReg());
922 if (DefMI->getOpcode() != AArch64::MOVi32imm)
923 return 0;
924 if (!DefMI->getOperand(1).isImm() || DefMI->getOperand(1).getImm() != 1)
925 return 0;
926 assert(Is64Bit);
927 SrcReg = AArch64::XZR;
928 Opc = AArch64::CSINCXr;
929 break;
930
931 case AArch64::MOVi32imm:
932 case AArch64::MOVi64imm:
933 if (!DefMI->getOperand(1).isImm() || DefMI->getOperand(1).getImm() != 1)
934 return 0;
935 SrcReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
936 Opc = Is64Bit ? AArch64::CSINCXr : AArch64::CSINCWr;
937 break;
938
939 case AArch64::ADDSXri:
940 case AArch64::ADDSWri:
941 // if NZCV is used, do not fold.
942 if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr,
943 true) == -1)
944 return 0;
945 // fall-through to ADDXri and ADDWri.
946 [[fallthrough]];
947 case AArch64::ADDXri:
948 case AArch64::ADDWri:
949 // add x, 1 -> csinc.
950 if (!DefMI->getOperand(2).isImm() || DefMI->getOperand(2).getImm() != 1 ||
951 DefMI->getOperand(3).getImm() != 0)
952 return 0;
953 SrcReg = DefMI->getOperand(1).getReg();
954 Opc = Is64Bit ? AArch64::CSINCXr : AArch64::CSINCWr;
955 break;
956
957 case AArch64::ORNXrr:
958 case AArch64::ORNWrr: {
959 // not x -> csinv, represented as orn dst, xzr, src.
960 unsigned ZReg = removeCopies(MRI, DefMI->getOperand(1).getReg());
961 if (ZReg != AArch64::XZR && ZReg != AArch64::WZR)
962 return 0;
963 SrcReg = DefMI->getOperand(2).getReg();
964 Opc = Is64Bit ? AArch64::CSINVXr : AArch64::CSINVWr;
965 break;
966 }
967
968 case AArch64::SUBSXrr:
969 case AArch64::SUBSWrr:
970 // if NZCV is used, do not fold.
971 if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr,
972 true) == -1)
973 return 0;
974 // fall-through to SUBXrr and SUBWrr.
975 [[fallthrough]];
976 case AArch64::SUBXrr:
977 case AArch64::SUBWrr: {
978 // neg x -> csneg, represented as sub dst, xzr, src.
979 unsigned ZReg = removeCopies(MRI, DefMI->getOperand(1).getReg());
980 if (ZReg != AArch64::XZR && ZReg != AArch64::WZR)
981 return 0;
982 SrcReg = DefMI->getOperand(2).getReg();
983 Opc = Is64Bit ? AArch64::CSNEGXr : AArch64::CSNEGWr;
984 break;
985 }
986 default:
987 return 0;
988 }
989 assert(Opc && SrcReg && "Missing parameters");
990
991 if (NewReg)
992 *NewReg = SrcReg;
993 return Opc;
994}
995
998 Register DstReg, Register TrueReg,
999 Register FalseReg, int &CondCycles,
1000 int &TrueCycles,
1001 int &FalseCycles) const {
1002 // Check register classes.
1003 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1004 const TargetRegisterClass *RC =
1005 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
1006 if (!RC)
1007 return false;
1008
1009 // Also need to check the dest regclass, in case we're trying to optimize
1010 // something like:
1011 // %1(gpr) = PHI %2(fpr), bb1, %(fpr), bb2
1012 if (!RI.getCommonSubClass(RC, MRI.getRegClass(DstReg)))
1013 return false;
1014
1015 // Expanding cbz/tbz requires an extra cycle of latency on the condition.
1016 unsigned ExtraCondLat = Cond.size() != 1;
1017
1018 // GPRs are handled by csel.
1019 // FIXME: Fold in x+1, -x, and ~x when applicable.
1020 if (AArch64::GPR64allRegClass.hasSubClassEq(RC) ||
1021 AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
1022 // Single-cycle csel, csinc, csinv, and csneg.
1023 CondCycles = 1 + ExtraCondLat;
1024 TrueCycles = FalseCycles = 1;
1025 if (canFoldIntoCSel(MRI, TrueReg))
1026 TrueCycles = 0;
1027 else if (canFoldIntoCSel(MRI, FalseReg))
1028 FalseCycles = 0;
1029 return true;
1030 }
1031
1032 // Scalar floating point is handled by fcsel.
1033 // FIXME: Form fabs, fmin, and fmax when applicable.
1034 if (AArch64::FPR64RegClass.hasSubClassEq(RC) ||
1035 AArch64::FPR32RegClass.hasSubClassEq(RC)) {
1036 CondCycles = 5 + ExtraCondLat;
1037 TrueCycles = FalseCycles = 2;
1038 return true;
1039 }
1040
1041 // Can't do vectors.
1042 return false;
1043}
1044
1047 const DebugLoc &DL, Register DstReg,
1049 Register TrueReg, Register FalseReg) const {
1050 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1051
1052 // Parse the condition code, see parseCondBranch() above.
1054 switch (Cond.size()) {
1055 default:
1056 llvm_unreachable("Unknown condition opcode in Cond");
1057 case 1: // b.cc
1058 CC = AArch64CC::CondCode(Cond[0].getImm());
1059 break;
1060 case 3: { // cbz/cbnz
1061 // We must insert a compare against 0.
1062 bool Is64Bit;
1063 switch (Cond[1].getImm()) {
1064 default:
1065 llvm_unreachable("Unknown branch opcode in Cond");
1066 case AArch64::CBZW:
1067 Is64Bit = false;
1068 CC = AArch64CC::EQ;
1069 break;
1070 case AArch64::CBZX:
1071 Is64Bit = true;
1072 CC = AArch64CC::EQ;
1073 break;
1074 case AArch64::CBNZW:
1075 Is64Bit = false;
1076 CC = AArch64CC::NE;
1077 break;
1078 case AArch64::CBNZX:
1079 Is64Bit = true;
1080 CC = AArch64CC::NE;
1081 break;
1082 }
1083 Register SrcReg = Cond[2].getReg();
1084 if (Is64Bit) {
1085 // cmp reg, #0 is actually subs xzr, reg, #0.
1086 MRI.constrainRegClass(SrcReg, &AArch64::GPR64spRegClass);
1087 BuildMI(MBB, I, DL, get(AArch64::SUBSXri), AArch64::XZR)
1088 .addReg(SrcReg)
1089 .addImm(0)
1090 .addImm(0);
1091 } else {
1092 MRI.constrainRegClass(SrcReg, &AArch64::GPR32spRegClass);
1093 BuildMI(MBB, I, DL, get(AArch64::SUBSWri), AArch64::WZR)
1094 .addReg(SrcReg)
1095 .addImm(0)
1096 .addImm(0);
1097 }
1098 break;
1099 }
1100 case 4: { // tbz/tbnz
1101 // We must insert a tst instruction.
1102 switch (Cond[1].getImm()) {
1103 default:
1104 llvm_unreachable("Unknown branch opcode in Cond");
1105 case AArch64::TBZW:
1106 case AArch64::TBZX:
1107 CC = AArch64CC::EQ;
1108 break;
1109 case AArch64::TBNZW:
1110 case AArch64::TBNZX:
1111 CC = AArch64CC::NE;
1112 break;
1113 }
1114 // cmp reg, #foo is actually ands xzr, reg, #1<<foo.
1115 if (Cond[1].getImm() == AArch64::TBZW || Cond[1].getImm() == AArch64::TBNZW)
1116 BuildMI(MBB, I, DL, get(AArch64::ANDSWri), AArch64::WZR)
1117 .addReg(Cond[2].getReg())
1118 .addImm(
1120 else
1121 BuildMI(MBB, I, DL, get(AArch64::ANDSXri), AArch64::XZR)
1122 .addReg(Cond[2].getReg())
1123 .addImm(
1125 break;
1126 }
1127 case 5: { // cb
1128 // We must insert a cmp, that is a subs
1129 // 0 1 2 3 4
1130 // Cond is { -1, Opcode, CC, Op0, Op1 }
1131
1132 unsigned SubsOpc, SubsDestReg;
1133 bool IsImm = false;
1134 CC = static_cast<AArch64CC::CondCode>(Cond[2].getImm());
1135 switch (Cond[1].getImm()) {
1136 default:
1137 llvm_unreachable("Unknown branch opcode in Cond");
1138 case AArch64::CBWPri:
1139 SubsOpc = AArch64::SUBSWri;
1140 SubsDestReg = AArch64::WZR;
1141 IsImm = true;
1142 break;
1143 case AArch64::CBXPri:
1144 SubsOpc = AArch64::SUBSXri;
1145 SubsDestReg = AArch64::XZR;
1146 IsImm = true;
1147 break;
1148 case AArch64::CBWPrr:
1149 SubsOpc = AArch64::SUBSWrr;
1150 SubsDestReg = AArch64::WZR;
1151 IsImm = false;
1152 break;
1153 case AArch64::CBXPrr:
1154 SubsOpc = AArch64::SUBSXrr;
1155 SubsDestReg = AArch64::XZR;
1156 IsImm = false;
1157 break;
1158 }
1159
1160 if (IsImm)
1161 BuildMI(MBB, I, DL, get(SubsOpc), SubsDestReg)
1162 .addReg(Cond[3].getReg())
1163 .addImm(Cond[4].getImm())
1164 .addImm(0);
1165 else
1166 BuildMI(MBB, I, DL, get(SubsOpc), SubsDestReg)
1167 .addReg(Cond[3].getReg())
1168 .addReg(Cond[4].getReg());
1169 } break;
1170 case 7: { // cb[b,h]
1171 // We must insert a cmp, that is a subs, but also zero- or sign-extensions
1172 // that have been folded. For the first operand we codegen an explicit
1173 // extension, for the second operand we fold the extension into cmp.
1174 // 0 1 2 3 4 5 6
1175 // Cond is { -1, Opcode, CC, Op0, Op1, Ext0, Ext1 }
1176
1177 // We need a new register for the now explicitly extended register
1178 Register Reg = Cond[4].getReg();
1180 unsigned ExtOpc;
1181 unsigned ExtBits;
1182 AArch64_AM::ShiftExtendType ExtendType =
1184 switch (ExtendType) {
1185 default:
1186 llvm_unreachable("Unknown shift-extend for CB instruction");
1187 case AArch64_AM::SXTB:
1188 assert(
1189 Cond[1].getImm() == AArch64::CBBAssertExt &&
1190 "Unexpected compare-and-branch instruction for SXTB shift-extend");
1191 ExtOpc = AArch64::SBFMWri;
1192 ExtBits = AArch64_AM::encodeLogicalImmediate(0xff, 32);
1193 break;
1194 case AArch64_AM::SXTH:
1195 assert(
1196 Cond[1].getImm() == AArch64::CBHAssertExt &&
1197 "Unexpected compare-and-branch instruction for SXTH shift-extend");
1198 ExtOpc = AArch64::SBFMWri;
1199 ExtBits = AArch64_AM::encodeLogicalImmediate(0xffff, 32);
1200 break;
1201 case AArch64_AM::UXTB:
1202 assert(
1203 Cond[1].getImm() == AArch64::CBBAssertExt &&
1204 "Unexpected compare-and-branch instruction for UXTB shift-extend");
1205 ExtOpc = AArch64::ANDWri;
1206 ExtBits = AArch64_AM::encodeLogicalImmediate(0xff, 32);
1207 break;
1208 case AArch64_AM::UXTH:
1209 assert(
1210 Cond[1].getImm() == AArch64::CBHAssertExt &&
1211 "Unexpected compare-and-branch instruction for UXTH shift-extend");
1212 ExtOpc = AArch64::ANDWri;
1213 ExtBits = AArch64_AM::encodeLogicalImmediate(0xffff, 32);
1214 break;
1215 }
1216
1217 // Build the explicit extension of the first operand
1218 Reg = MRI.createVirtualRegister(&AArch64::GPR32spRegClass);
1220 BuildMI(MBB, I, DL, get(ExtOpc), Reg).addReg(Cond[4].getReg());
1221 if (ExtOpc != AArch64::ANDWri)
1222 MBBI.addImm(0);
1223 MBBI.addImm(ExtBits);
1224 }
1225
1226 // Now, subs with an extended second operand
1228 AArch64_AM::ShiftExtendType ExtendType =
1230 MRI.constrainRegClass(Reg, MRI.getRegClass(Cond[3].getReg()));
1231 MRI.constrainRegClass(Cond[3].getReg(), &AArch64::GPR32spRegClass);
1232 BuildMI(MBB, I, DL, get(AArch64::SUBSWrx), AArch64::WZR)
1233 .addReg(Cond[3].getReg())
1234 .addReg(Reg)
1235 .addImm(AArch64_AM::getArithExtendImm(ExtendType, 0));
1236 } // If no extension is needed, just a regular subs
1237 else {
1238 MRI.constrainRegClass(Reg, MRI.getRegClass(Cond[3].getReg()));
1239 MRI.constrainRegClass(Cond[3].getReg(), &AArch64::GPR32spRegClass);
1240 BuildMI(MBB, I, DL, get(AArch64::SUBSWrr), AArch64::WZR)
1241 .addReg(Cond[3].getReg())
1242 .addReg(Reg);
1243 }
1244
1245 CC = static_cast<AArch64CC::CondCode>(Cond[2].getImm());
1246 } break;
1247 }
1248
1249 unsigned Opc = 0;
1250 const TargetRegisterClass *RC = nullptr;
1251 bool TryFold = false;
1252 if (MRI.constrainRegClass(DstReg, &AArch64::GPR64RegClass)) {
1253 RC = &AArch64::GPR64RegClass;
1254 Opc = AArch64::CSELXr;
1255 TryFold = true;
1256 } else if (MRI.constrainRegClass(DstReg, &AArch64::GPR32RegClass)) {
1257 RC = &AArch64::GPR32RegClass;
1258 Opc = AArch64::CSELWr;
1259 TryFold = true;
1260 } else if (MRI.constrainRegClass(DstReg, &AArch64::FPR64RegClass)) {
1261 RC = &AArch64::FPR64RegClass;
1262 Opc = AArch64::FCSELDrrr;
1263 } else if (MRI.constrainRegClass(DstReg, &AArch64::FPR32RegClass)) {
1264 RC = &AArch64::FPR32RegClass;
1265 Opc = AArch64::FCSELSrrr;
1266 }
1267 assert(RC && "Unsupported regclass");
1268
1269 // Try folding simple instructions into the csel.
1270 if (TryFold) {
1271 unsigned NewReg = 0;
1272 unsigned FoldedOpc = canFoldIntoCSel(MRI, TrueReg, &NewReg);
1273 if (FoldedOpc) {
1274 // The folded opcodes csinc, csinc and csneg apply the operation to
1275 // FalseReg, so we need to invert the condition.
1277 TrueReg = FalseReg;
1278 } else
1279 FoldedOpc = canFoldIntoCSel(MRI, FalseReg, &NewReg);
1280
1281 // Fold the operation. Leave any dead instructions for DCE to clean up.
1282 if (FoldedOpc) {
1283 FalseReg = NewReg;
1284 Opc = FoldedOpc;
1285 // Extend the live range of NewReg.
1286 MRI.clearKillFlags(NewReg);
1287 }
1288 }
1289
1290 // Pull all virtual register into the appropriate class.
1291 MRI.constrainRegClass(TrueReg, RC);
1292 // FalseReg might be WZR or XZR if the folded operand is a literal 1.
1293 assert(
1294 (FalseReg.isVirtual() || FalseReg == AArch64::WZR ||
1295 FalseReg == AArch64::XZR) &&
1296 "FalseReg was folded into a non-virtual register other than WZR or XZR");
1297 if (FalseReg.isVirtual())
1298 MRI.constrainRegClass(FalseReg, RC);
1299
1300 // Insert the csel.
1301 BuildMI(MBB, I, DL, get(Opc), DstReg)
1302 .addReg(TrueReg)
1303 .addReg(FalseReg)
1304 .addImm(CC);
1305}
1306
1307// Return true if Imm can be loaded into a register by a "cheap" sequence of
1308// instructions. For now, "cheap" means at most two instructions.
1309static bool isCheapImmediate(const MachineInstr &MI, unsigned BitSize) {
1310 if (BitSize == 32)
1311 return true;
1312
1313 assert(BitSize == 64 && "Only bit sizes of 32 or 64 allowed");
1314 uint64_t Imm = static_cast<uint64_t>(MI.getOperand(1).getImm());
1316 AArch64_IMM::expandMOVImm(Imm, BitSize, Is);
1317
1318 return Is.size() <= 2;
1319}
1320
1321// Check if a COPY instruction is cheap.
1322static bool isCheapCopy(const MachineInstr &MI, const AArch64RegisterInfo &RI) {
1323 assert(MI.isCopy() && "Expected COPY instruction");
1324 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1325
1326 // Cross-bank copies (e.g., between GPR and FPR) are expensive on AArch64,
1327 // typically requiring an FMOV instruction with a 2-6 cycle latency.
1328 auto GetRegClass = [&](Register Reg) -> const TargetRegisterClass * {
1329 if (Reg.isVirtual())
1330 return MRI.getRegClass(Reg);
1331 if (Reg.isPhysical())
1332 return RI.getMinimalPhysRegClass(Reg);
1333 return nullptr;
1334 };
1335 const TargetRegisterClass *DstRC = GetRegClass(MI.getOperand(0).getReg());
1336 const TargetRegisterClass *SrcRC = GetRegClass(MI.getOperand(1).getReg());
1337 if (DstRC && SrcRC && !RI.getCommonSubClass(DstRC, SrcRC))
1338 return false;
1339
1340 return MI.isAsCheapAsAMove();
1341}
1342
1343// FIXME: this implementation should be micro-architecture dependent, so a
1344// micro-architecture target hook should be introduced here in future.
1346 if (Subtarget.hasExynosCheapAsMoveHandling()) {
1347 if (isExynosCheapAsMove(MI))
1348 return true;
1349 return MI.isAsCheapAsAMove();
1350 }
1351
1352 switch (MI.getOpcode()) {
1353 default:
1354 return MI.isAsCheapAsAMove();
1355
1356 case TargetOpcode::COPY:
1357 return isCheapCopy(MI, RI);
1358
1359 case AArch64::ADDWrs:
1360 case AArch64::ADDXrs:
1361 case AArch64::SUBWrs:
1362 case AArch64::SUBXrs:
1363 return Subtarget.hasALULSLFast() && MI.getOperand(3).getImm() <= 4;
1364
1365 // If MOVi32imm or MOVi64imm can be expanded into ORRWri or
1366 // ORRXri, it is as cheap as MOV.
1367 // Likewise if it can be expanded to MOVZ/MOVN/MOVK.
1368 case AArch64::MOVi32imm:
1369 return isCheapImmediate(MI, 32);
1370 case AArch64::MOVi64imm:
1371 return isCheapImmediate(MI, 64);
1372 }
1373}
1374
1375bool AArch64InstrInfo::isFalkorShiftExtFast(const MachineInstr &MI) {
1376 switch (MI.getOpcode()) {
1377 default:
1378 return false;
1379
1380 case AArch64::ADDWrs:
1381 case AArch64::ADDXrs:
1382 case AArch64::ADDSWrs:
1383 case AArch64::ADDSXrs: {
1384 unsigned Imm = MI.getOperand(3).getImm();
1385 unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
1386 if (ShiftVal == 0)
1387 return true;
1388 return AArch64_AM::getShiftType(Imm) == AArch64_AM::LSL && ShiftVal <= 5;
1389 }
1390
1391 case AArch64::ADDWrx:
1392 case AArch64::ADDXrx:
1393 case AArch64::ADDXrx64:
1394 case AArch64::ADDSWrx:
1395 case AArch64::ADDSXrx:
1396 case AArch64::ADDSXrx64: {
1397 unsigned Imm = MI.getOperand(3).getImm();
1398 switch (AArch64_AM::getArithExtendType(Imm)) {
1399 default:
1400 return false;
1401 case AArch64_AM::UXTB:
1402 case AArch64_AM::UXTH:
1403 case AArch64_AM::UXTW:
1404 case AArch64_AM::UXTX:
1405 return AArch64_AM::getArithShiftValue(Imm) <= 4;
1406 }
1407 }
1408
1409 case AArch64::SUBWrs:
1410 case AArch64::SUBSWrs: {
1411 unsigned Imm = MI.getOperand(3).getImm();
1412 unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
1413 return ShiftVal == 0 ||
1414 (AArch64_AM::getShiftType(Imm) == AArch64_AM::ASR && ShiftVal == 31);
1415 }
1416
1417 case AArch64::SUBXrs:
1418 case AArch64::SUBSXrs: {
1419 unsigned Imm = MI.getOperand(3).getImm();
1420 unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
1421 return ShiftVal == 0 ||
1422 (AArch64_AM::getShiftType(Imm) == AArch64_AM::ASR && ShiftVal == 63);
1423 }
1424
1425 case AArch64::SUBWrx:
1426 case AArch64::SUBXrx:
1427 case AArch64::SUBXrx64:
1428 case AArch64::SUBSWrx:
1429 case AArch64::SUBSXrx:
1430 case AArch64::SUBSXrx64: {
1431 unsigned Imm = MI.getOperand(3).getImm();
1432 switch (AArch64_AM::getArithExtendType(Imm)) {
1433 default:
1434 return false;
1435 case AArch64_AM::UXTB:
1436 case AArch64_AM::UXTH:
1437 case AArch64_AM::UXTW:
1438 case AArch64_AM::UXTX:
1439 return AArch64_AM::getArithShiftValue(Imm) == 0;
1440 }
1441 }
1442
1443 case AArch64::LDRBBroW:
1444 case AArch64::LDRBBroX:
1445 case AArch64::LDRBroW:
1446 case AArch64::LDRBroX:
1447 case AArch64::LDRDroW:
1448 case AArch64::LDRDroX:
1449 case AArch64::LDRHHroW:
1450 case AArch64::LDRHHroX:
1451 case AArch64::LDRHroW:
1452 case AArch64::LDRHroX:
1453 case AArch64::LDRQroW:
1454 case AArch64::LDRQroX:
1455 case AArch64::LDRSBWroW:
1456 case AArch64::LDRSBWroX:
1457 case AArch64::LDRSBXroW:
1458 case AArch64::LDRSBXroX:
1459 case AArch64::LDRSHWroW:
1460 case AArch64::LDRSHWroX:
1461 case AArch64::LDRSHXroW:
1462 case AArch64::LDRSHXroX:
1463 case AArch64::LDRSWroW:
1464 case AArch64::LDRSWroX:
1465 case AArch64::LDRSroW:
1466 case AArch64::LDRSroX:
1467 case AArch64::LDRWroW:
1468 case AArch64::LDRWroX:
1469 case AArch64::LDRXroW:
1470 case AArch64::LDRXroX:
1471 case AArch64::PRFMroW:
1472 case AArch64::PRFMroX:
1473 case AArch64::STRBBroW:
1474 case AArch64::STRBBroX:
1475 case AArch64::STRBroW:
1476 case AArch64::STRBroX:
1477 case AArch64::STRDroW:
1478 case AArch64::STRDroX:
1479 case AArch64::STRHHroW:
1480 case AArch64::STRHHroX:
1481 case AArch64::STRHroW:
1482 case AArch64::STRHroX:
1483 case AArch64::STRQroW:
1484 case AArch64::STRQroX:
1485 case AArch64::STRSroW:
1486 case AArch64::STRSroX:
1487 case AArch64::STRWroW:
1488 case AArch64::STRWroX:
1489 case AArch64::STRXroW:
1490 case AArch64::STRXroX: {
1491 unsigned IsSigned = MI.getOperand(3).getImm();
1492 return !IsSigned;
1493 }
1494 }
1495}
1496
1497bool AArch64InstrInfo::isSEHInstruction(const MachineInstr &MI) {
1498 unsigned Opc = MI.getOpcode();
1499 switch (Opc) {
1500 default:
1501 return false;
1502 case AArch64::SEH_StackAlloc:
1503 case AArch64::SEH_SaveFPLR:
1504 case AArch64::SEH_SaveFPLR_X:
1505 case AArch64::SEH_SaveReg:
1506 case AArch64::SEH_SaveReg_X:
1507 case AArch64::SEH_SaveRegP:
1508 case AArch64::SEH_SaveRegP_X:
1509 case AArch64::SEH_SaveFReg:
1510 case AArch64::SEH_SaveFReg_X:
1511 case AArch64::SEH_SaveFRegP:
1512 case AArch64::SEH_SaveFRegP_X:
1513 case AArch64::SEH_SetFP:
1514 case AArch64::SEH_AddFP:
1515 case AArch64::SEH_Nop:
1516 case AArch64::SEH_PrologEnd:
1517 case AArch64::SEH_EpilogStart:
1518 case AArch64::SEH_EpilogEnd:
1519 case AArch64::SEH_PACSignLR:
1520 case AArch64::SEH_SaveAnyRegI:
1521 case AArch64::SEH_SaveAnyRegIP:
1522 case AArch64::SEH_SaveAnyRegQP:
1523 case AArch64::SEH_SaveAnyRegQPX:
1524 case AArch64::SEH_AllocZ:
1525 case AArch64::SEH_SaveZReg:
1526 case AArch64::SEH_SavePReg:
1527 return true;
1528 }
1529}
1530
1532 Register &SrcReg, Register &DstReg,
1533 unsigned &SubIdx) const {
1534 switch (MI.getOpcode()) {
1535 default:
1536 return false;
1537 case AArch64::SBFMXri: // aka sxtw
1538 case AArch64::UBFMXri: // aka uxtw
1539 // Check for the 32 -> 64 bit extension case, these instructions can do
1540 // much more.
1541 if (MI.getOperand(2).getImm() != 0 || MI.getOperand(3).getImm() != 31)
1542 return false;
1543 // This is a signed or unsigned 32 -> 64 bit extension.
1544 SrcReg = MI.getOperand(1).getReg();
1545 DstReg = MI.getOperand(0).getReg();
1546 SubIdx = AArch64::sub_32;
1547 return true;
1548 }
1549}
1550
1552 const MachineInstr &MIa, const MachineInstr &MIb) const {
1554 const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr;
1555 int64_t OffsetA = 0, OffsetB = 0;
1556 TypeSize WidthA(0, false), WidthB(0, false);
1557 bool OffsetAIsScalable = false, OffsetBIsScalable = false;
1558
1559 assert(MIa.mayLoadOrStore() && "MIa must be a load or store.");
1560 assert(MIb.mayLoadOrStore() && "MIb must be a load or store.");
1561
1564 return false;
1565
1566 // Retrieve the base, offset from the base and width. Width
1567 // is the size of memory that is being loaded/stored (e.g. 1, 2, 4, 8). If
1568 // base are identical, and the offset of a lower memory access +
1569 // the width doesn't overlap the offset of a higher memory access,
1570 // then the memory accesses are different.
1571 // If OffsetAIsScalable and OffsetBIsScalable are both true, they
1572 // are assumed to have the same scale (vscale).
1573 if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, OffsetAIsScalable,
1574 WidthA, TRI) &&
1575 getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, OffsetBIsScalable,
1576 WidthB, TRI)) {
1577 if (BaseOpA->isIdenticalTo(*BaseOpB) &&
1578 OffsetAIsScalable == OffsetBIsScalable) {
1579 int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
1580 int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
1581 TypeSize LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
1582 if (LowWidth.isScalable() == OffsetAIsScalable &&
1583 LowOffset + (int)LowWidth.getKnownMinValue() <= HighOffset)
1584 return true;
1585 }
1586 }
1587 return false;
1588}
1589
1591 const MachineBasicBlock *MBB,
1592 const MachineFunction &MF) const {
1594 return true;
1595
1596 // Do not move an instruction that can be recognized as a branch target.
1597 if (hasBTISemantics(MI))
1598 return true;
1599
1600 switch (MI.getOpcode()) {
1601 case AArch64::HINT:
1602 // CSDB hints are scheduling barriers.
1603 if (MI.getOperand(0).getImm() == 0x14)
1604 return true;
1605 break;
1606 case AArch64::DSB:
1607 case AArch64::ISB:
1608 // DSB and ISB also are scheduling barriers.
1609 return true;
1610 case AArch64::MSRpstatesvcrImm1:
1611 // SMSTART and SMSTOP are also scheduling barriers.
1612 return true;
1613 default:;
1614 }
1615 if (isSEHInstruction(MI))
1616 return true;
1617 auto Next = std::next(MI.getIterator());
1618 return Next != MBB->end() && Next->isCFIInstruction();
1619}
1620
1621/// analyzeCompare - For a comparison instruction, return the source registers
1622/// in SrcReg and SrcReg2, and the value it compares against in CmpValue.
1623/// Return true if the comparison instruction can be analyzed.
1625 Register &SrcReg2, int64_t &CmpMask,
1626 int64_t &CmpValue) const {
1627 // The first operand can be a frame index where we'd normally expect a
1628 // register.
1629 // FIXME: Pass subregisters out of analyzeCompare
1630 assert(MI.getNumOperands() >= 2 && "All AArch64 cmps should have 2 operands");
1631 if (!MI.getOperand(1).isReg() || MI.getOperand(1).getSubReg())
1632 return false;
1633
1634 switch (MI.getOpcode()) {
1635 default:
1636 break;
1637 case AArch64::PTEST_PP:
1638 case AArch64::PTEST_PP_ANY:
1639 case AArch64::PTEST_PP_FIRST:
1640 SrcReg = MI.getOperand(0).getReg();
1641 SrcReg2 = MI.getOperand(1).getReg();
1642 if (MI.getOperand(2).getSubReg())
1643 return false;
1644
1645 // Not sure about the mask and value for now...
1646 CmpMask = ~0;
1647 CmpValue = 0;
1648 return true;
1649 case AArch64::SUBSWrr:
1650 case AArch64::SUBSWrs:
1651 case AArch64::SUBSWrx:
1652 case AArch64::SUBSXrr:
1653 case AArch64::SUBSXrs:
1654 case AArch64::SUBSXrx:
1655 case AArch64::ADDSWrr:
1656 case AArch64::ADDSWrs:
1657 case AArch64::ADDSWrx:
1658 case AArch64::ADDSXrr:
1659 case AArch64::ADDSXrs:
1660 case AArch64::ADDSXrx:
1661 // Replace SUBSWrr with SUBWrr if NZCV is not used.
1662 SrcReg = MI.getOperand(1).getReg();
1663 SrcReg2 = MI.getOperand(2).getReg();
1664
1665 // FIXME: Pass subregisters out of analyzeCompare
1666 if (MI.getOperand(2).getSubReg())
1667 return false;
1668
1669 CmpMask = ~0;
1670 CmpValue = 0;
1671 return true;
1672 case AArch64::SUBSWri:
1673 case AArch64::ADDSWri:
1674 case AArch64::SUBSXri:
1675 case AArch64::ADDSXri:
1676 SrcReg = MI.getOperand(1).getReg();
1677 SrcReg2 = 0;
1678 CmpMask = ~0;
1679 CmpValue = MI.getOperand(2).getImm();
1680 return true;
1681 case AArch64::ANDSWri:
1682 case AArch64::ANDSXri:
1683 // ANDS does not use the same encoding scheme as the others xxxS
1684 // instructions.
1685 SrcReg = MI.getOperand(1).getReg();
1686 SrcReg2 = 0;
1687 CmpMask = ~0;
1689 MI.getOperand(2).getImm(),
1690 MI.getOpcode() == AArch64::ANDSWri ? 32 : 64);
1691 return true;
1692 }
1693
1694 return false;
1695}
1696
1698 MachineBasicBlock *MBB = Instr.getParent();
1699 assert(MBB && "Can't get MachineBasicBlock here");
1700 MachineFunction *MF = MBB->getParent();
1701 assert(MF && "Can't get MachineFunction here");
1704 MachineRegisterInfo *MRI = &MF->getRegInfo();
1705
1706 for (unsigned OpIdx = 0, EndIdx = Instr.getNumOperands(); OpIdx < EndIdx;
1707 ++OpIdx) {
1708 MachineOperand &MO = Instr.getOperand(OpIdx);
1709 const TargetRegisterClass *OpRegCstraints =
1710 Instr.getRegClassConstraint(OpIdx, TII, TRI);
1711
1712 // If there's no constraint, there's nothing to do.
1713 if (!OpRegCstraints)
1714 continue;
1715 // If the operand is a frame index, there's nothing to do here.
1716 // A frame index operand will resolve correctly during PEI.
1717 if (MO.isFI())
1718 continue;
1719
1720 assert(MO.isReg() &&
1721 "Operand has register constraints without being a register!");
1722
1723 Register Reg = MO.getReg();
1724 if (Reg.isPhysical()) {
1725 if (!OpRegCstraints->contains(Reg))
1726 return false;
1727 } else if (!OpRegCstraints->hasSubClassEq(MRI->getRegClass(Reg)) &&
1728 !MRI->constrainRegClass(Reg, OpRegCstraints))
1729 return false;
1730 }
1731
1732 return true;
1733}
1734
1735/// Return the opcode that does not set flags when possible - otherwise
1736/// return the original opcode. The caller is responsible to do the actual
1737/// substitution and legality checking.
1739 // Don't convert all compare instructions, because for some the zero register
1740 // encoding becomes the sp register.
1741 bool MIDefinesZeroReg = false;
1742 if (MI.definesRegister(AArch64::WZR, /*TRI=*/nullptr) ||
1743 MI.definesRegister(AArch64::XZR, /*TRI=*/nullptr))
1744 MIDefinesZeroReg = true;
1745
1746 switch (MI.getOpcode()) {
1747 default:
1748 return MI.getOpcode();
1749 case AArch64::ADDSWrr:
1750 return AArch64::ADDWrr;
1751 case AArch64::ADDSWri:
1752 return MIDefinesZeroReg ? AArch64::ADDSWri : AArch64::ADDWri;
1753 case AArch64::ADDSWrs:
1754 return MIDefinesZeroReg ? AArch64::ADDSWrs : AArch64::ADDWrs;
1755 case AArch64::ADDSWrx:
1756 return AArch64::ADDWrx;
1757 case AArch64::ADDSXrr:
1758 return AArch64::ADDXrr;
1759 case AArch64::ADDSXri:
1760 return MIDefinesZeroReg ? AArch64::ADDSXri : AArch64::ADDXri;
1761 case AArch64::ADDSXrs:
1762 return MIDefinesZeroReg ? AArch64::ADDSXrs : AArch64::ADDXrs;
1763 case AArch64::ADDSXrx:
1764 return AArch64::ADDXrx;
1765 case AArch64::SUBSWrr:
1766 return AArch64::SUBWrr;
1767 case AArch64::SUBSWri:
1768 return MIDefinesZeroReg ? AArch64::SUBSWri : AArch64::SUBWri;
1769 case AArch64::SUBSWrs:
1770 return MIDefinesZeroReg ? AArch64::SUBSWrs : AArch64::SUBWrs;
1771 case AArch64::SUBSWrx:
1772 return AArch64::SUBWrx;
1773 case AArch64::SUBSXrr:
1774 return AArch64::SUBXrr;
1775 case AArch64::SUBSXri:
1776 return MIDefinesZeroReg ? AArch64::SUBSXri : AArch64::SUBXri;
1777 case AArch64::SUBSXrs:
1778 return MIDefinesZeroReg ? AArch64::SUBSXrs : AArch64::SUBXrs;
1779 case AArch64::SUBSXrx:
1780 return AArch64::SUBXrx;
1781 }
1782}
1783
1784enum AccessKind { AK_Write = 0x01, AK_Read = 0x10, AK_All = 0x11 };
1785
1786/// True when condition flags are accessed (either by writing or reading)
1787/// on the instruction trace starting at From and ending at To.
1788///
1789/// Note: If From and To are from different blocks it's assumed CC are accessed
1790/// on the path.
1793 const TargetRegisterInfo *TRI, const AccessKind AccessToCheck = AK_All) {
1794 // Early exit if To is at the beginning of the BB.
1795 if (To == To->getParent()->begin())
1796 return true;
1797
1798 // Check whether the instructions are in the same basic block
1799 // If not, assume the condition flags might get modified somewhere.
1800 if (To->getParent() != From->getParent())
1801 return true;
1802
1803 // From must be above To.
1804 assert(std::any_of(
1805 ++To.getReverse(), To->getParent()->rend(),
1806 [From](MachineInstr &MI) { return MI.getIterator() == From; }));
1807
1808 // We iterate backward starting at \p To until we hit \p From.
1809 for (const MachineInstr &Instr :
1811 if (((AccessToCheck & AK_Write) &&
1812 Instr.modifiesRegister(AArch64::NZCV, TRI)) ||
1813 ((AccessToCheck & AK_Read) && Instr.readsRegister(AArch64::NZCV, TRI)))
1814 return true;
1815 }
1816 return false;
1817}
1818
1819std::optional<unsigned>
1820AArch64InstrInfo::canRemovePTestInstr(MachineInstr *PTest, MachineInstr *Mask,
1821 MachineInstr *Pred,
1822 const MachineRegisterInfo *MRI) const {
1823 unsigned MaskOpcode = Mask->getOpcode();
1824 unsigned PredOpcode = Pred->getOpcode();
1825 bool PredIsPTestLike = isPTestLikeOpcode(PredOpcode);
1826 bool PredIsWhileLike = isWhileOpcode(PredOpcode);
1827
1828 if (PredIsWhileLike) {
1829 // For PTEST(PG, PG), PTEST is redundant when PG is the result of a WHILEcc
1830 // instruction and the condition is "any" since WHILcc does an implicit
1831 // PTEST(ALL, PG) check and PG is always a subset of ALL.
1832 if ((Mask == Pred) && PTest->getOpcode() == AArch64::PTEST_PP_ANY)
1833 return PredOpcode;
1834
1835 // For PTEST(PTRUE_ALL, WHILE), if the element size matches, the PTEST is
1836 // redundant since WHILE performs an implicit PTEST with an all active
1837 // mask.
1838 if (isPTrueOpcode(MaskOpcode) && Mask->getOperand(1).getImm() == 31 &&
1839 getElementSizeForOpcode(MaskOpcode) ==
1840 getElementSizeForOpcode(PredOpcode))
1841 return PredOpcode;
1842
1843 // For PTEST_FIRST(PTRUE_ALL, WHILE), the PTEST_FIRST is redundant since
1844 // WHILEcc performs an implicit PTEST with an all active mask, setting
1845 // the N flag as the PTEST_FIRST would.
1846 if (PTest->getOpcode() == AArch64::PTEST_PP_FIRST &&
1847 isPTrueOpcode(MaskOpcode) && Mask->getOperand(1).getImm() == 31)
1848 return PredOpcode;
1849
1850 return {};
1851 }
1852
1853 if (PredIsPTestLike) {
1854 // For PTEST(PG, PG), PTEST is redundant when PG is the result of an
1855 // instruction that sets the flags as PTEST would and the condition is
1856 // "any" since PG is always a subset of the governing predicate of the
1857 // ptest-like instruction.
1858 if ((Mask == Pred) && PTest->getOpcode() == AArch64::PTEST_PP_ANY)
1859 return PredOpcode;
1860
1861 auto PTestLikeMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
1862
1863 // If the PTEST like instruction's general predicate is not `Mask`, attempt
1864 // to look through a copy and try again. This is because some instructions
1865 // take a predicate whose register class is a subset of its result class.
1866 if (Mask != PTestLikeMask && PTestLikeMask->isFullCopy() &&
1867 PTestLikeMask->getOperand(1).getReg().isVirtual())
1868 PTestLikeMask =
1869 MRI->getUniqueVRegDef(PTestLikeMask->getOperand(1).getReg());
1870
1871 // For PTEST(PTRUE_ALL, PTEST_LIKE), the PTEST is redundant if the
1872 // the element size matches and either the PTEST_LIKE instruction uses
1873 // the same all active mask or the condition is "any".
1874 if (isPTrueOpcode(MaskOpcode) && Mask->getOperand(1).getImm() == 31 &&
1875 getElementSizeForOpcode(MaskOpcode) ==
1876 getElementSizeForOpcode(PredOpcode)) {
1877 if (Mask == PTestLikeMask || PTest->getOpcode() == AArch64::PTEST_PP_ANY)
1878 return PredOpcode;
1879 }
1880
1881 // For PTEST(PG, PTEST_LIKE(PG, ...)), the PTEST is redundant since the
1882 // flags are set based on the same mask 'PG', but PTEST_LIKE must operate
1883 // on 8-bit predicates like the PTEST. Otherwise, for instructions like
1884 // compare that also support 16/32/64-bit predicates, the implicit PTEST
1885 // performed by the compare could consider fewer lanes for these element
1886 // sizes.
1887 //
1888 // For example, consider
1889 //
1890 // ptrue p0.b ; P0=1111-1111-1111-1111
1891 // index z0.s, #0, #1 ; Z0=<0,1,2,3>
1892 // index z1.s, #1, #1 ; Z1=<1,2,3,4>
1893 // cmphi p1.s, p0/z, z1.s, z0.s ; P1=0001-0001-0001-0001
1894 // ; ^ last active
1895 // ptest p0, p1.b ; P1=0001-0001-0001-0001
1896 // ; ^ last active
1897 //
1898 // where the compare generates a canonical all active 32-bit predicate
1899 // (equivalent to 'ptrue p1.s, all'). The implicit PTEST sets the last
1900 // active flag, whereas the PTEST instruction with the same mask doesn't.
1901 // For PTEST_ANY this doesn't apply as the flags in this case would be
1902 // identical regardless of element size.
1903 uint64_t PredElementSize = getElementSizeForOpcode(PredOpcode);
1904 if (Mask == PTestLikeMask && (PredElementSize == AArch64::ElementSizeB ||
1905 PTest->getOpcode() == AArch64::PTEST_PP_ANY))
1906 return PredOpcode;
1907
1908 return {};
1909 }
1910
1911 // If OP in PTEST(PG, OP(PG, ...)) has a flag-setting variant change the
1912 // opcode so the PTEST becomes redundant.
1913 switch (PredOpcode) {
1914 case AArch64::AND_PPzPP:
1915 case AArch64::BIC_PPzPP:
1916 case AArch64::EOR_PPzPP:
1917 case AArch64::NAND_PPzPP:
1918 case AArch64::NOR_PPzPP:
1919 case AArch64::ORN_PPzPP:
1920 case AArch64::ORR_PPzPP:
1921 case AArch64::BRKA_PPzP:
1922 case AArch64::BRKPA_PPzPP:
1923 case AArch64::BRKB_PPzP:
1924 case AArch64::BRKPB_PPzPP:
1925 case AArch64::RDFFR_PPz: {
1926 // Check to see if our mask is the same. If not the resulting flag bits
1927 // may be different and we can't remove the ptest.
1928 auto *PredMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
1929 if (Mask != PredMask)
1930 return {};
1931 break;
1932 }
1933 case AArch64::BRKN_PPzP: {
1934 // BRKN uses an all active implicit mask to set flags unlike the other
1935 // flag-setting instructions.
1936 // PTEST(PTRUE_B(31), BRKN(PG, A, B)) -> BRKNS(PG, A, B).
1937 if ((MaskOpcode != AArch64::PTRUE_B) ||
1938 (Mask->getOperand(1).getImm() != 31))
1939 return {};
1940 break;
1941 }
1942 case AArch64::PTRUE_B:
1943 // PTEST(OP=PTRUE_B(A), OP) -> PTRUES_B(A)
1944 break;
1945 default:
1946 // Bail out if we don't recognize the input
1947 return {};
1948 }
1949
1950 return convertToFlagSettingOpc(PredOpcode);
1951}
1952
1953/// optimizePTestInstr - Attempt to remove a ptest of a predicate-generating
1954/// operation which could set the flags in an identical manner
1955bool AArch64InstrInfo::optimizePTestInstr(
1956 MachineInstr *PTest, unsigned MaskReg, unsigned PredReg,
1957 const MachineRegisterInfo *MRI) const {
1958 auto *Mask = MRI->getUniqueVRegDef(MaskReg);
1959 auto *Pred = MRI->getUniqueVRegDef(PredReg);
1960
1961 if (Pred->isCopy() && PTest->getOpcode() == AArch64::PTEST_PP_FIRST) {
1962 // Instructions which return a multi-vector (e.g. WHILECC_x2) require copies
1963 // before the branch to extract each subregister.
1964 auto Op = Pred->getOperand(1);
1965 if (Op.isReg() && Op.getReg().isVirtual() &&
1966 Op.getSubReg() == AArch64::psub0)
1967 Pred = MRI->getUniqueVRegDef(Op.getReg());
1968 }
1969
1970 unsigned PredOpcode = Pred->getOpcode();
1971 auto NewOp = canRemovePTestInstr(PTest, Mask, Pred, MRI);
1972 if (!NewOp)
1973 return false;
1974
1975 const TargetRegisterInfo *TRI = &getRegisterInfo();
1976
1977 // If another instruction between Pred and PTest accesses flags, don't remove
1978 // the ptest or update the earlier instruction to modify them.
1979 if (areCFlagsAccessedBetweenInstrs(Pred, PTest, TRI))
1980 return false;
1981
1982 // If we pass all the checks, it's safe to remove the PTEST and use the flags
1983 // as they are prior to PTEST. Sometimes this requires the tested PTEST
1984 // operand to be replaced with an equivalent instruction that also sets the
1985 // flags.
1986 PTest->eraseFromParent();
1987 if (*NewOp != PredOpcode) {
1988 Pred->setDesc(get(*NewOp));
1989 bool succeeded = UpdateOperandRegClass(*Pred);
1990 (void)succeeded;
1991 assert(succeeded && "Operands have incompatible register classes!");
1992 Pred->addRegisterDefined(AArch64::NZCV, TRI);
1993 }
1994
1995 // Ensure that the flags def is live.
1996 if (Pred->registerDefIsDead(AArch64::NZCV, TRI)) {
1997 unsigned i = 0, e = Pred->getNumOperands();
1998 for (; i != e; ++i) {
1999 MachineOperand &MO = Pred->getOperand(i);
2000 if (MO.isReg() && MO.isDef() && MO.getReg() == AArch64::NZCV) {
2001 MO.setIsDead(false);
2002 break;
2003 }
2004 }
2005 }
2006 return true;
2007}
2008
2009/// Try to optimize a compare instruction. A compare instruction is an
2010/// instruction which produces AArch64::NZCV. It can be truly compare
2011/// instruction
2012/// when there are no uses of its destination register.
2013///
2014/// The following steps are tried in order:
2015/// 1. Convert CmpInstr into an unconditional version.
2016/// 2. Remove CmpInstr if above there is an instruction producing a needed
2017/// condition code or an instruction which can be converted into such an
2018/// instruction.
2019/// Only comparison with zero is supported.
2021 MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2, int64_t CmpMask,
2022 int64_t CmpValue, const MachineRegisterInfo *MRI) const {
2023 assert(CmpInstr.getParent());
2024 assert(MRI);
2025
2026 // Replace SUBSWrr with SUBWrr if NZCV is not used.
2027 int DeadNZCVIdx =
2028 CmpInstr.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true);
2029 if (DeadNZCVIdx != -1) {
2030 if (CmpInstr.definesRegister(AArch64::WZR, /*TRI=*/nullptr) ||
2031 CmpInstr.definesRegister(AArch64::XZR, /*TRI=*/nullptr)) {
2032 CmpInstr.eraseFromParent();
2033 return true;
2034 }
2035 unsigned Opc = CmpInstr.getOpcode();
2036 unsigned NewOpc = convertToNonFlagSettingOpc(CmpInstr);
2037 if (NewOpc == Opc)
2038 return false;
2039 const MCInstrDesc &MCID = get(NewOpc);
2040 CmpInstr.setDesc(MCID);
2041 CmpInstr.removeOperand(DeadNZCVIdx);
2042 bool succeeded = UpdateOperandRegClass(CmpInstr);
2043 (void)succeeded;
2044 assert(succeeded && "Some operands reg class are incompatible!");
2045 return true;
2046 }
2047
2048 if (CmpInstr.getOpcode() == AArch64::PTEST_PP ||
2049 CmpInstr.getOpcode() == AArch64::PTEST_PP_ANY ||
2050 CmpInstr.getOpcode() == AArch64::PTEST_PP_FIRST)
2051 return optimizePTestInstr(&CmpInstr, SrcReg, SrcReg2, MRI);
2052
2053 if (SrcReg2 != 0)
2054 return false;
2055
2056 // CmpInstr is a Compare instruction if destination register is not used.
2057 if (!MRI->use_nodbg_empty(CmpInstr.getOperand(0).getReg()))
2058 return false;
2059
2060 if (CmpValue == 0 && substituteCmpToZero(CmpInstr, SrcReg, *MRI))
2061 return true;
2062 return (CmpValue == 0 || CmpValue == 1) &&
2063 removeCmpToZeroOrOne(CmpInstr, SrcReg, CmpValue, *MRI);
2064}
2065
2066/// Get opcode of S version of Instr.
2067/// If Instr is S version its opcode is returned.
2068/// AArch64::INSTRUCTION_LIST_END is returned if Instr does not have S version
2069/// or we are not interested in it.
2070static unsigned sForm(MachineInstr &Instr) {
2071 switch (Instr.getOpcode()) {
2072 default:
2073 return AArch64::INSTRUCTION_LIST_END;
2074
2075 case AArch64::ADDSWrr:
2076 case AArch64::ADDSWri:
2077 case AArch64::ADDSXrr:
2078 case AArch64::ADDSXri:
2079 case AArch64::ADDSWrx:
2080 case AArch64::ADDSXrx:
2081 case AArch64::ADDSWrs:
2082 case AArch64::ADDSXrs:
2083 case AArch64::SUBSWrr:
2084 case AArch64::SUBSWri:
2085 case AArch64::SUBSWrx:
2086 case AArch64::SUBSWrs:
2087 case AArch64::SUBSXrr:
2088 case AArch64::SUBSXri:
2089 case AArch64::SUBSXrx:
2090 case AArch64::SUBSXrs:
2091 case AArch64::ANDSWri:
2092 case AArch64::ANDSWrr:
2093 case AArch64::ANDSWrs:
2094 case AArch64::ANDSXri:
2095 case AArch64::ANDSXrr:
2096 case AArch64::ANDSXrs:
2097 case AArch64::BICSWrr:
2098 case AArch64::BICSXrr:
2099 case AArch64::BICSWrs:
2100 case AArch64::BICSXrs:
2101 case AArch64::ADCSWr:
2102 case AArch64::ADCSXr:
2103 case AArch64::SBCSWr:
2104 case AArch64::SBCSXr:
2105 return Instr.getOpcode();
2106
2107 case AArch64::ADDWrr:
2108 return AArch64::ADDSWrr;
2109 case AArch64::ADDWri:
2110 return AArch64::ADDSWri;
2111 case AArch64::ADDXrr:
2112 return AArch64::ADDSXrr;
2113 case AArch64::ADDXri:
2114 return AArch64::ADDSXri;
2115 case AArch64::ADDWrx:
2116 return AArch64::ADDSWrx;
2117 case AArch64::ADDXrx:
2118 return AArch64::ADDSXrx;
2119 case AArch64::ADDWrs:
2120 return AArch64::ADDSWrs;
2121 case AArch64::ADDXrs:
2122 return AArch64::ADDSXrs;
2123 case AArch64::ADCWr:
2124 return AArch64::ADCSWr;
2125 case AArch64::ADCXr:
2126 return AArch64::ADCSXr;
2127 case AArch64::SUBWrr:
2128 return AArch64::SUBSWrr;
2129 case AArch64::SUBWri:
2130 return AArch64::SUBSWri;
2131 case AArch64::SUBXrr:
2132 return AArch64::SUBSXrr;
2133 case AArch64::SUBXri:
2134 return AArch64::SUBSXri;
2135 case AArch64::SUBWrx:
2136 return AArch64::SUBSWrx;
2137 case AArch64::SUBXrx:
2138 return AArch64::SUBSXrx;
2139 case AArch64::SUBWrs:
2140 return AArch64::SUBSWrs;
2141 case AArch64::SUBXrs:
2142 return AArch64::SUBSXrs;
2143 case AArch64::SBCWr:
2144 return AArch64::SBCSWr;
2145 case AArch64::SBCXr:
2146 return AArch64::SBCSXr;
2147 case AArch64::ANDWri:
2148 return AArch64::ANDSWri;
2149 case AArch64::ANDXri:
2150 return AArch64::ANDSXri;
2151 case AArch64::ANDWrr:
2152 return AArch64::ANDSWrr;
2153 case AArch64::ANDWrs:
2154 return AArch64::ANDSWrs;
2155 case AArch64::ANDXrr:
2156 return AArch64::ANDSXrr;
2157 case AArch64::ANDXrs:
2158 return AArch64::ANDSXrs;
2159 case AArch64::BICWrr:
2160 return AArch64::BICSWrr;
2161 case AArch64::BICXrr:
2162 return AArch64::BICSXrr;
2163 case AArch64::BICWrs:
2164 return AArch64::BICSWrs;
2165 case AArch64::BICXrs:
2166 return AArch64::BICSXrs;
2167 }
2168}
2169
2170/// Check if AArch64::NZCV should be alive in successors of MBB.
2172 for (auto *BB : MBB->successors())
2173 if (BB->isLiveIn(AArch64::NZCV))
2174 return true;
2175 return false;
2176}
2177
2178/// \returns The condition code operand index for \p Instr if it is a branch
2179/// or select and -1 otherwise.
2180int AArch64InstrInfo::findCondCodeUseOperandIdxForBranchOrSelect(
2181 const MachineInstr &Instr) {
2182 switch (Instr.getOpcode()) {
2183 default:
2184 return -1;
2185
2186 case AArch64::Bcc: {
2187 int Idx = Instr.findRegisterUseOperandIdx(AArch64::NZCV, /*TRI=*/nullptr);
2188 assert(Idx >= 2);
2189 return Idx - 2;
2190 }
2191
2192 case AArch64::CSINVWr:
2193 case AArch64::CSINVXr:
2194 case AArch64::CSINCWr:
2195 case AArch64::CSINCXr:
2196 case AArch64::CSELWr:
2197 case AArch64::CSELXr:
2198 case AArch64::CSNEGWr:
2199 case AArch64::CSNEGXr:
2200 case AArch64::FCSELSrrr:
2201 case AArch64::FCSELDrrr: {
2202 int Idx = Instr.findRegisterUseOperandIdx(AArch64::NZCV, /*TRI=*/nullptr);
2203 assert(Idx >= 1);
2204 return Idx - 1;
2205 }
2206 }
2207}
2208
2209/// Find a condition code used by the instruction.
2210/// Returns AArch64CC::Invalid if either the instruction does not use condition
2211/// codes or we don't optimize CmpInstr in the presence of such instructions.
2213 int CCIdx =
2214 AArch64InstrInfo::findCondCodeUseOperandIdxForBranchOrSelect(Instr);
2215 return CCIdx >= 0 ? static_cast<AArch64CC::CondCode>(
2216 Instr.getOperand(CCIdx).getImm())
2218}
2219
2222 UsedNZCV UsedFlags;
2223 switch (CC) {
2224 default:
2225 break;
2226
2227 case AArch64CC::EQ: // Z set
2228 case AArch64CC::NE: // Z clear
2229 UsedFlags.Z = true;
2230 break;
2231
2232 case AArch64CC::HI: // Z clear and C set
2233 case AArch64CC::LS: // Z set or C clear
2234 UsedFlags.Z = true;
2235 [[fallthrough]];
2236 case AArch64CC::HS: // C set
2237 case AArch64CC::LO: // C clear
2238 UsedFlags.C = true;
2239 break;
2240
2241 case AArch64CC::MI: // N set
2242 case AArch64CC::PL: // N clear
2243 UsedFlags.N = true;
2244 break;
2245
2246 case AArch64CC::VS: // V set
2247 case AArch64CC::VC: // V clear
2248 UsedFlags.V = true;
2249 break;
2250
2251 case AArch64CC::GT: // Z clear, N and V the same
2252 case AArch64CC::LE: // Z set, N and V differ
2253 UsedFlags.Z = true;
2254 [[fallthrough]];
2255 case AArch64CC::GE: // N and V the same
2256 case AArch64CC::LT: // N and V differ
2257 UsedFlags.N = true;
2258 UsedFlags.V = true;
2259 break;
2260 }
2261 return UsedFlags;
2262}
2263
2264/// \returns Conditions flags used after \p CmpInstr in its MachineBB if NZCV
2265/// flags are not alive in successors of the same \p CmpInstr and \p MI parent.
2266/// \returns std::nullopt otherwise.
2267///
2268/// Collect instructions using that flags in \p CCUseInstrs if provided.
2269std::optional<UsedNZCV>
2271 const TargetRegisterInfo &TRI,
2272 SmallVectorImpl<MachineInstr *> *CCUseInstrs) {
2273 MachineBasicBlock *CmpParent = CmpInstr.getParent();
2274 if (MI.getParent() != CmpParent)
2275 return std::nullopt;
2276
2277 if (areCFlagsAliveInSuccessors(CmpParent))
2278 return std::nullopt;
2279
2280 UsedNZCV NZCVUsedAfterCmp;
2282 std::next(CmpInstr.getIterator()), CmpParent->instr_end())) {
2283 if (Instr.readsRegister(AArch64::NZCV, &TRI)) {
2285 if (CC == AArch64CC::Invalid) // Unsupported conditional instruction
2286 return std::nullopt;
2287 NZCVUsedAfterCmp |= getUsedNZCV(CC);
2288 if (CCUseInstrs)
2289 CCUseInstrs->push_back(&Instr);
2290 }
2291 if (Instr.modifiesRegister(AArch64::NZCV, &TRI))
2292 break;
2293 }
2294 return NZCVUsedAfterCmp;
2295}
2296
2297static bool isADDSRegImm(unsigned Opcode) {
2298 return Opcode == AArch64::ADDSWri || Opcode == AArch64::ADDSXri;
2299}
2300
2301static bool isSUBSRegImm(unsigned Opcode) {
2302 return Opcode == AArch64::SUBSWri || Opcode == AArch64::SUBSXri;
2303}
2304
2306 unsigned Opc = sForm(MI);
2307 switch (Opc) {
2308 case AArch64::ANDSWri:
2309 case AArch64::ANDSWrr:
2310 case AArch64::ANDSWrs:
2311 case AArch64::ANDSXri:
2312 case AArch64::ANDSXrr:
2313 case AArch64::ANDSXrs:
2314 case AArch64::BICSWrr:
2315 case AArch64::BICSXrr:
2316 case AArch64::BICSWrs:
2317 case AArch64::BICSXrs:
2318 return true;
2319 default:
2320 return false;
2321 }
2322}
2323
2324/// Check if CmpInstr can be substituted by MI.
2325///
2326/// CmpInstr can be substituted:
2327/// - CmpInstr is either 'ADDS %vreg, 0' or 'SUBS %vreg, 0'
2328/// - and, MI and CmpInstr are from the same MachineBB
2329/// - and, condition flags are not alive in successors of the CmpInstr parent
2330/// - and, if MI opcode is the S form there must be no defs of flags between
2331/// MI and CmpInstr
2332/// or if MI opcode is not the S form there must be neither defs of flags
2333/// nor uses of flags between MI and CmpInstr.
2334/// - and, C is not used after CmpInstr; CmpInstr's C is from adds/subs #0 on
2335/// SrcReg and can differ from MI (e.g. carry out of ADCS/SBCS).
2336/// - and, V is not used after CmpInstr unless MI is AND/BIC (V cleared) or MI
2337/// has NoSWrap (overflow is poison and the fold is still safe).
2339 const TargetRegisterInfo &TRI) {
2340 // MI is an opcode sForm maps (add/sub/adc/sbc/and/bic and their S forms).
2341 assert(sForm(MI) != AArch64::INSTRUCTION_LIST_END);
2342
2343 const unsigned CmpOpcode = CmpInstr.getOpcode();
2344 if (!isADDSRegImm(CmpOpcode) && !isSUBSRegImm(CmpOpcode))
2345 return false;
2346
2347 assert((CmpInstr.getOperand(2).isImm() &&
2348 CmpInstr.getOperand(2).getImm() == 0) &&
2349 "Caller guarantees that CmpInstr compares with constant 0");
2350
2351 std::optional<UsedNZCV> NZVCUsed = examineCFlagsUse(MI, CmpInstr, TRI);
2352 if (!NZVCUsed || NZVCUsed->C)
2353 return false;
2354
2355 // CmpInstr is ADDS/SUBS with immediate 0 on SrcReg (compare SrcReg to zero).
2356 // After the fold, users see NZCV from MI (or its S form), not from CmpInstr.
2357 // N/Z match CmpInstr for the value in SrcReg; C/V need not match in general
2358 // (e.g. ADCS vs adds #0), so we require C unused after CmpInstr and gate V
2359 // as below. NoSWrap makes signed overflow poison; AND/BIC clear V.
2360 if (NZVCUsed->V && !MI.getFlag(MachineInstr::NoSWrap) && !isANDOpcode(MI))
2361 return false;
2362
2363 AccessKind AccessToCheck = AK_Write;
2364 if (sForm(MI) != MI.getOpcode())
2365 AccessToCheck = AK_All;
2366 return !areCFlagsAccessedBetweenInstrs(&MI, &CmpInstr, &TRI, AccessToCheck);
2367}
2368
2369/// Substitute an instruction comparing to zero with another instruction
2370/// which produces needed condition flags.
2371///
2372/// Return true on success.
2373bool AArch64InstrInfo::substituteCmpToZero(
2374 MachineInstr &CmpInstr, unsigned SrcReg,
2375 const MachineRegisterInfo &MRI) const {
2376 // Get the unique definition of SrcReg.
2377 MachineInstr *MI = MRI.getUniqueVRegDef(SrcReg);
2378 if (!MI)
2379 return false;
2380
2381 const TargetRegisterInfo &TRI = getRegisterInfo();
2382
2383 unsigned NewOpc = sForm(*MI);
2384 if (NewOpc == AArch64::INSTRUCTION_LIST_END)
2385 return false;
2386
2387 if (!canInstrSubstituteCmpInstr(*MI, CmpInstr, TRI))
2388 return false;
2389
2390 // Update the instruction to set NZCV.
2391 MI->setDesc(get(NewOpc));
2392 CmpInstr.eraseFromParent();
2394 (void)succeeded;
2395 assert(succeeded && "Some operands reg class are incompatible!");
2396 MI->addRegisterDefined(AArch64::NZCV, &TRI);
2397 return true;
2398}
2399
2400/// \returns True if \p CmpInstr can be removed.
2401///
2402/// \p IsInvertCC is true if, after removing \p CmpInstr, condition
2403/// codes used in \p CCUseInstrs must be inverted.
2405 int CmpValue, const TargetRegisterInfo &TRI,
2407 bool &IsInvertCC) {
2408 assert((CmpValue == 0 || CmpValue == 1) &&
2409 "Only comparisons to 0 or 1 considered for removal!");
2410
2411 // MI is 'CSINCWr %vreg, wzr, wzr, <cc>' or 'CSINCXr %vreg, xzr, xzr, <cc>'
2412 unsigned MIOpc = MI.getOpcode();
2413 if (MIOpc == AArch64::CSINCWr) {
2414 if (MI.getOperand(1).getReg() != AArch64::WZR ||
2415 MI.getOperand(2).getReg() != AArch64::WZR)
2416 return false;
2417 } else if (MIOpc == AArch64::CSINCXr) {
2418 if (MI.getOperand(1).getReg() != AArch64::XZR ||
2419 MI.getOperand(2).getReg() != AArch64::XZR)
2420 return false;
2421 } else {
2422 return false;
2423 }
2425 if (MICC == AArch64CC::Invalid)
2426 return false;
2427
2428 // NZCV needs to be defined
2429 if (MI.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true) != -1)
2430 return false;
2431
2432 // CmpInstr is 'ADDS %vreg, 0' or 'SUBS %vreg, 0' or 'SUBS %vreg, 1'
2433 const unsigned CmpOpcode = CmpInstr.getOpcode();
2434 bool IsSubsRegImm = isSUBSRegImm(CmpOpcode);
2435 if (CmpValue && !IsSubsRegImm)
2436 return false;
2437 if (!CmpValue && !IsSubsRegImm && !isADDSRegImm(CmpOpcode))
2438 return false;
2439
2440 // MI conditions allowed: eq, ne, mi, pl
2441 UsedNZCV MIUsedNZCV = getUsedNZCV(MICC);
2442 if (MIUsedNZCV.C || MIUsedNZCV.V)
2443 return false;
2444
2445 std::optional<UsedNZCV> NZCVUsedAfterCmp =
2446 examineCFlagsUse(MI, CmpInstr, TRI, &CCUseInstrs);
2447 // Condition flags are not used in CmpInstr basic block successors and only
2448 // Z or N flags allowed to be used after CmpInstr within its basic block
2449 if (!NZCVUsedAfterCmp || NZCVUsedAfterCmp->C || NZCVUsedAfterCmp->V)
2450 return false;
2451 // Z or N flag used after CmpInstr must correspond to the flag used in MI
2452 if ((MIUsedNZCV.Z && NZCVUsedAfterCmp->N) ||
2453 (MIUsedNZCV.N && NZCVUsedAfterCmp->Z))
2454 return false;
2455 // If CmpInstr is comparison to zero MI conditions are limited to eq, ne
2456 if (MIUsedNZCV.N && !CmpValue)
2457 return false;
2458
2459 // There must be no defs of flags between MI and CmpInstr
2460 if (areCFlagsAccessedBetweenInstrs(&MI, &CmpInstr, &TRI, AK_Write))
2461 return false;
2462
2463 // Condition code is inverted in the following cases:
2464 // 1. MI condition is ne; CmpInstr is 'ADDS %vreg, 0' or 'SUBS %vreg, 0'
2465 // 2. MI condition is eq, pl; CmpInstr is 'SUBS %vreg, 1'
2466 IsInvertCC = (CmpValue && (MICC == AArch64CC::EQ || MICC == AArch64CC::PL)) ||
2467 (!CmpValue && MICC == AArch64CC::NE);
2468 return true;
2469}
2470
2471/// Remove comparison in csinc-cmp sequence
2472///
2473/// Examples:
2474/// 1. \code
2475/// csinc w9, wzr, wzr, ne
2476/// cmp w9, #0
2477/// b.eq
2478/// \endcode
2479/// to
2480/// \code
2481/// csinc w9, wzr, wzr, ne
2482/// b.ne
2483/// \endcode
2484///
2485/// 2. \code
2486/// csinc x2, xzr, xzr, mi
2487/// cmp x2, #1
2488/// b.pl
2489/// \endcode
2490/// to
2491/// \code
2492/// csinc x2, xzr, xzr, mi
2493/// b.pl
2494/// \endcode
2495///
2496/// \param CmpInstr comparison instruction
2497/// \return True when comparison removed
2498bool AArch64InstrInfo::removeCmpToZeroOrOne(
2499 MachineInstr &CmpInstr, unsigned SrcReg, int CmpValue,
2500 const MachineRegisterInfo &MRI) const {
2501 MachineInstr *MI = MRI.getUniqueVRegDef(SrcReg);
2502 if (!MI)
2503 return false;
2504 const TargetRegisterInfo &TRI = getRegisterInfo();
2505 SmallVector<MachineInstr *, 4> CCUseInstrs;
2506 bool IsInvertCC = false;
2507 if (!canCmpInstrBeRemoved(*MI, CmpInstr, CmpValue, TRI, CCUseInstrs,
2508 IsInvertCC))
2509 return false;
2510 // Make transformation
2511 CmpInstr.eraseFromParent();
2512 if (IsInvertCC) {
2513 // Invert condition codes in CmpInstr CC users
2514 for (MachineInstr *CCUseInstr : CCUseInstrs) {
2515 int Idx = findCondCodeUseOperandIdxForBranchOrSelect(*CCUseInstr);
2516 assert(Idx >= 0 && "Unexpected instruction using CC.");
2517 MachineOperand &CCOperand = CCUseInstr->getOperand(Idx);
2519 static_cast<AArch64CC::CondCode>(CCOperand.getImm()));
2520 CCOperand.setImm(CCUse);
2521 }
2522 }
2523 return true;
2524}
2525
2526bool AArch64InstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
2527 if (MI.getOpcode() != TargetOpcode::LOAD_STACK_GUARD &&
2528 MI.getOpcode() != AArch64::CATCHRET &&
2529 MI.getOpcode() != AArch64::STACK_GUARD_UNMIX)
2530 return false;
2531
2532 MachineBasicBlock &MBB = *MI.getParent();
2533 auto &Subtarget = MBB.getParent()->getSubtarget<AArch64Subtarget>();
2534 auto TRI = Subtarget.getRegisterInfo();
2535 DebugLoc DL = MI.getDebugLoc();
2536
2537 if (MI.getOpcode() == AArch64::STACK_GUARD_UNMIX) {
2538 // Expand STACK_GUARD_UNMIX to: sub Rd, fp, Rs
2539 // This computes FP - stored_mixed_value to unmix the cookie
2540 Register DstReg = MI.getOperand(0).getReg();
2541 Register SrcReg = MI.getOperand(1).getReg();
2542
2543 BuildMI(MBB, MI, DL, get(AArch64::SUBXrr), DstReg)
2544 .addReg(AArch64::FP)
2545 .addReg(SrcReg);
2546
2547 MBB.erase(MI);
2548 return true;
2549 }
2550
2551 if (MI.getOpcode() == AArch64::CATCHRET) {
2552 // Skip to the first instruction before the epilog.
2553 const TargetInstrInfo *TII =
2555 MachineBasicBlock *TargetMBB = MI.getOperand(0).getMBB();
2557 MachineBasicBlock::iterator FirstEpilogSEH = std::prev(MBBI);
2558 while (FirstEpilogSEH->getFlag(MachineInstr::FrameDestroy) &&
2559 FirstEpilogSEH != MBB.begin())
2560 FirstEpilogSEH = std::prev(FirstEpilogSEH);
2561 if (FirstEpilogSEH != MBB.begin())
2562 FirstEpilogSEH = std::next(FirstEpilogSEH);
2563 BuildMI(MBB, FirstEpilogSEH, DL, TII->get(AArch64::ADRP))
2564 .addReg(AArch64::X0, RegState::Define)
2565 .addMBB(TargetMBB);
2566 BuildMI(MBB, FirstEpilogSEH, DL, TII->get(AArch64::ADDXri))
2567 .addReg(AArch64::X0, RegState::Define)
2568 .addReg(AArch64::X0)
2569 .addMBB(TargetMBB)
2570 .addImm(0);
2571 TargetMBB->setMachineBlockAddressTaken();
2572 return true;
2573 }
2574
2575 Register Reg = MI.getOperand(0).getReg();
2577 if (M.getStackProtectorGuard() == "sysreg") {
2578 const AArch64SysReg::SysReg *SrcReg =
2579 AArch64SysReg::lookupSysRegByName(M.getStackProtectorGuardReg());
2580 if (!SrcReg)
2581 report_fatal_error("Unknown SysReg for Stack Protector Guard Register");
2582
2583 // mrs xN, sysreg
2584 BuildMI(MBB, MI, DL, get(AArch64::MRS))
2586 .addImm(SrcReg->Encoding);
2587 int Offset = M.getStackProtectorGuardOffset();
2588 if (Offset >= 0 && Offset <= 32760 && Offset % 8 == 0) {
2589 // ldr xN, [xN, #offset]
2590 BuildMI(MBB, MI, DL, get(AArch64::LDRXui))
2591 .addDef(Reg)
2593 .addImm(Offset / 8);
2594 } else if (Offset >= -256 && Offset <= 255) {
2595 // ldur xN, [xN, #offset]
2596 BuildMI(MBB, MI, DL, get(AArch64::LDURXi))
2597 .addDef(Reg)
2599 .addImm(Offset);
2600 } else if (Offset >= -4095 && Offset <= 4095) {
2601 if (Offset > 0) {
2602 // add xN, xN, #offset
2603 BuildMI(MBB, MI, DL, get(AArch64::ADDXri))
2604 .addDef(Reg)
2606 .addImm(Offset)
2607 .addImm(0);
2608 } else {
2609 // sub xN, xN, #offset
2610 BuildMI(MBB, MI, DL, get(AArch64::SUBXri))
2611 .addDef(Reg)
2613 .addImm(-Offset)
2614 .addImm(0);
2615 }
2616 // ldr xN, [xN]
2617 BuildMI(MBB, MI, DL, get(AArch64::LDRXui))
2618 .addDef(Reg)
2620 .addImm(0);
2621 } else {
2622 // Cases that are larger than +/- 4095 and not a multiple of 8, or larger
2623 // than 23760.
2624 // It might be nice to use AArch64::MOVi32imm here, which would get
2625 // expanded in PreSched2 after PostRA, but our lone scratch Reg already
2626 // contains the MRS result. findScratchNonCalleeSaveRegister() in
2627 // AArch64FrameLowering might help us find such a scratch register
2628 // though. If we failed to find a scratch register, we could emit a
2629 // stream of add instructions to build up the immediate. Or, we could try
2630 // to insert a AArch64::MOVi32imm before register allocation so that we
2631 // didn't need to scavenge for a scratch register.
2632 report_fatal_error("Unable to encode Stack Protector Guard Offset");
2633 }
2634 MBB.erase(MI);
2635 return true;
2636 }
2637
2638 const GlobalValue *GV =
2639 cast<GlobalValue>((*MI.memoperands_begin())->getValue());
2640 const TargetMachine &TM = MBB.getParent()->getTarget();
2641 unsigned OpFlags = Subtarget.ClassifyGlobalReference(GV, TM);
2642 const unsigned char MO_NC = AArch64II::MO_NC;
2643
2644 unsigned GuardWidth = M.getStackProtectorGuardValueWidth().value_or(
2645 Subtarget.isTargetILP32() ? 4 : 8);
2646 if (GuardWidth != 4 && GuardWidth != 8)
2647 report_fatal_error("Unsupported stack protector value width");
2648 if ((OpFlags & AArch64II::MO_GOT) != 0) {
2649 BuildMI(MBB, MI, DL, get(AArch64::LOADgot), Reg)
2650 .addGlobalAddress(GV, 0, OpFlags);
2651 if (GuardWidth == 4) {
2652 unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
2653 BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
2654 .addDef(Reg32, RegState::Dead)
2656 .addImm(0)
2657 .addMemOperand(*MI.memoperands_begin())
2659 } else {
2660 BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
2662 .addImm(0)
2663 .addMemOperand(*MI.memoperands_begin());
2664 }
2665 } else if (TM.getCodeModel() == CodeModel::Large) {
2666 BuildMI(MBB, MI, DL, get(AArch64::MOVZXi), Reg)
2667 .addGlobalAddress(GV, 0, AArch64II::MO_G0 | MO_NC)
2668 .addImm(0);
2669 BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
2671 .addGlobalAddress(GV, 0, AArch64II::MO_G1 | MO_NC)
2672 .addImm(16);
2673 BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
2675 .addGlobalAddress(GV, 0, AArch64II::MO_G2 | MO_NC)
2676 .addImm(32);
2677 BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
2680 .addImm(48);
2681 if (GuardWidth == 4) {
2682 unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
2683 BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
2684 .addDef(Reg32, RegState::Dead)
2686 .addImm(0)
2687 .addMemOperand(*MI.memoperands_begin())
2689 } else {
2690 BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
2692 .addImm(0)
2693 .addMemOperand(*MI.memoperands_begin());
2694 }
2695 } else {
2696 BuildMI(MBB, MI, DL, get(AArch64::ADRP), Reg)
2697 .addGlobalAddress(GV, 0, OpFlags | AArch64II::MO_PAGE);
2698 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | MO_NC;
2699 if (GuardWidth == 4) {
2700 unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
2701 BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
2702 .addDef(Reg32, RegState::Dead)
2704 .addGlobalAddress(GV, 0, LoFlags)
2705 .addMemOperand(*MI.memoperands_begin())
2707 } else {
2708 BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
2710 .addGlobalAddress(GV, 0, LoFlags)
2711 .addMemOperand(*MI.memoperands_begin());
2712 }
2713 }
2714 // To match MSVC. Unlike x86_64 which uses xor instruction to mix the cookie,
2715 // we use sub instruction to mix the cookie on aarch64.
2716 // The mixing happens here in expandPostRAPseudo (after RA) to ensure we use
2717 // the final frame pointer value.
2718 if (Subtarget.getTargetTriple().isOSMSVCRT())
2719 BuildMI(MBB, MI, DL, get(AArch64::SUBXrr), Reg)
2720 .addReg(AArch64::FP)
2722
2723 MBB.erase(MI);
2724
2725 return true;
2726}
2727
2728// Return true if this instruction simply sets its single destination register
2729// to zero. This is equivalent to a register rename of the zero-register.
2731 switch (MI.getOpcode()) {
2732 default:
2733 break;
2734 case AArch64::MOVZWi:
2735 case AArch64::MOVZXi: // movz Rd, #0 (LSL #0)
2736 if (MI.getOperand(1).isImm() && MI.getOperand(1).getImm() == 0) {
2737 assert(MI.getDesc().getNumOperands() == 3 &&
2738 MI.getOperand(2).getImm() == 0 && "invalid MOVZi operands");
2739 return true;
2740 }
2741 break;
2742 case AArch64::ANDWri: // and Rd, Rzr, #imm
2743 return MI.getOperand(1).getReg() == AArch64::WZR;
2744 case AArch64::ANDXri:
2745 return MI.getOperand(1).getReg() == AArch64::XZR;
2746 case TargetOpcode::COPY:
2747 return MI.getOperand(1).getReg() == AArch64::WZR;
2748 }
2749 return false;
2750}
2751
2752// Return true if this instruction simply renames a general register without
2753// modifying bits.
2755 switch (MI.getOpcode()) {
2756 default:
2757 break;
2758 case TargetOpcode::COPY: {
2759 // GPR32 copies will by lowered to ORRXrs
2760 Register DstReg = MI.getOperand(0).getReg();
2761 return (AArch64::GPR32RegClass.contains(DstReg) ||
2762 AArch64::GPR64RegClass.contains(DstReg));
2763 }
2764 case AArch64::ORRXrs: // orr Xd, Xzr, Xm (LSL #0)
2765 if (MI.getOperand(1).getReg() == AArch64::XZR) {
2766 assert(MI.getDesc().getNumOperands() == 4 &&
2767 MI.getOperand(3).getImm() == 0 && "invalid ORRrs operands");
2768 return true;
2769 }
2770 break;
2771 case AArch64::ADDXri: // add Xd, Xn, #0 (LSL #0)
2772 if (MI.getOperand(2).getImm() == 0) {
2773 assert(MI.getDesc().getNumOperands() == 4 &&
2774 MI.getOperand(3).getImm() == 0 && "invalid ADDXri operands");
2775 return true;
2776 }
2777 break;
2778 }
2779 return false;
2780}
2781
2782// Return true if this instruction simply renames a general register without
2783// modifying bits.
2785 switch (MI.getOpcode()) {
2786 default:
2787 break;
2788 case TargetOpcode::COPY: {
2789 Register DstReg = MI.getOperand(0).getReg();
2790 return AArch64::FPR128RegClass.contains(DstReg);
2791 }
2792 case AArch64::ORRv16i8:
2793 if (MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) {
2794 assert(MI.getDesc().getNumOperands() == 3 && MI.getOperand(0).isReg() &&
2795 "invalid ORRv16i8 operands");
2796 return true;
2797 }
2798 break;
2799 }
2800 return false;
2801}
2802
2803static bool isFrameLoadOpcode(int Opcode) {
2804 switch (Opcode) {
2805 default:
2806 return false;
2807 case AArch64::LDRWui:
2808 case AArch64::LDRXui:
2809 case AArch64::LDRBui:
2810 case AArch64::LDRHui:
2811 case AArch64::LDRSui:
2812 case AArch64::LDRDui:
2813 case AArch64::LDRQui:
2814 case AArch64::LDR_PXI:
2815 return true;
2816 }
2817}
2818
2820 int &FrameIndex) const {
2821 if (!isFrameLoadOpcode(MI.getOpcode()))
2822 return Register();
2823
2824 if (MI.getOperand(0).getSubReg() == 0 && MI.getOperand(1).isFI() &&
2825 MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) {
2826 FrameIndex = MI.getOperand(1).getIndex();
2827 return MI.getOperand(0).getReg();
2828 }
2829 return Register();
2830}
2831
2832static bool isFrameStoreOpcode(int Opcode) {
2833 switch (Opcode) {
2834 default:
2835 return false;
2836 case AArch64::STRWui:
2837 case AArch64::STRXui:
2838 case AArch64::STRBui:
2839 case AArch64::STRHui:
2840 case AArch64::STRSui:
2841 case AArch64::STRDui:
2842 case AArch64::STRQui:
2843 case AArch64::STR_PXI:
2844 return true;
2845 }
2846}
2847
2849 int &FrameIndex) const {
2850 if (!isFrameStoreOpcode(MI.getOpcode()))
2851 return Register();
2852
2853 if (MI.getOperand(0).getSubReg() == 0 && MI.getOperand(1).isFI() &&
2854 MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) {
2855 FrameIndex = MI.getOperand(1).getIndex();
2856 return MI.getOperand(0).getReg();
2857 }
2858 return Register();
2859}
2860
2862 int &FrameIndex) const {
2863 if (!isFrameStoreOpcode(MI.getOpcode()))
2864 return Register();
2865
2866 if (Register Reg = isStoreToStackSlot(MI, FrameIndex))
2867 return Reg;
2868
2870 if (hasStoreToStackSlot(MI, Accesses)) {
2871 if (Accesses.size() > 1)
2872 return Register();
2873
2874 FrameIndex =
2875 cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
2876 ->getFrameIndex();
2877 return MI.getOperand(0).getReg();
2878 }
2879 return Register();
2880}
2881
2883 int &FrameIndex) const {
2884 if (!isFrameLoadOpcode(MI.getOpcode()))
2885 return Register();
2886
2887 if (Register Reg = isLoadFromStackSlot(MI, FrameIndex))
2888 return Reg;
2889
2891 if (hasLoadFromStackSlot(MI, Accesses)) {
2892 if (Accesses.size() > 1)
2893 return Register();
2894
2895 FrameIndex =
2896 cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
2897 ->getFrameIndex();
2898 return MI.getOperand(0).getReg();
2899 }
2900 return Register();
2901}
2902
2903/// Check all MachineMemOperands for a hint to suppress pairing.
2905 return llvm::any_of(MI.memoperands(), [](MachineMemOperand *MMO) {
2906 return MMO->getFlags() & MOSuppressPair;
2907 });
2908}
2909
2910/// Set a flag on the first MachineMemOperand to suppress pairing.
2912 if (MI.memoperands_empty())
2913 return;
2914 (*MI.memoperands_begin())->setFlags(MOSuppressPair);
2915}
2916
2917/// Check all MachineMemOperands for a hint that the load/store is strided.
2919 return llvm::any_of(MI.memoperands(), [](MachineMemOperand *MMO) {
2920 return MMO->getFlags() & MOStridedAccess;
2921 });
2922}
2923
2925 switch (Opc) {
2926 default:
2927 return false;
2928 case AArch64::STURSi:
2929 case AArch64::STRSpre:
2930 case AArch64::STURDi:
2931 case AArch64::STRDpre:
2932 case AArch64::STURQi:
2933 case AArch64::STRQpre:
2934 case AArch64::STURBBi:
2935 case AArch64::STURHHi:
2936 case AArch64::STURWi:
2937 case AArch64::STRWpre:
2938 case AArch64::STURXi:
2939 case AArch64::STRXpre:
2940 case AArch64::LDURSi:
2941 case AArch64::LDRSpre:
2942 case AArch64::LDURDi:
2943 case AArch64::LDRDpre:
2944 case AArch64::LDURQi:
2945 case AArch64::LDRQpre:
2946 case AArch64::LDURWi:
2947 case AArch64::LDRWpre:
2948 case AArch64::LDURXi:
2949 case AArch64::LDRXpre:
2950 case AArch64::LDRSWpre:
2951 case AArch64::LDURSWi:
2952 case AArch64::LDURHHi:
2953 case AArch64::LDURBBi:
2954 case AArch64::LDURSBWi:
2955 case AArch64::LDURSHWi:
2956 return true;
2957 }
2958}
2959
2960std::optional<unsigned> AArch64InstrInfo::getUnscaledLdSt(unsigned Opc) {
2961 switch (Opc) {
2962 default: return {};
2963 case AArch64::PRFMui: return AArch64::PRFUMi;
2964 case AArch64::LDRXui: return AArch64::LDURXi;
2965 case AArch64::LDRWui: return AArch64::LDURWi;
2966 case AArch64::LDRBui: return AArch64::LDURBi;
2967 case AArch64::LDRHui: return AArch64::LDURHi;
2968 case AArch64::LDRSui: return AArch64::LDURSi;
2969 case AArch64::LDRDui: return AArch64::LDURDi;
2970 case AArch64::LDRQui: return AArch64::LDURQi;
2971 case AArch64::LDRBBui: return AArch64::LDURBBi;
2972 case AArch64::LDRHHui: return AArch64::LDURHHi;
2973 case AArch64::LDRSBXui: return AArch64::LDURSBXi;
2974 case AArch64::LDRSBWui: return AArch64::LDURSBWi;
2975 case AArch64::LDRSHXui: return AArch64::LDURSHXi;
2976 case AArch64::LDRSHWui: return AArch64::LDURSHWi;
2977 case AArch64::LDRSWui: return AArch64::LDURSWi;
2978 case AArch64::STRXui: return AArch64::STURXi;
2979 case AArch64::STRWui: return AArch64::STURWi;
2980 case AArch64::STRBui: return AArch64::STURBi;
2981 case AArch64::STRHui: return AArch64::STURHi;
2982 case AArch64::STRSui: return AArch64::STURSi;
2983 case AArch64::STRDui: return AArch64::STURDi;
2984 case AArch64::STRQui: return AArch64::STURQi;
2985 case AArch64::STRBBui: return AArch64::STURBBi;
2986 case AArch64::STRHHui: return AArch64::STURHHi;
2987 }
2988}
2989
2991 switch (Opc) {
2992 default:
2993 llvm_unreachable("Unhandled Opcode in getLoadStoreImmIdx");
2994 case AArch64::ADDG:
2995 case AArch64::LDAPURBi:
2996 case AArch64::LDAPURHi:
2997 case AArch64::LDAPURi:
2998 case AArch64::LDAPURSBWi:
2999 case AArch64::LDAPURSBXi:
3000 case AArch64::LDAPURSHWi:
3001 case AArch64::LDAPURSHXi:
3002 case AArch64::LDAPURSWi:
3003 case AArch64::LDAPURXi:
3004 case AArch64::LDR_PPXI:
3005 case AArch64::LDR_PXI:
3006 case AArch64::LDR_ZXI:
3007 case AArch64::LDR_ZZXI:
3008 case AArch64::LDR_ZZXI_STRIDED_CONTIGUOUS:
3009 case AArch64::LDR_ZZZXI:
3010 case AArch64::LDR_ZZZZXI:
3011 case AArch64::LDR_ZZZZXI_STRIDED_CONTIGUOUS:
3012 case AArch64::LDRBBui:
3013 case AArch64::LDRBui:
3014 case AArch64::LDRDui:
3015 case AArch64::LDRHHui:
3016 case AArch64::LDRHui:
3017 case AArch64::LDRQui:
3018 case AArch64::LDRSBWui:
3019 case AArch64::LDRSBXui:
3020 case AArch64::LDRSHWui:
3021 case AArch64::LDRSHXui:
3022 case AArch64::LDRSui:
3023 case AArch64::LDRSWui:
3024 case AArch64::LDRWui:
3025 case AArch64::LDRXui:
3026 case AArch64::LDURBBi:
3027 case AArch64::LDURBi:
3028 case AArch64::LDURDi:
3029 case AArch64::LDURHHi:
3030 case AArch64::LDURHi:
3031 case AArch64::LDURQi:
3032 case AArch64::LDURSBWi:
3033 case AArch64::LDURSBXi:
3034 case AArch64::LDURSHWi:
3035 case AArch64::LDURSHXi:
3036 case AArch64::LDURSi:
3037 case AArch64::LDURSWi:
3038 case AArch64::LDURWi:
3039 case AArch64::LDURXi:
3040 case AArch64::PRFMui:
3041 case AArch64::PRFUMi:
3042 case AArch64::ST2Gi:
3043 case AArch64::STGi:
3044 case AArch64::STLURBi:
3045 case AArch64::STLURHi:
3046 case AArch64::STLURWi:
3047 case AArch64::STLURXi:
3048 case AArch64::StoreSwiftAsyncContext:
3049 case AArch64::STR_PPXI:
3050 case AArch64::STR_PXI:
3051 case AArch64::STR_ZXI:
3052 case AArch64::STR_ZZXI:
3053 case AArch64::STR_ZZXI_STRIDED_CONTIGUOUS:
3054 case AArch64::STR_ZZZXI:
3055 case AArch64::STR_ZZZZXI:
3056 case AArch64::STR_ZZZZXI_STRIDED_CONTIGUOUS:
3057 case AArch64::STRBBui:
3058 case AArch64::STRBui:
3059 case AArch64::STRDui:
3060 case AArch64::STRHHui:
3061 case AArch64::STRHui:
3062 case AArch64::STRQui:
3063 case AArch64::STRSui:
3064 case AArch64::STRWui:
3065 case AArch64::STRXui:
3066 case AArch64::STURBBi:
3067 case AArch64::STURBi:
3068 case AArch64::STURDi:
3069 case AArch64::STURHHi:
3070 case AArch64::STURHi:
3071 case AArch64::STURQi:
3072 case AArch64::STURSi:
3073 case AArch64::STURWi:
3074 case AArch64::STURXi:
3075 case AArch64::STZ2Gi:
3076 case AArch64::STZGi:
3077 case AArch64::TAGPstack:
3078 return 2;
3079 case AArch64::LD1B_D_IMM:
3080 case AArch64::LD1B_H_IMM:
3081 case AArch64::LD1B_IMM:
3082 case AArch64::LD1B_S_IMM:
3083 case AArch64::LD1D_IMM:
3084 case AArch64::LD1H_D_IMM:
3085 case AArch64::LD1H_IMM:
3086 case AArch64::LD1H_S_IMM:
3087 case AArch64::LD1RB_D_IMM:
3088 case AArch64::LD1RB_H_IMM:
3089 case AArch64::LD1RB_IMM:
3090 case AArch64::LD1RB_S_IMM:
3091 case AArch64::LD1RD_IMM:
3092 case AArch64::LD1RH_D_IMM:
3093 case AArch64::LD1RH_IMM:
3094 case AArch64::LD1RH_S_IMM:
3095 case AArch64::LD1RSB_D_IMM:
3096 case AArch64::LD1RSB_H_IMM:
3097 case AArch64::LD1RSB_S_IMM:
3098 case AArch64::LD1RSH_D_IMM:
3099 case AArch64::LD1RSH_S_IMM:
3100 case AArch64::LD1RSW_IMM:
3101 case AArch64::LD1RW_D_IMM:
3102 case AArch64::LD1RW_IMM:
3103 case AArch64::LD1SB_D_IMM:
3104 case AArch64::LD1SB_H_IMM:
3105 case AArch64::LD1SB_S_IMM:
3106 case AArch64::LD1SH_D_IMM:
3107 case AArch64::LD1SH_S_IMM:
3108 case AArch64::LD1SW_D_IMM:
3109 case AArch64::LD1W_D_IMM:
3110 case AArch64::LD1W_IMM:
3111 case AArch64::LD2B_IMM:
3112 case AArch64::LD2D_IMM:
3113 case AArch64::LD2H_IMM:
3114 case AArch64::LD2W_IMM:
3115 case AArch64::LD3B_IMM:
3116 case AArch64::LD3D_IMM:
3117 case AArch64::LD3H_IMM:
3118 case AArch64::LD3W_IMM:
3119 case AArch64::LD4B_IMM:
3120 case AArch64::LD4D_IMM:
3121 case AArch64::LD4H_IMM:
3122 case AArch64::LD4W_IMM:
3123 case AArch64::LDG:
3124 case AArch64::LDNF1B_D_IMM:
3125 case AArch64::LDNF1B_H_IMM:
3126 case AArch64::LDNF1B_IMM:
3127 case AArch64::LDNF1B_S_IMM:
3128 case AArch64::LDNF1D_IMM:
3129 case AArch64::LDNF1H_D_IMM:
3130 case AArch64::LDNF1H_IMM:
3131 case AArch64::LDNF1H_S_IMM:
3132 case AArch64::LDNF1SB_D_IMM:
3133 case AArch64::LDNF1SB_H_IMM:
3134 case AArch64::LDNF1SB_S_IMM:
3135 case AArch64::LDNF1SH_D_IMM:
3136 case AArch64::LDNF1SH_S_IMM:
3137 case AArch64::LDNF1SW_D_IMM:
3138 case AArch64::LDNF1W_D_IMM:
3139 case AArch64::LDNF1W_IMM:
3140 case AArch64::LDNPDi:
3141 case AArch64::LDNPQi:
3142 case AArch64::LDNPSi:
3143 case AArch64::LDNPWi:
3144 case AArch64::LDNPXi:
3145 case AArch64::LDNT1B_ZRI:
3146 case AArch64::LDNT1D_ZRI:
3147 case AArch64::LDNT1H_ZRI:
3148 case AArch64::LDNT1W_ZRI:
3149 case AArch64::LDPDi:
3150 case AArch64::LDPQi:
3151 case AArch64::LDPSi:
3152 case AArch64::LDPWi:
3153 case AArch64::LDPXi:
3154 case AArch64::LDRBBpost:
3155 case AArch64::LDRBBpre:
3156 case AArch64::LDRBpost:
3157 case AArch64::LDRBpre:
3158 case AArch64::LDRDpost:
3159 case AArch64::LDRDpre:
3160 case AArch64::LDRHHpost:
3161 case AArch64::LDRHHpre:
3162 case AArch64::LDRHpost:
3163 case AArch64::LDRHpre:
3164 case AArch64::LDRQpost:
3165 case AArch64::LDRQpre:
3166 case AArch64::LDRSpost:
3167 case AArch64::LDRSpre:
3168 case AArch64::LDRWpost:
3169 case AArch64::LDRWpre:
3170 case AArch64::LDRXpost:
3171 case AArch64::LDRXpre:
3172 case AArch64::ST1B_D_IMM:
3173 case AArch64::ST1B_H_IMM:
3174 case AArch64::ST1B_IMM:
3175 case AArch64::ST1B_S_IMM:
3176 case AArch64::ST1D_IMM:
3177 case AArch64::ST1H_D_IMM:
3178 case AArch64::ST1H_IMM:
3179 case AArch64::ST1H_S_IMM:
3180 case AArch64::ST1W_D_IMM:
3181 case AArch64::ST1W_IMM:
3182 case AArch64::ST2B_IMM:
3183 case AArch64::ST2D_IMM:
3184 case AArch64::ST2H_IMM:
3185 case AArch64::ST2W_IMM:
3186 case AArch64::ST3B_IMM:
3187 case AArch64::ST3D_IMM:
3188 case AArch64::ST3H_IMM:
3189 case AArch64::ST3W_IMM:
3190 case AArch64::ST4B_IMM:
3191 case AArch64::ST4D_IMM:
3192 case AArch64::ST4H_IMM:
3193 case AArch64::ST4W_IMM:
3194 case AArch64::STGPi:
3195 case AArch64::STGPreIndex:
3196 case AArch64::STZGPreIndex:
3197 case AArch64::ST2GPreIndex:
3198 case AArch64::STZ2GPreIndex:
3199 case AArch64::STGPostIndex:
3200 case AArch64::STZGPostIndex:
3201 case AArch64::ST2GPostIndex:
3202 case AArch64::STZ2GPostIndex:
3203 case AArch64::STNPDi:
3204 case AArch64::STNPQi:
3205 case AArch64::STNPSi:
3206 case AArch64::STNPWi:
3207 case AArch64::STNPXi:
3208 case AArch64::STNT1B_ZRI:
3209 case AArch64::STNT1D_ZRI:
3210 case AArch64::STNT1H_ZRI:
3211 case AArch64::STNT1W_ZRI:
3212 case AArch64::STPDi:
3213 case AArch64::STPQi:
3214 case AArch64::STPSi:
3215 case AArch64::STPWi:
3216 case AArch64::STPXi:
3217 case AArch64::STRBBpost:
3218 case AArch64::STRBBpre:
3219 case AArch64::STRBpost:
3220 case AArch64::STRBpre:
3221 case AArch64::STRDpost:
3222 case AArch64::STRDpre:
3223 case AArch64::STRHHpost:
3224 case AArch64::STRHHpre:
3225 case AArch64::STRHpost:
3226 case AArch64::STRHpre:
3227 case AArch64::STRQpost:
3228 case AArch64::STRQpre:
3229 case AArch64::STRSpost:
3230 case AArch64::STRSpre:
3231 case AArch64::STRWpost:
3232 case AArch64::STRWpre:
3233 case AArch64::STRXpost:
3234 case AArch64::STRXpre:
3235 case AArch64::LD1B_2Z_IMM:
3236 case AArch64::LD1B_2Z_STRIDED_IMM:
3237 case AArch64::LD1H_2Z_IMM:
3238 case AArch64::LD1H_2Z_STRIDED_IMM:
3239 case AArch64::LD1W_2Z_IMM:
3240 case AArch64::LD1W_2Z_STRIDED_IMM:
3241 case AArch64::LD1D_2Z_IMM:
3242 case AArch64::LD1D_2Z_STRIDED_IMM:
3243 case AArch64::LD1B_4Z_IMM:
3244 case AArch64::LD1B_4Z_STRIDED_IMM:
3245 case AArch64::LD1H_4Z_IMM:
3246 case AArch64::LD1H_4Z_STRIDED_IMM:
3247 case AArch64::LD1W_4Z_IMM:
3248 case AArch64::LD1W_4Z_STRIDED_IMM:
3249 case AArch64::LD1D_4Z_IMM:
3250 case AArch64::LD1D_4Z_STRIDED_IMM:
3251 case AArch64::LD1B_2Z_IMM_PSEUDO:
3252 case AArch64::LD1H_2Z_IMM_PSEUDO:
3253 case AArch64::LD1W_2Z_IMM_PSEUDO:
3254 case AArch64::LD1D_2Z_IMM_PSEUDO:
3255 case AArch64::LD1B_4Z_IMM_PSEUDO:
3256 case AArch64::LD1H_4Z_IMM_PSEUDO:
3257 case AArch64::LD1W_4Z_IMM_PSEUDO:
3258 case AArch64::LD1D_4Z_IMM_PSEUDO:
3259 case AArch64::ST1B_2Z_IMM:
3260 case AArch64::ST1B_2Z_STRIDED_IMM:
3261 case AArch64::ST1H_2Z_IMM:
3262 case AArch64::ST1H_2Z_STRIDED_IMM:
3263 case AArch64::ST1W_2Z_IMM:
3264 case AArch64::ST1W_2Z_STRIDED_IMM:
3265 case AArch64::ST1D_2Z_IMM:
3266 case AArch64::ST1D_2Z_STRIDED_IMM:
3267 case AArch64::LDNT1B_2Z_IMM_PSEUDO:
3268 case AArch64::LDNT1B_2Z_IMM:
3269 case AArch64::LDNT1B_2Z_STRIDED_IMM:
3270 case AArch64::LDNT1H_2Z_IMM_PSEUDO:
3271 case AArch64::LDNT1H_2Z_IMM:
3272 case AArch64::LDNT1H_2Z_STRIDED_IMM:
3273 case AArch64::LDNT1W_2Z_IMM_PSEUDO:
3274 case AArch64::LDNT1W_2Z_IMM:
3275 case AArch64::LDNT1W_2Z_STRIDED_IMM:
3276 case AArch64::LDNT1D_2Z_IMM_PSEUDO:
3277 case AArch64::LDNT1D_2Z_IMM:
3278 case AArch64::LDNT1D_2Z_STRIDED_IMM:
3279 case AArch64::STNT1B_2Z_IMM:
3280 case AArch64::STNT1B_2Z_STRIDED_IMM:
3281 case AArch64::STNT1H_2Z_IMM:
3282 case AArch64::STNT1H_2Z_STRIDED_IMM:
3283 case AArch64::STNT1W_2Z_IMM:
3284 case AArch64::STNT1W_2Z_STRIDED_IMM:
3285 case AArch64::STNT1D_2Z_IMM:
3286 case AArch64::STNT1D_2Z_STRIDED_IMM:
3287 case AArch64::ST1B_4Z_IMM:
3288 case AArch64::ST1B_4Z_STRIDED_IMM:
3289 case AArch64::ST1H_4Z_IMM:
3290 case AArch64::ST1H_4Z_STRIDED_IMM:
3291 case AArch64::ST1W_4Z_IMM:
3292 case AArch64::ST1W_4Z_STRIDED_IMM:
3293 case AArch64::ST1D_4Z_IMM:
3294 case AArch64::ST1D_4Z_STRIDED_IMM:
3295 case AArch64::LDNT1B_4Z_IMM_PSEUDO:
3296 case AArch64::LDNT1B_4Z_IMM:
3297 case AArch64::LDNT1B_4Z_STRIDED_IMM:
3298 case AArch64::LDNT1H_4Z_IMM_PSEUDO:
3299 case AArch64::LDNT1H_4Z_IMM:
3300 case AArch64::LDNT1H_4Z_STRIDED_IMM:
3301 case AArch64::LDNT1W_4Z_IMM_PSEUDO:
3302 case AArch64::LDNT1W_4Z_IMM:
3303 case AArch64::LDNT1W_4Z_STRIDED_IMM:
3304 case AArch64::LDNT1D_4Z_IMM_PSEUDO:
3305 case AArch64::LDNT1D_4Z_IMM:
3306 case AArch64::LDNT1D_4Z_STRIDED_IMM:
3307 case AArch64::STNT1B_4Z_IMM:
3308 case AArch64::STNT1B_4Z_STRIDED_IMM:
3309 case AArch64::STNT1H_4Z_IMM:
3310 case AArch64::STNT1H_4Z_STRIDED_IMM:
3311 case AArch64::STNT1W_4Z_IMM:
3312 case AArch64::STNT1W_4Z_STRIDED_IMM:
3313 case AArch64::STNT1D_4Z_IMM:
3314 case AArch64::STNT1D_4Z_STRIDED_IMM:
3315 return 3;
3316 case AArch64::LDPDpost:
3317 case AArch64::LDPDpre:
3318 case AArch64::LDPQpost:
3319 case AArch64::LDPQpre:
3320 case AArch64::LDPSpost:
3321 case AArch64::LDPSpre:
3322 case AArch64::LDPWpost:
3323 case AArch64::LDPWpre:
3324 case AArch64::LDPXpost:
3325 case AArch64::LDPXpre:
3326 case AArch64::STGPpre:
3327 case AArch64::STGPpost:
3328 case AArch64::STPDpost:
3329 case AArch64::STPDpre:
3330 case AArch64::STPQpost:
3331 case AArch64::STPQpre:
3332 case AArch64::STPSpost:
3333 case AArch64::STPSpre:
3334 case AArch64::STPWpost:
3335 case AArch64::STPWpre:
3336 case AArch64::STPXpost:
3337 case AArch64::STPXpre:
3338 return 4;
3339 }
3340}
3341
3343 switch (MI.getOpcode()) {
3344 default:
3345 return false;
3346 // Scaled instructions.
3347 case AArch64::STRSui:
3348 case AArch64::STRDui:
3349 case AArch64::STRQui:
3350 case AArch64::STRXui:
3351 case AArch64::STRWui:
3352 case AArch64::LDRSui:
3353 case AArch64::LDRDui:
3354 case AArch64::LDRQui:
3355 case AArch64::LDRXui:
3356 case AArch64::LDRWui:
3357 case AArch64::LDRSWui:
3358 // Unscaled instructions.
3359 case AArch64::STURSi:
3360 case AArch64::STRSpre:
3361 case AArch64::STURDi:
3362 case AArch64::STRDpre:
3363 case AArch64::STURQi:
3364 case AArch64::STRQpre:
3365 case AArch64::STURWi:
3366 case AArch64::STRWpre:
3367 case AArch64::STURXi:
3368 case AArch64::STRXpre:
3369 case AArch64::LDURSi:
3370 case AArch64::LDRSpre:
3371 case AArch64::LDURDi:
3372 case AArch64::LDRDpre:
3373 case AArch64::LDURQi:
3374 case AArch64::LDRQpre:
3375 case AArch64::LDURWi:
3376 case AArch64::LDRWpre:
3377 case AArch64::LDURXi:
3378 case AArch64::LDRXpre:
3379 case AArch64::LDURSWi:
3380 case AArch64::LDRSWpre:
3381 // SVE instructions.
3382 case AArch64::LDR_ZXI:
3383 case AArch64::STR_ZXI:
3384 return true;
3385 }
3386}
3387
3389 switch (MI.getOpcode()) {
3390 default:
3391 assert((!MI.isCall() || !MI.isReturn()) &&
3392 "Unexpected instruction - was a new tail call opcode introduced?");
3393 return false;
3394 case AArch64::TCRETURNdi:
3395 case AArch64::TCRETURNri:
3396 case AArch64::TCRETURNrix16x17:
3397 case AArch64::TCRETURNrix17:
3398 case AArch64::TCRETURNrinotx16:
3399 case AArch64::TCRETURNriALL:
3400 case AArch64::AUTH_TCRETURN:
3401 case AArch64::AUTH_TCRETURN_BTI:
3402 return true;
3403 }
3404}
3405
3407 switch (Opc) {
3408 default:
3409 llvm_unreachable("Opcode has no flag setting equivalent!");
3410 // 32-bit cases:
3411 case AArch64::ADDWri:
3412 return AArch64::ADDSWri;
3413 case AArch64::ADDWrr:
3414 return AArch64::ADDSWrr;
3415 case AArch64::ADDWrs:
3416 return AArch64::ADDSWrs;
3417 case AArch64::ADDWrx:
3418 return AArch64::ADDSWrx;
3419 case AArch64::ANDWri:
3420 return AArch64::ANDSWri;
3421 case AArch64::ANDWrr:
3422 return AArch64::ANDSWrr;
3423 case AArch64::ANDWrs:
3424 return AArch64::ANDSWrs;
3425 case AArch64::BICWrr:
3426 return AArch64::BICSWrr;
3427 case AArch64::BICWrs:
3428 return AArch64::BICSWrs;
3429 case AArch64::SUBWri:
3430 return AArch64::SUBSWri;
3431 case AArch64::SUBWrr:
3432 return AArch64::SUBSWrr;
3433 case AArch64::SUBWrs:
3434 return AArch64::SUBSWrs;
3435 case AArch64::SUBWrx:
3436 return AArch64::SUBSWrx;
3437 // 64-bit cases:
3438 case AArch64::ADDXri:
3439 return AArch64::ADDSXri;
3440 case AArch64::ADDXrr:
3441 return AArch64::ADDSXrr;
3442 case AArch64::ADDXrs:
3443 return AArch64::ADDSXrs;
3444 case AArch64::ADDXrx:
3445 return AArch64::ADDSXrx;
3446 case AArch64::ANDXri:
3447 return AArch64::ANDSXri;
3448 case AArch64::ANDXrr:
3449 return AArch64::ANDSXrr;
3450 case AArch64::ANDXrs:
3451 return AArch64::ANDSXrs;
3452 case AArch64::BICXrr:
3453 return AArch64::BICSXrr;
3454 case AArch64::BICXrs:
3455 return AArch64::BICSXrs;
3456 case AArch64::SUBXri:
3457 return AArch64::SUBSXri;
3458 case AArch64::SUBXrr:
3459 return AArch64::SUBSXrr;
3460 case AArch64::SUBXrs:
3461 return AArch64::SUBSXrs;
3462 case AArch64::SUBXrx:
3463 return AArch64::SUBSXrx;
3464 // SVE instructions:
3465 case AArch64::AND_PPzPP:
3466 return AArch64::ANDS_PPzPP;
3467 case AArch64::BIC_PPzPP:
3468 return AArch64::BICS_PPzPP;
3469 case AArch64::EOR_PPzPP:
3470 return AArch64::EORS_PPzPP;
3471 case AArch64::NAND_PPzPP:
3472 return AArch64::NANDS_PPzPP;
3473 case AArch64::NOR_PPzPP:
3474 return AArch64::NORS_PPzPP;
3475 case AArch64::ORN_PPzPP:
3476 return AArch64::ORNS_PPzPP;
3477 case AArch64::ORR_PPzPP:
3478 return AArch64::ORRS_PPzPP;
3479 case AArch64::BRKA_PPzP:
3480 return AArch64::BRKAS_PPzP;
3481 case AArch64::BRKPA_PPzPP:
3482 return AArch64::BRKPAS_PPzPP;
3483 case AArch64::BRKB_PPzP:
3484 return AArch64::BRKBS_PPzP;
3485 case AArch64::BRKPB_PPzPP:
3486 return AArch64::BRKPBS_PPzPP;
3487 case AArch64::BRKN_PPzP:
3488 return AArch64::BRKNS_PPzP;
3489 case AArch64::RDFFR_PPz:
3490 return AArch64::RDFFRS_PPz;
3491 case AArch64::PTRUE_B:
3492 return AArch64::PTRUES_B;
3493 }
3494}
3495
3496// Is this a candidate for ld/st merging or pairing? For example, we don't
3497// touch volatiles or load/stores that have a hint to avoid pair formation.
3499
3500 bool IsPreLdSt = isPreLdSt(MI);
3501
3502 // If this is a volatile load/store, don't mess with it.
3503 if (MI.hasOrderedMemoryRef())
3504 return false;
3505
3506 // Make sure this is a reg/fi+imm (as opposed to an address reloc).
3507 // For Pre-inc LD/ST, the operand is shifted by one.
3508 assert((MI.getOperand(IsPreLdSt ? 2 : 1).isReg() ||
3509 MI.getOperand(IsPreLdSt ? 2 : 1).isFI()) &&
3510 "Expected a reg or frame index operand.");
3511
3512 // For Pre-indexed addressing quadword instructions, the third operand is the
3513 // immediate value.
3514 bool IsImmPreLdSt = IsPreLdSt && MI.getOperand(3).isImm();
3515
3516 if (!MI.getOperand(2).isImm() && !IsImmPreLdSt)
3517 return false;
3518
3519 // Can't merge/pair if the instruction modifies the base register.
3520 // e.g., ldr x0, [x0]
3521 // This case will never occur with an FI base.
3522 // However, if the instruction is an LDR<S,D,Q,W,X,SW>pre or
3523 // STR<S,D,Q,W,X>pre, it can be merged.
3524 // For example:
3525 // ldr q0, [x11, #32]!
3526 // ldr q1, [x11, #16]
3527 // to
3528 // ldp q0, q1, [x11, #32]!
3529 if (MI.getOperand(1).isReg() && !IsPreLdSt) {
3530 Register BaseReg = MI.getOperand(1).getReg();
3532 if (MI.modifiesRegister(BaseReg, TRI))
3533 return false;
3534 }
3535
3536 // Pairing SVE fills/spills is only valid for little-endian targets that
3537 // implement VLS 128.
3538 switch (MI.getOpcode()) {
3539 default:
3540 break;
3541 case AArch64::LDR_ZXI:
3542 case AArch64::STR_ZXI:
3543 if (!Subtarget.isLittleEndian() ||
3544 Subtarget.getSVEVectorSizeInBits() != 128)
3545 return false;
3546 }
3547
3548 // Check if this load/store has a hint to avoid pair formation.
3549 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
3551 return false;
3552
3553 // Do not pair any callee-save store/reload instructions in the
3554 // prologue/epilogue if the CFI information encoded the operations as separate
3555 // instructions, as that will cause the size of the actual prologue to mismatch
3556 // with the prologue size recorded in the Windows CFI.
3557 const MCAsmInfo &MAI = MI.getMF()->getTarget().getMCAsmInfo();
3558 bool NeedsWinCFI =
3559 MAI.usesWindowsCFI() && MI.getMF()->getFunction().needsUnwindTableEntry();
3560 if (NeedsWinCFI && (MI.getFlag(MachineInstr::FrameSetup) ||
3562 return false;
3563
3564 // On some CPUs quad load/store pairs are slower than two single load/stores.
3565 if (Subtarget.isPaired128Slow()) {
3566 switch (MI.getOpcode()) {
3567 default:
3568 break;
3569 case AArch64::LDURQi:
3570 case AArch64::STURQi:
3571 case AArch64::LDRQui:
3572 case AArch64::STRQui:
3573 return false;
3574 }
3575 }
3576
3577 return true;
3578}
3579
3582 int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width,
3583 const TargetRegisterInfo *TRI) const {
3584 if (!LdSt.mayLoadOrStore())
3585 return false;
3586
3587 const MachineOperand *BaseOp;
3588 TypeSize WidthN(0, false);
3589 if (!getMemOperandWithOffsetWidth(LdSt, BaseOp, Offset, OffsetIsScalable,
3590 WidthN, TRI))
3591 return false;
3592 // The maximum vscale is 16 under AArch64, return the maximal extent for the
3593 // vector.
3594 Width = LocationSize::precise(WidthN);
3595 BaseOps.push_back(BaseOp);
3596 return true;
3597}
3598
3599std::optional<ExtAddrMode>
3601 const TargetRegisterInfo *TRI) const {
3602 const MachineOperand *Base; // Filled with the base operand of MI.
3603 int64_t Offset; // Filled with the offset of MI.
3604 bool OffsetIsScalable;
3605 if (!getMemOperandWithOffset(MemI, Base, Offset, OffsetIsScalable, TRI))
3606 return std::nullopt;
3607
3608 if (!Base->isReg())
3609 return std::nullopt;
3610 ExtAddrMode AM;
3611 AM.BaseReg = Base->getReg();
3612 AM.Displacement = Offset;
3613 AM.ScaledReg = 0;
3614 AM.Scale = 0;
3615 return AM;
3616}
3617
3619 Register Reg,
3620 const MachineInstr &AddrI,
3621 ExtAddrMode &AM) const {
3622 // Filter out instructions into which we cannot fold.
3623 unsigned NumBytes;
3624 int64_t OffsetScale = 1;
3625 switch (MemI.getOpcode()) {
3626 default:
3627 return false;
3628
3629 case AArch64::LDURQi:
3630 case AArch64::STURQi:
3631 NumBytes = 16;
3632 break;
3633
3634 case AArch64::LDURDi:
3635 case AArch64::STURDi:
3636 case AArch64::LDURXi:
3637 case AArch64::STURXi:
3638 NumBytes = 8;
3639 break;
3640
3641 case AArch64::LDURWi:
3642 case AArch64::LDURSWi:
3643 case AArch64::STURWi:
3644 NumBytes = 4;
3645 break;
3646
3647 case AArch64::LDURHi:
3648 case AArch64::STURHi:
3649 case AArch64::LDURHHi:
3650 case AArch64::STURHHi:
3651 case AArch64::LDURSHXi:
3652 case AArch64::LDURSHWi:
3653 NumBytes = 2;
3654 break;
3655
3656 case AArch64::LDRBroX:
3657 case AArch64::LDRBBroX:
3658 case AArch64::LDRSBXroX:
3659 case AArch64::LDRSBWroX:
3660 case AArch64::STRBroX:
3661 case AArch64::STRBBroX:
3662 case AArch64::LDURBi:
3663 case AArch64::LDURBBi:
3664 case AArch64::LDURSBXi:
3665 case AArch64::LDURSBWi:
3666 case AArch64::STURBi:
3667 case AArch64::STURBBi:
3668 case AArch64::LDRBui:
3669 case AArch64::LDRBBui:
3670 case AArch64::LDRSBXui:
3671 case AArch64::LDRSBWui:
3672 case AArch64::STRBui:
3673 case AArch64::STRBBui:
3674 NumBytes = 1;
3675 break;
3676
3677 case AArch64::LDRQroX:
3678 case AArch64::STRQroX:
3679 case AArch64::LDRQui:
3680 case AArch64::STRQui:
3681 NumBytes = 16;
3682 OffsetScale = 16;
3683 break;
3684
3685 case AArch64::LDRDroX:
3686 case AArch64::STRDroX:
3687 case AArch64::LDRXroX:
3688 case AArch64::STRXroX:
3689 case AArch64::LDRDui:
3690 case AArch64::STRDui:
3691 case AArch64::LDRXui:
3692 case AArch64::STRXui:
3693 NumBytes = 8;
3694 OffsetScale = 8;
3695 break;
3696
3697 case AArch64::LDRWroX:
3698 case AArch64::LDRSWroX:
3699 case AArch64::STRWroX:
3700 case AArch64::LDRWui:
3701 case AArch64::LDRSWui:
3702 case AArch64::STRWui:
3703 NumBytes = 4;
3704 OffsetScale = 4;
3705 break;
3706
3707 case AArch64::LDRHroX:
3708 case AArch64::STRHroX:
3709 case AArch64::LDRHHroX:
3710 case AArch64::STRHHroX:
3711 case AArch64::LDRSHXroX:
3712 case AArch64::LDRSHWroX:
3713 case AArch64::LDRHui:
3714 case AArch64::STRHui:
3715 case AArch64::LDRHHui:
3716 case AArch64::STRHHui:
3717 case AArch64::LDRSHXui:
3718 case AArch64::LDRSHWui:
3719 NumBytes = 2;
3720 OffsetScale = 2;
3721 break;
3722 }
3723
3724 // Check the fold operand is not the loaded/stored value.
3725 const MachineOperand &BaseRegOp = MemI.getOperand(0);
3726 if (BaseRegOp.isReg() && BaseRegOp.getReg() == Reg)
3727 return false;
3728
3729 // Handle memory instructions with a [Reg, Reg] addressing mode.
3730 if (MemI.getOperand(2).isReg()) {
3731 // Bail if the addressing mode already includes extension of the offset
3732 // register.
3733 if (MemI.getOperand(3).getImm())
3734 return false;
3735
3736 // Check if we actually have a scaled offset.
3737 if (MemI.getOperand(4).getImm() == 0)
3738 OffsetScale = 1;
3739
3740 // If the address instructions is folded into the base register, then the
3741 // addressing mode must not have a scale. Then we can swap the base and the
3742 // scaled registers.
3743 if (MemI.getOperand(1).getReg() == Reg && OffsetScale != 1)
3744 return false;
3745
3746 switch (AddrI.getOpcode()) {
3747 default:
3748 return false;
3749
3750 case AArch64::SBFMXri:
3751 // sxtw Xa, Wm
3752 // ldr Xd, [Xn, Xa, lsl #N]
3753 // ->
3754 // ldr Xd, [Xn, Wm, sxtw #N]
3755 if (AddrI.getOperand(2).getImm() != 0 ||
3756 AddrI.getOperand(3).getImm() != 31)
3757 return false;
3758
3759 AM.BaseReg = MemI.getOperand(1).getReg();
3760 if (AM.BaseReg == Reg)
3761 AM.BaseReg = MemI.getOperand(2).getReg();
3762 AM.ScaledReg = AddrI.getOperand(1).getReg();
3763 AM.Scale = OffsetScale;
3764 AM.Displacement = 0;
3766 return true;
3767
3768 case TargetOpcode::SUBREG_TO_REG: {
3769 // mov Wa, Wm
3770 // ldr Xd, [Xn, Xa, lsl #N]
3771 // ->
3772 // ldr Xd, [Xn, Wm, uxtw #N]
3773
3774 // Zero-extension looks like an ORRWrs followed by a SUBREG_TO_REG.
3775 if (AddrI.getOperand(2).getImm() != AArch64::sub_32)
3776 return false;
3777
3778 const MachineRegisterInfo &MRI = AddrI.getMF()->getRegInfo();
3779 Register OffsetReg = AddrI.getOperand(1).getReg();
3780 if (!OffsetReg.isVirtual() || !MRI.hasOneNonDBGUse(OffsetReg))
3781 return false;
3782
3783 const MachineInstr &DefMI = *MRI.getVRegDef(OffsetReg);
3784 if (DefMI.getOpcode() != AArch64::ORRWrs ||
3785 DefMI.getOperand(1).getReg() != AArch64::WZR ||
3786 DefMI.getOperand(3).getImm() != 0)
3787 return false;
3788
3789 AM.BaseReg = MemI.getOperand(1).getReg();
3790 if (AM.BaseReg == Reg)
3791 AM.BaseReg = MemI.getOperand(2).getReg();
3792 AM.ScaledReg = DefMI.getOperand(2).getReg();
3793 AM.Scale = OffsetScale;
3794 AM.Displacement = 0;
3796 return true;
3797 }
3798 }
3799 }
3800
3801 // Handle memory instructions with a [Reg, #Imm] addressing mode.
3802
3803 // Check we are not breaking a potential conversion to an LDP.
3804 auto validateOffsetForLDP = [](unsigned NumBytes, int64_t OldOffset,
3805 int64_t NewOffset) -> bool {
3806 int64_t MinOffset, MaxOffset;
3807 switch (NumBytes) {
3808 default:
3809 return true;
3810 case 4:
3811 MinOffset = -256;
3812 MaxOffset = 252;
3813 break;
3814 case 8:
3815 MinOffset = -512;
3816 MaxOffset = 504;
3817 break;
3818 case 16:
3819 MinOffset = -1024;
3820 MaxOffset = 1008;
3821 break;
3822 }
3823 return OldOffset < MinOffset || OldOffset > MaxOffset ||
3824 (NewOffset >= MinOffset && NewOffset <= MaxOffset);
3825 };
3826 auto canFoldAddSubImmIntoAddrMode = [&](int64_t Disp) -> bool {
3827 int64_t OldOffset = MemI.getOperand(2).getImm() * OffsetScale;
3828 int64_t NewOffset = OldOffset + Disp;
3829 if (!isLegalAddressingMode(NumBytes, NewOffset, /* Scale */ 0))
3830 return false;
3831 // If the old offset would fit into an LDP, but the new offset wouldn't,
3832 // bail out.
3833 if (!validateOffsetForLDP(NumBytes, OldOffset, NewOffset))
3834 return false;
3835 AM.BaseReg = AddrI.getOperand(1).getReg();
3836 AM.ScaledReg = 0;
3837 AM.Scale = 0;
3838 AM.Displacement = NewOffset;
3840 return true;
3841 };
3842
3843 auto canFoldAddRegIntoAddrMode =
3844 [&](int64_t Scale,
3846 if (MemI.getOperand(2).getImm() != 0)
3847 return false;
3848 if ((unsigned)Scale != Scale)
3849 return false;
3850 if (!isLegalAddressingMode(NumBytes, /* Offset */ 0, Scale))
3851 return false;
3852 AM.BaseReg = AddrI.getOperand(1).getReg();
3853 AM.ScaledReg = AddrI.getOperand(2).getReg();
3854 AM.Scale = Scale;
3855 AM.Displacement = 0;
3856 AM.Form = Form;
3857 return true;
3858 };
3859
3860 auto avoidSlowSTRQ = [&](const MachineInstr &MemI) {
3861 unsigned Opcode = MemI.getOpcode();
3862 return (Opcode == AArch64::STURQi || Opcode == AArch64::STRQui) &&
3863 Subtarget.isSTRQroSlow();
3864 };
3865
3866 int64_t Disp = 0;
3867 const bool OptSize = MemI.getMF()->getFunction().hasOptSize();
3868 switch (AddrI.getOpcode()) {
3869 default:
3870 return false;
3871
3872 case AArch64::ADDXri:
3873 // add Xa, Xn, #N
3874 // ldr Xd, [Xa, #M]
3875 // ->
3876 // ldr Xd, [Xn, #N'+M]
3877 Disp = AddrI.getOperand(2).getImm() << AddrI.getOperand(3).getImm();
3878 return canFoldAddSubImmIntoAddrMode(Disp);
3879
3880 case AArch64::SUBXri:
3881 // sub Xa, Xn, #N
3882 // ldr Xd, [Xa, #M]
3883 // ->
3884 // ldr Xd, [Xn, #N'+M]
3885 Disp = AddrI.getOperand(2).getImm() << AddrI.getOperand(3).getImm();
3886 return canFoldAddSubImmIntoAddrMode(-Disp);
3887
3888 case AArch64::ADDXrs: {
3889 // add Xa, Xn, Xm, lsl #N
3890 // ldr Xd, [Xa]
3891 // ->
3892 // ldr Xd, [Xn, Xm, lsl #N]
3893
3894 // Don't fold the add if the result would be slower, unless optimising for
3895 // size.
3896 unsigned Shift = static_cast<unsigned>(AddrI.getOperand(3).getImm());
3898 return false;
3899 Shift = AArch64_AM::getShiftValue(Shift);
3900 if (!OptSize) {
3901 if (Shift != 2 && Shift != 3 && Subtarget.hasAddrLSLSlow14())
3902 return false;
3903 if (avoidSlowSTRQ(MemI))
3904 return false;
3905 }
3906 return canFoldAddRegIntoAddrMode(1ULL << Shift);
3907 }
3908
3909 case AArch64::ADDXrr:
3910 // add Xa, Xn, Xm
3911 // ldr Xd, [Xa]
3912 // ->
3913 // ldr Xd, [Xn, Xm, lsl #0]
3914
3915 // Don't fold the add if the result would be slower, unless optimising for
3916 // size.
3917 if (!OptSize && avoidSlowSTRQ(MemI))
3918 return false;
3919 return canFoldAddRegIntoAddrMode(1);
3920
3921 case AArch64::ADDXrx:
3922 // add Xa, Xn, Wm, {s,u}xtw #N
3923 // ldr Xd, [Xa]
3924 // ->
3925 // ldr Xd, [Xn, Wm, {s,u}xtw #N]
3926
3927 // Don't fold the add if the result would be slower, unless optimising for
3928 // size.
3929 if (!OptSize && avoidSlowSTRQ(MemI))
3930 return false;
3931
3932 // Can fold only sign-/zero-extend of a word.
3933 unsigned Imm = static_cast<unsigned>(AddrI.getOperand(3).getImm());
3935 if (Extend != AArch64_AM::UXTW && Extend != AArch64_AM::SXTW)
3936 return false;
3937
3938 return canFoldAddRegIntoAddrMode(
3939 1ULL << AArch64_AM::getArithShiftValue(Imm),
3942 }
3943}
3944
3945// Given an opcode for an instruction with a [Reg, #Imm] addressing mode,
3946// return the opcode of an instruction performing the same operation, but using
3947// the [Reg, Reg] addressing mode.
3948static unsigned regOffsetOpcode(unsigned Opcode) {
3949 switch (Opcode) {
3950 default:
3951 llvm_unreachable("Address folding not implemented for instruction");
3952
3953 case AArch64::LDURQi:
3954 case AArch64::LDRQui:
3955 return AArch64::LDRQroX;
3956 case AArch64::STURQi:
3957 case AArch64::STRQui:
3958 return AArch64::STRQroX;
3959 case AArch64::LDURDi:
3960 case AArch64::LDRDui:
3961 return AArch64::LDRDroX;
3962 case AArch64::STURDi:
3963 case AArch64::STRDui:
3964 return AArch64::STRDroX;
3965 case AArch64::LDURXi:
3966 case AArch64::LDRXui:
3967 return AArch64::LDRXroX;
3968 case AArch64::STURXi:
3969 case AArch64::STRXui:
3970 return AArch64::STRXroX;
3971 case AArch64::LDURWi:
3972 case AArch64::LDRWui:
3973 return AArch64::LDRWroX;
3974 case AArch64::LDURSWi:
3975 case AArch64::LDRSWui:
3976 return AArch64::LDRSWroX;
3977 case AArch64::STURWi:
3978 case AArch64::STRWui:
3979 return AArch64::STRWroX;
3980 case AArch64::LDURHi:
3981 case AArch64::LDRHui:
3982 return AArch64::LDRHroX;
3983 case AArch64::STURHi:
3984 case AArch64::STRHui:
3985 return AArch64::STRHroX;
3986 case AArch64::LDURHHi:
3987 case AArch64::LDRHHui:
3988 return AArch64::LDRHHroX;
3989 case AArch64::STURHHi:
3990 case AArch64::STRHHui:
3991 return AArch64::STRHHroX;
3992 case AArch64::LDURSHXi:
3993 case AArch64::LDRSHXui:
3994 return AArch64::LDRSHXroX;
3995 case AArch64::LDURSHWi:
3996 case AArch64::LDRSHWui:
3997 return AArch64::LDRSHWroX;
3998 case AArch64::LDURBi:
3999 case AArch64::LDRBui:
4000 return AArch64::LDRBroX;
4001 case AArch64::LDURBBi:
4002 case AArch64::LDRBBui:
4003 return AArch64::LDRBBroX;
4004 case AArch64::LDURSBXi:
4005 case AArch64::LDRSBXui:
4006 return AArch64::LDRSBXroX;
4007 case AArch64::LDURSBWi:
4008 case AArch64::LDRSBWui:
4009 return AArch64::LDRSBWroX;
4010 case AArch64::STURBi:
4011 case AArch64::STRBui:
4012 return AArch64::STRBroX;
4013 case AArch64::STURBBi:
4014 case AArch64::STRBBui:
4015 return AArch64::STRBBroX;
4016 }
4017}
4018
4019// Given an opcode for an instruction with a [Reg, #Imm] addressing mode, return
4020// the opcode of an instruction performing the same operation, but using the
4021// [Reg, #Imm] addressing mode with scaled offset.
4022unsigned scaledOffsetOpcode(unsigned Opcode, unsigned &Scale) {
4023 switch (Opcode) {
4024 default:
4025 llvm_unreachable("Address folding not implemented for instruction");
4026
4027 case AArch64::LDURQi:
4028 Scale = 16;
4029 return AArch64::LDRQui;
4030 case AArch64::STURQi:
4031 Scale = 16;
4032 return AArch64::STRQui;
4033 case AArch64::LDURDi:
4034 Scale = 8;
4035 return AArch64::LDRDui;
4036 case AArch64::STURDi:
4037 Scale = 8;
4038 return AArch64::STRDui;
4039 case AArch64::LDURXi:
4040 Scale = 8;
4041 return AArch64::LDRXui;
4042 case AArch64::STURXi:
4043 Scale = 8;
4044 return AArch64::STRXui;
4045 case AArch64::LDURWi:
4046 Scale = 4;
4047 return AArch64::LDRWui;
4048 case AArch64::LDURSWi:
4049 Scale = 4;
4050 return AArch64::LDRSWui;
4051 case AArch64::STURWi:
4052 Scale = 4;
4053 return AArch64::STRWui;
4054 case AArch64::LDURHi:
4055 Scale = 2;
4056 return AArch64::LDRHui;
4057 case AArch64::STURHi:
4058 Scale = 2;
4059 return AArch64::STRHui;
4060 case AArch64::LDURHHi:
4061 Scale = 2;
4062 return AArch64::LDRHHui;
4063 case AArch64::STURHHi:
4064 Scale = 2;
4065 return AArch64::STRHHui;
4066 case AArch64::LDURSHXi:
4067 Scale = 2;
4068 return AArch64::LDRSHXui;
4069 case AArch64::LDURSHWi:
4070 Scale = 2;
4071 return AArch64::LDRSHWui;
4072 case AArch64::LDURBi:
4073 Scale = 1;
4074 return AArch64::LDRBui;
4075 case AArch64::LDURBBi:
4076 Scale = 1;
4077 return AArch64::LDRBBui;
4078 case AArch64::LDURSBXi:
4079 Scale = 1;
4080 return AArch64::LDRSBXui;
4081 case AArch64::LDURSBWi:
4082 Scale = 1;
4083 return AArch64::LDRSBWui;
4084 case AArch64::STURBi:
4085 Scale = 1;
4086 return AArch64::STRBui;
4087 case AArch64::STURBBi:
4088 Scale = 1;
4089 return AArch64::STRBBui;
4090 case AArch64::LDRQui:
4091 case AArch64::STRQui:
4092 Scale = 16;
4093 return Opcode;
4094 case AArch64::LDRDui:
4095 case AArch64::STRDui:
4096 case AArch64::LDRXui:
4097 case AArch64::STRXui:
4098 Scale = 8;
4099 return Opcode;
4100 case AArch64::LDRWui:
4101 case AArch64::LDRSWui:
4102 case AArch64::STRWui:
4103 Scale = 4;
4104 return Opcode;
4105 case AArch64::LDRHui:
4106 case AArch64::STRHui:
4107 case AArch64::LDRHHui:
4108 case AArch64::STRHHui:
4109 case AArch64::LDRSHXui:
4110 case AArch64::LDRSHWui:
4111 Scale = 2;
4112 return Opcode;
4113 case AArch64::LDRBui:
4114 case AArch64::LDRBBui:
4115 case AArch64::LDRSBXui:
4116 case AArch64::LDRSBWui:
4117 case AArch64::STRBui:
4118 case AArch64::STRBBui:
4119 Scale = 1;
4120 return Opcode;
4121 }
4122}
4123
4124// Given an opcode for an instruction with a [Reg, #Imm] addressing mode, return
4125// the opcode of an instruction performing the same operation, but using the
4126// [Reg, #Imm] addressing mode with unscaled offset.
4127unsigned unscaledOffsetOpcode(unsigned Opcode) {
4128 switch (Opcode) {
4129 default:
4130 llvm_unreachable("Address folding not implemented for instruction");
4131
4132 case AArch64::LDURQi:
4133 case AArch64::STURQi:
4134 case AArch64::LDURDi:
4135 case AArch64::STURDi:
4136 case AArch64::LDURXi:
4137 case AArch64::STURXi:
4138 case AArch64::LDURWi:
4139 case AArch64::LDURSWi:
4140 case AArch64::STURWi:
4141 case AArch64::LDURHi:
4142 case AArch64::STURHi:
4143 case AArch64::LDURHHi:
4144 case AArch64::STURHHi:
4145 case AArch64::LDURSHXi:
4146 case AArch64::LDURSHWi:
4147 case AArch64::LDURBi:
4148 case AArch64::STURBi:
4149 case AArch64::LDURBBi:
4150 case AArch64::STURBBi:
4151 case AArch64::LDURSBWi:
4152 case AArch64::LDURSBXi:
4153 return Opcode;
4154 case AArch64::LDRQui:
4155 return AArch64::LDURQi;
4156 case AArch64::STRQui:
4157 return AArch64::STURQi;
4158 case AArch64::LDRDui:
4159 return AArch64::LDURDi;
4160 case AArch64::STRDui:
4161 return AArch64::STURDi;
4162 case AArch64::LDRXui:
4163 return AArch64::LDURXi;
4164 case AArch64::STRXui:
4165 return AArch64::STURXi;
4166 case AArch64::LDRWui:
4167 return AArch64::LDURWi;
4168 case AArch64::LDRSWui:
4169 return AArch64::LDURSWi;
4170 case AArch64::STRWui:
4171 return AArch64::STURWi;
4172 case AArch64::LDRHui:
4173 return AArch64::LDURHi;
4174 case AArch64::STRHui:
4175 return AArch64::STURHi;
4176 case AArch64::LDRHHui:
4177 return AArch64::LDURHHi;
4178 case AArch64::STRHHui:
4179 return AArch64::STURHHi;
4180 case AArch64::LDRSHXui:
4181 return AArch64::LDURSHXi;
4182 case AArch64::LDRSHWui:
4183 return AArch64::LDURSHWi;
4184 case AArch64::LDRBBui:
4185 return AArch64::LDURBBi;
4186 case AArch64::LDRBui:
4187 return AArch64::LDURBi;
4188 case AArch64::STRBBui:
4189 return AArch64::STURBBi;
4190 case AArch64::STRBui:
4191 return AArch64::STURBi;
4192 case AArch64::LDRSBWui:
4193 return AArch64::LDURSBWi;
4194 case AArch64::LDRSBXui:
4195 return AArch64::LDURSBXi;
4196 }
4197}
4198
4199// Given the opcode of a memory load/store instruction, return the opcode of an
4200// instruction performing the same operation, but using
4201// the [Reg, Reg, {s,u}xtw #N] addressing mode with sign-/zero-extend of the
4202// offset register.
4203static unsigned offsetExtendOpcode(unsigned Opcode) {
4204 switch (Opcode) {
4205 default:
4206 llvm_unreachable("Address folding not implemented for instruction");
4207
4208 case AArch64::LDRQroX:
4209 case AArch64::LDURQi:
4210 case AArch64::LDRQui:
4211 return AArch64::LDRQroW;
4212 case AArch64::STRQroX:
4213 case AArch64::STURQi:
4214 case AArch64::STRQui:
4215 return AArch64::STRQroW;
4216 case AArch64::LDRDroX:
4217 case AArch64::LDURDi:
4218 case AArch64::LDRDui:
4219 return AArch64::LDRDroW;
4220 case AArch64::STRDroX:
4221 case AArch64::STURDi:
4222 case AArch64::STRDui:
4223 return AArch64::STRDroW;
4224 case AArch64::LDRXroX:
4225 case AArch64::LDURXi:
4226 case AArch64::LDRXui:
4227 return AArch64::LDRXroW;
4228 case AArch64::STRXroX:
4229 case AArch64::STURXi:
4230 case AArch64::STRXui:
4231 return AArch64::STRXroW;
4232 case AArch64::LDRWroX:
4233 case AArch64::LDURWi:
4234 case AArch64::LDRWui:
4235 return AArch64::LDRWroW;
4236 case AArch64::LDRSWroX:
4237 case AArch64::LDURSWi:
4238 case AArch64::LDRSWui:
4239 return AArch64::LDRSWroW;
4240 case AArch64::STRWroX:
4241 case AArch64::STURWi:
4242 case AArch64::STRWui:
4243 return AArch64::STRWroW;
4244 case AArch64::LDRHroX:
4245 case AArch64::LDURHi:
4246 case AArch64::LDRHui:
4247 return AArch64::LDRHroW;
4248 case AArch64::STRHroX:
4249 case AArch64::STURHi:
4250 case AArch64::STRHui:
4251 return AArch64::STRHroW;
4252 case AArch64::LDRHHroX:
4253 case AArch64::LDURHHi:
4254 case AArch64::LDRHHui:
4255 return AArch64::LDRHHroW;
4256 case AArch64::STRHHroX:
4257 case AArch64::STURHHi:
4258 case AArch64::STRHHui:
4259 return AArch64::STRHHroW;
4260 case AArch64::LDRSHXroX:
4261 case AArch64::LDURSHXi:
4262 case AArch64::LDRSHXui:
4263 return AArch64::LDRSHXroW;
4264 case AArch64::LDRSHWroX:
4265 case AArch64::LDURSHWi:
4266 case AArch64::LDRSHWui:
4267 return AArch64::LDRSHWroW;
4268 case AArch64::LDRBroX:
4269 case AArch64::LDURBi:
4270 case AArch64::LDRBui:
4271 return AArch64::LDRBroW;
4272 case AArch64::LDRBBroX:
4273 case AArch64::LDURBBi:
4274 case AArch64::LDRBBui:
4275 return AArch64::LDRBBroW;
4276 case AArch64::LDRSBXroX:
4277 case AArch64::LDURSBXi:
4278 case AArch64::LDRSBXui:
4279 return AArch64::LDRSBXroW;
4280 case AArch64::LDRSBWroX:
4281 case AArch64::LDURSBWi:
4282 case AArch64::LDRSBWui:
4283 return AArch64::LDRSBWroW;
4284 case AArch64::STRBroX:
4285 case AArch64::STURBi:
4286 case AArch64::STRBui:
4287 return AArch64::STRBroW;
4288 case AArch64::STRBBroX:
4289 case AArch64::STURBBi:
4290 case AArch64::STRBBui:
4291 return AArch64::STRBBroW;
4292 }
4293}
4294
4296 const ExtAddrMode &AM) const {
4297
4298 const DebugLoc &DL = MemI.getDebugLoc();
4299 MachineBasicBlock &MBB = *MemI.getParent();
4300 MachineRegisterInfo &MRI = MemI.getMF()->getRegInfo();
4301
4303 if (AM.ScaledReg) {
4304 // The new instruction will be in the form `ldr Rt, [Xn, Xm, lsl #imm]`.
4305 unsigned Opcode = regOffsetOpcode(MemI.getOpcode());
4306 MRI.constrainRegClass(AM.BaseReg, &AArch64::GPR64spRegClass);
4307 auto B = BuildMI(MBB, MemI, DL, get(Opcode))
4308 .addReg(MemI.getOperand(0).getReg(),
4309 getDefRegState(MemI.mayLoad()))
4310 .addReg(AM.BaseReg)
4311 .addReg(AM.ScaledReg)
4312 .addImm(0)
4313 .addImm(AM.Scale > 1)
4314 .setMemRefs(MemI.memoperands())
4315 .setMIFlags(MemI.getFlags());
4316 return B.getInstr();
4317 }
4318
4319 assert(AM.ScaledReg == 0 && AM.Scale == 0 &&
4320 "Addressing mode not supported for folding");
4321
4322 // The new instruction will be in the form `ld[u]r Rt, [Xn, #imm]`.
4323 unsigned Scale = 1;
4324 unsigned Opcode = MemI.getOpcode();
4325 if (isInt<9>(AM.Displacement))
4326 Opcode = unscaledOffsetOpcode(Opcode);
4327 else
4328 Opcode = scaledOffsetOpcode(Opcode, Scale);
4329
4330 auto B =
4331 BuildMI(MBB, MemI, DL, get(Opcode))
4332 .addReg(MemI.getOperand(0).getReg(), getDefRegState(MemI.mayLoad()))
4333 .addReg(AM.BaseReg)
4334 .addImm(AM.Displacement / Scale)
4335 .setMemRefs(MemI.memoperands())
4336 .setMIFlags(MemI.getFlags());
4337 return B.getInstr();
4338 }
4339
4342 // The new instruction will be in the form `ldr Rt, [Xn, Wm, {s,u}xtw #N]`.
4343 assert(AM.ScaledReg && !AM.Displacement &&
4344 "Address offset can be a register or an immediate, but not both");
4345 unsigned Opcode = offsetExtendOpcode(MemI.getOpcode());
4346 MRI.constrainRegClass(AM.BaseReg, &AArch64::GPR64spRegClass);
4347 // Make sure the offset register is in the correct register class.
4348 Register OffsetReg = AM.ScaledReg;
4349 const TargetRegisterClass *RC = MRI.getRegClass(OffsetReg);
4350 if (RC->hasSuperClassEq(&AArch64::GPR64RegClass)) {
4351 OffsetReg = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
4352 BuildMI(MBB, MemI, DL, get(TargetOpcode::COPY), OffsetReg)
4353 .addReg(AM.ScaledReg, {}, AArch64::sub_32);
4354 }
4355 auto B =
4356 BuildMI(MBB, MemI, DL, get(Opcode))
4357 .addReg(MemI.getOperand(0).getReg(), getDefRegState(MemI.mayLoad()))
4358 .addReg(AM.BaseReg)
4359 .addReg(OffsetReg)
4361 .addImm(AM.Scale != 1)
4362 .setMemRefs(MemI.memoperands())
4363 .setMIFlags(MemI.getFlags());
4364
4365 return B.getInstr();
4366 }
4367
4369 "Function must not be called with an addressing mode it can't handle");
4370}
4371
4372/// Return true if the opcode is a post-index ld/st instruction, which really
4373/// loads from base+0.
4374static bool isPostIndexLdStOpcode(unsigned Opcode) {
4375 switch (Opcode) {
4376 default:
4377 return false;
4378 case AArch64::LD1Fourv16b_POST:
4379 case AArch64::LD1Fourv1d_POST:
4380 case AArch64::LD1Fourv2d_POST:
4381 case AArch64::LD1Fourv2s_POST:
4382 case AArch64::LD1Fourv4h_POST:
4383 case AArch64::LD1Fourv4s_POST:
4384 case AArch64::LD1Fourv8b_POST:
4385 case AArch64::LD1Fourv8h_POST:
4386 case AArch64::LD1Onev16b_POST:
4387 case AArch64::LD1Onev1d_POST:
4388 case AArch64::LD1Onev2d_POST:
4389 case AArch64::LD1Onev2s_POST:
4390 case AArch64::LD1Onev4h_POST:
4391 case AArch64::LD1Onev4s_POST:
4392 case AArch64::LD1Onev8b_POST:
4393 case AArch64::LD1Onev8h_POST:
4394 case AArch64::LD1Rv16b_POST:
4395 case AArch64::LD1Rv1d_POST:
4396 case AArch64::LD1Rv2d_POST:
4397 case AArch64::LD1Rv2s_POST:
4398 case AArch64::LD1Rv4h_POST:
4399 case AArch64::LD1Rv4s_POST:
4400 case AArch64::LD1Rv8b_POST:
4401 case AArch64::LD1Rv8h_POST:
4402 case AArch64::LD1Threev16b_POST:
4403 case AArch64::LD1Threev1d_POST:
4404 case AArch64::LD1Threev2d_POST:
4405 case AArch64::LD1Threev2s_POST:
4406 case AArch64::LD1Threev4h_POST:
4407 case AArch64::LD1Threev4s_POST:
4408 case AArch64::LD1Threev8b_POST:
4409 case AArch64::LD1Threev8h_POST:
4410 case AArch64::LD1Twov16b_POST:
4411 case AArch64::LD1Twov1d_POST:
4412 case AArch64::LD1Twov2d_POST:
4413 case AArch64::LD1Twov2s_POST:
4414 case AArch64::LD1Twov4h_POST:
4415 case AArch64::LD1Twov4s_POST:
4416 case AArch64::LD1Twov8b_POST:
4417 case AArch64::LD1Twov8h_POST:
4418 case AArch64::LD1i16_POST:
4419 case AArch64::LD1i32_POST:
4420 case AArch64::LD1i64_POST:
4421 case AArch64::LD1i8_POST:
4422 case AArch64::LD2Rv16b_POST:
4423 case AArch64::LD2Rv1d_POST:
4424 case AArch64::LD2Rv2d_POST:
4425 case AArch64::LD2Rv2s_POST:
4426 case AArch64::LD2Rv4h_POST:
4427 case AArch64::LD2Rv4s_POST:
4428 case AArch64::LD2Rv8b_POST:
4429 case AArch64::LD2Rv8h_POST:
4430 case AArch64::LD2Twov16b_POST:
4431 case AArch64::LD2Twov2d_POST:
4432 case AArch64::LD2Twov2s_POST:
4433 case AArch64::LD2Twov4h_POST:
4434 case AArch64::LD2Twov4s_POST:
4435 case AArch64::LD2Twov8b_POST:
4436 case AArch64::LD2Twov8h_POST:
4437 case AArch64::LD2i16_POST:
4438 case AArch64::LD2i32_POST:
4439 case AArch64::LD2i64_POST:
4440 case AArch64::LD2i8_POST:
4441 case AArch64::LD3Rv16b_POST:
4442 case AArch64::LD3Rv1d_POST:
4443 case AArch64::LD3Rv2d_POST:
4444 case AArch64::LD3Rv2s_POST:
4445 case AArch64::LD3Rv4h_POST:
4446 case AArch64::LD3Rv4s_POST:
4447 case AArch64::LD3Rv8b_POST:
4448 case AArch64::LD3Rv8h_POST:
4449 case AArch64::LD3Threev16b_POST:
4450 case AArch64::LD3Threev2d_POST:
4451 case AArch64::LD3Threev2s_POST:
4452 case AArch64::LD3Threev4h_POST:
4453 case AArch64::LD3Threev4s_POST:
4454 case AArch64::LD3Threev8b_POST:
4455 case AArch64::LD3Threev8h_POST:
4456 case AArch64::LD3i16_POST:
4457 case AArch64::LD3i32_POST:
4458 case AArch64::LD3i64_POST:
4459 case AArch64::LD3i8_POST:
4460 case AArch64::LD4Fourv16b_POST:
4461 case AArch64::LD4Fourv2d_POST:
4462 case AArch64::LD4Fourv2s_POST:
4463 case AArch64::LD4Fourv4h_POST:
4464 case AArch64::LD4Fourv4s_POST:
4465 case AArch64::LD4Fourv8b_POST:
4466 case AArch64::LD4Fourv8h_POST:
4467 case AArch64::LD4Rv16b_POST:
4468 case AArch64::LD4Rv1d_POST:
4469 case AArch64::LD4Rv2d_POST:
4470 case AArch64::LD4Rv2s_POST:
4471 case AArch64::LD4Rv4h_POST:
4472 case AArch64::LD4Rv4s_POST:
4473 case AArch64::LD4Rv8b_POST:
4474 case AArch64::LD4Rv8h_POST:
4475 case AArch64::LD4i16_POST:
4476 case AArch64::LD4i32_POST:
4477 case AArch64::LD4i64_POST:
4478 case AArch64::LD4i8_POST:
4479 case AArch64::LDAPRWpost:
4480 case AArch64::LDAPRXpost:
4481 case AArch64::LDIAPPWpost:
4482 case AArch64::LDIAPPXpost:
4483 case AArch64::LDPDpost:
4484 case AArch64::LDPQpost:
4485 case AArch64::LDPSWpost:
4486 case AArch64::LDPSpost:
4487 case AArch64::LDPWpost:
4488 case AArch64::LDPXpost:
4489 case AArch64::LDRBBpost:
4490 case AArch64::LDRBpost:
4491 case AArch64::LDRDpost:
4492 case AArch64::LDRHHpost:
4493 case AArch64::LDRHpost:
4494 case AArch64::LDRQpost:
4495 case AArch64::LDRSBWpost:
4496 case AArch64::LDRSBXpost:
4497 case AArch64::LDRSHWpost:
4498 case AArch64::LDRSHXpost:
4499 case AArch64::LDRSWpost:
4500 case AArch64::LDRSpost:
4501 case AArch64::LDRWpost:
4502 case AArch64::LDRXpost:
4503 case AArch64::ST1Fourv16b_POST:
4504 case AArch64::ST1Fourv1d_POST:
4505 case AArch64::ST1Fourv2d_POST:
4506 case AArch64::ST1Fourv2s_POST:
4507 case AArch64::ST1Fourv4h_POST:
4508 case AArch64::ST1Fourv4s_POST:
4509 case AArch64::ST1Fourv8b_POST:
4510 case AArch64::ST1Fourv8h_POST:
4511 case AArch64::ST1Onev16b_POST:
4512 case AArch64::ST1Onev1d_POST:
4513 case AArch64::ST1Onev2d_POST:
4514 case AArch64::ST1Onev2s_POST:
4515 case AArch64::ST1Onev4h_POST:
4516 case AArch64::ST1Onev4s_POST:
4517 case AArch64::ST1Onev8b_POST:
4518 case AArch64::ST1Onev8h_POST:
4519 case AArch64::ST1Threev16b_POST:
4520 case AArch64::ST1Threev1d_POST:
4521 case AArch64::ST1Threev2d_POST:
4522 case AArch64::ST1Threev2s_POST:
4523 case AArch64::ST1Threev4h_POST:
4524 case AArch64::ST1Threev4s_POST:
4525 case AArch64::ST1Threev8b_POST:
4526 case AArch64::ST1Threev8h_POST:
4527 case AArch64::ST1Twov16b_POST:
4528 case AArch64::ST1Twov1d_POST:
4529 case AArch64::ST1Twov2d_POST:
4530 case AArch64::ST1Twov2s_POST:
4531 case AArch64::ST1Twov4h_POST:
4532 case AArch64::ST1Twov4s_POST:
4533 case AArch64::ST1Twov8b_POST:
4534 case AArch64::ST1Twov8h_POST:
4535 case AArch64::ST1i16_POST:
4536 case AArch64::ST1i32_POST:
4537 case AArch64::ST1i64_POST:
4538 case AArch64::ST1i8_POST:
4539 case AArch64::ST2GPostIndex:
4540 case AArch64::ST2Twov16b_POST:
4541 case AArch64::ST2Twov2d_POST:
4542 case AArch64::ST2Twov2s_POST:
4543 case AArch64::ST2Twov4h_POST:
4544 case AArch64::ST2Twov4s_POST:
4545 case AArch64::ST2Twov8b_POST:
4546 case AArch64::ST2Twov8h_POST:
4547 case AArch64::ST2i16_POST:
4548 case AArch64::ST2i32_POST:
4549 case AArch64::ST2i64_POST:
4550 case AArch64::ST2i8_POST:
4551 case AArch64::ST3Threev16b_POST:
4552 case AArch64::ST3Threev2d_POST:
4553 case AArch64::ST3Threev2s_POST:
4554 case AArch64::ST3Threev4h_POST:
4555 case AArch64::ST3Threev4s_POST:
4556 case AArch64::ST3Threev8b_POST:
4557 case AArch64::ST3Threev8h_POST:
4558 case AArch64::ST3i16_POST:
4559 case AArch64::ST3i32_POST:
4560 case AArch64::ST3i64_POST:
4561 case AArch64::ST3i8_POST:
4562 case AArch64::ST4Fourv16b_POST:
4563 case AArch64::ST4Fourv2d_POST:
4564 case AArch64::ST4Fourv2s_POST:
4565 case AArch64::ST4Fourv4h_POST:
4566 case AArch64::ST4Fourv4s_POST:
4567 case AArch64::ST4Fourv8b_POST:
4568 case AArch64::ST4Fourv8h_POST:
4569 case AArch64::ST4i16_POST:
4570 case AArch64::ST4i32_POST:
4571 case AArch64::ST4i64_POST:
4572 case AArch64::ST4i8_POST:
4573 case AArch64::STGPostIndex:
4574 case AArch64::STGPpost:
4575 case AArch64::STPDpost:
4576 case AArch64::STPQpost:
4577 case AArch64::STPSpost:
4578 case AArch64::STPWpost:
4579 case AArch64::STPXpost:
4580 case AArch64::STRBBpost:
4581 case AArch64::STRBpost:
4582 case AArch64::STRDpost:
4583 case AArch64::STRHHpost:
4584 case AArch64::STRHpost:
4585 case AArch64::STRQpost:
4586 case AArch64::STRSpost:
4587 case AArch64::STRWpost:
4588 case AArch64::STRXpost:
4589 case AArch64::STZ2GPostIndex:
4590 case AArch64::STZGPostIndex:
4591 return true;
4592 }
4593}
4594
4596 const MachineInstr &LdSt, const MachineOperand *&BaseOp, int64_t &Offset,
4597 bool &OffsetIsScalable, TypeSize &Width,
4598 const TargetRegisterInfo *TRI) const {
4599 assert(LdSt.mayLoadOrStore() && "Expected a memory operation.");
4600 // Handle only loads/stores with base register followed by immediate offset.
4601 if (LdSt.getNumExplicitOperands() == 3) {
4602 // Non-paired instruction (e.g., ldr x1, [x0, #8]).
4603 if ((!LdSt.getOperand(1).isReg() && !LdSt.getOperand(1).isFI()) ||
4604 !LdSt.getOperand(2).isImm())
4605 return false;
4606 } else if (LdSt.getNumExplicitOperands() == 4) {
4607 // Paired instruction (e.g., ldp x1, x2, [x0, #8]).
4608 if (!LdSt.getOperand(1).isReg() ||
4609 (!LdSt.getOperand(2).isReg() && !LdSt.getOperand(2).isFI()) ||
4610 !LdSt.getOperand(3).isImm())
4611 return false;
4612 } else
4613 return false;
4614
4615 // Get the scaling factor for the instruction and set the width for the
4616 // instruction.
4617 TypeSize Scale(0U, false);
4618 int64_t Dummy1, Dummy2;
4619
4620 // If this returns false, then it's an instruction we don't want to handle.
4621 if (!getMemOpInfo(LdSt.getOpcode(), Scale, Width, Dummy1, Dummy2))
4622 return false;
4623
4624 // Compute the offset. Offset is calculated as the immediate operand
4625 // multiplied by the scaling factor. Unscaled instructions have scaling factor
4626 // set to 1. Postindex are a special case which have an offset of 0.
4627 if (isPostIndexLdStOpcode(LdSt.getOpcode())) {
4628 BaseOp = &LdSt.getOperand(2);
4629 Offset = 0;
4630 } else if (LdSt.getNumExplicitOperands() == 3) {
4631 BaseOp = &LdSt.getOperand(1);
4632 Offset = LdSt.getOperand(2).getImm() * Scale.getKnownMinValue();
4633 } else {
4634 assert(LdSt.getNumExplicitOperands() == 4 && "invalid number of operands");
4635 BaseOp = &LdSt.getOperand(2);
4636 Offset = LdSt.getOperand(3).getImm() * Scale.getKnownMinValue();
4637 }
4638 OffsetIsScalable = Scale.isScalable();
4639
4640 return BaseOp->isReg() || BaseOp->isFI();
4641}
4642
4645 assert(LdSt.mayLoadOrStore() && "Expected a memory operation.");
4646 MachineOperand &OfsOp = LdSt.getOperand(LdSt.getNumExplicitOperands() - 1);
4647 assert(OfsOp.isImm() && "Offset operand wasn't immediate.");
4648 return OfsOp;
4649}
4650
4651bool AArch64InstrInfo::getMemOpInfo(unsigned Opcode, TypeSize &Scale,
4652 TypeSize &Width, int64_t &MinOffset,
4653 int64_t &MaxOffset) {
4654 switch (Opcode) {
4655 // Not a memory operation or something we want to handle.
4656 default:
4657 Scale = Width = TypeSize::getFixed(0);
4658 MinOffset = MaxOffset = 0;
4659 return false;
4660 // LDR / STR
4661 case AArch64::LDRQui:
4662 case AArch64::STRQui:
4663 Scale = Width = TypeSize::getFixed(16);
4664 MinOffset = 0;
4665 MaxOffset = 4095;
4666 break;
4667 case AArch64::LDRXui:
4668 case AArch64::LDRDui:
4669 case AArch64::STRXui:
4670 case AArch64::STRDui:
4671 case AArch64::PRFMui:
4672 Scale = Width = TypeSize::getFixed(8);
4673 MinOffset = 0;
4674 MaxOffset = 4095;
4675 break;
4676 case AArch64::LDRWui:
4677 case AArch64::LDRSui:
4678 case AArch64::LDRSWui:
4679 case AArch64::STRWui:
4680 case AArch64::STRSui:
4681 Scale = Width = TypeSize::getFixed(4);
4682 MinOffset = 0;
4683 MaxOffset = 4095;
4684 break;
4685 case AArch64::LDRHui:
4686 case AArch64::LDRHHui:
4687 case AArch64::LDRSHWui:
4688 case AArch64::LDRSHXui:
4689 case AArch64::STRHui:
4690 case AArch64::STRHHui:
4691 Scale = Width = TypeSize::getFixed(2);
4692 MinOffset = 0;
4693 MaxOffset = 4095;
4694 break;
4695 case AArch64::LDRBui:
4696 case AArch64::LDRBBui:
4697 case AArch64::LDRSBWui:
4698 case AArch64::LDRSBXui:
4699 case AArch64::STRBui:
4700 case AArch64::STRBBui:
4701 Scale = Width = TypeSize::getFixed(1);
4702 MinOffset = 0;
4703 MaxOffset = 4095;
4704 break;
4705 // post/pre inc
4706 case AArch64::STRQpre:
4707 case AArch64::LDRQpost:
4708 Scale = TypeSize::getFixed(1);
4709 Width = TypeSize::getFixed(16);
4710 MinOffset = -256;
4711 MaxOffset = 255;
4712 break;
4713 case AArch64::LDRDpost:
4714 case AArch64::LDRDpre:
4715 case AArch64::LDRXpost:
4716 case AArch64::LDRXpre:
4717 case AArch64::STRDpost:
4718 case AArch64::STRDpre:
4719 case AArch64::STRXpost:
4720 case AArch64::STRXpre:
4721 Scale = TypeSize::getFixed(1);
4722 Width = TypeSize::getFixed(8);
4723 MinOffset = -256;
4724 MaxOffset = 255;
4725 break;
4726 case AArch64::STRWpost:
4727 case AArch64::STRWpre:
4728 case AArch64::LDRWpost:
4729 case AArch64::LDRWpre:
4730 case AArch64::STRSpost:
4731 case AArch64::STRSpre:
4732 case AArch64::LDRSpost:
4733 case AArch64::LDRSpre:
4734 Scale = TypeSize::getFixed(1);
4735 Width = TypeSize::getFixed(4);
4736 MinOffset = -256;
4737 MaxOffset = 255;
4738 break;
4739 case AArch64::LDRHpost:
4740 case AArch64::LDRHpre:
4741 case AArch64::STRHpost:
4742 case AArch64::STRHpre:
4743 case AArch64::LDRHHpost:
4744 case AArch64::LDRHHpre:
4745 case AArch64::STRHHpost:
4746 case AArch64::STRHHpre:
4747 Scale = TypeSize::getFixed(1);
4748 Width = TypeSize::getFixed(2);
4749 MinOffset = -256;
4750 MaxOffset = 255;
4751 break;
4752 case AArch64::LDRBpost:
4753 case AArch64::LDRBpre:
4754 case AArch64::STRBpost:
4755 case AArch64::STRBpre:
4756 case AArch64::LDRBBpost:
4757 case AArch64::LDRBBpre:
4758 case AArch64::STRBBpost:
4759 case AArch64::STRBBpre:
4760 Scale = Width = TypeSize::getFixed(1);
4761 MinOffset = -256;
4762 MaxOffset = 255;
4763 break;
4764 // Unscaled
4765 case AArch64::LDURQi:
4766 case AArch64::STURQi:
4767 Scale = TypeSize::getFixed(1);
4768 Width = TypeSize::getFixed(16);
4769 MinOffset = -256;
4770 MaxOffset = 255;
4771 break;
4772 case AArch64::LDURXi:
4773 case AArch64::LDURDi:
4774 case AArch64::LDAPURXi:
4775 case AArch64::STURXi:
4776 case AArch64::STURDi:
4777 case AArch64::STLURXi:
4778 case AArch64::PRFUMi:
4779 Scale = TypeSize::getFixed(1);
4780 Width = TypeSize::getFixed(8);
4781 MinOffset = -256;
4782 MaxOffset = 255;
4783 break;
4784 case AArch64::LDURWi:
4785 case AArch64::LDURSi:
4786 case AArch64::LDURSWi:
4787 case AArch64::LDAPURi:
4788 case AArch64::LDAPURSWi:
4789 case AArch64::STURWi:
4790 case AArch64::STURSi:
4791 case AArch64::STLURWi:
4792 Scale = TypeSize::getFixed(1);
4793 Width = TypeSize::getFixed(4);
4794 MinOffset = -256;
4795 MaxOffset = 255;
4796 break;
4797 case AArch64::LDURHi:
4798 case AArch64::LDURHHi:
4799 case AArch64::LDURSHXi:
4800 case AArch64::LDURSHWi:
4801 case AArch64::LDAPURHi:
4802 case AArch64::LDAPURSHWi:
4803 case AArch64::LDAPURSHXi:
4804 case AArch64::STURHi:
4805 case AArch64::STURHHi:
4806 case AArch64::STLURHi:
4807 Scale = TypeSize::getFixed(1);
4808 Width = TypeSize::getFixed(2);
4809 MinOffset = -256;
4810 MaxOffset = 255;
4811 break;
4812 case AArch64::LDURBi:
4813 case AArch64::LDURBBi:
4814 case AArch64::LDURSBXi:
4815 case AArch64::LDURSBWi:
4816 case AArch64::LDAPURBi:
4817 case AArch64::LDAPURSBWi:
4818 case AArch64::LDAPURSBXi:
4819 case AArch64::STURBi:
4820 case AArch64::STURBBi:
4821 case AArch64::STLURBi:
4822 Scale = Width = TypeSize::getFixed(1);
4823 MinOffset = -256;
4824 MaxOffset = 255;
4825 break;
4826 // LDP / STP (including pre/post inc)
4827 case AArch64::LDPQi:
4828 case AArch64::LDNPQi:
4829 case AArch64::STPQi:
4830 case AArch64::STNPQi:
4831 case AArch64::LDPQpost:
4832 case AArch64::LDPQpre:
4833 case AArch64::STPQpost:
4834 case AArch64::STPQpre:
4835 Scale = TypeSize::getFixed(16);
4836 Width = TypeSize::getFixed(16 * 2);
4837 MinOffset = -64;
4838 MaxOffset = 63;
4839 break;
4840 case AArch64::LDPXi:
4841 case AArch64::LDPDi:
4842 case AArch64::LDNPXi:
4843 case AArch64::LDNPDi:
4844 case AArch64::STPXi:
4845 case AArch64::STPDi:
4846 case AArch64::STNPXi:
4847 case AArch64::STNPDi:
4848 case AArch64::LDPDpost:
4849 case AArch64::LDPDpre:
4850 case AArch64::LDPXpost:
4851 case AArch64::LDPXpre:
4852 case AArch64::STPDpost:
4853 case AArch64::STPDpre:
4854 case AArch64::STPXpost:
4855 case AArch64::STPXpre:
4856 Scale = TypeSize::getFixed(8);
4857 Width = TypeSize::getFixed(8 * 2);
4858 MinOffset = -64;
4859 MaxOffset = 63;
4860 break;
4861 case AArch64::LDPWi:
4862 case AArch64::LDPSi:
4863 case AArch64::LDNPWi:
4864 case AArch64::LDNPSi:
4865 case AArch64::STPWi:
4866 case AArch64::STPSi:
4867 case AArch64::STNPWi:
4868 case AArch64::STNPSi:
4869 case AArch64::LDPSpost:
4870 case AArch64::LDPSpre:
4871 case AArch64::LDPWpost:
4872 case AArch64::LDPWpre:
4873 case AArch64::STPSpost:
4874 case AArch64::STPSpre:
4875 case AArch64::STPWpost:
4876 case AArch64::STPWpre:
4877 Scale = TypeSize::getFixed(4);
4878 Width = TypeSize::getFixed(4 * 2);
4879 MinOffset = -64;
4880 MaxOffset = 63;
4881 break;
4882 case AArch64::StoreSwiftAsyncContext:
4883 // Store is an STRXui, but there might be an ADDXri in the expansion too.
4884 Scale = TypeSize::getFixed(1);
4885 Width = TypeSize::getFixed(8);
4886 MinOffset = 0;
4887 MaxOffset = 4095;
4888 break;
4889 case AArch64::ADDG:
4890 Scale = TypeSize::getFixed(16);
4891 Width = TypeSize::getFixed(0);
4892 MinOffset = 0;
4893 MaxOffset = 63;
4894 break;
4895 case AArch64::TAGPstack:
4896 Scale = TypeSize::getFixed(16);
4897 Width = TypeSize::getFixed(0);
4898 // TAGP with a negative offset turns into SUBP, which has a maximum offset
4899 // of 63 (not 64!).
4900 MinOffset = -63;
4901 MaxOffset = 63;
4902 break;
4903 case AArch64::LDG:
4904 case AArch64::STGi:
4905 case AArch64::STGPreIndex:
4906 case AArch64::STGPostIndex:
4907 case AArch64::STZGi:
4908 case AArch64::STZGPreIndex:
4909 case AArch64::STZGPostIndex:
4910 Scale = Width = TypeSize::getFixed(16);
4911 MinOffset = -256;
4912 MaxOffset = 255;
4913 break;
4914 // SVE
4915 case AArch64::STR_ZZZZXI:
4916 case AArch64::STR_ZZZZXI_STRIDED_CONTIGUOUS:
4917 case AArch64::LDR_ZZZZXI:
4918 case AArch64::LDR_ZZZZXI_STRIDED_CONTIGUOUS:
4919 Scale = TypeSize::getScalable(16);
4920 Width = TypeSize::getScalable(16 * 4);
4921 MinOffset = -256;
4922 MaxOffset = 252;
4923 break;
4924 case AArch64::STR_ZZZXI:
4925 case AArch64::LDR_ZZZXI:
4926 Scale = TypeSize::getScalable(16);
4927 Width = TypeSize::getScalable(16 * 3);
4928 MinOffset = -256;
4929 MaxOffset = 253;
4930 break;
4931 case AArch64::STR_ZZXI:
4932 case AArch64::STR_ZZXI_STRIDED_CONTIGUOUS:
4933 case AArch64::LDR_ZZXI:
4934 case AArch64::LDR_ZZXI_STRIDED_CONTIGUOUS:
4935 Scale = TypeSize::getScalable(16);
4936 Width = TypeSize::getScalable(16 * 2);
4937 MinOffset = -256;
4938 MaxOffset = 254;
4939 break;
4940 case AArch64::LDR_PXI:
4941 case AArch64::STR_PXI:
4942 Scale = Width = TypeSize::getScalable(2);
4943 MinOffset = -256;
4944 MaxOffset = 255;
4945 break;
4946 case AArch64::LDR_PPXI:
4947 case AArch64::STR_PPXI:
4948 Scale = TypeSize::getScalable(2);
4949 Width = TypeSize::getScalable(2 * 2);
4950 MinOffset = -256;
4951 MaxOffset = 254;
4952 break;
4953 case AArch64::LDR_ZXI:
4954 case AArch64::STR_ZXI:
4955 Scale = Width = TypeSize::getScalable(16);
4956 MinOffset = -256;
4957 MaxOffset = 255;
4958 break;
4959 case AArch64::LD1B_IMM:
4960 case AArch64::LD1H_IMM:
4961 case AArch64::LD1W_IMM:
4962 case AArch64::LD1D_IMM:
4963 case AArch64::LDNT1B_ZRI:
4964 case AArch64::LDNT1H_ZRI:
4965 case AArch64::LDNT1W_ZRI:
4966 case AArch64::LDNT1D_ZRI:
4967 case AArch64::ST1B_IMM:
4968 case AArch64::ST1H_IMM:
4969 case AArch64::ST1W_IMM:
4970 case AArch64::ST1D_IMM:
4971 case AArch64::STNT1B_ZRI:
4972 case AArch64::STNT1H_ZRI:
4973 case AArch64::STNT1W_ZRI:
4974 case AArch64::STNT1D_ZRI:
4975 case AArch64::LDNF1B_IMM:
4976 case AArch64::LDNF1H_IMM:
4977 case AArch64::LDNF1W_IMM:
4978 case AArch64::LDNF1D_IMM:
4979 // A full vectors worth of data
4980 // Width = mbytes * elements
4981 Scale = Width = TypeSize::getScalable(16);
4982 MinOffset = -8;
4983 MaxOffset = 7;
4984 break;
4985 case AArch64::LD2B_IMM:
4986 case AArch64::LD2H_IMM:
4987 case AArch64::LD2W_IMM:
4988 case AArch64::LD2D_IMM:
4989 case AArch64::ST2B_IMM:
4990 case AArch64::ST2H_IMM:
4991 case AArch64::ST2W_IMM:
4992 case AArch64::ST2D_IMM:
4993 case AArch64::LD1B_2Z_IMM:
4994 case AArch64::LD1B_2Z_STRIDED_IMM:
4995 case AArch64::LD1H_2Z_IMM:
4996 case AArch64::LD1H_2Z_STRIDED_IMM:
4997 case AArch64::LD1W_2Z_IMM:
4998 case AArch64::LD1W_2Z_STRIDED_IMM:
4999 case AArch64::LD1D_2Z_IMM:
5000 case AArch64::LD1D_2Z_STRIDED_IMM:
5001 case AArch64::LD1B_2Z_IMM_PSEUDO:
5002 case AArch64::LD1H_2Z_IMM_PSEUDO:
5003 case AArch64::LD1W_2Z_IMM_PSEUDO:
5004 case AArch64::LD1D_2Z_IMM_PSEUDO:
5005 case AArch64::ST1B_2Z_IMM:
5006 case AArch64::ST1B_2Z_STRIDED_IMM:
5007 case AArch64::ST1H_2Z_IMM:
5008 case AArch64::ST1H_2Z_STRIDED_IMM:
5009 case AArch64::ST1W_2Z_IMM:
5010 case AArch64::ST1W_2Z_STRIDED_IMM:
5011 case AArch64::ST1D_2Z_IMM:
5012 case AArch64::ST1D_2Z_STRIDED_IMM:
5013 case AArch64::LDNT1B_2Z_IMM_PSEUDO:
5014 case AArch64::LDNT1B_2Z_IMM:
5015 case AArch64::LDNT1B_2Z_STRIDED_IMM:
5016 case AArch64::LDNT1H_2Z_IMM_PSEUDO:
5017 case AArch64::LDNT1H_2Z_IMM:
5018 case AArch64::LDNT1H_2Z_STRIDED_IMM:
5019 case AArch64::LDNT1W_2Z_IMM_PSEUDO:
5020 case AArch64::LDNT1W_2Z_IMM:
5021 case AArch64::LDNT1W_2Z_STRIDED_IMM:
5022 case AArch64::LDNT1D_2Z_IMM_PSEUDO:
5023 case AArch64::LDNT1D_2Z_IMM:
5024 case AArch64::LDNT1D_2Z_STRIDED_IMM:
5025 case AArch64::STNT1B_2Z_IMM:
5026 case AArch64::STNT1B_2Z_STRIDED_IMM:
5027 case AArch64::STNT1H_2Z_IMM:
5028 case AArch64::STNT1H_2Z_STRIDED_IMM:
5029 case AArch64::STNT1W_2Z_IMM:
5030 case AArch64::STNT1W_2Z_STRIDED_IMM:
5031 case AArch64::STNT1D_2Z_IMM:
5032 case AArch64::STNT1D_2Z_STRIDED_IMM:
5033 Scale = Width = TypeSize::getScalable(16 * 2);
5034 MinOffset = -8;
5035 MaxOffset = 7;
5036 break;
5037 case AArch64::LD3B_IMM:
5038 case AArch64::LD3H_IMM:
5039 case AArch64::LD3W_IMM:
5040 case AArch64::LD3D_IMM:
5041 case AArch64::ST3B_IMM:
5042 case AArch64::ST3H_IMM:
5043 case AArch64::ST3W_IMM:
5044 case AArch64::ST3D_IMM:
5045 Scale = Width = TypeSize::getScalable(16 * 3);
5046 MinOffset = -8;
5047 MaxOffset = 7;
5048 break;
5049 case AArch64::LD4B_IMM:
5050 case AArch64::LD4H_IMM:
5051 case AArch64::LD4W_IMM:
5052 case AArch64::LD4D_IMM:
5053 case AArch64::ST4B_IMM:
5054 case AArch64::ST4H_IMM:
5055 case AArch64::ST4W_IMM:
5056 case AArch64::ST4D_IMM:
5057 case AArch64::LD1B_4Z_IMM:
5058 case AArch64::LD1B_4Z_STRIDED_IMM:
5059 case AArch64::LD1H_4Z_IMM:
5060 case AArch64::LD1H_4Z_STRIDED_IMM:
5061 case AArch64::LD1W_4Z_IMM:
5062 case AArch64::LD1W_4Z_STRIDED_IMM:
5063 case AArch64::LD1D_4Z_IMM:
5064 case AArch64::LD1D_4Z_STRIDED_IMM:
5065 case AArch64::LD1B_4Z_IMM_PSEUDO:
5066 case AArch64::LD1H_4Z_IMM_PSEUDO:
5067 case AArch64::LD1W_4Z_IMM_PSEUDO:
5068 case AArch64::LD1D_4Z_IMM_PSEUDO:
5069 case AArch64::ST1B_4Z_IMM:
5070 case AArch64::ST1B_4Z_STRIDED_IMM:
5071 case AArch64::ST1H_4Z_IMM:
5072 case AArch64::ST1H_4Z_STRIDED_IMM:
5073 case AArch64::ST1W_4Z_IMM:
5074 case AArch64::ST1W_4Z_STRIDED_IMM:
5075 case AArch64::ST1D_4Z_IMM:
5076 case AArch64::ST1D_4Z_STRIDED_IMM:
5077 case AArch64::LDNT1B_4Z_IMM_PSEUDO:
5078 case AArch64::LDNT1B_4Z_IMM:
5079 case AArch64::LDNT1B_4Z_STRIDED_IMM:
5080 case AArch64::LDNT1H_4Z_IMM_PSEUDO:
5081 case AArch64::LDNT1H_4Z_IMM:
5082 case AArch64::LDNT1H_4Z_STRIDED_IMM:
5083 case AArch64::LDNT1W_4Z_IMM_PSEUDO:
5084 case AArch64::LDNT1W_4Z_IMM:
5085 case AArch64::LDNT1W_4Z_STRIDED_IMM:
5086 case AArch64::LDNT1D_4Z_IMM_PSEUDO:
5087 case AArch64::LDNT1D_4Z_IMM:
5088 case AArch64::LDNT1D_4Z_STRIDED_IMM:
5089 case AArch64::STNT1B_4Z_IMM:
5090 case AArch64::STNT1B_4Z_STRIDED_IMM:
5091 case AArch64::STNT1H_4Z_IMM:
5092 case AArch64::STNT1H_4Z_STRIDED_IMM:
5093 case AArch64::STNT1W_4Z_IMM:
5094 case AArch64::STNT1W_4Z_STRIDED_IMM:
5095 case AArch64::STNT1D_4Z_IMM:
5096 case AArch64::STNT1D_4Z_STRIDED_IMM:
5097 Scale = Width = TypeSize::getScalable(16 * 4);
5098 MinOffset = -8;
5099 MaxOffset = 7;
5100 break;
5101 case AArch64::LD1B_H_IMM:
5102 case AArch64::LD1SB_H_IMM:
5103 case AArch64::LD1H_S_IMM:
5104 case AArch64::LD1SH_S_IMM:
5105 case AArch64::LD1W_D_IMM:
5106 case AArch64::LD1SW_D_IMM:
5107 case AArch64::ST1B_H_IMM:
5108 case AArch64::ST1H_S_IMM:
5109 case AArch64::ST1W_D_IMM:
5110 case AArch64::LDNF1B_H_IMM:
5111 case AArch64::LDNF1SB_H_IMM:
5112 case AArch64::LDNF1H_S_IMM:
5113 case AArch64::LDNF1SH_S_IMM:
5114 case AArch64::LDNF1W_D_IMM:
5115 case AArch64::LDNF1SW_D_IMM:
5116 // A half vector worth of data
5117 // Width = mbytes * elements
5118 Scale = Width = TypeSize::getScalable(8);
5119 MinOffset = -8;
5120 MaxOffset = 7;
5121 break;
5122 case AArch64::LD1B_S_IMM:
5123 case AArch64::LD1SB_S_IMM:
5124 case AArch64::LD1H_D_IMM:
5125 case AArch64::LD1SH_D_IMM:
5126 case AArch64::ST1B_S_IMM:
5127 case AArch64::ST1H_D_IMM:
5128 case AArch64::LDNF1B_S_IMM:
5129 case AArch64::LDNF1SB_S_IMM:
5130 case AArch64::LDNF1H_D_IMM:
5131 case AArch64::LDNF1SH_D_IMM:
5132 // A quarter vector worth of data
5133 // Width = mbytes * elements
5134 Scale = Width = TypeSize::getScalable(4);
5135 MinOffset = -8;
5136 MaxOffset = 7;
5137 break;
5138 case AArch64::LD1B_D_IMM:
5139 case AArch64::LD1SB_D_IMM:
5140 case AArch64::ST1B_D_IMM:
5141 case AArch64::LDNF1B_D_IMM:
5142 case AArch64::LDNF1SB_D_IMM:
5143 // A eighth vector worth of data
5144 // Width = mbytes * elements
5145 Scale = Width = TypeSize::getScalable(2);
5146 MinOffset = -8;
5147 MaxOffset = 7;
5148 break;
5149 case AArch64::ST2Gi:
5150 case AArch64::ST2GPreIndex:
5151 case AArch64::ST2GPostIndex:
5152 case AArch64::STZ2Gi:
5153 case AArch64::STZ2GPreIndex:
5154 case AArch64::STZ2GPostIndex:
5155 Scale = TypeSize::getFixed(16);
5156 Width = TypeSize::getFixed(32);
5157 MinOffset = -256;
5158 MaxOffset = 255;
5159 break;
5160 case AArch64::STGPi:
5161 case AArch64::STGPpost:
5162 case AArch64::STGPpre:
5163 Scale = Width = TypeSize::getFixed(16);
5164 MinOffset = -64;
5165 MaxOffset = 63;
5166 break;
5167 case AArch64::LD1RB_IMM:
5168 case AArch64::LD1RB_H_IMM:
5169 case AArch64::LD1RB_S_IMM:
5170 case AArch64::LD1RB_D_IMM:
5171 case AArch64::LD1RSB_H_IMM:
5172 case AArch64::LD1RSB_S_IMM:
5173 case AArch64::LD1RSB_D_IMM:
5174 Scale = Width = TypeSize::getFixed(1);
5175 MinOffset = 0;
5176 MaxOffset = 63;
5177 break;
5178 case AArch64::LD1RH_IMM:
5179 case AArch64::LD1RH_S_IMM:
5180 case AArch64::LD1RH_D_IMM:
5181 case AArch64::LD1RSH_S_IMM:
5182 case AArch64::LD1RSH_D_IMM:
5183 Scale = Width = TypeSize::getFixed(2);
5184 MinOffset = 0;
5185 MaxOffset = 63;
5186 break;
5187 case AArch64::LD1RW_IMM:
5188 case AArch64::LD1RW_D_IMM:
5189 case AArch64::LD1RSW_IMM:
5190 Scale = Width = TypeSize::getFixed(4);
5191 MinOffset = 0;
5192 MaxOffset = 63;
5193 break;
5194 case AArch64::LD1RD_IMM:
5195 Scale = Width = TypeSize::getFixed(8);
5196 MinOffset = 0;
5197 MaxOffset = 63;
5198 break;
5199 }
5200
5201 return true;
5202}
5203
5204// Scaling factor for unscaled load or store.
5206 switch (Opc) {
5207 default:
5208 llvm_unreachable("Opcode has unknown scale!");
5209 case AArch64::LDRBui:
5210 case AArch64::LDRBBui:
5211 case AArch64::LDURBBi:
5212 case AArch64::LDRSBWui:
5213 case AArch64::LDURSBWi:
5214 case AArch64::STRBui:
5215 case AArch64::STRBBui:
5216 case AArch64::STURBBi:
5217 return 1;
5218 case AArch64::LDRHui:
5219 case AArch64::LDRHHui:
5220 case AArch64::LDURHHi:
5221 case AArch64::LDRSHWui:
5222 case AArch64::LDURSHWi:
5223 case AArch64::STRHui:
5224 case AArch64::STRHHui:
5225 case AArch64::STURHHi:
5226 return 2;
5227 case AArch64::LDRSui:
5228 case AArch64::LDURSi:
5229 case AArch64::LDRSpre:
5230 case AArch64::LDRSWui:
5231 case AArch64::LDURSWi:
5232 case AArch64::LDRSWpre:
5233 case AArch64::LDRWpre:
5234 case AArch64::LDRWui:
5235 case AArch64::LDURWi:
5236 case AArch64::STRSui:
5237 case AArch64::STURSi:
5238 case AArch64::STRSpre:
5239 case AArch64::STRWui:
5240 case AArch64::STURWi:
5241 case AArch64::STRWpre:
5242 case AArch64::LDPSi:
5243 case AArch64::LDPSWi:
5244 case AArch64::LDPWi:
5245 case AArch64::STPSi:
5246 case AArch64::STPWi:
5247 return 4;
5248 case AArch64::LDRDui:
5249 case AArch64::LDURDi:
5250 case AArch64::LDRDpre:
5251 case AArch64::LDRXui:
5252 case AArch64::LDURXi:
5253 case AArch64::LDRXpre:
5254 case AArch64::STRDui:
5255 case AArch64::STURDi:
5256 case AArch64::STRDpre:
5257 case AArch64::STRXui:
5258 case AArch64::STURXi:
5259 case AArch64::STRXpre:
5260 case AArch64::LDPDi:
5261 case AArch64::LDPXi:
5262 case AArch64::STPDi:
5263 case AArch64::STPXi:
5264 return 8;
5265 case AArch64::LDRQui:
5266 case AArch64::LDURQi:
5267 case AArch64::STRQui:
5268 case AArch64::STURQi:
5269 case AArch64::STRQpre:
5270 case AArch64::LDPQi:
5271 case AArch64::LDRQpre:
5272 case AArch64::STPQi:
5273 case AArch64::STGi:
5274 case AArch64::STZGi:
5275 case AArch64::ST2Gi:
5276 case AArch64::STZ2Gi:
5277 case AArch64::STGPi:
5278 return 16;
5279 }
5280}
5281
5283 switch (MI.getOpcode()) {
5284 default:
5285 return false;
5286 case AArch64::LDRWpre:
5287 case AArch64::LDRXpre:
5288 case AArch64::LDRSWpre:
5289 case AArch64::LDRSpre:
5290 case AArch64::LDRDpre:
5291 case AArch64::LDRQpre:
5292 return true;
5293 }
5294}
5295
5297 switch (MI.getOpcode()) {
5298 default:
5299 return false;
5300 case AArch64::STRWpre:
5301 case AArch64::STRXpre:
5302 case AArch64::STRSpre:
5303 case AArch64::STRDpre:
5304 case AArch64::STRQpre:
5305 return true;
5306 }
5307}
5308
5310 return isPreLd(MI) || isPreSt(MI);
5311}
5312
5314 switch (MI.getOpcode()) {
5315 default:
5316 return false;
5317 case AArch64::LDURBBi:
5318 case AArch64::LDURHHi:
5319 case AArch64::LDURWi:
5320 case AArch64::LDRBBui:
5321 case AArch64::LDRHHui:
5322 case AArch64::LDRWui:
5323 case AArch64::LDRBBroX:
5324 case AArch64::LDRHHroX:
5325 case AArch64::LDRWroX:
5326 case AArch64::LDRBBroW:
5327 case AArch64::LDRHHroW:
5328 case AArch64::LDRWroW:
5329 return true;
5330 }
5331}
5332
5334 switch (MI.getOpcode()) {
5335 default:
5336 return false;
5337 case AArch64::LDURSBWi:
5338 case AArch64::LDURSHWi:
5339 case AArch64::LDURSBXi:
5340 case AArch64::LDURSHXi:
5341 case AArch64::LDURSWi:
5342 case AArch64::LDRSBWui:
5343 case AArch64::LDRSHWui:
5344 case AArch64::LDRSBXui:
5345 case AArch64::LDRSHXui:
5346 case AArch64::LDRSWui:
5347 case AArch64::LDRSBWroX:
5348 case AArch64::LDRSHWroX:
5349 case AArch64::LDRSBXroX:
5350 case AArch64::LDRSHXroX:
5351 case AArch64::LDRSWroX:
5352 case AArch64::LDRSBWroW:
5353 case AArch64::LDRSHWroW:
5354 case AArch64::LDRSBXroW:
5355 case AArch64::LDRSHXroW:
5356 case AArch64::LDRSWroW:
5357 return true;
5358 }
5359}
5360
5362 switch (MI.getOpcode()) {
5363 default:
5364 return false;
5365 case AArch64::LDPSi:
5366 case AArch64::LDPSWi:
5367 case AArch64::LDPDi:
5368 case AArch64::LDPQi:
5369 case AArch64::LDPWi:
5370 case AArch64::LDPXi:
5371 case AArch64::STPSi:
5372 case AArch64::STPDi:
5373 case AArch64::STPQi:
5374 case AArch64::STPWi:
5375 case AArch64::STPXi:
5376 case AArch64::STGPi:
5377 return true;
5378 }
5379}
5380
5382 assert(MI.mayLoadOrStore() && "Load or store instruction expected");
5383 unsigned Idx =
5385 : 1;
5386 return MI.getOperand(Idx);
5387}
5388
5389const MachineOperand &
5391 assert(MI.mayLoadOrStore() && "Load or store instruction expected");
5392 unsigned Idx =
5394 : 2;
5395 return MI.getOperand(Idx);
5396}
5397
5398const MachineOperand &
5400 switch (MI.getOpcode()) {
5401 default:
5402 llvm_unreachable("Unexpected opcode");
5403 case AArch64::LDRBroX:
5404 case AArch64::LDRBBroX:
5405 case AArch64::LDRSBXroX:
5406 case AArch64::LDRSBWroX:
5407 case AArch64::LDRHroX:
5408 case AArch64::LDRHHroX:
5409 case AArch64::LDRSHXroX:
5410 case AArch64::LDRSHWroX:
5411 case AArch64::LDRWroX:
5412 case AArch64::LDRSroX:
5413 case AArch64::LDRSWroX:
5414 case AArch64::LDRDroX:
5415 case AArch64::LDRXroX:
5416 case AArch64::LDRQroX:
5417 return MI.getOperand(4);
5418 }
5419}
5420
5422 Register Reg) {
5423 if (MI.getParent() == nullptr)
5424 return nullptr;
5425 const MachineFunction *MF = MI.getParent()->getParent();
5426 return MF ? MF->getRegInfo().getRegClassOrNull(Reg) : nullptr;
5427}
5428
5430 auto IsHFPR = [&](const MachineOperand &Op) {
5431 if (!Op.isReg())
5432 return false;
5433 auto Reg = Op.getReg();
5434 if (Reg.isPhysical())
5435 return AArch64::FPR16RegClass.contains(Reg);
5436 const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
5437 return TRC == &AArch64::FPR16RegClass ||
5438 TRC == &AArch64::FPR16_loRegClass;
5439 };
5440 return llvm::any_of(MI.operands(), IsHFPR);
5441}
5442
5444 auto IsQFPR = [&](const MachineOperand &Op) {
5445 if (!Op.isReg())
5446 return false;
5447 auto Reg = Op.getReg();
5448 if (Reg.isPhysical())
5449 return AArch64::FPR128RegClass.contains(Reg);
5450 const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
5451 return TRC == &AArch64::FPR128RegClass ||
5452 TRC == &AArch64::FPR128_loRegClass;
5453 };
5454 return llvm::any_of(MI.operands(), IsQFPR);
5455}
5456
5458 switch (MI.getOpcode()) {
5459 case AArch64::BRK:
5460 case AArch64::HLT:
5461 case AArch64::PACIASP:
5462 case AArch64::PACIBSP:
5463 // Implicit BTI behavior.
5464 return true;
5465 case AArch64::PAUTH_PROLOGUE:
5466 // PAUTH_PROLOGUE expands to PACI(A|B)SP.
5467 return true;
5468 case AArch64::HINT: {
5469 unsigned Imm = MI.getOperand(0).getImm();
5470 // Explicit BTI instruction.
5471 if (Imm == 32 || Imm == 34 || Imm == 36 || Imm == 38)
5472 return true;
5473 // PACI(A|B)SP instructions.
5474 if (Imm == 25 || Imm == 27)
5475 return true;
5476 return false;
5477 }
5478 default:
5479 return false;
5480 }
5481}
5482
5484 if (Reg == 0)
5485 return false;
5486 assert(Reg.isPhysical() && "Expected physical register in isFpOrNEON");
5487 return AArch64::FPR128RegClass.contains(Reg) ||
5488 AArch64::FPR64RegClass.contains(Reg) ||
5489 AArch64::FPR32RegClass.contains(Reg) ||
5490 AArch64::FPR16RegClass.contains(Reg) ||
5491 AArch64::FPR8RegClass.contains(Reg);
5492}
5493
5495 auto IsFPR = [&](const MachineOperand &Op) {
5496 if (!Op.isReg())
5497 return false;
5498 auto Reg = Op.getReg();
5499 if (Reg.isPhysical())
5500 return isFpOrNEON(Reg);
5501
5502 const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
5503 return TRC == &AArch64::FPR128RegClass ||
5504 TRC == &AArch64::FPR128_loRegClass ||
5505 TRC == &AArch64::FPR64RegClass ||
5506 TRC == &AArch64::FPR64_loRegClass ||
5507 TRC == &AArch64::FPR32RegClass || TRC == &AArch64::FPR16RegClass ||
5508 TRC == &AArch64::FPR8RegClass;
5509 };
5510 return llvm::any_of(MI.operands(), IsFPR);
5511}
5512
5513// Scale the unscaled offsets. Returns false if the unscaled offset can't be
5514// scaled.
5515static bool scaleOffset(unsigned Opc, int64_t &Offset) {
5517
5518 // If the byte-offset isn't a multiple of the stride, we can't scale this
5519 // offset.
5520 if (Offset % Scale != 0)
5521 return false;
5522
5523 // Convert the byte-offset used by unscaled into an "element" offset used
5524 // by the scaled pair load/store instructions.
5525 Offset /= Scale;
5526 return true;
5527}
5528
5529static bool canPairLdStOpc(unsigned FirstOpc, unsigned SecondOpc) {
5530 if (FirstOpc == SecondOpc)
5531 return true;
5532 // We can also pair sign-ext and zero-ext instructions.
5533 switch (FirstOpc) {
5534 default:
5535 return false;
5536 case AArch64::STRSui:
5537 case AArch64::STURSi:
5538 return SecondOpc == AArch64::STRSui || SecondOpc == AArch64::STURSi;
5539 case AArch64::STRDui:
5540 case AArch64::STURDi:
5541 return SecondOpc == AArch64::STRDui || SecondOpc == AArch64::STURDi;
5542 case AArch64::STRQui:
5543 case AArch64::STURQi:
5544 return SecondOpc == AArch64::STRQui || SecondOpc == AArch64::STURQi;
5545 case AArch64::STRWui:
5546 case AArch64::STURWi:
5547 return SecondOpc == AArch64::STRWui || SecondOpc == AArch64::STURWi;
5548 case AArch64::STRXui:
5549 case AArch64::STURXi:
5550 return SecondOpc == AArch64::STRXui || SecondOpc == AArch64::STURXi;
5551 case AArch64::LDRSui:
5552 case AArch64::LDURSi:
5553 return SecondOpc == AArch64::LDRSui || SecondOpc == AArch64::LDURSi;
5554 case AArch64::LDRDui:
5555 case AArch64::LDURDi:
5556 return SecondOpc == AArch64::LDRDui || SecondOpc == AArch64::LDURDi;
5557 case AArch64::LDRQui:
5558 case AArch64::LDURQi:
5559 return SecondOpc == AArch64::LDRQui || SecondOpc == AArch64::LDURQi;
5560 case AArch64::LDRWui:
5561 case AArch64::LDURWi:
5562 return SecondOpc == AArch64::LDRSWui || SecondOpc == AArch64::LDURSWi;
5563 case AArch64::LDRSWui:
5564 case AArch64::LDURSWi:
5565 return SecondOpc == AArch64::LDRWui || SecondOpc == AArch64::LDURWi;
5566 case AArch64::LDRXui:
5567 case AArch64::LDURXi:
5568 return SecondOpc == AArch64::LDRXui || SecondOpc == AArch64::LDURXi;
5569 }
5570 // These instructions can't be paired based on their opcodes.
5571 return false;
5572}
5573
5574static bool shouldClusterFI(const MachineFrameInfo &MFI, int FI1,
5575 int64_t Offset1, unsigned Opcode1, int FI2,
5576 int64_t Offset2, unsigned Opcode2) {
5577 // Accesses through fixed stack object frame indices may access a different
5578 // fixed stack slot. Check that the object offsets + offsets match.
5579 if (MFI.isFixedObjectIndex(FI1) && MFI.isFixedObjectIndex(FI2)) {
5580 int64_t ObjectOffset1 = MFI.getObjectOffset(FI1);
5581 int64_t ObjectOffset2 = MFI.getObjectOffset(FI2);
5582 assert(ObjectOffset1 <= ObjectOffset2 && "Object offsets are not ordered.");
5583 // Convert to scaled object offsets.
5584 int Scale1 = AArch64InstrInfo::getMemScale(Opcode1);
5585 if (ObjectOffset1 % Scale1 != 0)
5586 return false;
5587 ObjectOffset1 /= Scale1;
5588 int Scale2 = AArch64InstrInfo::getMemScale(Opcode2);
5589 if (ObjectOffset2 % Scale2 != 0)
5590 return false;
5591 ObjectOffset2 /= Scale2;
5592 ObjectOffset1 += Offset1;
5593 ObjectOffset2 += Offset2;
5594 return ObjectOffset1 + 1 == ObjectOffset2;
5595 }
5596
5597 return FI1 == FI2;
5598}
5599
5600/// Detect opportunities for ldp/stp formation.
5601///
5602/// Only called for LdSt for which getMemOperandWithOffset returns true.
5604 ArrayRef<const MachineOperand *> BaseOps1, int64_t OpOffset1,
5605 bool OffsetIsScalable1, ArrayRef<const MachineOperand *> BaseOps2,
5606 int64_t OpOffset2, bool OffsetIsScalable2, unsigned ClusterSize,
5607 unsigned NumBytes) const {
5608 assert(BaseOps1.size() == 1 && BaseOps2.size() == 1);
5609 const MachineOperand &BaseOp1 = *BaseOps1.front();
5610 const MachineOperand &BaseOp2 = *BaseOps2.front();
5611 const MachineInstr &FirstLdSt = *BaseOp1.getParent();
5612 const MachineInstr &SecondLdSt = *BaseOp2.getParent();
5613 if (BaseOp1.getType() != BaseOp2.getType())
5614 return false;
5615
5616 assert((BaseOp1.isReg() || BaseOp1.isFI()) &&
5617 "Only base registers and frame indices are supported.");
5618
5619 // Check for both base regs and base FI.
5620 if (BaseOp1.isReg() && BaseOp1.getReg() != BaseOp2.getReg())
5621 return false;
5622
5623 // Only cluster up to a single pair.
5624 if (ClusterSize > 2)
5625 return false;
5626
5627 if (!isPairableLdStInst(FirstLdSt) || !isPairableLdStInst(SecondLdSt))
5628 return false;
5629
5630 // Can we pair these instructions based on their opcodes?
5631 unsigned FirstOpc = FirstLdSt.getOpcode();
5632 unsigned SecondOpc = SecondLdSt.getOpcode();
5633 if (!canPairLdStOpc(FirstOpc, SecondOpc))
5634 return false;
5635
5636 // Can't merge volatiles or load/stores that have a hint to avoid pair
5637 // formation, for example.
5638 if (!isCandidateToMergeOrPair(FirstLdSt) ||
5639 !isCandidateToMergeOrPair(SecondLdSt))
5640 return false;
5641
5642 // isCandidateToMergeOrPair guarantees that operand 2 is an immediate.
5643 int64_t Offset1 = FirstLdSt.getOperand(2).getImm();
5644 if (hasUnscaledLdStOffset(FirstOpc) && !scaleOffset(FirstOpc, Offset1))
5645 return false;
5646
5647 int64_t Offset2 = SecondLdSt.getOperand(2).getImm();
5648 if (hasUnscaledLdStOffset(SecondOpc) && !scaleOffset(SecondOpc, Offset2))
5649 return false;
5650
5651 // Pairwise instructions have a 7-bit signed offset field.
5652 if (Offset1 > 63 || Offset1 < -64)
5653 return false;
5654
5655 // The caller should already have ordered First/SecondLdSt by offset.
5656 // Note: except for non-equal frame index bases
5657 if (BaseOp1.isFI()) {
5658 assert((!BaseOp1.isIdenticalTo(BaseOp2) || Offset1 <= Offset2) &&
5659 "Caller should have ordered offsets.");
5660
5661 const MachineFrameInfo &MFI =
5662 FirstLdSt.getParent()->getParent()->getFrameInfo();
5663 return shouldClusterFI(MFI, BaseOp1.getIndex(), Offset1, FirstOpc,
5664 BaseOp2.getIndex(), Offset2, SecondOpc);
5665 }
5666
5667 assert(Offset1 <= Offset2 && "Caller should have ordered offsets.");
5668
5669 return Offset1 + 1 == Offset2;
5670}
5671
5673 MCRegister Reg, unsigned SubIdx,
5674 RegState State,
5675 const TargetRegisterInfo *TRI) {
5676 if (!SubIdx)
5677 return MIB.addReg(Reg, State);
5678
5679 if (Reg.isPhysical())
5680 return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
5681 return MIB.addReg(Reg, State, SubIdx);
5682}
5683
5684static bool forwardCopyWillClobberTuple(unsigned DestReg, unsigned SrcReg,
5685 unsigned NumRegs) {
5686 // We really want the positive remainder mod 32 here, that happens to be
5687 // easily obtainable with a mask.
5688 return ((DestReg - SrcReg) & 0x1f) < NumRegs;
5689}
5690
5693 const DebugLoc &DL, MCRegister DestReg,
5694 MCRegister SrcReg, bool KillSrc,
5695 unsigned Opcode,
5696 ArrayRef<unsigned> Indices) const {
5697 assert(Subtarget.hasNEON() && "Unexpected register copy without NEON");
5699 uint16_t DestEncoding = TRI->getEncodingValue(DestReg);
5700 uint16_t SrcEncoding = TRI->getEncodingValue(SrcReg);
5701 unsigned NumRegs = Indices.size();
5702
5703 int SubReg = 0, End = NumRegs, Incr = 1;
5704 if (forwardCopyWillClobberTuple(DestEncoding, SrcEncoding, NumRegs)) {
5705 SubReg = NumRegs - 1;
5706 End = -1;
5707 Incr = -1;
5708 }
5709
5710 for (; SubReg != End; SubReg += Incr) {
5711 const MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opcode));
5712 AddSubReg(MIB, DestReg, Indices[SubReg], RegState::Define, TRI);
5713 AddSubReg(MIB, SrcReg, Indices[SubReg], {}, TRI);
5714 AddSubReg(MIB, SrcReg, Indices[SubReg], getKillRegState(KillSrc), TRI);
5715 }
5716}
5717
5720 const DebugLoc &DL, MCRegister DestReg,
5721 MCRegister SrcReg, bool KillSrc,
5722 unsigned Opcode, unsigned ZeroReg,
5723 llvm::ArrayRef<unsigned> Indices) const {
5725 unsigned NumRegs = Indices.size();
5726
5727#ifndef NDEBUG
5728 uint16_t DestEncoding = TRI->getEncodingValue(DestReg);
5729 uint16_t SrcEncoding = TRI->getEncodingValue(SrcReg);
5730 assert(DestEncoding % NumRegs == 0 && SrcEncoding % NumRegs == 0 &&
5731 "GPR reg sequences should not be able to overlap");
5732#endif
5733
5734 for (unsigned SubReg = 0; SubReg != NumRegs; ++SubReg) {
5735 const MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opcode));
5736 AddSubReg(MIB, DestReg, Indices[SubReg], RegState::Define, TRI);
5737 MIB.addReg(ZeroReg);
5738 AddSubReg(MIB, SrcReg, Indices[SubReg], getKillRegState(KillSrc), TRI);
5739 MIB.addImm(0);
5740 }
5741}
5742
5743/// Returns true if the instruction at I is in a streaming call site region,
5744/// within a single basic block.
5745/// A "call site streaming region" starts after smstart and ends at smstop
5746/// around a call to a streaming function. This walks backward from I.
5749 MachineFunction &MF = *MBB.getParent();
5751 if (!AFI->hasStreamingModeChanges())
5752 return false;
5753 // Walk backwards to find smstart/smstop
5754 for (MachineInstr &MI : reverse(make_range(MBB.begin(), I))) {
5755 unsigned Opc = MI.getOpcode();
5756 if (Opc == AArch64::MSRpstatesvcrImm1 || Opc == AArch64::MSRpstatePseudo) {
5757 // Check if this is SM change (not ZA)
5758 int64_t PState = MI.getOperand(0).getImm();
5759 if (PState == AArch64SVCR::SVCRSM || PState == AArch64SVCR::SVCRSMZA) {
5760 // Operand 1 is 1 for start, 0 for stop
5761 return MI.getOperand(1).getImm() == 1;
5762 }
5763 }
5764 }
5765 return false;
5766}
5767
5768/// Returns true if in a streaming call site region without SME-FA64.
5769static bool mustAvoidNeonAtMBBI(const AArch64Subtarget &Subtarget,
5772 return !Subtarget.hasSMEFA64() && isInStreamingCallSiteRegion(MBB, I);
5773}
5774
5777 const DebugLoc &DL, Register DestReg,
5778 Register SrcReg, bool KillSrc,
5779 bool RenamableDest,
5780 bool RenamableSrc) const {
5781 ++NumCopyInstrs;
5782 if (AArch64::GPR32spRegClass.contains(DestReg) &&
5783 AArch64::GPR32spRegClass.contains(SrcReg)) {
5784 if (DestReg == AArch64::WSP || SrcReg == AArch64::WSP) {
5785 // If either operand is WSP, expand to ADD #0.
5786 if (Subtarget.hasZeroCycleRegMoveGPR64() &&
5787 !Subtarget.hasZeroCycleRegMoveGPR32()) {
5788 // Cyclone recognizes "ADD Xd, Xn, #0" as a zero-cycle register move.
5789 MCRegister DestRegX = RI.getMatchingSuperReg(DestReg, AArch64::sub_32,
5790 &AArch64::GPR64spRegClass);
5791 MCRegister SrcRegX = RI.getMatchingSuperReg(SrcReg, AArch64::sub_32,
5792 &AArch64::GPR64spRegClass);
5793 // This instruction is reading and writing X registers. This may upset
5794 // the register scavenger and machine verifier, so we need to indicate
5795 // that we are reading an undefined value from SrcRegX, but a proper
5796 // value from SrcReg.
5797 BuildMI(MBB, I, DL, get(AArch64::ADDXri), DestRegX)
5798 .addReg(SrcRegX, RegState::Undef)
5799 .addImm(0)
5801 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
5802 ++NumZCRegMoveInstrsGPR;
5803 } else {
5804 BuildMI(MBB, I, DL, get(AArch64::ADDWri), DestReg)
5805 .addReg(SrcReg, getKillRegState(KillSrc))
5806 .addImm(0)
5808 if (Subtarget.hasZeroCycleRegMoveGPR32())
5809 ++NumZCRegMoveInstrsGPR;
5810 }
5811 } else if (Subtarget.hasZeroCycleRegMoveGPR64() &&
5812 !Subtarget.hasZeroCycleRegMoveGPR32()) {
5813 // Cyclone recognizes "ORR Xd, XZR, Xm" as a zero-cycle register move.
5814 MCRegister DestRegX = RI.getMatchingSuperReg(DestReg, AArch64::sub_32,
5815 &AArch64::GPR64spRegClass);
5816 assert(DestRegX.isValid() && "Destination super-reg not valid");
5817 MCRegister SrcRegX = RI.getMatchingSuperReg(SrcReg, AArch64::sub_32,
5818 &AArch64::GPR64spRegClass);
5819 assert(SrcRegX.isValid() && "Source super-reg not valid");
5820 // This instruction is reading and writing X registers. This may upset
5821 // the register scavenger and machine verifier, so we need to indicate
5822 // that we are reading an undefined value from SrcRegX, but a proper
5823 // value from SrcReg.
5824 BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestRegX)
5825 .addReg(AArch64::XZR)
5826 .addReg(SrcRegX, RegState::Undef)
5827 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
5828 ++NumZCRegMoveInstrsGPR;
5829 } else {
5830 // Otherwise, expand to ORR WZR.
5831 BuildMI(MBB, I, DL, get(AArch64::ORRWrr), DestReg)
5832 .addReg(AArch64::WZR)
5833 .addReg(SrcReg, getKillRegState(KillSrc));
5834 if (Subtarget.hasZeroCycleRegMoveGPR32())
5835 ++NumZCRegMoveInstrsGPR;
5836 }
5837 return;
5838 }
5839
5840 // GPR32 zeroing
5841 if (AArch64::GPR32spRegClass.contains(DestReg) && SrcReg == AArch64::WZR) {
5842 if (Subtarget.hasZeroCycleZeroingGPR64() &&
5843 !Subtarget.hasZeroCycleZeroingGPR32()) {
5844 MCRegister DestRegX = RI.getMatchingSuperReg(DestReg, AArch64::sub_32,
5845 &AArch64::GPR64spRegClass);
5846 assert(DestRegX.isValid() && "Destination super-reg not valid");
5847 BuildMI(MBB, I, DL, get(AArch64::MOVZXi), DestRegX)
5848 .addImm(0)
5850 ++NumZCZeroingInstrsGPR;
5851 } else if (Subtarget.hasZeroCycleZeroingGPR32()) {
5852 BuildMI(MBB, I, DL, get(AArch64::MOVZWi), DestReg)
5853 .addImm(0)
5855 ++NumZCZeroingInstrsGPR;
5856 } else {
5857 BuildMI(MBB, I, DL, get(AArch64::ORRWrr), DestReg)
5858 .addReg(AArch64::WZR)
5859 .addReg(AArch64::WZR);
5860 }
5861 return;
5862 }
5863
5864 if (AArch64::GPR64spRegClass.contains(DestReg) &&
5865 AArch64::GPR64spRegClass.contains(SrcReg)) {
5866 if (DestReg == AArch64::SP || SrcReg == AArch64::SP) {
5867 // If either operand is SP, expand to ADD #0.
5868 BuildMI(MBB, I, DL, get(AArch64::ADDXri), DestReg)
5869 .addReg(SrcReg, getKillRegState(KillSrc))
5870 .addImm(0)
5872 if (Subtarget.hasZeroCycleRegMoveGPR64())
5873 ++NumZCRegMoveInstrsGPR;
5874 } else {
5875 // Otherwise, expand to ORR XZR.
5876 BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestReg)
5877 .addReg(AArch64::XZR)
5878 .addReg(SrcReg, getKillRegState(KillSrc));
5879 if (Subtarget.hasZeroCycleRegMoveGPR64())
5880 ++NumZCRegMoveInstrsGPR;
5881 }
5882 return;
5883 }
5884
5885 // GPR64 zeroing
5886 if (AArch64::GPR64spRegClass.contains(DestReg) && SrcReg == AArch64::XZR) {
5887 if (Subtarget.hasZeroCycleZeroingGPR64()) {
5888 BuildMI(MBB, I, DL, get(AArch64::MOVZXi), DestReg)
5889 .addImm(0)
5891 ++NumZCZeroingInstrsGPR;
5892 } else {
5893 BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestReg)
5894 .addReg(AArch64::XZR)
5895 .addReg(AArch64::XZR);
5896 }
5897 return;
5898 }
5899
5900 // Copy a Predicate register by ORRing with itself.
5901 if (AArch64::PPRRegClass.contains(DestReg) &&
5902 AArch64::PPRRegClass.contains(SrcReg)) {
5903 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
5904 "Unexpected SVE register.");
5905 BuildMI(MBB, I, DL, get(AArch64::ORR_PPzPP), DestReg)
5906 .addReg(SrcReg) // Pg
5907 .addReg(SrcReg)
5908 .addReg(SrcReg, getKillRegState(KillSrc));
5909 return;
5910 }
5911
5912 // Copy a predicate-as-counter register by ORRing with itself as if it
5913 // were a regular predicate (mask) register.
5914 bool DestIsPNR = AArch64::PNRRegClass.contains(DestReg);
5915 bool SrcIsPNR = AArch64::PNRRegClass.contains(SrcReg);
5916 if (DestIsPNR || SrcIsPNR) {
5917 auto ToPPR = [](MCRegister R) -> MCRegister {
5918 return (R - AArch64::PN0) + AArch64::P0;
5919 };
5920 MCRegister PPRSrcReg = SrcIsPNR ? ToPPR(SrcReg) : SrcReg.asMCReg();
5921 MCRegister PPRDestReg = DestIsPNR ? ToPPR(DestReg) : DestReg.asMCReg();
5922
5923 if (PPRSrcReg != PPRDestReg) {
5924 auto NewMI = BuildMI(MBB, I, DL, get(AArch64::ORR_PPzPP), PPRDestReg)
5925 .addReg(PPRSrcReg) // Pg
5926 .addReg(PPRSrcReg)
5927 .addReg(PPRSrcReg, getKillRegState(KillSrc));
5928 if (DestIsPNR)
5929 NewMI.addDef(DestReg, RegState::Implicit);
5930 }
5931 return;
5932 }
5933
5934 // Copy a Z register by ORRing with itself.
5935 if (AArch64::ZPRRegClass.contains(DestReg) &&
5936 AArch64::ZPRRegClass.contains(SrcReg)) {
5937 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
5938 "Unexpected SVE register.");
5939 BuildMI(MBB, I, DL, get(AArch64::ORR_ZZZ), DestReg)
5940 .addReg(SrcReg)
5941 .addReg(SrcReg, getKillRegState(KillSrc));
5942 return;
5943 }
5944
5945 // Copy a Z register pair by copying the individual sub-registers.
5946 if ((AArch64::ZPR2RegClass.contains(DestReg) ||
5947 AArch64::ZPR2StridedOrContiguousRegClass.contains(DestReg)) &&
5948 (AArch64::ZPR2RegClass.contains(SrcReg) ||
5949 AArch64::ZPR2StridedOrContiguousRegClass.contains(SrcReg))) {
5950 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
5951 "Unexpected SVE register.");
5952 static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1};
5953 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORR_ZZZ,
5954 Indices);
5955 return;
5956 }
5957
5958 // Copy a Z register triple by copying the individual sub-registers.
5959 if (AArch64::ZPR3RegClass.contains(DestReg) &&
5960 AArch64::ZPR3RegClass.contains(SrcReg)) {
5961 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
5962 "Unexpected SVE register.");
5963 static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1,
5964 AArch64::zsub2};
5965 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORR_ZZZ,
5966 Indices);
5967 return;
5968 }
5969
5970 // Copy a Z register quad by copying the individual sub-registers.
5971 if ((AArch64::ZPR4RegClass.contains(DestReg) ||
5972 AArch64::ZPR4StridedOrContiguousRegClass.contains(DestReg)) &&
5973 (AArch64::ZPR4RegClass.contains(SrcReg) ||
5974 AArch64::ZPR4StridedOrContiguousRegClass.contains(SrcReg))) {
5975 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
5976 "Unexpected SVE register.");
5977 static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1,
5978 AArch64::zsub2, AArch64::zsub3};
5979 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORR_ZZZ,
5980 Indices);
5981 return;
5982 }
5983
5984 // Copy a DDDD register quad by copying the individual sub-registers.
5985 if (AArch64::DDDDRegClass.contains(DestReg) &&
5986 AArch64::DDDDRegClass.contains(SrcReg)) {
5987 static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1,
5988 AArch64::dsub2, AArch64::dsub3};
5989 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv8i8,
5990 Indices);
5991 return;
5992 }
5993
5994 // Copy a DDD register triple by copying the individual sub-registers.
5995 if (AArch64::DDDRegClass.contains(DestReg) &&
5996 AArch64::DDDRegClass.contains(SrcReg)) {
5997 static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1,
5998 AArch64::dsub2};
5999 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv8i8,
6000 Indices);
6001 return;
6002 }
6003
6004 // Copy a DD register pair by copying the individual sub-registers.
6005 if (AArch64::DDRegClass.contains(DestReg) &&
6006 AArch64::DDRegClass.contains(SrcReg)) {
6007 static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1};
6008 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv8i8,
6009 Indices);
6010 return;
6011 }
6012
6013 // Copy a QQQQ register quad by copying the individual sub-registers.
6014 if (AArch64::QQQQRegClass.contains(DestReg) &&
6015 AArch64::QQQQRegClass.contains(SrcReg)) {
6016 static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1,
6017 AArch64::qsub2, AArch64::qsub3};
6018 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv16i8,
6019 Indices);
6020 return;
6021 }
6022
6023 // Copy a QQQ register triple by copying the individual sub-registers.
6024 if (AArch64::QQQRegClass.contains(DestReg) &&
6025 AArch64::QQQRegClass.contains(SrcReg)) {
6026 static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1,
6027 AArch64::qsub2};
6028 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv16i8,
6029 Indices);
6030 return;
6031 }
6032
6033 // Copy a QQ register pair by copying the individual sub-registers.
6034 if (AArch64::QQRegClass.contains(DestReg) &&
6035 AArch64::QQRegClass.contains(SrcReg)) {
6036 static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1};
6037 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv16i8,
6038 Indices);
6039 return;
6040 }
6041
6042 if (AArch64::XSeqPairsClassRegClass.contains(DestReg) &&
6043 AArch64::XSeqPairsClassRegClass.contains(SrcReg)) {
6044 static const unsigned Indices[] = {AArch64::sube64, AArch64::subo64};
6045 copyGPRRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRXrs,
6046 AArch64::XZR, Indices);
6047 return;
6048 }
6049
6050 if (AArch64::WSeqPairsClassRegClass.contains(DestReg) &&
6051 AArch64::WSeqPairsClassRegClass.contains(SrcReg)) {
6052 static const unsigned Indices[] = {AArch64::sube32, AArch64::subo32};
6053 copyGPRRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRWrs,
6054 AArch64::WZR, Indices);
6055 return;
6056 }
6057
6058 if (AArch64::FPR128RegClass.contains(DestReg) &&
6059 AArch64::FPR128RegClass.contains(SrcReg)) {
6060 // In streaming regions, NEON is illegal but streaming-SVE is available.
6061 // Use SVE for copies if we're in a streaming region and SME is available.
6062 // With +sme-fa64, NEON is legal in streaming mode so we can use it.
6063 if ((Subtarget.isSVEorStreamingSVEAvailable() &&
6064 !Subtarget.isNeonAvailable()) ||
6065 mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6066 BuildMI(MBB, I, DL, get(AArch64::ORR_ZZZ))
6067 .addReg(AArch64::Z0 + (DestReg - AArch64::Q0), RegState::Define)
6068 .addReg(AArch64::Z0 + (SrcReg - AArch64::Q0))
6069 .addReg(AArch64::Z0 + (SrcReg - AArch64::Q0));
6070 } else if (Subtarget.isNeonAvailable()) {
6071 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestReg)
6072 .addReg(SrcReg)
6073 .addReg(SrcReg, getKillRegState(KillSrc));
6074 if (Subtarget.hasZeroCycleRegMoveFPR128())
6075 ++NumZCRegMoveInstrsFPR;
6076 } else {
6077 BuildMI(MBB, I, DL, get(AArch64::STRQpre))
6078 .addReg(AArch64::SP, RegState::Define)
6079 .addReg(SrcReg, getKillRegState(KillSrc))
6080 .addReg(AArch64::SP)
6081 .addImm(-16);
6082 BuildMI(MBB, I, DL, get(AArch64::LDRQpost))
6083 .addReg(AArch64::SP, RegState::Define)
6084 .addReg(DestReg, RegState::Define)
6085 .addReg(AArch64::SP)
6086 .addImm(16);
6087 }
6088 return;
6089 }
6090
6091 if (AArch64::FPR64RegClass.contains(DestReg) &&
6092 AArch64::FPR64RegClass.contains(SrcReg)) {
6093 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6094 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6095 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6096 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6097 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::dsub,
6098 &AArch64::FPR128RegClass);
6099 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::dsub,
6100 &AArch64::FPR128RegClass);
6101 // This instruction is reading and writing Q registers. This may upset
6102 // the register scavenger and machine verifier, so we need to indicate
6103 // that we are reading an undefined value from SrcRegQ, but a proper
6104 // value from SrcReg.
6105 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6106 .addReg(SrcRegQ, RegState::Undef)
6107 .addReg(SrcRegQ, RegState::Undef)
6108 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6109 ++NumZCRegMoveInstrsFPR;
6110 } else {
6111 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestReg)
6112 .addReg(SrcReg, getKillRegState(KillSrc));
6113 if (Subtarget.hasZeroCycleRegMoveFPR64())
6114 ++NumZCRegMoveInstrsFPR;
6115 }
6116 return;
6117 }
6118
6119 if (AArch64::FPR32RegClass.contains(DestReg) &&
6120 AArch64::FPR32RegClass.contains(SrcReg)) {
6121 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6122 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6123 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6124 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6125 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::ssub,
6126 &AArch64::FPR128RegClass);
6127 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::ssub,
6128 &AArch64::FPR128RegClass);
6129 // This instruction is reading and writing Q registers. This may upset
6130 // the register scavenger and machine verifier, so we need to indicate
6131 // that we are reading an undefined value from SrcRegQ, but a proper
6132 // value from SrcReg.
6133 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6134 .addReg(SrcRegQ, RegState::Undef)
6135 .addReg(SrcRegQ, RegState::Undef)
6136 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6137 ++NumZCRegMoveInstrsFPR;
6138 } else if (Subtarget.hasZeroCycleRegMoveFPR64() &&
6139 !Subtarget.hasZeroCycleRegMoveFPR32()) {
6140 MCRegister DestRegD = RI.getMatchingSuperReg(DestReg, AArch64::ssub,
6141 &AArch64::FPR64RegClass);
6142 MCRegister SrcRegD = RI.getMatchingSuperReg(SrcReg, AArch64::ssub,
6143 &AArch64::FPR64RegClass);
6144 // This instruction is reading and writing D registers. This may upset
6145 // the register scavenger and machine verifier, so we need to indicate
6146 // that we are reading an undefined value from SrcRegD, but a proper
6147 // value from SrcReg.
6148 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestRegD)
6149 .addReg(SrcRegD, RegState::Undef)
6150 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6151 ++NumZCRegMoveInstrsFPR;
6152 } else {
6153 BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
6154 .addReg(SrcReg, getKillRegState(KillSrc));
6155 if (Subtarget.hasZeroCycleRegMoveFPR32())
6156 ++NumZCRegMoveInstrsFPR;
6157 }
6158 return;
6159 }
6160
6161 if (AArch64::FPR16RegClass.contains(DestReg) &&
6162 AArch64::FPR16RegClass.contains(SrcReg)) {
6163 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6164 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6165 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6166 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6167 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::hsub,
6168 &AArch64::FPR128RegClass);
6169 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::hsub,
6170 &AArch64::FPR128RegClass);
6171 // This instruction is reading and writing Q registers. This may upset
6172 // the register scavenger and machine verifier, so we need to indicate
6173 // that we are reading an undefined value from SrcRegQ, but a proper
6174 // value from SrcReg.
6175 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6176 .addReg(SrcRegQ, RegState::Undef)
6177 .addReg(SrcRegQ, RegState::Undef)
6178 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6179 } else if (Subtarget.hasZeroCycleRegMoveFPR64() &&
6180 !Subtarget.hasZeroCycleRegMoveFPR32()) {
6181 MCRegister DestRegD = RI.getMatchingSuperReg(DestReg, AArch64::hsub,
6182 &AArch64::FPR64RegClass);
6183 MCRegister SrcRegD = RI.getMatchingSuperReg(SrcReg, AArch64::hsub,
6184 &AArch64::FPR64RegClass);
6185 // This instruction is reading and writing D registers. This may upset
6186 // the register scavenger and machine verifier, so we need to indicate
6187 // that we are reading an undefined value from SrcRegD, but a proper
6188 // value from SrcReg.
6189 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestRegD)
6190 .addReg(SrcRegD, RegState::Undef)
6191 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6192 } else {
6193 DestReg = RI.getMatchingSuperReg(DestReg, AArch64::hsub,
6194 &AArch64::FPR32RegClass);
6195 SrcReg = RI.getMatchingSuperReg(SrcReg, AArch64::hsub,
6196 &AArch64::FPR32RegClass);
6197 BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
6198 .addReg(SrcReg, getKillRegState(KillSrc));
6199 }
6200 return;
6201 }
6202
6203 if (AArch64::FPR8RegClass.contains(DestReg) &&
6204 AArch64::FPR8RegClass.contains(SrcReg)) {
6205 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6206 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6207 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6208 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6209 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::bsub,
6210 &AArch64::FPR128RegClass);
6211 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::bsub,
6212 &AArch64::FPR128RegClass);
6213 // This instruction is reading and writing Q registers. This may upset
6214 // the register scavenger and machine verifier, so we need to indicate
6215 // that we are reading an undefined value from SrcRegQ, but a proper
6216 // value from SrcReg.
6217 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6218 .addReg(SrcRegQ, RegState::Undef)
6219 .addReg(SrcRegQ, RegState::Undef)
6220 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6221 } else if (Subtarget.hasZeroCycleRegMoveFPR64() &&
6222 !Subtarget.hasZeroCycleRegMoveFPR32()) {
6223 MCRegister DestRegD = RI.getMatchingSuperReg(DestReg, AArch64::bsub,
6224 &AArch64::FPR64RegClass);
6225 MCRegister SrcRegD = RI.getMatchingSuperReg(SrcReg, AArch64::bsub,
6226 &AArch64::FPR64RegClass);
6227 // This instruction is reading and writing D registers. This may upset
6228 // the register scavenger and machine verifier, so we need to indicate
6229 // that we are reading an undefined value from SrcRegD, but a proper
6230 // value from SrcReg.
6231 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestRegD)
6232 .addReg(SrcRegD, RegState::Undef)
6233 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6234 } else {
6235 DestReg = RI.getMatchingSuperReg(DestReg, AArch64::bsub,
6236 &AArch64::FPR32RegClass);
6237 SrcReg = RI.getMatchingSuperReg(SrcReg, AArch64::bsub,
6238 &AArch64::FPR32RegClass);
6239 BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
6240 .addReg(SrcReg, getKillRegState(KillSrc));
6241 }
6242 return;
6243 }
6244
6245 // Copies between GPR64 and FPR64.
6246 if (AArch64::FPR64RegClass.contains(DestReg) &&
6247 AArch64::GPR64RegClass.contains(SrcReg)) {
6248 if (AArch64::XZR == SrcReg) {
6249 BuildMI(MBB, I, DL, get(AArch64::FMOVD0), DestReg);
6250 } else {
6251 BuildMI(MBB, I, DL, get(AArch64::FMOVXDr), DestReg)
6252 .addReg(SrcReg, getKillRegState(KillSrc));
6253 }
6254 return;
6255 }
6256 if (AArch64::GPR64RegClass.contains(DestReg) &&
6257 AArch64::FPR64RegClass.contains(SrcReg)) {
6258 BuildMI(MBB, I, DL, get(AArch64::FMOVDXr), DestReg)
6259 .addReg(SrcReg, getKillRegState(KillSrc));
6260 return;
6261 }
6262 // Copies between GPR32 and FPR32.
6263 if (AArch64::FPR32RegClass.contains(DestReg) &&
6264 AArch64::GPR32RegClass.contains(SrcReg)) {
6265 if (AArch64::WZR == SrcReg) {
6266 BuildMI(MBB, I, DL, get(AArch64::FMOVS0), DestReg);
6267 } else {
6268 BuildMI(MBB, I, DL, get(AArch64::FMOVWSr), DestReg)
6269 .addReg(SrcReg, getKillRegState(KillSrc));
6270 }
6271 return;
6272 }
6273 if (AArch64::GPR32RegClass.contains(DestReg) &&
6274 AArch64::FPR32RegClass.contains(SrcReg)) {
6275 BuildMI(MBB, I, DL, get(AArch64::FMOVSWr), DestReg)
6276 .addReg(SrcReg, getKillRegState(KillSrc));
6277 return;
6278 }
6279
6280 if (DestReg == AArch64::NZCV) {
6281 assert(AArch64::GPR64RegClass.contains(SrcReg) && "Invalid NZCV copy");
6282 BuildMI(MBB, I, DL, get(AArch64::MSR))
6283 .addImm(AArch64SysReg::NZCV)
6284 .addReg(SrcReg, getKillRegState(KillSrc))
6285 .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define);
6286 return;
6287 }
6288
6289 if (SrcReg == AArch64::NZCV) {
6290 assert(AArch64::GPR64RegClass.contains(DestReg) && "Invalid NZCV copy");
6291 BuildMI(MBB, I, DL, get(AArch64::MRS), DestReg)
6292 .addImm(AArch64SysReg::NZCV)
6293 .addReg(AArch64::NZCV, RegState::Implicit | getKillRegState(KillSrc));
6294 return;
6295 }
6296
6297#ifndef NDEBUG
6298 errs() << RI.getRegAsmName(DestReg) << " = COPY " << RI.getRegAsmName(SrcReg)
6299 << "\n";
6300#endif
6301 llvm_unreachable("unimplemented reg-to-reg copy");
6302}
6303
6306 MachineBasicBlock::iterator InsertBefore,
6307 const MCInstrDesc &MCID,
6308 Register SrcReg, bool IsKill,
6309 unsigned SubIdx0, unsigned SubIdx1, int FI,
6310 MachineMemOperand *MMO) {
6311 Register SrcReg0 = SrcReg;
6312 Register SrcReg1 = SrcReg;
6313 if (SrcReg.isPhysical()) {
6314 SrcReg0 = TRI.getSubReg(SrcReg, SubIdx0);
6315 SubIdx0 = 0;
6316 SrcReg1 = TRI.getSubReg(SrcReg, SubIdx1);
6317 SubIdx1 = 0;
6318 }
6319 BuildMI(MBB, InsertBefore, DebugLoc(), MCID)
6320 .addReg(SrcReg0, getKillRegState(IsKill), SubIdx0)
6321 .addReg(SrcReg1, getKillRegState(IsKill), SubIdx1)
6322 .addFrameIndex(FI)
6323 .addImm(0)
6324 .addMemOperand(MMO);
6325}
6326
6329 Register SrcReg, bool isKill, int FI,
6330 const TargetRegisterClass *RC,
6331 Register VReg,
6332 MachineInstr::MIFlag Flags) const {
6333 MachineFunction &MF = *MBB.getParent();
6334 MachineFrameInfo &MFI = MF.getFrameInfo();
6335
6337 MachineMemOperand *MMO =
6339 MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
6340 unsigned Opc = 0;
6341 bool Offset = true;
6343 unsigned StackID = TargetStackID::Default;
6344 switch (RI.getSpillSize(*RC)) {
6345 case 1:
6346 if (AArch64::FPR8RegClass.hasSubClassEq(RC))
6347 Opc = AArch64::STRBui;
6348 break;
6349 case 2: {
6350 if (AArch64::FPR16RegClass.hasSubClassEq(RC))
6351 Opc = AArch64::STRHui;
6352 else if (AArch64::PNRRegClass.hasSubClassEq(RC) ||
6353 AArch64::PPRRegClass.hasSubClassEq(RC)) {
6354 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6355 "Unexpected register store without SVE store instructions");
6356 Opc = AArch64::STR_PXI;
6358 }
6359 break;
6360 }
6361 case 4:
6362 if (AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
6363 Opc = AArch64::STRWui;
6364 if (SrcReg.isVirtual())
6365 MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR32RegClass);
6366 else
6367 assert(SrcReg != AArch64::WSP);
6368 } else if (AArch64::FPR32RegClass.hasSubClassEq(RC))
6369 Opc = AArch64::STRSui;
6370 else if (AArch64::PPR2RegClass.hasSubClassEq(RC)) {
6371 Opc = AArch64::STR_PPXI;
6373 }
6374 break;
6375 case 8:
6376 if (AArch64::GPR64allRegClass.hasSubClassEq(RC)) {
6377 Opc = AArch64::STRXui;
6378 if (SrcReg.isVirtual())
6379 MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR64RegClass);
6380 else
6381 assert(SrcReg != AArch64::SP);
6382 } else if (AArch64::FPR64RegClass.hasSubClassEq(RC)) {
6383 Opc = AArch64::STRDui;
6384 } else if (AArch64::WSeqPairsClassRegClass.hasSubClassEq(RC)) {
6386 get(AArch64::STPWi), SrcReg, isKill,
6387 AArch64::sube32, AArch64::subo32, FI, MMO);
6388 return;
6389 }
6390 break;
6391 case 16:
6392 if (AArch64::FPR128RegClass.hasSubClassEq(RC))
6393 Opc = AArch64::STRQui;
6394 else if (AArch64::DDRegClass.hasSubClassEq(RC)) {
6395 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6396 Opc = AArch64::ST1Twov1d;
6397 Offset = false;
6398 } else if (AArch64::XSeqPairsClassRegClass.hasSubClassEq(RC)) {
6400 get(AArch64::STPXi), SrcReg, isKill,
6401 AArch64::sube64, AArch64::subo64, FI, MMO);
6402 return;
6403 } else if (AArch64::ZPRRegClass.hasSubClassEq(RC)) {
6404 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6405 "Unexpected register store without SVE store instructions");
6406 Opc = AArch64::STR_ZXI;
6408 }
6409 break;
6410 case 24:
6411 if (AArch64::DDDRegClass.hasSubClassEq(RC)) {
6412 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6413 Opc = AArch64::ST1Threev1d;
6414 Offset = false;
6415 }
6416 break;
6417 case 32:
6418 if (AArch64::DDDDRegClass.hasSubClassEq(RC)) {
6419 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6420 Opc = AArch64::ST1Fourv1d;
6421 Offset = false;
6422 } else if (AArch64::QQRegClass.hasSubClassEq(RC)) {
6423 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6424 Opc = AArch64::ST1Twov2d;
6425 Offset = false;
6426 } else if (AArch64::ZPR2StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6427 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6428 "Unexpected register store without SVE store instructions");
6429 Opc = AArch64::STR_ZZXI_STRIDED_CONTIGUOUS;
6431 } else if (AArch64::ZPR2RegClass.hasSubClassEq(RC)) {
6432 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6433 "Unexpected register store without SVE store instructions");
6434 Opc = AArch64::STR_ZZXI;
6436 }
6437 break;
6438 case 48:
6439 if (AArch64::QQQRegClass.hasSubClassEq(RC)) {
6440 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6441 Opc = AArch64::ST1Threev2d;
6442 Offset = false;
6443 } else if (AArch64::ZPR3RegClass.hasSubClassEq(RC)) {
6444 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6445 "Unexpected register store without SVE store instructions");
6446 Opc = AArch64::STR_ZZZXI;
6448 }
6449 break;
6450 case 64:
6451 if (AArch64::QQQQRegClass.hasSubClassEq(RC)) {
6452 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6453 Opc = AArch64::ST1Fourv2d;
6454 Offset = false;
6455 } else if (AArch64::ZPR4StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6456 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6457 "Unexpected register store without SVE store instructions");
6458 Opc = AArch64::STR_ZZZZXI_STRIDED_CONTIGUOUS;
6460 } else if (AArch64::ZPR4RegClass.hasSubClassEq(RC)) {
6461 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6462 "Unexpected register store without SVE store instructions");
6463 Opc = AArch64::STR_ZZZZXI;
6465 }
6466 break;
6467 }
6468 assert(Opc && "Unknown register class");
6469 MFI.setStackID(FI, StackID);
6470
6472 .addReg(SrcReg, getKillRegState(isKill))
6473 .addFrameIndex(FI);
6474
6475 if (Offset)
6476 MI.addImm(0);
6477 if (PNRReg.isValid())
6478 MI.addDef(PNRReg, RegState::Implicit);
6479 MI.addMemOperand(MMO);
6480}
6481
6484 MachineBasicBlock::iterator InsertBefore,
6485 const MCInstrDesc &MCID,
6486 Register DestReg, unsigned SubIdx0,
6487 unsigned SubIdx1, int FI,
6488 MachineMemOperand *MMO) {
6489 Register DestReg0 = DestReg;
6490 Register DestReg1 = DestReg;
6491 bool IsUndef = true;
6492 if (DestReg.isPhysical()) {
6493 DestReg0 = TRI.getSubReg(DestReg, SubIdx0);
6494 SubIdx0 = 0;
6495 DestReg1 = TRI.getSubReg(DestReg, SubIdx1);
6496 SubIdx1 = 0;
6497 IsUndef = false;
6498 }
6499 BuildMI(MBB, InsertBefore, DebugLoc(), MCID)
6500 .addReg(DestReg0, RegState::Define | getUndefRegState(IsUndef), SubIdx0)
6501 .addReg(DestReg1, RegState::Define | getUndefRegState(IsUndef), SubIdx1)
6502 .addFrameIndex(FI)
6503 .addImm(0)
6504 .addMemOperand(MMO);
6505}
6506
6509 Register DestReg, int FI,
6510 const TargetRegisterClass *RC,
6511 Register VReg, unsigned SubReg,
6512 MachineInstr::MIFlag Flags) const {
6513 MachineFunction &MF = *MBB.getParent();
6514 MachineFrameInfo &MFI = MF.getFrameInfo();
6516 MachineMemOperand *MMO =
6518 MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
6519
6520 unsigned Opc = 0;
6521 bool Offset = true;
6522 unsigned StackID = TargetStackID::Default;
6524 switch (TRI.getSpillSize(*RC)) {
6525 case 1:
6526 if (AArch64::FPR8RegClass.hasSubClassEq(RC))
6527 Opc = AArch64::LDRBui;
6528 break;
6529 case 2: {
6530 bool IsPNR = AArch64::PNRRegClass.hasSubClassEq(RC);
6531 if (AArch64::FPR16RegClass.hasSubClassEq(RC))
6532 Opc = AArch64::LDRHui;
6533 else if (IsPNR || AArch64::PPRRegClass.hasSubClassEq(RC)) {
6534 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6535 "Unexpected register load without SVE load instructions");
6536 if (IsPNR)
6537 PNRReg = DestReg;
6538 Opc = AArch64::LDR_PXI;
6540 }
6541 break;
6542 }
6543 case 4:
6544 if (AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
6545 Opc = AArch64::LDRWui;
6546 if (DestReg.isVirtual())
6547 MF.getRegInfo().constrainRegClass(DestReg, &AArch64::GPR32RegClass);
6548 else
6549 assert(DestReg != AArch64::WSP);
6550 } else if (AArch64::FPR32RegClass.hasSubClassEq(RC))
6551 Opc = AArch64::LDRSui;
6552 else if (AArch64::PPR2RegClass.hasSubClassEq(RC)) {
6553 Opc = AArch64::LDR_PPXI;
6555 }
6556 break;
6557 case 8:
6558 if (AArch64::GPR64allRegClass.hasSubClassEq(RC)) {
6559 Opc = AArch64::LDRXui;
6560 if (DestReg.isVirtual())
6561 MF.getRegInfo().constrainRegClass(DestReg, &AArch64::GPR64RegClass);
6562 else
6563 assert(DestReg != AArch64::SP);
6564 } else if (AArch64::FPR64RegClass.hasSubClassEq(RC)) {
6565 Opc = AArch64::LDRDui;
6566 } else if (AArch64::WSeqPairsClassRegClass.hasSubClassEq(RC)) {
6568 get(AArch64::LDPWi), DestReg, AArch64::sube32,
6569 AArch64::subo32, FI, MMO);
6570 return;
6571 }
6572 break;
6573 case 16:
6574 if (AArch64::FPR128RegClass.hasSubClassEq(RC))
6575 Opc = AArch64::LDRQui;
6576 else if (AArch64::DDRegClass.hasSubClassEq(RC)) {
6577 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6578 Opc = AArch64::LD1Twov1d;
6579 Offset = false;
6580 } else if (AArch64::XSeqPairsClassRegClass.hasSubClassEq(RC)) {
6582 get(AArch64::LDPXi), DestReg, AArch64::sube64,
6583 AArch64::subo64, FI, MMO);
6584 return;
6585 } else if (AArch64::ZPRRegClass.hasSubClassEq(RC)) {
6586 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6587 "Unexpected register load without SVE load instructions");
6588 Opc = AArch64::LDR_ZXI;
6590 }
6591 break;
6592 case 24:
6593 if (AArch64::DDDRegClass.hasSubClassEq(RC)) {
6594 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6595 Opc = AArch64::LD1Threev1d;
6596 Offset = false;
6597 }
6598 break;
6599 case 32:
6600 if (AArch64::DDDDRegClass.hasSubClassEq(RC)) {
6601 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6602 Opc = AArch64::LD1Fourv1d;
6603 Offset = false;
6604 } else if (AArch64::QQRegClass.hasSubClassEq(RC)) {
6605 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6606 Opc = AArch64::LD1Twov2d;
6607 Offset = false;
6608 } else if (AArch64::ZPR2StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6609 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6610 "Unexpected register load without SVE load instructions");
6611 Opc = AArch64::LDR_ZZXI_STRIDED_CONTIGUOUS;
6613 } else if (AArch64::ZPR2RegClass.hasSubClassEq(RC)) {
6614 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6615 "Unexpected register load without SVE load instructions");
6616 Opc = AArch64::LDR_ZZXI;
6618 }
6619 break;
6620 case 48:
6621 if (AArch64::QQQRegClass.hasSubClassEq(RC)) {
6622 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6623 Opc = AArch64::LD1Threev2d;
6624 Offset = false;
6625 } else if (AArch64::ZPR3RegClass.hasSubClassEq(RC)) {
6626 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6627 "Unexpected register load without SVE load instructions");
6628 Opc = AArch64::LDR_ZZZXI;
6630 }
6631 break;
6632 case 64:
6633 if (AArch64::QQQQRegClass.hasSubClassEq(RC)) {
6634 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6635 Opc = AArch64::LD1Fourv2d;
6636 Offset = false;
6637 } else if (AArch64::ZPR4StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6638 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6639 "Unexpected register load without SVE load instructions");
6640 Opc = AArch64::LDR_ZZZZXI_STRIDED_CONTIGUOUS;
6642 } else if (AArch64::ZPR4RegClass.hasSubClassEq(RC)) {
6643 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6644 "Unexpected register load without SVE load instructions");
6645 Opc = AArch64::LDR_ZZZZXI;
6647 }
6648 break;
6649 }
6650
6651 assert(Opc && "Unknown register class");
6652 MFI.setStackID(FI, StackID);
6653
6655 .addReg(DestReg, getDefRegState(true))
6656 .addFrameIndex(FI);
6657 if (Offset)
6658 MI.addImm(0);
6659 if (PNRReg.isValid() && !PNRReg.isVirtual())
6660 MI.addDef(PNRReg, RegState::Implicit);
6661 MI.addMemOperand(MMO);
6662}
6663
6665 const MachineInstr &UseMI,
6666 const TargetRegisterInfo *TRI) {
6667 return any_of(instructionsWithoutDebug(std::next(DefMI.getIterator()),
6668 UseMI.getIterator()),
6669 [TRI](const MachineInstr &I) {
6670 return I.modifiesRegister(AArch64::NZCV, TRI) ||
6671 I.readsRegister(AArch64::NZCV, TRI);
6672 });
6673}
6674
6675void AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(
6676 const StackOffset &Offset, int64_t &ByteSized, int64_t &VGSized) {
6677 // The smallest scalable element supported by scaled SVE addressing
6678 // modes are predicates, which are 2 scalable bytes in size. So the scalable
6679 // byte offset must always be a multiple of 2.
6680 assert(Offset.getScalable() % 2 == 0 && "Invalid frame offset");
6681
6682 // VGSized offsets are divided by '2', because the VG register is the
6683 // the number of 64bit granules as opposed to 128bit vector chunks,
6684 // which is how the 'n' in e.g. MVT::nxv1i8 is modelled.
6685 // So, for a stack offset of 16 MVT::nxv1i8's, the size is n x 16 bytes.
6686 // VG = n * 2 and the dwarf offset must be VG * 8 bytes.
6687 ByteSized = Offset.getFixed();
6688 VGSized = Offset.getScalable() / 2;
6689}
6690
6691/// Returns the offset in parts to which this frame offset can be
6692/// decomposed for the purpose of describing a frame offset.
6693/// For non-scalable offsets this is simply its byte size.
6694void AArch64InstrInfo::decomposeStackOffsetForFrameOffsets(
6695 const StackOffset &Offset, int64_t &NumBytes, int64_t &NumPredicateVectors,
6696 int64_t &NumDataVectors) {
6697 // The smallest scalable element supported by scaled SVE addressing
6698 // modes are predicates, which are 2 scalable bytes in size. So the scalable
6699 // byte offset must always be a multiple of 2.
6700 assert(Offset.getScalable() % 2 == 0 && "Invalid frame offset");
6701
6702 NumBytes = Offset.getFixed();
6703 NumDataVectors = 0;
6704 NumPredicateVectors = Offset.getScalable() / 2;
6705 // This method is used to get the offsets to adjust the frame offset.
6706 // If the function requires ADDPL to be used and needs more than two ADDPL
6707 // instructions, part of the offset is folded into NumDataVectors so that it
6708 // uses ADDVL for part of it, reducing the number of ADDPL instructions.
6709 if (NumPredicateVectors % 8 == 0 || NumPredicateVectors < -64 ||
6710 NumPredicateVectors > 62) {
6711 NumDataVectors = NumPredicateVectors / 8;
6712 NumPredicateVectors -= NumDataVectors * 8;
6713 }
6714}
6715
6716// Convenience function to create a DWARF expression for: Constant `Operation`.
6717// This helper emits compact sequences for common cases. For example, for`-15
6718// DW_OP_plus`, this helper would create DW_OP_lit15 DW_OP_minus.
6721 if (Operation == dwarf::DW_OP_plus && Constant < 0 && -Constant <= 31) {
6722 // -Constant (1 to 31)
6723 Expr.push_back(dwarf::DW_OP_lit0 - Constant);
6724 Operation = dwarf::DW_OP_minus;
6725 } else if (Constant >= 0 && Constant <= 31) {
6726 // Literal value 0 to 31
6727 Expr.push_back(dwarf::DW_OP_lit0 + Constant);
6728 } else {
6729 // Signed constant
6730 Expr.push_back(dwarf::DW_OP_consts);
6732 }
6733 return Expr.push_back(Operation);
6734}
6735
6736// Convenience function to create a DWARF expression for a register.
6737static void appendReadRegExpr(SmallVectorImpl<char> &Expr, unsigned RegNum) {
6738 Expr.push_back((char)dwarf::DW_OP_bregx);
6740 Expr.push_back(0);
6741}
6742
6743// Convenience function to create a DWARF expression for loading a register from
6744// a CFA offset.
6746 int64_t OffsetFromDefCFA) {
6747 // This assumes the top of the DWARF stack contains the CFA.
6748 Expr.push_back(dwarf::DW_OP_dup);
6749 // Add the offset to the register.
6750 appendConstantExpr(Expr, OffsetFromDefCFA, dwarf::DW_OP_plus);
6751 // Dereference the address (loads a 64 bit value)..
6752 Expr.push_back(dwarf::DW_OP_deref);
6753}
6754
6755// Convenience function to create a comment for
6756// (+/-) NumBytes (* RegScale)?
6757static void appendOffsetComment(int NumBytes, llvm::raw_string_ostream &Comment,
6758 StringRef RegScale = {}) {
6759 if (NumBytes) {
6760 Comment << (NumBytes < 0 ? " - " : " + ") << std::abs(NumBytes);
6761 if (!RegScale.empty())
6762 Comment << ' ' << RegScale;
6763 }
6764}
6765
6766// Creates an MCCFIInstruction:
6767// { DW_CFA_def_cfa_expression, ULEB128 (sizeof expr), expr }
6769 unsigned Reg,
6770 const StackOffset &Offset) {
6771 int64_t NumBytes, NumVGScaledBytes;
6772 AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(Offset, NumBytes,
6773 NumVGScaledBytes);
6774 std::string CommentBuffer;
6775 llvm::raw_string_ostream Comment(CommentBuffer);
6776
6777 if (Reg == AArch64::SP)
6778 Comment << "sp";
6779 else if (Reg == AArch64::FP)
6780 Comment << "fp";
6781 else
6782 Comment << printReg(Reg, &TRI);
6783
6784 // Build up the expression (Reg + NumBytes + VG * NumVGScaledBytes)
6785 SmallString<64> Expr;
6786 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
6787 assert(DwarfReg <= 31 && "DwarfReg out of bounds (0..31)");
6788 // Reg + NumBytes
6789 Expr.push_back(dwarf::DW_OP_breg0 + DwarfReg);
6790 appendLEB128<LEB128Sign::Signed>(Expr, NumBytes);
6791 appendOffsetComment(NumBytes, Comment);
6792 if (NumVGScaledBytes) {
6793 // + VG * NumVGScaledBytes
6794 appendOffsetComment(NumVGScaledBytes, Comment, "* VG");
6795 appendReadRegExpr(Expr, TRI.getDwarfRegNum(AArch64::VG, true));
6796 appendConstantExpr(Expr, NumVGScaledBytes, dwarf::DW_OP_mul);
6797 Expr.push_back(dwarf::DW_OP_plus);
6798 }
6799
6800 // Wrap this into DW_CFA_def_cfa.
6801 SmallString<64> DefCfaExpr;
6802 DefCfaExpr.push_back(dwarf::DW_CFA_def_cfa_expression);
6803 appendLEB128<LEB128Sign::Unsigned>(DefCfaExpr, Expr.size());
6804 DefCfaExpr.append(Expr.str());
6805 return MCCFIInstruction::createEscape(nullptr, DefCfaExpr.str(), SMLoc(),
6806 Comment.str());
6807}
6808
6810 unsigned FrameReg, unsigned Reg,
6811 const StackOffset &Offset,
6812 bool LastAdjustmentWasScalable) {
6813 if (Offset.getScalable())
6814 return createDefCFAExpression(TRI, Reg, Offset);
6815
6816 if (FrameReg == Reg && !LastAdjustmentWasScalable)
6817 return MCCFIInstruction::cfiDefCfaOffset(nullptr, int(Offset.getFixed()));
6818
6819 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
6820 return MCCFIInstruction::cfiDefCfa(nullptr, DwarfReg, (int)Offset.getFixed());
6821}
6822
6825 const StackOffset &OffsetFromDefCFA,
6826 std::optional<int64_t> IncomingVGOffsetFromDefCFA) {
6827 int64_t NumBytes, NumVGScaledBytes;
6828 AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(
6829 OffsetFromDefCFA, NumBytes, NumVGScaledBytes);
6830
6831 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
6832
6833 // Non-scalable offsets can use DW_CFA_offset directly.
6834 if (!NumVGScaledBytes)
6835 return MCCFIInstruction::createOffset(nullptr, DwarfReg, NumBytes);
6836
6837 std::string CommentBuffer;
6838 llvm::raw_string_ostream Comment(CommentBuffer);
6839 Comment << printReg(Reg, &TRI) << " @ cfa";
6840
6841 // Build up expression (CFA + VG * NumVGScaledBytes + NumBytes)
6842 assert(NumVGScaledBytes && "Expected scalable offset");
6843 SmallString<64> OffsetExpr;
6844 // + VG * NumVGScaledBytes
6845 StringRef VGRegScale;
6846 if (IncomingVGOffsetFromDefCFA) {
6847 appendLoadRegExpr(OffsetExpr, *IncomingVGOffsetFromDefCFA);
6848 VGRegScale = "* IncomingVG";
6849 } else {
6850 appendReadRegExpr(OffsetExpr, TRI.getDwarfRegNum(AArch64::VG, true));
6851 VGRegScale = "* VG";
6852 }
6853 appendConstantExpr(OffsetExpr, NumVGScaledBytes, dwarf::DW_OP_mul);
6854 appendOffsetComment(NumVGScaledBytes, Comment, VGRegScale);
6855 OffsetExpr.push_back(dwarf::DW_OP_plus);
6856 if (NumBytes) {
6857 // + NumBytes
6858 appendOffsetComment(NumBytes, Comment);
6859 appendConstantExpr(OffsetExpr, NumBytes, dwarf::DW_OP_plus);
6860 }
6861
6862 // Wrap this into DW_CFA_expression
6863 SmallString<64> CfaExpr;
6864 CfaExpr.push_back(dwarf::DW_CFA_expression);
6865 appendLEB128<LEB128Sign::Unsigned>(CfaExpr, DwarfReg);
6866 appendLEB128<LEB128Sign::Unsigned>(CfaExpr, OffsetExpr.size());
6867 CfaExpr.append(OffsetExpr.str());
6868
6869 return MCCFIInstruction::createEscape(nullptr, CfaExpr.str(), SMLoc(),
6870 Comment.str());
6871}
6872
6873// Helper function to emit a frame offset adjustment from a given
6874// pointer (SrcReg), stored into DestReg. This function is explicit
6875// in that it requires the opcode.
6878 const DebugLoc &DL, unsigned DestReg,
6879 unsigned SrcReg, int64_t Offset, unsigned Opc,
6880 const TargetInstrInfo *TII,
6881 MachineInstr::MIFlag Flag, bool NeedsWinCFI,
6882 bool *HasWinCFI, bool EmitCFAOffset,
6883 StackOffset CFAOffset, unsigned FrameReg) {
6884 int Sign = 1;
6885 unsigned MaxEncoding, ShiftSize;
6886 switch (Opc) {
6887 case AArch64::ADDXri:
6888 case AArch64::ADDSXri:
6889 case AArch64::SUBXri:
6890 case AArch64::SUBSXri:
6891 MaxEncoding = 0xfff;
6892 ShiftSize = 12;
6893 break;
6894 case AArch64::ADDVL_XXI:
6895 case AArch64::ADDPL_XXI:
6896 case AArch64::ADDSVL_XXI:
6897 case AArch64::ADDSPL_XXI:
6898 MaxEncoding = 31;
6899 ShiftSize = 0;
6900 if (Offset < 0) {
6901 MaxEncoding = 32;
6902 Sign = -1;
6903 Offset = -Offset;
6904 }
6905 break;
6906 default:
6907 llvm_unreachable("Unsupported opcode");
6908 }
6909
6910 // `Offset` can be in bytes or in "scalable bytes".
6911 int VScale = 1;
6912 if (Opc == AArch64::ADDVL_XXI || Opc == AArch64::ADDSVL_XXI)
6913 VScale = 16;
6914 else if (Opc == AArch64::ADDPL_XXI || Opc == AArch64::ADDSPL_XXI)
6915 VScale = 2;
6916
6917 // FIXME: If the offset won't fit in 24-bits, compute the offset into a
6918 // scratch register. If DestReg is a virtual register, use it as the
6919 // scratch register; otherwise, create a new virtual register (to be
6920 // replaced by the scavenger at the end of PEI). That case can be optimized
6921 // slightly if DestReg is SP which is always 16-byte aligned, so the scratch
6922 // register can be loaded with offset%8 and the add/sub can use an extending
6923 // instruction with LSL#3.
6924 // Currently the function handles any offsets but generates a poor sequence
6925 // of code.
6926 // assert(Offset < (1 << 24) && "unimplemented reg plus immediate");
6927
6928 const unsigned MaxEncodableValue = MaxEncoding << ShiftSize;
6929 Register TmpReg = DestReg;
6930 if (TmpReg == AArch64::XZR)
6931 TmpReg = MBB.getParent()->getRegInfo().createVirtualRegister(
6932 &AArch64::GPR64RegClass);
6933 do {
6934 uint64_t ThisVal = std::min<uint64_t>(Offset, MaxEncodableValue);
6935 unsigned LocalShiftSize = 0;
6936 if (ThisVal > MaxEncoding) {
6937 ThisVal = ThisVal >> ShiftSize;
6938 LocalShiftSize = ShiftSize;
6939 }
6940 assert((ThisVal >> ShiftSize) <= MaxEncoding &&
6941 "Encoding cannot handle value that big");
6942
6943 Offset -= ThisVal << LocalShiftSize;
6944 if (Offset == 0)
6945 TmpReg = DestReg;
6946 auto MBI = BuildMI(MBB, MBBI, DL, TII->get(Opc), TmpReg)
6947 .addReg(SrcReg)
6948 .addImm(Sign * (int)ThisVal);
6949 if (ShiftSize)
6950 MBI = MBI.addImm(
6952 MBI = MBI.setMIFlag(Flag);
6953
6954 auto Change =
6955 VScale == 1
6956 ? StackOffset::getFixed(ThisVal << LocalShiftSize)
6957 : StackOffset::getScalable(VScale * (ThisVal << LocalShiftSize));
6958 if (Sign == -1 || Opc == AArch64::SUBXri || Opc == AArch64::SUBSXri)
6959 CFAOffset += Change;
6960 else
6961 CFAOffset -= Change;
6962 if (EmitCFAOffset && DestReg == TmpReg) {
6963 MachineFunction &MF = *MBB.getParent();
6964 const TargetSubtargetInfo &STI = MF.getSubtarget();
6965 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
6966
6967 unsigned CFIIndex = MF.addFrameInst(
6968 createDefCFA(TRI, FrameReg, DestReg, CFAOffset, VScale != 1));
6969 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
6970 .addCFIIndex(CFIIndex)
6971 .setMIFlags(Flag);
6972 }
6973
6974 if (NeedsWinCFI) {
6975 int Imm = (int)(ThisVal << LocalShiftSize);
6976 if (VScale != 1 && DestReg == AArch64::SP) {
6977 if (HasWinCFI)
6978 *HasWinCFI = true;
6979 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_AllocZ))
6980 .addImm(ThisVal)
6981 .setMIFlag(Flag);
6982 } else if ((DestReg == AArch64::FP && SrcReg == AArch64::SP) ||
6983 (SrcReg == AArch64::FP && DestReg == AArch64::SP)) {
6984 assert(VScale == 1 && "Expected non-scalable operation");
6985 if (HasWinCFI)
6986 *HasWinCFI = true;
6987 if (Imm == 0)
6988 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_SetFP)).setMIFlag(Flag);
6989 else
6990 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_AddFP))
6991 .addImm(Imm)
6992 .setMIFlag(Flag);
6993 assert(Offset == 0 && "Expected remaining offset to be zero to "
6994 "emit a single SEH directive");
6995 } else if (DestReg == AArch64::SP) {
6996 assert(VScale == 1 && "Expected non-scalable operation");
6997 if (HasWinCFI)
6998 *HasWinCFI = true;
6999 assert(SrcReg == AArch64::SP && "Unexpected SrcReg for SEH_StackAlloc");
7000 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
7001 .addImm(Imm)
7002 .setMIFlag(Flag);
7003 }
7004 }
7005
7006 SrcReg = TmpReg;
7007 } while (Offset);
7008}
7009
7012 unsigned DestReg, unsigned SrcReg,
7014 MachineInstr::MIFlag Flag, bool SetNZCV,
7015 bool NeedsWinCFI, bool *HasWinCFI,
7016 bool EmitCFAOffset, StackOffset CFAOffset,
7017 unsigned FrameReg) {
7018 // If a function is marked as arm_locally_streaming, then the runtime value of
7019 // vscale in the prologue/epilogue is different the runtime value of vscale
7020 // in the function's body. To avoid having to consider multiple vscales,
7021 // we can use `addsvl` to allocate any scalable stack-slots, which under
7022 // most circumstances will be only locals, not callee-save slots.
7023 const Function &F = MBB.getParent()->getFunction();
7024 bool UseSVL = F.hasFnAttribute("aarch64_pstate_sm_body");
7025
7026 int64_t Bytes, NumPredicateVectors, NumDataVectors;
7027 AArch64InstrInfo::decomposeStackOffsetForFrameOffsets(
7028 Offset, Bytes, NumPredicateVectors, NumDataVectors);
7029
7030 // Insert ADDSXri for scalable offset at the end.
7031 bool NeedsFinalDefNZCV = SetNZCV && (NumPredicateVectors || NumDataVectors);
7032 if (NeedsFinalDefNZCV)
7033 SetNZCV = false;
7034
7035 // First emit non-scalable frame offsets, or a simple 'mov'.
7036 if (Bytes || (!Offset && SrcReg != DestReg)) {
7037 assert((DestReg != AArch64::SP || Bytes % 8 == 0) &&
7038 "SP increment/decrement not 8-byte aligned");
7039 unsigned Opc = SetNZCV ? AArch64::ADDSXri : AArch64::ADDXri;
7040 if (Bytes < 0) {
7041 Bytes = -Bytes;
7042 Opc = SetNZCV ? AArch64::SUBSXri : AArch64::SUBXri;
7043 }
7044 emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, Bytes, Opc, TII, Flag,
7045 NeedsWinCFI, HasWinCFI, EmitCFAOffset, CFAOffset,
7046 FrameReg);
7047 CFAOffset += (Opc == AArch64::ADDXri || Opc == AArch64::ADDSXri)
7048 ? StackOffset::getFixed(-Bytes)
7049 : StackOffset::getFixed(Bytes);
7050 SrcReg = DestReg;
7051 FrameReg = DestReg;
7052 }
7053
7054 assert(!(NeedsWinCFI && NumPredicateVectors) &&
7055 "WinCFI can't allocate fractions of an SVE data vector");
7056
7057 if (NumDataVectors) {
7058 emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, NumDataVectors,
7059 UseSVL ? AArch64::ADDSVL_XXI : AArch64::ADDVL_XXI, TII,
7060 Flag, NeedsWinCFI, HasWinCFI, EmitCFAOffset, CFAOffset,
7061 FrameReg);
7062 CFAOffset += StackOffset::getScalable(-NumDataVectors * 16);
7063 SrcReg = DestReg;
7064 }
7065
7066 if (NumPredicateVectors) {
7067 assert(DestReg != AArch64::SP && "Unaligned access to SP");
7068 emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, NumPredicateVectors,
7069 UseSVL ? AArch64::ADDSPL_XXI : AArch64::ADDPL_XXI, TII,
7070 Flag, NeedsWinCFI, HasWinCFI, EmitCFAOffset, CFAOffset,
7071 FrameReg);
7072 }
7073
7074 if (NeedsFinalDefNZCV)
7075 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ADDSXri), DestReg)
7076 .addReg(DestReg)
7077 .addImm(0)
7078 .addImm(0);
7079}
7080
7083 int FrameIndex, MachineInstr *&CopyMI, LiveIntervals *LIS,
7084 VirtRegMap *VRM) const {
7086 // This is a bit of a hack. Consider this instruction:
7087 //
7088 // %0 = COPY %sp; GPR64all:%0
7089 //
7090 // We explicitly chose GPR64all for the virtual register so such a copy might
7091 // be eliminated by RegisterCoalescer. However, that may not be possible, and
7092 // %0 may even spill. We can't spill %sp, and since it is in the GPR64all
7093 // register class, TargetInstrInfo::foldMemoryOperand() is going to try.
7094 //
7095 // To prevent that, we are going to constrain the %0 register class here.
7096 if (MI.isFullCopy()) {
7097 Register DstReg = MI.getOperand(0).getReg();
7098 Register SrcReg = MI.getOperand(1).getReg();
7099 if (SrcReg == AArch64::SP && DstReg.isVirtual()) {
7100 MF.getRegInfo().constrainRegClass(DstReg, &AArch64::GPR64RegClass);
7101 return nullptr;
7102 }
7103 if (DstReg == AArch64::SP && SrcReg.isVirtual()) {
7104 MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR64RegClass);
7105 return nullptr;
7106 }
7107 // Nothing can folded with copy from/to NZCV.
7108 if (SrcReg == AArch64::NZCV || DstReg == AArch64::NZCV)
7109 return nullptr;
7110 }
7111
7112 // Handle the case where a copy is being spilled or filled but the source
7113 // and destination register class don't match. For example:
7114 //
7115 // %0 = COPY %xzr; GPR64common:%0
7116 //
7117 // In this case we can still safely fold away the COPY and generate the
7118 // following spill code:
7119 //
7120 // STRXui %xzr, %stack.0
7121 //
7122 // This also eliminates spilled cross register class COPYs (e.g. between x and
7123 // d regs) of the same size. For example:
7124 //
7125 // %0 = COPY %1; GPR64:%0, FPR64:%1
7126 //
7127 // will be filled as
7128 //
7129 // LDRDui %0, fi<#0>
7130 //
7131 // instead of
7132 //
7133 // LDRXui %Temp, fi<#0>
7134 // %0 = FMOV %Temp
7135 //
7136 if (MI.isCopy() && Ops.size() == 1 &&
7137 // Make sure we're only folding the explicit COPY defs/uses.
7138 (Ops[0] == 0 || Ops[0] == 1)) {
7139 bool IsSpill = Ops[0] == 0;
7140 bool IsFill = !IsSpill;
7142 const MachineRegisterInfo &MRI = MF.getRegInfo();
7143 MachineBasicBlock &MBB = *MI.getParent();
7144 const MachineOperand &DstMO = MI.getOperand(0);
7145 const MachineOperand &SrcMO = MI.getOperand(1);
7146 Register DstReg = DstMO.getReg();
7147 Register SrcReg = SrcMO.getReg();
7148 // This is slightly expensive to compute for physical regs since
7149 // getMinimalPhysRegClass is slow.
7150 auto getRegClass = [&](unsigned Reg) {
7151 return Register::isVirtualRegister(Reg) ? MRI.getRegClass(Reg)
7152 : TRI.getMinimalPhysRegClass(Reg);
7153 };
7154
7155 if (DstMO.getSubReg() == 0 && SrcMO.getSubReg() == 0) {
7156 assert(TRI.getRegSizeInBits(*getRegClass(DstReg)) ==
7157 TRI.getRegSizeInBits(*getRegClass(SrcReg)) &&
7158 "Mismatched register size in non subreg COPY");
7159 if (IsSpill)
7160 storeRegToStackSlot(MBB, InsertPt, SrcReg, SrcMO.isKill(), FrameIndex,
7161 getRegClass(SrcReg), Register());
7162 else
7163 loadRegFromStackSlot(MBB, InsertPt, DstReg, FrameIndex,
7164 getRegClass(DstReg), Register());
7165 return &*--InsertPt;
7166 }
7167
7168 // Handle cases like spilling def of:
7169 //
7170 // %0:sub_32<def,read-undef> = COPY %wzr; GPR64common:%0
7171 //
7172 // where the physical register source can be widened and stored to the full
7173 // virtual reg destination stack slot, in this case producing:
7174 //
7175 // STRXui %xzr, %stack.0
7176 //
7177 if (IsSpill && DstMO.isUndef() && SrcReg == AArch64::WZR &&
7178 TRI.getRegSizeInBits(*getRegClass(DstReg)) == 64) {
7179 assert(SrcMO.getSubReg() == 0 &&
7180 "Unexpected subreg on physical register");
7181 storeRegToStackSlot(MBB, InsertPt, AArch64::XZR, SrcMO.isKill(),
7182 FrameIndex, &AArch64::GPR64RegClass, Register());
7183 return &*--InsertPt;
7184 }
7185
7186 // Handle cases like filling use of:
7187 //
7188 // %0:sub_32<def,read-undef> = COPY %1; GPR64:%0, GPR32:%1
7189 //
7190 // where we can load the full virtual reg source stack slot, into the subreg
7191 // destination, in this case producing:
7192 //
7193 // LDRWui %0:sub_32<def,read-undef>, %stack.0
7194 //
7195 if (IsFill && SrcMO.getSubReg() == 0 && DstMO.isUndef()) {
7196 const TargetRegisterClass *FillRC = nullptr;
7197 switch (DstMO.getSubReg()) {
7198 default:
7199 break;
7200 case AArch64::sub_32:
7201 if (AArch64::GPR64RegClass.hasSubClassEq(getRegClass(DstReg)))
7202 FillRC = &AArch64::GPR32RegClass;
7203 break;
7204 case AArch64::ssub:
7205 FillRC = &AArch64::FPR32RegClass;
7206 break;
7207 case AArch64::dsub:
7208 FillRC = &AArch64::FPR64RegClass;
7209 break;
7210 }
7211
7212 if (FillRC) {
7213 assert(TRI.getRegSizeInBits(*getRegClass(SrcReg)) ==
7214 TRI.getRegSizeInBits(*FillRC) &&
7215 "Mismatched regclass size on folded subreg COPY");
7216 loadRegFromStackSlot(MBB, InsertPt, DstReg, FrameIndex, FillRC,
7217 Register());
7218 MachineInstr &LoadMI = *--InsertPt;
7219 MachineOperand &LoadDst = LoadMI.getOperand(0);
7220 assert(LoadDst.getSubReg() == 0 && "unexpected subreg on fill load");
7221 LoadDst.setSubReg(DstMO.getSubReg());
7222 LoadDst.setIsUndef();
7223 return &LoadMI;
7224 }
7225 }
7226 }
7227
7228 // Cannot fold.
7229 return nullptr;
7230}
7231
7233 StackOffset &SOffset,
7234 bool *OutUseUnscaledOp,
7235 unsigned *OutUnscaledOp,
7236 int64_t *EmittableOffset) {
7237 // Set output values in case of early exit.
7238 if (EmittableOffset)
7239 *EmittableOffset = 0;
7240 if (OutUseUnscaledOp)
7241 *OutUseUnscaledOp = false;
7242 if (OutUnscaledOp)
7243 *OutUnscaledOp = 0;
7244
7245 // Exit early for structured vector spills/fills as they can't take an
7246 // immediate offset.
7247 switch (MI.getOpcode()) {
7248 default:
7249 break;
7250 case AArch64::LD1Rv1d:
7251 case AArch64::LD1Rv2s:
7252 case AArch64::LD1Rv2d:
7253 case AArch64::LD1Rv4h:
7254 case AArch64::LD1Rv4s:
7255 case AArch64::LD1Rv8b:
7256 case AArch64::LD1Rv8h:
7257 case AArch64::LD1Rv16b:
7258 case AArch64::LD1Twov2d:
7259 case AArch64::LD1Threev2d:
7260 case AArch64::LD1Fourv2d:
7261 case AArch64::LD1Twov1d:
7262 case AArch64::LD1Threev1d:
7263 case AArch64::LD1Fourv1d:
7264 case AArch64::ST1Twov2d:
7265 case AArch64::ST1Threev2d:
7266 case AArch64::ST1Fourv2d:
7267 case AArch64::ST1Twov1d:
7268 case AArch64::ST1Threev1d:
7269 case AArch64::ST1Fourv1d:
7270 case AArch64::ST1i8:
7271 case AArch64::ST1i16:
7272 case AArch64::ST1i32:
7273 case AArch64::ST1i64:
7274 case AArch64::IRG:
7275 case AArch64::IRGstack:
7276 case AArch64::STGloop:
7277 case AArch64::STZGloop:
7279 }
7280
7281 // Get the min/max offset and the scale.
7282 TypeSize ScaleValue(0U, false), Width(0U, false);
7283 int64_t MinOff, MaxOff;
7284 if (!AArch64InstrInfo::getMemOpInfo(MI.getOpcode(), ScaleValue, Width, MinOff,
7285 MaxOff))
7286 llvm_unreachable("unhandled opcode in isAArch64FrameOffsetLegal");
7287
7288 // Construct the complete offset.
7289 bool IsMulVL = ScaleValue.isScalable();
7290 unsigned Scale = ScaleValue.getKnownMinValue();
7291 int64_t Offset = IsMulVL ? SOffset.getScalable() : SOffset.getFixed();
7292
7293 const MachineOperand &ImmOpnd =
7294 MI.getOperand(AArch64InstrInfo::getLoadStoreImmIdx(MI.getOpcode()));
7295 Offset += ImmOpnd.getImm() * Scale;
7296
7297 // If the offset doesn't match the scale, we rewrite the instruction to
7298 // use the unscaled instruction instead. Likewise, if we have a negative
7299 // offset and there is an unscaled op to use.
7300 std::optional<unsigned> UnscaledOp =
7302 bool useUnscaledOp = UnscaledOp && (Offset % Scale || Offset < 0);
7303 if (useUnscaledOp &&
7304 !AArch64InstrInfo::getMemOpInfo(*UnscaledOp, ScaleValue, Width, MinOff,
7305 MaxOff))
7306 llvm_unreachable("unhandled opcode in isAArch64FrameOffsetLegal");
7307
7308 Scale = ScaleValue.getKnownMinValue();
7309 assert(IsMulVL == ScaleValue.isScalable() &&
7310 "Unscaled opcode has different value for scalable");
7311
7312 int64_t Remainder = Offset % Scale;
7313 assert(!(Remainder && useUnscaledOp) &&
7314 "Cannot have remainder when using unscaled op");
7315
7316 assert(MinOff < MaxOff && "Unexpected Min/Max offsets");
7317 int64_t NewOffset = Offset / Scale;
7318 if (MinOff <= NewOffset && NewOffset <= MaxOff)
7319 Offset = Remainder;
7320 else {
7321 // Try to minimise the number of instructions required to materialise the
7322 // offset calculation. Specifically, for fixed offsets, if masking out the
7323 // low 12 bits leaves a legal add immediate, we can realise the offset
7324 // calculation with a single add instruction. Whenever this is possible,
7325 // prefer this split.
7326 int64_t HighPart = Offset & ~0xFFF;
7327 int64_t LowPart = Offset & 0xFFF;
7328 int64_t LowScaled = LowPart / Scale;
7329 if (!IsMulVL && NewOffset >= 0 && LowPart % Scale == 0 &&
7330 MinOff <= LowScaled && LowScaled <= MaxOff &&
7332 NewOffset = LowScaled;
7333 Offset = HighPart;
7334 } else {
7335 // Default to a greedy split: take the memop immediate to be maximum /
7336 // minimum expressible offset and materialise the remainder.
7337 NewOffset = NewOffset < 0 ? MinOff : MaxOff;
7338 Offset = Offset - (NewOffset * Scale);
7339 }
7340 }
7341
7342 if (EmittableOffset)
7343 *EmittableOffset = NewOffset;
7344 if (OutUseUnscaledOp)
7345 *OutUseUnscaledOp = useUnscaledOp;
7346 if (OutUnscaledOp && UnscaledOp)
7347 *OutUnscaledOp = *UnscaledOp;
7348
7349 if (IsMulVL)
7350 SOffset = StackOffset::get(SOffset.getFixed(), Offset);
7351 else
7352 SOffset = StackOffset::get(Offset, SOffset.getScalable());
7354 (SOffset ? 0 : AArch64FrameOffsetIsLegal);
7355}
7356
7358 unsigned FrameReg, StackOffset &Offset,
7359 const AArch64InstrInfo *TII) {
7360 unsigned Opcode = MI.getOpcode();
7361 unsigned ImmIdx = FrameRegIdx + 1;
7362
7363 if (Opcode == AArch64::ADDSXri || Opcode == AArch64::ADDXri) {
7364 Offset += StackOffset::getFixed(MI.getOperand(ImmIdx).getImm());
7365 emitFrameOffset(*MI.getParent(), MI, MI.getDebugLoc(),
7366 MI.getOperand(0).getReg(), FrameReg, Offset, TII,
7367 MachineInstr::NoFlags, (Opcode == AArch64::ADDSXri));
7368 MI.eraseFromParent();
7369 Offset = StackOffset();
7370 return true;
7371 }
7372
7373 int64_t NewOffset;
7374 unsigned UnscaledOp;
7375 bool UseUnscaledOp;
7376 int Status = isAArch64FrameOffsetLegal(MI, Offset, &UseUnscaledOp,
7377 &UnscaledOp, &NewOffset);
7380 // Replace the FrameIndex with FrameReg.
7381 MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
7382 if (UseUnscaledOp)
7383 MI.setDesc(TII->get(UnscaledOp));
7384
7385 MI.getOperand(ImmIdx).ChangeToImmediate(NewOffset);
7386 return !Offset;
7387 }
7388
7389 return false;
7390}
7391
7397
7398MCInst AArch64InstrInfo::getNop() const { return MCInstBuilder(AArch64::NOP); }
7399
7400// AArch64 supports MachineCombiner.
7401bool AArch64InstrInfo::useMachineCombiner() const { return true; }
7402
7403// True when Opc sets flag
7404static bool isCombineInstrSettingFlag(unsigned Opc) {
7405 switch (Opc) {
7406 case AArch64::ADDSWrr:
7407 case AArch64::ADDSWri:
7408 case AArch64::ADDSXrr:
7409 case AArch64::ADDSXri:
7410 case AArch64::SUBSWrr:
7411 case AArch64::SUBSXrr:
7412 // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
7413 case AArch64::SUBSWri:
7414 case AArch64::SUBSXri:
7415 return true;
7416 default:
7417 break;
7418 }
7419 return false;
7420}
7421
7422// 32b Opcodes that can be combined with a MUL
7423static bool isCombineInstrCandidate32(unsigned Opc) {
7424 switch (Opc) {
7425 case AArch64::ADDWrr:
7426 case AArch64::ADDWri:
7427 case AArch64::SUBWrr:
7428 case AArch64::ADDSWrr:
7429 case AArch64::ADDSWri:
7430 case AArch64::SUBSWrr:
7431 // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
7432 case AArch64::SUBWri:
7433 case AArch64::SUBSWri:
7434 return true;
7435 default:
7436 break;
7437 }
7438 return false;
7439}
7440
7441// 64b Opcodes that can be combined with a MUL
7442static bool isCombineInstrCandidate64(unsigned Opc) {
7443 switch (Opc) {
7444 case AArch64::ADDXrr:
7445 case AArch64::ADDXri:
7446 case AArch64::SUBXrr:
7447 case AArch64::ADDSXrr:
7448 case AArch64::ADDSXri:
7449 case AArch64::SUBSXrr:
7450 // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
7451 case AArch64::SUBXri:
7452 case AArch64::SUBSXri:
7453 case AArch64::ADDv8i8:
7454 case AArch64::ADDv16i8:
7455 case AArch64::ADDv4i16:
7456 case AArch64::ADDv8i16:
7457 case AArch64::ADDv2i32:
7458 case AArch64::ADDv4i32:
7459 case AArch64::SUBv8i8:
7460 case AArch64::SUBv16i8:
7461 case AArch64::SUBv4i16:
7462 case AArch64::SUBv8i16:
7463 case AArch64::SUBv2i32:
7464 case AArch64::SUBv4i32:
7465 return true;
7466 default:
7467 break;
7468 }
7469 return false;
7470}
7471
7472// FP Opcodes that can be combined with a FMUL.
7473static bool isCombineInstrCandidateFP(const MachineInstr &Inst) {
7474 switch (Inst.getOpcode()) {
7475 default:
7476 break;
7477 case AArch64::FADDHrr:
7478 case AArch64::FADDSrr:
7479 case AArch64::FADDDrr:
7480 case AArch64::FADDv4f16:
7481 case AArch64::FADDv8f16:
7482 case AArch64::FADDv2f32:
7483 case AArch64::FADDv2f64:
7484 case AArch64::FADDv4f32:
7485 case AArch64::FSUBHrr:
7486 case AArch64::FSUBSrr:
7487 case AArch64::FSUBDrr:
7488 case AArch64::FSUBv4f16:
7489 case AArch64::FSUBv8f16:
7490 case AArch64::FSUBv2f32:
7491 case AArch64::FSUBv2f64:
7492 case AArch64::FSUBv4f32:
7494 // We can fuse FADD/FSUB with FMUL, if fusion is either allowed globally by
7495 // the target options or if FADD/FSUB has the contract fast-math flag.
7496 return Options.AllowFPOpFusion == FPOpFusion::Fast ||
7498 }
7499 return false;
7500}
7501
7502// Opcodes that can be combined with a MUL
7506
7507//
7508// Utility routine that checks if \param MO is defined by an
7509// \param CombineOpc instruction in the basic block \param MBB
7511 unsigned CombineOpc, unsigned ZeroReg = 0,
7512 bool CheckZeroReg = false) {
7513 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
7514 MachineInstr *MI = nullptr;
7515
7516 if (MO.isReg() && MO.getReg().isVirtual())
7517 MI = MRI.getUniqueVRegDef(MO.getReg());
7518 // And it needs to be in the trace (otherwise, it won't have a depth).
7519 if (!MI || MI->getParent() != &MBB || MI->getOpcode() != CombineOpc)
7520 return false;
7521 // Must only used by the user we combine with.
7522 if (!MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()))
7523 return false;
7524
7525 if (CheckZeroReg) {
7526 assert(MI->getNumOperands() >= 4 && MI->getOperand(0).isReg() &&
7527 MI->getOperand(1).isReg() && MI->getOperand(2).isReg() &&
7528 MI->getOperand(3).isReg() && "MAdd/MSub must have a least 4 regs");
7529 // The third input reg must be zero.
7530 if (MI->getOperand(3).getReg() != ZeroReg)
7531 return false;
7532 }
7533
7534 if (isCombineInstrSettingFlag(CombineOpc) &&
7535 MI->findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true) == -1)
7536 return false;
7537
7538 return true;
7539}
7540
7541//
7542// Is \param MO defined by an integer multiply and can be combined?
7544 unsigned MulOpc, unsigned ZeroReg) {
7545 return canCombine(MBB, MO, MulOpc, ZeroReg, true);
7546}
7547
7548//
7549// Is \param MO defined by a floating-point multiply and can be combined?
7551 unsigned MulOpc) {
7552 return canCombine(MBB, MO, MulOpc);
7553}
7554
7555// TODO: There are many more machine instruction opcodes to match:
7556// 1. Other data types (integer, vectors)
7557// 2. Other math / logic operations (xor, or)
7558// 3. Other forms of the same operation (intrinsics and other variants)
7559bool AArch64InstrInfo::isAssociativeAndCommutative(const MachineInstr &Inst,
7560 bool Invert) const {
7561 if (Invert)
7562 return false;
7563 switch (Inst.getOpcode()) {
7564 // == Floating-point types ==
7565 // -- Floating-point instructions --
7566 case AArch64::FADDHrr:
7567 case AArch64::FADDSrr:
7568 case AArch64::FADDDrr:
7569 case AArch64::FMULHrr:
7570 case AArch64::FMULSrr:
7571 case AArch64::FMULDrr:
7572 case AArch64::FMULX16:
7573 case AArch64::FMULX32:
7574 case AArch64::FMULX64:
7575 // -- Advanced SIMD instructions --
7576 case AArch64::FADDv4f16:
7577 case AArch64::FADDv8f16:
7578 case AArch64::FADDv2f32:
7579 case AArch64::FADDv4f32:
7580 case AArch64::FADDv2f64:
7581 case AArch64::FMULv4f16:
7582 case AArch64::FMULv8f16:
7583 case AArch64::FMULv2f32:
7584 case AArch64::FMULv4f32:
7585 case AArch64::FMULv2f64:
7586 case AArch64::FMULXv4f16:
7587 case AArch64::FMULXv8f16:
7588 case AArch64::FMULXv2f32:
7589 case AArch64::FMULXv4f32:
7590 case AArch64::FMULXv2f64:
7591 // -- SVE instructions --
7592 // Opcodes FMULX_ZZZ_? don't exist because there is no unpredicated FMULX
7593 // in the SVE instruction set (though there are predicated ones).
7594 case AArch64::FADD_ZZZ_H:
7595 case AArch64::FADD_ZZZ_S:
7596 case AArch64::FADD_ZZZ_D:
7597 case AArch64::FMUL_ZZZ_H:
7598 case AArch64::FMUL_ZZZ_S:
7599 case AArch64::FMUL_ZZZ_D:
7602
7603 // == Integer types ==
7604 // -- Base instructions --
7605 // Opcodes MULWrr and MULXrr don't exist because
7606 // `MUL <Wd>, <Wn>, <Wm>` and `MUL <Xd>, <Xn>, <Xm>` are aliases of
7607 // `MADD <Wd>, <Wn>, <Wm>, WZR` and `MADD <Xd>, <Xn>, <Xm>, XZR` respectively.
7608 // The machine-combiner does not support three-source-operands machine
7609 // instruction. So we cannot reassociate MULs.
7610 case AArch64::ADDWrr:
7611 case AArch64::ADDXrr:
7612 case AArch64::ANDWrr:
7613 case AArch64::ANDXrr:
7614 case AArch64::ORRWrr:
7615 case AArch64::ORRXrr:
7616 case AArch64::EORWrr:
7617 case AArch64::EORXrr:
7618 case AArch64::EONWrr:
7619 case AArch64::EONXrr:
7620 // -- Advanced SIMD instructions --
7621 // Opcodes MULv1i64 and MULv2i64 don't exist because there is no 64-bit MUL
7622 // in the Advanced SIMD instruction set.
7623 case AArch64::ADDv8i8:
7624 case AArch64::ADDv16i8:
7625 case AArch64::ADDv4i16:
7626 case AArch64::ADDv8i16:
7627 case AArch64::ADDv2i32:
7628 case AArch64::ADDv4i32:
7629 case AArch64::ADDv1i64:
7630 case AArch64::ADDv2i64:
7631 case AArch64::MULv8i8:
7632 case AArch64::MULv16i8:
7633 case AArch64::MULv4i16:
7634 case AArch64::MULv8i16:
7635 case AArch64::MULv2i32:
7636 case AArch64::MULv4i32:
7637 case AArch64::ANDv8i8:
7638 case AArch64::ANDv16i8:
7639 case AArch64::ORRv8i8:
7640 case AArch64::ORRv16i8:
7641 case AArch64::EORv8i8:
7642 case AArch64::EORv16i8:
7643 // -- SVE instructions --
7644 case AArch64::ADD_ZZZ_B:
7645 case AArch64::ADD_ZZZ_H:
7646 case AArch64::ADD_ZZZ_S:
7647 case AArch64::ADD_ZZZ_D:
7648 case AArch64::MUL_ZZZ_B:
7649 case AArch64::MUL_ZZZ_H:
7650 case AArch64::MUL_ZZZ_S:
7651 case AArch64::MUL_ZZZ_D:
7652 case AArch64::AND_ZZZ:
7653 case AArch64::ORR_ZZZ:
7654 case AArch64::EOR_ZZZ:
7655 return true;
7656
7657 default:
7658 return false;
7659 }
7660}
7661
7662/// Find instructions that can be turned into madd.
7664 SmallVectorImpl<unsigned> &Patterns) {
7665 unsigned Opc = Root.getOpcode();
7666 MachineBasicBlock &MBB = *Root.getParent();
7667 bool Found = false;
7668
7670 return false;
7672 int Cmp_NZCV =
7673 Root.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true);
7674 // When NZCV is live bail out.
7675 if (Cmp_NZCV == -1)
7676 return false;
7677 unsigned NewOpc = convertToNonFlagSettingOpc(Root);
7678 // When opcode can't change bail out.
7679 // CHECKME: do we miss any cases for opcode conversion?
7680 if (NewOpc == Opc)
7681 return false;
7682 Opc = NewOpc;
7683 }
7684
7685 auto setFound = [&](int Opcode, int Operand, unsigned ZeroReg,
7686 unsigned Pattern) {
7687 if (canCombineWithMUL(MBB, Root.getOperand(Operand), Opcode, ZeroReg)) {
7688 Patterns.push_back(Pattern);
7689 Found = true;
7690 }
7691 };
7692
7693 auto setVFound = [&](int Opcode, int Operand, unsigned Pattern) {
7694 if (canCombine(MBB, Root.getOperand(Operand), Opcode)) {
7695 Patterns.push_back(Pattern);
7696 Found = true;
7697 }
7698 };
7699
7701
7702 switch (Opc) {
7703 default:
7704 break;
7705 case AArch64::ADDWrr:
7706 assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
7707 "ADDWrr does not have register operands");
7708 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULADDW_OP1);
7709 setFound(AArch64::MADDWrrr, 2, AArch64::WZR, MCP::MULADDW_OP2);
7710 break;
7711 case AArch64::ADDXrr:
7712 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULADDX_OP1);
7713 setFound(AArch64::MADDXrrr, 2, AArch64::XZR, MCP::MULADDX_OP2);
7714 break;
7715 case AArch64::SUBWrr:
7716 setFound(AArch64::MADDWrrr, 2, AArch64::WZR, MCP::MULSUBW_OP2);
7717 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULSUBW_OP1);
7718 break;
7719 case AArch64::SUBXrr:
7720 setFound(AArch64::MADDXrrr, 2, AArch64::XZR, MCP::MULSUBX_OP2);
7721 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULSUBX_OP1);
7722 break;
7723 case AArch64::ADDWri:
7724 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULADDWI_OP1);
7725 break;
7726 case AArch64::ADDXri:
7727 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULADDXI_OP1);
7728 break;
7729 case AArch64::SUBWri:
7730 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULSUBWI_OP1);
7731 break;
7732 case AArch64::SUBXri:
7733 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULSUBXI_OP1);
7734 break;
7735 case AArch64::ADDv8i8:
7736 setVFound(AArch64::MULv8i8, 1, MCP::MULADDv8i8_OP1);
7737 setVFound(AArch64::MULv8i8, 2, MCP::MULADDv8i8_OP2);
7738 break;
7739 case AArch64::ADDv16i8:
7740 setVFound(AArch64::MULv16i8, 1, MCP::MULADDv16i8_OP1);
7741 setVFound(AArch64::MULv16i8, 2, MCP::MULADDv16i8_OP2);
7742 break;
7743 case AArch64::ADDv4i16:
7744 setVFound(AArch64::MULv4i16, 1, MCP::MULADDv4i16_OP1);
7745 setVFound(AArch64::MULv4i16, 2, MCP::MULADDv4i16_OP2);
7746 setVFound(AArch64::MULv4i16_indexed, 1, MCP::MULADDv4i16_indexed_OP1);
7747 setVFound(AArch64::MULv4i16_indexed, 2, MCP::MULADDv4i16_indexed_OP2);
7748 break;
7749 case AArch64::ADDv8i16:
7750 setVFound(AArch64::MULv8i16, 1, MCP::MULADDv8i16_OP1);
7751 setVFound(AArch64::MULv8i16, 2, MCP::MULADDv8i16_OP2);
7752 setVFound(AArch64::MULv8i16_indexed, 1, MCP::MULADDv8i16_indexed_OP1);
7753 setVFound(AArch64::MULv8i16_indexed, 2, MCP::MULADDv8i16_indexed_OP2);
7754 break;
7755 case AArch64::ADDv2i32:
7756 setVFound(AArch64::MULv2i32, 1, MCP::MULADDv2i32_OP1);
7757 setVFound(AArch64::MULv2i32, 2, MCP::MULADDv2i32_OP2);
7758 setVFound(AArch64::MULv2i32_indexed, 1, MCP::MULADDv2i32_indexed_OP1);
7759 setVFound(AArch64::MULv2i32_indexed, 2, MCP::MULADDv2i32_indexed_OP2);
7760 break;
7761 case AArch64::ADDv4i32:
7762 setVFound(AArch64::MULv4i32, 1, MCP::MULADDv4i32_OP1);
7763 setVFound(AArch64::MULv4i32, 2, MCP::MULADDv4i32_OP2);
7764 setVFound(AArch64::MULv4i32_indexed, 1, MCP::MULADDv4i32_indexed_OP1);
7765 setVFound(AArch64::MULv4i32_indexed, 2, MCP::MULADDv4i32_indexed_OP2);
7766 break;
7767 case AArch64::SUBv8i8:
7768 setVFound(AArch64::MULv8i8, 1, MCP::MULSUBv8i8_OP1);
7769 setVFound(AArch64::MULv8i8, 2, MCP::MULSUBv8i8_OP2);
7770 break;
7771 case AArch64::SUBv16i8:
7772 setVFound(AArch64::MULv16i8, 1, MCP::MULSUBv16i8_OP1);
7773 setVFound(AArch64::MULv16i8, 2, MCP::MULSUBv16i8_OP2);
7774 break;
7775 case AArch64::SUBv4i16:
7776 setVFound(AArch64::MULv4i16, 1, MCP::MULSUBv4i16_OP1);
7777 setVFound(AArch64::MULv4i16, 2, MCP::MULSUBv4i16_OP2);
7778 setVFound(AArch64::MULv4i16_indexed, 1, MCP::MULSUBv4i16_indexed_OP1);
7779 setVFound(AArch64::MULv4i16_indexed, 2, MCP::MULSUBv4i16_indexed_OP2);
7780 break;
7781 case AArch64::SUBv8i16:
7782 setVFound(AArch64::MULv8i16, 1, MCP::MULSUBv8i16_OP1);
7783 setVFound(AArch64::MULv8i16, 2, MCP::MULSUBv8i16_OP2);
7784 setVFound(AArch64::MULv8i16_indexed, 1, MCP::MULSUBv8i16_indexed_OP1);
7785 setVFound(AArch64::MULv8i16_indexed, 2, MCP::MULSUBv8i16_indexed_OP2);
7786 break;
7787 case AArch64::SUBv2i32:
7788 setVFound(AArch64::MULv2i32, 1, MCP::MULSUBv2i32_OP1);
7789 setVFound(AArch64::MULv2i32, 2, MCP::MULSUBv2i32_OP2);
7790 setVFound(AArch64::MULv2i32_indexed, 1, MCP::MULSUBv2i32_indexed_OP1);
7791 setVFound(AArch64::MULv2i32_indexed, 2, MCP::MULSUBv2i32_indexed_OP2);
7792 break;
7793 case AArch64::SUBv4i32:
7794 setVFound(AArch64::MULv4i32, 1, MCP::MULSUBv4i32_OP1);
7795 setVFound(AArch64::MULv4i32, 2, MCP::MULSUBv4i32_OP2);
7796 setVFound(AArch64::MULv4i32_indexed, 1, MCP::MULSUBv4i32_indexed_OP1);
7797 setVFound(AArch64::MULv4i32_indexed, 2, MCP::MULSUBv4i32_indexed_OP2);
7798 break;
7799 }
7800 return Found;
7801}
7802
7803bool AArch64InstrInfo::isAccumulationOpcode(unsigned Opcode) const {
7804 switch (Opcode) {
7805 default:
7806 break;
7807 case AArch64::UABALB_ZZZ_D:
7808 case AArch64::UABALB_ZZZ_H:
7809 case AArch64::UABALB_ZZZ_S:
7810 case AArch64::UABALT_ZZZ_D:
7811 case AArch64::UABALT_ZZZ_H:
7812 case AArch64::UABALT_ZZZ_S:
7813 case AArch64::SABALB_ZZZ_D:
7814 case AArch64::SABALB_ZZZ_S:
7815 case AArch64::SABALB_ZZZ_H:
7816 case AArch64::SABALT_ZZZ_D:
7817 case AArch64::SABALT_ZZZ_S:
7818 case AArch64::SABALT_ZZZ_H:
7819 case AArch64::UABALv16i8_v8i16:
7820 case AArch64::UABALv2i32_v2i64:
7821 case AArch64::UABALv4i16_v4i32:
7822 case AArch64::UABALv4i32_v2i64:
7823 case AArch64::UABALv8i16_v4i32:
7824 case AArch64::UABALv8i8_v8i16:
7825 case AArch64::UABAv16i8:
7826 case AArch64::UABAv2i32:
7827 case AArch64::UABAv4i16:
7828 case AArch64::UABAv4i32:
7829 case AArch64::UABAv8i16:
7830 case AArch64::UABAv8i8:
7831 case AArch64::SABALv16i8_v8i16:
7832 case AArch64::SABALv2i32_v2i64:
7833 case AArch64::SABALv4i16_v4i32:
7834 case AArch64::SABALv4i32_v2i64:
7835 case AArch64::SABALv8i16_v4i32:
7836 case AArch64::SABALv8i8_v8i16:
7837 case AArch64::SABAv16i8:
7838 case AArch64::SABAv2i32:
7839 case AArch64::SABAv4i16:
7840 case AArch64::SABAv4i32:
7841 case AArch64::SABAv8i16:
7842 case AArch64::SABAv8i8:
7843 return true;
7844 }
7845
7846 return false;
7847}
7848
7849unsigned AArch64InstrInfo::getAccumulationStartOpcode(
7850 unsigned AccumulationOpcode) const {
7851 switch (AccumulationOpcode) {
7852 default:
7853 llvm_unreachable("Unsupported accumulation Opcode!");
7854 case AArch64::UABALB_ZZZ_D:
7855 return AArch64::UABDLB_ZZZ_D;
7856 case AArch64::UABALB_ZZZ_H:
7857 return AArch64::UABDLB_ZZZ_H;
7858 case AArch64::UABALB_ZZZ_S:
7859 return AArch64::UABDLB_ZZZ_S;
7860 case AArch64::UABALT_ZZZ_D:
7861 return AArch64::UABDLT_ZZZ_D;
7862 case AArch64::UABALT_ZZZ_H:
7863 return AArch64::UABDLT_ZZZ_H;
7864 case AArch64::UABALT_ZZZ_S:
7865 return AArch64::UABDLT_ZZZ_S;
7866 case AArch64::UABALv16i8_v8i16:
7867 return AArch64::UABDLv16i8_v8i16;
7868 case AArch64::UABALv2i32_v2i64:
7869 return AArch64::UABDLv2i32_v2i64;
7870 case AArch64::UABALv4i16_v4i32:
7871 return AArch64::UABDLv4i16_v4i32;
7872 case AArch64::UABALv4i32_v2i64:
7873 return AArch64::UABDLv4i32_v2i64;
7874 case AArch64::UABALv8i16_v4i32:
7875 return AArch64::UABDLv8i16_v4i32;
7876 case AArch64::UABALv8i8_v8i16:
7877 return AArch64::UABDLv8i8_v8i16;
7878 case AArch64::UABAv16i8:
7879 return AArch64::UABDv16i8;
7880 case AArch64::UABAv2i32:
7881 return AArch64::UABDv2i32;
7882 case AArch64::UABAv4i16:
7883 return AArch64::UABDv4i16;
7884 case AArch64::UABAv4i32:
7885 return AArch64::UABDv4i32;
7886 case AArch64::UABAv8i16:
7887 return AArch64::UABDv8i16;
7888 case AArch64::UABAv8i8:
7889 return AArch64::UABDv8i8;
7890 case AArch64::SABALB_ZZZ_D:
7891 return AArch64::SABDLB_ZZZ_D;
7892 case AArch64::SABALB_ZZZ_S:
7893 return AArch64::SABDLB_ZZZ_S;
7894 case AArch64::SABALB_ZZZ_H:
7895 return AArch64::SABDLB_ZZZ_H;
7896 case AArch64::SABALT_ZZZ_D:
7897 return AArch64::SABDLT_ZZZ_D;
7898 case AArch64::SABALT_ZZZ_S:
7899 return AArch64::SABDLT_ZZZ_S;
7900 case AArch64::SABALT_ZZZ_H:
7901 return AArch64::SABDLT_ZZZ_H;
7902 case AArch64::SABALv16i8_v8i16:
7903 return AArch64::SABDLv16i8_v8i16;
7904 case AArch64::SABALv2i32_v2i64:
7905 return AArch64::SABDLv2i32_v2i64;
7906 case AArch64::SABALv4i16_v4i32:
7907 return AArch64::SABDLv4i16_v4i32;
7908 case AArch64::SABALv4i32_v2i64:
7909 return AArch64::SABDLv4i32_v2i64;
7910 case AArch64::SABALv8i16_v4i32:
7911 return AArch64::SABDLv8i16_v4i32;
7912 case AArch64::SABALv8i8_v8i16:
7913 return AArch64::SABDLv8i8_v8i16;
7914 case AArch64::SABAv16i8:
7915 return AArch64::SABDv16i8;
7916 case AArch64::SABAv2i32:
7917 return AArch64::SABAv2i32;
7918 case AArch64::SABAv4i16:
7919 return AArch64::SABDv4i16;
7920 case AArch64::SABAv4i32:
7921 return AArch64::SABDv4i32;
7922 case AArch64::SABAv8i16:
7923 return AArch64::SABDv8i16;
7924 case AArch64::SABAv8i8:
7925 return AArch64::SABDv8i8;
7926 }
7927}
7928
7929/// Floating-Point Support
7930
7931/// Find instructions that can be turned into madd.
7933 SmallVectorImpl<unsigned> &Patterns) {
7934
7935 if (!isCombineInstrCandidateFP(Root))
7936 return false;
7937
7938 MachineBasicBlock &MBB = *Root.getParent();
7939 bool Found = false;
7940
7941 auto Match = [&](int Opcode, int Operand, unsigned Pattern) -> bool {
7942 if (canCombineWithFMUL(MBB, Root.getOperand(Operand), Opcode)) {
7943 Patterns.push_back(Pattern);
7944 return true;
7945 }
7946 return false;
7947 };
7948
7950
7951 switch (Root.getOpcode()) {
7952 default:
7953 assert(false && "Unsupported FP instruction in combiner\n");
7954 break;
7955 case AArch64::FADDHrr:
7956 assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
7957 "FADDHrr does not have register operands");
7958
7959 Found = Match(AArch64::FMULHrr, 1, MCP::FMULADDH_OP1);
7960 Found |= Match(AArch64::FMULHrr, 2, MCP::FMULADDH_OP2);
7961 break;
7962 case AArch64::FADDSrr:
7963 assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
7964 "FADDSrr does not have register operands");
7965
7966 Found |= Match(AArch64::FMULSrr, 1, MCP::FMULADDS_OP1) ||
7967 Match(AArch64::FMULv1i32_indexed, 1, MCP::FMLAv1i32_indexed_OP1);
7968
7969 Found |= Match(AArch64::FMULSrr, 2, MCP::FMULADDS_OP2) ||
7970 Match(AArch64::FMULv1i32_indexed, 2, MCP::FMLAv1i32_indexed_OP2);
7971 break;
7972 case AArch64::FADDDrr:
7973 Found |= Match(AArch64::FMULDrr, 1, MCP::FMULADDD_OP1) ||
7974 Match(AArch64::FMULv1i64_indexed, 1, MCP::FMLAv1i64_indexed_OP1);
7975
7976 Found |= Match(AArch64::FMULDrr, 2, MCP::FMULADDD_OP2) ||
7977 Match(AArch64::FMULv1i64_indexed, 2, MCP::FMLAv1i64_indexed_OP2);
7978 break;
7979 case AArch64::FADDv4f16:
7980 Found |= Match(AArch64::FMULv4i16_indexed, 1, MCP::FMLAv4i16_indexed_OP1) ||
7981 Match(AArch64::FMULv4f16, 1, MCP::FMLAv4f16_OP1);
7982
7983 Found |= Match(AArch64::FMULv4i16_indexed, 2, MCP::FMLAv4i16_indexed_OP2) ||
7984 Match(AArch64::FMULv4f16, 2, MCP::FMLAv4f16_OP2);
7985 break;
7986 case AArch64::FADDv8f16:
7987 Found |= Match(AArch64::FMULv8i16_indexed, 1, MCP::FMLAv8i16_indexed_OP1) ||
7988 Match(AArch64::FMULv8f16, 1, MCP::FMLAv8f16_OP1);
7989
7990 Found |= Match(AArch64::FMULv8i16_indexed, 2, MCP::FMLAv8i16_indexed_OP2) ||
7991 Match(AArch64::FMULv8f16, 2, MCP::FMLAv8f16_OP2);
7992 break;
7993 case AArch64::FADDv2f32:
7994 Found |= Match(AArch64::FMULv2i32_indexed, 1, MCP::FMLAv2i32_indexed_OP1) ||
7995 Match(AArch64::FMULv2f32, 1, MCP::FMLAv2f32_OP1);
7996
7997 Found |= Match(AArch64::FMULv2i32_indexed, 2, MCP::FMLAv2i32_indexed_OP2) ||
7998 Match(AArch64::FMULv2f32, 2, MCP::FMLAv2f32_OP2);
7999 break;
8000 case AArch64::FADDv2f64:
8001 Found |= Match(AArch64::FMULv2i64_indexed, 1, MCP::FMLAv2i64_indexed_OP1) ||
8002 Match(AArch64::FMULv2f64, 1, MCP::FMLAv2f64_OP1);
8003
8004 Found |= Match(AArch64::FMULv2i64_indexed, 2, MCP::FMLAv2i64_indexed_OP2) ||
8005 Match(AArch64::FMULv2f64, 2, MCP::FMLAv2f64_OP2);
8006 break;
8007 case AArch64::FADDv4f32:
8008 Found |= Match(AArch64::FMULv4i32_indexed, 1, MCP::FMLAv4i32_indexed_OP1) ||
8009 Match(AArch64::FMULv4f32, 1, MCP::FMLAv4f32_OP1);
8010
8011 Found |= Match(AArch64::FMULv4i32_indexed, 2, MCP::FMLAv4i32_indexed_OP2) ||
8012 Match(AArch64::FMULv4f32, 2, MCP::FMLAv4f32_OP2);
8013 break;
8014 case AArch64::FSUBHrr:
8015 Found = Match(AArch64::FMULHrr, 1, MCP::FMULSUBH_OP1);
8016 Found |= Match(AArch64::FMULHrr, 2, MCP::FMULSUBH_OP2);
8017 Found |= Match(AArch64::FNMULHrr, 1, MCP::FNMULSUBH_OP1);
8018 break;
8019 case AArch64::FSUBSrr:
8020 Found = Match(AArch64::FMULSrr, 1, MCP::FMULSUBS_OP1);
8021
8022 Found |= Match(AArch64::FMULSrr, 2, MCP::FMULSUBS_OP2) ||
8023 Match(AArch64::FMULv1i32_indexed, 2, MCP::FMLSv1i32_indexed_OP2);
8024
8025 Found |= Match(AArch64::FNMULSrr, 1, MCP::FNMULSUBS_OP1);
8026 break;
8027 case AArch64::FSUBDrr:
8028 Found = Match(AArch64::FMULDrr, 1, MCP::FMULSUBD_OP1);
8029
8030 Found |= Match(AArch64::FMULDrr, 2, MCP::FMULSUBD_OP2) ||
8031 Match(AArch64::FMULv1i64_indexed, 2, MCP::FMLSv1i64_indexed_OP2);
8032
8033 Found |= Match(AArch64::FNMULDrr, 1, MCP::FNMULSUBD_OP1);
8034 break;
8035 case AArch64::FSUBv4f16:
8036 Found |= Match(AArch64::FMULv4i16_indexed, 2, MCP::FMLSv4i16_indexed_OP2) ||
8037 Match(AArch64::FMULv4f16, 2, MCP::FMLSv4f16_OP2);
8038
8039 Found |= Match(AArch64::FMULv4i16_indexed, 1, MCP::FMLSv4i16_indexed_OP1) ||
8040 Match(AArch64::FMULv4f16, 1, MCP::FMLSv4f16_OP1);
8041 break;
8042 case AArch64::FSUBv8f16:
8043 Found |= Match(AArch64::FMULv8i16_indexed, 2, MCP::FMLSv8i16_indexed_OP2) ||
8044 Match(AArch64::FMULv8f16, 2, MCP::FMLSv8f16_OP2);
8045
8046 Found |= Match(AArch64::FMULv8i16_indexed, 1, MCP::FMLSv8i16_indexed_OP1) ||
8047 Match(AArch64::FMULv8f16, 1, MCP::FMLSv8f16_OP1);
8048 break;
8049 case AArch64::FSUBv2f32:
8050 Found |= Match(AArch64::FMULv2i32_indexed, 2, MCP::FMLSv2i32_indexed_OP2) ||
8051 Match(AArch64::FMULv2f32, 2, MCP::FMLSv2f32_OP2);
8052
8053 Found |= Match(AArch64::FMULv2i32_indexed, 1, MCP::FMLSv2i32_indexed_OP1) ||
8054 Match(AArch64::FMULv2f32, 1, MCP::FMLSv2f32_OP1);
8055 break;
8056 case AArch64::FSUBv2f64:
8057 Found |= Match(AArch64::FMULv2i64_indexed, 2, MCP::FMLSv2i64_indexed_OP2) ||
8058 Match(AArch64::FMULv2f64, 2, MCP::FMLSv2f64_OP2);
8059
8060 Found |= Match(AArch64::FMULv2i64_indexed, 1, MCP::FMLSv2i64_indexed_OP1) ||
8061 Match(AArch64::FMULv2f64, 1, MCP::FMLSv2f64_OP1);
8062 break;
8063 case AArch64::FSUBv4f32:
8064 Found |= Match(AArch64::FMULv4i32_indexed, 2, MCP::FMLSv4i32_indexed_OP2) ||
8065 Match(AArch64::FMULv4f32, 2, MCP::FMLSv4f32_OP2);
8066
8067 Found |= Match(AArch64::FMULv4i32_indexed, 1, MCP::FMLSv4i32_indexed_OP1) ||
8068 Match(AArch64::FMULv4f32, 1, MCP::FMLSv4f32_OP1);
8069 break;
8070 }
8071 return Found;
8072}
8073
8075 SmallVectorImpl<unsigned> &Patterns) {
8076 MachineBasicBlock &MBB = *Root.getParent();
8077 bool Found = false;
8078
8079 auto Match = [&](unsigned Opcode, int Operand, unsigned Pattern) -> bool {
8080 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
8081 MachineOperand &MO = Root.getOperand(Operand);
8082 MachineInstr *MI = nullptr;
8083 if (MO.isReg() && MO.getReg().isVirtual())
8084 MI = MRI.getUniqueVRegDef(MO.getReg());
8085 // Ignore No-op COPYs in FMUL(COPY(DUP(..)))
8086 if (MI && MI->getOpcode() == TargetOpcode::COPY &&
8087 MI->getOperand(1).getReg().isVirtual())
8088 MI = MRI.getUniqueVRegDef(MI->getOperand(1).getReg());
8089 if (MI && MI->getOpcode() == Opcode) {
8090 Patterns.push_back(Pattern);
8091 return true;
8092 }
8093 return false;
8094 };
8095
8097
8098 switch (Root.getOpcode()) {
8099 default:
8100 return false;
8101 case AArch64::FMULv2f32:
8102 Found = Match(AArch64::DUPv2i32lane, 1, MCP::FMULv2i32_indexed_OP1);
8103 Found |= Match(AArch64::DUPv2i32lane, 2, MCP::FMULv2i32_indexed_OP2);
8104 break;
8105 case AArch64::FMULv2f64:
8106 Found = Match(AArch64::DUPv2i64lane, 1, MCP::FMULv2i64_indexed_OP1);
8107 Found |= Match(AArch64::DUPv2i64lane, 2, MCP::FMULv2i64_indexed_OP2);
8108 break;
8109 case AArch64::FMULv4f16:
8110 Found = Match(AArch64::DUPv4i16lane, 1, MCP::FMULv4i16_indexed_OP1);
8111 Found |= Match(AArch64::DUPv4i16lane, 2, MCP::FMULv4i16_indexed_OP2);
8112 break;
8113 case AArch64::FMULv4f32:
8114 Found = Match(AArch64::DUPv4i32lane, 1, MCP::FMULv4i32_indexed_OP1);
8115 Found |= Match(AArch64::DUPv4i32lane, 2, MCP::FMULv4i32_indexed_OP2);
8116 break;
8117 case AArch64::FMULv8f16:
8118 Found = Match(AArch64::DUPv8i16lane, 1, MCP::FMULv8i16_indexed_OP1);
8119 Found |= Match(AArch64::DUPv8i16lane, 2, MCP::FMULv8i16_indexed_OP2);
8120 break;
8121 }
8122
8123 return Found;
8124}
8125
8127 SmallVectorImpl<unsigned> &Patterns) {
8128 unsigned Opc = Root.getOpcode();
8129 MachineBasicBlock &MBB = *Root.getParent();
8130 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
8131
8132 auto Match = [&](unsigned Opcode, unsigned Pattern) -> bool {
8133 MachineOperand &MO = Root.getOperand(1);
8135 if (MI != nullptr && (MI->getOpcode() == Opcode) &&
8136 MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()) &&
8140 MI->getFlag(MachineInstr::MIFlag::FmNsz)) {
8141 Patterns.push_back(Pattern);
8142 return true;
8143 }
8144 return false;
8145 };
8146
8147 switch (Opc) {
8148 default:
8149 break;
8150 case AArch64::FNEGDr:
8151 return Match(AArch64::FMADDDrrr, AArch64MachineCombinerPattern::FNMADD);
8152 case AArch64::FNEGSr:
8153 return Match(AArch64::FMADDSrrr, AArch64MachineCombinerPattern::FNMADD);
8154 }
8155
8156 return false;
8157}
8158
8159/// Return true when a code sequence can improve throughput. It
8160/// should be called only for instructions in loops.
8161/// \param Pattern - combiner pattern
8163 switch (Pattern) {
8164 default:
8165 break;
8271 return true;
8272 } // end switch (Pattern)
8273 return false;
8274}
8275
8276/// Find other MI combine patterns.
8278 SmallVectorImpl<unsigned> &Patterns) {
8279 // A - (B + C) ==> (A - B) - C or (A - C) - B
8280 unsigned Opc = Root.getOpcode();
8281 MachineBasicBlock &MBB = *Root.getParent();
8282
8283 switch (Opc) {
8284 case AArch64::SUBWrr:
8285 case AArch64::SUBSWrr:
8286 case AArch64::SUBXrr:
8287 case AArch64::SUBSXrr:
8288 // Found candidate root.
8289 break;
8290 default:
8291 return false;
8292 }
8293
8295 Root.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true) ==
8296 -1)
8297 return false;
8298
8299 if (canCombine(MBB, Root.getOperand(2), AArch64::ADDWrr) ||
8300 canCombine(MBB, Root.getOperand(2), AArch64::ADDSWrr) ||
8301 canCombine(MBB, Root.getOperand(2), AArch64::ADDXrr) ||
8302 canCombine(MBB, Root.getOperand(2), AArch64::ADDSXrr)) {
8305 return true;
8306 }
8307
8308 return false;
8309}
8310
8311/// Check if the given instruction forms a gather load pattern that can be
8312/// optimized for better Memory-Level Parallelism (MLP). This function
8313/// identifies chains of NEON lane load instructions that load data from
8314/// different memory addresses into individual lanes of a 128-bit vector
8315/// register, then attempts to split the pattern into parallel loads to break
8316/// the serial dependency between instructions.
8317///
8318/// Pattern Matched:
8319/// Initial scalar load -> SUBREG_TO_REG (lane 0) -> LD1i* (lane 1) ->
8320/// LD1i* (lane 2) -> ... -> LD1i* (lane N-1, Root)
8321///
8322/// Transformed Into:
8323/// Two parallel vector loads using fewer lanes each, followed by ZIP1v2i64
8324/// to combine the results, enabling better memory-level parallelism.
8325///
8326/// Supported Element Types:
8327/// - 32-bit elements (LD1i32, 4 lanes total)
8328/// - 16-bit elements (LD1i16, 8 lanes total)
8329/// - 8-bit elements (LD1i8, 16 lanes total)
8331 SmallVectorImpl<unsigned> &Patterns,
8332 unsigned LoadLaneOpCode, unsigned NumLanes) {
8333 const MachineFunction *MF = Root.getMF();
8334
8335 // Early exit if optimizing for size.
8336 if (MF->getFunction().hasMinSize())
8337 return false;
8338
8339 const MachineRegisterInfo &MRI = MF->getRegInfo();
8341
8342 // The root of the pattern must load into the last lane of the vector.
8343 if (Root.getOperand(2).getImm() != NumLanes - 1)
8344 return false;
8345
8346 // Check that we have load into all lanes except lane 0.
8347 // For each load we also want to check that:
8348 // 1. It has a single non-debug use (since we will be replacing the virtual
8349 // register)
8350 // 2. That the addressing mode only uses a single pointer operand
8351 auto *CurrInstr = MRI.getUniqueVRegDef(Root.getOperand(1).getReg());
8352 auto Range = llvm::seq<unsigned>(1, NumLanes - 1);
8353 SmallSet<unsigned, 16> RemainingLanes(Range.begin(), Range.end());
8355 while (!RemainingLanes.empty() && CurrInstr &&
8356 CurrInstr->getOpcode() == LoadLaneOpCode &&
8357 MRI.hasOneNonDBGUse(CurrInstr->getOperand(0).getReg()) &&
8358 CurrInstr->getNumOperands() == 4) {
8359 RemainingLanes.erase(CurrInstr->getOperand(2).getImm());
8360 LoadInstrs.push_back(CurrInstr);
8361 CurrInstr = MRI.getUniqueVRegDef(CurrInstr->getOperand(1).getReg());
8362 }
8363
8364 // Check that we have found a match for lanes N-1.. 1.
8365 if (!RemainingLanes.empty())
8366 return false;
8367
8368 // Match the SUBREG_TO_REG sequence.
8369 if (CurrInstr->getOpcode() != TargetOpcode::SUBREG_TO_REG)
8370 return false;
8371
8372 // Verify that the subreg to reg loads an integer into the first lane.
8373 auto Lane0LoadReg = CurrInstr->getOperand(1).getReg();
8374 unsigned SingleLaneSizeInBits = 128 / NumLanes;
8375 if (TRI->getRegSizeInBits(Lane0LoadReg, MRI) != SingleLaneSizeInBits)
8376 return false;
8377
8378 // Verify that it also has a single non debug use.
8379 if (!MRI.hasOneNonDBGUse(Lane0LoadReg))
8380 return false;
8381
8382 LoadInstrs.push_back(MRI.getUniqueVRegDef(Lane0LoadReg));
8383
8384 // If there is any chance of aliasing, do not apply the pattern.
8385 // Walk backward through the MBB starting from Root.
8386 // Exit early if we've encountered all load instructions or hit the search
8387 // limit.
8388 auto MBBItr = Root.getIterator();
8389 unsigned RemainingSteps = GatherOptSearchLimit;
8390 SmallPtrSet<const MachineInstr *, 16> RemainingLoadInstrs;
8391 RemainingLoadInstrs.insert(LoadInstrs.begin(), LoadInstrs.end());
8392 const MachineBasicBlock *MBB = Root.getParent();
8393
8394 for (; MBBItr != MBB->begin() && RemainingSteps > 0 &&
8395 !RemainingLoadInstrs.empty();
8396 --MBBItr, --RemainingSteps) {
8397 const MachineInstr &CurrInstr = *MBBItr;
8398
8399 // Remove this instruction from remaining loads if it's one we're tracking.
8400 RemainingLoadInstrs.erase(&CurrInstr);
8401
8402 // Check for potential aliasing with any of the load instructions to
8403 // optimize.
8404 if (CurrInstr.isLoadFoldBarrier())
8405 return false;
8406 }
8407
8408 // If we hit the search limit without finding all load instructions,
8409 // don't match the pattern.
8410 if (RemainingSteps == 0 && !RemainingLoadInstrs.empty())
8411 return false;
8412
8413 switch (NumLanes) {
8414 case 4:
8416 break;
8417 case 8:
8419 break;
8420 case 16:
8422 break;
8423 default:
8424 llvm_unreachable("Got bad number of lanes for gather pattern.");
8425 }
8426
8427 return true;
8428}
8429
8430/// Search for patterns of LD instructions we can optimize.
8432 SmallVectorImpl<unsigned> &Patterns) {
8433
8434 // The pattern searches for loads into single lanes.
8435 switch (Root.getOpcode()) {
8436 case AArch64::LD1i32:
8437 return getGatherLanePattern(Root, Patterns, Root.getOpcode(), 4);
8438 case AArch64::LD1i16:
8439 return getGatherLanePattern(Root, Patterns, Root.getOpcode(), 8);
8440 case AArch64::LD1i8:
8441 return getGatherLanePattern(Root, Patterns, Root.getOpcode(), 16);
8442 default:
8443 return false;
8444 }
8445}
8446
8447/// Generate optimized instruction sequence for gather load patterns to improve
8448/// Memory-Level Parallelism (MLP). This function transforms a chain of
8449/// sequential NEON lane loads into parallel vector loads that can execute
8450/// concurrently.
8451static void
8455 DenseMap<Register, unsigned> &InstrIdxForVirtReg,
8456 unsigned Pattern, unsigned NumLanes) {
8457 MachineFunction &MF = *Root.getParent()->getParent();
8458 MachineRegisterInfo &MRI = MF.getRegInfo();
8460
8461 // Gather the initial load instructions to build the pattern.
8462 SmallVector<MachineInstr *, 16> LoadToLaneInstrs;
8463 MachineInstr *CurrInstr = &Root;
8464 for (unsigned i = 0; i < NumLanes - 1; ++i) {
8465 LoadToLaneInstrs.push_back(CurrInstr);
8466 CurrInstr = MRI.getUniqueVRegDef(CurrInstr->getOperand(1).getReg());
8467 }
8468
8469 // Sort the load instructions according to the lane.
8470 llvm::sort(LoadToLaneInstrs,
8471 [](const MachineInstr *A, const MachineInstr *B) {
8472 return A->getOperand(2).getImm() > B->getOperand(2).getImm();
8473 });
8474
8475 MachineInstr *SubregToReg = CurrInstr;
8476 LoadToLaneInstrs.push_back(
8477 MRI.getUniqueVRegDef(SubregToReg->getOperand(1).getReg()));
8478 auto LoadToLaneInstrsAscending = llvm::reverse(LoadToLaneInstrs);
8479
8480 const TargetRegisterClass *FPR128RegClass =
8481 MRI.getRegClass(Root.getOperand(0).getReg());
8482
8483 // Helper lambda to create a LD1 instruction.
8484 auto CreateLD1Instruction = [&](MachineInstr *OriginalInstr,
8485 Register SrcRegister, unsigned Lane,
8486 Register OffsetRegister,
8487 bool OffsetRegisterKillState) {
8488 auto NewRegister = MRI.createVirtualRegister(FPR128RegClass);
8489 MachineInstrBuilder LoadIndexIntoRegister =
8490 BuildMI(MF, MIMetadata(*OriginalInstr), TII->get(Root.getOpcode()),
8491 NewRegister)
8492 .addReg(SrcRegister)
8493 .addImm(Lane)
8494 .addReg(OffsetRegister, getKillRegState(OffsetRegisterKillState))
8495 .setMemRefs(OriginalInstr->memoperands());
8496 InstrIdxForVirtReg.insert(std::make_pair(NewRegister, InsInstrs.size()));
8497 InsInstrs.push_back(LoadIndexIntoRegister);
8498 return NewRegister;
8499 };
8500
8501 // Helper to create load instruction based on the NumLanes in the NEON
8502 // register we are rewriting.
8503 auto CreateLDRInstruction =
8504 [&](unsigned NumLanes, Register DestReg, Register OffsetReg,
8506 unsigned Opcode;
8507 switch (NumLanes) {
8508 case 4:
8509 Opcode = AArch64::LDRSui;
8510 break;
8511 case 8:
8512 Opcode = AArch64::LDRHui;
8513 break;
8514 case 16:
8515 Opcode = AArch64::LDRBui;
8516 break;
8517 default:
8519 "Got unsupported number of lanes in machine-combiner gather pattern");
8520 }
8521 // Immediate offset load
8522 return BuildMI(MF, MIMetadata(Root), TII->get(Opcode), DestReg)
8523 .addReg(OffsetReg)
8524 .addImm(0)
8525 .setMemRefs(MMOs);
8526 };
8527
8528 // Load the remaining lanes into register 0.
8529 auto LanesToLoadToReg0 =
8530 llvm::make_range(LoadToLaneInstrsAscending.begin() + 1,
8531 LoadToLaneInstrsAscending.begin() + NumLanes / 2);
8532 Register PrevReg = SubregToReg->getOperand(0).getReg();
8533 for (auto [Index, LoadInstr] : llvm::enumerate(LanesToLoadToReg0)) {
8534 const MachineOperand &OffsetRegOperand = LoadInstr->getOperand(3);
8535 PrevReg = CreateLD1Instruction(LoadInstr, PrevReg, Index + 1,
8536 OffsetRegOperand.getReg(),
8537 OffsetRegOperand.isKill());
8538 DelInstrs.push_back(LoadInstr);
8539 }
8540 Register LastLoadReg0 = PrevReg;
8541
8542 // First load into register 1. Perform an integer load to zero out the upper
8543 // lanes in a single instruction.
8544 MachineInstr *Lane0Load = *LoadToLaneInstrsAscending.begin();
8545 MachineInstr *OriginalSplitLoad =
8546 *std::next(LoadToLaneInstrsAscending.begin(), NumLanes / 2);
8547 Register DestRegForMiddleIndex = MRI.createVirtualRegister(
8548 MRI.getRegClass(Lane0Load->getOperand(0).getReg()));
8549
8550 const MachineOperand &OriginalSplitToLoadOffsetOperand =
8551 OriginalSplitLoad->getOperand(3);
8552 MachineInstrBuilder MiddleIndexLoadInstr =
8553 CreateLDRInstruction(NumLanes, DestRegForMiddleIndex,
8554 OriginalSplitToLoadOffsetOperand.getReg(),
8555 OriginalSplitLoad->memoperands());
8556
8557 InstrIdxForVirtReg.insert(
8558 std::make_pair(DestRegForMiddleIndex, InsInstrs.size()));
8559 InsInstrs.push_back(MiddleIndexLoadInstr);
8560 DelInstrs.push_back(OriginalSplitLoad);
8561
8562 // Subreg To Reg instruction for register 1.
8563 Register DestRegForSubregToReg = MRI.createVirtualRegister(FPR128RegClass);
8564 unsigned SubregType;
8565 switch (NumLanes) {
8566 case 4:
8567 SubregType = AArch64::ssub;
8568 break;
8569 case 8:
8570 SubregType = AArch64::hsub;
8571 break;
8572 case 16:
8573 SubregType = AArch64::bsub;
8574 break;
8575 default:
8577 "Got invalid NumLanes for machine-combiner gather pattern");
8578 }
8579
8580 auto SubRegToRegInstr =
8581 BuildMI(MF, MIMetadata(Root), TII->get(SubregToReg->getOpcode()),
8582 DestRegForSubregToReg)
8583 .addReg(DestRegForMiddleIndex, getKillRegState(true))
8584 .addImm(SubregType);
8585 InstrIdxForVirtReg.insert(
8586 std::make_pair(DestRegForSubregToReg, InsInstrs.size()));
8587 InsInstrs.push_back(SubRegToRegInstr);
8588
8589 // Load remaining lanes into register 1.
8590 auto LanesToLoadToReg1 =
8591 llvm::make_range(LoadToLaneInstrsAscending.begin() + NumLanes / 2 + 1,
8592 LoadToLaneInstrsAscending.end());
8593 PrevReg = SubRegToRegInstr->getOperand(0).getReg();
8594 for (auto [Index, LoadInstr] : llvm::enumerate(LanesToLoadToReg1)) {
8595 const MachineOperand &OffsetRegOperand = LoadInstr->getOperand(3);
8596 PrevReg = CreateLD1Instruction(LoadInstr, PrevReg, Index + 1,
8597 OffsetRegOperand.getReg(),
8598 OffsetRegOperand.isKill());
8599
8600 // Do not add the last reg to DelInstrs - it will be removed later.
8601 if (Index == NumLanes / 2 - 2) {
8602 break;
8603 }
8604 DelInstrs.push_back(LoadInstr);
8605 }
8606 Register LastLoadReg1 = PrevReg;
8607
8608 // Create the final zip instruction to combine the results.
8609 MachineInstrBuilder ZipInstr =
8610 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::ZIP1v2i64),
8611 Root.getOperand(0).getReg())
8612 .addReg(LastLoadReg0)
8613 .addReg(LastLoadReg1);
8614 InsInstrs.push_back(ZipInstr);
8615}
8616
8630
8631/// Return true when there is potentially a faster code sequence for an
8632/// instruction chain ending in \p Root. All potential patterns are listed in
8633/// the \p Pattern vector. Pattern should be sorted in priority order since the
8634/// pattern evaluator stops checking as soon as it finds a faster sequence.
8635
8636bool AArch64InstrInfo::getMachineCombinerPatterns(
8637 MachineInstr &Root, SmallVectorImpl<unsigned> &Patterns,
8638 bool DoRegPressureReduce) const {
8639 // Integer patterns
8640 if (getMaddPatterns(Root, Patterns))
8641 return true;
8642 // Floating point patterns
8643 if (getFMULPatterns(Root, Patterns))
8644 return true;
8645 if (getFMAPatterns(Root, Patterns))
8646 return true;
8647 if (getFNEGPatterns(Root, Patterns))
8648 return true;
8649
8650 // Other patterns
8651 if (getMiscPatterns(Root, Patterns))
8652 return true;
8653
8654 // Load patterns
8655 if (getLoadPatterns(Root, Patterns))
8656 return true;
8657
8658 return TargetInstrInfo::getMachineCombinerPatterns(Root, Patterns,
8659 DoRegPressureReduce);
8660}
8661
8663/// genFusedMultiply - Generate fused multiply instructions.
8664/// This function supports both integer and floating point instructions.
8665/// A typical example:
8666/// F|MUL I=A,B,0
8667/// F|ADD R,I,C
8668/// ==> F|MADD R,A,B,C
8669/// \param MF Containing MachineFunction
8670/// \param MRI Register information
8671/// \param TII Target information
8672/// \param Root is the F|ADD instruction
8673/// \param [out] InsInstrs is a vector of machine instructions and will
8674/// contain the generated madd instruction
8675/// \param IdxMulOpd is index of operand in Root that is the result of
8676/// the F|MUL. In the example above IdxMulOpd is 1.
8677/// \param MaddOpc the opcode fo the f|madd instruction
8678/// \param RC Register class of operands
8679/// \param kind of fma instruction (addressing mode) to be generated
8680/// \param ReplacedAddend is the result register from the instruction
8681/// replacing the non-combined operand, if any.
8682static MachineInstr *
8684 const TargetInstrInfo *TII, MachineInstr &Root,
8685 SmallVectorImpl<MachineInstr *> &InsInstrs, unsigned IdxMulOpd,
8686 unsigned MaddOpc, const TargetRegisterClass *RC,
8688 const Register *ReplacedAddend = nullptr) {
8689 assert(IdxMulOpd == 1 || IdxMulOpd == 2);
8690
8691 unsigned IdxOtherOpd = IdxMulOpd == 1 ? 2 : 1;
8692 MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(IdxMulOpd).getReg());
8693 Register ResultReg = Root.getOperand(0).getReg();
8694 Register SrcReg0 = MUL->getOperand(1).getReg();
8695 bool Src0IsKill = MUL->getOperand(1).isKill();
8696 Register SrcReg1 = MUL->getOperand(2).getReg();
8697 bool Src1IsKill = MUL->getOperand(2).isKill();
8698
8699 Register SrcReg2;
8700 bool Src2IsKill;
8701 if (ReplacedAddend) {
8702 // If we just generated a new addend, we must be it's only use.
8703 SrcReg2 = *ReplacedAddend;
8704 Src2IsKill = true;
8705 } else {
8706 SrcReg2 = Root.getOperand(IdxOtherOpd).getReg();
8707 Src2IsKill = Root.getOperand(IdxOtherOpd).isKill();
8708 }
8709
8710 if (ResultReg.isVirtual())
8711 MRI.constrainRegClass(ResultReg, RC);
8712 if (SrcReg0.isVirtual())
8713 MRI.constrainRegClass(SrcReg0, RC);
8714 if (SrcReg1.isVirtual())
8715 MRI.constrainRegClass(SrcReg1, RC);
8716 if (SrcReg2.isVirtual())
8717 MRI.constrainRegClass(SrcReg2, RC);
8718
8720 if (kind == FMAInstKind::Default)
8721 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
8722 .addReg(SrcReg0, getKillRegState(Src0IsKill))
8723 .addReg(SrcReg1, getKillRegState(Src1IsKill))
8724 .addReg(SrcReg2, getKillRegState(Src2IsKill));
8725 else if (kind == FMAInstKind::Indexed)
8726 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
8727 .addReg(SrcReg2, getKillRegState(Src2IsKill))
8728 .addReg(SrcReg0, getKillRegState(Src0IsKill))
8729 .addReg(SrcReg1, getKillRegState(Src1IsKill))
8730 .addImm(MUL->getOperand(3).getImm());
8731 else if (kind == FMAInstKind::Accumulator)
8732 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
8733 .addReg(SrcReg2, getKillRegState(Src2IsKill))
8734 .addReg(SrcReg0, getKillRegState(Src0IsKill))
8735 .addReg(SrcReg1, getKillRegState(Src1IsKill));
8736 else
8737 assert(false && "Invalid FMA instruction kind \n");
8738 // Insert the MADD (MADD, FMA, FMS, FMLA, FMSL)
8739 InsInstrs.push_back(MIB);
8740 return MUL;
8741}
8742
8743static MachineInstr *
8745 const TargetInstrInfo *TII, MachineInstr &Root,
8747 MachineInstr *MAD = MRI.getUniqueVRegDef(Root.getOperand(1).getReg());
8748
8749 unsigned Opc = 0;
8750 const TargetRegisterClass *RC = MRI.getRegClass(MAD->getOperand(0).getReg());
8751 if (AArch64::FPR32RegClass.hasSubClassEq(RC))
8752 Opc = AArch64::FNMADDSrrr;
8753 else if (AArch64::FPR64RegClass.hasSubClassEq(RC))
8754 Opc = AArch64::FNMADDDrrr;
8755 else
8756 return nullptr;
8757
8758 Register ResultReg = Root.getOperand(0).getReg();
8759 Register SrcReg0 = MAD->getOperand(1).getReg();
8760 Register SrcReg1 = MAD->getOperand(2).getReg();
8761 Register SrcReg2 = MAD->getOperand(3).getReg();
8762 bool Src0IsKill = MAD->getOperand(1).isKill();
8763 bool Src1IsKill = MAD->getOperand(2).isKill();
8764 bool Src2IsKill = MAD->getOperand(3).isKill();
8765 if (ResultReg.isVirtual())
8766 MRI.constrainRegClass(ResultReg, RC);
8767 if (SrcReg0.isVirtual())
8768 MRI.constrainRegClass(SrcReg0, RC);
8769 if (SrcReg1.isVirtual())
8770 MRI.constrainRegClass(SrcReg1, RC);
8771 if (SrcReg2.isVirtual())
8772 MRI.constrainRegClass(SrcReg2, RC);
8773
8775 BuildMI(MF, MIMetadata(Root), TII->get(Opc), ResultReg)
8776 .addReg(SrcReg0, getKillRegState(Src0IsKill))
8777 .addReg(SrcReg1, getKillRegState(Src1IsKill))
8778 .addReg(SrcReg2, getKillRegState(Src2IsKill));
8779 InsInstrs.push_back(MIB);
8780
8781 return MAD;
8782}
8783
8784/// Fold (FMUL x (DUP y lane)) into (FMUL_indexed x y lane)
8785static MachineInstr *
8788 unsigned IdxDupOp, unsigned MulOpc,
8789 const TargetRegisterClass *RC, MachineRegisterInfo &MRI) {
8790 assert(((IdxDupOp == 1) || (IdxDupOp == 2)) &&
8791 "Invalid index of FMUL operand");
8792
8793 MachineFunction &MF = *Root.getMF();
8795
8796 MachineInstr *Dup =
8797 MF.getRegInfo().getUniqueVRegDef(Root.getOperand(IdxDupOp).getReg());
8798
8799 if (Dup->getOpcode() == TargetOpcode::COPY)
8800 Dup = MRI.getUniqueVRegDef(Dup->getOperand(1).getReg());
8801
8802 Register DupSrcReg = Dup->getOperand(1).getReg();
8803 MRI.clearKillFlags(DupSrcReg);
8804 MRI.constrainRegClass(DupSrcReg, RC);
8805
8806 unsigned DupSrcLane = Dup->getOperand(2).getImm();
8807
8808 unsigned IdxMulOp = IdxDupOp == 1 ? 2 : 1;
8809 MachineOperand &MulOp = Root.getOperand(IdxMulOp);
8810
8811 Register ResultReg = Root.getOperand(0).getReg();
8812
8814 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MulOpc), ResultReg)
8815 .add(MulOp)
8816 .addReg(DupSrcReg)
8817 .addImm(DupSrcLane);
8818
8819 InsInstrs.push_back(MIB);
8820 return &Root;
8821}
8822
8823/// genFusedMultiplyAcc - Helper to generate fused multiply accumulate
8824/// instructions.
8825///
8826/// \see genFusedMultiply
8830 unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC) {
8831 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
8833}
8834
8835/// genNeg - Helper to generate an intermediate negation of the second operand
8836/// of Root
8838 const TargetInstrInfo *TII, MachineInstr &Root,
8840 DenseMap<Register, unsigned> &InstrIdxForVirtReg,
8841 unsigned MnegOpc, const TargetRegisterClass *RC) {
8842 Register NewVR = MRI.createVirtualRegister(RC);
8844 BuildMI(MF, MIMetadata(Root), TII->get(MnegOpc), NewVR)
8845 .add(Root.getOperand(2));
8846 InsInstrs.push_back(MIB);
8847
8848 assert(InstrIdxForVirtReg.empty());
8849 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
8850
8851 return NewVR;
8852}
8853
8854/// genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate
8855/// instructions with an additional negation of the accumulator
8859 DenseMap<Register, unsigned> &InstrIdxForVirtReg, unsigned IdxMulOpd,
8860 unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC) {
8861 assert(IdxMulOpd == 1);
8862
8863 Register NewVR =
8864 genNeg(MF, MRI, TII, Root, InsInstrs, InstrIdxForVirtReg, MnegOpc, RC);
8865 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
8866 FMAInstKind::Accumulator, &NewVR);
8867}
8868
8869/// genFusedMultiplyIdx - Helper to generate fused multiply accumulate
8870/// instructions.
8871///
8872/// \see genFusedMultiply
8876 unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC) {
8877 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
8879}
8880
8881/// genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate
8882/// instructions with an additional negation of the accumulator
8886 DenseMap<Register, unsigned> &InstrIdxForVirtReg, unsigned IdxMulOpd,
8887 unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC) {
8888 assert(IdxMulOpd == 1);
8889
8890 Register NewVR =
8891 genNeg(MF, MRI, TII, Root, InsInstrs, InstrIdxForVirtReg, MnegOpc, RC);
8892
8893 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
8894 FMAInstKind::Indexed, &NewVR);
8895}
8896
8897/// genMaddR - Generate madd instruction and combine mul and add using
8898/// an extra virtual register
8899/// Example - an ADD intermediate needs to be stored in a register:
8900/// MUL I=A,B,0
8901/// ADD R,I,Imm
8902/// ==> ORR V, ZR, Imm
8903/// ==> MADD R,A,B,V
8904/// \param MF Containing MachineFunction
8905/// \param MRI Register information
8906/// \param TII Target information
8907/// \param Root is the ADD instruction
8908/// \param [out] InsInstrs is a vector of machine instructions and will
8909/// contain the generated madd instruction
8910/// \param IdxMulOpd is index of operand in Root that is the result of
8911/// the MUL. In the example above IdxMulOpd is 1.
8912/// \param MaddOpc the opcode fo the madd instruction
8913/// \param VR is a virtual register that holds the value of an ADD operand
8914/// (V in the example above).
8915/// \param RC Register class of operands
8917 const TargetInstrInfo *TII, MachineInstr &Root,
8919 unsigned IdxMulOpd, unsigned MaddOpc, unsigned VR,
8920 const TargetRegisterClass *RC) {
8921 assert(IdxMulOpd == 1 || IdxMulOpd == 2);
8922
8923 MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(IdxMulOpd).getReg());
8924 Register ResultReg = Root.getOperand(0).getReg();
8925 Register SrcReg0 = MUL->getOperand(1).getReg();
8926 bool Src0IsKill = MUL->getOperand(1).isKill();
8927 Register SrcReg1 = MUL->getOperand(2).getReg();
8928 bool Src1IsKill = MUL->getOperand(2).isKill();
8929
8930 if (ResultReg.isVirtual())
8931 MRI.constrainRegClass(ResultReg, RC);
8932 if (SrcReg0.isVirtual())
8933 MRI.constrainRegClass(SrcReg0, RC);
8934 if (SrcReg1.isVirtual())
8935 MRI.constrainRegClass(SrcReg1, RC);
8937 MRI.constrainRegClass(VR, RC);
8938
8940 BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
8941 .addReg(SrcReg0, getKillRegState(Src0IsKill))
8942 .addReg(SrcReg1, getKillRegState(Src1IsKill))
8943 .addReg(VR);
8944 // Insert the MADD
8945 InsInstrs.push_back(MIB);
8946 return MUL;
8947}
8948
8949/// Do the following transformation
8950/// A - (B + C) ==> (A - B) - C
8951/// A - (B + C) ==> (A - C) - B
8953 const TargetInstrInfo *TII, MachineInstr &Root,
8956 unsigned IdxOpd1,
8957 DenseMap<Register, unsigned> &InstrIdxForVirtReg) {
8958 assert(IdxOpd1 == 1 || IdxOpd1 == 2);
8959 unsigned IdxOtherOpd = IdxOpd1 == 1 ? 2 : 1;
8960 MachineInstr *AddMI = MRI.getUniqueVRegDef(Root.getOperand(2).getReg());
8961
8962 Register ResultReg = Root.getOperand(0).getReg();
8963 Register RegA = Root.getOperand(1).getReg();
8964 bool RegAIsKill = Root.getOperand(1).isKill();
8965 Register RegB = AddMI->getOperand(IdxOpd1).getReg();
8966 bool RegBIsKill = AddMI->getOperand(IdxOpd1).isKill();
8967 Register RegC = AddMI->getOperand(IdxOtherOpd).getReg();
8968 bool RegCIsKill = AddMI->getOperand(IdxOtherOpd).isKill();
8969 Register NewVR =
8971
8972 unsigned Opcode = Root.getOpcode();
8973 if (Opcode == AArch64::SUBSWrr)
8974 Opcode = AArch64::SUBWrr;
8975 else if (Opcode == AArch64::SUBSXrr)
8976 Opcode = AArch64::SUBXrr;
8977 else
8978 assert((Opcode == AArch64::SUBWrr || Opcode == AArch64::SUBXrr) &&
8979 "Unexpected instruction opcode.");
8980
8981 uint32_t Flags = Root.mergeFlagsWith(*AddMI);
8982 Flags &= ~MachineInstr::NoSWrap;
8983 Flags &= ~MachineInstr::NoUWrap;
8984
8985 MachineInstrBuilder MIB1 =
8986 BuildMI(MF, MIMetadata(Root), TII->get(Opcode), NewVR)
8987 .addReg(RegA, getKillRegState(RegAIsKill))
8988 .addReg(RegB, getKillRegState(RegBIsKill))
8989 .setMIFlags(Flags);
8990 MachineInstrBuilder MIB2 =
8991 BuildMI(MF, MIMetadata(Root), TII->get(Opcode), ResultReg)
8992 .addReg(NewVR, getKillRegState(true))
8993 .addReg(RegC, getKillRegState(RegCIsKill))
8994 .setMIFlags(Flags);
8995
8996 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
8997 InsInstrs.push_back(MIB1);
8998 InsInstrs.push_back(MIB2);
8999 DelInstrs.push_back(AddMI);
9000 DelInstrs.push_back(&Root);
9001}
9002
9003unsigned AArch64InstrInfo::getReduceOpcodeForAccumulator(
9004 unsigned int AccumulatorOpCode) const {
9005 switch (AccumulatorOpCode) {
9006 case AArch64::UABALB_ZZZ_D:
9007 case AArch64::SABALB_ZZZ_D:
9008 case AArch64::UABALT_ZZZ_D:
9009 case AArch64::SABALT_ZZZ_D:
9010 return AArch64::ADD_ZZZ_D;
9011 case AArch64::UABALB_ZZZ_H:
9012 case AArch64::SABALB_ZZZ_H:
9013 case AArch64::UABALT_ZZZ_H:
9014 case AArch64::SABALT_ZZZ_H:
9015 return AArch64::ADD_ZZZ_H;
9016 case AArch64::UABALB_ZZZ_S:
9017 case AArch64::SABALB_ZZZ_S:
9018 case AArch64::UABALT_ZZZ_S:
9019 case AArch64::SABALT_ZZZ_S:
9020 return AArch64::ADD_ZZZ_S;
9021 case AArch64::UABALv16i8_v8i16:
9022 case AArch64::SABALv8i8_v8i16:
9023 case AArch64::SABAv8i16:
9024 case AArch64::UABAv8i16:
9025 return AArch64::ADDv8i16;
9026 case AArch64::SABALv2i32_v2i64:
9027 case AArch64::UABALv2i32_v2i64:
9028 case AArch64::SABALv4i32_v2i64:
9029 return AArch64::ADDv2i64;
9030 case AArch64::UABALv4i16_v4i32:
9031 case AArch64::SABALv4i16_v4i32:
9032 case AArch64::SABALv8i16_v4i32:
9033 case AArch64::SABAv4i32:
9034 case AArch64::UABAv4i32:
9035 return AArch64::ADDv4i32;
9036 case AArch64::UABALv4i32_v2i64:
9037 return AArch64::ADDv2i64;
9038 case AArch64::UABALv8i16_v4i32:
9039 return AArch64::ADDv4i32;
9040 case AArch64::UABALv8i8_v8i16:
9041 case AArch64::SABALv16i8_v8i16:
9042 return AArch64::ADDv8i16;
9043 case AArch64::UABAv16i8:
9044 case AArch64::SABAv16i8:
9045 return AArch64::ADDv16i8;
9046 case AArch64::UABAv4i16:
9047 case AArch64::SABAv4i16:
9048 return AArch64::ADDv4i16;
9049 case AArch64::UABAv2i32:
9050 case AArch64::SABAv2i32:
9051 return AArch64::ADDv2i32;
9052 case AArch64::UABAv8i8:
9053 case AArch64::SABAv8i8:
9054 return AArch64::ADDv8i8;
9055 default:
9056 llvm_unreachable("Unknown accumulator opcode");
9057 }
9058}
9059
9060/// When getMachineCombinerPatterns() finds potential patterns,
9061/// this function generates the instructions that could replace the
9062/// original code sequence
9063void AArch64InstrInfo::genAlternativeCodeSequence(
9064 MachineInstr &Root, unsigned Pattern,
9067 DenseMap<Register, unsigned> &InstrIdxForVirtReg) const {
9068 MachineBasicBlock &MBB = *Root.getParent();
9069 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9070 MachineFunction &MF = *MBB.getParent();
9071 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9072
9073 MachineInstr *MUL = nullptr;
9074 const TargetRegisterClass *RC;
9075 unsigned Opc;
9076 switch (Pattern) {
9077 default:
9078 // Reassociate instructions.
9079 TargetInstrInfo::genAlternativeCodeSequence(Root, Pattern, InsInstrs,
9080 DelInstrs, InstrIdxForVirtReg);
9081 return;
9083 // A - (B + C)
9084 // ==> (A - B) - C
9085 genSubAdd2SubSub(MF, MRI, TII, Root, InsInstrs, DelInstrs, 1,
9086 InstrIdxForVirtReg);
9087 return;
9089 // A - (B + C)
9090 // ==> (A - C) - B
9091 genSubAdd2SubSub(MF, MRI, TII, Root, InsInstrs, DelInstrs, 2,
9092 InstrIdxForVirtReg);
9093 return;
9096 // MUL I=A,B,0
9097 // ADD R,I,C
9098 // ==> MADD R,A,B,C
9099 // --- Create(MADD);
9101 Opc = AArch64::MADDWrrr;
9102 RC = &AArch64::GPR32RegClass;
9103 } else {
9104 Opc = AArch64::MADDXrrr;
9105 RC = &AArch64::GPR64RegClass;
9106 }
9107 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9108 break;
9111 // MUL I=A,B,0
9112 // ADD R,C,I
9113 // ==> MADD R,A,B,C
9114 // --- Create(MADD);
9116 Opc = AArch64::MADDWrrr;
9117 RC = &AArch64::GPR32RegClass;
9118 } else {
9119 Opc = AArch64::MADDXrrr;
9120 RC = &AArch64::GPR64RegClass;
9121 }
9122 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9123 break;
9128 // MUL I=A,B,0
9129 // ADD/SUB R,I,Imm
9130 // ==> MOV V, Imm/-Imm
9131 // ==> MADD R,A,B,V
9132 // --- Create(MADD);
9133 const TargetRegisterClass *RC;
9134 unsigned BitSize, MovImm;
9137 MovImm = AArch64::MOVi32imm;
9138 RC = &AArch64::GPR32spRegClass;
9139 BitSize = 32;
9140 Opc = AArch64::MADDWrrr;
9141 RC = &AArch64::GPR32RegClass;
9142 } else {
9143 MovImm = AArch64::MOVi64imm;
9144 RC = &AArch64::GPR64spRegClass;
9145 BitSize = 64;
9146 Opc = AArch64::MADDXrrr;
9147 RC = &AArch64::GPR64RegClass;
9148 }
9149 Register NewVR = MRI.createVirtualRegister(RC);
9150 uint64_t Imm = Root.getOperand(2).getImm();
9151
9152 if (Root.getOperand(3).isImm()) {
9153 unsigned Val = Root.getOperand(3).getImm();
9154 Imm = Imm << Val;
9155 }
9156 bool IsSub = Pattern == AArch64MachineCombinerPattern::MULSUBWI_OP1 ||
9158 uint64_t UImm = SignExtend64(IsSub ? -Imm : Imm, BitSize);
9159 // Check that the immediate can be composed via a single instruction.
9161 AArch64_IMM::expandMOVImm(UImm, BitSize, Insn);
9162 if (Insn.size() != 1)
9163 return;
9164 MachineInstrBuilder MIB1 =
9165 BuildMI(MF, MIMetadata(Root), TII->get(MovImm), NewVR)
9166 .addImm(IsSub ? -Imm : Imm);
9167 InsInstrs.push_back(MIB1);
9168 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9169 MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC);
9170 break;
9171 }
9174 // MUL I=A,B,0
9175 // SUB R,I, C
9176 // ==> SUB V, 0, C
9177 // ==> MADD R,A,B,V // = -C + A*B
9178 // --- Create(MADD);
9179 const TargetRegisterClass *SubRC;
9180 unsigned SubOpc, ZeroReg;
9182 SubOpc = AArch64::SUBWrr;
9183 SubRC = &AArch64::GPR32spRegClass;
9184 ZeroReg = AArch64::WZR;
9185 Opc = AArch64::MADDWrrr;
9186 RC = &AArch64::GPR32RegClass;
9187 } else {
9188 SubOpc = AArch64::SUBXrr;
9189 SubRC = &AArch64::GPR64spRegClass;
9190 ZeroReg = AArch64::XZR;
9191 Opc = AArch64::MADDXrrr;
9192 RC = &AArch64::GPR64RegClass;
9193 }
9194 Register NewVR = MRI.createVirtualRegister(SubRC);
9195 // SUB NewVR, 0, C
9196 MachineInstrBuilder MIB1 =
9197 BuildMI(MF, MIMetadata(Root), TII->get(SubOpc), NewVR)
9198 .addReg(ZeroReg)
9199 .add(Root.getOperand(2));
9200 InsInstrs.push_back(MIB1);
9201 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9202 MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC);
9203 break;
9204 }
9207 // MUL I=A,B,0
9208 // SUB R,C,I
9209 // ==> MSUB R,A,B,C (computes C - A*B)
9210 // --- Create(MSUB);
9212 Opc = AArch64::MSUBWrrr;
9213 RC = &AArch64::GPR32RegClass;
9214 } else {
9215 Opc = AArch64::MSUBXrrr;
9216 RC = &AArch64::GPR64RegClass;
9217 }
9218 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9219 break;
9221 Opc = AArch64::MLAv8i8;
9222 RC = &AArch64::FPR64RegClass;
9223 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9224 break;
9226 Opc = AArch64::MLAv8i8;
9227 RC = &AArch64::FPR64RegClass;
9228 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9229 break;
9231 Opc = AArch64::MLAv16i8;
9232 RC = &AArch64::FPR128RegClass;
9233 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9234 break;
9236 Opc = AArch64::MLAv16i8;
9237 RC = &AArch64::FPR128RegClass;
9238 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9239 break;
9241 Opc = AArch64::MLAv4i16;
9242 RC = &AArch64::FPR64RegClass;
9243 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9244 break;
9246 Opc = AArch64::MLAv4i16;
9247 RC = &AArch64::FPR64RegClass;
9248 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9249 break;
9251 Opc = AArch64::MLAv8i16;
9252 RC = &AArch64::FPR128RegClass;
9253 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9254 break;
9256 Opc = AArch64::MLAv8i16;
9257 RC = &AArch64::FPR128RegClass;
9258 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9259 break;
9261 Opc = AArch64::MLAv2i32;
9262 RC = &AArch64::FPR64RegClass;
9263 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9264 break;
9266 Opc = AArch64::MLAv2i32;
9267 RC = &AArch64::FPR64RegClass;
9268 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9269 break;
9271 Opc = AArch64::MLAv4i32;
9272 RC = &AArch64::FPR128RegClass;
9273 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9274 break;
9276 Opc = AArch64::MLAv4i32;
9277 RC = &AArch64::FPR128RegClass;
9278 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9279 break;
9280
9282 Opc = AArch64::MLAv8i8;
9283 RC = &AArch64::FPR64RegClass;
9284 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9285 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i8,
9286 RC);
9287 break;
9289 Opc = AArch64::MLSv8i8;
9290 RC = &AArch64::FPR64RegClass;
9291 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9292 break;
9294 Opc = AArch64::MLAv16i8;
9295 RC = &AArch64::FPR128RegClass;
9296 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9297 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv16i8,
9298 RC);
9299 break;
9301 Opc = AArch64::MLSv16i8;
9302 RC = &AArch64::FPR128RegClass;
9303 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9304 break;
9306 Opc = AArch64::MLAv4i16;
9307 RC = &AArch64::FPR64RegClass;
9308 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9309 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i16,
9310 RC);
9311 break;
9313 Opc = AArch64::MLSv4i16;
9314 RC = &AArch64::FPR64RegClass;
9315 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9316 break;
9318 Opc = AArch64::MLAv8i16;
9319 RC = &AArch64::FPR128RegClass;
9320 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9321 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i16,
9322 RC);
9323 break;
9325 Opc = AArch64::MLSv8i16;
9326 RC = &AArch64::FPR128RegClass;
9327 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9328 break;
9330 Opc = AArch64::MLAv2i32;
9331 RC = &AArch64::FPR64RegClass;
9332 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9333 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv2i32,
9334 RC);
9335 break;
9337 Opc = AArch64::MLSv2i32;
9338 RC = &AArch64::FPR64RegClass;
9339 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9340 break;
9342 Opc = AArch64::MLAv4i32;
9343 RC = &AArch64::FPR128RegClass;
9344 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9345 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i32,
9346 RC);
9347 break;
9349 Opc = AArch64::MLSv4i32;
9350 RC = &AArch64::FPR128RegClass;
9351 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9352 break;
9353
9355 Opc = AArch64::MLAv4i16_indexed;
9356 RC = &AArch64::FPR64RegClass;
9357 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9358 break;
9360 Opc = AArch64::MLAv4i16_indexed;
9361 RC = &AArch64::FPR64RegClass;
9362 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9363 break;
9365 Opc = AArch64::MLAv8i16_indexed;
9366 RC = &AArch64::FPR128RegClass;
9367 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9368 break;
9370 Opc = AArch64::MLAv8i16_indexed;
9371 RC = &AArch64::FPR128RegClass;
9372 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9373 break;
9375 Opc = AArch64::MLAv2i32_indexed;
9376 RC = &AArch64::FPR64RegClass;
9377 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9378 break;
9380 Opc = AArch64::MLAv2i32_indexed;
9381 RC = &AArch64::FPR64RegClass;
9382 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9383 break;
9385 Opc = AArch64::MLAv4i32_indexed;
9386 RC = &AArch64::FPR128RegClass;
9387 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9388 break;
9390 Opc = AArch64::MLAv4i32_indexed;
9391 RC = &AArch64::FPR128RegClass;
9392 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9393 break;
9394
9396 Opc = AArch64::MLAv4i16_indexed;
9397 RC = &AArch64::FPR64RegClass;
9398 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9399 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i16,
9400 RC);
9401 break;
9403 Opc = AArch64::MLSv4i16_indexed;
9404 RC = &AArch64::FPR64RegClass;
9405 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9406 break;
9408 Opc = AArch64::MLAv8i16_indexed;
9409 RC = &AArch64::FPR128RegClass;
9410 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9411 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i16,
9412 RC);
9413 break;
9415 Opc = AArch64::MLSv8i16_indexed;
9416 RC = &AArch64::FPR128RegClass;
9417 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9418 break;
9420 Opc = AArch64::MLAv2i32_indexed;
9421 RC = &AArch64::FPR64RegClass;
9422 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9423 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv2i32,
9424 RC);
9425 break;
9427 Opc = AArch64::MLSv2i32_indexed;
9428 RC = &AArch64::FPR64RegClass;
9429 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9430 break;
9432 Opc = AArch64::MLAv4i32_indexed;
9433 RC = &AArch64::FPR128RegClass;
9434 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9435 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i32,
9436 RC);
9437 break;
9439 Opc = AArch64::MLSv4i32_indexed;
9440 RC = &AArch64::FPR128RegClass;
9441 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9442 break;
9443
9444 // Floating Point Support
9446 Opc = AArch64::FMADDHrrr;
9447 RC = &AArch64::FPR16RegClass;
9448 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9449 break;
9451 Opc = AArch64::FMADDSrrr;
9452 RC = &AArch64::FPR32RegClass;
9453 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9454 break;
9456 Opc = AArch64::FMADDDrrr;
9457 RC = &AArch64::FPR64RegClass;
9458 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9459 break;
9460
9462 Opc = AArch64::FMADDHrrr;
9463 RC = &AArch64::FPR16RegClass;
9464 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9465 break;
9467 Opc = AArch64::FMADDSrrr;
9468 RC = &AArch64::FPR32RegClass;
9469 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9470 break;
9472 Opc = AArch64::FMADDDrrr;
9473 RC = &AArch64::FPR64RegClass;
9474 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9475 break;
9476
9478 Opc = AArch64::FMLAv1i32_indexed;
9479 RC = &AArch64::FPR32RegClass;
9480 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9482 break;
9484 Opc = AArch64::FMLAv1i32_indexed;
9485 RC = &AArch64::FPR32RegClass;
9486 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9488 break;
9489
9491 Opc = AArch64::FMLAv1i64_indexed;
9492 RC = &AArch64::FPR64RegClass;
9493 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9495 break;
9497 Opc = AArch64::FMLAv1i64_indexed;
9498 RC = &AArch64::FPR64RegClass;
9499 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9501 break;
9502
9504 RC = &AArch64::FPR64RegClass;
9505 Opc = AArch64::FMLAv4i16_indexed;
9506 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9508 break;
9510 RC = &AArch64::FPR64RegClass;
9511 Opc = AArch64::FMLAv4f16;
9512 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9514 break;
9516 RC = &AArch64::FPR64RegClass;
9517 Opc = AArch64::FMLAv4i16_indexed;
9518 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9520 break;
9522 RC = &AArch64::FPR64RegClass;
9523 Opc = AArch64::FMLAv4f16;
9524 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9526 break;
9527
9530 RC = &AArch64::FPR64RegClass;
9532 Opc = AArch64::FMLAv2i32_indexed;
9533 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9535 } else {
9536 Opc = AArch64::FMLAv2f32;
9537 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9539 }
9540 break;
9543 RC = &AArch64::FPR64RegClass;
9545 Opc = AArch64::FMLAv2i32_indexed;
9546 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9548 } else {
9549 Opc = AArch64::FMLAv2f32;
9550 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9552 }
9553 break;
9554
9556 RC = &AArch64::FPR128RegClass;
9557 Opc = AArch64::FMLAv8i16_indexed;
9558 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9560 break;
9562 RC = &AArch64::FPR128RegClass;
9563 Opc = AArch64::FMLAv8f16;
9564 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9566 break;
9568 RC = &AArch64::FPR128RegClass;
9569 Opc = AArch64::FMLAv8i16_indexed;
9570 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9572 break;
9574 RC = &AArch64::FPR128RegClass;
9575 Opc = AArch64::FMLAv8f16;
9576 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9578 break;
9579
9582 RC = &AArch64::FPR128RegClass;
9584 Opc = AArch64::FMLAv2i64_indexed;
9585 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9587 } else {
9588 Opc = AArch64::FMLAv2f64;
9589 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9591 }
9592 break;
9595 RC = &AArch64::FPR128RegClass;
9597 Opc = AArch64::FMLAv2i64_indexed;
9598 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9600 } else {
9601 Opc = AArch64::FMLAv2f64;
9602 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9604 }
9605 break;
9606
9609 RC = &AArch64::FPR128RegClass;
9611 Opc = AArch64::FMLAv4i32_indexed;
9612 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9614 } else {
9615 Opc = AArch64::FMLAv4f32;
9616 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9618 }
9619 break;
9620
9623 RC = &AArch64::FPR128RegClass;
9625 Opc = AArch64::FMLAv4i32_indexed;
9626 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9628 } else {
9629 Opc = AArch64::FMLAv4f32;
9630 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9632 }
9633 break;
9634
9636 Opc = AArch64::FNMSUBHrrr;
9637 RC = &AArch64::FPR16RegClass;
9638 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9639 break;
9641 Opc = AArch64::FNMSUBSrrr;
9642 RC = &AArch64::FPR32RegClass;
9643 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9644 break;
9646 Opc = AArch64::FNMSUBDrrr;
9647 RC = &AArch64::FPR64RegClass;
9648 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9649 break;
9650
9652 Opc = AArch64::FNMADDHrrr;
9653 RC = &AArch64::FPR16RegClass;
9654 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9655 break;
9657 Opc = AArch64::FNMADDSrrr;
9658 RC = &AArch64::FPR32RegClass;
9659 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9660 break;
9662 Opc = AArch64::FNMADDDrrr;
9663 RC = &AArch64::FPR64RegClass;
9664 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9665 break;
9666
9668 Opc = AArch64::FMSUBHrrr;
9669 RC = &AArch64::FPR16RegClass;
9670 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9671 break;
9673 Opc = AArch64::FMSUBSrrr;
9674 RC = &AArch64::FPR32RegClass;
9675 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9676 break;
9678 Opc = AArch64::FMSUBDrrr;
9679 RC = &AArch64::FPR64RegClass;
9680 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9681 break;
9682
9684 Opc = AArch64::FMLSv1i32_indexed;
9685 RC = &AArch64::FPR32RegClass;
9686 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9688 break;
9689
9691 Opc = AArch64::FMLSv1i64_indexed;
9692 RC = &AArch64::FPR64RegClass;
9693 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9695 break;
9696
9699 RC = &AArch64::FPR64RegClass;
9700 Register NewVR = MRI.createVirtualRegister(RC);
9701 MachineInstrBuilder MIB1 =
9702 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv4f16), NewVR)
9703 .add(Root.getOperand(2));
9704 InsInstrs.push_back(MIB1);
9705 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9707 Opc = AArch64::FMLAv4f16;
9708 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9709 FMAInstKind::Accumulator, &NewVR);
9710 } else {
9711 Opc = AArch64::FMLAv4i16_indexed;
9712 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9713 FMAInstKind::Indexed, &NewVR);
9714 }
9715 break;
9716 }
9718 RC = &AArch64::FPR64RegClass;
9719 Opc = AArch64::FMLSv4f16;
9720 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9722 break;
9724 RC = &AArch64::FPR64RegClass;
9725 Opc = AArch64::FMLSv4i16_indexed;
9726 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9728 break;
9729
9732 RC = &AArch64::FPR64RegClass;
9734 Opc = AArch64::FMLSv2i32_indexed;
9735 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9737 } else {
9738 Opc = AArch64::FMLSv2f32;
9739 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9741 }
9742 break;
9743
9746 RC = &AArch64::FPR128RegClass;
9747 Register NewVR = MRI.createVirtualRegister(RC);
9748 MachineInstrBuilder MIB1 =
9749 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv8f16), NewVR)
9750 .add(Root.getOperand(2));
9751 InsInstrs.push_back(MIB1);
9752 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9754 Opc = AArch64::FMLAv8f16;
9755 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9756 FMAInstKind::Accumulator, &NewVR);
9757 } else {
9758 Opc = AArch64::FMLAv8i16_indexed;
9759 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9760 FMAInstKind::Indexed, &NewVR);
9761 }
9762 break;
9763 }
9765 RC = &AArch64::FPR128RegClass;
9766 Opc = AArch64::FMLSv8f16;
9767 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9769 break;
9771 RC = &AArch64::FPR128RegClass;
9772 Opc = AArch64::FMLSv8i16_indexed;
9773 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9775 break;
9776
9779 RC = &AArch64::FPR128RegClass;
9781 Opc = AArch64::FMLSv2i64_indexed;
9782 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9784 } else {
9785 Opc = AArch64::FMLSv2f64;
9786 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9788 }
9789 break;
9790
9793 RC = &AArch64::FPR128RegClass;
9795 Opc = AArch64::FMLSv4i32_indexed;
9796 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9798 } else {
9799 Opc = AArch64::FMLSv4f32;
9800 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9802 }
9803 break;
9806 RC = &AArch64::FPR64RegClass;
9807 Register NewVR = MRI.createVirtualRegister(RC);
9808 MachineInstrBuilder MIB1 =
9809 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv2f32), NewVR)
9810 .add(Root.getOperand(2));
9811 InsInstrs.push_back(MIB1);
9812 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9814 Opc = AArch64::FMLAv2i32_indexed;
9815 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9816 FMAInstKind::Indexed, &NewVR);
9817 } else {
9818 Opc = AArch64::FMLAv2f32;
9819 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9820 FMAInstKind::Accumulator, &NewVR);
9821 }
9822 break;
9823 }
9826 RC = &AArch64::FPR128RegClass;
9827 Register NewVR = MRI.createVirtualRegister(RC);
9828 MachineInstrBuilder MIB1 =
9829 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv4f32), NewVR)
9830 .add(Root.getOperand(2));
9831 InsInstrs.push_back(MIB1);
9832 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9834 Opc = AArch64::FMLAv4i32_indexed;
9835 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9836 FMAInstKind::Indexed, &NewVR);
9837 } else {
9838 Opc = AArch64::FMLAv4f32;
9839 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9840 FMAInstKind::Accumulator, &NewVR);
9841 }
9842 break;
9843 }
9846 RC = &AArch64::FPR128RegClass;
9847 Register NewVR = MRI.createVirtualRegister(RC);
9848 MachineInstrBuilder MIB1 =
9849 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv2f64), NewVR)
9850 .add(Root.getOperand(2));
9851 InsInstrs.push_back(MIB1);
9852 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9854 Opc = AArch64::FMLAv2i64_indexed;
9855 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9856 FMAInstKind::Indexed, &NewVR);
9857 } else {
9858 Opc = AArch64::FMLAv2f64;
9859 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9860 FMAInstKind::Accumulator, &NewVR);
9861 }
9862 break;
9863 }
9866 unsigned IdxDupOp =
9868 : 2;
9869 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv2i32_indexed,
9870 &AArch64::FPR128RegClass, MRI);
9871 break;
9872 }
9875 unsigned IdxDupOp =
9877 : 2;
9878 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv2i64_indexed,
9879 &AArch64::FPR128RegClass, MRI);
9880 break;
9881 }
9884 unsigned IdxDupOp =
9886 : 2;
9887 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv4i16_indexed,
9888 &AArch64::FPR128_loRegClass, MRI);
9889 break;
9890 }
9893 unsigned IdxDupOp =
9895 : 2;
9896 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv4i32_indexed,
9897 &AArch64::FPR128RegClass, MRI);
9898 break;
9899 }
9902 unsigned IdxDupOp =
9904 : 2;
9905 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv8i16_indexed,
9906 &AArch64::FPR128_loRegClass, MRI);
9907 break;
9908 }
9910 MUL = genFNegatedMAD(MF, MRI, TII, Root, InsInstrs);
9911 break;
9912 }
9914 generateGatherLanePattern(Root, InsInstrs, DelInstrs, InstrIdxForVirtReg,
9915 Pattern, 4);
9916 break;
9917 }
9919 generateGatherLanePattern(Root, InsInstrs, DelInstrs, InstrIdxForVirtReg,
9920 Pattern, 8);
9921 break;
9922 }
9924 generateGatherLanePattern(Root, InsInstrs, DelInstrs, InstrIdxForVirtReg,
9925 Pattern, 16);
9926 break;
9927 }
9928
9929 } // end switch (Pattern)
9930 // Record MUL and ADD/SUB for deletion
9931 if (MUL)
9932 DelInstrs.push_back(MUL);
9933 DelInstrs.push_back(&Root);
9934
9935 // Set the flags on the inserted instructions to be the merged flags of the
9936 // instructions that we have combined.
9937 uint32_t Flags = Root.getFlags();
9938 if (MUL)
9939 Flags = Root.mergeFlagsWith(*MUL);
9940 for (auto *MI : InsInstrs)
9941 MI->setFlags(Flags);
9942}
9943
9944/// Replace csincr-branch sequence by simple conditional branch
9945///
9946/// Examples:
9947/// 1. \code
9948/// csinc w9, wzr, wzr, <condition code>
9949/// tbnz w9, #0, 0x44
9950/// \endcode
9951/// to
9952/// \code
9953/// b.<inverted condition code>
9954/// \endcode
9955///
9956/// 2. \code
9957/// csinc w9, wzr, wzr, <condition code>
9958/// tbz w9, #0, 0x44
9959/// \endcode
9960/// to
9961/// \code
9962/// b.<condition code>
9963/// \endcode
9964///
9965/// Replace compare and branch sequence by TBZ/TBNZ instruction when the
9966/// compare's constant operand is power of 2.
9967///
9968/// Examples:
9969/// \code
9970/// and w8, w8, #0x400
9971/// cbnz w8, L1
9972/// \endcode
9973/// to
9974/// \code
9975/// tbnz w8, #10, L1
9976/// \endcode
9977///
9978/// \param MI Conditional Branch
9979/// \return True when the simple conditional branch is generated
9980///
9982 bool IsNegativeBranch = false;
9983 bool IsTestAndBranch = false;
9984 unsigned TargetBBInMI = 0;
9985 switch (MI.getOpcode()) {
9986 default:
9987 llvm_unreachable("Unknown branch instruction?");
9988 case AArch64::Bcc:
9989 case AArch64::CBWPri:
9990 case AArch64::CBXPri:
9991 case AArch64::CBBAssertExt:
9992 case AArch64::CBHAssertExt:
9993 case AArch64::CBWPrr:
9994 case AArch64::CBXPrr:
9995 return false;
9996 case AArch64::CBZW:
9997 case AArch64::CBZX:
9998 TargetBBInMI = 1;
9999 break;
10000 case AArch64::CBNZW:
10001 case AArch64::CBNZX:
10002 TargetBBInMI = 1;
10003 IsNegativeBranch = true;
10004 break;
10005 case AArch64::TBZW:
10006 case AArch64::TBZX:
10007 TargetBBInMI = 2;
10008 IsTestAndBranch = true;
10009 break;
10010 case AArch64::TBNZW:
10011 case AArch64::TBNZX:
10012 TargetBBInMI = 2;
10013 IsNegativeBranch = true;
10014 IsTestAndBranch = true;
10015 break;
10016 }
10017 // So we increment a zero register and test for bits other
10018 // than bit 0? Conservatively bail out in case the verifier
10019 // missed this case.
10020 if (IsTestAndBranch && MI.getOperand(1).getImm())
10021 return false;
10022
10023 // Find Definition.
10024 assert(MI.getParent() && "Incomplete machine instruction\n");
10025 MachineBasicBlock *MBB = MI.getParent();
10026 MachineFunction *MF = MBB->getParent();
10027 MachineRegisterInfo *MRI = &MF->getRegInfo();
10028 Register VReg = MI.getOperand(0).getReg();
10029 if (!VReg.isVirtual())
10030 return false;
10031
10032 MachineInstr *DefMI = MRI->getVRegDef(VReg);
10033
10034 // Look through COPY instructions to find definition.
10035 while (DefMI->isCopy()) {
10036 Register CopyVReg = DefMI->getOperand(1).getReg();
10037 if (!MRI->hasOneNonDBGUse(CopyVReg))
10038 return false;
10039 if (!MRI->hasOneDef(CopyVReg))
10040 return false;
10041 DefMI = MRI->getVRegDef(CopyVReg);
10042 }
10043
10044 switch (DefMI->getOpcode()) {
10045 default:
10046 return false;
10047 // Fold AND into a TBZ/TBNZ if constant operand is power of 2.
10048 case AArch64::ANDWri:
10049 case AArch64::ANDXri: {
10050 if (IsTestAndBranch)
10051 return false;
10052 if (DefMI->getParent() != MBB)
10053 return false;
10054 if (!MRI->hasOneNonDBGUse(VReg))
10055 return false;
10056
10057 bool Is32Bit = (DefMI->getOpcode() == AArch64::ANDWri);
10059 DefMI->getOperand(2).getImm(), Is32Bit ? 32 : 64);
10060 if (!isPowerOf2_64(Mask))
10061 return false;
10062
10063 MachineOperand &MO = DefMI->getOperand(1);
10064 Register NewReg = MO.getReg();
10065 if (!NewReg.isVirtual())
10066 return false;
10067
10068 assert(!MRI->def_empty(NewReg) && "Register must be defined.");
10069
10070 MachineBasicBlock &RefToMBB = *MBB;
10071 MachineBasicBlock *TBB = MI.getOperand(1).getMBB();
10072 DebugLoc DL = MI.getDebugLoc();
10073 unsigned Imm = Log2_64(Mask);
10074 unsigned Opc = (Imm < 32)
10075 ? (IsNegativeBranch ? AArch64::TBNZW : AArch64::TBZW)
10076 : (IsNegativeBranch ? AArch64::TBNZX : AArch64::TBZX);
10077 MachineInstr *NewMI = BuildMI(RefToMBB, MI, DL, get(Opc))
10078 .addReg(NewReg)
10079 .addImm(Imm)
10080 .addMBB(TBB);
10081 // Register lives on to the CBZ now.
10082 MO.setIsKill(false);
10083
10084 // For immediate smaller than 32, we need to use the 32-bit
10085 // variant (W) in all cases. Indeed the 64-bit variant does not
10086 // allow to encode them.
10087 // Therefore, if the input register is 64-bit, we need to take the
10088 // 32-bit sub-part.
10089 if (!Is32Bit && Imm < 32)
10090 NewMI->getOperand(0).setSubReg(AArch64::sub_32);
10091 MI.eraseFromParent();
10092 return true;
10093 }
10094 // Look for CSINC
10095 case AArch64::CSINCWr:
10096 case AArch64::CSINCXr: {
10097 if (!(DefMI->getOperand(1).getReg() == AArch64::WZR &&
10098 DefMI->getOperand(2).getReg() == AArch64::WZR) &&
10099 !(DefMI->getOperand(1).getReg() == AArch64::XZR &&
10100 DefMI->getOperand(2).getReg() == AArch64::XZR))
10101 return false;
10102
10103 if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr,
10104 true) != -1)
10105 return false;
10106
10107 AArch64CC::CondCode CC = (AArch64CC::CondCode)DefMI->getOperand(3).getImm();
10108 // Convert only when the condition code is not modified between
10109 // the CSINC and the branch. The CC may be used by other
10110 // instructions in between.
10112 return false;
10113 MachineBasicBlock &RefToMBB = *MBB;
10114 MachineBasicBlock *TBB = MI.getOperand(TargetBBInMI).getMBB();
10115 DebugLoc DL = MI.getDebugLoc();
10116 if (IsNegativeBranch)
10118 BuildMI(RefToMBB, MI, DL, get(AArch64::Bcc)).addImm(CC).addMBB(TBB);
10119 MI.eraseFromParent();
10120 return true;
10121 }
10122 }
10123}
10124
10125std::pair<unsigned, unsigned>
10126AArch64InstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
10127 const unsigned Mask = AArch64II::MO_FRAGMENT;
10128 return std::make_pair(TF & Mask, TF & ~Mask);
10129}
10130
10132AArch64InstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
10133 using namespace AArch64II;
10134
10135 static const std::pair<unsigned, const char *> TargetFlags[] = {
10136 {MO_PAGE, "aarch64-page"}, {MO_PAGEOFF, "aarch64-pageoff"},
10137 {MO_G3, "aarch64-g3"}, {MO_G2, "aarch64-g2"},
10138 {MO_G1, "aarch64-g1"}, {MO_G0, "aarch64-g0"},
10139 {MO_HI12, "aarch64-hi12"}};
10140 return ArrayRef(TargetFlags);
10141}
10142
10144AArch64InstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
10145 using namespace AArch64II;
10146
10147 static const std::pair<unsigned, const char *> TargetFlags[] = {
10148 {MO_COFFSTUB, "aarch64-coffstub"},
10149 {MO_GOT, "aarch64-got"},
10150 {MO_NC, "aarch64-nc"},
10151 {MO_S, "aarch64-s"},
10152 {MO_TLS, "aarch64-tls"},
10153 {MO_DLLIMPORT, "aarch64-dllimport"},
10154 {MO_PREL, "aarch64-prel"},
10155 {MO_TAGGED, "aarch64-tagged"},
10156 {MO_ARM64EC_CALLMANGLE, "aarch64-arm64ec-callmangle"},
10157 };
10158 return ArrayRef(TargetFlags);
10159}
10160
10162AArch64InstrInfo::getSerializableMachineMemOperandTargetFlags() const {
10163 static const std::pair<MachineMemOperand::Flags, const char *> TargetFlags[] =
10164 {{MOSuppressPair, "aarch64-suppress-pair"},
10165 {MOStridedAccess, "aarch64-strided-access"}};
10166 return ArrayRef(TargetFlags);
10167}
10168
10169/// Constants defining how certain sequences should be outlined.
10170/// This encompasses how an outlined function should be called, and what kind of
10171/// frame should be emitted for that outlined function.
10172///
10173/// \p MachineOutlinerDefault implies that the function should be called with
10174/// a save and restore of LR to the stack.
10175///
10176/// That is,
10177///
10178/// I1 Save LR OUTLINED_FUNCTION:
10179/// I2 --> BL OUTLINED_FUNCTION I1
10180/// I3 Restore LR I2
10181/// I3
10182/// RET
10183///
10184/// * Call construction overhead: 3 (save + BL + restore)
10185/// * Frame construction overhead: 1 (ret)
10186/// * Requires stack fixups? Yes
10187///
10188/// \p MachineOutlinerTailCall implies that the function is being created from
10189/// a sequence of instructions ending in a return.
10190///
10191/// That is,
10192///
10193/// I1 OUTLINED_FUNCTION:
10194/// I2 --> B OUTLINED_FUNCTION I1
10195/// RET I2
10196/// RET
10197///
10198/// * Call construction overhead: 1 (B)
10199/// * Frame construction overhead: 0 (Return included in sequence)
10200/// * Requires stack fixups? No
10201///
10202/// \p MachineOutlinerNoLRSave implies that the function should be called using
10203/// a BL instruction, but doesn't require LR to be saved and restored. This
10204/// happens when LR is known to be dead.
10205///
10206/// That is,
10207///
10208/// I1 OUTLINED_FUNCTION:
10209/// I2 --> BL OUTLINED_FUNCTION I1
10210/// I3 I2
10211/// I3
10212/// RET
10213///
10214/// * Call construction overhead: 1 (BL)
10215/// * Frame construction overhead: 1 (RET)
10216/// * Requires stack fixups? No
10217///
10218/// \p MachineOutlinerThunk implies that the function is being created from
10219/// a sequence of instructions ending in a call. The outlined function is
10220/// called with a BL instruction, and the outlined function tail-calls the
10221/// original call destination.
10222///
10223/// That is,
10224///
10225/// I1 OUTLINED_FUNCTION:
10226/// I2 --> BL OUTLINED_FUNCTION I1
10227/// BL f I2
10228/// B f
10229/// * Call construction overhead: 1 (BL)
10230/// * Frame construction overhead: 0
10231/// * Requires stack fixups? No
10232///
10233/// \p MachineOutlinerRegSave implies that the function should be called with a
10234/// save and restore of LR to an available register. This allows us to avoid
10235/// stack fixups. Note that this outlining variant is compatible with the
10236/// NoLRSave case.
10237///
10238/// That is,
10239///
10240/// I1 Save LR OUTLINED_FUNCTION:
10241/// I2 --> BL OUTLINED_FUNCTION I1
10242/// I3 Restore LR I2
10243/// I3
10244/// RET
10245///
10246/// * Call construction overhead: 3 (save + BL + restore)
10247/// * Frame construction overhead: 1 (ret)
10248/// * Requires stack fixups? No
10250 MachineOutlinerDefault, /// Emit a save, restore, call, and return.
10251 MachineOutlinerTailCall, /// Only emit a branch.
10252 MachineOutlinerNoLRSave, /// Emit a call and return.
10253 MachineOutlinerThunk, /// Emit a call and tail-call.
10254 MachineOutlinerRegSave /// Same as default, but save to a register.
10255};
10256
10262
10264AArch64InstrInfo::findRegisterToSaveLRTo(outliner::Candidate &C) const {
10265 MachineFunction *MF = C.getMF();
10266 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
10267 const AArch64RegisterInfo *ARI =
10268 static_cast<const AArch64RegisterInfo *>(&TRI);
10269 // Check if there is an available register across the sequence that we can
10270 // use.
10271 for (unsigned Reg : AArch64::GPR64RegClass) {
10272 if (!ARI->isReservedReg(*MF, Reg) &&
10273 Reg != AArch64::LR && // LR is not reserved, but don't use it.
10274 Reg != AArch64::X16 && // X16 is not guaranteed to be preserved.
10275 Reg != AArch64::X17 && // Ditto for X17.
10276 C.isAvailableAcrossAndOutOfSeq(Reg, TRI) &&
10277 C.isAvailableInsideSeq(Reg, TRI))
10278 return Reg;
10279 }
10280 return Register();
10281}
10282
10283static bool
10285 const outliner::Candidate &b) {
10286 const auto &MFIa = a.getMF()->getInfo<AArch64FunctionInfo>();
10287 const auto &MFIb = b.getMF()->getInfo<AArch64FunctionInfo>();
10288
10289 return MFIa->getSignReturnAddressCondition() ==
10291}
10292
10293static bool
10295 const outliner::Candidate &b) {
10296 const auto &MFIa = a.getMF()->getInfo<AArch64FunctionInfo>();
10297 const auto &MFIb = b.getMF()->getInfo<AArch64FunctionInfo>();
10298
10299 return MFIa->shouldSignWithBKey() == MFIb->shouldSignWithBKey();
10300}
10301
10303 const outliner::Candidate &b) {
10304 const AArch64Subtarget &SubtargetA =
10306 const AArch64Subtarget &SubtargetB =
10307 b.getMF()->getSubtarget<AArch64Subtarget>();
10308 return SubtargetA.hasV8_3aOps() == SubtargetB.hasV8_3aOps();
10309}
10310
10311std::optional<std::unique_ptr<outliner::OutlinedFunction>>
10312AArch64InstrInfo::getOutliningCandidateInfo(
10313 const MachineModuleInfo &MMI,
10314 std::vector<outliner::Candidate> &RepeatedSequenceLocs,
10315 unsigned MinRepeats) const {
10316 unsigned SequenceSize = 0;
10317 for (auto &MI : RepeatedSequenceLocs[0])
10318 SequenceSize += getInstSizeInBytes(MI);
10319
10320 unsigned NumBytesToCreateFrame = 0;
10321
10322 // Avoid splitting ADRP ADD/LDR pair into outlined functions.
10323 // These instructions are fused together by the scheduler.
10324 // Any candidate where ADRP is the last instruction should be rejected
10325 // as that will lead to splitting ADRP pair.
10326 MachineInstr &LastMI = RepeatedSequenceLocs[0].back();
10327 MachineInstr &FirstMI = RepeatedSequenceLocs[0].front();
10328 if (LastMI.getOpcode() == AArch64::ADRP &&
10329 (LastMI.getOperand(1).getTargetFlags() & AArch64II::MO_PAGE) != 0 &&
10330 (LastMI.getOperand(1).getTargetFlags() & AArch64II::MO_GOT) != 0) {
10331 return std::nullopt;
10332 }
10333
10334 // Similarly any candidate where the first instruction is ADD/LDR with a
10335 // page offset should be rejected to avoid ADRP splitting.
10336 if ((FirstMI.getOpcode() == AArch64::ADDXri ||
10337 FirstMI.getOpcode() == AArch64::LDRXui) &&
10338 (FirstMI.getOperand(2).getTargetFlags() & AArch64II::MO_PAGEOFF) != 0 &&
10339 (FirstMI.getOperand(2).getTargetFlags() & AArch64II::MO_GOT) != 0) {
10340 return std::nullopt;
10341 }
10342
10343 // We only allow outlining for functions having exactly matching return
10344 // address signing attributes, i.e., all share the same value for the
10345 // attribute "sign-return-address" and all share the same type of key they
10346 // are signed with.
10347 // Additionally we require all functions to simultaneously either support
10348 // v8.3a features or not. Otherwise an outlined function could get signed
10349 // using dedicated v8.3 instructions and a call from a function that doesn't
10350 // support v8.3 instructions would therefore be invalid.
10351 if (std::adjacent_find(
10352 RepeatedSequenceLocs.begin(), RepeatedSequenceLocs.end(),
10353 [](const outliner::Candidate &a, const outliner::Candidate &b) {
10354 // Return true if a and b are non-equal w.r.t. return address
10355 // signing or support of v8.3a features
10356 if (outliningCandidatesSigningScopeConsensus(a, b) &&
10357 outliningCandidatesSigningKeyConsensus(a, b) &&
10358 outliningCandidatesV8_3OpsConsensus(a, b)) {
10359 return false;
10360 }
10361 return true;
10362 }) != RepeatedSequenceLocs.end()) {
10363 return std::nullopt;
10364 }
10365
10366 // Since at this point all candidates agree on their return address signing
10367 // picking just one is fine. If the candidate functions potentially sign their
10368 // return addresses, the outlined function should do the same. Note that in
10369 // the case of "sign-return-address"="non-leaf" this is an assumption: It is
10370 // not certainly true that the outlined function will have to sign its return
10371 // address but this decision is made later, when the decision to outline
10372 // has already been made.
10373 // The same holds for the number of additional instructions we need: On
10374 // v8.3a RET can be replaced by RETAA/RETAB and no AUT instruction is
10375 // necessary. However, at this point we don't know if the outlined function
10376 // will have a RET instruction so we assume the worst.
10377 const TargetRegisterInfo &TRI = getRegisterInfo();
10378 // Performing a tail call may require extra checks when PAuth is enabled.
10379 // If PAuth is disabled, set it to zero for uniformity.
10380 unsigned NumBytesToCheckLRInTCEpilogue = 0;
10381 const auto RASignCondition = RepeatedSequenceLocs[0]
10382 .getMF()
10383 ->getInfo<AArch64FunctionInfo>()
10384 ->getSignReturnAddressCondition();
10385 if (RASignCondition != SignReturnAddress::None) {
10386 // One PAC and one AUT instructions
10387 NumBytesToCreateFrame += 8;
10388
10389 // PAuth is enabled - set extra tail call cost, if any.
10390 auto LRCheckMethod = Subtarget.getAuthenticatedLRCheckMethod(
10391 *RepeatedSequenceLocs[0].getMF());
10392 NumBytesToCheckLRInTCEpilogue =
10394 // Checking the authenticated LR value may significantly impact
10395 // SequenceSize, so account for it for more precise results.
10396 if (isTailCallReturnInst(RepeatedSequenceLocs[0].back()))
10397 SequenceSize += NumBytesToCheckLRInTCEpilogue;
10398
10399 // We have to check if sp modifying instructions would get outlined.
10400 // If so we only allow outlining if sp is unchanged overall, so matching
10401 // sub and add instructions are okay to outline, all other sp modifications
10402 // are not
10403 auto hasIllegalSPModification = [&TRI](outliner::Candidate &C) {
10404 int SPValue = 0;
10405 for (auto &MI : C) {
10406 if (MI.modifiesRegister(AArch64::SP, &TRI)) {
10407 switch (MI.getOpcode()) {
10408 case AArch64::ADDXri:
10409 case AArch64::ADDWri:
10410 assert(MI.getNumOperands() == 4 && "Wrong number of operands");
10411 assert(MI.getOperand(2).isImm() &&
10412 "Expected operand to be immediate");
10413 assert(MI.getOperand(1).isReg() &&
10414 "Expected operand to be a register");
10415 // Check if the add just increments sp. If so, we search for
10416 // matching sub instructions that decrement sp. If not, the
10417 // modification is illegal
10418 if (MI.getOperand(1).getReg() == AArch64::SP)
10419 SPValue += MI.getOperand(2).getImm();
10420 else
10421 return true;
10422 break;
10423 case AArch64::SUBXri:
10424 case AArch64::SUBWri:
10425 assert(MI.getNumOperands() == 4 && "Wrong number of operands");
10426 assert(MI.getOperand(2).isImm() &&
10427 "Expected operand to be immediate");
10428 assert(MI.getOperand(1).isReg() &&
10429 "Expected operand to be a register");
10430 // Check if the sub just decrements sp. If so, we search for
10431 // matching add instructions that increment sp. If not, the
10432 // modification is illegal
10433 if (MI.getOperand(1).getReg() == AArch64::SP)
10434 SPValue -= MI.getOperand(2).getImm();
10435 else
10436 return true;
10437 break;
10438 default:
10439 return true;
10440 }
10441 }
10442 }
10443 if (SPValue)
10444 return true;
10445 return false;
10446 };
10447 // Remove candidates with illegal stack modifying instructions
10448 llvm::erase_if(RepeatedSequenceLocs, hasIllegalSPModification);
10449
10450 // If the sequence doesn't have enough candidates left, then we're done.
10451 if (RepeatedSequenceLocs.size() < MinRepeats)
10452 return std::nullopt;
10453 }
10454
10455 // Properties about candidate MBBs that hold for all of them.
10456 unsigned FlagsSetInAll = 0xF;
10457
10458 // Compute liveness information for each candidate, and set FlagsSetInAll.
10459 for (outliner::Candidate &C : RepeatedSequenceLocs)
10460 FlagsSetInAll &= C.Flags;
10461
10462 unsigned LastInstrOpcode = RepeatedSequenceLocs[0].back().getOpcode();
10463
10464 // Helper lambda which sets call information for every candidate.
10465 auto SetCandidateCallInfo =
10466 [&RepeatedSequenceLocs](unsigned CallID, unsigned NumBytesForCall) {
10467 for (outliner::Candidate &C : RepeatedSequenceLocs)
10468 C.setCallInfo(CallID, NumBytesForCall);
10469 };
10470
10471 unsigned FrameID = MachineOutlinerDefault;
10472 NumBytesToCreateFrame += 4;
10473
10474 bool HasBTI = any_of(RepeatedSequenceLocs, [](outliner::Candidate &C) {
10475 return C.getMF()->getInfo<AArch64FunctionInfo>()->branchTargetEnforcement();
10476 });
10477
10478 // We check to see if CFI Instructions are present, and if they are
10479 // we find the number of CFI Instructions in the candidates.
10480 unsigned CFICount = 0;
10481 for (auto &I : RepeatedSequenceLocs[0]) {
10482 if (I.isCFIInstruction())
10483 CFICount++;
10484 }
10485
10486 // We compare the number of found CFI Instructions to the number of CFI
10487 // instructions in the parent function for each candidate. We must check this
10488 // since if we outline one of the CFI instructions in a function, we have to
10489 // outline them all for correctness. If we do not, the address offsets will be
10490 // incorrect between the two sections of the program.
10491 for (outliner::Candidate &C : RepeatedSequenceLocs) {
10492 std::vector<MCCFIInstruction> CFIInstructions =
10493 C.getMF()->getFrameInstructions();
10494
10495 if (CFICount > 0 && CFICount != CFIInstructions.size())
10496 return std::nullopt;
10497 }
10498
10499 // Returns true if an instructions is safe to fix up, false otherwise.
10500 auto IsSafeToFixup = [this, &TRI](MachineInstr &MI) {
10501 if (MI.isCall())
10502 return true;
10503
10504 if (!MI.modifiesRegister(AArch64::SP, &TRI) &&
10505 !MI.readsRegister(AArch64::SP, &TRI))
10506 return true;
10507
10508 // Any modification of SP will break our code to save/restore LR.
10509 // FIXME: We could handle some instructions which add a constant
10510 // offset to SP, with a bit more work.
10511 if (MI.modifiesRegister(AArch64::SP, &TRI))
10512 return false;
10513
10514 // At this point, we have a stack instruction that we might need to
10515 // fix up. We'll handle it if it's a load or store.
10516 if (MI.mayLoadOrStore()) {
10517 const MachineOperand *Base; // Filled with the base operand of MI.
10518 int64_t Offset; // Filled with the offset of MI.
10519 bool OffsetIsScalable;
10520
10521 // Does it allow us to offset the base operand and is the base the
10522 // register SP?
10523 if (!getMemOperandWithOffset(MI, Base, Offset, OffsetIsScalable, &TRI) ||
10524 !Base->isReg() || Base->getReg() != AArch64::SP)
10525 return false;
10526
10527 // Fixe-up code below assumes bytes.
10528 if (OffsetIsScalable)
10529 return false;
10530
10531 // Find the minimum/maximum offset for this instruction and check
10532 // if fixing it up would be in range.
10533 int64_t MinOffset,
10534 MaxOffset; // Unscaled offsets for the instruction.
10535 // The scale to multiply the offsets by.
10536 TypeSize Scale(0U, false), DummyWidth(0U, false);
10537 getMemOpInfo(MI.getOpcode(), Scale, DummyWidth, MinOffset, MaxOffset);
10538
10539 Offset += 16; // Update the offset to what it would be if we outlined.
10540 if (Offset < MinOffset * (int64_t)Scale.getFixedValue() ||
10541 Offset > MaxOffset * (int64_t)Scale.getFixedValue())
10542 return false;
10543
10544 // It's in range, so we can outline it.
10545 return true;
10546 }
10547
10548 // FIXME: Add handling for instructions like "add x0, sp, #8".
10549
10550 // We can't fix it up, so don't outline it.
10551 return false;
10552 };
10553
10554 // True if it's possible to fix up each stack instruction in this sequence.
10555 // Important for frames/call variants that modify the stack.
10556 bool AllStackInstrsSafe =
10557 llvm::all_of(RepeatedSequenceLocs[0], IsSafeToFixup);
10558
10559 // If the last instruction in any candidate is a terminator, then we should
10560 // tail call all of the candidates.
10561 if (RepeatedSequenceLocs[0].back().isTerminator()) {
10562 FrameID = MachineOutlinerTailCall;
10563 NumBytesToCreateFrame = 0;
10564 unsigned NumBytesForCall = 4 + NumBytesToCheckLRInTCEpilogue;
10565 SetCandidateCallInfo(MachineOutlinerTailCall, NumBytesForCall);
10566 }
10567
10568 else if (LastInstrOpcode == AArch64::BL ||
10569 ((LastInstrOpcode == AArch64::BLR ||
10570 LastInstrOpcode == AArch64::BLRNoIP) &&
10571 !HasBTI)) {
10572 // FIXME: Do we need to check if the code after this uses the value of LR?
10573 FrameID = MachineOutlinerThunk;
10574 NumBytesToCreateFrame = NumBytesToCheckLRInTCEpilogue;
10575 SetCandidateCallInfo(MachineOutlinerThunk, 4);
10576 }
10577
10578 else {
10579 // We need to decide how to emit calls + frames. We can always emit the same
10580 // frame if we don't need to save to the stack. If we have to save to the
10581 // stack, then we need a different frame.
10582 unsigned NumBytesNoStackCalls = 0;
10583 std::vector<outliner::Candidate> CandidatesWithoutStackFixups;
10584
10585 // Check if we have to save LR.
10586 for (outliner::Candidate &C : RepeatedSequenceLocs) {
10587 bool LRAvailable =
10589 ? C.isAvailableAcrossAndOutOfSeq(AArch64::LR, TRI)
10590 : true;
10591 // If we have a noreturn caller, then we're going to be conservative and
10592 // say that we have to save LR. If we don't have a ret at the end of the
10593 // block, then we can't reason about liveness accurately.
10594 //
10595 // FIXME: We can probably do better than always disabling this in
10596 // noreturn functions by fixing up the liveness info.
10597 bool IsNoReturn =
10598 C.getMF()->getFunction().hasFnAttribute(Attribute::NoReturn);
10599
10600 // Is LR available? If so, we don't need a save.
10601 if (LRAvailable && !IsNoReturn) {
10602 NumBytesNoStackCalls += 4;
10603 C.setCallInfo(MachineOutlinerNoLRSave, 4);
10604 CandidatesWithoutStackFixups.push_back(C);
10605 }
10606
10607 // Is an unused register available? If so, we won't modify the stack, so
10608 // we can outline with the same frame type as those that don't save LR.
10609 else if (findRegisterToSaveLRTo(C)) {
10610 NumBytesNoStackCalls += 12;
10611 C.setCallInfo(MachineOutlinerRegSave, 12);
10612 CandidatesWithoutStackFixups.push_back(C);
10613 }
10614
10615 // Is SP used in the sequence at all? If not, we don't have to modify
10616 // the stack, so we are guaranteed to get the same frame.
10617 else if (C.isAvailableInsideSeq(AArch64::SP, TRI)) {
10618 NumBytesNoStackCalls += 12;
10619 C.setCallInfo(MachineOutlinerDefault, 12);
10620 CandidatesWithoutStackFixups.push_back(C);
10621 }
10622
10623 // If we outline this, we need to modify the stack. Pretend we don't
10624 // outline this by saving all of its bytes.
10625 else {
10626 NumBytesNoStackCalls += SequenceSize;
10627 }
10628 }
10629
10630 // If there are no places where we have to save LR, then note that we
10631 // don't have to update the stack. Otherwise, give every candidate the
10632 // default call type, as long as it's safe to do so.
10633 if (!AllStackInstrsSafe ||
10634 NumBytesNoStackCalls <= RepeatedSequenceLocs.size() * 12) {
10635 RepeatedSequenceLocs = CandidatesWithoutStackFixups;
10636 FrameID = MachineOutlinerNoLRSave;
10637 if (RepeatedSequenceLocs.size() < MinRepeats)
10638 return std::nullopt;
10639 } else {
10640 SetCandidateCallInfo(MachineOutlinerDefault, 12);
10641
10642 // Bugzilla ID: 46767
10643 // TODO: Check if fixing up the stack more than once is safe so we can
10644 // outline these.
10645 //
10646 // An outline resulting in a caller that requires stack fixups at the
10647 // callsite to a callee that also requires stack fixups can happen when
10648 // there are no available registers at the candidate callsite for a
10649 // candidate that itself also has calls.
10650 //
10651 // In other words if function_containing_sequence in the following pseudo
10652 // assembly requires that we save LR at the point of the call, but there
10653 // are no available registers: in this case we save using SP and as a
10654 // result the SP offsets requires stack fixups by multiples of 16.
10655 //
10656 // function_containing_sequence:
10657 // ...
10658 // save LR to SP <- Requires stack instr fixups in OUTLINED_FUNCTION_N
10659 // call OUTLINED_FUNCTION_N
10660 // restore LR from SP
10661 // ...
10662 //
10663 // OUTLINED_FUNCTION_N:
10664 // save LR to SP <- Requires stack instr fixups in OUTLINED_FUNCTION_N
10665 // ...
10666 // bl foo
10667 // restore LR from SP
10668 // ret
10669 //
10670 // Because the code to handle more than one stack fixup does not
10671 // currently have the proper checks for legality, these cases will assert
10672 // in the AArch64 MachineOutliner. This is because the code to do this
10673 // needs more hardening, testing, better checks that generated code is
10674 // legal, etc and because it is only verified to handle a single pass of
10675 // stack fixup.
10676 //
10677 // The assert happens in AArch64InstrInfo::buildOutlinedFrame to catch
10678 // these cases until they are known to be handled. Bugzilla 46767 is
10679 // referenced in comments at the assert site.
10680 //
10681 // To avoid asserting (or generating non-legal code on noassert builds)
10682 // we remove all candidates which would need more than one stack fixup by
10683 // pruning the cases where the candidate has calls while also having no
10684 // available LR and having no available general purpose registers to copy
10685 // LR to (ie one extra stack save/restore).
10686 //
10687 if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) {
10688 erase_if(RepeatedSequenceLocs, [this, &TRI](outliner::Candidate &C) {
10689 auto IsCall = [](const MachineInstr &MI) { return MI.isCall(); };
10690 return (llvm::any_of(C, IsCall)) &&
10691 (!C.isAvailableAcrossAndOutOfSeq(AArch64::LR, TRI) ||
10692 !findRegisterToSaveLRTo(C));
10693 });
10694 }
10695 }
10696
10697 // If we dropped all of the candidates, bail out here.
10698 if (RepeatedSequenceLocs.size() < MinRepeats)
10699 return std::nullopt;
10700 }
10701
10702 // Does every candidate's MBB contain a call? If so, then we might have a call
10703 // in the range.
10704 if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) {
10705 // Check if the range contains a call. These require a save + restore of the
10706 // link register.
10707 outliner::Candidate &FirstCand = RepeatedSequenceLocs[0];
10708 bool ModStackToSaveLR = false;
10709 if (any_of(drop_end(FirstCand),
10710 [](const MachineInstr &MI) { return MI.isCall(); }))
10711 ModStackToSaveLR = true;
10712
10713 // Handle the last instruction separately. If this is a tail call, then the
10714 // last instruction is a call. We don't want to save + restore in this case.
10715 // However, it could be possible that the last instruction is a call without
10716 // it being valid to tail call this sequence. We should consider this as
10717 // well.
10718 else if (FrameID != MachineOutlinerThunk &&
10719 FrameID != MachineOutlinerTailCall && FirstCand.back().isCall())
10720 ModStackToSaveLR = true;
10721
10722 if (ModStackToSaveLR) {
10723 // We can't fix up the stack. Bail out.
10724 if (!AllStackInstrsSafe)
10725 return std::nullopt;
10726
10727 // Save + restore LR.
10728 NumBytesToCreateFrame += 8;
10729 }
10730 }
10731
10732 // If we have CFI instructions, we can only outline if the outlined section
10733 // can be a tail call
10734 if (FrameID != MachineOutlinerTailCall && CFICount > 0)
10735 return std::nullopt;
10736
10737 return std::make_unique<outliner::OutlinedFunction>(
10738 RepeatedSequenceLocs, SequenceSize, NumBytesToCreateFrame, FrameID);
10739}
10740
10741void AArch64InstrInfo::mergeOutliningCandidateAttributes(
10742 Function &F, std::vector<outliner::Candidate> &Candidates) const {
10743 // If a bunch of candidates reach this point they must agree on their return
10744 // address signing. It is therefore enough to just consider the signing
10745 // behaviour of one of them
10746 const auto &CFn = Candidates.front().getMF()->getFunction();
10747
10748 if (CFn.hasFnAttribute("ptrauth-returns"))
10749 F.addFnAttr(CFn.getFnAttribute("ptrauth-returns"));
10750 if (CFn.hasFnAttribute("ptrauth-auth-traps"))
10751 F.addFnAttr(CFn.getFnAttribute("ptrauth-auth-traps"));
10752 // Since all candidates belong to the same module, just copy the
10753 // function-level attributes of an arbitrary function.
10754 if (CFn.hasFnAttribute("sign-return-address"))
10755 F.addFnAttr(CFn.getFnAttribute("sign-return-address"));
10756 if (CFn.hasFnAttribute("sign-return-address-key"))
10757 F.addFnAttr(CFn.getFnAttribute("sign-return-address-key"));
10758
10759 AArch64GenInstrInfo::mergeOutliningCandidateAttributes(F, Candidates);
10760}
10761
10762bool AArch64InstrInfo::isFunctionSafeToOutlineFrom(
10763 MachineFunction &MF, bool OutlineFromLinkOnceODRs) const {
10764 const Function &F = MF.getFunction();
10765
10766 // Can F be deduplicated by the linker? If it can, don't outline from it.
10767 if (!OutlineFromLinkOnceODRs && F.hasLinkOnceODRLinkage())
10768 return false;
10769
10770 // Don't outline from functions with section markings; the program could
10771 // expect that all the code is in the named section.
10772 // FIXME: Allow outlining from multiple functions with the same section
10773 // marking.
10774 if (F.hasSection())
10775 return false;
10776
10777 // Outlining from functions with redzones is unsafe since the outliner may
10778 // modify the stack. Check if hasRedZone is true or unknown; if yes, don't
10779 // outline from it.
10780 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
10781 if (!AFI || AFI->hasRedZone().value_or(true))
10782 return false;
10783
10784 // FIXME: Determine whether it is safe to outline from functions which contain
10785 // streaming-mode changes. We may need to ensure any smstart/smstop pairs are
10786 // outlined together and ensure it is safe to outline with async unwind info,
10787 // required for saving & restoring VG around calls.
10788 if (AFI->hasStreamingModeChanges())
10789 return false;
10790
10791 // FIXME: Teach the outliner to generate/handle Windows unwind info.
10793 return false;
10794
10795 // It's safe to outline from MF.
10796 return true;
10797}
10798
10800AArch64InstrInfo::getOutlinableRanges(MachineBasicBlock &MBB,
10801 unsigned &Flags) const {
10803 "Must track liveness!");
10805 std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>>
10806 Ranges;
10807 // According to the AArch64 Procedure Call Standard, the following are
10808 // undefined on entry/exit from a function call:
10809 //
10810 // * Registers x16, x17, (and thus w16, w17)
10811 // * Condition codes (and thus the NZCV register)
10812 //
10813 // If any of these registers are used inside or live across an outlined
10814 // function, then they may be modified later, either by the compiler or
10815 // some other tool (like the linker).
10816 //
10817 // To avoid outlining in these situations, partition each block into ranges
10818 // where these registers are dead. We will only outline from those ranges.
10819 LiveRegUnits LRU(getRegisterInfo());
10820 auto AreAllUnsafeRegsDead = [&LRU]() {
10821 return LRU.available(AArch64::W16) && LRU.available(AArch64::W17) &&
10822 LRU.available(AArch64::NZCV);
10823 };
10824
10825 // We need to know if LR is live across an outlining boundary later on in
10826 // order to decide how we'll create the outlined call, frame, etc.
10827 //
10828 // It's pretty expensive to check this for *every candidate* within a block.
10829 // That's some potentially n^2 behaviour, since in the worst case, we'd need
10830 // to compute liveness from the end of the block for O(n) candidates within
10831 // the block.
10832 //
10833 // So, to improve the average case, let's keep track of liveness from the end
10834 // of the block to the beginning of *every outlinable range*. If we know that
10835 // LR is available in every range we could outline from, then we know that
10836 // we don't need to check liveness for any candidate within that range.
10837 bool LRAvailableEverywhere = true;
10838 // Compute liveness bottom-up.
10839 LRU.addLiveOuts(MBB);
10840 // Update flags that require info about the entire MBB.
10841 auto UpdateWholeMBBFlags = [&Flags](const MachineInstr &MI) {
10842 if (MI.isCall() && !MI.isTerminator())
10844 };
10845 // Range: [RangeBegin, RangeEnd)
10846 MachineBasicBlock::instr_iterator RangeBegin, RangeEnd;
10847 unsigned RangeLen;
10848 auto CreateNewRangeStartingAt =
10849 [&RangeBegin, &RangeEnd,
10850 &RangeLen](MachineBasicBlock::instr_iterator NewBegin) {
10851 RangeBegin = NewBegin;
10852 RangeEnd = std::next(RangeBegin);
10853 RangeLen = 0;
10854 };
10855 auto SaveRangeIfNonEmpty = [&RangeLen, &Ranges, &RangeBegin, &RangeEnd]() {
10856 // At least one unsafe register is not dead. We do not want to outline at
10857 // this point. If it is long enough to outline from and does not cross a
10858 // bundle boundary, save the range [RangeBegin, RangeEnd).
10859 if (RangeLen <= 1)
10860 return;
10861 if (!RangeBegin.isEnd() && RangeBegin->isBundledWithPred())
10862 return;
10863 if (!RangeEnd.isEnd() && RangeEnd->isBundledWithPred())
10864 return;
10865 Ranges.emplace_back(RangeBegin, RangeEnd);
10866 };
10867 // Find the first point where all unsafe registers are dead.
10868 // FIND: <safe instr> <-- end of first potential range
10869 // SKIP: <unsafe def>
10870 // SKIP: ... everything between ...
10871 // SKIP: <unsafe use>
10872 auto FirstPossibleEndPt = MBB.instr_rbegin();
10873 for (; FirstPossibleEndPt != MBB.instr_rend(); ++FirstPossibleEndPt) {
10874 if (!FirstPossibleEndPt->isDebugInstr())
10875 LRU.stepBackward(*FirstPossibleEndPt);
10876 // Update flags that impact how we outline across the entire block,
10877 // regardless of safety.
10878 UpdateWholeMBBFlags(*FirstPossibleEndPt);
10879 if (AreAllUnsafeRegsDead())
10880 break;
10881 }
10882 // If we exhausted the entire block, we have no safe ranges to outline.
10883 if (FirstPossibleEndPt == MBB.instr_rend())
10884 return Ranges;
10885 // Current range.
10886 CreateNewRangeStartingAt(FirstPossibleEndPt->getIterator());
10887 // StartPt points to the first place where all unsafe registers
10888 // are dead (if there is any such point). Begin partitioning the MBB into
10889 // ranges.
10890 for (auto &MI : make_range(FirstPossibleEndPt, MBB.instr_rend())) {
10891 if (!MI.isDebugInstr())
10892 LRU.stepBackward(MI);
10893 UpdateWholeMBBFlags(MI);
10894 if (!AreAllUnsafeRegsDead()) {
10895 SaveRangeIfNonEmpty();
10896 CreateNewRangeStartingAt(MI.getIterator());
10897 continue;
10898 }
10899 LRAvailableEverywhere &= LRU.available(AArch64::LR);
10900 RangeBegin = MI.getIterator();
10901 ++RangeLen;
10902 }
10903 // Above loop misses the last (or only) range. If we are still safe, then
10904 // let's save the range.
10905 if (AreAllUnsafeRegsDead())
10906 SaveRangeIfNonEmpty();
10907 if (Ranges.empty())
10908 return Ranges;
10909 // We found the ranges bottom-up. Mapping expects the top-down. Reverse
10910 // the order.
10911 std::reverse(Ranges.begin(), Ranges.end());
10912 // If there is at least one outlinable range where LR is unavailable
10913 // somewhere, remember that.
10914 if (!LRAvailableEverywhere)
10916 return Ranges;
10917}
10918
10920AArch64InstrInfo::getOutliningTypeImpl(const MachineModuleInfo &MMI,
10922 unsigned Flags) const {
10923 MachineInstr &MI = *MIT;
10924
10925 // Don't outline anything used for return address signing. The outlined
10926 // function will get signed later if needed
10927 switch (MI.getOpcode()) {
10928 case AArch64::PACM:
10929 case AArch64::PACIASP:
10930 case AArch64::PACIBSP:
10931 case AArch64::PACIASPPC:
10932 case AArch64::PACIBSPPC:
10933 case AArch64::AUTIASP:
10934 case AArch64::AUTIBSP:
10935 case AArch64::AUTIASPPCi:
10936 case AArch64::AUTIASPPCr:
10937 case AArch64::AUTIBSPPCi:
10938 case AArch64::AUTIBSPPCr:
10939 case AArch64::RETAA:
10940 case AArch64::RETAB:
10941 case AArch64::RETAASPPCi:
10942 case AArch64::RETAASPPCr:
10943 case AArch64::RETABSPPCi:
10944 case AArch64::RETABSPPCr:
10945 case AArch64::EMITBKEY:
10946 case AArch64::PAUTH_PROLOGUE:
10947 case AArch64::PAUTH_EPILOGUE:
10949 }
10950
10951 // We can only outline these if we will tail call the outlined function, or
10952 // fix up the CFI offsets. Currently, CFI instructions are outlined only if
10953 // in a tail call.
10954 //
10955 // FIXME: If the proper fixups for the offset are implemented, this should be
10956 // possible.
10957 if (MI.isCFIInstruction())
10959
10960 // Is this a terminator for a basic block?
10961 if (MI.isTerminator())
10962 // TargetInstrInfo::getOutliningType has already filtered out anything
10963 // that would break this, so we can allow it here.
10965
10966 // Make sure none of the operands are un-outlinable.
10967 for (const MachineOperand &MOP : MI.operands()) {
10968 // A check preventing CFI indices was here before, but only CFI
10969 // instructions should have those.
10970 assert(!MOP.isCFIIndex());
10971
10972 // If it uses LR or W30 explicitly, then don't touch it.
10973 if (MOP.isReg() && !MOP.isImplicit() &&
10974 (MOP.getReg() == AArch64::LR || MOP.getReg() == AArch64::W30))
10976 }
10977
10978 // Special cases for instructions that can always be outlined, but will fail
10979 // the later tests. e.g, ADRPs, which are PC-relative use LR, but can always
10980 // be outlined because they don't require a *specific* value to be in LR.
10981 if (MI.getOpcode() == AArch64::ADRP)
10983
10984 // If MI is a call we might be able to outline it. We don't want to outline
10985 // any calls that rely on the position of items on the stack. When we outline
10986 // something containing a call, we have to emit a save and restore of LR in
10987 // the outlined function. Currently, this always happens by saving LR to the
10988 // stack. Thus, if we outline, say, half the parameters for a function call
10989 // plus the call, then we'll break the callee's expectations for the layout
10990 // of the stack.
10991 //
10992 // FIXME: Allow calls to functions which construct a stack frame, as long
10993 // as they don't access arguments on the stack.
10994 // FIXME: Figure out some way to analyze functions defined in other modules.
10995 // We should be able to compute the memory usage based on the IR calling
10996 // convention, even if we can't see the definition.
10997 if (MI.isCall()) {
10998 // Get the function associated with the call. Look at each operand and find
10999 // the one that represents the callee and get its name.
11000 const Function *Callee = nullptr;
11001 for (const MachineOperand &MOP : MI.operands()) {
11002 if (MOP.isGlobal()) {
11003 Callee = dyn_cast<Function>(MOP.getGlobal());
11004 break;
11005 }
11006 }
11007
11008 // Never outline calls to mcount. There isn't any rule that would require
11009 // this, but the Linux kernel's "ftrace" feature depends on it.
11010 if (Callee && Callee->getName() == "\01_mcount")
11012
11013 // If we don't know anything about the callee, assume it depends on the
11014 // stack layout of the caller. In that case, it's only legal to outline
11015 // as a tail-call. Explicitly list the call instructions we know about so we
11016 // don't get unexpected results with call pseudo-instructions.
11017 auto UnknownCallOutlineType = outliner::InstrType::Illegal;
11018 if (MI.getOpcode() == AArch64::BLR ||
11019 MI.getOpcode() == AArch64::BLRNoIP || MI.getOpcode() == AArch64::BL)
11020 UnknownCallOutlineType = outliner::InstrType::LegalTerminator;
11021
11022 if (!Callee)
11023 return UnknownCallOutlineType;
11024
11025 // We have a function we have information about. Check it if it's something
11026 // can safely outline.
11027 MachineFunction *CalleeMF = MMI.getMachineFunction(*Callee);
11028
11029 // We don't know what's going on with the callee at all. Don't touch it.
11030 if (!CalleeMF)
11031 return UnknownCallOutlineType;
11032
11033 // Check if we know anything about the callee saves on the function. If we
11034 // don't, then don't touch it, since that implies that we haven't
11035 // computed anything about its stack frame yet.
11036 MachineFrameInfo &MFI = CalleeMF->getFrameInfo();
11037 if (!MFI.isCalleeSavedInfoValid() || MFI.getStackSize() > 0 ||
11038 MFI.getNumObjects() > 0)
11039 return UnknownCallOutlineType;
11040
11041 // At this point, we can say that CalleeMF ought to not pass anything on the
11042 // stack. Therefore, we can outline it.
11044 }
11045
11046 // Don't touch the link register or W30.
11047 if (MI.readsRegister(AArch64::W30, &getRegisterInfo()) ||
11048 MI.modifiesRegister(AArch64::W30, &getRegisterInfo()))
11050
11051 // Don't outline BTI instructions, because that will prevent the outlining
11052 // site from being indirectly callable.
11053 if (hasBTISemantics(MI))
11055
11057}
11058
11059void AArch64InstrInfo::fixupPostOutline(MachineBasicBlock &MBB) const {
11060 for (MachineInstr &MI : MBB) {
11061 const MachineOperand *Base;
11062 TypeSize Width(0, false);
11063 int64_t Offset;
11064 bool OffsetIsScalable;
11065
11066 // Is this a load or store with an immediate offset with SP as the base?
11067 if (!MI.mayLoadOrStore() ||
11068 !getMemOperandWithOffsetWidth(MI, Base, Offset, OffsetIsScalable, Width,
11069 &RI) ||
11070 (Base->isReg() && Base->getReg() != AArch64::SP))
11071 continue;
11072
11073 // It is, so we have to fix it up.
11074 TypeSize Scale(0U, false);
11075 int64_t Dummy1, Dummy2;
11076
11077 MachineOperand &StackOffsetOperand = getMemOpBaseRegImmOfsOffsetOperand(MI);
11078 assert(StackOffsetOperand.isImm() && "Stack offset wasn't immediate!");
11079 getMemOpInfo(MI.getOpcode(), Scale, Width, Dummy1, Dummy2);
11080 assert(Scale != 0 && "Unexpected opcode!");
11081 assert(!OffsetIsScalable && "Expected offset to be a byte offset");
11082
11083 // We've pushed the return address to the stack, so add 16 to the offset.
11084 // This is safe, since we already checked if it would overflow when we
11085 // checked if this instruction was legal to outline.
11086 int64_t NewImm = (Offset + 16) / (int64_t)Scale.getFixedValue();
11087 StackOffsetOperand.setImm(NewImm);
11088 }
11089}
11090
11092 const AArch64InstrInfo *TII,
11093 bool ShouldSignReturnAddr) {
11094 if (!ShouldSignReturnAddr)
11095 return;
11096
11097 BuildMI(MBB, MBB.begin(), DebugLoc(), TII->get(AArch64::PAUTH_PROLOGUE))
11099 TII->createPauthEpilogueInstr(MBB, DebugLoc());
11100}
11101
11102void AArch64InstrInfo::buildOutlinedFrame(
11104 const outliner::OutlinedFunction &OF) const {
11105
11106 AArch64FunctionInfo *FI = MF.getInfo<AArch64FunctionInfo>();
11107
11108 if (OF.FrameConstructionID == MachineOutlinerTailCall)
11109 FI->setOutliningStyle("Tail Call");
11110 else if (OF.FrameConstructionID == MachineOutlinerThunk) {
11111 // For thunk outlining, rewrite the last instruction from a call to a
11112 // tail-call.
11113 MachineInstr *Call = &*--MBB.instr_end();
11114 unsigned TailOpcode;
11115 if (Call->getOpcode() == AArch64::BL) {
11116 TailOpcode = AArch64::TCRETURNdi;
11117 } else {
11118 assert(Call->getOpcode() == AArch64::BLR ||
11119 Call->getOpcode() == AArch64::BLRNoIP);
11120 TailOpcode = AArch64::TCRETURNriALL;
11121 }
11122 MachineInstr *TC = BuildMI(MF, DebugLoc(), get(TailOpcode))
11123 .add(Call->getOperand(0))
11124 .addImm(0);
11125 MBB.insert(MBB.end(), TC);
11127
11128 FI->setOutliningStyle("Thunk");
11129 }
11130
11131 bool IsLeafFunction = true;
11132
11133 // Is there a call in the outlined range?
11134 auto IsNonTailCall = [](const MachineInstr &MI) {
11135 return MI.isCall() && !MI.isReturn();
11136 };
11137
11138 if (llvm::any_of(MBB.instrs(), IsNonTailCall)) {
11139 // Fix up the instructions in the range, since we're going to modify the
11140 // stack.
11141
11142 // Bugzilla ID: 46767
11143 // TODO: Check if fixing up twice is safe so we can outline these.
11144 assert(OF.FrameConstructionID != MachineOutlinerDefault &&
11145 "Can only fix up stack references once");
11146 fixupPostOutline(MBB);
11147
11148 IsLeafFunction = false;
11149
11150 // LR has to be a live in so that we can save it.
11151 if (!MBB.isLiveIn(AArch64::LR))
11152 MBB.addLiveIn(AArch64::LR);
11153
11156
11157 if (OF.FrameConstructionID == MachineOutlinerTailCall ||
11158 OF.FrameConstructionID == MachineOutlinerThunk)
11159 Et = std::prev(MBB.end());
11160
11161 // Insert a save before the outlined region
11162 MachineInstr *STRXpre = BuildMI(MF, DebugLoc(), get(AArch64::STRXpre))
11163 .addReg(AArch64::SP, RegState::Define)
11164 .addReg(AArch64::LR)
11165 .addReg(AArch64::SP)
11166 .addImm(-16);
11167 It = MBB.insert(It, STRXpre);
11168
11169 if (MF.getInfo<AArch64FunctionInfo>()->needsDwarfUnwindInfo(MF)) {
11170 CFIInstBuilder CFIBuilder(MBB, It, MachineInstr::FrameSetup);
11171
11172 // Add a CFI saying the stack was moved 16 B down.
11173 CFIBuilder.buildDefCFAOffset(16);
11174
11175 // Add a CFI saying that the LR that we want to find is now 16 B higher
11176 // than before.
11177 CFIBuilder.buildOffset(AArch64::LR, -16);
11178 }
11179
11180 // Insert a restore before the terminator for the function.
11181 MachineInstr *LDRXpost = BuildMI(MF, DebugLoc(), get(AArch64::LDRXpost))
11182 .addReg(AArch64::SP, RegState::Define)
11183 .addReg(AArch64::LR, RegState::Define)
11184 .addReg(AArch64::SP)
11185 .addImm(16);
11186 Et = MBB.insert(Et, LDRXpost);
11187 }
11188
11189 auto RASignCondition = FI->getSignReturnAddressCondition();
11190 bool ShouldSignReturnAddr = AArch64FunctionInfo::shouldSignReturnAddress(
11191 RASignCondition, !IsLeafFunction);
11192
11193 // If this is a tail call outlined function, then there's already a return.
11194 if (OF.FrameConstructionID == MachineOutlinerTailCall ||
11195 OF.FrameConstructionID == MachineOutlinerThunk) {
11196 signOutlinedFunction(MF, MBB, this, ShouldSignReturnAddr);
11197 return;
11198 }
11199
11200 // It's not a tail call, so we have to insert the return ourselves.
11201
11202 // LR has to be a live in so that we can return to it.
11203 if (!MBB.isLiveIn(AArch64::LR))
11204 MBB.addLiveIn(AArch64::LR);
11205
11206 MachineInstr *ret = BuildMI(MF, DebugLoc(), get(AArch64::RET))
11207 .addReg(AArch64::LR);
11208 MBB.insert(MBB.end(), ret);
11209
11210 signOutlinedFunction(MF, MBB, this, ShouldSignReturnAddr);
11211
11212 FI->setOutliningStyle("Function");
11213
11214 // Did we have to modify the stack by saving the link register?
11215 if (OF.FrameConstructionID != MachineOutlinerDefault)
11216 return;
11217
11218 // We modified the stack.
11219 // Walk over the basic block and fix up all the stack accesses.
11220 fixupPostOutline(MBB);
11221}
11222
11223MachineBasicBlock::iterator AArch64InstrInfo::insertOutlinedCall(
11226
11227 // Are we tail calling?
11228 if (C.CallConstructionID == MachineOutlinerTailCall) {
11229 // If yes, then we can just branch to the label.
11230 It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::TCRETURNdi))
11231 .addGlobalAddress(M.getNamedValue(MF.getName()))
11232 .addImm(0));
11233 return It;
11234 }
11235
11236 // Are we saving the link register?
11237 if (C.CallConstructionID == MachineOutlinerNoLRSave ||
11238 C.CallConstructionID == MachineOutlinerThunk) {
11239 // No, so just insert the call.
11240 It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::BL))
11241 .addGlobalAddress(M.getNamedValue(MF.getName())));
11242 return It;
11243 }
11244
11245 // We want to return the spot where we inserted the call.
11247
11248 // Instructions for saving and restoring LR around the call instruction we're
11249 // going to insert.
11250 MachineInstr *Save;
11251 MachineInstr *Restore;
11252 // Can we save to a register?
11253 if (C.CallConstructionID == MachineOutlinerRegSave) {
11254 // FIXME: This logic should be sunk into a target-specific interface so that
11255 // we don't have to recompute the register.
11256 Register Reg = findRegisterToSaveLRTo(C);
11257 assert(Reg && "No callee-saved register available?");
11258
11259 // LR has to be a live in so that we can save it.
11260 if (!MBB.isLiveIn(AArch64::LR))
11261 MBB.addLiveIn(AArch64::LR);
11262
11263 // Save and restore LR from Reg.
11264 Save = BuildMI(MF, DebugLoc(), get(AArch64::ORRXrs), Reg)
11265 .addReg(AArch64::XZR)
11266 .addReg(AArch64::LR)
11267 .addImm(0);
11268 Restore = BuildMI(MF, DebugLoc(), get(AArch64::ORRXrs), AArch64::LR)
11269 .addReg(AArch64::XZR)
11270 .addReg(Reg)
11271 .addImm(0);
11272 } else {
11273 // We have the default case. Save and restore from SP.
11274 Save = BuildMI(MF, DebugLoc(), get(AArch64::STRXpre))
11275 .addReg(AArch64::SP, RegState::Define)
11276 .addReg(AArch64::LR)
11277 .addReg(AArch64::SP)
11278 .addImm(-16);
11279 Restore = BuildMI(MF, DebugLoc(), get(AArch64::LDRXpost))
11280 .addReg(AArch64::SP, RegState::Define)
11281 .addReg(AArch64::LR, RegState::Define)
11282 .addReg(AArch64::SP)
11283 .addImm(16);
11284 }
11285
11286 It = MBB.insert(It, Save);
11287 It++;
11288
11289 // Insert the call.
11290 It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::BL))
11291 .addGlobalAddress(M.getNamedValue(MF.getName())));
11292 CallPt = It;
11293 It++;
11294
11295 It = MBB.insert(It, Restore);
11296 return CallPt;
11297}
11298
11299bool AArch64InstrInfo::shouldOutlineFromFunctionByDefault(
11300 MachineFunction &MF) const {
11301 return MF.getFunction().hasMinSize();
11302}
11303
11304void AArch64InstrInfo::buildClearRegister(Register Reg, MachineBasicBlock &MBB,
11306 DebugLoc &DL,
11307 bool AllowSideEffects) const {
11308 const MachineFunction &MF = *MBB.getParent();
11309 const AArch64Subtarget &STI = MF.getSubtarget<AArch64Subtarget>();
11310 const AArch64RegisterInfo &TRI = *STI.getRegisterInfo();
11311
11312 if (TRI.isGeneralPurposeRegister(MF, Reg)) {
11313 BuildMI(MBB, Iter, DL, get(AArch64::MOVZXi), Reg).addImm(0).addImm(0);
11314 } else if (STI.isSVEorStreamingSVEAvailable()) {
11315 BuildMI(MBB, Iter, DL, get(AArch64::DUP_ZI_D), Reg)
11316 .addImm(0)
11317 .addImm(0);
11318 } else if (STI.isNeonAvailable()) {
11319 BuildMI(MBB, Iter, DL, get(AArch64::MOVIv2d_ns), Reg)
11320 .addImm(0);
11321 } else {
11322 // This is a streaming-compatible function without SVE. We don't have full
11323 // Neon (just FPRs), so we can at most use the first 64-bit sub-register.
11324 // So given `movi v..` would be illegal use `fmov d..` instead.
11325 assert(STI.hasNEON() && "Expected to have NEON.");
11326 Register Reg64 = TRI.getSubReg(Reg, AArch64::dsub);
11327 BuildMI(MBB, Iter, DL, get(AArch64::FMOVD0), Reg64);
11328 }
11329}
11330
11331std::optional<DestSourcePair>
11333
11334 // AArch64::ORRWrs and AArch64::ORRXrs with WZR/XZR reg
11335 // and zero immediate operands used as an alias for mov instruction.
11336 if (((MI.getOpcode() == AArch64::ORRWrs &&
11337 MI.getOperand(1).getReg() == AArch64::WZR &&
11338 MI.getOperand(3).getImm() == 0x0) ||
11339 (MI.getOpcode() == AArch64::ORRWrr &&
11340 MI.getOperand(1).getReg() == AArch64::WZR)) &&
11341 // Check that the w->w move is not a zero-extending w->x mov.
11342 (!MI.getOperand(0).getReg().isVirtual() ||
11343 MI.getOperand(0).getSubReg() == 0) &&
11344 (!MI.getOperand(0).getReg().isPhysical() ||
11345 MI.findRegisterDefOperandIdx(getXRegFromWReg(MI.getOperand(0).getReg()),
11346 /*TRI=*/nullptr) == -1))
11347 return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
11348
11349 if (MI.getOpcode() == AArch64::ORRXrs &&
11350 MI.getOperand(1).getReg() == AArch64::XZR &&
11351 MI.getOperand(3).getImm() == 0x0)
11352 return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
11353
11354 return std::nullopt;
11355}
11356
11357std::optional<DestSourcePair>
11359 if ((MI.getOpcode() == AArch64::ORRWrs &&
11360 MI.getOperand(1).getReg() == AArch64::WZR &&
11361 MI.getOperand(3).getImm() == 0x0) ||
11362 (MI.getOpcode() == AArch64::ORRWrr &&
11363 MI.getOperand(1).getReg() == AArch64::WZR))
11364 return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
11365 return std::nullopt;
11366}
11367
11368std::optional<RegImmPair>
11369AArch64InstrInfo::isAddImmediate(const MachineInstr &MI, Register Reg) const {
11370 int Sign = 1;
11371 int64_t Offset = 0;
11372
11373 // TODO: Handle cases where Reg is a super- or sub-register of the
11374 // destination register.
11375 const MachineOperand &Op0 = MI.getOperand(0);
11376 if (!Op0.isReg() || Reg != Op0.getReg())
11377 return std::nullopt;
11378
11379 switch (MI.getOpcode()) {
11380 default:
11381 return std::nullopt;
11382 case AArch64::SUBWri:
11383 case AArch64::SUBXri:
11384 case AArch64::SUBSWri:
11385 case AArch64::SUBSXri:
11386 Sign *= -1;
11387 [[fallthrough]];
11388 case AArch64::ADDSWri:
11389 case AArch64::ADDSXri:
11390 case AArch64::ADDWri:
11391 case AArch64::ADDXri: {
11392 // TODO: Third operand can be global address (usually some string).
11393 if (!MI.getOperand(0).isReg() || !MI.getOperand(1).isReg() ||
11394 !MI.getOperand(2).isImm())
11395 return std::nullopt;
11396 int Shift = MI.getOperand(3).getImm();
11397 assert((Shift == 0 || Shift == 12) && "Shift can be either 0 or 12");
11398 Offset = Sign * (MI.getOperand(2).getImm() << Shift);
11399 }
11400 }
11401 return RegImmPair{MI.getOperand(1).getReg(), Offset};
11402}
11403
11404/// If the given ORR instruction is a copy, and \p DescribedReg overlaps with
11405/// the destination register then, if possible, describe the value in terms of
11406/// the source register.
11407static std::optional<ParamLoadedValue>
11409 const TargetInstrInfo *TII,
11410 const TargetRegisterInfo *TRI) {
11411 auto DestSrc = TII->isCopyLikeInstr(MI);
11412 if (!DestSrc)
11413 return std::nullopt;
11414
11415 Register DestReg = DestSrc->Destination->getReg();
11416 Register SrcReg = DestSrc->Source->getReg();
11417
11418 if (!DestReg.isValid() || !SrcReg.isValid())
11419 return std::nullopt;
11420
11421 auto Expr = DIExpression::get(MI.getMF()->getFunction().getContext(), {});
11422
11423 // If the described register is the destination, just return the source.
11424 if (DestReg == DescribedReg)
11425 return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
11426
11427 // ORRWrs zero-extends to 64-bits, so we need to consider such cases.
11428 if (MI.getOpcode() == AArch64::ORRWrs &&
11429 TRI->isSuperRegister(DestReg, DescribedReg))
11430 return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
11431
11432 // We may need to describe the lower part of a ORRXrs move.
11433 if (MI.getOpcode() == AArch64::ORRXrs &&
11434 TRI->isSubRegister(DestReg, DescribedReg)) {
11435 Register SrcSubReg = TRI->getSubReg(SrcReg, AArch64::sub_32);
11436 return ParamLoadedValue(MachineOperand::CreateReg(SrcSubReg, false), Expr);
11437 }
11438
11439 assert(!TRI->isSuperOrSubRegisterEq(DestReg, DescribedReg) &&
11440 "Unhandled ORR[XW]rs copy case");
11441
11442 return std::nullopt;
11443}
11444
11445bool AArch64InstrInfo::isFunctionSafeToSplit(const MachineFunction &MF) const {
11446 // Functions cannot be split to different sections on AArch64 if they have
11447 // a red zone. This is because relaxing a cross-section branch may require
11448 // incrementing the stack pointer to spill a register, which would overwrite
11449 // the red zone.
11450 if (MF.getInfo<AArch64FunctionInfo>()->hasRedZone().value_or(true))
11451 return false;
11452
11454}
11455
11456bool AArch64InstrInfo::isMBBSafeToSplitToCold(
11457 const MachineBasicBlock &MBB) const {
11458 // Asm Goto blocks can contain conditional branches to goto labels, which can
11459 // get moved out of range of the branch instruction.
11460 auto isAsmGoto = [](const MachineInstr &MI) {
11461 return MI.getOpcode() == AArch64::INLINEASM_BR;
11462 };
11463 if (llvm::any_of(MBB, isAsmGoto) || MBB.isInlineAsmBrIndirectTarget())
11464 return false;
11465
11466 // Because jump tables are label-relative instead of table-relative, they all
11467 // must be in the same section or relocation fixup handling will fail.
11468
11469 // Check if MBB is a jump table target
11470 const MachineJumpTableInfo *MJTI = MBB.getParent()->getJumpTableInfo();
11471 auto containsMBB = [&MBB](const MachineJumpTableEntry &JTE) {
11472 return llvm::is_contained(JTE.MBBs, &MBB);
11473 };
11474 if (MJTI != nullptr && llvm::any_of(MJTI->getJumpTables(), containsMBB))
11475 return false;
11476
11477 // Check if MBB contains a jump table lookup
11478 for (const MachineInstr &MI : MBB) {
11479 switch (MI.getOpcode()) {
11480 case TargetOpcode::G_BRJT:
11481 case AArch64::JumpTableDest32:
11482 case AArch64::JumpTableDest16:
11483 case AArch64::JumpTableDest8:
11484 return false;
11485 default:
11486 continue;
11487 }
11488 }
11489
11490 // MBB isn't a special case, so it's safe to be split to the cold section.
11491 return true;
11492}
11493
11494std::optional<ParamLoadedValue>
11495AArch64InstrInfo::describeLoadedValue(const MachineInstr &MI,
11496 Register Reg) const {
11497 const MachineFunction *MF = MI.getMF();
11498 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
11499 switch (MI.getOpcode()) {
11500 case AArch64::MOVZWi:
11501 case AArch64::MOVZXi: {
11502 // MOVZWi may be used for producing zero-extended 32-bit immediates in
11503 // 64-bit parameters, so we need to consider super-registers.
11504 if (!TRI->isSuperRegisterEq(MI.getOperand(0).getReg(), Reg))
11505 return std::nullopt;
11506
11507 if (!MI.getOperand(1).isImm())
11508 return std::nullopt;
11509 int64_t Immediate = MI.getOperand(1).getImm();
11510 int Shift = MI.getOperand(2).getImm();
11511 return ParamLoadedValue(MachineOperand::CreateImm(Immediate << Shift),
11512 nullptr);
11513 }
11514 case AArch64::ORRWrs:
11515 case AArch64::ORRXrs:
11516 return describeORRLoadedValue(MI, Reg, this, TRI);
11517 }
11518
11520}
11521
11522bool AArch64InstrInfo::isExtendLikelyToBeFolded(
11523 MachineInstr &ExtMI, MachineRegisterInfo &MRI) const {
11524 assert(ExtMI.getOpcode() == TargetOpcode::G_SEXT ||
11525 ExtMI.getOpcode() == TargetOpcode::G_ZEXT ||
11526 ExtMI.getOpcode() == TargetOpcode::G_ANYEXT);
11527
11528 // Anyexts are nops.
11529 if (ExtMI.getOpcode() == TargetOpcode::G_ANYEXT)
11530 return true;
11531
11532 Register DefReg = ExtMI.getOperand(0).getReg();
11533 if (!MRI.hasOneNonDBGUse(DefReg))
11534 return false;
11535
11536 // It's likely that a sext/zext as a G_PTR_ADD offset will be folded into an
11537 // addressing mode.
11538 auto *UserMI = &*MRI.use_instr_nodbg_begin(DefReg);
11539 return UserMI->getOpcode() == TargetOpcode::G_PTR_ADD;
11540}
11541
11542uint64_t AArch64InstrInfo::getElementSizeForOpcode(unsigned Opc) const {
11543 return get(Opc).TSFlags & AArch64::ElementSizeMask;
11544}
11545
11546bool AArch64InstrInfo::isPTestLikeOpcode(unsigned Opc) const {
11547 return get(Opc).TSFlags & AArch64::InstrFlagIsPTestLike;
11548}
11549
11550bool AArch64InstrInfo::isWhileOpcode(unsigned Opc) const {
11551 return get(Opc).TSFlags & AArch64::InstrFlagIsWhile;
11552}
11553
11554unsigned int
11555AArch64InstrInfo::getTailDuplicateSize(CodeGenOptLevel OptLevel) const {
11556 return OptLevel >= CodeGenOptLevel::Aggressive ? 6 : 2;
11557}
11558
11559bool AArch64InstrInfo::isLegalAddressingMode(unsigned NumBytes, int64_t Offset,
11560 unsigned Scale) const {
11561 if (Offset && Scale)
11562 return false;
11563
11564 // Check Reg + Imm
11565 if (!Scale) {
11566 // 9-bit signed offset
11567 if (isInt<9>(Offset))
11568 return true;
11569
11570 // 12-bit unsigned offset
11571 unsigned Shift = Log2_64(NumBytes);
11572 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
11573 // Must be a multiple of NumBytes (NumBytes is a power of 2)
11574 (Offset >> Shift) << Shift == Offset)
11575 return true;
11576 return false;
11577 }
11578
11579 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
11580 return Scale == 1 || (Scale > 0 && Scale == NumBytes);
11581}
11582
11584 if (MF.getSubtarget<AArch64Subtarget>().hardenSlsBlr())
11585 return AArch64::BLRNoIP;
11586 else
11587 return AArch64::BLR;
11588}
11589
11591 DebugLoc DL) const {
11592 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
11593 auto Builder = BuildMI(MBB, InsertPt, DL, get(AArch64::PAUTH_EPILOGUE))
11595
11596 MachineFunction &MF = *MBB.getParent();
11597 const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
11598 auto &AFL = *static_cast<const AArch64FrameLowering *>(
11599 MF.getSubtarget().getFrameLowering());
11600 if (AFL.getArgumentStackToRestore(MF, MBB)) {
11601 Builder.addReg(AArch64::X17, RegState::ImplicitDefine);
11602 Builder.addReg(AArch64::X16, RegState::ImplicitDefine);
11603 if (Subtarget.hasPAuthLR())
11604 Builder.addReg(AArch64::X15, RegState::ImplicitDefine);
11605 return;
11606 }
11607
11608 if (AFI->branchProtectionPAuthLR() && !Subtarget.hasPAuthLR())
11609 Builder.addReg(AArch64::X16, RegState::ImplicitDefine);
11610}
11611
11613AArch64InstrInfo::probedStackAlloc(MachineBasicBlock::iterator MBBI,
11614 Register TargetReg, bool FrameSetup) const {
11615 assert(TargetReg != AArch64::SP && "New top of stack cannot already be in SP");
11616
11617 MachineBasicBlock &MBB = *MBBI->getParent();
11618 MachineFunction &MF = *MBB.getParent();
11619 const AArch64InstrInfo *TII =
11620 MF.getSubtarget<AArch64Subtarget>().getInstrInfo();
11621 int64_t ProbeSize = MF.getInfo<AArch64FunctionInfo>()->getStackProbeSize();
11622 DebugLoc DL = MBB.findDebugLoc(MBBI);
11623
11624 MachineFunction::iterator MBBInsertPoint = std::next(MBB.getIterator());
11625 MachineBasicBlock *LoopTestMBB =
11626 MF.CreateMachineBasicBlock(MBB.getBasicBlock());
11627 MF.insert(MBBInsertPoint, LoopTestMBB);
11628 MachineBasicBlock *LoopBodyMBB =
11629 MF.CreateMachineBasicBlock(MBB.getBasicBlock());
11630 MF.insert(MBBInsertPoint, LoopBodyMBB);
11631 MachineBasicBlock *ExitMBB = MF.CreateMachineBasicBlock(MBB.getBasicBlock());
11632 MF.insert(MBBInsertPoint, ExitMBB);
11633 MachineInstr::MIFlag Flags =
11635
11636 // LoopTest:
11637 // SUB SP, SP, #ProbeSize
11638 emitFrameOffset(*LoopTestMBB, LoopTestMBB->end(), DL, AArch64::SP,
11639 AArch64::SP, StackOffset::getFixed(-ProbeSize), TII, Flags);
11640
11641 // CMP SP, TargetReg
11642 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(AArch64::SUBSXrx64),
11643 AArch64::XZR)
11644 .addReg(AArch64::SP)
11645 .addReg(TargetReg)
11647 .setMIFlags(Flags);
11648
11649 // B.<Cond> LoopExit
11650 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(AArch64::Bcc))
11652 .addMBB(ExitMBB)
11653 .setMIFlags(Flags);
11654
11655 // LDR XZR, [SP]
11656 BuildMI(*LoopBodyMBB, LoopBodyMBB->end(), DL, TII->get(AArch64::LDRXui))
11657 .addDef(AArch64::XZR)
11658 .addReg(AArch64::SP)
11659 .addImm(0)
11663 Align(8)))
11664 .setMIFlags(Flags);
11665
11666 // B loop
11667 BuildMI(*LoopBodyMBB, LoopBodyMBB->end(), DL, TII->get(AArch64::B))
11668 .addMBB(LoopTestMBB)
11669 .setMIFlags(Flags);
11670
11671 // LoopExit:
11672 // MOV SP, TargetReg
11673 BuildMI(*ExitMBB, ExitMBB->end(), DL, TII->get(AArch64::ADDXri), AArch64::SP)
11674 .addReg(TargetReg)
11675 .addImm(0)
11677 .setMIFlags(Flags);
11678
11679 // LDR XZR, [SP]
11680 BuildMI(*ExitMBB, ExitMBB->end(), DL, TII->get(AArch64::LDRXui))
11681 .addReg(AArch64::XZR, RegState::Define)
11682 .addReg(AArch64::SP)
11683 .addImm(0)
11684 .setMIFlags(Flags);
11685
11686 ExitMBB->splice(ExitMBB->end(), &MBB, std::next(MBBI), MBB.end());
11688
11689 LoopTestMBB->addSuccessor(ExitMBB);
11690 LoopTestMBB->addSuccessor(LoopBodyMBB);
11691 LoopBodyMBB->addSuccessor(LoopTestMBB);
11692 MBB.addSuccessor(LoopTestMBB);
11693
11694 // Update liveins.
11695 if (MF.getRegInfo().reservedRegsFrozen())
11696 fullyRecomputeLiveIns({ExitMBB, LoopBodyMBB, LoopTestMBB});
11697
11698 return ExitMBB->begin();
11699}
11700
11701namespace {
11702class AArch64PipelinerLoopInfo : public TargetInstrInfo::PipelinerLoopInfo {
11703 MachineFunction *MF;
11704 const TargetInstrInfo *TII;
11705 const TargetRegisterInfo *TRI;
11706 MachineRegisterInfo &MRI;
11707
11708 /// The block of the loop
11709 MachineBasicBlock *LoopBB;
11710 /// The conditional branch of the loop
11711 MachineInstr *CondBranch;
11712 /// The compare instruction for loop control
11713 MachineInstr *Comp;
11714 /// The number of the operand of the loop counter value in Comp
11715 unsigned CompCounterOprNum;
11716 /// The instruction that updates the loop counter value
11717 MachineInstr *Update;
11718 /// The number of the operand of the loop counter value in Update
11719 unsigned UpdateCounterOprNum;
11720 /// The initial value of the loop counter
11721 Register Init;
11722 /// True iff Update is a predecessor of Comp
11723 bool IsUpdatePriorComp;
11724
11725 /// The normalized condition used by createTripCountGreaterCondition()
11727
11728public:
11729 AArch64PipelinerLoopInfo(MachineBasicBlock *LoopBB, MachineInstr *CondBranch,
11730 MachineInstr *Comp, unsigned CompCounterOprNum,
11731 MachineInstr *Update, unsigned UpdateCounterOprNum,
11732 Register Init, bool IsUpdatePriorComp,
11733 const SmallVectorImpl<MachineOperand> &Cond)
11734 : MF(Comp->getParent()->getParent()),
11735 TII(MF->getSubtarget().getInstrInfo()),
11736 TRI(MF->getSubtarget().getRegisterInfo()), MRI(MF->getRegInfo()),
11737 LoopBB(LoopBB), CondBranch(CondBranch), Comp(Comp),
11738 CompCounterOprNum(CompCounterOprNum), Update(Update),
11739 UpdateCounterOprNum(UpdateCounterOprNum), Init(Init),
11740 IsUpdatePriorComp(IsUpdatePriorComp), Cond(Cond.begin(), Cond.end()) {}
11741
11742 bool shouldIgnoreForPipelining(const MachineInstr *MI) const override {
11743 // Make the instructions for loop control be placed in stage 0.
11744 // The predecessors of Comp are considered by the caller.
11745 return MI == Comp;
11746 }
11747
11748 std::optional<bool> createTripCountGreaterCondition(
11749 int TC, MachineBasicBlock &MBB,
11750 SmallVectorImpl<MachineOperand> &CondParam) override {
11751 // A branch instruction will be inserted as "if (Cond) goto epilogue".
11752 // Cond is normalized for such use.
11753 // The predecessors of the branch are assumed to have already been inserted.
11754 CondParam = Cond;
11755 return {};
11756 }
11757
11758 void createRemainingIterationsGreaterCondition(
11759 int TC, MachineBasicBlock &MBB, SmallVectorImpl<MachineOperand> &Cond,
11760 DenseMap<MachineInstr *, MachineInstr *> &LastStage0Insts) override;
11761
11762 void setPreheader(MachineBasicBlock *NewPreheader) override {}
11763
11764 void adjustTripCount(int TripCountAdjust) override {}
11765
11766 bool isMVEExpanderSupported() override { return true; }
11767};
11768} // namespace
11769
11770/// Clone an instruction from MI. The register of ReplaceOprNum-th operand
11771/// is replaced by ReplaceReg. The output register is newly created.
11772/// The other operands are unchanged from MI.
11773static Register cloneInstr(const MachineInstr *MI, unsigned ReplaceOprNum,
11774 Register ReplaceReg, MachineBasicBlock &MBB,
11775 MachineBasicBlock::iterator InsertTo) {
11776 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
11777 const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
11778 MachineInstr *NewMI = MBB.getParent()->CloneMachineInstr(MI);
11779 Register Result = 0;
11780 for (unsigned I = 0; I < NewMI->getNumOperands(); ++I) {
11781 if (I == 0 && NewMI->getOperand(0).getReg().isVirtual()) {
11782 Result = MRI.createVirtualRegister(
11783 MRI.getRegClass(NewMI->getOperand(0).getReg()));
11784 NewMI->getOperand(I).setReg(Result);
11785 } else if (I == ReplaceOprNum) {
11786 MRI.constrainRegClass(ReplaceReg, TII->getRegClass(NewMI->getDesc(), I));
11787 NewMI->getOperand(I).setReg(ReplaceReg);
11788 }
11789 }
11790 MBB.insert(InsertTo, NewMI);
11791 return Result;
11792}
11793
11794void AArch64PipelinerLoopInfo::createRemainingIterationsGreaterCondition(
11797 // Create and accumulate conditions for next TC iterations.
11798 // Example:
11799 // SUBSXrr N, counter, implicit-def $nzcv # compare instruction for the last
11800 // # iteration of the kernel
11801 //
11802 // # insert the following instructions
11803 // cond = CSINCXr 0, 0, C, implicit $nzcv
11804 // counter = ADDXri counter, 1 # clone from this->Update
11805 // SUBSXrr n, counter, implicit-def $nzcv # clone from this->Comp
11806 // cond = CSINCXr cond, cond, C, implicit $nzcv
11807 // ... (repeat TC times)
11808 // SUBSXri cond, 0, implicit-def $nzcv
11809
11810 assert(CondBranch->getOpcode() == AArch64::Bcc);
11811 // CondCode to exit the loop
11813 (AArch64CC::CondCode)CondBranch->getOperand(0).getImm();
11814 if (CondBranch->getOperand(1).getMBB() == LoopBB)
11816
11817 // Accumulate conditions to exit the loop
11818 Register AccCond = AArch64::XZR;
11819
11820 // If CC holds, CurCond+1 is returned; otherwise CurCond is returned.
11821 auto AccumulateCond = [&](Register CurCond,
11823 Register NewCond = MRI.createVirtualRegister(&AArch64::GPR64commonRegClass);
11824 BuildMI(MBB, MBB.end(), Comp->getDebugLoc(), TII->get(AArch64::CSINCXr))
11825 .addReg(NewCond, RegState::Define)
11826 .addReg(CurCond)
11827 .addReg(CurCond)
11829 return NewCond;
11830 };
11831
11832 if (!LastStage0Insts.empty() && LastStage0Insts[Comp]->getParent() == &MBB) {
11833 // Update and Comp for I==0 are already exists in MBB
11834 // (MBB is an unrolled kernel)
11835 Register Counter;
11836 for (int I = 0; I <= TC; ++I) {
11837 Register NextCounter;
11838 if (I != 0)
11839 NextCounter =
11840 cloneInstr(Comp, CompCounterOprNum, Counter, MBB, MBB.end());
11841
11842 AccCond = AccumulateCond(AccCond, CC);
11843
11844 if (I != TC) {
11845 if (I == 0) {
11846 if (Update != Comp && IsUpdatePriorComp) {
11847 Counter =
11848 LastStage0Insts[Comp]->getOperand(CompCounterOprNum).getReg();
11849 NextCounter = cloneInstr(Update, UpdateCounterOprNum, Counter, MBB,
11850 MBB.end());
11851 } else {
11852 // can use already calculated value
11853 NextCounter = LastStage0Insts[Update]->getOperand(0).getReg();
11854 }
11855 } else if (Update != Comp) {
11856 NextCounter =
11857 cloneInstr(Update, UpdateCounterOprNum, Counter, MBB, MBB.end());
11858 }
11859 }
11860 Counter = NextCounter;
11861 }
11862 } else {
11863 Register Counter;
11864 if (LastStage0Insts.empty()) {
11865 // use initial counter value (testing if the trip count is sufficient to
11866 // be executed by pipelined code)
11867 Counter = Init;
11868 if (IsUpdatePriorComp)
11869 Counter =
11870 cloneInstr(Update, UpdateCounterOprNum, Counter, MBB, MBB.end());
11871 } else {
11872 // MBB is an epilogue block. LastStage0Insts[Comp] is in the kernel block.
11873 Counter = LastStage0Insts[Comp]->getOperand(CompCounterOprNum).getReg();
11874 }
11875
11876 for (int I = 0; I <= TC; ++I) {
11877 Register NextCounter;
11878 NextCounter =
11879 cloneInstr(Comp, CompCounterOprNum, Counter, MBB, MBB.end());
11880 AccCond = AccumulateCond(AccCond, CC);
11881 if (I != TC && Update != Comp)
11882 NextCounter =
11883 cloneInstr(Update, UpdateCounterOprNum, Counter, MBB, MBB.end());
11884 Counter = NextCounter;
11885 }
11886 }
11887
11888 // If AccCond == 0, the remainder is greater than TC.
11889 BuildMI(MBB, MBB.end(), Comp->getDebugLoc(), TII->get(AArch64::SUBSXri))
11890 .addReg(AArch64::XZR, RegState::Define | RegState::Dead)
11891 .addReg(AccCond)
11892 .addImm(0)
11893 .addImm(0);
11894 Cond.clear();
11896}
11897
11898static void extractPhiReg(const MachineInstr &Phi, const MachineBasicBlock *MBB,
11899 Register &RegMBB, Register &RegOther) {
11900 assert(Phi.getNumOperands() == 5);
11901 if (Phi.getOperand(2).getMBB() == MBB) {
11902 RegMBB = Phi.getOperand(1).getReg();
11903 RegOther = Phi.getOperand(3).getReg();
11904 } else {
11905 assert(Phi.getOperand(4).getMBB() == MBB);
11906 RegMBB = Phi.getOperand(3).getReg();
11907 RegOther = Phi.getOperand(1).getReg();
11908 }
11909}
11910
11912 if (!Reg.isVirtual())
11913 return false;
11914 const MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
11915 return MRI.getVRegDef(Reg)->getParent() != BB;
11916}
11917
11918/// If Reg is an induction variable, return true and set some parameters
11919static bool getIndVarInfo(Register Reg, const MachineBasicBlock *LoopBB,
11920 MachineInstr *&UpdateInst,
11921 unsigned &UpdateCounterOprNum, Register &InitReg,
11922 bool &IsUpdatePriorComp) {
11923 // Example:
11924 //
11925 // Preheader:
11926 // InitReg = ...
11927 // LoopBB:
11928 // Reg0 = PHI (InitReg, Preheader), (Reg1, LoopBB)
11929 // Reg = COPY Reg0 ; COPY is ignored.
11930 // Reg1 = ADD Reg, #1; UpdateInst. Incremented by a loop invariant value.
11931 // ; Reg is the value calculated in the previous
11932 // ; iteration, so IsUpdatePriorComp == false.
11933
11934 if (LoopBB->pred_size() != 2)
11935 return false;
11936 if (!Reg.isVirtual())
11937 return false;
11938 const MachineRegisterInfo &MRI = LoopBB->getParent()->getRegInfo();
11939 UpdateInst = nullptr;
11940 UpdateCounterOprNum = 0;
11941 InitReg = 0;
11942 IsUpdatePriorComp = true;
11943 Register CurReg = Reg;
11944 while (true) {
11945 MachineInstr *Def = MRI.getVRegDef(CurReg);
11946 if (Def->getParent() != LoopBB)
11947 return false;
11948 if (Def->isCopy()) {
11949 // Ignore copy instructions unless they contain subregisters
11950 if (Def->getOperand(0).getSubReg() || Def->getOperand(1).getSubReg())
11951 return false;
11952 CurReg = Def->getOperand(1).getReg();
11953 } else if (Def->isPHI()) {
11954 if (InitReg != 0)
11955 return false;
11956 if (!UpdateInst)
11957 IsUpdatePriorComp = false;
11958 extractPhiReg(*Def, LoopBB, CurReg, InitReg);
11959 } else {
11960 if (UpdateInst)
11961 return false;
11962 switch (Def->getOpcode()) {
11963 case AArch64::ADDSXri:
11964 case AArch64::ADDSWri:
11965 case AArch64::SUBSXri:
11966 case AArch64::SUBSWri:
11967 case AArch64::ADDXri:
11968 case AArch64::ADDWri:
11969 case AArch64::SUBXri:
11970 case AArch64::SUBWri:
11971 UpdateInst = Def;
11972 UpdateCounterOprNum = 1;
11973 break;
11974 case AArch64::ADDSXrr:
11975 case AArch64::ADDSWrr:
11976 case AArch64::SUBSXrr:
11977 case AArch64::SUBSWrr:
11978 case AArch64::ADDXrr:
11979 case AArch64::ADDWrr:
11980 case AArch64::SUBXrr:
11981 case AArch64::SUBWrr:
11982 UpdateInst = Def;
11983 if (isDefinedOutside(Def->getOperand(2).getReg(), LoopBB))
11984 UpdateCounterOprNum = 1;
11985 else if (isDefinedOutside(Def->getOperand(1).getReg(), LoopBB))
11986 UpdateCounterOprNum = 2;
11987 else
11988 return false;
11989 break;
11990 default:
11991 return false;
11992 }
11993 CurReg = Def->getOperand(UpdateCounterOprNum).getReg();
11994 }
11995
11996 if (!CurReg.isVirtual())
11997 return false;
11998 if (Reg == CurReg)
11999 break;
12000 }
12001
12002 if (!UpdateInst)
12003 return false;
12004
12005 return true;
12006}
12007
12008std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo>
12010 // Accept loops that meet the following conditions
12011 // * The conditional branch is BCC
12012 // * The compare instruction is ADDS/SUBS/WHILEXX
12013 // * One operand of the compare is an induction variable and the other is a
12014 // loop invariant value
12015 // * The induction variable is incremented/decremented by a single instruction
12016 // * Does not contain CALL or instructions which have unmodeled side effects
12017
12018 for (MachineInstr &MI : *LoopBB)
12019 if (MI.isCall() || MI.hasUnmodeledSideEffects())
12020 // This instruction may use NZCV, which interferes with the instruction to
12021 // be inserted for loop control.
12022 return nullptr;
12023
12024 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
12026 if (analyzeBranch(*LoopBB, TBB, FBB, Cond))
12027 return nullptr;
12028
12029 // Infinite loops are not supported
12030 if (TBB == LoopBB && FBB == LoopBB)
12031 return nullptr;
12032
12033 // Must be conditional branch
12034 if (TBB != LoopBB && FBB == nullptr)
12035 return nullptr;
12036
12037 assert((TBB == LoopBB || FBB == LoopBB) &&
12038 "The Loop must be a single-basic-block loop");
12039
12040 MachineInstr *CondBranch = &*LoopBB->getFirstTerminator();
12042
12043 if (CondBranch->getOpcode() != AArch64::Bcc)
12044 return nullptr;
12045
12046 // Normalization for createTripCountGreaterCondition()
12047 if (TBB == LoopBB)
12049
12050 MachineInstr *Comp = nullptr;
12051 unsigned CompCounterOprNum = 0;
12052 for (MachineInstr &MI : reverse(*LoopBB)) {
12053 if (MI.modifiesRegister(AArch64::NZCV, &TRI)) {
12054 // Guarantee that the compare is SUBS/ADDS/WHILEXX and that one of the
12055 // operands is a loop invariant value
12056
12057 switch (MI.getOpcode()) {
12058 case AArch64::SUBSXri:
12059 case AArch64::SUBSWri:
12060 case AArch64::ADDSXri:
12061 case AArch64::ADDSWri:
12062 Comp = &MI;
12063 CompCounterOprNum = 1;
12064 break;
12065 case AArch64::ADDSWrr:
12066 case AArch64::ADDSXrr:
12067 case AArch64::SUBSWrr:
12068 case AArch64::SUBSXrr:
12069 Comp = &MI;
12070 break;
12071 default:
12072 if (isWhileOpcode(MI.getOpcode())) {
12073 Comp = &MI;
12074 break;
12075 }
12076 return nullptr;
12077 }
12078
12079 if (CompCounterOprNum == 0) {
12080 if (isDefinedOutside(Comp->getOperand(1).getReg(), LoopBB))
12081 CompCounterOprNum = 2;
12082 else if (isDefinedOutside(Comp->getOperand(2).getReg(), LoopBB))
12083 CompCounterOprNum = 1;
12084 else
12085 return nullptr;
12086 }
12087 break;
12088 }
12089 }
12090 if (!Comp)
12091 return nullptr;
12092
12093 MachineInstr *Update = nullptr;
12094 Register Init;
12095 bool IsUpdatePriorComp;
12096 unsigned UpdateCounterOprNum;
12097 if (!getIndVarInfo(Comp->getOperand(CompCounterOprNum).getReg(), LoopBB,
12098 Update, UpdateCounterOprNum, Init, IsUpdatePriorComp))
12099 return nullptr;
12100
12101 return std::make_unique<AArch64PipelinerLoopInfo>(
12102 LoopBB, CondBranch, Comp, CompCounterOprNum, Update, UpdateCounterOprNum,
12103 Init, IsUpdatePriorComp, Cond);
12104}
12105
12106/// verifyInstruction - Perform target specific instruction verification.
12107bool AArch64InstrInfo::verifyInstruction(const MachineInstr &MI,
12108 StringRef &ErrInfo) const {
12109 // Verify that immediate offsets on load/store instructions are within range.
12110 // Stack objects with an FI operand are excluded as they can be fixed up
12111 // during PEI.
12112 TypeSize Scale(0U, false), Width(0U, false);
12113 int64_t MinOffset, MaxOffset;
12114 if (getMemOpInfo(MI.getOpcode(), Scale, Width, MinOffset, MaxOffset)) {
12115 unsigned ImmIdx = getLoadStoreImmIdx(MI.getOpcode());
12116 if (MI.getOperand(ImmIdx).isImm() && !MI.getOperand(ImmIdx - 1).isFI()) {
12117 int64_t Imm = MI.getOperand(ImmIdx).getImm();
12118 if (Imm < MinOffset || Imm > MaxOffset) {
12119 ErrInfo = "Unexpected immediate on load/store instruction";
12120 return false;
12121 }
12122 }
12123 }
12124
12125 const MCInstrDesc &MCID = MI.getDesc();
12126 for (unsigned Op = 0; Op < MCID.getNumOperands(); Op++) {
12127 const MachineOperand &MO = MI.getOperand(Op);
12128 switch (MCID.operands()[Op].OperandType) {
12130 if (!MO.isImm() || MO.getImm() != 0) {
12131 ErrInfo = "OPERAND_IMPLICIT_IMM_0 should be 0";
12132 return false;
12133 }
12134 break;
12136 if (!MO.isImm() ||
12138 (AArch64_AM::getShiftValue(MO.getImm()) != 8 &&
12139 AArch64_AM::getShiftValue(MO.getImm()) != 16)) {
12140 ErrInfo = "OPERAND_SHIFT_MSL should be msl shift of 8 or 16";
12141 return false;
12142 }
12143 break;
12145 if (!MO.isImm() || !isUInt<5>(MO.getImm())) {
12146 ErrInfo = "OPERAND_IMM_UINT5 should be in the range 0 to 31";
12147 return false;
12148 }
12149 break;
12151 if (!MO.isImm() || !isUInt<8>(MO.getImm())) {
12152 ErrInfo = "OPERAND_IMM_UINT8 should be in the range 0 to 255";
12153 return false;
12154 }
12155 break;
12156 default:
12157 break;
12158 }
12159 }
12160 return true;
12161}
12162
12163#define GET_INSTRINFO_HELPERS
12164#define GET_INSTRMAP_INFO
12165#include "AArch64GenInstrInfo.inc"
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
static bool forwardCopyWillClobberTuple(unsigned DestReg, unsigned SrcReg, unsigned NumRegs)
static cl::opt< unsigned > BCCDisplacementBits("aarch64-bcc-offset-bits", cl::Hidden, cl::init(19), cl::desc("Restrict range of Bcc instructions (DEBUG)"))
static Register genNeg(MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, DenseMap< Register, unsigned > &InstrIdxForVirtReg, unsigned MnegOpc, const TargetRegisterClass *RC)
genNeg - Helper to generate an intermediate negation of the second operand of Root
static bool isFrameStoreOpcode(int Opcode)
static cl::opt< unsigned > GatherOptSearchLimit("aarch64-search-limit", cl::Hidden, cl::init(2048), cl::desc("Restrict range of instructions to search for the " "machine-combiner gather pattern optimization"))
static bool getMaddPatterns(MachineInstr &Root, SmallVectorImpl< unsigned > &Patterns)
Find instructions that can be turned into madd.
static AArch64CC::CondCode findCondCodeUsedByInstr(const MachineInstr &Instr)
Find a condition code used by the instruction.
static MachineInstr * genFusedMultiplyAcc(MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC)
genFusedMultiplyAcc - Helper to generate fused multiply accumulate instructions.
static MachineInstr * genFusedMultiplyAccNeg(MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, DenseMap< Register, unsigned > &InstrIdxForVirtReg, unsigned IdxMulOpd, unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC)
genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate instructions with an additional...
static bool isCombineInstrCandidate64(unsigned Opc)
static bool isFrameLoadOpcode(int Opcode)
static unsigned removeCopies(const MachineRegisterInfo &MRI, unsigned VReg)
static bool areCFlagsAccessedBetweenInstrs(MachineBasicBlock::iterator From, MachineBasicBlock::iterator To, const TargetRegisterInfo *TRI, const AccessKind AccessToCheck=AK_All)
True when condition flags are accessed (either by writing or reading) on the instruction trace starti...
static bool getFMAPatterns(MachineInstr &Root, SmallVectorImpl< unsigned > &Patterns)
Floating-Point Support.
static bool isADDSRegImm(unsigned Opcode)
static bool isCheapCopy(const MachineInstr &MI, const AArch64RegisterInfo &RI)
static bool isANDOpcode(MachineInstr &MI)
static void appendOffsetComment(int NumBytes, llvm::raw_string_ostream &Comment, StringRef RegScale={})
static unsigned sForm(MachineInstr &Instr)
Get opcode of S version of Instr.
static bool isCombineInstrSettingFlag(unsigned Opc)
static bool getFNEGPatterns(MachineInstr &Root, SmallVectorImpl< unsigned > &Patterns)
static bool getIndVarInfo(Register Reg, const MachineBasicBlock *LoopBB, MachineInstr *&UpdateInst, unsigned &UpdateCounterOprNum, Register &InitReg, bool &IsUpdatePriorComp)
If Reg is an induction variable, return true and set some parameters.
static bool canPairLdStOpc(unsigned FirstOpc, unsigned SecondOpc)
static bool mustAvoidNeonAtMBBI(const AArch64Subtarget &Subtarget, MachineBasicBlock &MBB, MachineBasicBlock::iterator I)
Returns true if in a streaming call site region without SME-FA64.
static bool isPostIndexLdStOpcode(unsigned Opcode)
Return true if the opcode is a post-index ld/st instruction, which really loads from base+0.
static std::optional< unsigned > getLFIInstSizeInBytes(const MachineInstr &MI)
Return the maximum number of bytes of code the specified instruction may be after LFI rewriting.
static unsigned getBranchDisplacementBits(unsigned Opc)
static cl::opt< unsigned > CBDisplacementBits("aarch64-cb-offset-bits", cl::Hidden, cl::init(9), cl::desc("Restrict range of CB instructions (DEBUG)"))
static std::optional< ParamLoadedValue > describeORRLoadedValue(const MachineInstr &MI, Register DescribedReg, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI)
If the given ORR instruction is a copy, and DescribedReg overlaps with the destination register then,...
static bool getFMULPatterns(MachineInstr &Root, SmallVectorImpl< unsigned > &Patterns)
static void appendReadRegExpr(SmallVectorImpl< char > &Expr, unsigned RegNum)
static MachineInstr * genMaddR(MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, unsigned IdxMulOpd, unsigned MaddOpc, unsigned VR, const TargetRegisterClass *RC)
genMaddR - Generate madd instruction and combine mul and add using an extra virtual register Example ...
static Register cloneInstr(const MachineInstr *MI, unsigned ReplaceOprNum, Register ReplaceReg, MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertTo)
Clone an instruction from MI.
static bool scaleOffset(unsigned Opc, int64_t &Offset)
static bool canCombineWithFMUL(MachineBasicBlock &MBB, MachineOperand &MO, unsigned MulOpc)
unsigned scaledOffsetOpcode(unsigned Opcode, unsigned &Scale)
static MachineInstr * genFusedMultiplyIdx(MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC)
genFusedMultiplyIdx - Helper to generate fused multiply accumulate instructions.
static MachineInstr * genIndexedMultiply(MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, unsigned IdxDupOp, unsigned MulOpc, const TargetRegisterClass *RC, MachineRegisterInfo &MRI)
Fold (FMUL x (DUP y lane)) into (FMUL_indexed x y lane)
static bool isSUBSRegImm(unsigned Opcode)
static bool UpdateOperandRegClass(MachineInstr &Instr)
static const TargetRegisterClass * getRegClass(const MachineInstr &MI, Register Reg)
static bool isInStreamingCallSiteRegion(MachineBasicBlock &MBB, MachineBasicBlock::iterator I)
Returns true if the instruction at I is in a streaming call site region, within a single basic block.
static bool canCmpInstrBeRemoved(MachineInstr &MI, MachineInstr &CmpInstr, int CmpValue, const TargetRegisterInfo &TRI, SmallVectorImpl< MachineInstr * > &CCUseInstrs, bool &IsInvertCC)
unsigned unscaledOffsetOpcode(unsigned Opcode)
static bool getLoadPatterns(MachineInstr &Root, SmallVectorImpl< unsigned > &Patterns)
Search for patterns of LD instructions we can optimize.
static bool canInstrSubstituteCmpInstr(MachineInstr &MI, MachineInstr &CmpInstr, const TargetRegisterInfo &TRI)
Check if CmpInstr can be substituted by MI.
static UsedNZCV getUsedNZCV(AArch64CC::CondCode CC)
static bool isCombineInstrCandidateFP(const MachineInstr &Inst)
static void appendLoadRegExpr(SmallVectorImpl< char > &Expr, int64_t OffsetFromDefCFA)
static void appendConstantExpr(SmallVectorImpl< char > &Expr, int64_t Constant, dwarf::LocationAtom Operation)
static unsigned convertToNonFlagSettingOpc(const MachineInstr &MI)
Return the opcode that does not set flags when possible - otherwise return the original opcode.
static bool outliningCandidatesV8_3OpsConsensus(const outliner::Candidate &a, const outliner::Candidate &b)
static bool isCombineInstrCandidate32(unsigned Opc)
static void parseCondBranch(MachineInstr *LastInst, MachineBasicBlock *&Target, SmallVectorImpl< MachineOperand > &Cond)
static unsigned offsetExtendOpcode(unsigned Opcode)
MachineOutlinerMBBFlags
@ LRUnavailableSomewhere
@ UnsafeRegsDead
static void loadRegPairFromStackSlot(const TargetRegisterInfo &TRI, MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore, const MCInstrDesc &MCID, Register DestReg, unsigned SubIdx0, unsigned SubIdx1, int FI, MachineMemOperand *MMO)
static void generateGatherLanePattern(MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, SmallVectorImpl< MachineInstr * > &DelInstrs, DenseMap< Register, unsigned > &InstrIdxForVirtReg, unsigned Pattern, unsigned NumLanes)
Generate optimized instruction sequence for gather load patterns to improve Memory-Level Parallelism ...
static bool getMiscPatterns(MachineInstr &Root, SmallVectorImpl< unsigned > &Patterns)
Find other MI combine patterns.
static bool outliningCandidatesSigningKeyConsensus(const outliner::Candidate &a, const outliner::Candidate &b)
static const MachineInstrBuilder & AddSubReg(const MachineInstrBuilder &MIB, MCRegister Reg, unsigned SubIdx, RegState State, const TargetRegisterInfo *TRI)
static bool outliningCandidatesSigningScopeConsensus(const outliner::Candidate &a, const outliner::Candidate &b)
static bool shouldClusterFI(const MachineFrameInfo &MFI, int FI1, int64_t Offset1, unsigned Opcode1, int FI2, int64_t Offset2, unsigned Opcode2)
static cl::opt< unsigned > TBZDisplacementBits("aarch64-tbz-offset-bits", cl::Hidden, cl::init(14), cl::desc("Restrict range of TB[N]Z instructions (DEBUG)"))
static void extractPhiReg(const MachineInstr &Phi, const MachineBasicBlock *MBB, Register &RegMBB, Register &RegOther)
static MCCFIInstruction createDefCFAExpression(const TargetRegisterInfo &TRI, unsigned Reg, const StackOffset &Offset)
static bool isDefinedOutside(Register Reg, const MachineBasicBlock *BB)
static MachineInstr * genFusedMultiply(MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC, FMAInstKind kind=FMAInstKind::Default, const Register *ReplacedAddend=nullptr)
genFusedMultiply - Generate fused multiply instructions.
static bool getGatherLanePattern(MachineInstr &Root, SmallVectorImpl< unsigned > &Patterns, unsigned LoadLaneOpCode, unsigned NumLanes)
Check if the given instruction forms a gather load pattern that can be optimized for better Memory-Le...
static MachineInstr * genFusedMultiplyIdxNeg(MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, DenseMap< Register, unsigned > &InstrIdxForVirtReg, unsigned IdxMulOpd, unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC)
genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate instructions with an additional...
static bool isCombineInstrCandidate(unsigned Opc)
static unsigned regOffsetOpcode(unsigned Opcode)
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
static cl::opt< unsigned > BDisplacementBits("aarch64-b-offset-bits", cl::Hidden, cl::init(26), cl::desc("Restrict range of B instructions (DEBUG)"))
static bool areCFlagsAliveInSuccessors(const MachineBasicBlock *MBB)
Check if AArch64::NZCV should be alive in successors of MBB.
static void emitFrameOffsetAdj(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, unsigned DestReg, unsigned SrcReg, int64_t Offset, unsigned Opc, const TargetInstrInfo *TII, MachineInstr::MIFlag Flag, bool NeedsWinCFI, bool *HasWinCFI, bool EmitCFAOffset, StackOffset CFAOffset, unsigned FrameReg)
static bool isCheapImmediate(const MachineInstr &MI, unsigned BitSize)
static cl::opt< unsigned > CBZDisplacementBits("aarch64-cbz-offset-bits", cl::Hidden, cl::init(19), cl::desc("Restrict range of CB[N]Z instructions (DEBUG)"))
static void genSubAdd2SubSub(MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, SmallVectorImpl< MachineInstr * > &DelInstrs, unsigned IdxOpd1, DenseMap< Register, unsigned > &InstrIdxForVirtReg)
Do the following transformation A - (B + C) ==> (A - B) - C A - (B + C) ==> (A - C) - B.
static unsigned canFoldIntoCSel(const MachineRegisterInfo &MRI, unsigned VReg, unsigned *NewReg=nullptr)
static void signOutlinedFunction(MachineFunction &MF, MachineBasicBlock &MBB, const AArch64InstrInfo *TII, bool ShouldSignReturnAddr)
static MachineInstr * genFNegatedMAD(MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs)
static bool canCombineWithMUL(MachineBasicBlock &MBB, MachineOperand &MO, unsigned MulOpc, unsigned ZeroReg)
static void storeRegPairToStackSlot(const TargetRegisterInfo &TRI, MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore, const MCInstrDesc &MCID, Register SrcReg, bool IsKill, unsigned SubIdx0, unsigned SubIdx1, int FI, MachineMemOperand *MMO)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static const Function * getParent(const Value *V)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
DXIL Forward Handle Accesses
@ Default
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static LVOptions Options
Definition LVOptions.cpp:25
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
MachineInstr unsigned OpIdx
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
PowerPC Reduce CR logical Operation
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
This file declares the machine register scavenger class.
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:484
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define DEBUG_WITH_TYPE(TYPE,...)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
Definition Debug.h:72
static bool canCombine(MachineBasicBlock &MBB, MachineOperand &MO, unsigned CombineOpc=0)
AArch64FunctionInfo - This class is derived from MachineFunctionInfo and contains private AArch64-spe...
SignReturnAddress getSignReturnAddressCondition() const
void setOutliningStyle(const std::string &Style)
std::optional< bool > hasRedZone() const
static bool shouldSignReturnAddress(SignReturnAddress Condition, bool IsLRSpilled)
static bool isHForm(const MachineInstr &MI)
Returns whether the instruction is in H form (16 bit operands)
void insertSelect(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL, Register DstReg, ArrayRef< MachineOperand > Cond, Register TrueReg, Register FalseReg) const override
static bool hasBTISemantics(const MachineInstr &MI)
Returns whether the instruction can be compatible with non-zero BTYPE.
static bool isQForm(const MachineInstr &MI)
Returns whether the instruction is in Q form (128 bit operands)
static bool getMemOpInfo(unsigned Opcode, TypeSize &Scale, TypeSize &Width, int64_t &MinOffset, int64_t &MaxOffset)
Returns true if opcode Opc is a memory operation.
static bool isTailCallReturnInst(const MachineInstr &MI)
Returns true if MI is one of the TCRETURN* instructions.
static bool isFPRCopy(const MachineInstr &MI)
Does this instruction rename an FPR without modifying bits?
MachineInstr * emitLdStWithAddr(MachineInstr &MemI, const ExtAddrMode &AM) const override
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...
MachineBasicBlock * getBranchDestBlock(const MachineInstr &MI) const override
unsigned getInstSizeInBytes(const MachineInstr &MI) const override
GetInstSize - Return the number of bytes of code the specified instruction may be.
static bool isZExtLoad(const MachineInstr &MI)
Returns whether the instruction is a zero-extending load.
bool areMemAccessesTriviallyDisjoint(const MachineInstr &MIa, const MachineInstr &MIb) 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
static bool isGPRCopy(const MachineInstr &MI)
Does this instruction rename a GPR without modifying bits?
static unsigned convertToFlagSettingOpc(unsigned Opc)
Return the opcode that set flags when possible.
void createPauthEpilogueInstr(MachineBasicBlock &MBB, DebugLoc DL) const
Return true when there is potentially a faster code sequence for an instruction chain ending in Root.
bool isBranchOffsetInRange(unsigned BranchOpc, int64_t BrOffset) const override
bool canInsertSelect(const MachineBasicBlock &, ArrayRef< MachineOperand > Cond, Register, Register, Register, int &, int &, int &) const override
Register isLoadFromStackSlotPostFE(const MachineInstr &MI, int &FrameIndex) const override
Check for post-frame ptr elimination stack locations as well.
static const MachineOperand & getLdStOffsetOp(const MachineInstr &MI)
Returns the immediate offset operator of a load/store.
bool isCoalescableExtInstr(const MachineInstr &MI, Register &SrcReg, Register &DstReg, unsigned &SubIdx) const override
static std::optional< unsigned > getUnscaledLdSt(unsigned Opc)
Returns the unscaled load/store for the scaled load/store opcode, if there is a corresponding unscale...
static bool hasUnscaledLdStOffset(unsigned Opc)
Return true if it has an unscaled load/store offset.
static const MachineOperand & getLdStAmountOp(const MachineInstr &MI)
Returns the shift amount operator of a load/store.
static bool isPreLdSt(const MachineInstr &MI)
Returns whether the instruction is a pre-indexed load/store.
std::optional< ExtAddrMode > getAddrModeFromMemoryOp(const MachineInstr &MemI, const TargetRegisterInfo *TRI) const override
bool getMemOperandsWithOffsetWidth(const MachineInstr &MI, SmallVectorImpl< const MachineOperand * > &BaseOps, int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width, const TargetRegisterInfo *TRI) const override
bool analyzeBranchPredicate(MachineBasicBlock &MBB, MachineBranchPredicate &MBP, bool AllowModify) const override
void insertIndirectBranch(MachineBasicBlock &MBB, MachineBasicBlock &NewDestBB, MachineBasicBlock &RestoreBB, const DebugLoc &DL, int64_t BrOffset, RegScavenger *RS) 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
static bool isPairableLdStInst(const MachineInstr &MI)
Return true if pairing the given load or store may be paired with another.
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
static bool isSExtLoad(const MachineInstr &MI)
Returns whether the instruction is a sign-extending load.
const AArch64RegisterInfo & getRegisterInfo() const
getRegisterInfo - TargetInstrInfo is a superset of MRegister info.
static bool isPreSt(const MachineInstr &MI)
Returns whether the instruction is a pre-indexed store.
void insertNoop(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const override
AArch64InstrInfo(const AArch64Subtarget &STI)
static bool isPairedLdSt(const MachineInstr &MI)
Returns whether the instruction is a paired load/store.
MachineInstr * foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI, ArrayRef< unsigned > Ops, int FrameIndex, MachineInstr *&CopyMI, LiveIntervals *LIS=nullptr, VirtRegMap *VRM=nullptr) const override
bool getMemOperandWithOffsetWidth(const MachineInstr &MI, const MachineOperand *&BaseOp, int64_t &Offset, bool &OffsetIsScalable, TypeSize &Width, const TargetRegisterInfo *TRI) const
If OffsetIsScalable is set to 'true', the offset is scaled by vscale.
Register isLoadFromStackSlot(const MachineInstr &MI, int &FrameIndex) const override
bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
static bool isStridedAccess(const MachineInstr &MI)
Return true if the given load or store is a strided memory access.
bool shouldClusterMemOps(ArrayRef< const MachineOperand * > BaseOps1, int64_t Offset1, bool OffsetIsScalable1, ArrayRef< const MachineOperand * > BaseOps2, int64_t Offset2, bool OffsetIsScalable2, unsigned ClusterSize, unsigned NumBytes) const override
Detect opportunities for ldp/stp formation.
unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const override
bool isThroughputPattern(unsigned Pattern) const override
Return true when a code sequence can improve throughput.
MachineOperand & getMemOpBaseRegImmOfsOffsetOperand(MachineInstr &LdSt) const
Return the immediate offset of the base register in a load/store LdSt.
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify=false) const override
bool canFoldIntoAddrMode(const MachineInstr &MemI, Register Reg, const MachineInstr &AddrI, ExtAddrMode &AM) const override
static bool isLdStPairSuppressed(const MachineInstr &MI)
Return true if pairing the given load or store is hinted to be unprofitable.
Register isStoreToStackSlotPostFE(const MachineInstr &MI, int &FrameIndex) const override
Check for post-frame ptr elimination stack locations as well.
std::unique_ptr< TargetInstrInfo::PipelinerLoopInfo > analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const override
bool isSchedulingBoundary(const MachineInstr &MI, const MachineBasicBlock *MBB, const MachineFunction &MF) const override
unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) 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 supplying the argument to the comparison into one that...
static unsigned getLoadStoreImmIdx(unsigned Opc)
Returns the index for the immediate for a given instruction.
static bool isGPRZero(const MachineInstr &MI)
Does this instruction set its full destination register to zero?
void copyGPRRegTuple(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, MCRegister DestReg, MCRegister SrcReg, bool KillSrc, unsigned Opcode, unsigned ZeroReg, llvm::ArrayRef< unsigned > Indices) const
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,...
CombinerObjective getCombinerObjective(unsigned Pattern) const override
static bool isFpOrNEON(Register Reg)
Returns whether the physical register is FP or NEON.
bool isAsCheapAsAMove(const MachineInstr &MI) const override
std::optional< DestSourcePair > isCopyLikeInstrImpl(const MachineInstr &MI) const override
static void suppressLdStPair(MachineInstr &MI)
Hint that pairing the given load or store is unprofitable.
Register isStoreToStackSlot(const MachineInstr &MI, int &FrameIndex) const override
static bool isPreLd(const MachineInstr &MI)
Returns whether the instruction is a pre-indexed load.
void copyPhysRegTuple(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, MCRegister DestReg, MCRegister SrcReg, bool KillSrc, unsigned Opcode, llvm::ArrayRef< unsigned > Indices) const
bool optimizeCondBranch(MachineInstr &MI) const override
Replace csincr-branch sequence by simple conditional branch.
static int getMemScale(unsigned Opc)
Scaling factor for (scaled or unscaled) load or store.
bool isCandidateToMergeOrPair(const MachineInstr &MI) const
Return true if this is a load/store that can be potentially paired/merged.
MCInst getNop() const override
static const MachineOperand & getLdStBaseOp(const MachineInstr &MI)
Returns the base register operator of a load/store.
bool isReservedReg(const MachineFunction &MF, MCRegister Reg) const
const AArch64RegisterInfo * getRegisterInfo() const override
bool isNeonAvailable() const
Returns true if the target has NEON and the function at runtime is known to have NEON enabled (e....
bool isSVEorStreamingSVEAvailable() const
Returns true if the target has access to either the full range of SVE instructions,...
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
This is an important base class in LLVM.
Definition Constant.h:43
A debug info location.
Definition DebugLoc.h:126
bool empty() const
Definition DenseMap.h:171
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition Function.h:688
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:685
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
static LocationSize precise(uint64_t Value)
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition MCAsmInfo.h:66
bool usesWindowsCFI() const
Definition MCAsmInfo.h:674
static MCCFIInstruction cfiDefCfa(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa defines a rule for computing CFA as: take address from Register and add Offset to it.
Definition MCDwarf.h:615
static MCCFIInstruction createOffset(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_offset Previous value of Register is saved at offset Offset from CFA.
Definition MCDwarf.h:657
static MCCFIInstruction cfiDefCfaOffset(MCSymbol *L, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa_offset modifies a rule for computing CFA.
Definition MCDwarf.h:630
static MCCFIInstruction createEscape(MCSymbol *L, StringRef Vals, SMLoc Loc={}, StringRef Comment="")
.cfi_escape Allows the user to add arbitrary bytes to the unwind info.
Definition MCDwarf.h:727
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:188
Describe properties that are true of each instruction in the target description file.
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
ArrayRef< MCOperandInfo > operands() const
bool hasSuperClassEq(const MCRegisterClass *RC) const
Returns true if RC is a super-class of or equal to this class.
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
bool hasSubClassEq(const MCRegisterClass *RC) const
Returns true if RC is a sub-class of or equal to this class.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
constexpr bool isValid() const
Definition MCRegister.h:84
static constexpr unsigned NoRegister
Definition MCRegister.h:60
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1565
Set of metadata that should be preserved when using BuildMI().
bool isInlineAsmBrIndirectTarget() const
Returns true if this is the indirect dest of an INLINEASM_BR.
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
reverse_instr_iterator instr_rbegin()
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
reverse_instr_iterator instr_rend()
Instructions::iterator instr_iterator
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
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.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
void setMachineBlockAddressTaken()
Set this block to indicate that its address is used as something other than the target of a terminato...
LLVM_ABI bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
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.
void setStackID(int ObjectIdx, uint8_t ID)
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.
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
unsigned addFrameInst(const MCCFIInstruction &Inst)
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.
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy, Align base_alignment, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr, SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
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.
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & setMemRefs(ArrayRef< MachineMemOperand * > MMOs) const
const MachineInstrBuilder & addCFIIndex(unsigned CFIIndex) const
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addSym(MCSymbol *Sym, unsigned char TargetFlags=0) const
const MachineInstrBuilder & addFrameIndex(int Idx) 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 & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
reverse_iterator getReverse() const
Get a reverse iterator to the same node.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
bool isCopy() const
const MachineBasicBlock * getParent() const
bool isCall(QueryType Type=AnyInBundle) const
bool getFlag(MIFlag Flag) const
Return whether an MI flag is set.
LLVM_ABI uint32_t mergeFlagsWith(const MachineInstr &Other) const
Return the MIFlags which represent both MachineInstrs.
unsigned getNumOperands() const
Retuns the total number of operands.
LLVM_ABI unsigned getNumExplicitOperands() const
Returns the number of non-implicit operands.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
LLVM_ABI bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore,...
bool registerDefIsDead(Register Reg, const TargetRegisterInfo *TRI) const
Returns true if the register is dead in this machine instruction.
bool definesRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr fully defines the specified register.
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
LLVM_ABI bool hasOrderedMemoryRef() const
Return true if this instruction may have an ordered or volatile memory reference, or if the informati...
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
ArrayRef< MachineMemOperand * > memoperands() const
Access to memory operands of the instruction.
LLVM_ABI bool isLoadFoldBarrier() const
Returns true if it is illegal to fold a load across this instruction.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
LLVM_ABI void addRegisterDefined(Register Reg, const TargetRegisterInfo *RegInfo=nullptr)
We have determined MI defines a register.
const MachineOperand & getOperand(unsigned i) const
uint32_t getFlags() const
Return the MI flags bitvector.
LLVM_ABI int findRegisterDefOperandIdx(Register Reg, const TargetRegisterInfo *TRI, bool isDead=false, bool Overlap=false) const
Returns the operand index that is a def of the specified register or -1 if it is not found.
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
const std::vector< MachineJumpTableEntry > & getJumpTables() const
A description of a memory reference used in the backend.
@ MOVolatile
The memory access is volatile.
@ MOLoad
The memory access reads data.
@ 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.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
void setImm(int64_t immVal)
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
void setIsDead(bool Val=true)
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
void setIsKill(bool Val=true)
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
unsigned getTargetFlags() const
static MachineOperand CreateImm(int64_t Val)
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
bool isFI() const
isFI - Tests if this is a MO_FrameIndex operand.
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 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)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI bool hasOneNonDBGUse(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug use of the specified register.
bool tracksLiveness() const
tracksLiveness - Returns true when tracking register liveness accurately.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI void clearKillFlags(Register Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
LLVM_ABI MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
bool use_nodbg_empty(Register RegNo) const
use_nodbg_empty - Return true if there are no non-Debug instructions using the specified register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
bool reservedRegsFrozen() const
reservedRegsFrozen - Returns true after freezeReservedRegs() was called to ensure the set of reserved...
bool def_empty(Register RegNo) const
def_empty - Return true if there are no instructions defining the specified register (it may be live-...
use_instr_nodbg_iterator use_instr_nodbg_begin(Register RegNo) const
bool hasOneDef(Register RegNo) const
Return true if there is exactly one operand defining the specified register.
const TargetRegisterClass * getRegClassOrNull(Register Reg) const
Return the register class of Reg, or null if Reg has not been assigned a register class yet.
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
LLVM_ABI MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
MI-level patchpoint operands.
Definition StackMaps.h:77
uint32_t getNumPatchBytes() const
Return the number of patchable bytes the given patchpoint should emit.
Definition StackMaps.h:105
Wrapper class representing virtual and physical registers.
Definition Register.h:20
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
constexpr bool isValid() const
Definition Register.h:112
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
static constexpr bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:66
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
Represents a location in source code.
Definition SMLoc.h:22
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.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
bool empty() const
Definition SmallSet.h:169
bool erase(const T &V)
Definition SmallSet.h:200
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:68
StringRef str() const
Explicit conversion to StringRef.
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.
MI-level stackmap operands.
Definition StackMaps.h:36
uint32_t getNumPatchBytes() const
Return the number of patchable bytes the given stackmap should emit.
Definition StackMaps.h:51
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:30
int64_t getFixed() const
Returns the fixed component of the stack.
Definition TypeSize.h:46
int64_t getScalable() const
Returns the scalable component of the stack.
Definition TypeSize.h:49
static StackOffset get(int64_t Fixed, int64_t Scalable)
Definition TypeSize.h:41
static StackOffset getScalable(int64_t Scalable)
Definition TypeSize.h:40
static StackOffset getFixed(int64_t Fixed)
Definition TypeSize.h:39
MI-level Statepoint operands.
Definition StackMaps.h:159
uint32_t getNumPatchBytes() const
Return the number of patchable bytes the given statepoint should emit.
Definition StackMaps.h:208
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Object returned by analyzeLoopForPipelining.
TargetInstrInfo - Interface to description of machine instruction set.
virtual void genAlternativeCodeSequence(MachineInstr &Root, unsigned Pattern, SmallVectorImpl< MachineInstr * > &InsInstrs, SmallVectorImpl< MachineInstr * > &DelInstrs, DenseMap< Register, unsigned > &InstIdxForVirtReg) const
When getMachineCombinerPatterns() finds patterns, this function generates the instructions that could...
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 bool getMachineCombinerPatterns(MachineInstr &Root, SmallVectorImpl< unsigned > &Patterns, bool DoRegPressureReduce) const
Return true when there is potentially a faster code sequence for an instruction chain ending in Root.
virtual bool isSchedulingBoundary(const MachineInstr &MI, const MachineBasicBlock *MBB, const MachineFunction &MF) const
Test if the given instruction should be considered a scheduling boundary.
virtual CombinerObjective getCombinerObjective(unsigned Pattern) const
Return the objective of a combiner pattern.
virtual bool isFunctionSafeToSplit(const MachineFunction &MF) const
Return true if the function is a viable candidate for machine function splitting.
const MCAsmInfo & getMCAsmInfo() const
Return target specific asm information.
TargetOptions Options
CodeModel::Model getCodeModel() const
Returns the code model.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
Target - Wrapper for Target specific information.
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:343
static constexpr TypeSize getScalable(ScalarTy MinimumSize)
Definition TypeSize.h:346
Value * getOperand(unsigned i) const
Definition User.h:207
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
self_iterator getIterator()
Definition ilist_node.h:123
A raw_ostream that writes to an std::string.
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static CondCode getInvertedCondCode(CondCode Code)
@ MO_DLLIMPORT
MO_DLLIMPORT - On a symbol operand, this represents that the reference to the symbol is for an import...
@ MO_NC
MO_NC - Indicates whether the linker is expected to check the symbol reference for overflow.
@ MO_G1
MO_G1 - A symbol operand with this flag (granule 1) represents the bits 16-31 of a 64-bit address,...
@ MO_S
MO_S - Indicates that the bits of the symbol operand represented by MO_G0 etc are signed.
@ MO_PAGEOFF
MO_PAGEOFF - A symbol operand with this flag represents the offset of that symbol within a 4K page.
@ MO_GOT
MO_GOT - This flag indicates that a symbol operand represents the address of the GOT entry for the sy...
@ MO_PREL
MO_PREL - Indicates that the bits of the symbol operand represented by MO_G0 etc are PC relative.
@ MO_G0
MO_G0 - A symbol operand with this flag (granule 0) represents the bits 0-15 of a 64-bit address,...
@ MO_ARM64EC_CALLMANGLE
MO_ARM64EC_CALLMANGLE - Operand refers to the Arm64EC-mangled version of a symbol,...
@ MO_PAGE
MO_PAGE - A symbol operand with this flag represents the pc-relative offset of the 4K page containing...
@ MO_HI12
MO_HI12 - This flag indicates that a symbol operand represents the bits 13-24 of a 64-bit address,...
@ MO_TLS
MO_TLS - Indicates that the operand being accessed is some kind of thread-local symbol.
@ MO_G2
MO_G2 - A symbol operand with this flag (granule 2) represents the bits 32-47 of a 64-bit address,...
@ MO_TAGGED
MO_TAGGED - With MO_PAGE, indicates that the page includes a memory tag in bits 56-63.
@ MO_G3
MO_G3 - A symbol operand with this flag (granule 3) represents the high 16-bits of a 64-bit address,...
@ MO_COFFSTUB
MO_COFFSTUB - On a symbol operand "FOO", this indicates that the reference is actually to the "....
unsigned getCheckerSizeInBytes(AuthCheckMethod Method)
Returns the number of bytes added by checkAuthenticatedRegister.
static uint64_t decodeLogicalImmediate(uint64_t val, unsigned regSize)
decodeLogicalImmediate - Decode a logical immediate value in the form "N:immr:imms" (where the immr a...
static unsigned getShiftValue(unsigned Imm)
getShiftValue - Extract the shift value.
static unsigned getArithExtendImm(AArch64_AM::ShiftExtendType ET, unsigned Imm)
getArithExtendImm - Encode the extend type and shift amount for an arithmetic instruction: imm: 3-bit...
constexpr bool isLegalArithImmed(const uint64_t C)
isLegalArithImmed -
static unsigned getArithShiftValue(unsigned Imm)
getArithShiftValue - get the arithmetic shift value.
static uint64_t encodeLogicalImmediate(uint64_t imm, unsigned regSize)
encodeLogicalImmediate - Return the encoded immediate value for a logical immediate instruction of th...
static AArch64_AM::ShiftExtendType getExtendType(unsigned Imm)
getExtendType - Extract the extend type for operands of arithmetic ops.
static AArch64_AM::ShiftExtendType getArithExtendType(unsigned Imm)
static AArch64_AM::ShiftExtendType getShiftType(unsigned Imm)
getShiftType - Extract the shift type.
static unsigned getShifterImm(AArch64_AM::ShiftExtendType ST, unsigned Imm)
getShifterImm - Encode the shift type and amount: imm: 6-bit shift amount shifter: 000 ==> lsl 001 ==...
void expandMOVAddr(unsigned Opcode, unsigned TargetFlags, bool IsTargetMachO, SmallVectorImpl< AddrInsnModel > &Insn)
void expandMOVImm(uint64_t Imm, unsigned BitSize, SmallVectorImpl< ImmInsnModel > &Insn)
Expand a MOVi32imm or MOVi64imm pseudo instruction to one or more real move-immediate instructions to...
static const uint64_t InstrFlagIsWhile
static const uint64_t InstrFlagIsPTestLike
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
initializer< Ty > init(const Ty &Val)
constexpr double e
InstrType
Represents how an instruction should be mapped by the outliner.
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:391
iterator end() const
Definition BasicBlock.h:89
LLVM_ABI Instruction & back() const
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
@ Offset
Definition DWP.cpp:573
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
static bool isCondBranchOpcode(int Opc)
MCCFIInstruction createDefCFA(const TargetRegisterInfo &TRI, unsigned FrameReg, unsigned Reg, const StackOffset &Offset, bool LastAdjustmentWasScalable=true)
static bool isPTrueOpcode(unsigned Opc)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
bool succeeded(LogicalResult Result)
Utility function that returns true if the provided LogicalResult corresponds to a success value.
int isAArch64FrameOffsetLegal(const MachineInstr &MI, StackOffset &Offset, bool *OutUseUnscaledOp=nullptr, unsigned *OutUnscaledOp=nullptr, int64_t *EmittableOffset=nullptr)
Check if the Offset is a valid frame offset for MI.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:165
RegState
Flags to represent properties of register accesses.
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Dead
Unused definition.
@ Kill
The last use of a register.
@ Undef
Value of the register doesn't matter.
@ Define
Register definition.
@ Renamable
Register that may be renamed.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
constexpr RegState getKillRegState(bool B)
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 isIndirectBranchOpcode(int Opc)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
unsigned getBLRCallOpcode(const MachineFunction &MF)
Return opcode to be used for indirect calls.
@ AArch64FrameOffsetIsLegal
Offset is legal.
@ AArch64FrameOffsetCanUpdate
Offset can apply, at least partly.
@ AArch64FrameOffsetCannotUpdate
Offset cannot apply.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:284
Op::Description Desc
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:337
static bool isSEHInstruction(const MachineInstr &MI)
bool isLFIPrePostMemAccess(unsigned Opcode)
Returns true if Opcode is a pre- or post-indexed memory access that the LFI rewriter expands with a b...
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:1746
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
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:1636
AArch64MachineCombinerPattern
@ MULSUBv8i16_OP2
@ FMULv4i16_indexed_OP1
@ FMLSv1i32_indexed_OP2
@ MULSUBv2i32_indexed_OP1
@ FMLAv2i32_indexed_OP2
@ MULADDv4i16_indexed_OP2
@ FMLAv1i64_indexed_OP1
@ MULSUBv16i8_OP1
@ FMLAv8i16_indexed_OP2
@ FMULv2i32_indexed_OP1
@ MULSUBv8i16_indexed_OP2
@ FMLAv1i64_indexed_OP2
@ MULSUBv4i16_indexed_OP2
@ FMLAv1i32_indexed_OP1
@ FMLAv2i64_indexed_OP2
@ FMLSv8i16_indexed_OP1
@ MULSUBv2i32_OP1
@ FMULv4i16_indexed_OP2
@ MULSUBv4i32_indexed_OP2
@ FMULv2i64_indexed_OP2
@ FMLAv4i32_indexed_OP1
@ MULADDv4i16_OP2
@ FMULv8i16_indexed_OP2
@ MULSUBv4i16_OP1
@ MULADDv4i32_OP2
@ MULADDv2i32_OP2
@ MULADDv16i8_OP2
@ FMLSv4i16_indexed_OP1
@ MULADDv16i8_OP1
@ FMLAv2i64_indexed_OP1
@ FMLAv1i32_indexed_OP2
@ FMLSv2i64_indexed_OP2
@ MULADDv2i32_OP1
@ MULADDv4i32_OP1
@ MULADDv2i32_indexed_OP1
@ MULSUBv16i8_OP2
@ MULADDv4i32_indexed_OP1
@ MULADDv2i32_indexed_OP2
@ FMLAv4i16_indexed_OP2
@ MULSUBv8i16_OP1
@ FMULv2i32_indexed_OP2
@ FMLSv2i32_indexed_OP2
@ FMLSv4i32_indexed_OP1
@ FMULv2i64_indexed_OP1
@ MULSUBv4i16_OP2
@ FMLSv4i16_indexed_OP2
@ FMLAv2i32_indexed_OP1
@ FMLSv2i32_indexed_OP1
@ FMLAv8i16_indexed_OP1
@ MULSUBv4i16_indexed_OP1
@ FMLSv4i32_indexed_OP2
@ MULADDv4i32_indexed_OP2
@ MULSUBv4i32_OP2
@ MULSUBv8i16_indexed_OP1
@ MULADDv8i16_OP2
@ MULSUBv2i32_indexed_OP2
@ FMULv4i32_indexed_OP2
@ FMLSv2i64_indexed_OP1
@ MULADDv4i16_OP1
@ FMLAv4i32_indexed_OP2
@ MULADDv8i16_indexed_OP1
@ FMULv4i32_indexed_OP1
@ FMLAv4i16_indexed_OP1
@ FMULv8i16_indexed_OP1
@ MULADDv8i16_OP1
@ MULSUBv4i32_indexed_OP1
@ MULSUBv4i32_OP1
@ FMLSv8i16_indexed_OP2
@ MULADDv8i16_indexed_OP2
@ MULSUBv2i32_OP2
@ FMLSv1i64_indexed_OP2
@ MULADDv4i16_indexed_OP1
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
void emitFrameOffset(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, unsigned DestReg, unsigned SrcReg, StackOffset Offset, const TargetInstrInfo *TII, MachineInstr::MIFlag=MachineInstr::NoFlags, bool SetNZCV=false, bool NeedsWinCFI=false, bool *HasWinCFI=nullptr, bool EmitCFAOffset=false, StackOffset InitialOffset={}, unsigned FrameReg=AArch64::SP)
emitFrameOffset - Emit instructions as needed to set DestReg to SrcReg plus Offset.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr RegState getDefRegState(bool B)
CombinerObjective
The combiner's goal may differ based on which pattern it is attempting to optimize.
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:189
std::optional< UsedNZCV > examineCFlagsUse(MachineInstr &MI, MachineInstr &CmpInstr, const TargetRegisterInfo &TRI, SmallVectorImpl< MachineInstr * > *CCUseInstrs=nullptr)
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:82
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,...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:322
static MCRegister getXRegFromWReg(MCRegister Reg)
MCCFIInstruction createCFAOffset(const TargetRegisterInfo &MRI, unsigned Reg, const StackOffset &OffsetFromDefCFA, std::optional< int64_t > IncomingVGOffsetFromDefCFA)
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
static bool isUncondBranchOpcode(int Opc)
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:2192
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:248
bool rewriteAArch64FrameIndex(MachineInstr &MI, unsigned FrameRegIdx, unsigned FrameReg, StackOffset &Offset, const AArch64InstrInfo *TII)
rewriteAArch64FrameIndex - Rewrite MI to access 'Offset' bytes from the FP.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
static const MachineMemOperand::Flags MOSuppressPair
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:572
void appendLEB128(SmallVectorImpl< U > &Buffer, T Value)
Definition LEB128.h:246
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
bool optimizeTerminators(MachineBasicBlock *MBB, const TargetInstrInfo &TII)
std::pair< MachineOperand, DIExpression * > ParamLoadedValue
bool isNZCVTouchedInInstructionRange(const MachineInstr &DefMI, const MachineInstr &UseMI, const TargetRegisterInfo *TRI)
Return true if there is an instruction /after/ DefMI and before UseMI which either reads or clobbers ...
auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:305
static const MachineMemOperand::Flags MOStridedAccess
constexpr RegState getUndefRegState(bool B)
void fullyRecomputeLiveIns(ArrayRef< MachineBasicBlock * > MBBs)
Convenience function for recomputing live-in's for a set of MBBs until the computation converges.
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Used to describe addressing mode similar to ExtAddrMode in CodeGenPrepare.
LLVM_ABI static const MBBSectionID ColdSectionID
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getUnknownStack(MachineFunction &MF)
Stack memory without other information.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
An individual sequence of instructions to be replaced with a call to an outlined function.
MachineFunction * getMF() const
The information necessary to create an outlined function for some class of candidate.