LLVM 24.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 "aarch64-outliner-compact-unwind-frame", cl::Hidden, cl::init(true),
108 cl::desc("Use a frame record for Mach-O non-leaf outlined functions"));
109
111 : AArch64GenInstrInfo(STI, RI, AArch64::ADJCALLSTACKDOWN,
112 AArch64::ADJCALLSTACKUP, AArch64::CATCHRET),
113 RI(STI.getTargetTriple(), STI.getHwMode()), Subtarget(STI) {}
114
115/// Return the maximum number of bytes of code the specified instruction may be
116/// after LFI rewriting. If the instruction is not rewritten, std::nullopt is
117/// returned (use default sizing).
118///
119/// NOTE: the size estimates here must be kept in sync with the rewrites in
120/// AArch64MCLFIRewriter.cpp. Sizes may be overestimates of the rewritten
121/// instruction sequences.
122static std::optional<unsigned> getLFIInstSizeInBytes(const MachineInstr &MI) {
123 switch (MI.getOpcode()) {
124 case AArch64::SVC:
125 // SVC expands to 4 instructions.
126 return 16;
127 case AArch64::BR:
128 case AArch64::BLR:
129 // Indirect branches/calls expand to 2 instructions (guard + br/blr).
130 return 8;
131 case AArch64::RET:
132 // RET through LR is not rewritten, but RET through another register
133 // expands to 2 instructions (guard + ret).
134 if (MI.getOperand(0).getReg() != AArch64::LR)
135 return 8;
136 return 4;
137 case AArch64::RETAA:
138 case AArch64::RETAB:
139 // Authenticated returns expand to 3 instructions (authenticate + guard +
140 // ret).
141 return 12;
142 case AArch64::BRAA:
143 case AArch64::BRAAZ:
144 case AArch64::BRAB:
145 case AArch64::BRABZ:
146 case AArch64::BLRAA:
147 case AArch64::BLRAAZ:
148 case AArch64::BLRAB:
149 case AArch64::BLRABZ:
150 // Authenticated branches/calls expand to 3 instructions (authenticate +
151 // guard + branch).
152 return 12;
153 case AArch64::AUTIASP:
154 case AArch64::AUTIBSP:
155 case AArch64::AUTIAZ:
156 case AArch64::AUTIBZ:
157 case AArch64::XPACLRI:
158 // Authenticating LR expands to the instruction plus a deferred LR guard.
159 return 8;
160 case AArch64::SYSxt:
161 // VA-based DC/IC ops (op1=3, Cn=7, op2=1) expand to 2 instructions.
162 if (MI.getOperand(0).getImm() == 3 && MI.getOperand(1).getImm() == 7 &&
163 MI.getOperand(3).getImm() == 1)
164 return 8;
165 return std::nullopt;
166 default:
167 break;
168 }
169
170 // Detect instructions that explicitly define SP or LR.
171 bool ModifiesLR = false;
172 bool ModifiesSP = false;
173 for (const MachineOperand &MO : MI.defs()) {
174 if (!MO.isReg())
175 continue;
176 if (MO.getReg() == AArch64::LR)
177 ModifiesLR = true;
178 else if (MO.getReg() == AArch64::SP)
179 ModifiesSP = true;
180 }
181
182 // Memory accesses expand to a base-register guard plus the rewritten access
183 // (8 bytes), with an extra base-register update for pre/post-index forms (12
184 // bytes total). If the access also defines LR, an LR mask is appended (+4
185 // bytes). Depending on additional optimizations that the rewriter performs,
186 // this may be an overestimate.
187 if (MI.mayLoadOrStore()) {
188 unsigned Size = isLFIPrePostMemAccess(MI.getOpcode()) ? 12 : 8;
189 if (ModifiesLR)
190 Size += 4;
191 return Size;
192 }
193
194 // Non memory operations that modify LR or SP expand to 2 instructions.
195 if (ModifiesSP || ModifiesLR)
196 return 8;
197
198 // Default case: instructions that don't cause expansion.
199 // - TP accesses in LFI are a single load/store, so no expansion.
200 // - All remaining instructions are not rewritten.
201 return std::nullopt;
202}
203
204/// GetInstSize - Return the number of bytes of code the specified
205/// instruction may be. This returns the maximum number of bytes.
207 const MachineBasicBlock &MBB = *MI.getParent();
208 const MachineFunction *MF = MBB.getParent();
209 const Function &F = MF->getFunction();
210 const MCAsmInfo &MAI = MF->getTarget().getMCAsmInfo();
211
212 {
213 auto Op = MI.getOpcode();
214 if (Op == AArch64::INLINEASM || Op == AArch64::INLINEASM_BR)
215 return getInlineAsmLength(MI.getOperand(0).getSymbolName(), MAI);
216 }
217
218 // Meta-instructions emit no code.
219 if (MI.isMetaInstruction())
220 return 0;
221
222 // FIXME: We currently only handle pseudoinstructions that don't get expanded
223 // before the assembly printer.
224 unsigned NumBytes = 0;
225 const MCInstrDesc &Desc = MI.getDesc();
226
227 // LFI rewriter expansions that supersede normal sizing.
228 const auto &STI = MF->getSubtarget<AArch64Subtarget>();
229 if (STI.isLFI())
230 if (auto Size = getLFIInstSizeInBytes(MI))
231 return *Size;
232
233 if (!MI.isBundle() && isTailCallReturnInst(MI)) {
234 NumBytes = Desc.getSize() ? Desc.getSize() : 4;
235
236 const auto *MFI = MF->getInfo<AArch64FunctionInfo>();
237 if (!MFI->shouldSignReturnAddress(*MF))
238 return NumBytes;
239
240 auto Method = STI.getAuthenticatedLRCheckMethod(*MF);
241 NumBytes += AArch64PAuth::getCheckerSizeInBytes(Method);
242 return NumBytes;
243 }
244
245 // Size should be preferably set in
246 // llvm/lib/Target/AArch64/AArch64InstrInfo.td (default case).
247 // Specific cases handle instructions of variable sizes
248 switch (Desc.getOpcode()) {
249 default:
250 if (Desc.getSize())
251 return Desc.getSize();
252
253 // Anything not explicitly designated otherwise (i.e. pseudo-instructions
254 // with fixed constant size but not specified in .td file) is a normal
255 // 4-byte insn.
256 NumBytes = 4;
257 break;
258 case TargetOpcode::STACKMAP:
259 // The upper bound for a stackmap intrinsic is the full length of its shadow
260 NumBytes = StackMapOpers(&MI).getNumPatchBytes();
261 assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
262 break;
263 case TargetOpcode::PATCHPOINT:
264 // The size of the patchpoint intrinsic is the number of bytes requested
265 NumBytes = PatchPointOpers(&MI).getNumPatchBytes();
266 assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
267 break;
268 case TargetOpcode::STATEPOINT:
269 NumBytes = StatepointOpers(&MI).getNumPatchBytes();
270 assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
271 // No patch bytes means a normal call inst is emitted
272 if (NumBytes == 0)
273 NumBytes = 4;
274 break;
275 case TargetOpcode::PATCHABLE_FUNCTION_ENTER:
276 // If `patchable-function-entry` is set, PATCHABLE_FUNCTION_ENTER
277 // instructions are expanded to the specified number of NOPs. Otherwise,
278 // they are expanded to 36-byte XRay sleds.
279 NumBytes =
280 F.getFnAttributeAsParsedInteger("patchable-function-entry", 9) * 4;
281 break;
282 case TargetOpcode::PATCHABLE_FUNCTION_EXIT:
283 case TargetOpcode::PATCHABLE_TAIL_CALL:
284 case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
285 // An XRay sled can be 4 bytes of alignment plus a 32-byte block.
286 NumBytes = 36;
287 break;
288 case TargetOpcode::PATCHABLE_EVENT_CALL:
289 // EVENT_CALL XRay sleds are exactly 6 instructions long (no alignment).
290 NumBytes = 24;
291 break;
292
293 case AArch64::SPACE:
294 NumBytes = MI.getOperand(1).getImm();
295 break;
296 case AArch64::MOVaddr:
297 case AArch64::MOVaddrJT:
298 case AArch64::MOVaddrCP:
299 case AArch64::MOVaddrBA:
300 case AArch64::MOVaddrTLS:
301 case AArch64::MOVaddrEXT: {
302 // Use the same logic as the pseudo expansion to count instructions.
305 MI.getOperand(1).getTargetFlags(),
306 Subtarget.isTargetMachO(), Insn);
307 NumBytes = Insn.size() * 4;
308 break;
309 }
310
311 case AArch64::MOVi32imm:
312 case AArch64::MOVi64imm: {
313 // Use the same logic as the pseudo expansion to count instructions.
314 unsigned BitSize = Desc.getOpcode() == AArch64::MOVi32imm ? 32 : 64;
316 AArch64_IMM::expandMOVImm(MI.getOperand(1).getImm(), BitSize, Insn);
317 NumBytes = Insn.size() * 4;
318 break;
319 }
320
321 case TargetOpcode::BUNDLE:
322 NumBytes = getInstBundleSize(MI);
323 break;
324 }
325
326 return NumBytes;
327}
328
331 // Block ends with fall-through condbranch.
332 switch (LastInst->getOpcode()) {
333 default:
334 llvm_unreachable("Unknown branch instruction?");
335 case AArch64::Bcc:
336 Target = LastInst->getOperand(1).getMBB();
337 Cond.push_back(LastInst->getOperand(0));
338 break;
339 case AArch64::CBZW:
340 case AArch64::CBZX:
341 case AArch64::CBNZW:
342 case AArch64::CBNZX:
343 Target = LastInst->getOperand(1).getMBB();
344 Cond.push_back(MachineOperand::CreateImm(-1));
345 Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
346 Cond.push_back(LastInst->getOperand(0));
347 break;
348 case AArch64::TBZW:
349 case AArch64::TBZX:
350 case AArch64::TBNZW:
351 case AArch64::TBNZX:
352 Target = LastInst->getOperand(2).getMBB();
353 Cond.push_back(MachineOperand::CreateImm(-1));
354 Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
355 Cond.push_back(LastInst->getOperand(0));
356 Cond.push_back(LastInst->getOperand(1));
357 break;
358 case AArch64::CBWPri:
359 case AArch64::CBXPri:
360 case AArch64::CBWPrr:
361 case AArch64::CBXPrr:
362 Target = LastInst->getOperand(3).getMBB();
363 Cond.push_back(MachineOperand::CreateImm(-1));
364 Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
365 Cond.push_back(LastInst->getOperand(0));
366 Cond.push_back(LastInst->getOperand(1));
367 Cond.push_back(LastInst->getOperand(2));
368 break;
369 case AArch64::CBBAssertExt:
370 case AArch64::CBHAssertExt:
371 Target = LastInst->getOperand(3).getMBB();
372 Cond.push_back(MachineOperand::CreateImm(-1)); // -1
373 Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode())); // Opc
374 Cond.push_back(LastInst->getOperand(0)); // Cond
375 Cond.push_back(LastInst->getOperand(1)); // Op0
376 Cond.push_back(LastInst->getOperand(2)); // Op1
377 Cond.push_back(LastInst->getOperand(4)); // Ext0
378 Cond.push_back(LastInst->getOperand(5)); // Ext1
379 break;
380 }
381}
382
383static unsigned getBranchDisplacementBits(unsigned Opc) {
384 switch (Opc) {
385 default:
386 llvm_unreachable("unexpected opcode!");
387 case AArch64::B:
388 return BDisplacementBits;
389 case AArch64::TBNZW:
390 case AArch64::TBZW:
391 case AArch64::TBNZX:
392 case AArch64::TBZX:
393 return TBZDisplacementBits;
394 case AArch64::CBNZW:
395 case AArch64::CBZW:
396 case AArch64::CBNZX:
397 case AArch64::CBZX:
398 return CBZDisplacementBits;
399 case AArch64::Bcc:
400 return BCCDisplacementBits;
401 case AArch64::CBWPri:
402 case AArch64::CBXPri:
403 case AArch64::CBBAssertExt:
404 case AArch64::CBHAssertExt:
405 case AArch64::CBWPrr:
406 case AArch64::CBXPrr:
407 return CBDisplacementBits;
408 }
409}
410
412 int64_t BrOffset) const {
413 unsigned Bits = getBranchDisplacementBits(BranchOp);
414 assert(Bits >= 3 && "max branch displacement must be enough to jump"
415 "over conditional branch expansion");
416 return isIntN(Bits, BrOffset / 4);
417}
418
421 switch (MI.getOpcode()) {
422 default:
423 llvm_unreachable("unexpected opcode!");
424 case AArch64::B:
425 return MI.getOperand(0).getMBB();
426 case AArch64::TBZW:
427 case AArch64::TBNZW:
428 case AArch64::TBZX:
429 case AArch64::TBNZX:
430 return MI.getOperand(2).getMBB();
431 case AArch64::CBZW:
432 case AArch64::CBNZW:
433 case AArch64::CBZX:
434 case AArch64::CBNZX:
435 case AArch64::Bcc:
436 return MI.getOperand(1).getMBB();
437 case AArch64::CBWPri:
438 case AArch64::CBXPri:
439 case AArch64::CBBAssertExt:
440 case AArch64::CBHAssertExt:
441 case AArch64::CBWPrr:
442 case AArch64::CBXPrr:
443 return MI.getOperand(3).getMBB();
444 }
445}
446
448 MachineBasicBlock &NewDestBB,
449 MachineBasicBlock &RestoreBB,
450 const DebugLoc &DL,
451 int64_t BrOffset,
452 RegScavenger *RS) const {
453 assert(RS && "RegScavenger required for long branching");
454 assert(MBB.empty() &&
455 "new block should be inserted for expanding unconditional branch");
456 assert(MBB.pred_size() == 1);
457 assert(RestoreBB.empty() &&
458 "restore block should be inserted for restoring clobbered registers");
459
460 auto buildIndirectBranch = [&](Register Reg, MachineBasicBlock &DestBB) {
461 // Offsets outside of the signed 33-bit range are not supported for ADRP +
462 // ADD.
463 if (!isInt<33>(BrOffset))
465 "Branch offsets outside of the signed 33-bit range not supported");
466
467 BuildMI(MBB, MBB.end(), DL, get(AArch64::ADRP), Reg)
468 .addSym(DestBB.getSymbol(), AArch64II::MO_PAGE);
469 BuildMI(MBB, MBB.end(), DL, get(AArch64::ADDXri), Reg)
470 .addReg(Reg)
471 .addSym(DestBB.getSymbol(), AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
472 .addImm(0);
473 BuildMI(MBB, MBB.end(), DL, get(AArch64::BR)).addReg(Reg);
474 };
475
476 RS->enterBasicBlockEnd(MBB);
477 // If X16 is unused, we can rely on the linker to insert a range extension
478 // thunk if NewDestBB is out of range of a single B instruction.
479 constexpr Register Reg = AArch64::X16;
480 if (!RS->isRegUsed(Reg)) {
481 insertUnconditionalBranch(MBB, &NewDestBB, DL);
482 RS->setRegUsed(Reg);
483 return;
484 }
485
486 // In a cold block without BTI, insert the indirect branch if a register is
487 // free. Skip this if BTI is enabled to avoid inserting a BTI at the target,
488 // prioritizing a dynamic cost in cold code over a static cost in hot code.
489 AArch64FunctionInfo *AFI = MBB.getParent()->getInfo<AArch64FunctionInfo>();
490 bool HasBTI = AFI && AFI->branchTargetEnforcement();
491 if (MBB.getSectionID() == MBBSectionID::ColdSectionID && !HasBTI) {
492 Register Scavenged = RS->FindUnusedReg(&AArch64::GPR64RegClass);
493 if (Scavenged != AArch64::NoRegister) {
494 buildIndirectBranch(Scavenged, NewDestBB);
495 RS->setRegUsed(Scavenged);
496 return;
497 }
498 }
499
500 // Note: Spilling X16 briefly moves the stack pointer, making it incompatible
501 // with red zones.
502 if (!AFI || AFI->hasRedZone().value_or(true))
504 "Unable to insert indirect branch inside function that has red zone");
505
506 // Otherwise, spill X16 and defer range extension to the linker.
507 BuildMI(MBB, MBB.end(), DL, get(AArch64::STRXpre))
508 .addReg(AArch64::SP, RegState::Define)
509 .addReg(Reg)
510 .addReg(AArch64::SP)
511 .addImm(-16);
512
513 BuildMI(MBB, MBB.end(), DL, get(AArch64::B)).addMBB(&RestoreBB);
514
515 BuildMI(RestoreBB, RestoreBB.end(), DL, get(AArch64::LDRXpost))
516 .addReg(AArch64::SP, RegState::Define)
518 .addReg(AArch64::SP)
519 .addImm(16);
520}
521
522// Branch analysis.
525 MachineBasicBlock *&FBB,
527 bool AllowModify) const {
528 // If the block has no terminators, it just falls into the block after it.
529 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
530 if (I == MBB.end())
531 return false;
532
533 // Skip over SpeculationBarrierEndBB terminators
534 if (I->getOpcode() == AArch64::SpeculationBarrierISBDSBEndBB ||
535 I->getOpcode() == AArch64::SpeculationBarrierSBEndBB) {
536 --I;
537 }
538
539 if (!isUnpredicatedTerminator(*I))
540 return false;
541
542 // Get the last instruction in the block.
543 MachineInstr *LastInst = &*I;
544
545 // If there is only one terminator instruction, process it.
546 unsigned LastOpc = LastInst->getOpcode();
547 if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
548 if (isUncondBranchOpcode(LastOpc)) {
549 TBB = LastInst->getOperand(0).getMBB();
550 return false;
551 }
552 if (isCondBranchOpcode(LastOpc)) {
553 // Block ends with fall-through condbranch.
554 parseCondBranch(LastInst, TBB, Cond);
555 return false;
556 }
557 return true; // Can't handle indirect branch.
558 }
559
560 // Get the instruction before it if it is a terminator.
561 MachineInstr *SecondLastInst = &*I;
562 unsigned SecondLastOpc = SecondLastInst->getOpcode();
563
564 // If AllowModify is true and the block ends with two or more unconditional
565 // branches, delete all but the first unconditional branch.
566 if (AllowModify && isUncondBranchOpcode(LastOpc)) {
567 while (isUncondBranchOpcode(SecondLastOpc)) {
568 LastInst->eraseFromParent();
569 LastInst = SecondLastInst;
570 LastOpc = LastInst->getOpcode();
571 if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
572 // Return now the only terminator is an unconditional branch.
573 TBB = LastInst->getOperand(0).getMBB();
574 return false;
575 }
576 SecondLastInst = &*I;
577 SecondLastOpc = SecondLastInst->getOpcode();
578 }
579 }
580
581 // If we're allowed to modify and the block ends in a unconditional branch
582 // which could simply fallthrough, remove the branch. (Note: This case only
583 // matters when we can't understand the whole sequence, otherwise it's also
584 // handled by BranchFolding.cpp.)
585 if (AllowModify && isUncondBranchOpcode(LastOpc) &&
586 MBB.isLayoutSuccessor(getBranchDestBlock(*LastInst))) {
587 LastInst->eraseFromParent();
588 LastInst = SecondLastInst;
589 LastOpc = LastInst->getOpcode();
590 if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
591 assert(!isUncondBranchOpcode(LastOpc) &&
592 "unreachable unconditional branches removed above");
593
594 if (isCondBranchOpcode(LastOpc)) {
595 // Block ends with fall-through condbranch.
596 parseCondBranch(LastInst, TBB, Cond);
597 return false;
598 }
599 return true; // Can't handle indirect branch.
600 }
601 SecondLastInst = &*I;
602 SecondLastOpc = SecondLastInst->getOpcode();
603 }
604
605 // If there are three terminators, we don't know what sort of block this is.
606 if (SecondLastInst && I != MBB.begin() && isUnpredicatedTerminator(*--I))
607 return true;
608
609 // If the block ends with a B and a Bcc, handle it.
610 if (isCondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
611 parseCondBranch(SecondLastInst, TBB, Cond);
612 FBB = LastInst->getOperand(0).getMBB();
613 return false;
614 }
615
616 // If the block ends with two unconditional branches, handle it. The second
617 // one is not executed, so remove it.
618 if (isUncondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
619 TBB = SecondLastInst->getOperand(0).getMBB();
620 I = LastInst;
621 if (AllowModify)
622 I->eraseFromParent();
623 return false;
624 }
625
626 // ...likewise if it ends with an indirect branch followed by an unconditional
627 // branch.
628 if (isIndirectBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
629 I = LastInst;
630 if (AllowModify)
631 I->eraseFromParent();
632 return true;
633 }
634
635 // Otherwise, can't handle this.
636 return true;
637}
638
640 MachineBranchPredicate &MBP,
641 bool AllowModify) const {
642 // Use analyzeBranch to validate the branch pattern.
643 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
645 if (analyzeBranch(MBB, TBB, FBB, Cond, AllowModify))
646 return true;
647
648 // analyzeBranch returns success with empty Cond for unconditional branches.
649 if (Cond.empty())
650 return true;
651
652 MBP.TrueDest = TBB;
653 assert(MBP.TrueDest && "expected!");
654 MBP.FalseDest = FBB ? FBB : MBB.getNextNode();
655
656 MBP.ConditionDef = nullptr;
657 MBP.SingleUseCondition = false;
658
659 // Find the conditional branch. After analyzeBranch succeeds with non-empty
660 // Cond, there's exactly one conditional branch - either last (fallthrough)
661 // or second-to-last (followed by unconditional B).
662 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
663 if (I == MBB.end())
664 return true;
665
666 if (isUncondBranchOpcode(I->getOpcode())) {
667 if (I == MBB.begin())
668 return true;
669 --I;
670 }
671
672 MachineInstr *CondBranch = &*I;
673 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
674
675 switch (CondBranch->getOpcode()) {
676 default:
677 return true;
678
679 case AArch64::Bcc:
680 // Bcc takes the NZCV flag as the operand to branch on, walk up the
681 // instruction stream to find the last instruction to define NZCV.
683 if (MI.modifiesRegister(AArch64::NZCV, /*TRI=*/nullptr)) {
684 MBP.ConditionDef = &MI;
685 break;
686 }
687 }
688 return false;
689
690 case AArch64::CBZW:
691 case AArch64::CBZX:
692 case AArch64::CBNZW:
693 case AArch64::CBNZX: {
694 MBP.LHS = CondBranch->getOperand(0);
695 MBP.RHS = MachineOperand::CreateImm(0);
696 unsigned Opc = CondBranch->getOpcode();
697 MBP.Predicate = (Opc == AArch64::CBNZX || Opc == AArch64::CBNZW)
698 ? MachineBranchPredicate::PRED_NE
699 : MachineBranchPredicate::PRED_EQ;
700 Register CondReg = MBP.LHS.getReg();
701 if (CondReg.isVirtual())
702 MBP.ConditionDef = MRI.getVRegDef(CondReg);
703 return false;
704 }
705
706 case AArch64::TBZW:
707 case AArch64::TBZX:
708 case AArch64::TBNZW:
709 case AArch64::TBNZX: {
710 Register CondReg = CondBranch->getOperand(0).getReg();
711 if (CondReg.isVirtual())
712 MBP.ConditionDef = MRI.getVRegDef(CondReg);
713 return false;
714 }
715 }
716}
717
720 if (Cond[0].getImm() != -1) {
721 // Regular Bcc
722 AArch64CC::CondCode CC = (AArch64CC::CondCode)(int)Cond[0].getImm();
724 } else {
725 // Folded compare-and-branch
726 switch (Cond[1].getImm()) {
727 default:
728 llvm_unreachable("Unknown conditional branch!");
729 case AArch64::CBZW:
730 Cond[1].setImm(AArch64::CBNZW);
731 break;
732 case AArch64::CBNZW:
733 Cond[1].setImm(AArch64::CBZW);
734 break;
735 case AArch64::CBZX:
736 Cond[1].setImm(AArch64::CBNZX);
737 break;
738 case AArch64::CBNZX:
739 Cond[1].setImm(AArch64::CBZX);
740 break;
741 case AArch64::TBZW:
742 Cond[1].setImm(AArch64::TBNZW);
743 break;
744 case AArch64::TBNZW:
745 Cond[1].setImm(AArch64::TBZW);
746 break;
747 case AArch64::TBZX:
748 Cond[1].setImm(AArch64::TBNZX);
749 break;
750 case AArch64::TBNZX:
751 Cond[1].setImm(AArch64::TBZX);
752 break;
753
754 // Cond is { -1, Opcode, CC, Op0, Op1, ... }
755 case AArch64::CBWPri:
756 case AArch64::CBXPri:
757 case AArch64::CBBAssertExt:
758 case AArch64::CBHAssertExt:
759 case AArch64::CBWPrr:
760 case AArch64::CBXPrr: {
761 // Pseudos using standard 4bit Arm condition codes
763 static_cast<AArch64CC::CondCode>(Cond[2].getImm());
765 }
766 }
767 }
768
769 return false;
770}
771
773 int *BytesRemoved) const {
774 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
775 if (I == MBB.end())
776 return 0;
777
778 if (!isUncondBranchOpcode(I->getOpcode()) &&
779 !isCondBranchOpcode(I->getOpcode()))
780 return 0;
781
782 // Remove the branch.
783 I->eraseFromParent();
784
785 I = MBB.end();
786
787 if (I == MBB.begin()) {
788 if (BytesRemoved)
789 *BytesRemoved = 4;
790 return 1;
791 }
792 --I;
793 if (!isCondBranchOpcode(I->getOpcode())) {
794 if (BytesRemoved)
795 *BytesRemoved = 4;
796 return 1;
797 }
798
799 // Remove the branch.
800 I->eraseFromParent();
801 if (BytesRemoved)
802 *BytesRemoved = 8;
803
804 return 2;
805}
806
807void AArch64InstrInfo::instantiateCondBranch(
810 if (Cond[0].getImm() != -1) {
811 // Regular Bcc
812 BuildMI(&MBB, DL, get(AArch64::Bcc)).addImm(Cond[0].getImm()).addMBB(TBB);
813 } else {
814 // Folded compare-and-branch
815 // Note that we use addOperand instead of addReg to keep the flags.
816
817 // cbz, cbnz
818 const MachineInstrBuilder MIB =
819 BuildMI(&MBB, DL, get(Cond[1].getImm())).add(Cond[2]);
820
821 // tbz/tbnz
822 if (Cond.size() > 3)
823 MIB.add(Cond[3]);
824
825 // cb
826 if (Cond.size() > 4)
827 MIB.add(Cond[4]);
828
829 MIB.addMBB(TBB);
830
831 // cb[b,h]
832 if (Cond.size() > 5) {
833 MIB.addImm(Cond[5].getImm());
834 MIB.addImm(Cond[6].getImm());
835 }
836 }
837}
838
841 ArrayRef<MachineOperand> Cond, const DebugLoc &DL, int *BytesAdded) const {
842 // Shouldn't be a fall through.
843 assert(TBB && "insertBranch must not be told to insert a fallthrough");
844
845 if (!FBB) {
846 if (Cond.empty()) // Unconditional branch?
847 BuildMI(&MBB, DL, get(AArch64::B)).addMBB(TBB);
848 else
849 instantiateCondBranch(MBB, DL, TBB, Cond);
850
851 if (BytesAdded)
852 *BytesAdded = 4;
853
854 return 1;
855 }
856
857 // Two-way conditional branch.
858 instantiateCondBranch(MBB, DL, TBB, Cond);
859 BuildMI(&MBB, DL, get(AArch64::B)).addMBB(FBB);
860
861 if (BytesAdded)
862 *BytesAdded = 8;
863
864 return 2;
865}
866
870 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
871
872 // Parse the condition code, see parseCondBranch() above.
874 switch (Cond.size()) {
875 default:
876 llvm_unreachable("Unknown condition opcode in Cond");
877 case 1: // b.cc
879 break;
880 case 3: { // cbz/cbnz
881 // We must insert a compare against 0.
882 bool Is64Bit;
883 switch (Cond[1].getImm()) {
884 default:
885 llvm_unreachable("Unknown branch opcode in Cond");
886 case AArch64::CBZW:
887 Is64Bit = false;
888 CC = AArch64CC::EQ;
889 break;
890 case AArch64::CBZX:
891 Is64Bit = true;
892 CC = AArch64CC::EQ;
893 break;
894 case AArch64::CBNZW:
895 Is64Bit = false;
896 CC = AArch64CC::NE;
897 break;
898 case AArch64::CBNZX:
899 Is64Bit = true;
900 CC = AArch64CC::NE;
901 break;
902 }
903 Register SrcReg = Cond[2].getReg();
904 if (Is64Bit) {
905 // cmp reg, #0 is actually subs xzr, reg, #0.
906 MRI.constrainRegClass(SrcReg, &AArch64::GPR64spRegClass);
907 BuildMI(MBB, MI, DL, get(AArch64::SUBSXri), AArch64::XZR)
908 .addReg(SrcReg)
909 .addImm(0)
910 .addImm(0);
911 } else {
912 MRI.constrainRegClass(SrcReg, &AArch64::GPR32spRegClass);
913 BuildMI(MBB, MI, DL, get(AArch64::SUBSWri), AArch64::WZR)
914 .addReg(SrcReg)
915 .addImm(0)
916 .addImm(0);
917 }
918 } break;
919 case 4: { // tbz/tbnz
920 // We must insert a tst instruction.
921 switch (Cond[1].getImm()) {
922 default:
923 llvm_unreachable("Unknown branch opcode in Cond");
924 case AArch64::TBZW:
925 case AArch64::TBZX:
926 CC = AArch64CC::EQ;
927 break;
928 case AArch64::TBNZW:
929 case AArch64::TBNZX:
930 CC = AArch64CC::NE;
931 break;
932 }
933 // cmp reg, #foo is actually ands xzr, reg, #1<<foo.
934 if (Cond[1].getImm() == AArch64::TBZW || Cond[1].getImm() == AArch64::TBNZW)
935 BuildMI(MBB, MI, DL, get(AArch64::ANDSWri), AArch64::WZR)
936 .addReg(Cond[2].getReg())
937 .addImm(
939 else
940 BuildMI(MBB, MI, DL, get(AArch64::ANDSXri), AArch64::XZR)
941 .addReg(Cond[2].getReg())
942 .addImm(
944 } break;
945 case 5: { // cb
946 // We must insert a cmp, that is a subs
947 // 0 1 2 3 4
948 // Cond is { -1, Opcode, CC, Op0, Op1 }
949 unsigned SubsOpc, SubsDestReg;
950 bool IsImm = false;
951 CC = static_cast<AArch64CC::CondCode>(Cond[2].getImm());
952 switch (Cond[1].getImm()) {
953 default:
954 llvm_unreachable("Unknown branch opcode in Cond");
955 case AArch64::CBWPri:
956 SubsOpc = AArch64::SUBSWri;
957 SubsDestReg = AArch64::WZR;
958 IsImm = true;
959 break;
960 case AArch64::CBXPri:
961 SubsOpc = AArch64::SUBSXri;
962 SubsDestReg = AArch64::XZR;
963 IsImm = true;
964 break;
965 case AArch64::CBWPrr:
966 SubsOpc = AArch64::SUBSWrr;
967 SubsDestReg = AArch64::WZR;
968 IsImm = false;
969 break;
970 case AArch64::CBXPrr:
971 SubsOpc = AArch64::SUBSXrr;
972 SubsDestReg = AArch64::XZR;
973 IsImm = false;
974 break;
975 }
976
977 if (IsImm) {
978 MRI.constrainRegClass(Cond[3].getReg(), getRegClass(get(SubsOpc), 1));
979 BuildMI(MBB, MI, DL, get(SubsOpc), SubsDestReg)
980 .addReg(Cond[3].getReg())
981 .addImm(Cond[4].getImm())
982 .addImm(0);
983 } else {
984 MRI.constrainRegClass(Cond[3].getReg(), getRegClass(get(SubsOpc), 1));
985 MRI.constrainRegClass(Cond[4].getReg(), getRegClass(get(SubsOpc), 2));
986 BuildMI(MBB, MI, DL, get(SubsOpc), SubsDestReg)
987 .addReg(Cond[3].getReg())
988 .addReg(Cond[4].getReg());
989 }
990 } break;
991 case 7: { // cb[b,h]
992 // We must insert a cmp, that is a subs, but also zero- or sign-extensions
993 // that have been folded. For the first operand we codegen an explicit
994 // extension, for the second operand we fold the extension into cmp.
995 // 0 1 2 3 4 5 6
996 // Cond is { -1, Opcode, CC, Op0, Op1, Ext0, Ext1 }
997
998 // We need a new register for the now explicitly extended register
999 Register Reg = Cond[4].getReg();
1001 unsigned ExtOpc;
1002 unsigned ExtBits;
1003 AArch64_AM::ShiftExtendType ExtendType =
1005 switch (ExtendType) {
1006 default:
1007 llvm_unreachable("Unknown shift-extend for CB instruction");
1008 case AArch64_AM::SXTB:
1009 assert(
1010 Cond[1].getImm() == AArch64::CBBAssertExt &&
1011 "Unexpected compare-and-branch instruction for SXTB shift-extend");
1012 ExtOpc = AArch64::SBFMWri;
1013 ExtBits = AArch64_AM::encodeLogicalImmediate(0xff, 32);
1014 break;
1015 case AArch64_AM::SXTH:
1016 assert(
1017 Cond[1].getImm() == AArch64::CBHAssertExt &&
1018 "Unexpected compare-and-branch instruction for SXTH shift-extend");
1019 ExtOpc = AArch64::SBFMWri;
1020 ExtBits = AArch64_AM::encodeLogicalImmediate(0xffff, 32);
1021 break;
1022 case AArch64_AM::UXTB:
1023 assert(
1024 Cond[1].getImm() == AArch64::CBBAssertExt &&
1025 "Unexpected compare-and-branch instruction for UXTB shift-extend");
1026 ExtOpc = AArch64::ANDWri;
1027 ExtBits = AArch64_AM::encodeLogicalImmediate(0xff, 32);
1028 break;
1029 case AArch64_AM::UXTH:
1030 assert(
1031 Cond[1].getImm() == AArch64::CBHAssertExt &&
1032 "Unexpected compare-and-branch instruction for UXTH shift-extend");
1033 ExtOpc = AArch64::ANDWri;
1034 ExtBits = AArch64_AM::encodeLogicalImmediate(0xffff, 32);
1035 break;
1036 }
1037
1038 // Build the explicit extension of the first operand
1039 Reg = MRI.createVirtualRegister(&AArch64::GPR32spRegClass);
1041 BuildMI(MBB, MI, DL, get(ExtOpc), Reg).addReg(Cond[4].getReg());
1042 if (ExtOpc != AArch64::ANDWri)
1043 MBBI.addImm(0);
1044 MBBI.addImm(ExtBits);
1045 }
1046
1047 // Now, subs with an extended second operand
1049 AArch64_AM::ShiftExtendType ExtendType =
1051 MRI.constrainRegClass(Reg, MRI.getRegClass(Cond[3].getReg()));
1052 MRI.constrainRegClass(Cond[3].getReg(), &AArch64::GPR32spRegClass);
1053 BuildMI(MBB, MI, DL, get(AArch64::SUBSWrx), AArch64::WZR)
1054 .addReg(Cond[3].getReg())
1055 .addReg(Reg)
1056 .addImm(AArch64_AM::getArithExtendImm(ExtendType, 0));
1057 } // If no extension is needed, just a regular subs
1058 else {
1059 MRI.constrainRegClass(Reg, MRI.getRegClass(Cond[3].getReg()));
1060 MRI.constrainRegClass(Cond[3].getReg(), &AArch64::GPR32spRegClass);
1061 BuildMI(MBB, MI, DL, get(AArch64::SUBSWrr), AArch64::WZR)
1062 .addReg(Cond[3].getReg())
1063 .addReg(Reg);
1064 }
1065
1066 CC = static_cast<AArch64CC::CondCode>(Cond[2].getImm());
1067 } break;
1068 }
1069 return CC;
1070}
1071
1073 const TargetInstrInfo &TII) {
1074 for (MachineInstr &MI : MBB->terminators()) {
1075 unsigned Opc = MI.getOpcode();
1076 switch (Opc) {
1077 case AArch64::CBZW:
1078 case AArch64::CBZX:
1079 case AArch64::TBZW:
1080 case AArch64::TBZX:
1081 // CBZ/TBZ with WZR/XZR -> unconditional B
1082 if (MI.getOperand(0).getReg() == AArch64::WZR ||
1083 MI.getOperand(0).getReg() == AArch64::XZR) {
1084 DEBUG_WITH_TYPE("optimizeTerminators",
1085 dbgs() << "Removing always taken branch: " << MI);
1086 MachineBasicBlock *Target = TII.getBranchDestBlock(MI);
1087 SmallVector<MachineBasicBlock *> Succs(MBB->successors());
1088 for (auto *S : Succs)
1089 if (S != Target)
1090 MBB->removeSuccessor(S);
1091 DebugLoc DL = MI.getDebugLoc();
1092 while (MBB->rbegin() != &MI)
1093 MBB->rbegin()->eraseFromParent();
1094 MI.eraseFromParent();
1095 BuildMI(MBB, DL, TII.get(AArch64::B)).addMBB(Target);
1096 return true;
1097 }
1098 break;
1099 case AArch64::CBNZW:
1100 case AArch64::CBNZX:
1101 case AArch64::TBNZW:
1102 case AArch64::TBNZX:
1103 // CBNZ/TBNZ with WZR/XZR -> never taken, remove branch and successor
1104 if (MI.getOperand(0).getReg() == AArch64::WZR ||
1105 MI.getOperand(0).getReg() == AArch64::XZR) {
1106 DEBUG_WITH_TYPE("optimizeTerminators",
1107 dbgs() << "Removing never taken branch: " << MI);
1108 MachineBasicBlock *Target = TII.getBranchDestBlock(MI);
1109 MI.getParent()->removeSuccessor(Target);
1110 MI.eraseFromParent();
1111 return true;
1112 }
1113 break;
1114 }
1115 }
1116 return false;
1117}
1118
1119// Find the original register that VReg is copied from.
1120static unsigned removeCopies(const MachineRegisterInfo &MRI, unsigned VReg) {
1121 while (Register::isVirtualRegister(VReg)) {
1122 const MachineInstr *DefMI = MRI.getVRegDef(VReg);
1123 if (!DefMI || !DefMI->isFullCopy())
1124 return VReg;
1125 VReg = DefMI->getOperand(1).getReg();
1126 }
1127 return VReg;
1128}
1129
1130// Determine if VReg is defined by an instruction that can be folded into a
1131// csel instruction. If so, return the folded opcode, and the replacement
1132// register.
1133static unsigned canFoldIntoCSel(const MachineRegisterInfo &MRI, unsigned VReg,
1134 unsigned *NewReg = nullptr) {
1135 VReg = removeCopies(MRI, VReg);
1136 if (!Register::isVirtualRegister(VReg))
1137 return 0;
1138
1139 bool Is64Bit = AArch64::GPR64allRegClass.hasSubClassEq(MRI.getRegClass(VReg));
1140 const MachineInstr *DefMI = MRI.getVRegDef(VReg);
1141 if (!DefMI)
1142 return 0;
1143 unsigned Opc = 0;
1144 unsigned SrcReg = 0;
1145 switch (DefMI->getOpcode()) {
1146 case AArch64::SUBREG_TO_REG:
1147 // Check for the following way to define an 64-bit immediate:
1148 // %0:gpr32 = MOVi32imm 1
1149 // %1:gpr64 = SUBREG_TO_REG %0:gpr32, %subreg.sub_32
1150 if (!DefMI->getOperand(1).isReg())
1151 return 0;
1152 if (!DefMI->getOperand(2).isImm() ||
1153 DefMI->getOperand(2).getImm() != AArch64::sub_32)
1154 return 0;
1155 DefMI = MRI.getVRegDef(DefMI->getOperand(1).getReg());
1156 if (DefMI->getOpcode() != AArch64::MOVi32imm)
1157 return 0;
1158 if (!DefMI->getOperand(1).isImm() || DefMI->getOperand(1).getImm() != 1)
1159 return 0;
1160 assert(Is64Bit);
1161 SrcReg = AArch64::XZR;
1162 Opc = AArch64::CSINCXr;
1163 break;
1164
1165 case AArch64::MOVi32imm:
1166 case AArch64::MOVi64imm:
1167 if (!DefMI->getOperand(1).isImm() || DefMI->getOperand(1).getImm() != 1)
1168 return 0;
1169 SrcReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1170 Opc = Is64Bit ? AArch64::CSINCXr : AArch64::CSINCWr;
1171 break;
1172
1173 case AArch64::ADDSXri:
1174 case AArch64::ADDSWri:
1175 // if NZCV is used, do not fold.
1176 if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr,
1177 true) == -1)
1178 return 0;
1179 // fall-through to ADDXri and ADDWri.
1180 [[fallthrough]];
1181 case AArch64::ADDXri:
1182 case AArch64::ADDWri:
1183 // add x, 1 -> csinc.
1184 if (!DefMI->getOperand(2).isImm() || DefMI->getOperand(2).getImm() != 1 ||
1185 DefMI->getOperand(3).getImm() != 0)
1186 return 0;
1187 SrcReg = DefMI->getOperand(1).getReg();
1188 Opc = Is64Bit ? AArch64::CSINCXr : AArch64::CSINCWr;
1189 break;
1190
1191 case AArch64::ORNXrr:
1192 case AArch64::ORNWrr: {
1193 // not x -> csinv, represented as orn dst, xzr, src.
1194 unsigned ZReg = removeCopies(MRI, DefMI->getOperand(1).getReg());
1195 if (ZReg != AArch64::XZR && ZReg != AArch64::WZR)
1196 return 0;
1197 SrcReg = DefMI->getOperand(2).getReg();
1198 Opc = Is64Bit ? AArch64::CSINVXr : AArch64::CSINVWr;
1199 break;
1200 }
1201
1202 case AArch64::SUBSXrr:
1203 case AArch64::SUBSWrr:
1204 // if NZCV is used, do not fold.
1205 if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr,
1206 true) == -1)
1207 return 0;
1208 // fall-through to SUBXrr and SUBWrr.
1209 [[fallthrough]];
1210 case AArch64::SUBXrr:
1211 case AArch64::SUBWrr: {
1212 // neg x -> csneg, represented as sub dst, xzr, src.
1213 unsigned ZReg = removeCopies(MRI, DefMI->getOperand(1).getReg());
1214 if (ZReg != AArch64::XZR && ZReg != AArch64::WZR)
1215 return 0;
1216 SrcReg = DefMI->getOperand(2).getReg();
1217 Opc = Is64Bit ? AArch64::CSNEGXr : AArch64::CSNEGWr;
1218 break;
1219 }
1220 default:
1221 return 0;
1222 }
1223 assert(Opc && SrcReg && "Missing parameters");
1224
1225 if (NewReg)
1226 *NewReg = SrcReg;
1227 return Opc;
1228}
1229
1232 Register DstReg, Register TrueReg,
1233 Register FalseReg, int &CondCycles,
1234 int &TrueCycles,
1235 int &FalseCycles) const {
1236 // Check register classes.
1237 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1238 const TargetRegisterClass *RC =
1239 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
1240 if (!RC)
1241 return false;
1242
1243 // Also need to check the dest regclass, in case we're trying to optimize
1244 // something like:
1245 // %1(gpr) = PHI %2(fpr), bb1, %(fpr), bb2
1246 if (!RI.getCommonSubClass(RC, MRI.getRegClass(DstReg)))
1247 return false;
1248
1249 // Expanding cbz/tbz requires an extra cycle of latency on the condition.
1250 unsigned ExtraCondLat = Cond.size() != 1;
1251
1252 // GPRs are handled by csel.
1253 // FIXME: Fold in x+1, -x, and ~x when applicable.
1254 if (AArch64::GPR64allRegClass.hasSubClassEq(RC) ||
1255 AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
1256 // Single-cycle csel, csinc, csinv, and csneg.
1257 CondCycles = 1 + ExtraCondLat;
1258 TrueCycles = FalseCycles = 1;
1259 if (canFoldIntoCSel(MRI, TrueReg))
1260 TrueCycles = 0;
1261 else if (canFoldIntoCSel(MRI, FalseReg))
1262 FalseCycles = 0;
1263 return true;
1264 }
1265
1266 // Scalar floating point is handled by fcsel.
1267 // FIXME: Form fabs, fmin, and fmax when applicable.
1268 if (AArch64::FPR64RegClass.hasSubClassEq(RC) ||
1269 AArch64::FPR32RegClass.hasSubClassEq(RC)) {
1270 CondCycles = 5 + ExtraCondLat;
1271 TrueCycles = FalseCycles = 2;
1272 return true;
1273 }
1274
1275 // Can't do vectors.
1276 return false;
1277}
1278
1281 const DebugLoc &DL, Register DstReg,
1283 Register TrueReg, Register FalseReg) const {
1284
1285 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1287
1288 unsigned Opc = 0;
1289 const TargetRegisterClass *RC = nullptr;
1290 bool TryFold = false;
1291 if (MRI.constrainRegClass(DstReg, &AArch64::GPR64RegClass)) {
1292 RC = &AArch64::GPR64RegClass;
1293 Opc = AArch64::CSELXr;
1294 TryFold = true;
1295 } else if (MRI.constrainRegClass(DstReg, &AArch64::GPR32RegClass)) {
1296 RC = &AArch64::GPR32RegClass;
1297 Opc = AArch64::CSELWr;
1298 TryFold = true;
1299 } else if (MRI.constrainRegClass(DstReg, &AArch64::FPR64RegClass)) {
1300 RC = &AArch64::FPR64RegClass;
1301 Opc = AArch64::FCSELDrrr;
1302 } else if (MRI.constrainRegClass(DstReg, &AArch64::FPR32RegClass)) {
1303 RC = &AArch64::FPR32RegClass;
1304 Opc = AArch64::FCSELSrrr;
1305 }
1306 assert(RC && "Unsupported regclass");
1307
1308 // Try folding simple instructions into the csel.
1309 if (TryFold) {
1310 unsigned NewReg = 0;
1311 unsigned FoldedOpc = canFoldIntoCSel(MRI, TrueReg, &NewReg);
1312 if (FoldedOpc) {
1313 // The folded opcodes csinc, csinc and csneg apply the operation to
1314 // FalseReg, so we need to invert the condition.
1316 TrueReg = FalseReg;
1317 } else
1318 FoldedOpc = canFoldIntoCSel(MRI, FalseReg, &NewReg);
1319
1320 // Fold the operation. Leave any dead instructions for DCE to clean up.
1321 if (FoldedOpc) {
1322 FalseReg = NewReg;
1323 Opc = FoldedOpc;
1324 // Extend the live range of NewReg.
1325 MRI.clearKillFlags(NewReg);
1326 }
1327 }
1328
1329 // Pull all virtual register into the appropriate class.
1330 MRI.constrainRegClass(TrueReg, RC);
1331 // FalseReg might be WZR or XZR if the folded operand is a literal 1.
1332 assert(
1333 (FalseReg.isVirtual() || FalseReg == AArch64::WZR ||
1334 FalseReg == AArch64::XZR) &&
1335 "FalseReg was folded into a non-virtual register other than WZR or XZR");
1336 if (FalseReg.isVirtual())
1337 MRI.constrainRegClass(FalseReg, RC);
1338
1339 // Insert the csel.
1340 BuildMI(MBB, I, DL, get(Opc), DstReg)
1341 .addReg(TrueReg)
1342 .addReg(FalseReg)
1343 .addImm(CC);
1344}
1345
1346// Return true if Imm can be loaded into a register by a "cheap" sequence of
1347// instructions. For now, "cheap" means at most two instructions.
1348static bool isCheapImmediate(const MachineInstr &MI, unsigned BitSize) {
1349 if (BitSize == 32)
1350 return true;
1351
1352 assert(BitSize == 64 && "Only bit sizes of 32 or 64 allowed");
1353 uint64_t Imm = static_cast<uint64_t>(MI.getOperand(1).getImm());
1355 AArch64_IMM::expandMOVImm(Imm, BitSize, Is);
1356
1357 return Is.size() <= 2;
1358}
1359
1360// Check if a COPY instruction is cheap.
1361static bool isCheapCopy(const MachineInstr &MI, const AArch64RegisterInfo &RI) {
1362 assert(MI.isCopy() && "Expected COPY instruction");
1363 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1364
1365 // Cross-bank copies (e.g., between GPR and FPR) are expensive on AArch64,
1366 // typically requiring an FMOV instruction with a 2-6 cycle latency.
1367 auto GetRegClass = [&](Register Reg) -> const TargetRegisterClass * {
1368 if (Reg.isVirtual())
1369 return MRI.getRegClass(Reg);
1370 if (Reg.isPhysical())
1371 return RI.getMinimalPhysRegClass(Reg);
1372 return nullptr;
1373 };
1374 const TargetRegisterClass *DstRC = GetRegClass(MI.getOperand(0).getReg());
1375 const TargetRegisterClass *SrcRC = GetRegClass(MI.getOperand(1).getReg());
1376 if (DstRC && SrcRC && !RI.getCommonSubClass(DstRC, SrcRC))
1377 return false;
1378
1379 return MI.isAsCheapAsAMove();
1380}
1381
1382// FIXME: this implementation should be micro-architecture dependent, so a
1383// micro-architecture target hook should be introduced here in future.
1385 if (Subtarget.hasExynosCheapAsMoveHandling()) {
1386 if (isExynosCheapAsMove(MI))
1387 return true;
1388 return MI.isAsCheapAsAMove();
1389 }
1390
1391 switch (MI.getOpcode()) {
1392 default:
1393 return MI.isAsCheapAsAMove();
1394
1395 case TargetOpcode::COPY:
1396 return isCheapCopy(MI, RI);
1397
1398 case AArch64::ADDWrs:
1399 case AArch64::ADDXrs:
1400 case AArch64::SUBWrs:
1401 case AArch64::SUBXrs:
1402 return Subtarget.hasALULSLFast() && MI.getOperand(3).getImm() <= 4;
1403
1404 // If MOVi32imm or MOVi64imm can be expanded into ORRWri or
1405 // ORRXri, it is as cheap as MOV.
1406 // Likewise if it can be expanded to MOVZ/MOVN/MOVK.
1407 case AArch64::MOVi32imm:
1408 return isCheapImmediate(MI, 32);
1409 case AArch64::MOVi64imm:
1410 return isCheapImmediate(MI, 64);
1411 }
1412}
1413
1414bool AArch64InstrInfo::isFalkorShiftExtFast(const MachineInstr &MI) {
1415 switch (MI.getOpcode()) {
1416 default:
1417 return false;
1418
1419 case AArch64::ADDWrs:
1420 case AArch64::ADDXrs:
1421 case AArch64::ADDSWrs:
1422 case AArch64::ADDSXrs: {
1423 unsigned Imm = MI.getOperand(3).getImm();
1424 unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
1425 if (ShiftVal == 0)
1426 return true;
1427 return AArch64_AM::getShiftType(Imm) == AArch64_AM::LSL && ShiftVal <= 5;
1428 }
1429
1430 case AArch64::ADDWrx:
1431 case AArch64::ADDXrx:
1432 case AArch64::ADDXrx64:
1433 case AArch64::ADDSWrx:
1434 case AArch64::ADDSXrx:
1435 case AArch64::ADDSXrx64: {
1436 unsigned Imm = MI.getOperand(3).getImm();
1438 default:
1439 return false;
1440 case AArch64_AM::UXTB:
1441 case AArch64_AM::UXTH:
1442 case AArch64_AM::UXTW:
1443 case AArch64_AM::UXTX:
1445 }
1446 }
1447
1448 case AArch64::SUBWrs:
1449 case AArch64::SUBSWrs: {
1450 unsigned Imm = MI.getOperand(3).getImm();
1451 unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
1452 return ShiftVal == 0 ||
1453 (AArch64_AM::getShiftType(Imm) == AArch64_AM::ASR && ShiftVal == 31);
1454 }
1455
1456 case AArch64::SUBXrs:
1457 case AArch64::SUBSXrs: {
1458 unsigned Imm = MI.getOperand(3).getImm();
1459 unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
1460 return ShiftVal == 0 ||
1461 (AArch64_AM::getShiftType(Imm) == AArch64_AM::ASR && ShiftVal == 63);
1462 }
1463
1464 case AArch64::SUBWrx:
1465 case AArch64::SUBXrx:
1466 case AArch64::SUBXrx64:
1467 case AArch64::SUBSWrx:
1468 case AArch64::SUBSXrx:
1469 case AArch64::SUBSXrx64: {
1470 unsigned Imm = MI.getOperand(3).getImm();
1472 default:
1473 return false;
1474 case AArch64_AM::UXTB:
1475 case AArch64_AM::UXTH:
1476 case AArch64_AM::UXTW:
1477 case AArch64_AM::UXTX:
1479 }
1480 }
1481
1482 case AArch64::LDRBBroW:
1483 case AArch64::LDRBBroX:
1484 case AArch64::LDRBroW:
1485 case AArch64::LDRBroX:
1486 case AArch64::LDRDroW:
1487 case AArch64::LDRDroX:
1488 case AArch64::LDRHHroW:
1489 case AArch64::LDRHHroX:
1490 case AArch64::LDRHroW:
1491 case AArch64::LDRHroX:
1492 case AArch64::LDRQroW:
1493 case AArch64::LDRQroX:
1494 case AArch64::LDRSBWroW:
1495 case AArch64::LDRSBWroX:
1496 case AArch64::LDRSBXroW:
1497 case AArch64::LDRSBXroX:
1498 case AArch64::LDRSHWroW:
1499 case AArch64::LDRSHWroX:
1500 case AArch64::LDRSHXroW:
1501 case AArch64::LDRSHXroX:
1502 case AArch64::LDRSWroW:
1503 case AArch64::LDRSWroX:
1504 case AArch64::LDRSroW:
1505 case AArch64::LDRSroX:
1506 case AArch64::LDRWroW:
1507 case AArch64::LDRWroX:
1508 case AArch64::LDRXroW:
1509 case AArch64::LDRXroX:
1510 case AArch64::PRFMroW:
1511 case AArch64::PRFMroX:
1512 case AArch64::STRBBroW:
1513 case AArch64::STRBBroX:
1514 case AArch64::STRBroW:
1515 case AArch64::STRBroX:
1516 case AArch64::STRDroW:
1517 case AArch64::STRDroX:
1518 case AArch64::STRHHroW:
1519 case AArch64::STRHHroX:
1520 case AArch64::STRHroW:
1521 case AArch64::STRHroX:
1522 case AArch64::STRQroW:
1523 case AArch64::STRQroX:
1524 case AArch64::STRSroW:
1525 case AArch64::STRSroX:
1526 case AArch64::STRWroW:
1527 case AArch64::STRWroX:
1528 case AArch64::STRXroW:
1529 case AArch64::STRXroX: {
1530 unsigned IsSigned = MI.getOperand(3).getImm();
1531 return !IsSigned;
1532 }
1533 }
1534}
1535
1536bool AArch64InstrInfo::isSEHInstruction(const MachineInstr &MI) {
1537 unsigned Opc = MI.getOpcode();
1538 switch (Opc) {
1539 default:
1540 return false;
1541 case AArch64::SEH_StackAlloc:
1542 case AArch64::SEH_SaveFPLR:
1543 case AArch64::SEH_SaveFPLR_X:
1544 case AArch64::SEH_SaveReg:
1545 case AArch64::SEH_SaveReg_X:
1546 case AArch64::SEH_SaveRegP:
1547 case AArch64::SEH_SaveRegP_X:
1548 case AArch64::SEH_SaveFReg:
1549 case AArch64::SEH_SaveFReg_X:
1550 case AArch64::SEH_SaveFRegP:
1551 case AArch64::SEH_SaveFRegP_X:
1552 case AArch64::SEH_SetFP:
1553 case AArch64::SEH_AddFP:
1554 case AArch64::SEH_Nop:
1555 case AArch64::SEH_PrologEnd:
1556 case AArch64::SEH_EpilogStart:
1557 case AArch64::SEH_EpilogEnd:
1558 case AArch64::SEH_PACSignLR:
1559 case AArch64::SEH_SaveAnyRegI:
1560 case AArch64::SEH_SaveAnyRegIP:
1561 case AArch64::SEH_SaveAnyRegQP:
1562 case AArch64::SEH_SaveAnyRegQPX:
1563 case AArch64::SEH_AllocZ:
1564 case AArch64::SEH_SaveZReg:
1565 case AArch64::SEH_SavePReg:
1566 return true;
1567 }
1568}
1569
1571 Register &SrcReg, Register &DstReg,
1572 unsigned &SubIdx) const {
1573 switch (MI.getOpcode()) {
1574 default:
1575 return false;
1576 case AArch64::SBFMXri: // aka sxtw
1577 case AArch64::UBFMXri: // aka uxtw
1578 // Check for the 32 -> 64 bit extension case, these instructions can do
1579 // much more.
1580 if (MI.getOperand(2).getImm() != 0 || MI.getOperand(3).getImm() != 31)
1581 return false;
1582 // This is a signed or unsigned 32 -> 64 bit extension.
1583 SrcReg = MI.getOperand(1).getReg();
1584 DstReg = MI.getOperand(0).getReg();
1585 SubIdx = AArch64::sub_32;
1586 return true;
1587 }
1588}
1589
1591 const MachineInstr &MIa, const MachineInstr &MIb) const {
1593 const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr;
1594 int64_t OffsetA = 0, OffsetB = 0;
1595 TypeSize WidthA(0, false), WidthB(0, false);
1596 bool OffsetAIsScalable = false, OffsetBIsScalable = false;
1597
1598 assert(MIa.mayLoadOrStore() && "MIa must be a load or store.");
1599 assert(MIb.mayLoadOrStore() && "MIb must be a load or store.");
1600
1603 return false;
1604
1605 // Retrieve the base, offset from the base and width. Width
1606 // is the size of memory that is being loaded/stored (e.g. 1, 2, 4, 8). If
1607 // base are identical, and the offset of a lower memory access +
1608 // the width doesn't overlap the offset of a higher memory access,
1609 // then the memory accesses are different.
1610 // If OffsetAIsScalable and OffsetBIsScalable are both true, they
1611 // are assumed to have the same scale (vscale).
1612 if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, OffsetAIsScalable,
1613 WidthA, TRI) &&
1614 getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, OffsetBIsScalable,
1615 WidthB, TRI)) {
1616 if (BaseOpA->isIdenticalTo(*BaseOpB) &&
1617 OffsetAIsScalable == OffsetBIsScalable) {
1618 int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
1619 int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
1620 TypeSize LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
1621 if (LowWidth.isScalable() == OffsetAIsScalable &&
1622 LowOffset + (int)LowWidth.getKnownMinValue() <= HighOffset)
1623 return true;
1624 }
1625 }
1626 return false;
1627}
1628
1630 const MachineBasicBlock *MBB,
1631 const MachineFunction &MF) const {
1633 return true;
1634
1635 // Do not move an instruction that can be recognized as a branch target.
1636 if (hasBTISemantics(MI))
1637 return true;
1638
1639 switch (MI.getOpcode()) {
1640 case AArch64::HINT:
1641 // CSDB hints are scheduling barriers.
1642 if (MI.getOperand(0).getImm() == 0x14)
1643 return true;
1644 break;
1645 case AArch64::DSB:
1646 case AArch64::ISB:
1647 // DSB and ISB also are scheduling barriers.
1648 return true;
1649 case AArch64::MSRpstatesvcrImm1:
1650 // SMSTART and SMSTOP are also scheduling barriers.
1651 return true;
1652 default:;
1653 }
1654 if (isSEHInstruction(MI))
1655 return true;
1656 auto Next = std::next(MI.getIterator());
1657 return Next != MBB->end() && Next->isCFIInstruction();
1658}
1659
1660/// analyzeCompare - For a comparison instruction, return the source registers
1661/// in SrcReg and SrcReg2, and the value it compares against in CmpValue.
1662/// Return true if the comparison instruction can be analyzed.
1664 Register &SrcReg2, int64_t &CmpMask,
1665 int64_t &CmpValue) const {
1666 // The first operand can be a frame index where we'd normally expect a
1667 // register.
1668 // FIXME: Pass subregisters out of analyzeCompare
1669 assert(MI.getNumOperands() >= 2 && "All AArch64 cmps should have 2 operands");
1670 if (!MI.getOperand(1).isReg() || MI.getOperand(1).getSubReg())
1671 return false;
1672
1673 switch (MI.getOpcode()) {
1674 default:
1675 break;
1676 case AArch64::PTEST_PP:
1677 case AArch64::PTEST_PP_ANY:
1678 case AArch64::PTEST_PP_FIRST:
1679 SrcReg = MI.getOperand(0).getReg();
1680 SrcReg2 = MI.getOperand(1).getReg();
1681 if (MI.getOperand(2).getSubReg())
1682 return false;
1683
1684 // Not sure about the mask and value for now...
1685 CmpMask = ~0;
1686 CmpValue = 0;
1687 return true;
1688 case AArch64::SUBSWrr:
1689 case AArch64::SUBSWrs:
1690 case AArch64::SUBSWrx:
1691 case AArch64::SUBSXrr:
1692 case AArch64::SUBSXrs:
1693 case AArch64::SUBSXrx:
1694 case AArch64::ADDSWrr:
1695 case AArch64::ADDSWrs:
1696 case AArch64::ADDSWrx:
1697 case AArch64::ADDSXrr:
1698 case AArch64::ADDSXrs:
1699 case AArch64::ADDSXrx:
1700 // Replace SUBSWrr with SUBWrr if NZCV is not used.
1701 SrcReg = MI.getOperand(1).getReg();
1702 SrcReg2 = MI.getOperand(2).getReg();
1703
1704 // FIXME: Pass subregisters out of analyzeCompare
1705 if (MI.getOperand(2).getSubReg())
1706 return false;
1707
1708 CmpMask = ~0;
1709 CmpValue = 0;
1710 return true;
1711 case AArch64::SUBSWri:
1712 case AArch64::ADDSWri:
1713 case AArch64::SUBSXri:
1714 case AArch64::ADDSXri:
1715 SrcReg = MI.getOperand(1).getReg();
1716 SrcReg2 = 0;
1717 CmpMask = ~0;
1718 CmpValue = MI.getOperand(2).getImm();
1719 return true;
1720 case AArch64::ANDSWri:
1721 case AArch64::ANDSXri:
1722 // ANDS does not use the same encoding scheme as the others xxxS
1723 // instructions.
1724 SrcReg = MI.getOperand(1).getReg();
1725 SrcReg2 = 0;
1726 CmpMask = ~0;
1728 MI.getOperand(2).getImm(),
1729 MI.getOpcode() == AArch64::ANDSWri ? 32 : 64);
1730 return true;
1731 }
1732
1733 return false;
1734}
1735
1737 MachineBasicBlock *MBB = Instr.getParent();
1738 assert(MBB && "Can't get MachineBasicBlock here");
1739 MachineFunction *MF = MBB->getParent();
1740 assert(MF && "Can't get MachineFunction here");
1743 MachineRegisterInfo *MRI = &MF->getRegInfo();
1744
1745 for (unsigned OpIdx = 0, EndIdx = Instr.getNumOperands(); OpIdx < EndIdx;
1746 ++OpIdx) {
1747 MachineOperand &MO = Instr.getOperand(OpIdx);
1748 const TargetRegisterClass *OpRegCstraints =
1749 Instr.getRegClassConstraint(OpIdx, TII, TRI);
1750
1751 // If there's no constraint, there's nothing to do.
1752 if (!OpRegCstraints)
1753 continue;
1754 // If the operand is a frame index, there's nothing to do here.
1755 // A frame index operand will resolve correctly during PEI.
1756 if (MO.isFI())
1757 continue;
1758
1759 assert(MO.isReg() &&
1760 "Operand has register constraints without being a register!");
1761
1762 Register Reg = MO.getReg();
1763 if (Reg.isPhysical()) {
1764 if (!OpRegCstraints->contains(Reg))
1765 return false;
1766 } else if (!OpRegCstraints->hasSubClassEq(MRI->getRegClass(Reg)) &&
1767 !MRI->constrainRegClass(Reg, OpRegCstraints))
1768 return false;
1769 }
1770
1771 return true;
1772}
1773
1774/// Return the opcode that does not set flags when possible - otherwise
1775/// return the original opcode. The caller is responsible to do the actual
1776/// substitution and legality checking.
1778 // Don't convert all compare instructions, because for some the zero register
1779 // encoding becomes the sp register.
1780 bool MIDefinesZeroReg = false;
1781 if (MI.definesRegister(AArch64::WZR, /*TRI=*/nullptr) ||
1782 MI.definesRegister(AArch64::XZR, /*TRI=*/nullptr))
1783 MIDefinesZeroReg = true;
1784
1785 switch (MI.getOpcode()) {
1786 default:
1787 return MI.getOpcode();
1788 case AArch64::ADDSWrr:
1789 return AArch64::ADDWrr;
1790 case AArch64::ADDSWri:
1791 return MIDefinesZeroReg ? AArch64::ADDSWri : AArch64::ADDWri;
1792 case AArch64::ADDSWrs:
1793 return MIDefinesZeroReg ? AArch64::ADDSWrs : AArch64::ADDWrs;
1794 case AArch64::ADDSWrx:
1795 return AArch64::ADDWrx;
1796 case AArch64::ADDSXrr:
1797 return AArch64::ADDXrr;
1798 case AArch64::ADDSXri:
1799 return MIDefinesZeroReg ? AArch64::ADDSXri : AArch64::ADDXri;
1800 case AArch64::ADDSXrs:
1801 return MIDefinesZeroReg ? AArch64::ADDSXrs : AArch64::ADDXrs;
1802 case AArch64::ADDSXrx:
1803 return AArch64::ADDXrx;
1804 case AArch64::SUBSWrr:
1805 return AArch64::SUBWrr;
1806 case AArch64::SUBSWri:
1807 return MIDefinesZeroReg ? AArch64::SUBSWri : AArch64::SUBWri;
1808 case AArch64::SUBSWrs:
1809 return MIDefinesZeroReg ? AArch64::SUBSWrs : AArch64::SUBWrs;
1810 case AArch64::SUBSWrx:
1811 return AArch64::SUBWrx;
1812 case AArch64::SUBSXrr:
1813 return AArch64::SUBXrr;
1814 case AArch64::SUBSXri:
1815 return MIDefinesZeroReg ? AArch64::SUBSXri : AArch64::SUBXri;
1816 case AArch64::SUBSXrs:
1817 return MIDefinesZeroReg ? AArch64::SUBSXrs : AArch64::SUBXrs;
1818 case AArch64::SUBSXrx:
1819 return AArch64::SUBXrx;
1820 }
1821}
1822
1823enum AccessKind { AK_Write = 0x01, AK_Read = 0x10, AK_All = 0x11 };
1824
1825/// True when condition flags are accessed (either by writing or reading)
1826/// on the instruction trace starting at From and ending at To.
1827///
1828/// Note: If From and To are from different blocks it's assumed CC are accessed
1829/// on the path.
1832 const TargetRegisterInfo *TRI, const AccessKind AccessToCheck = AK_All) {
1833 // Early exit if To is at the beginning of the BB.
1834 if (To == To->getParent()->begin())
1835 return true;
1836
1837 // Check whether the instructions are in the same basic block
1838 // If not, assume the condition flags might get modified somewhere.
1839 if (To->getParent() != From->getParent())
1840 return true;
1841
1842 // From must be above To.
1843 assert(std::any_of(
1844 ++To.getReverse(), To->getParent()->rend(),
1845 [From](MachineInstr &MI) { return MI.getIterator() == From; }));
1846
1847 // We iterate backward starting at \p To until we hit \p From.
1848 for (const MachineInstr &Instr :
1850 if (((AccessToCheck & AK_Write) &&
1851 Instr.modifiesRegister(AArch64::NZCV, TRI)) ||
1852 ((AccessToCheck & AK_Read) && Instr.readsRegister(AArch64::NZCV, TRI)))
1853 return true;
1854 }
1855 return false;
1856}
1857
1858std::optional<unsigned>
1859AArch64InstrInfo::canRemovePTestInstr(MachineInstr *PTest, MachineInstr *Mask,
1860 MachineInstr *Pred,
1861 const MachineRegisterInfo *MRI) const {
1862 unsigned MaskOpcode = Mask->getOpcode();
1863 unsigned PredOpcode = Pred->getOpcode();
1864 bool PredIsPTestLike = isPTestLikeOpcode(PredOpcode);
1865 bool PredIsWhileLike = isWhileOpcode(PredOpcode);
1866
1867 if (PredIsWhileLike) {
1868 // For PTEST(PG, PG), PTEST is redundant when PG is the result of a WHILEcc
1869 // instruction and the condition is "any" since WHILcc does an implicit
1870 // PTEST(ALL, PG) check and PG is always a subset of ALL.
1871 if ((Mask == Pred) && PTest->getOpcode() == AArch64::PTEST_PP_ANY)
1872 return PredOpcode;
1873
1874 // For PTEST(PTRUE_ALL, WHILE), if the element size matches, the PTEST is
1875 // redundant since WHILE performs an implicit PTEST with an all active
1876 // mask.
1877 if (isPTrueOpcode(MaskOpcode) && Mask->getOperand(1).getImm() == 31 &&
1878 getElementSizeForOpcode(MaskOpcode) ==
1879 getElementSizeForOpcode(PredOpcode))
1880 return PredOpcode;
1881
1882 // For PTEST_FIRST(PTRUE_ALL, WHILE), the PTEST_FIRST is redundant since
1883 // WHILEcc performs an implicit PTEST with an all active mask, setting
1884 // the N flag as the PTEST_FIRST would.
1885 if (PTest->getOpcode() == AArch64::PTEST_PP_FIRST &&
1886 isPTrueOpcode(MaskOpcode) && Mask->getOperand(1).getImm() == 31)
1887 return PredOpcode;
1888
1889 return {};
1890 }
1891
1892 if (PredIsPTestLike) {
1893 // For PTEST(PG, PG), PTEST is redundant when PG is the result of an
1894 // instruction that sets the flags as PTEST would and the condition is
1895 // "any" since PG is always a subset of the governing predicate of the
1896 // ptest-like instruction.
1897 if ((Mask == Pred) && PTest->getOpcode() == AArch64::PTEST_PP_ANY)
1898 return PredOpcode;
1899
1900 auto PTestLikeMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
1901
1902 // If the PTEST like instruction's general predicate is not `Mask`, attempt
1903 // to look through a copy and try again. This is because some instructions
1904 // take a predicate whose register class is a subset of its result class.
1905 if (Mask != PTestLikeMask && PTestLikeMask->isFullCopy() &&
1906 PTestLikeMask->getOperand(1).getReg().isVirtual())
1907 PTestLikeMask =
1908 MRI->getUniqueVRegDef(PTestLikeMask->getOperand(1).getReg());
1909
1910 // For PTEST(PTRUE_ALL, PTEST_LIKE), the PTEST is redundant if the
1911 // the element size matches and either the PTEST_LIKE instruction uses
1912 // the same all active mask or the condition is "any".
1913 if (isPTrueOpcode(MaskOpcode) && Mask->getOperand(1).getImm() == 31 &&
1914 getElementSizeForOpcode(MaskOpcode) ==
1915 getElementSizeForOpcode(PredOpcode)) {
1916 if (Mask == PTestLikeMask || PTest->getOpcode() == AArch64::PTEST_PP_ANY)
1917 return PredOpcode;
1918 }
1919
1920 // For PTEST(PG, PTEST_LIKE(PG, ...)), the PTEST is redundant since the
1921 // flags are set based on the same mask 'PG', but PTEST_LIKE must operate
1922 // on 8-bit predicates like the PTEST. Otherwise, for instructions like
1923 // compare that also support 16/32/64-bit predicates, the implicit PTEST
1924 // performed by the compare could consider fewer lanes for these element
1925 // sizes.
1926 //
1927 // For example, consider
1928 //
1929 // ptrue p0.b ; P0=1111-1111-1111-1111
1930 // index z0.s, #0, #1 ; Z0=<0,1,2,3>
1931 // index z1.s, #1, #1 ; Z1=<1,2,3,4>
1932 // cmphi p1.s, p0/z, z1.s, z0.s ; P1=0001-0001-0001-0001
1933 // ; ^ last active
1934 // ptest p0, p1.b ; P1=0001-0001-0001-0001
1935 // ; ^ last active
1936 //
1937 // where the compare generates a canonical all active 32-bit predicate
1938 // (equivalent to 'ptrue p1.s, all'). The implicit PTEST sets the last
1939 // active flag, whereas the PTEST instruction with the same mask doesn't.
1940 // For PTEST_ANY this doesn't apply as the flags in this case would be
1941 // identical regardless of element size.
1942 uint64_t PredElementSize = getElementSizeForOpcode(PredOpcode);
1943 if (Mask == PTestLikeMask && (PredElementSize == AArch64::ElementSizeB ||
1944 PTest->getOpcode() == AArch64::PTEST_PP_ANY))
1945 return PredOpcode;
1946
1947 return {};
1948 }
1949
1950 // If OP in PTEST(PG, OP(PG, ...)) has a flag-setting variant change the
1951 // opcode so the PTEST becomes redundant.
1952 switch (PredOpcode) {
1953 case AArch64::AND_PPzPP:
1954 case AArch64::BIC_PPzPP:
1955 case AArch64::EOR_PPzPP:
1956 case AArch64::NAND_PPzPP:
1957 case AArch64::NOR_PPzPP:
1958 case AArch64::ORN_PPzPP:
1959 case AArch64::ORR_PPzPP:
1960 case AArch64::BRKA_PPzP:
1961 case AArch64::BRKPA_PPzPP:
1962 case AArch64::BRKB_PPzP:
1963 case AArch64::BRKPB_PPzPP:
1964 case AArch64::RDFFR_PPz: {
1965 // Check to see if our mask is the same. If not the resulting flag bits
1966 // may be different and we can't remove the ptest.
1967 auto *PredMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
1968 if (Mask != PredMask)
1969 return {};
1970 break;
1971 }
1972 case AArch64::BRKN_PPzP: {
1973 // BRKN uses an all active implicit mask to set flags unlike the other
1974 // flag-setting instructions.
1975 // PTEST(PTRUE_B(31), BRKN(PG, A, B)) -> BRKNS(PG, A, B).
1976 if ((MaskOpcode != AArch64::PTRUE_B) ||
1977 (Mask->getOperand(1).getImm() != 31))
1978 return {};
1979 break;
1980 }
1981 case AArch64::PTRUE_B:
1982 // PTEST(OP=PTRUE_B(A), OP) -> PTRUES_B(A)
1983 break;
1984 default:
1985 // Bail out if we don't recognize the input
1986 return {};
1987 }
1988
1989 return convertToFlagSettingOpc(PredOpcode);
1990}
1991
1992/// optimizePTestInstr - Attempt to remove a ptest of a predicate-generating
1993/// operation which could set the flags in an identical manner
1994bool AArch64InstrInfo::optimizePTestInstr(
1995 MachineInstr *PTest, unsigned MaskReg, unsigned PredReg,
1996 const MachineRegisterInfo *MRI) const {
1997 auto *Mask = MRI->getUniqueVRegDef(MaskReg);
1998 auto *Pred = MRI->getUniqueVRegDef(PredReg);
1999
2000 if (Pred->isCopy() && PTest->getOpcode() == AArch64::PTEST_PP_FIRST) {
2001 // Instructions which return a multi-vector (e.g. WHILECC_x2) require copies
2002 // before the branch to extract each subregister.
2003 auto Op = Pred->getOperand(1);
2004 if (Op.isReg() && Op.getReg().isVirtual() &&
2005 Op.getSubReg() == AArch64::psub0)
2006 Pred = MRI->getUniqueVRegDef(Op.getReg());
2007 }
2008
2009 unsigned PredOpcode = Pred->getOpcode();
2010 auto NewOp = canRemovePTestInstr(PTest, Mask, Pred, MRI);
2011 if (!NewOp)
2012 return false;
2013
2014 const TargetRegisterInfo *TRI = &getRegisterInfo();
2015
2016 // If another instruction between Pred and PTest accesses flags, don't remove
2017 // the ptest or update the earlier instruction to modify them.
2018 if (areCFlagsAccessedBetweenInstrs(Pred, PTest, TRI))
2019 return false;
2020
2021 // If we pass all the checks, it's safe to remove the PTEST and use the flags
2022 // as they are prior to PTEST. Sometimes this requires the tested PTEST
2023 // operand to be replaced with an equivalent instruction that also sets the
2024 // flags.
2025 PTest->eraseFromParent();
2026 if (*NewOp != PredOpcode) {
2027 Pred->setDesc(get(*NewOp));
2028 bool succeeded = UpdateOperandRegClass(*Pred);
2029 (void)succeeded;
2030 assert(succeeded && "Operands have incompatible register classes!");
2031 Pred->addRegisterDefined(AArch64::NZCV, TRI);
2032 }
2033
2034 // Ensure that the flags def is live.
2035 if (Pred->registerDefIsDead(AArch64::NZCV, TRI)) {
2036 unsigned i = 0, e = Pred->getNumOperands();
2037 for (; i != e; ++i) {
2038 MachineOperand &MO = Pred->getOperand(i);
2039 if (MO.isReg() && MO.isDef() && MO.getReg() == AArch64::NZCV) {
2040 MO.setIsDead(false);
2041 break;
2042 }
2043 }
2044 }
2045 return true;
2046}
2047
2048/// Try to optimize a compare instruction. A compare instruction is an
2049/// instruction which produces AArch64::NZCV. It can be truly compare
2050/// instruction
2051/// when there are no uses of its destination register.
2052///
2053/// The following steps are tried in order:
2054/// 1. Convert CmpInstr into an unconditional version.
2055/// 2. Remove CmpInstr if above there is an instruction producing a needed
2056/// condition code or an instruction which can be converted into such an
2057/// instruction.
2058/// Only comparison with zero is supported.
2060 MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2, int64_t CmpMask,
2061 int64_t CmpValue, const MachineRegisterInfo *MRI) const {
2062 assert(CmpInstr.getParent());
2063 assert(MRI);
2064
2065 // Replace SUBSWrr with SUBWrr if NZCV is not used.
2066 int DeadNZCVIdx =
2067 CmpInstr.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true);
2068 if (DeadNZCVIdx != -1) {
2069 if (CmpInstr.definesRegister(AArch64::WZR, /*TRI=*/nullptr) ||
2070 CmpInstr.definesRegister(AArch64::XZR, /*TRI=*/nullptr)) {
2071 CmpInstr.eraseFromParent();
2072 return true;
2073 }
2074 unsigned Opc = CmpInstr.getOpcode();
2075 unsigned NewOpc = convertToNonFlagSettingOpc(CmpInstr);
2076 if (NewOpc == Opc)
2077 return false;
2078 const MCInstrDesc &MCID = get(NewOpc);
2079 CmpInstr.setDesc(MCID);
2080 CmpInstr.removeOperand(DeadNZCVIdx);
2081 bool succeeded = UpdateOperandRegClass(CmpInstr);
2082 (void)succeeded;
2083 assert(succeeded && "Some operands reg class are incompatible!");
2084 return true;
2085 }
2086
2087 if (CmpInstr.getOpcode() == AArch64::PTEST_PP ||
2088 CmpInstr.getOpcode() == AArch64::PTEST_PP_ANY ||
2089 CmpInstr.getOpcode() == AArch64::PTEST_PP_FIRST)
2090 return optimizePTestInstr(&CmpInstr, SrcReg, SrcReg2, MRI);
2091
2092 if (SrcReg2 != 0)
2093 return false;
2094
2095 // CmpInstr is a Compare instruction if destination register is not used.
2096 if (!MRI->use_nodbg_empty(CmpInstr.getOperand(0).getReg()))
2097 return false;
2098
2099 if (CmpValue == 0 && substituteCmpToZero(CmpInstr, SrcReg, *MRI))
2100 return true;
2101 return (CmpValue == 0 || CmpValue == 1) &&
2102 removeCmpToZeroOrOne(CmpInstr, SrcReg, CmpValue, *MRI);
2103}
2104
2105/// Get opcode of S version of Instr.
2106/// If Instr is S version its opcode is returned.
2107/// AArch64::INSTRUCTION_LIST_END is returned if Instr does not have S version
2108/// or we are not interested in it.
2109static unsigned sForm(MachineInstr &Instr) {
2110 switch (Instr.getOpcode()) {
2111 default:
2112 return AArch64::INSTRUCTION_LIST_END;
2113
2114 case AArch64::ADDSWrr:
2115 case AArch64::ADDSWri:
2116 case AArch64::ADDSXrr:
2117 case AArch64::ADDSXri:
2118 case AArch64::ADDSWrx:
2119 case AArch64::ADDSXrx:
2120 case AArch64::ADDSWrs:
2121 case AArch64::ADDSXrs:
2122 case AArch64::SUBSWrr:
2123 case AArch64::SUBSWri:
2124 case AArch64::SUBSWrx:
2125 case AArch64::SUBSWrs:
2126 case AArch64::SUBSXrr:
2127 case AArch64::SUBSXri:
2128 case AArch64::SUBSXrx:
2129 case AArch64::SUBSXrs:
2130 case AArch64::ANDSWri:
2131 case AArch64::ANDSWrr:
2132 case AArch64::ANDSWrs:
2133 case AArch64::ANDSXri:
2134 case AArch64::ANDSXrr:
2135 case AArch64::ANDSXrs:
2136 case AArch64::BICSWrr:
2137 case AArch64::BICSXrr:
2138 case AArch64::BICSWrs:
2139 case AArch64::BICSXrs:
2140 case AArch64::ADCSWr:
2141 case AArch64::ADCSXr:
2142 case AArch64::SBCSWr:
2143 case AArch64::SBCSXr:
2144 return Instr.getOpcode();
2145
2146 case AArch64::ADDWrr:
2147 return AArch64::ADDSWrr;
2148 case AArch64::ADDWri:
2149 return AArch64::ADDSWri;
2150 case AArch64::ADDXrr:
2151 return AArch64::ADDSXrr;
2152 case AArch64::ADDXri:
2153 return AArch64::ADDSXri;
2154 case AArch64::ADDWrx:
2155 return AArch64::ADDSWrx;
2156 case AArch64::ADDXrx:
2157 return AArch64::ADDSXrx;
2158 case AArch64::ADDWrs:
2159 return AArch64::ADDSWrs;
2160 case AArch64::ADDXrs:
2161 return AArch64::ADDSXrs;
2162 case AArch64::ADCWr:
2163 return AArch64::ADCSWr;
2164 case AArch64::ADCXr:
2165 return AArch64::ADCSXr;
2166 case AArch64::SUBWrr:
2167 return AArch64::SUBSWrr;
2168 case AArch64::SUBWri:
2169 return AArch64::SUBSWri;
2170 case AArch64::SUBXrr:
2171 return AArch64::SUBSXrr;
2172 case AArch64::SUBXri:
2173 return AArch64::SUBSXri;
2174 case AArch64::SUBWrx:
2175 return AArch64::SUBSWrx;
2176 case AArch64::SUBXrx:
2177 return AArch64::SUBSXrx;
2178 case AArch64::SUBWrs:
2179 return AArch64::SUBSWrs;
2180 case AArch64::SUBXrs:
2181 return AArch64::SUBSXrs;
2182 case AArch64::SBCWr:
2183 return AArch64::SBCSWr;
2184 case AArch64::SBCXr:
2185 return AArch64::SBCSXr;
2186 case AArch64::ANDWri:
2187 return AArch64::ANDSWri;
2188 case AArch64::ANDXri:
2189 return AArch64::ANDSXri;
2190 case AArch64::ANDWrr:
2191 return AArch64::ANDSWrr;
2192 case AArch64::ANDWrs:
2193 return AArch64::ANDSWrs;
2194 case AArch64::ANDXrr:
2195 return AArch64::ANDSXrr;
2196 case AArch64::ANDXrs:
2197 return AArch64::ANDSXrs;
2198 case AArch64::BICWrr:
2199 return AArch64::BICSWrr;
2200 case AArch64::BICXrr:
2201 return AArch64::BICSXrr;
2202 case AArch64::BICWrs:
2203 return AArch64::BICSWrs;
2204 case AArch64::BICXrs:
2205 return AArch64::BICSXrs;
2206 }
2207}
2208
2209/// Check if AArch64::NZCV should be alive in successors of MBB.
2211 for (auto *BB : MBB->successors())
2212 if (BB->isLiveIn(AArch64::NZCV))
2213 return true;
2214 return false;
2215}
2216
2217/// \returns The condition code operand index for \p Instr if it is a branch
2218/// or select and -1 otherwise.
2219int AArch64InstrInfo::findCondCodeUseOperandIdxForBranchOrSelect(
2220 const MachineInstr &Instr) {
2221 switch (Instr.getOpcode()) {
2222 default:
2223 return -1;
2224
2225 case AArch64::Bcc: {
2226 int Idx = Instr.findRegisterUseOperandIdx(AArch64::NZCV, /*TRI=*/nullptr);
2227 assert(Idx >= 2);
2228 return Idx - 2;
2229 }
2230
2231 case AArch64::CSINVWr:
2232 case AArch64::CSINVXr:
2233 case AArch64::CSINCWr:
2234 case AArch64::CSINCXr:
2235 case AArch64::CSELWr:
2236 case AArch64::CSELXr:
2237 case AArch64::CSNEGWr:
2238 case AArch64::CSNEGXr:
2239 case AArch64::FCSELSrrr:
2240 case AArch64::FCSELDrrr: {
2241 int Idx = Instr.findRegisterUseOperandIdx(AArch64::NZCV, /*TRI=*/nullptr);
2242 assert(Idx >= 1);
2243 return Idx - 1;
2244 }
2245 }
2246}
2247
2248/// Find a condition code used by the instruction.
2249/// Returns AArch64CC::Invalid if either the instruction does not use condition
2250/// codes or we don't optimize CmpInstr in the presence of such instructions.
2252 int CCIdx =
2253 AArch64InstrInfo::findCondCodeUseOperandIdxForBranchOrSelect(Instr);
2254 return CCIdx >= 0 ? static_cast<AArch64CC::CondCode>(
2255 Instr.getOperand(CCIdx).getImm())
2257}
2258
2261 UsedNZCV UsedFlags;
2262 switch (CC) {
2263 default:
2264 break;
2265
2266 case AArch64CC::EQ: // Z set
2267 case AArch64CC::NE: // Z clear
2268 UsedFlags.Z = true;
2269 break;
2270
2271 case AArch64CC::HI: // Z clear and C set
2272 case AArch64CC::LS: // Z set or C clear
2273 UsedFlags.Z = true;
2274 [[fallthrough]];
2275 case AArch64CC::HS: // C set
2276 case AArch64CC::LO: // C clear
2277 UsedFlags.C = true;
2278 break;
2279
2280 case AArch64CC::MI: // N set
2281 case AArch64CC::PL: // N clear
2282 UsedFlags.N = true;
2283 break;
2284
2285 case AArch64CC::VS: // V set
2286 case AArch64CC::VC: // V clear
2287 UsedFlags.V = true;
2288 break;
2289
2290 case AArch64CC::GT: // Z clear, N and V the same
2291 case AArch64CC::LE: // Z set, N and V differ
2292 UsedFlags.Z = true;
2293 [[fallthrough]];
2294 case AArch64CC::GE: // N and V the same
2295 case AArch64CC::LT: // N and V differ
2296 UsedFlags.N = true;
2297 UsedFlags.V = true;
2298 break;
2299 }
2300 return UsedFlags;
2301}
2302
2303/// \returns Conditions flags used after \p CmpInstr in its MachineBB if NZCV
2304/// flags are not alive in successors of the same \p CmpInstr and \p MI parent.
2305/// \returns std::nullopt otherwise.
2306///
2307/// Collect instructions using that flags in \p CCUseInstrs if provided.
2308std::optional<UsedNZCV>
2310 const TargetRegisterInfo &TRI,
2311 SmallVectorImpl<MachineInstr *> *CCUseInstrs) {
2312 MachineBasicBlock *CmpParent = CmpInstr.getParent();
2313 if (MI.getParent() != CmpParent)
2314 return std::nullopt;
2315
2316 if (areCFlagsAliveInSuccessors(CmpParent))
2317 return std::nullopt;
2318
2319 UsedNZCV NZCVUsedAfterCmp;
2321 std::next(CmpInstr.getIterator()), CmpParent->instr_end())) {
2322 if (Instr.readsRegister(AArch64::NZCV, &TRI)) {
2324 if (CC == AArch64CC::Invalid) // Unsupported conditional instruction
2325 return std::nullopt;
2326 NZCVUsedAfterCmp |= getUsedNZCV(CC);
2327 if (CCUseInstrs)
2328 CCUseInstrs->push_back(&Instr);
2329 }
2330 if (Instr.modifiesRegister(AArch64::NZCV, &TRI))
2331 break;
2332 }
2333 return NZCVUsedAfterCmp;
2334}
2335
2336static bool isADDSRegImm(unsigned Opcode) {
2337 return Opcode == AArch64::ADDSWri || Opcode == AArch64::ADDSXri;
2338}
2339
2340static bool isSUBSRegImm(unsigned Opcode) {
2341 return Opcode == AArch64::SUBSWri || Opcode == AArch64::SUBSXri;
2342}
2343
2345 unsigned Opc = sForm(MI);
2346 switch (Opc) {
2347 case AArch64::ANDSWri:
2348 case AArch64::ANDSWrr:
2349 case AArch64::ANDSWrs:
2350 case AArch64::ANDSXri:
2351 case AArch64::ANDSXrr:
2352 case AArch64::ANDSXrs:
2353 case AArch64::BICSWrr:
2354 case AArch64::BICSXrr:
2355 case AArch64::BICSWrs:
2356 case AArch64::BICSXrs:
2357 return true;
2358 default:
2359 return false;
2360 }
2361}
2362
2363/// Check if CmpInstr can be substituted by MI.
2364///
2365/// CmpInstr can be substituted:
2366/// - CmpInstr is either 'ADDS %vreg, 0' or 'SUBS %vreg, 0'
2367/// - and, MI and CmpInstr are from the same MachineBB
2368/// - and, condition flags are not alive in successors of the CmpInstr parent
2369/// - and, if MI opcode is the S form there must be no defs of flags between
2370/// MI and CmpInstr
2371/// or if MI opcode is not the S form there must be neither defs of flags
2372/// nor uses of flags between MI and CmpInstr.
2373/// - and, C is not used after CmpInstr; CmpInstr's C is from adds/subs #0 on
2374/// SrcReg and can differ from MI (e.g. carry out of ADCS/SBCS).
2375/// - and, V is not used after CmpInstr unless MI is AND/BIC (V cleared) or MI
2376/// has NoSWrap (overflow is poison and the fold is still safe).
2378 const TargetRegisterInfo &TRI) {
2379 // MI is an opcode sForm maps (add/sub/adc/sbc/and/bic and their S forms).
2380 assert(sForm(MI) != AArch64::INSTRUCTION_LIST_END);
2381
2382 const unsigned CmpOpcode = CmpInstr.getOpcode();
2383 if (!isADDSRegImm(CmpOpcode) && !isSUBSRegImm(CmpOpcode))
2384 return false;
2385
2386 assert((CmpInstr.getOperand(2).isImm() &&
2387 CmpInstr.getOperand(2).getImm() == 0) &&
2388 "Caller guarantees that CmpInstr compares with constant 0");
2389
2390 std::optional<UsedNZCV> NZVCUsed = examineCFlagsUse(MI, CmpInstr, TRI);
2391 if (!NZVCUsed || NZVCUsed->C)
2392 return false;
2393
2394 // CmpInstr is ADDS/SUBS with immediate 0 on SrcReg (compare SrcReg to zero).
2395 // After the fold, users see NZCV from MI (or its S form), not from CmpInstr.
2396 // N/Z match CmpInstr for the value in SrcReg; C/V need not match in general
2397 // (e.g. ADCS vs adds #0), so we require C unused after CmpInstr and gate V
2398 // as below. NoSWrap makes signed overflow poison; AND/BIC clear V.
2399 if (NZVCUsed->V && !MI.getFlag(MachineInstr::NoSWrap) && !isANDOpcode(MI))
2400 return false;
2401
2402 AccessKind AccessToCheck = AK_Write;
2403 if (sForm(MI) != MI.getOpcode())
2404 AccessToCheck = AK_All;
2405 return !areCFlagsAccessedBetweenInstrs(&MI, &CmpInstr, &TRI, AccessToCheck);
2406}
2407
2408/// Substitute an instruction comparing to zero with another instruction
2409/// which produces needed condition flags.
2410///
2411/// Return true on success.
2412bool AArch64InstrInfo::substituteCmpToZero(
2413 MachineInstr &CmpInstr, unsigned SrcReg,
2414 const MachineRegisterInfo &MRI) const {
2415 // Get the unique definition of SrcReg.
2416 MachineInstr *MI = MRI.getUniqueVRegDef(SrcReg);
2417 if (!MI)
2418 return false;
2419
2420 const TargetRegisterInfo &TRI = getRegisterInfo();
2421
2422 unsigned NewOpc = sForm(*MI);
2423 if (NewOpc == AArch64::INSTRUCTION_LIST_END)
2424 return false;
2425
2426 if (!canInstrSubstituteCmpInstr(*MI, CmpInstr, TRI))
2427 return false;
2428
2429 // Update the instruction to set NZCV.
2430 MI->setDesc(get(NewOpc));
2431 CmpInstr.eraseFromParent();
2433 (void)succeeded;
2434 assert(succeeded && "Some operands reg class are incompatible!");
2435 MI->addRegisterDefined(AArch64::NZCV, &TRI);
2436 return true;
2437}
2438
2439/// \returns True if \p CmpInstr can be removed.
2440///
2441/// \p IsInvertCC is true if, after removing \p CmpInstr, condition
2442/// codes used in \p CCUseInstrs must be inverted.
2444 int CmpValue, const TargetRegisterInfo &TRI,
2446 bool &IsInvertCC) {
2447 assert((CmpValue == 0 || CmpValue == 1) &&
2448 "Only comparisons to 0 or 1 considered for removal!");
2449
2450 // MI is 'CSINCWr %vreg, wzr, wzr, <cc>' or 'CSINCXr %vreg, xzr, xzr, <cc>'
2451 unsigned MIOpc = MI.getOpcode();
2452 if (MIOpc == AArch64::CSINCWr) {
2453 if (MI.getOperand(1).getReg() != AArch64::WZR ||
2454 MI.getOperand(2).getReg() != AArch64::WZR)
2455 return false;
2456 } else if (MIOpc == AArch64::CSINCXr) {
2457 if (MI.getOperand(1).getReg() != AArch64::XZR ||
2458 MI.getOperand(2).getReg() != AArch64::XZR)
2459 return false;
2460 } else {
2461 return false;
2462 }
2464 if (MICC == AArch64CC::Invalid)
2465 return false;
2466
2467 // NZCV needs to be defined
2468 if (MI.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true) != -1)
2469 return false;
2470
2471 // CmpInstr is 'ADDS %vreg, 0' or 'SUBS %vreg, 0' or 'SUBS %vreg, 1'
2472 const unsigned CmpOpcode = CmpInstr.getOpcode();
2473 bool IsSubsRegImm = isSUBSRegImm(CmpOpcode);
2474 if (CmpValue && !IsSubsRegImm)
2475 return false;
2476 if (!CmpValue && !IsSubsRegImm && !isADDSRegImm(CmpOpcode))
2477 return false;
2478
2479 // MI conditions allowed: eq, ne, mi, pl
2480 UsedNZCV MIUsedNZCV = getUsedNZCV(MICC);
2481 if (MIUsedNZCV.C || MIUsedNZCV.V)
2482 return false;
2483
2484 std::optional<UsedNZCV> NZCVUsedAfterCmp =
2485 examineCFlagsUse(MI, CmpInstr, TRI, &CCUseInstrs);
2486 // Condition flags are not used in CmpInstr basic block successors and only
2487 // Z or N flags allowed to be used after CmpInstr within its basic block
2488 if (!NZCVUsedAfterCmp || NZCVUsedAfterCmp->C || NZCVUsedAfterCmp->V)
2489 return false;
2490 // Z or N flag used after CmpInstr must correspond to the flag used in MI
2491 if ((MIUsedNZCV.Z && NZCVUsedAfterCmp->N) ||
2492 (MIUsedNZCV.N && NZCVUsedAfterCmp->Z))
2493 return false;
2494 // If CmpInstr is comparison to zero MI conditions are limited to eq, ne
2495 if (MIUsedNZCV.N && !CmpValue)
2496 return false;
2497
2498 // There must be no defs of flags between MI and CmpInstr
2499 if (areCFlagsAccessedBetweenInstrs(&MI, &CmpInstr, &TRI, AK_Write))
2500 return false;
2501
2502 // Condition code is inverted in the following cases:
2503 // 1. MI condition is ne; CmpInstr is 'ADDS %vreg, 0' or 'SUBS %vreg, 0'
2504 // 2. MI condition is eq, pl; CmpInstr is 'SUBS %vreg, 1'
2505 IsInvertCC = (CmpValue && (MICC == AArch64CC::EQ || MICC == AArch64CC::PL)) ||
2506 (!CmpValue && MICC == AArch64CC::NE);
2507 return true;
2508}
2509
2510/// Remove comparison in csinc-cmp sequence
2511///
2512/// Examples:
2513/// 1. \code
2514/// csinc w9, wzr, wzr, ne
2515/// cmp w9, #0
2516/// b.eq
2517/// \endcode
2518/// to
2519/// \code
2520/// csinc w9, wzr, wzr, ne
2521/// b.ne
2522/// \endcode
2523///
2524/// 2. \code
2525/// csinc x2, xzr, xzr, mi
2526/// cmp x2, #1
2527/// b.pl
2528/// \endcode
2529/// to
2530/// \code
2531/// csinc x2, xzr, xzr, mi
2532/// b.pl
2533/// \endcode
2534///
2535/// \param CmpInstr comparison instruction
2536/// \return True when comparison removed
2537bool AArch64InstrInfo::removeCmpToZeroOrOne(
2538 MachineInstr &CmpInstr, unsigned SrcReg, int CmpValue,
2539 const MachineRegisterInfo &MRI) const {
2540 MachineInstr *MI = MRI.getUniqueVRegDef(SrcReg);
2541 if (!MI)
2542 return false;
2543 const TargetRegisterInfo &TRI = getRegisterInfo();
2544 SmallVector<MachineInstr *, 4> CCUseInstrs;
2545 bool IsInvertCC = false;
2546 if (!canCmpInstrBeRemoved(*MI, CmpInstr, CmpValue, TRI, CCUseInstrs,
2547 IsInvertCC))
2548 return false;
2549 // Make transformation
2550 CmpInstr.eraseFromParent();
2551 if (IsInvertCC) {
2552 // Invert condition codes in CmpInstr CC users
2553 for (MachineInstr *CCUseInstr : CCUseInstrs) {
2554 int Idx = findCondCodeUseOperandIdxForBranchOrSelect(*CCUseInstr);
2555 assert(Idx >= 0 && "Unexpected instruction using CC.");
2556 MachineOperand &CCOperand = CCUseInstr->getOperand(Idx);
2558 static_cast<AArch64CC::CondCode>(CCOperand.getImm()));
2559 CCOperand.setImm(CCUse);
2560 }
2561 }
2562 return true;
2563}
2564
2565bool AArch64InstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
2566 if (MI.getOpcode() != TargetOpcode::LOAD_STACK_GUARD &&
2567 MI.getOpcode() != AArch64::CATCHRET &&
2568 MI.getOpcode() != AArch64::STACK_GUARD_UNMIX)
2569 return false;
2570
2571 MachineBasicBlock &MBB = *MI.getParent();
2572 auto &Subtarget = MBB.getParent()->getSubtarget<AArch64Subtarget>();
2573 auto TRI = Subtarget.getRegisterInfo();
2574 DebugLoc DL = MI.getDebugLoc();
2575
2576 if (MI.getOpcode() == AArch64::STACK_GUARD_UNMIX) {
2577 // Expand STACK_GUARD_UNMIX to: sub Rd, fp, Rs
2578 // This computes FP - stored_mixed_value to unmix the cookie
2579 Register DstReg = MI.getOperand(0).getReg();
2580 Register SrcReg = MI.getOperand(1).getReg();
2581
2582 BuildMI(MBB, MI, DL, get(AArch64::SUBXrr), DstReg)
2583 .addReg(AArch64::FP)
2584 .addReg(SrcReg);
2585
2586 MBB.erase(MI);
2587 return true;
2588 }
2589
2590 if (MI.getOpcode() == AArch64::CATCHRET) {
2591 // Skip to the first instruction before the epilog.
2592 const TargetInstrInfo *TII =
2594 MachineBasicBlock *TargetMBB = MI.getOperand(0).getMBB();
2596 MachineBasicBlock::iterator FirstEpilogSEH = std::prev(MBBI);
2597 while (FirstEpilogSEH->getFlag(MachineInstr::FrameDestroy) &&
2598 FirstEpilogSEH != MBB.begin())
2599 FirstEpilogSEH = std::prev(FirstEpilogSEH);
2600 if (FirstEpilogSEH != MBB.begin())
2601 FirstEpilogSEH = std::next(FirstEpilogSEH);
2602 BuildMI(MBB, FirstEpilogSEH, DL, TII->get(AArch64::ADRP))
2603 .addReg(AArch64::X0, RegState::Define)
2604 .addMBB(TargetMBB, AArch64II::MO_PAGE);
2605 BuildMI(MBB, FirstEpilogSEH, DL, TII->get(AArch64::ADDXri))
2606 .addReg(AArch64::X0, RegState::Define)
2607 .addReg(AArch64::X0)
2609 .addImm(0);
2610 TargetMBB->setMachineBlockAddressTaken();
2611 return true;
2612 }
2613
2614 Register Reg = MI.getOperand(0).getReg();
2616 if (M.getStackProtectorGuard() == "sysreg") {
2617 const AArch64SysReg::SysReg *SrcReg =
2618 AArch64SysReg::lookupSysRegByName(M.getStackProtectorGuardReg());
2619 if (!SrcReg)
2620 report_fatal_error("Unknown SysReg for Stack Protector Guard Register");
2621
2622 // mrs xN, sysreg
2623 BuildMI(MBB, MI, DL, get(AArch64::MRS))
2625 .addImm(SrcReg->Encoding);
2626 int Offset = M.getStackProtectorGuardOffset();
2627 if (Offset >= 0 && Offset <= 32760 && Offset % 8 == 0) {
2628 // ldr xN, [xN, #offset]
2629 BuildMI(MBB, MI, DL, get(AArch64::LDRXui))
2630 .addDef(Reg)
2632 .addImm(Offset / 8);
2633 } else if (Offset >= -256 && Offset <= 255) {
2634 // ldur xN, [xN, #offset]
2635 BuildMI(MBB, MI, DL, get(AArch64::LDURXi))
2636 .addDef(Reg)
2638 .addImm(Offset);
2639 } else if (Offset >= -4095 && Offset <= 4095) {
2640 if (Offset > 0) {
2641 // add xN, xN, #offset
2642 BuildMI(MBB, MI, DL, get(AArch64::ADDXri))
2643 .addDef(Reg)
2645 .addImm(Offset)
2646 .addImm(0);
2647 } else {
2648 // sub xN, xN, #offset
2649 BuildMI(MBB, MI, DL, get(AArch64::SUBXri))
2650 .addDef(Reg)
2652 .addImm(-Offset)
2653 .addImm(0);
2654 }
2655 // ldr xN, [xN]
2656 BuildMI(MBB, MI, DL, get(AArch64::LDRXui))
2657 .addDef(Reg)
2659 .addImm(0);
2660 } else {
2661 // Cases that are larger than +/- 4095 and not a multiple of 8, or larger
2662 // than 23760.
2663 // It might be nice to use AArch64::MOVi32imm here, which would get
2664 // expanded in PreSched2 after PostRA, but our lone scratch Reg already
2665 // contains the MRS result. findScratchNonCalleeSaveRegister() in
2666 // AArch64FrameLowering might help us find such a scratch register
2667 // though. If we failed to find a scratch register, we could emit a
2668 // stream of add instructions to build up the immediate. Or, we could try
2669 // to insert a AArch64::MOVi32imm before register allocation so that we
2670 // didn't need to scavenge for a scratch register.
2671 report_fatal_error("Unable to encode Stack Protector Guard Offset");
2672 }
2673 MBB.erase(MI);
2674 return true;
2675 }
2676
2677 const GlobalValue *GV =
2678 cast<GlobalValue>((*MI.memoperands_begin())->getValue());
2679 const TargetMachine &TM = MBB.getParent()->getTarget();
2680 unsigned OpFlags = Subtarget.ClassifyGlobalReference(GV, TM);
2681 const unsigned char MO_NC = AArch64II::MO_NC;
2682
2683 unsigned GuardWidth = M.getStackProtectorGuardValueWidth().value_or(
2684 Subtarget.isTargetILP32() ? 4 : 8);
2685 if (GuardWidth != 4 && GuardWidth != 8)
2686 report_fatal_error("Unsupported stack protector value width");
2687 if ((OpFlags & AArch64II::MO_GOT) != 0) {
2688 BuildMI(MBB, MI, DL, get(AArch64::LOADgot), Reg)
2689 .addGlobalAddress(GV, 0, OpFlags);
2690 if (GuardWidth == 4) {
2691 unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
2692 BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
2693 .addDef(Reg32, RegState::Dead)
2695 .addImm(0)
2696 .addMemOperand(*MI.memoperands_begin())
2698 } else {
2699 BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
2701 .addImm(0)
2702 .addMemOperand(*MI.memoperands_begin());
2703 }
2704 } else if (TM.getCodeModel() == CodeModel::Large) {
2705 BuildMI(MBB, MI, DL, get(AArch64::MOVZXi), Reg)
2706 .addGlobalAddress(GV, 0, AArch64II::MO_G0 | MO_NC)
2707 .addImm(0);
2708 BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
2710 .addGlobalAddress(GV, 0, AArch64II::MO_G1 | MO_NC)
2711 .addImm(16);
2712 BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
2714 .addGlobalAddress(GV, 0, AArch64II::MO_G2 | MO_NC)
2715 .addImm(32);
2716 BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
2719 .addImm(48);
2720 if (GuardWidth == 4) {
2721 unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
2722 BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
2723 .addDef(Reg32, RegState::Dead)
2725 .addImm(0)
2726 .addMemOperand(*MI.memoperands_begin())
2728 } else {
2729 BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
2731 .addImm(0)
2732 .addMemOperand(*MI.memoperands_begin());
2733 }
2734 } else {
2735 BuildMI(MBB, MI, DL, get(AArch64::ADRP), Reg)
2736 .addGlobalAddress(GV, 0, OpFlags | AArch64II::MO_PAGE);
2737 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | MO_NC;
2738 if (GuardWidth == 4) {
2739 unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
2740 BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
2741 .addDef(Reg32, RegState::Dead)
2743 .addGlobalAddress(GV, 0, LoFlags)
2744 .addMemOperand(*MI.memoperands_begin())
2746 } else {
2747 BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
2749 .addGlobalAddress(GV, 0, LoFlags)
2750 .addMemOperand(*MI.memoperands_begin());
2751 }
2752 }
2753 // To match MSVC. Unlike x86_64 which uses xor instruction to mix the cookie,
2754 // we use sub instruction to mix the cookie on aarch64.
2755 // The mixing happens here in expandPostRAPseudo (after RA) to ensure we use
2756 // the final frame pointer value.
2757 if (Subtarget.getTargetTriple().isOSMSVCRT())
2758 BuildMI(MBB, MI, DL, get(AArch64::SUBXrr), Reg)
2759 .addReg(AArch64::FP)
2761
2762 MBB.erase(MI);
2763
2764 return true;
2765}
2766
2767// Return true if this instruction simply sets its single destination register
2768// to zero. This is equivalent to a register rename of the zero-register.
2770 switch (MI.getOpcode()) {
2771 default:
2772 break;
2773 case AArch64::MOVZWi:
2774 case AArch64::MOVZXi: // movz Rd, #0 (LSL #0)
2775 if (MI.getOperand(1).isImm() && MI.getOperand(1).getImm() == 0) {
2776 assert(MI.getDesc().getNumOperands() == 3 &&
2777 MI.getOperand(2).getImm() == 0 && "invalid MOVZi operands");
2778 return true;
2779 }
2780 break;
2781 case AArch64::ANDWri: // and Rd, Rzr, #imm
2782 return MI.getOperand(1).getReg() == AArch64::WZR;
2783 case AArch64::ANDXri:
2784 return MI.getOperand(1).getReg() == AArch64::XZR;
2785 case TargetOpcode::COPY:
2786 return MI.getOperand(1).getReg() == AArch64::WZR;
2787 }
2788 return false;
2789}
2790
2791// Return true if this instruction simply renames a general register without
2792// modifying bits.
2794 switch (MI.getOpcode()) {
2795 default:
2796 break;
2797 case TargetOpcode::COPY: {
2798 // GPR32 copies will by lowered to ORRXrs
2799 Register DstReg = MI.getOperand(0).getReg();
2800 return (AArch64::GPR32RegClass.contains(DstReg) ||
2801 AArch64::GPR64RegClass.contains(DstReg));
2802 }
2803 case AArch64::ORRXrs: // orr Xd, Xzr, Xm (LSL #0)
2804 if (MI.getOperand(1).getReg() == AArch64::XZR) {
2805 assert(MI.getDesc().getNumOperands() == 4 &&
2806 MI.getOperand(3).getImm() == 0 && "invalid ORRrs operands");
2807 return true;
2808 }
2809 break;
2810 case AArch64::ADDXri: // add Xd, Xn, #0 (LSL #0)
2811 if (MI.getOperand(2).getImm() == 0) {
2812 assert(MI.getDesc().getNumOperands() == 4 &&
2813 MI.getOperand(3).getImm() == 0 && "invalid ADDXri operands");
2814 return true;
2815 }
2816 break;
2817 }
2818 return false;
2819}
2820
2821// Return true if this instruction simply renames a general register without
2822// modifying bits.
2824 switch (MI.getOpcode()) {
2825 default:
2826 break;
2827 case TargetOpcode::COPY: {
2828 Register DstReg = MI.getOperand(0).getReg();
2829 return AArch64::FPR128RegClass.contains(DstReg);
2830 }
2831 case AArch64::ORRv16i8:
2832 if (MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) {
2833 assert(MI.getDesc().getNumOperands() == 3 && MI.getOperand(0).isReg() &&
2834 "invalid ORRv16i8 operands");
2835 return true;
2836 }
2837 break;
2838 }
2839 return false;
2840}
2841
2842static bool isFrameLoadOpcode(int Opcode) {
2843 switch (Opcode) {
2844 default:
2845 return false;
2846 case AArch64::LDRWui:
2847 case AArch64::LDRXui:
2848 case AArch64::LDRBui:
2849 case AArch64::LDRHui:
2850 case AArch64::LDRSui:
2851 case AArch64::LDRDui:
2852 case AArch64::LDRQui:
2853 case AArch64::LDR_PXI:
2854 return true;
2855 }
2856}
2857
2859 int &FrameIndex) const {
2860 if (!isFrameLoadOpcode(MI.getOpcode()))
2861 return Register();
2862
2863 if (MI.getOperand(0).getSubReg() == 0 && MI.getOperand(1).isFI() &&
2864 MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) {
2865 FrameIndex = MI.getOperand(1).getIndex();
2866 return MI.getOperand(0).getReg();
2867 }
2868 return Register();
2869}
2870
2871static bool isFrameStoreOpcode(int Opcode) {
2872 switch (Opcode) {
2873 default:
2874 return false;
2875 case AArch64::STRWui:
2876 case AArch64::STRXui:
2877 case AArch64::STRBui:
2878 case AArch64::STRHui:
2879 case AArch64::STRSui:
2880 case AArch64::STRDui:
2881 case AArch64::STRQui:
2882 case AArch64::STR_PXI:
2883 return true;
2884 }
2885}
2886
2888 int &FrameIndex) const {
2889 if (!isFrameStoreOpcode(MI.getOpcode()))
2890 return Register();
2891
2892 if (MI.getOperand(0).getSubReg() == 0 && MI.getOperand(1).isFI() &&
2893 MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) {
2894 FrameIndex = MI.getOperand(1).getIndex();
2895 return MI.getOperand(0).getReg();
2896 }
2897 return Register();
2898}
2899
2901 int &FrameIndex) const {
2902 if (!isFrameStoreOpcode(MI.getOpcode()))
2903 return Register();
2904
2905 if (Register Reg = isStoreToStackSlot(MI, FrameIndex))
2906 return Reg;
2907
2909 if (hasStoreToStackSlot(MI, Accesses)) {
2910 if (Accesses.size() > 1)
2911 return Register();
2912
2913 FrameIndex =
2914 cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
2915 ->getFrameIndex();
2916 return MI.getOperand(0).getReg();
2917 }
2918 return Register();
2919}
2920
2922 int &FrameIndex) const {
2923 if (!isFrameLoadOpcode(MI.getOpcode()))
2924 return Register();
2925
2926 if (Register Reg = isLoadFromStackSlot(MI, FrameIndex))
2927 return Reg;
2928
2930 if (hasLoadFromStackSlot(MI, Accesses)) {
2931 if (Accesses.size() > 1)
2932 return Register();
2933
2934 FrameIndex =
2935 cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
2936 ->getFrameIndex();
2937 return MI.getOperand(0).getReg();
2938 }
2939 return Register();
2940}
2941
2942/// Check all MachineMemOperands for a hint to suppress pairing.
2944 return llvm::any_of(MI.memoperands(), [](MachineMemOperand *MMO) {
2945 return MMO->getFlags() & MOSuppressPair;
2946 });
2947}
2948
2949/// Set a flag on the first MachineMemOperand to suppress pairing.
2951 if (MI.memoperands_empty())
2952 return;
2953 (*MI.memoperands_begin())->setFlags(MOSuppressPair);
2954}
2955
2956/// Check all MachineMemOperands for a hint that the load/store is strided.
2958 return llvm::any_of(MI.memoperands(), [](MachineMemOperand *MMO) {
2959 return MMO->getFlags() & MOStridedAccess;
2960 });
2961}
2962
2964 switch (Opc) {
2965 default:
2966 return false;
2967 case AArch64::STURSi:
2968 case AArch64::STRSpre:
2969 case AArch64::STURDi:
2970 case AArch64::STRDpre:
2971 case AArch64::STURQi:
2972 case AArch64::STRQpre:
2973 case AArch64::STURBBi:
2974 case AArch64::STURHHi:
2975 case AArch64::STURWi:
2976 case AArch64::STRWpre:
2977 case AArch64::STURXi:
2978 case AArch64::STRXpre:
2979 case AArch64::LDURSi:
2980 case AArch64::LDRSpre:
2981 case AArch64::LDURDi:
2982 case AArch64::LDRDpre:
2983 case AArch64::LDURQi:
2984 case AArch64::LDRQpre:
2985 case AArch64::LDURWi:
2986 case AArch64::LDRWpre:
2987 case AArch64::LDURXi:
2988 case AArch64::LDRXpre:
2989 case AArch64::LDRSWpre:
2990 case AArch64::LDURSWi:
2991 case AArch64::LDURHHi:
2992 case AArch64::LDURBBi:
2993 case AArch64::LDURSBWi:
2994 case AArch64::LDURSHWi:
2995 return true;
2996 }
2997}
2998
2999std::optional<unsigned> AArch64InstrInfo::getUnscaledLdSt(unsigned Opc) {
3000 switch (Opc) {
3001 default: return {};
3002 case AArch64::PRFMui: return AArch64::PRFUMi;
3003 case AArch64::LDRXui: return AArch64::LDURXi;
3004 case AArch64::LDRWui: return AArch64::LDURWi;
3005 case AArch64::LDRBui: return AArch64::LDURBi;
3006 case AArch64::LDRHui: return AArch64::LDURHi;
3007 case AArch64::LDRSui: return AArch64::LDURSi;
3008 case AArch64::LDRDui: return AArch64::LDURDi;
3009 case AArch64::LDRQui: return AArch64::LDURQi;
3010 case AArch64::LDRBBui: return AArch64::LDURBBi;
3011 case AArch64::LDRHHui: return AArch64::LDURHHi;
3012 case AArch64::LDRSBXui: return AArch64::LDURSBXi;
3013 case AArch64::LDRSBWui: return AArch64::LDURSBWi;
3014 case AArch64::LDRSHXui: return AArch64::LDURSHXi;
3015 case AArch64::LDRSHWui: return AArch64::LDURSHWi;
3016 case AArch64::LDRSWui: return AArch64::LDURSWi;
3017 case AArch64::STRXui: return AArch64::STURXi;
3018 case AArch64::STRWui: return AArch64::STURWi;
3019 case AArch64::STRBui: return AArch64::STURBi;
3020 case AArch64::STRHui: return AArch64::STURHi;
3021 case AArch64::STRSui: return AArch64::STURSi;
3022 case AArch64::STRDui: return AArch64::STURDi;
3023 case AArch64::STRQui: return AArch64::STURQi;
3024 case AArch64::STRBBui: return AArch64::STURBBi;
3025 case AArch64::STRHHui: return AArch64::STURHHi;
3026 }
3027}
3028
3030 switch (Opc) {
3031 default:
3032 llvm_unreachable("Unhandled Opcode in getLoadStoreImmIdx");
3033 case AArch64::ADDG:
3034 case AArch64::LDAPURBi:
3035 case AArch64::LDAPURHi:
3036 case AArch64::LDAPURi:
3037 case AArch64::LDAPURSBWi:
3038 case AArch64::LDAPURSBXi:
3039 case AArch64::LDAPURSHWi:
3040 case AArch64::LDAPURSHXi:
3041 case AArch64::LDAPURSWi:
3042 case AArch64::LDAPURXi:
3043 case AArch64::LDR_PPXI:
3044 case AArch64::LDR_PXI:
3045 case AArch64::LDR_ZXI:
3046 case AArch64::LDR_ZZXI:
3047 case AArch64::LDR_ZZXI_STRIDED_CONTIGUOUS:
3048 case AArch64::LDR_ZZZXI:
3049 case AArch64::LDR_ZZZZXI:
3050 case AArch64::LDR_ZZZZXI_STRIDED_CONTIGUOUS:
3051 case AArch64::LDRBBui:
3052 case AArch64::LDRBui:
3053 case AArch64::LDRDui:
3054 case AArch64::LDRHHui:
3055 case AArch64::LDRHui:
3056 case AArch64::LDRQui:
3057 case AArch64::LDRSBWui:
3058 case AArch64::LDRSBXui:
3059 case AArch64::LDRSHWui:
3060 case AArch64::LDRSHXui:
3061 case AArch64::LDRSui:
3062 case AArch64::LDRSWui:
3063 case AArch64::LDRWui:
3064 case AArch64::LDRXui:
3065 case AArch64::LDURBBi:
3066 case AArch64::LDURBi:
3067 case AArch64::LDURDi:
3068 case AArch64::LDURHHi:
3069 case AArch64::LDURHi:
3070 case AArch64::LDURQi:
3071 case AArch64::LDURSBWi:
3072 case AArch64::LDURSBXi:
3073 case AArch64::LDURSHWi:
3074 case AArch64::LDURSHXi:
3075 case AArch64::LDURSi:
3076 case AArch64::LDURSWi:
3077 case AArch64::LDURWi:
3078 case AArch64::LDURXi:
3079 case AArch64::PRFMui:
3080 case AArch64::PRFUMi:
3081 case AArch64::ST2Gi:
3082 case AArch64::STGi:
3083 case AArch64::STLURBi:
3084 case AArch64::STLURHi:
3085 case AArch64::STLURWi:
3086 case AArch64::STLURXi:
3087 case AArch64::StoreSwiftAsyncContext:
3088 case AArch64::STR_PPXI:
3089 case AArch64::STR_PXI:
3090 case AArch64::STR_ZXI:
3091 case AArch64::STR_ZZXI:
3092 case AArch64::STR_ZZXI_STRIDED_CONTIGUOUS:
3093 case AArch64::STR_ZZZXI:
3094 case AArch64::STR_ZZZZXI:
3095 case AArch64::STR_ZZZZXI_STRIDED_CONTIGUOUS:
3096 case AArch64::STRBBui:
3097 case AArch64::STRBui:
3098 case AArch64::STRDui:
3099 case AArch64::STRHHui:
3100 case AArch64::STRHui:
3101 case AArch64::STRQui:
3102 case AArch64::STRSui:
3103 case AArch64::STRWui:
3104 case AArch64::STRXui:
3105 case AArch64::STURBBi:
3106 case AArch64::STURBi:
3107 case AArch64::STURDi:
3108 case AArch64::STURHHi:
3109 case AArch64::STURHi:
3110 case AArch64::STURQi:
3111 case AArch64::STURSi:
3112 case AArch64::STURWi:
3113 case AArch64::STURXi:
3114 case AArch64::STZ2Gi:
3115 case AArch64::STZGi:
3116 case AArch64::TAGPstack:
3117 return 2;
3118 case AArch64::LD1B_D_IMM:
3119 case AArch64::LD1B_H_IMM:
3120 case AArch64::LD1B_IMM:
3121 case AArch64::LD1B_S_IMM:
3122 case AArch64::LD1D_IMM:
3123 case AArch64::LD1H_D_IMM:
3124 case AArch64::LD1H_IMM:
3125 case AArch64::LD1H_S_IMM:
3126 case AArch64::LD1RB_D_IMM:
3127 case AArch64::LD1RB_H_IMM:
3128 case AArch64::LD1RB_IMM:
3129 case AArch64::LD1RB_S_IMM:
3130 case AArch64::LD1RD_IMM:
3131 case AArch64::LD1RH_D_IMM:
3132 case AArch64::LD1RH_IMM:
3133 case AArch64::LD1RH_S_IMM:
3134 case AArch64::LD1RSB_D_IMM:
3135 case AArch64::LD1RSB_H_IMM:
3136 case AArch64::LD1RSB_S_IMM:
3137 case AArch64::LD1RSH_D_IMM:
3138 case AArch64::LD1RSH_S_IMM:
3139 case AArch64::LD1RSW_IMM:
3140 case AArch64::LD1RW_D_IMM:
3141 case AArch64::LD1RW_IMM:
3142 case AArch64::LD1SB_D_IMM:
3143 case AArch64::LD1SB_H_IMM:
3144 case AArch64::LD1SB_S_IMM:
3145 case AArch64::LD1SH_D_IMM:
3146 case AArch64::LD1SH_S_IMM:
3147 case AArch64::LD1SW_D_IMM:
3148 case AArch64::LD1W_D_IMM:
3149 case AArch64::LD1W_IMM:
3150 case AArch64::LD2B_IMM:
3151 case AArch64::LD2D_IMM:
3152 case AArch64::LD2H_IMM:
3153 case AArch64::LD2W_IMM:
3154 case AArch64::LD3B_IMM:
3155 case AArch64::LD3D_IMM:
3156 case AArch64::LD3H_IMM:
3157 case AArch64::LD3W_IMM:
3158 case AArch64::LD4B_IMM:
3159 case AArch64::LD4D_IMM:
3160 case AArch64::LD4H_IMM:
3161 case AArch64::LD4W_IMM:
3162 case AArch64::LDG:
3163 case AArch64::LDNF1B_D_IMM:
3164 case AArch64::LDNF1B_H_IMM:
3165 case AArch64::LDNF1B_IMM:
3166 case AArch64::LDNF1B_S_IMM:
3167 case AArch64::LDNF1D_IMM:
3168 case AArch64::LDNF1H_D_IMM:
3169 case AArch64::LDNF1H_IMM:
3170 case AArch64::LDNF1H_S_IMM:
3171 case AArch64::LDNF1SB_D_IMM:
3172 case AArch64::LDNF1SB_H_IMM:
3173 case AArch64::LDNF1SB_S_IMM:
3174 case AArch64::LDNF1SH_D_IMM:
3175 case AArch64::LDNF1SH_S_IMM:
3176 case AArch64::LDNF1SW_D_IMM:
3177 case AArch64::LDNF1W_D_IMM:
3178 case AArch64::LDNF1W_IMM:
3179 case AArch64::LDNPDi:
3180 case AArch64::LDNPQi:
3181 case AArch64::LDNPSi:
3182 case AArch64::LDNPWi:
3183 case AArch64::LDNPXi:
3184 case AArch64::LDNT1B_ZRI:
3185 case AArch64::LDNT1D_ZRI:
3186 case AArch64::LDNT1H_ZRI:
3187 case AArch64::LDNT1W_ZRI:
3188 case AArch64::LDPDi:
3189 case AArch64::LDPQi:
3190 case AArch64::LDPSi:
3191 case AArch64::LDPWi:
3192 case AArch64::LDPXi:
3193 case AArch64::LDRBBpost:
3194 case AArch64::LDRBBpre:
3195 case AArch64::LDRBpost:
3196 case AArch64::LDRBpre:
3197 case AArch64::LDRDpost:
3198 case AArch64::LDRDpre:
3199 case AArch64::LDRHHpost:
3200 case AArch64::LDRHHpre:
3201 case AArch64::LDRHpost:
3202 case AArch64::LDRHpre:
3203 case AArch64::LDRQpost:
3204 case AArch64::LDRQpre:
3205 case AArch64::LDRSpost:
3206 case AArch64::LDRSpre:
3207 case AArch64::LDRWpost:
3208 case AArch64::LDRWpre:
3209 case AArch64::LDRXpost:
3210 case AArch64::LDRXpre:
3211 case AArch64::ST1B_D_IMM:
3212 case AArch64::ST1B_H_IMM:
3213 case AArch64::ST1B_IMM:
3214 case AArch64::ST1B_S_IMM:
3215 case AArch64::ST1D_IMM:
3216 case AArch64::ST1H_D_IMM:
3217 case AArch64::ST1H_IMM:
3218 case AArch64::ST1H_S_IMM:
3219 case AArch64::ST1W_D_IMM:
3220 case AArch64::ST1W_IMM:
3221 case AArch64::ST2B_IMM:
3222 case AArch64::ST2D_IMM:
3223 case AArch64::ST2H_IMM:
3224 case AArch64::ST2W_IMM:
3225 case AArch64::ST3B_IMM:
3226 case AArch64::ST3D_IMM:
3227 case AArch64::ST3H_IMM:
3228 case AArch64::ST3W_IMM:
3229 case AArch64::ST4B_IMM:
3230 case AArch64::ST4D_IMM:
3231 case AArch64::ST4H_IMM:
3232 case AArch64::ST4W_IMM:
3233 case AArch64::STGPi:
3234 case AArch64::STGPreIndex:
3235 case AArch64::STZGPreIndex:
3236 case AArch64::ST2GPreIndex:
3237 case AArch64::STZ2GPreIndex:
3238 case AArch64::STGPostIndex:
3239 case AArch64::STZGPostIndex:
3240 case AArch64::ST2GPostIndex:
3241 case AArch64::STZ2GPostIndex:
3242 case AArch64::STNPDi:
3243 case AArch64::STNPQi:
3244 case AArch64::STNPSi:
3245 case AArch64::STNPWi:
3246 case AArch64::STNPXi:
3247 case AArch64::STNT1B_ZRI:
3248 case AArch64::STNT1D_ZRI:
3249 case AArch64::STNT1H_ZRI:
3250 case AArch64::STNT1W_ZRI:
3251 case AArch64::STPDi:
3252 case AArch64::STPQi:
3253 case AArch64::STPSi:
3254 case AArch64::STPWi:
3255 case AArch64::STPXi:
3256 case AArch64::STRBBpost:
3257 case AArch64::STRBBpre:
3258 case AArch64::STRBpost:
3259 case AArch64::STRBpre:
3260 case AArch64::STRDpost:
3261 case AArch64::STRDpre:
3262 case AArch64::STRHHpost:
3263 case AArch64::STRHHpre:
3264 case AArch64::STRHpost:
3265 case AArch64::STRHpre:
3266 case AArch64::STRQpost:
3267 case AArch64::STRQpre:
3268 case AArch64::STRSpost:
3269 case AArch64::STRSpre:
3270 case AArch64::STRWpost:
3271 case AArch64::STRWpre:
3272 case AArch64::STRXpost:
3273 case AArch64::STRXpre:
3274 case AArch64::LD1B_2Z_IMM:
3275 case AArch64::LD1B_2Z_STRIDED_IMM:
3276 case AArch64::LD1H_2Z_IMM:
3277 case AArch64::LD1H_2Z_STRIDED_IMM:
3278 case AArch64::LD1W_2Z_IMM:
3279 case AArch64::LD1W_2Z_STRIDED_IMM:
3280 case AArch64::LD1D_2Z_IMM:
3281 case AArch64::LD1D_2Z_STRIDED_IMM:
3282 case AArch64::LD1B_4Z_IMM:
3283 case AArch64::LD1B_4Z_STRIDED_IMM:
3284 case AArch64::LD1H_4Z_IMM:
3285 case AArch64::LD1H_4Z_STRIDED_IMM:
3286 case AArch64::LD1W_4Z_IMM:
3287 case AArch64::LD1W_4Z_STRIDED_IMM:
3288 case AArch64::LD1D_4Z_IMM:
3289 case AArch64::LD1D_4Z_STRIDED_IMM:
3290 case AArch64::LD1B_2Z_IMM_PSEUDO:
3291 case AArch64::LD1H_2Z_IMM_PSEUDO:
3292 case AArch64::LD1W_2Z_IMM_PSEUDO:
3293 case AArch64::LD1D_2Z_IMM_PSEUDO:
3294 case AArch64::LD1B_4Z_IMM_PSEUDO:
3295 case AArch64::LD1H_4Z_IMM_PSEUDO:
3296 case AArch64::LD1W_4Z_IMM_PSEUDO:
3297 case AArch64::LD1D_4Z_IMM_PSEUDO:
3298 case AArch64::ST1B_2Z_IMM:
3299 case AArch64::ST1B_2Z_STRIDED_IMM:
3300 case AArch64::ST1H_2Z_IMM:
3301 case AArch64::ST1H_2Z_STRIDED_IMM:
3302 case AArch64::ST1W_2Z_IMM:
3303 case AArch64::ST1W_2Z_STRIDED_IMM:
3304 case AArch64::ST1D_2Z_IMM:
3305 case AArch64::ST1D_2Z_STRIDED_IMM:
3306 case AArch64::LDNT1B_2Z_IMM_PSEUDO:
3307 case AArch64::LDNT1B_2Z_IMM:
3308 case AArch64::LDNT1B_2Z_STRIDED_IMM:
3309 case AArch64::LDNT1H_2Z_IMM_PSEUDO:
3310 case AArch64::LDNT1H_2Z_IMM:
3311 case AArch64::LDNT1H_2Z_STRIDED_IMM:
3312 case AArch64::LDNT1W_2Z_IMM_PSEUDO:
3313 case AArch64::LDNT1W_2Z_IMM:
3314 case AArch64::LDNT1W_2Z_STRIDED_IMM:
3315 case AArch64::LDNT1D_2Z_IMM_PSEUDO:
3316 case AArch64::LDNT1D_2Z_IMM:
3317 case AArch64::LDNT1D_2Z_STRIDED_IMM:
3318 case AArch64::STNT1B_2Z_IMM:
3319 case AArch64::STNT1B_2Z_STRIDED_IMM:
3320 case AArch64::STNT1H_2Z_IMM:
3321 case AArch64::STNT1H_2Z_STRIDED_IMM:
3322 case AArch64::STNT1W_2Z_IMM:
3323 case AArch64::STNT1W_2Z_STRIDED_IMM:
3324 case AArch64::STNT1D_2Z_IMM:
3325 case AArch64::STNT1D_2Z_STRIDED_IMM:
3326 case AArch64::ST1B_2Z_IMM_PSEUDO:
3327 case AArch64::ST1H_2Z_IMM_PSEUDO:
3328 case AArch64::ST1W_2Z_IMM_PSEUDO:
3329 case AArch64::ST1D_2Z_IMM_PSEUDO:
3330 case AArch64::STNT1B_2Z_IMM_PSEUDO:
3331 case AArch64::STNT1H_2Z_IMM_PSEUDO:
3332 case AArch64::STNT1W_2Z_IMM_PSEUDO:
3333 case AArch64::STNT1D_2Z_IMM_PSEUDO:
3334 case AArch64::ST1B_4Z_IMM:
3335 case AArch64::ST1B_4Z_STRIDED_IMM:
3336 case AArch64::ST1H_4Z_IMM:
3337 case AArch64::ST1H_4Z_STRIDED_IMM:
3338 case AArch64::ST1W_4Z_IMM:
3339 case AArch64::ST1W_4Z_STRIDED_IMM:
3340 case AArch64::ST1D_4Z_IMM:
3341 case AArch64::ST1D_4Z_STRIDED_IMM:
3342 case AArch64::LDNT1B_4Z_IMM_PSEUDO:
3343 case AArch64::LDNT1B_4Z_IMM:
3344 case AArch64::LDNT1B_4Z_STRIDED_IMM:
3345 case AArch64::LDNT1H_4Z_IMM_PSEUDO:
3346 case AArch64::LDNT1H_4Z_IMM:
3347 case AArch64::LDNT1H_4Z_STRIDED_IMM:
3348 case AArch64::LDNT1W_4Z_IMM_PSEUDO:
3349 case AArch64::LDNT1W_4Z_IMM:
3350 case AArch64::LDNT1W_4Z_STRIDED_IMM:
3351 case AArch64::LDNT1D_4Z_IMM_PSEUDO:
3352 case AArch64::LDNT1D_4Z_IMM:
3353 case AArch64::LDNT1D_4Z_STRIDED_IMM:
3354 case AArch64::STNT1B_4Z_IMM:
3355 case AArch64::STNT1B_4Z_STRIDED_IMM:
3356 case AArch64::STNT1H_4Z_IMM:
3357 case AArch64::STNT1H_4Z_STRIDED_IMM:
3358 case AArch64::STNT1W_4Z_IMM:
3359 case AArch64::STNT1W_4Z_STRIDED_IMM:
3360 case AArch64::STNT1D_4Z_IMM:
3361 case AArch64::STNT1D_4Z_STRIDED_IMM:
3362 case AArch64::ST1B_4Z_IMM_PSEUDO:
3363 case AArch64::ST1H_4Z_IMM_PSEUDO:
3364 case AArch64::ST1W_4Z_IMM_PSEUDO:
3365 case AArch64::ST1D_4Z_IMM_PSEUDO:
3366 case AArch64::STNT1B_4Z_IMM_PSEUDO:
3367 case AArch64::STNT1H_4Z_IMM_PSEUDO:
3368 case AArch64::STNT1W_4Z_IMM_PSEUDO:
3369 case AArch64::STNT1D_4Z_IMM_PSEUDO:
3370 return 3;
3371 case AArch64::LDPDpost:
3372 case AArch64::LDPDpre:
3373 case AArch64::LDPQpost:
3374 case AArch64::LDPQpre:
3375 case AArch64::LDPSpost:
3376 case AArch64::LDPSpre:
3377 case AArch64::LDPWpost:
3378 case AArch64::LDPWpre:
3379 case AArch64::LDPXpost:
3380 case AArch64::LDPXpre:
3381 case AArch64::STGPpre:
3382 case AArch64::STGPpost:
3383 case AArch64::STPDpost:
3384 case AArch64::STPDpre:
3385 case AArch64::STPQpost:
3386 case AArch64::STPQpre:
3387 case AArch64::STPSpost:
3388 case AArch64::STPSpre:
3389 case AArch64::STPWpost:
3390 case AArch64::STPWpre:
3391 case AArch64::STPXpost:
3392 case AArch64::STPXpre:
3393 return 4;
3394 }
3395}
3396
3398 switch (MI.getOpcode()) {
3399 default:
3400 return false;
3401 // Scaled instructions.
3402 case AArch64::STRSui:
3403 case AArch64::STRDui:
3404 case AArch64::STRQui:
3405 case AArch64::STRXui:
3406 case AArch64::STRWui:
3407 case AArch64::LDRSui:
3408 case AArch64::LDRDui:
3409 case AArch64::LDRQui:
3410 case AArch64::LDRXui:
3411 case AArch64::LDRWui:
3412 case AArch64::LDRSWui:
3413 // Unscaled instructions.
3414 case AArch64::STURSi:
3415 case AArch64::STRSpre:
3416 case AArch64::STURDi:
3417 case AArch64::STRDpre:
3418 case AArch64::STURQi:
3419 case AArch64::STRQpre:
3420 case AArch64::STURWi:
3421 case AArch64::STRWpre:
3422 case AArch64::STURXi:
3423 case AArch64::STRXpre:
3424 case AArch64::LDURSi:
3425 case AArch64::LDRSpre:
3426 case AArch64::LDURDi:
3427 case AArch64::LDRDpre:
3428 case AArch64::LDURQi:
3429 case AArch64::LDRQpre:
3430 case AArch64::LDURWi:
3431 case AArch64::LDRWpre:
3432 case AArch64::LDURXi:
3433 case AArch64::LDRXpre:
3434 case AArch64::LDURSWi:
3435 case AArch64::LDRSWpre:
3436 // SVE instructions.
3437 case AArch64::LDR_ZXI:
3438 case AArch64::STR_ZXI:
3439 return true;
3440 }
3441}
3442
3444 switch (MI.getOpcode()) {
3445 default:
3446 assert((!MI.isCall() || !MI.isReturn()) &&
3447 "Unexpected instruction - was a new tail call opcode introduced?");
3448 return false;
3449 case AArch64::TCRETURNdi:
3450 case AArch64::TCRETURNri:
3451 case AArch64::TCRETURNrix16x17:
3452 case AArch64::TCRETURNrix17:
3453 case AArch64::TCRETURNrinotx16:
3454 case AArch64::TCRETURNriALL:
3455 case AArch64::AUTH_TCRETURN:
3456 case AArch64::AUTH_TCRETURN_BTI:
3457 return true;
3458 }
3459}
3460
3462 switch (Opc) {
3463 default:
3464 llvm_unreachable("Opcode has no flag setting equivalent!");
3465 // 32-bit cases:
3466 case AArch64::ADDWri:
3467 return AArch64::ADDSWri;
3468 case AArch64::ADDWrr:
3469 return AArch64::ADDSWrr;
3470 case AArch64::ADDWrs:
3471 return AArch64::ADDSWrs;
3472 case AArch64::ADDWrx:
3473 return AArch64::ADDSWrx;
3474 case AArch64::ANDWri:
3475 return AArch64::ANDSWri;
3476 case AArch64::ANDWrr:
3477 return AArch64::ANDSWrr;
3478 case AArch64::ANDWrs:
3479 return AArch64::ANDSWrs;
3480 case AArch64::BICWrr:
3481 return AArch64::BICSWrr;
3482 case AArch64::BICWrs:
3483 return AArch64::BICSWrs;
3484 case AArch64::SUBWri:
3485 return AArch64::SUBSWri;
3486 case AArch64::SUBWrr:
3487 return AArch64::SUBSWrr;
3488 case AArch64::SUBWrs:
3489 return AArch64::SUBSWrs;
3490 case AArch64::SUBWrx:
3491 return AArch64::SUBSWrx;
3492 // 64-bit cases:
3493 case AArch64::ADDXri:
3494 return AArch64::ADDSXri;
3495 case AArch64::ADDXrr:
3496 return AArch64::ADDSXrr;
3497 case AArch64::ADDXrs:
3498 return AArch64::ADDSXrs;
3499 case AArch64::ADDXrx:
3500 return AArch64::ADDSXrx;
3501 case AArch64::ANDXri:
3502 return AArch64::ANDSXri;
3503 case AArch64::ANDXrr:
3504 return AArch64::ANDSXrr;
3505 case AArch64::ANDXrs:
3506 return AArch64::ANDSXrs;
3507 case AArch64::BICXrr:
3508 return AArch64::BICSXrr;
3509 case AArch64::BICXrs:
3510 return AArch64::BICSXrs;
3511 case AArch64::SUBXri:
3512 return AArch64::SUBSXri;
3513 case AArch64::SUBXrr:
3514 return AArch64::SUBSXrr;
3515 case AArch64::SUBXrs:
3516 return AArch64::SUBSXrs;
3517 case AArch64::SUBXrx:
3518 return AArch64::SUBSXrx;
3519 // SVE instructions:
3520 case AArch64::AND_PPzPP:
3521 return AArch64::ANDS_PPzPP;
3522 case AArch64::BIC_PPzPP:
3523 return AArch64::BICS_PPzPP;
3524 case AArch64::EOR_PPzPP:
3525 return AArch64::EORS_PPzPP;
3526 case AArch64::NAND_PPzPP:
3527 return AArch64::NANDS_PPzPP;
3528 case AArch64::NOR_PPzPP:
3529 return AArch64::NORS_PPzPP;
3530 case AArch64::ORN_PPzPP:
3531 return AArch64::ORNS_PPzPP;
3532 case AArch64::ORR_PPzPP:
3533 return AArch64::ORRS_PPzPP;
3534 case AArch64::BRKA_PPzP:
3535 return AArch64::BRKAS_PPzP;
3536 case AArch64::BRKPA_PPzPP:
3537 return AArch64::BRKPAS_PPzPP;
3538 case AArch64::BRKB_PPzP:
3539 return AArch64::BRKBS_PPzP;
3540 case AArch64::BRKPB_PPzPP:
3541 return AArch64::BRKPBS_PPzPP;
3542 case AArch64::BRKN_PPzP:
3543 return AArch64::BRKNS_PPzP;
3544 case AArch64::RDFFR_PPz:
3545 return AArch64::RDFFRS_PPz;
3546 case AArch64::PTRUE_B:
3547 return AArch64::PTRUES_B;
3548 }
3549}
3550
3551// Is this a candidate for ld/st merging or pairing? For example, we don't
3552// touch volatiles or load/stores that have a hint to avoid pair formation.
3554
3555 bool IsPreLdSt = isPreLdSt(MI);
3556
3557 // If this is a volatile load/store, don't mess with it.
3558 if (MI.hasOrderedMemoryRef())
3559 return false;
3560
3561 // Make sure this is a reg/fi+imm (as opposed to an address reloc).
3562 // For Pre-inc LD/ST, the operand is shifted by one.
3563 assert((MI.getOperand(IsPreLdSt ? 2 : 1).isReg() ||
3564 MI.getOperand(IsPreLdSt ? 2 : 1).isFI()) &&
3565 "Expected a reg or frame index operand.");
3566
3567 // For Pre-indexed addressing quadword instructions, the third operand is the
3568 // immediate value.
3569 bool IsImmPreLdSt = IsPreLdSt && MI.getOperand(3).isImm();
3570
3571 if (!MI.getOperand(2).isImm() && !IsImmPreLdSt)
3572 return false;
3573
3574 // Can't merge/pair if the instruction modifies the base register.
3575 // e.g., ldr x0, [x0]
3576 // This case will never occur with an FI base.
3577 // However, if the instruction is an LDR<S,D,Q,W,X,SW>pre or
3578 // STR<S,D,Q,W,X>pre, it can be merged.
3579 // For example:
3580 // ldr q0, [x11, #32]!
3581 // ldr q1, [x11, #16]
3582 // to
3583 // ldp q0, q1, [x11, #32]!
3584 if (MI.getOperand(1).isReg() && !IsPreLdSt) {
3585 Register BaseReg = MI.getOperand(1).getReg();
3587 if (MI.modifiesRegister(BaseReg, TRI))
3588 return false;
3589 }
3590
3591 // Pairing SVE fills/spills is only valid for little-endian targets that
3592 // implement VLS 128.
3593 switch (MI.getOpcode()) {
3594 default:
3595 break;
3596 case AArch64::LDR_ZXI:
3597 case AArch64::STR_ZXI:
3598 if (!Subtarget.isLittleEndian() ||
3599 Subtarget.getSVEVectorSizeInBits() != 128)
3600 return false;
3601 }
3602
3603 // Check if this load/store has a hint to avoid pair formation.
3604 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
3606 return false;
3607
3608 // Do not pair any callee-save store/reload instructions in the
3609 // prologue/epilogue if the CFI information encoded the operations as separate
3610 // instructions, as that will cause the size of the actual prologue to mismatch
3611 // with the prologue size recorded in the Windows CFI.
3612 const MCAsmInfo &MAI = MI.getMF()->getTarget().getMCAsmInfo();
3613 bool NeedsWinCFI =
3614 MAI.usesWindowsCFI() && MI.getMF()->getFunction().needsUnwindTableEntry();
3615 if (NeedsWinCFI && (MI.getFlag(MachineInstr::FrameSetup) ||
3617 return false;
3618
3619 // On some CPUs quad load/store pairs are slower than two single load/stores.
3620 if (Subtarget.isPaired128Slow()) {
3621 switch (MI.getOpcode()) {
3622 default:
3623 break;
3624 case AArch64::LDURQi:
3625 case AArch64::STURQi:
3626 case AArch64::LDRQui:
3627 case AArch64::STRQui:
3628 return false;
3629 }
3630 }
3631
3632 return true;
3633}
3634
3637 int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width,
3638 const TargetRegisterInfo *TRI) const {
3639 if (!LdSt.mayLoadOrStore())
3640 return false;
3641
3642 const MachineOperand *BaseOp;
3643 TypeSize WidthN(0, false);
3644 if (!getMemOperandWithOffsetWidth(LdSt, BaseOp, Offset, OffsetIsScalable,
3645 WidthN, TRI))
3646 return false;
3647 // The maximum vscale is 16 under AArch64, return the maximal extent for the
3648 // vector.
3649 Width = LocationSize::precise(WidthN);
3650 BaseOps.push_back(BaseOp);
3651 return true;
3652}
3653
3654std::optional<ExtAddrMode>
3656 const TargetRegisterInfo *TRI) const {
3657 const MachineOperand *Base; // Filled with the base operand of MI.
3658 int64_t Offset; // Filled with the offset of MI.
3659 bool OffsetIsScalable;
3660 if (!getMemOperandWithOffset(MemI, Base, Offset, OffsetIsScalable, TRI))
3661 return std::nullopt;
3662
3663 if (!Base->isReg())
3664 return std::nullopt;
3665 ExtAddrMode AM;
3666 AM.BaseReg = Base->getReg();
3667 AM.Displacement = Offset;
3668 AM.ScaledReg = 0;
3669 AM.Scale = 0;
3670 return AM;
3671}
3672
3674 Register Reg,
3675 const MachineInstr &AddrI,
3676 ExtAddrMode &AM) const {
3677 // Filter out instructions into which we cannot fold.
3678 unsigned NumBytes;
3679 int64_t OffsetScale = 1;
3680 switch (MemI.getOpcode()) {
3681 default:
3682 return false;
3683
3684 case AArch64::LDURQi:
3685 case AArch64::STURQi:
3686 NumBytes = 16;
3687 break;
3688
3689 case AArch64::LDURDi:
3690 case AArch64::STURDi:
3691 case AArch64::LDURXi:
3692 case AArch64::STURXi:
3693 NumBytes = 8;
3694 break;
3695
3696 case AArch64::LDURWi:
3697 case AArch64::LDURSWi:
3698 case AArch64::STURWi:
3699 NumBytes = 4;
3700 break;
3701
3702 case AArch64::LDURHi:
3703 case AArch64::STURHi:
3704 case AArch64::LDURHHi:
3705 case AArch64::STURHHi:
3706 case AArch64::LDURSHXi:
3707 case AArch64::LDURSHWi:
3708 NumBytes = 2;
3709 break;
3710
3711 case AArch64::LDRBroX:
3712 case AArch64::LDRBBroX:
3713 case AArch64::LDRSBXroX:
3714 case AArch64::LDRSBWroX:
3715 case AArch64::STRBroX:
3716 case AArch64::STRBBroX:
3717 case AArch64::LDURBi:
3718 case AArch64::LDURBBi:
3719 case AArch64::LDURSBXi:
3720 case AArch64::LDURSBWi:
3721 case AArch64::STURBi:
3722 case AArch64::STURBBi:
3723 case AArch64::LDRBui:
3724 case AArch64::LDRBBui:
3725 case AArch64::LDRSBXui:
3726 case AArch64::LDRSBWui:
3727 case AArch64::STRBui:
3728 case AArch64::STRBBui:
3729 NumBytes = 1;
3730 break;
3731
3732 case AArch64::LDRQroX:
3733 case AArch64::STRQroX:
3734 case AArch64::LDRQui:
3735 case AArch64::STRQui:
3736 NumBytes = 16;
3737 OffsetScale = 16;
3738 break;
3739
3740 case AArch64::LDRDroX:
3741 case AArch64::STRDroX:
3742 case AArch64::LDRXroX:
3743 case AArch64::STRXroX:
3744 case AArch64::LDRDui:
3745 case AArch64::STRDui:
3746 case AArch64::LDRXui:
3747 case AArch64::STRXui:
3748 NumBytes = 8;
3749 OffsetScale = 8;
3750 break;
3751
3752 case AArch64::LDRWroX:
3753 case AArch64::LDRSWroX:
3754 case AArch64::STRWroX:
3755 case AArch64::LDRWui:
3756 case AArch64::LDRSWui:
3757 case AArch64::STRWui:
3758 NumBytes = 4;
3759 OffsetScale = 4;
3760 break;
3761
3762 case AArch64::LDRHroX:
3763 case AArch64::STRHroX:
3764 case AArch64::LDRHHroX:
3765 case AArch64::STRHHroX:
3766 case AArch64::LDRSHXroX:
3767 case AArch64::LDRSHWroX:
3768 case AArch64::LDRHui:
3769 case AArch64::STRHui:
3770 case AArch64::LDRHHui:
3771 case AArch64::STRHHui:
3772 case AArch64::LDRSHXui:
3773 case AArch64::LDRSHWui:
3774 NumBytes = 2;
3775 OffsetScale = 2;
3776 break;
3777 }
3778
3779 // Check the fold operand is not the loaded/stored value.
3780 const MachineOperand &BaseRegOp = MemI.getOperand(0);
3781 if (BaseRegOp.isReg() && BaseRegOp.getReg() == Reg)
3782 return false;
3783
3784 // Handle memory instructions with a [Reg, Reg] addressing mode.
3785 if (MemI.getOperand(2).isReg()) {
3786 // Bail if the addressing mode already includes extension of the offset
3787 // register.
3788 if (MemI.getOperand(3).getImm())
3789 return false;
3790
3791 // Check if we actually have a scaled offset.
3792 if (MemI.getOperand(4).getImm() == 0)
3793 OffsetScale = 1;
3794
3795 // If the address instructions is folded into the base register, then the
3796 // addressing mode must not have a scale. Then we can swap the base and the
3797 // scaled registers.
3798 if (MemI.getOperand(1).getReg() == Reg && OffsetScale != 1)
3799 return false;
3800
3801 switch (AddrI.getOpcode()) {
3802 default:
3803 return false;
3804
3805 case AArch64::SBFMXri:
3806 // sxtw Xa, Wm
3807 // ldr Xd, [Xn, Xa, lsl #N]
3808 // ->
3809 // ldr Xd, [Xn, Wm, sxtw #N]
3810 if (AddrI.getOperand(2).getImm() != 0 ||
3811 AddrI.getOperand(3).getImm() != 31)
3812 return false;
3813
3814 AM.BaseReg = MemI.getOperand(1).getReg();
3815 if (AM.BaseReg == Reg)
3816 AM.BaseReg = MemI.getOperand(2).getReg();
3817 AM.ScaledReg = AddrI.getOperand(1).getReg();
3818 AM.Scale = OffsetScale;
3819 AM.Displacement = 0;
3821 return true;
3822
3823 case TargetOpcode::SUBREG_TO_REG: {
3824 // mov Wa, Wm
3825 // ldr Xd, [Xn, Xa, lsl #N]
3826 // ->
3827 // ldr Xd, [Xn, Wm, uxtw #N]
3828
3829 // Zero-extension looks like an ORRWrs followed by a SUBREG_TO_REG.
3830 if (AddrI.getOperand(2).getImm() != AArch64::sub_32)
3831 return false;
3832
3833 const MachineRegisterInfo &MRI = AddrI.getMF()->getRegInfo();
3834 Register OffsetReg = AddrI.getOperand(1).getReg();
3835 if (!OffsetReg.isVirtual() || !MRI.hasOneNonDBGUse(OffsetReg))
3836 return false;
3837
3838 const MachineInstr &DefMI = *MRI.getVRegDef(OffsetReg);
3839 if (DefMI.getOpcode() != AArch64::ORRWrs ||
3840 DefMI.getOperand(1).getReg() != AArch64::WZR ||
3841 DefMI.getOperand(3).getImm() != 0)
3842 return false;
3843
3844 AM.BaseReg = MemI.getOperand(1).getReg();
3845 if (AM.BaseReg == Reg)
3846 AM.BaseReg = MemI.getOperand(2).getReg();
3847 AM.ScaledReg = DefMI.getOperand(2).getReg();
3848 AM.Scale = OffsetScale;
3849 AM.Displacement = 0;
3851 return true;
3852 }
3853 }
3854 }
3855
3856 // Handle memory instructions with a [Reg, #Imm] addressing mode.
3857
3858 // Check we are not breaking a potential conversion to an LDP.
3859 auto validateOffsetForLDP = [](unsigned NumBytes, int64_t OldOffset,
3860 int64_t NewOffset) -> bool {
3861 int64_t MinOffset, MaxOffset;
3862 switch (NumBytes) {
3863 default:
3864 return true;
3865 case 4:
3866 MinOffset = -256;
3867 MaxOffset = 252;
3868 break;
3869 case 8:
3870 MinOffset = -512;
3871 MaxOffset = 504;
3872 break;
3873 case 16:
3874 MinOffset = -1024;
3875 MaxOffset = 1008;
3876 break;
3877 }
3878 return OldOffset < MinOffset || OldOffset > MaxOffset ||
3879 (NewOffset >= MinOffset && NewOffset <= MaxOffset);
3880 };
3881 auto canFoldAddSubImmIntoAddrMode = [&](int64_t Disp) -> bool {
3882 int64_t OldOffset = MemI.getOperand(2).getImm() * OffsetScale;
3883 int64_t NewOffset = OldOffset + Disp;
3884 if (!isLegalAddressingMode(NumBytes, NewOffset, /* Scale */ 0))
3885 return false;
3886 // If the old offset would fit into an LDP, but the new offset wouldn't,
3887 // bail out.
3888 if (!validateOffsetForLDP(NumBytes, OldOffset, NewOffset))
3889 return false;
3890 AM.BaseReg = AddrI.getOperand(1).getReg();
3891 AM.ScaledReg = 0;
3892 AM.Scale = 0;
3893 AM.Displacement = NewOffset;
3895 return true;
3896 };
3897
3898 auto canFoldAddRegIntoAddrMode =
3899 [&](int64_t Scale,
3901 if (MemI.getOperand(2).getImm() != 0)
3902 return false;
3903 if ((unsigned)Scale != Scale)
3904 return false;
3905 if (!isLegalAddressingMode(NumBytes, /* Offset */ 0, Scale))
3906 return false;
3907 AM.BaseReg = AddrI.getOperand(1).getReg();
3908 AM.ScaledReg = AddrI.getOperand(2).getReg();
3909 AM.Scale = Scale;
3910 AM.Displacement = 0;
3911 AM.Form = Form;
3912 return true;
3913 };
3914
3915 auto avoidSlowSTRQ = [&](const MachineInstr &MemI) {
3916 unsigned Opcode = MemI.getOpcode();
3917 return (Opcode == AArch64::STURQi || Opcode == AArch64::STRQui) &&
3918 Subtarget.isSTRQroSlow();
3919 };
3920
3921 int64_t Disp = 0;
3922 const bool OptSize = MemI.getMF()->getFunction().hasOptSize();
3923 switch (AddrI.getOpcode()) {
3924 default:
3925 return false;
3926
3927 case AArch64::ADDXri:
3928 // add Xa, Xn, #N
3929 // ldr Xd, [Xa, #M]
3930 // ->
3931 // ldr Xd, [Xn, #N'+M]
3932 Disp = AddrI.getOperand(2).getImm() << AddrI.getOperand(3).getImm();
3933 return canFoldAddSubImmIntoAddrMode(Disp);
3934
3935 case AArch64::SUBXri:
3936 // sub Xa, Xn, #N
3937 // ldr Xd, [Xa, #M]
3938 // ->
3939 // ldr Xd, [Xn, #N'+M]
3940 Disp = AddrI.getOperand(2).getImm() << AddrI.getOperand(3).getImm();
3941 return canFoldAddSubImmIntoAddrMode(-Disp);
3942
3943 case AArch64::ADDXrs: {
3944 // add Xa, Xn, Xm, lsl #N
3945 // ldr Xd, [Xa]
3946 // ->
3947 // ldr Xd, [Xn, Xm, lsl #N]
3948
3949 // Don't fold the add if the result would be slower, unless optimising for
3950 // size.
3951 unsigned Shift = static_cast<unsigned>(AddrI.getOperand(3).getImm());
3953 return false;
3954 Shift = AArch64_AM::getShiftValue(Shift);
3955 if (!OptSize) {
3956 if (Shift != 2 && Shift != 3 && Subtarget.hasAddrLSLSlow14())
3957 return false;
3958 if (avoidSlowSTRQ(MemI))
3959 return false;
3960 }
3961 return canFoldAddRegIntoAddrMode(1ULL << Shift);
3962 }
3963
3964 case AArch64::ADDXrr:
3965 // add Xa, Xn, Xm
3966 // ldr Xd, [Xa]
3967 // ->
3968 // ldr Xd, [Xn, Xm, lsl #0]
3969
3970 // Don't fold the add if the result would be slower, unless optimising for
3971 // size.
3972 if (!OptSize && avoidSlowSTRQ(MemI))
3973 return false;
3974 return canFoldAddRegIntoAddrMode(1);
3975
3976 case AArch64::ADDXrx:
3977 // add Xa, Xn, Wm, {s,u}xtw #N
3978 // ldr Xd, [Xa]
3979 // ->
3980 // ldr Xd, [Xn, Wm, {s,u}xtw #N]
3981
3982 // Don't fold the add if the result would be slower, unless optimising for
3983 // size.
3984 if (!OptSize && avoidSlowSTRQ(MemI))
3985 return false;
3986
3987 // Can fold only sign-/zero-extend of a word.
3988 unsigned Imm = static_cast<unsigned>(AddrI.getOperand(3).getImm());
3990 if (Extend != AArch64_AM::UXTW && Extend != AArch64_AM::SXTW)
3991 return false;
3992
3993 return canFoldAddRegIntoAddrMode(
3997 }
3998}
3999
4000// Given an opcode for an instruction with a [Reg, #Imm] addressing mode,
4001// return the opcode of an instruction performing the same operation, but using
4002// the [Reg, Reg] addressing mode.
4003static unsigned regOffsetOpcode(unsigned Opcode) {
4004 switch (Opcode) {
4005 default:
4006 llvm_unreachable("Address folding not implemented for instruction");
4007
4008 case AArch64::LDURQi:
4009 case AArch64::LDRQui:
4010 return AArch64::LDRQroX;
4011 case AArch64::STURQi:
4012 case AArch64::STRQui:
4013 return AArch64::STRQroX;
4014 case AArch64::LDURDi:
4015 case AArch64::LDRDui:
4016 return AArch64::LDRDroX;
4017 case AArch64::STURDi:
4018 case AArch64::STRDui:
4019 return AArch64::STRDroX;
4020 case AArch64::LDURXi:
4021 case AArch64::LDRXui:
4022 return AArch64::LDRXroX;
4023 case AArch64::STURXi:
4024 case AArch64::STRXui:
4025 return AArch64::STRXroX;
4026 case AArch64::LDURWi:
4027 case AArch64::LDRWui:
4028 return AArch64::LDRWroX;
4029 case AArch64::LDURSWi:
4030 case AArch64::LDRSWui:
4031 return AArch64::LDRSWroX;
4032 case AArch64::STURWi:
4033 case AArch64::STRWui:
4034 return AArch64::STRWroX;
4035 case AArch64::LDURHi:
4036 case AArch64::LDRHui:
4037 return AArch64::LDRHroX;
4038 case AArch64::STURHi:
4039 case AArch64::STRHui:
4040 return AArch64::STRHroX;
4041 case AArch64::LDURHHi:
4042 case AArch64::LDRHHui:
4043 return AArch64::LDRHHroX;
4044 case AArch64::STURHHi:
4045 case AArch64::STRHHui:
4046 return AArch64::STRHHroX;
4047 case AArch64::LDURSHXi:
4048 case AArch64::LDRSHXui:
4049 return AArch64::LDRSHXroX;
4050 case AArch64::LDURSHWi:
4051 case AArch64::LDRSHWui:
4052 return AArch64::LDRSHWroX;
4053 case AArch64::LDURBi:
4054 case AArch64::LDRBui:
4055 return AArch64::LDRBroX;
4056 case AArch64::LDURBBi:
4057 case AArch64::LDRBBui:
4058 return AArch64::LDRBBroX;
4059 case AArch64::LDURSBXi:
4060 case AArch64::LDRSBXui:
4061 return AArch64::LDRSBXroX;
4062 case AArch64::LDURSBWi:
4063 case AArch64::LDRSBWui:
4064 return AArch64::LDRSBWroX;
4065 case AArch64::STURBi:
4066 case AArch64::STRBui:
4067 return AArch64::STRBroX;
4068 case AArch64::STURBBi:
4069 case AArch64::STRBBui:
4070 return AArch64::STRBBroX;
4071 }
4072}
4073
4074// Given an opcode for an instruction with a [Reg, #Imm] addressing mode, return
4075// the opcode of an instruction performing the same operation, but using the
4076// [Reg, #Imm] addressing mode with scaled offset.
4077unsigned scaledOffsetOpcode(unsigned Opcode, unsigned &Scale) {
4078 switch (Opcode) {
4079 default:
4080 llvm_unreachable("Address folding not implemented for instruction");
4081
4082 case AArch64::LDURQi:
4083 Scale = 16;
4084 return AArch64::LDRQui;
4085 case AArch64::STURQi:
4086 Scale = 16;
4087 return AArch64::STRQui;
4088 case AArch64::LDURDi:
4089 Scale = 8;
4090 return AArch64::LDRDui;
4091 case AArch64::STURDi:
4092 Scale = 8;
4093 return AArch64::STRDui;
4094 case AArch64::LDURXi:
4095 Scale = 8;
4096 return AArch64::LDRXui;
4097 case AArch64::STURXi:
4098 Scale = 8;
4099 return AArch64::STRXui;
4100 case AArch64::LDURWi:
4101 Scale = 4;
4102 return AArch64::LDRWui;
4103 case AArch64::LDURSWi:
4104 Scale = 4;
4105 return AArch64::LDRSWui;
4106 case AArch64::STURWi:
4107 Scale = 4;
4108 return AArch64::STRWui;
4109 case AArch64::LDURHi:
4110 Scale = 2;
4111 return AArch64::LDRHui;
4112 case AArch64::STURHi:
4113 Scale = 2;
4114 return AArch64::STRHui;
4115 case AArch64::LDURHHi:
4116 Scale = 2;
4117 return AArch64::LDRHHui;
4118 case AArch64::STURHHi:
4119 Scale = 2;
4120 return AArch64::STRHHui;
4121 case AArch64::LDURSHXi:
4122 Scale = 2;
4123 return AArch64::LDRSHXui;
4124 case AArch64::LDURSHWi:
4125 Scale = 2;
4126 return AArch64::LDRSHWui;
4127 case AArch64::LDURBi:
4128 Scale = 1;
4129 return AArch64::LDRBui;
4130 case AArch64::LDURBBi:
4131 Scale = 1;
4132 return AArch64::LDRBBui;
4133 case AArch64::LDURSBXi:
4134 Scale = 1;
4135 return AArch64::LDRSBXui;
4136 case AArch64::LDURSBWi:
4137 Scale = 1;
4138 return AArch64::LDRSBWui;
4139 case AArch64::STURBi:
4140 Scale = 1;
4141 return AArch64::STRBui;
4142 case AArch64::STURBBi:
4143 Scale = 1;
4144 return AArch64::STRBBui;
4145 case AArch64::LDRQui:
4146 case AArch64::STRQui:
4147 Scale = 16;
4148 return Opcode;
4149 case AArch64::LDRDui:
4150 case AArch64::STRDui:
4151 case AArch64::LDRXui:
4152 case AArch64::STRXui:
4153 Scale = 8;
4154 return Opcode;
4155 case AArch64::LDRWui:
4156 case AArch64::LDRSWui:
4157 case AArch64::STRWui:
4158 Scale = 4;
4159 return Opcode;
4160 case AArch64::LDRHui:
4161 case AArch64::STRHui:
4162 case AArch64::LDRHHui:
4163 case AArch64::STRHHui:
4164 case AArch64::LDRSHXui:
4165 case AArch64::LDRSHWui:
4166 Scale = 2;
4167 return Opcode;
4168 case AArch64::LDRBui:
4169 case AArch64::LDRBBui:
4170 case AArch64::LDRSBXui:
4171 case AArch64::LDRSBWui:
4172 case AArch64::STRBui:
4173 case AArch64::STRBBui:
4174 Scale = 1;
4175 return Opcode;
4176 }
4177}
4178
4179// Given an opcode for an instruction with a [Reg, #Imm] addressing mode, return
4180// the opcode of an instruction performing the same operation, but using the
4181// [Reg, #Imm] addressing mode with unscaled offset.
4182unsigned unscaledOffsetOpcode(unsigned Opcode) {
4183 switch (Opcode) {
4184 default:
4185 llvm_unreachable("Address folding not implemented for instruction");
4186
4187 case AArch64::LDURQi:
4188 case AArch64::STURQi:
4189 case AArch64::LDURDi:
4190 case AArch64::STURDi:
4191 case AArch64::LDURXi:
4192 case AArch64::STURXi:
4193 case AArch64::LDURWi:
4194 case AArch64::LDURSWi:
4195 case AArch64::STURWi:
4196 case AArch64::LDURHi:
4197 case AArch64::STURHi:
4198 case AArch64::LDURHHi:
4199 case AArch64::STURHHi:
4200 case AArch64::LDURSHXi:
4201 case AArch64::LDURSHWi:
4202 case AArch64::LDURBi:
4203 case AArch64::STURBi:
4204 case AArch64::LDURBBi:
4205 case AArch64::STURBBi:
4206 case AArch64::LDURSBWi:
4207 case AArch64::LDURSBXi:
4208 return Opcode;
4209 case AArch64::LDRQui:
4210 return AArch64::LDURQi;
4211 case AArch64::STRQui:
4212 return AArch64::STURQi;
4213 case AArch64::LDRDui:
4214 return AArch64::LDURDi;
4215 case AArch64::STRDui:
4216 return AArch64::STURDi;
4217 case AArch64::LDRXui:
4218 return AArch64::LDURXi;
4219 case AArch64::STRXui:
4220 return AArch64::STURXi;
4221 case AArch64::LDRWui:
4222 return AArch64::LDURWi;
4223 case AArch64::LDRSWui:
4224 return AArch64::LDURSWi;
4225 case AArch64::STRWui:
4226 return AArch64::STURWi;
4227 case AArch64::LDRHui:
4228 return AArch64::LDURHi;
4229 case AArch64::STRHui:
4230 return AArch64::STURHi;
4231 case AArch64::LDRHHui:
4232 return AArch64::LDURHHi;
4233 case AArch64::STRHHui:
4234 return AArch64::STURHHi;
4235 case AArch64::LDRSHXui:
4236 return AArch64::LDURSHXi;
4237 case AArch64::LDRSHWui:
4238 return AArch64::LDURSHWi;
4239 case AArch64::LDRBBui:
4240 return AArch64::LDURBBi;
4241 case AArch64::LDRBui:
4242 return AArch64::LDURBi;
4243 case AArch64::STRBBui:
4244 return AArch64::STURBBi;
4245 case AArch64::STRBui:
4246 return AArch64::STURBi;
4247 case AArch64::LDRSBWui:
4248 return AArch64::LDURSBWi;
4249 case AArch64::LDRSBXui:
4250 return AArch64::LDURSBXi;
4251 }
4252}
4253
4254// Given the opcode of a memory load/store instruction, return the opcode of an
4255// instruction performing the same operation, but using
4256// the [Reg, Reg, {s,u}xtw #N] addressing mode with sign-/zero-extend of the
4257// offset register.
4258static unsigned offsetExtendOpcode(unsigned Opcode) {
4259 switch (Opcode) {
4260 default:
4261 llvm_unreachable("Address folding not implemented for instruction");
4262
4263 case AArch64::LDRQroX:
4264 case AArch64::LDURQi:
4265 case AArch64::LDRQui:
4266 return AArch64::LDRQroW;
4267 case AArch64::STRQroX:
4268 case AArch64::STURQi:
4269 case AArch64::STRQui:
4270 return AArch64::STRQroW;
4271 case AArch64::LDRDroX:
4272 case AArch64::LDURDi:
4273 case AArch64::LDRDui:
4274 return AArch64::LDRDroW;
4275 case AArch64::STRDroX:
4276 case AArch64::STURDi:
4277 case AArch64::STRDui:
4278 return AArch64::STRDroW;
4279 case AArch64::LDRXroX:
4280 case AArch64::LDURXi:
4281 case AArch64::LDRXui:
4282 return AArch64::LDRXroW;
4283 case AArch64::STRXroX:
4284 case AArch64::STURXi:
4285 case AArch64::STRXui:
4286 return AArch64::STRXroW;
4287 case AArch64::LDRWroX:
4288 case AArch64::LDURWi:
4289 case AArch64::LDRWui:
4290 return AArch64::LDRWroW;
4291 case AArch64::LDRSWroX:
4292 case AArch64::LDURSWi:
4293 case AArch64::LDRSWui:
4294 return AArch64::LDRSWroW;
4295 case AArch64::STRWroX:
4296 case AArch64::STURWi:
4297 case AArch64::STRWui:
4298 return AArch64::STRWroW;
4299 case AArch64::LDRHroX:
4300 case AArch64::LDURHi:
4301 case AArch64::LDRHui:
4302 return AArch64::LDRHroW;
4303 case AArch64::STRHroX:
4304 case AArch64::STURHi:
4305 case AArch64::STRHui:
4306 return AArch64::STRHroW;
4307 case AArch64::LDRHHroX:
4308 case AArch64::LDURHHi:
4309 case AArch64::LDRHHui:
4310 return AArch64::LDRHHroW;
4311 case AArch64::STRHHroX:
4312 case AArch64::STURHHi:
4313 case AArch64::STRHHui:
4314 return AArch64::STRHHroW;
4315 case AArch64::LDRSHXroX:
4316 case AArch64::LDURSHXi:
4317 case AArch64::LDRSHXui:
4318 return AArch64::LDRSHXroW;
4319 case AArch64::LDRSHWroX:
4320 case AArch64::LDURSHWi:
4321 case AArch64::LDRSHWui:
4322 return AArch64::LDRSHWroW;
4323 case AArch64::LDRBroX:
4324 case AArch64::LDURBi:
4325 case AArch64::LDRBui:
4326 return AArch64::LDRBroW;
4327 case AArch64::LDRBBroX:
4328 case AArch64::LDURBBi:
4329 case AArch64::LDRBBui:
4330 return AArch64::LDRBBroW;
4331 case AArch64::LDRSBXroX:
4332 case AArch64::LDURSBXi:
4333 case AArch64::LDRSBXui:
4334 return AArch64::LDRSBXroW;
4335 case AArch64::LDRSBWroX:
4336 case AArch64::LDURSBWi:
4337 case AArch64::LDRSBWui:
4338 return AArch64::LDRSBWroW;
4339 case AArch64::STRBroX:
4340 case AArch64::STURBi:
4341 case AArch64::STRBui:
4342 return AArch64::STRBroW;
4343 case AArch64::STRBBroX:
4344 case AArch64::STURBBi:
4345 case AArch64::STRBBui:
4346 return AArch64::STRBBroW;
4347 }
4348}
4349
4351 const ExtAddrMode &AM) const {
4352
4353 const DebugLoc &DL = MemI.getDebugLoc();
4354 MachineBasicBlock &MBB = *MemI.getParent();
4355 MachineRegisterInfo &MRI = MemI.getMF()->getRegInfo();
4356
4358 if (AM.ScaledReg) {
4359 // The new instruction will be in the form `ldr Rt, [Xn, Xm, lsl #imm]`.
4360 unsigned Opcode = regOffsetOpcode(MemI.getOpcode());
4361 MRI.constrainRegClass(AM.BaseReg, &AArch64::GPR64spRegClass);
4362 auto B = BuildMI(MBB, MemI, DL, get(Opcode))
4363 .addReg(MemI.getOperand(0).getReg(),
4364 getDefRegState(MemI.mayLoad()))
4365 .addReg(AM.BaseReg)
4366 .addReg(AM.ScaledReg)
4367 .addImm(0)
4368 .addImm(AM.Scale > 1)
4369 .setMemRefs(MemI.memoperands())
4370 .setMIFlags(MemI.getFlags());
4371 return B.getInstr();
4372 }
4373
4374 assert(AM.ScaledReg == 0 && AM.Scale == 0 &&
4375 "Addressing mode not supported for folding");
4376
4377 // The new instruction will be in the form `ld[u]r Rt, [Xn, #imm]`.
4378 unsigned Scale = 1;
4379 unsigned Opcode = MemI.getOpcode();
4380 if (isInt<9>(AM.Displacement))
4381 Opcode = unscaledOffsetOpcode(Opcode);
4382 else
4383 Opcode = scaledOffsetOpcode(Opcode, Scale);
4384
4385 auto B =
4386 BuildMI(MBB, MemI, DL, get(Opcode))
4387 .addReg(MemI.getOperand(0).getReg(), getDefRegState(MemI.mayLoad()))
4388 .addReg(AM.BaseReg)
4389 .addImm(AM.Displacement / Scale)
4390 .setMemRefs(MemI.memoperands())
4391 .setMIFlags(MemI.getFlags());
4392 return B.getInstr();
4393 }
4394
4397 // The new instruction will be in the form `ldr Rt, [Xn, Wm, {s,u}xtw #N]`.
4398 assert(AM.ScaledReg && !AM.Displacement &&
4399 "Address offset can be a register or an immediate, but not both");
4400 unsigned Opcode = offsetExtendOpcode(MemI.getOpcode());
4401 MRI.constrainRegClass(AM.BaseReg, &AArch64::GPR64spRegClass);
4402 // Make sure the offset register is in the correct register class.
4403 Register OffsetReg = AM.ScaledReg;
4404 const TargetRegisterClass *RC = MRI.getRegClass(OffsetReg);
4405 if (RC->hasSuperClassEq(&AArch64::GPR64RegClass)) {
4406 OffsetReg = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
4407 BuildMI(MBB, MemI, DL, get(TargetOpcode::COPY), OffsetReg)
4408 .addReg(AM.ScaledReg, {}, AArch64::sub_32);
4409 }
4410 auto B =
4411 BuildMI(MBB, MemI, DL, get(Opcode))
4412 .addReg(MemI.getOperand(0).getReg(), getDefRegState(MemI.mayLoad()))
4413 .addReg(AM.BaseReg)
4414 .addReg(OffsetReg)
4416 .addImm(AM.Scale != 1)
4417 .setMemRefs(MemI.memoperands())
4418 .setMIFlags(MemI.getFlags());
4419
4420 return B.getInstr();
4421 }
4422
4424 "Function must not be called with an addressing mode it can't handle");
4425}
4426
4427/// Return true if the opcode is a post-index ld/st instruction, which really
4428/// loads from base+0.
4429static bool isPostIndexLdStOpcode(unsigned Opcode) {
4430 switch (Opcode) {
4431 default:
4432 return false;
4433 case AArch64::LD1Fourv16b_POST:
4434 case AArch64::LD1Fourv1d_POST:
4435 case AArch64::LD1Fourv2d_POST:
4436 case AArch64::LD1Fourv2s_POST:
4437 case AArch64::LD1Fourv4h_POST:
4438 case AArch64::LD1Fourv4s_POST:
4439 case AArch64::LD1Fourv8b_POST:
4440 case AArch64::LD1Fourv8h_POST:
4441 case AArch64::LD1Onev16b_POST:
4442 case AArch64::LD1Onev1d_POST:
4443 case AArch64::LD1Onev2d_POST:
4444 case AArch64::LD1Onev2s_POST:
4445 case AArch64::LD1Onev4h_POST:
4446 case AArch64::LD1Onev4s_POST:
4447 case AArch64::LD1Onev8b_POST:
4448 case AArch64::LD1Onev8h_POST:
4449 case AArch64::LD1Rv16b_POST:
4450 case AArch64::LD1Rv1d_POST:
4451 case AArch64::LD1Rv2d_POST:
4452 case AArch64::LD1Rv2s_POST:
4453 case AArch64::LD1Rv4h_POST:
4454 case AArch64::LD1Rv4s_POST:
4455 case AArch64::LD1Rv8b_POST:
4456 case AArch64::LD1Rv8h_POST:
4457 case AArch64::LD1Threev16b_POST:
4458 case AArch64::LD1Threev1d_POST:
4459 case AArch64::LD1Threev2d_POST:
4460 case AArch64::LD1Threev2s_POST:
4461 case AArch64::LD1Threev4h_POST:
4462 case AArch64::LD1Threev4s_POST:
4463 case AArch64::LD1Threev8b_POST:
4464 case AArch64::LD1Threev8h_POST:
4465 case AArch64::LD1Twov16b_POST:
4466 case AArch64::LD1Twov1d_POST:
4467 case AArch64::LD1Twov2d_POST:
4468 case AArch64::LD1Twov2s_POST:
4469 case AArch64::LD1Twov4h_POST:
4470 case AArch64::LD1Twov4s_POST:
4471 case AArch64::LD1Twov8b_POST:
4472 case AArch64::LD1Twov8h_POST:
4473 case AArch64::LD1i16_POST:
4474 case AArch64::LD1i32_POST:
4475 case AArch64::LD1i64_POST:
4476 case AArch64::LD1i8_POST:
4477 case AArch64::LD2Rv16b_POST:
4478 case AArch64::LD2Rv1d_POST:
4479 case AArch64::LD2Rv2d_POST:
4480 case AArch64::LD2Rv2s_POST:
4481 case AArch64::LD2Rv4h_POST:
4482 case AArch64::LD2Rv4s_POST:
4483 case AArch64::LD2Rv8b_POST:
4484 case AArch64::LD2Rv8h_POST:
4485 case AArch64::LD2Twov16b_POST:
4486 case AArch64::LD2Twov2d_POST:
4487 case AArch64::LD2Twov2s_POST:
4488 case AArch64::LD2Twov4h_POST:
4489 case AArch64::LD2Twov4s_POST:
4490 case AArch64::LD2Twov8b_POST:
4491 case AArch64::LD2Twov8h_POST:
4492 case AArch64::LD2i16_POST:
4493 case AArch64::LD2i32_POST:
4494 case AArch64::LD2i64_POST:
4495 case AArch64::LD2i8_POST:
4496 case AArch64::LD3Rv16b_POST:
4497 case AArch64::LD3Rv1d_POST:
4498 case AArch64::LD3Rv2d_POST:
4499 case AArch64::LD3Rv2s_POST:
4500 case AArch64::LD3Rv4h_POST:
4501 case AArch64::LD3Rv4s_POST:
4502 case AArch64::LD3Rv8b_POST:
4503 case AArch64::LD3Rv8h_POST:
4504 case AArch64::LD3Threev16b_POST:
4505 case AArch64::LD3Threev2d_POST:
4506 case AArch64::LD3Threev2s_POST:
4507 case AArch64::LD3Threev4h_POST:
4508 case AArch64::LD3Threev4s_POST:
4509 case AArch64::LD3Threev8b_POST:
4510 case AArch64::LD3Threev8h_POST:
4511 case AArch64::LD3i16_POST:
4512 case AArch64::LD3i32_POST:
4513 case AArch64::LD3i64_POST:
4514 case AArch64::LD3i8_POST:
4515 case AArch64::LD4Fourv16b_POST:
4516 case AArch64::LD4Fourv2d_POST:
4517 case AArch64::LD4Fourv2s_POST:
4518 case AArch64::LD4Fourv4h_POST:
4519 case AArch64::LD4Fourv4s_POST:
4520 case AArch64::LD4Fourv8b_POST:
4521 case AArch64::LD4Fourv8h_POST:
4522 case AArch64::LD4Rv16b_POST:
4523 case AArch64::LD4Rv1d_POST:
4524 case AArch64::LD4Rv2d_POST:
4525 case AArch64::LD4Rv2s_POST:
4526 case AArch64::LD4Rv4h_POST:
4527 case AArch64::LD4Rv4s_POST:
4528 case AArch64::LD4Rv8b_POST:
4529 case AArch64::LD4Rv8h_POST:
4530 case AArch64::LD4i16_POST:
4531 case AArch64::LD4i32_POST:
4532 case AArch64::LD4i64_POST:
4533 case AArch64::LD4i8_POST:
4534 case AArch64::LDAPRWpost:
4535 case AArch64::LDAPRXpost:
4536 case AArch64::LDIAPPWpost:
4537 case AArch64::LDIAPPXpost:
4538 case AArch64::LDPDpost:
4539 case AArch64::LDPQpost:
4540 case AArch64::LDPSWpost:
4541 case AArch64::LDPSpost:
4542 case AArch64::LDPWpost:
4543 case AArch64::LDPXpost:
4544 case AArch64::LDRBBpost:
4545 case AArch64::LDRBpost:
4546 case AArch64::LDRDpost:
4547 case AArch64::LDRHHpost:
4548 case AArch64::LDRHpost:
4549 case AArch64::LDRQpost:
4550 case AArch64::LDRSBWpost:
4551 case AArch64::LDRSBXpost:
4552 case AArch64::LDRSHWpost:
4553 case AArch64::LDRSHXpost:
4554 case AArch64::LDRSWpost:
4555 case AArch64::LDRSpost:
4556 case AArch64::LDRWpost:
4557 case AArch64::LDRXpost:
4558 case AArch64::ST1Fourv16b_POST:
4559 case AArch64::ST1Fourv1d_POST:
4560 case AArch64::ST1Fourv2d_POST:
4561 case AArch64::ST1Fourv2s_POST:
4562 case AArch64::ST1Fourv4h_POST:
4563 case AArch64::ST1Fourv4s_POST:
4564 case AArch64::ST1Fourv8b_POST:
4565 case AArch64::ST1Fourv8h_POST:
4566 case AArch64::ST1Onev16b_POST:
4567 case AArch64::ST1Onev1d_POST:
4568 case AArch64::ST1Onev2d_POST:
4569 case AArch64::ST1Onev2s_POST:
4570 case AArch64::ST1Onev4h_POST:
4571 case AArch64::ST1Onev4s_POST:
4572 case AArch64::ST1Onev8b_POST:
4573 case AArch64::ST1Onev8h_POST:
4574 case AArch64::ST1Threev16b_POST:
4575 case AArch64::ST1Threev1d_POST:
4576 case AArch64::ST1Threev2d_POST:
4577 case AArch64::ST1Threev2s_POST:
4578 case AArch64::ST1Threev4h_POST:
4579 case AArch64::ST1Threev4s_POST:
4580 case AArch64::ST1Threev8b_POST:
4581 case AArch64::ST1Threev8h_POST:
4582 case AArch64::ST1Twov16b_POST:
4583 case AArch64::ST1Twov1d_POST:
4584 case AArch64::ST1Twov2d_POST:
4585 case AArch64::ST1Twov2s_POST:
4586 case AArch64::ST1Twov4h_POST:
4587 case AArch64::ST1Twov4s_POST:
4588 case AArch64::ST1Twov8b_POST:
4589 case AArch64::ST1Twov8h_POST:
4590 case AArch64::ST1i16_POST:
4591 case AArch64::ST1i32_POST:
4592 case AArch64::ST1i64_POST:
4593 case AArch64::ST1i8_POST:
4594 case AArch64::ST2GPostIndex:
4595 case AArch64::ST2Twov16b_POST:
4596 case AArch64::ST2Twov2d_POST:
4597 case AArch64::ST2Twov2s_POST:
4598 case AArch64::ST2Twov4h_POST:
4599 case AArch64::ST2Twov4s_POST:
4600 case AArch64::ST2Twov8b_POST:
4601 case AArch64::ST2Twov8h_POST:
4602 case AArch64::ST2i16_POST:
4603 case AArch64::ST2i32_POST:
4604 case AArch64::ST2i64_POST:
4605 case AArch64::ST2i8_POST:
4606 case AArch64::ST3Threev16b_POST:
4607 case AArch64::ST3Threev2d_POST:
4608 case AArch64::ST3Threev2s_POST:
4609 case AArch64::ST3Threev4h_POST:
4610 case AArch64::ST3Threev4s_POST:
4611 case AArch64::ST3Threev8b_POST:
4612 case AArch64::ST3Threev8h_POST:
4613 case AArch64::ST3i16_POST:
4614 case AArch64::ST3i32_POST:
4615 case AArch64::ST3i64_POST:
4616 case AArch64::ST3i8_POST:
4617 case AArch64::ST4Fourv16b_POST:
4618 case AArch64::ST4Fourv2d_POST:
4619 case AArch64::ST4Fourv2s_POST:
4620 case AArch64::ST4Fourv4h_POST:
4621 case AArch64::ST4Fourv4s_POST:
4622 case AArch64::ST4Fourv8b_POST:
4623 case AArch64::ST4Fourv8h_POST:
4624 case AArch64::ST4i16_POST:
4625 case AArch64::ST4i32_POST:
4626 case AArch64::ST4i64_POST:
4627 case AArch64::ST4i8_POST:
4628 case AArch64::STGPostIndex:
4629 case AArch64::STGPpost:
4630 case AArch64::STPDpost:
4631 case AArch64::STPQpost:
4632 case AArch64::STPSpost:
4633 case AArch64::STPWpost:
4634 case AArch64::STPXpost:
4635 case AArch64::STRBBpost:
4636 case AArch64::STRBpost:
4637 case AArch64::STRDpost:
4638 case AArch64::STRHHpost:
4639 case AArch64::STRHpost:
4640 case AArch64::STRQpost:
4641 case AArch64::STRSpost:
4642 case AArch64::STRWpost:
4643 case AArch64::STRXpost:
4644 case AArch64::STZ2GPostIndex:
4645 case AArch64::STZGPostIndex:
4646 return true;
4647 }
4648}
4649
4651 const MachineInstr &LdSt, const MachineOperand *&BaseOp, int64_t &Offset,
4652 bool &OffsetIsScalable, TypeSize &Width,
4653 const TargetRegisterInfo *TRI) const {
4654 assert(LdSt.mayLoadOrStore() && "Expected a memory operation.");
4655 // Handle only loads/stores with base register followed by immediate offset.
4656 if (LdSt.getNumExplicitOperands() == 3) {
4657 // Non-paired instruction (e.g., ldr x1, [x0, #8]).
4658 if ((!LdSt.getOperand(1).isReg() && !LdSt.getOperand(1).isFI()) ||
4659 !LdSt.getOperand(2).isImm())
4660 return false;
4661 } else if (LdSt.getNumExplicitOperands() == 4) {
4662 // Paired instruction (e.g., ldp x1, x2, [x0, #8]).
4663 if (!LdSt.getOperand(1).isReg() ||
4664 (!LdSt.getOperand(2).isReg() && !LdSt.getOperand(2).isFI()) ||
4665 !LdSt.getOperand(3).isImm())
4666 return false;
4667 } else
4668 return false;
4669
4670 // Get the scaling factor for the instruction and set the width for the
4671 // instruction.
4672 TypeSize Scale(0U, false);
4673 int64_t Dummy1, Dummy2;
4674
4675 // If this returns false, then it's an instruction we don't want to handle.
4676 if (!getMemOpInfo(LdSt.getOpcode(), Scale, Width, Dummy1, Dummy2))
4677 return false;
4678
4679 // Compute the offset. Offset is calculated as the immediate operand
4680 // multiplied by the scaling factor. Unscaled instructions have scaling factor
4681 // set to 1. Postindex are a special case which have an offset of 0.
4682 if (isPostIndexLdStOpcode(LdSt.getOpcode())) {
4683 BaseOp = &LdSt.getOperand(2);
4684 Offset = 0;
4685 } else if (LdSt.getNumExplicitOperands() == 3) {
4686 BaseOp = &LdSt.getOperand(1);
4687 Offset = LdSt.getOperand(2).getImm() * Scale.getKnownMinValue();
4688 } else {
4689 assert(LdSt.getNumExplicitOperands() == 4 && "invalid number of operands");
4690 BaseOp = &LdSt.getOperand(2);
4691 Offset = LdSt.getOperand(3).getImm() * Scale.getKnownMinValue();
4692 }
4693 OffsetIsScalable = Scale.isScalable();
4694
4695 return BaseOp->isReg() || BaseOp->isFI();
4696}
4697
4700 assert(LdSt.mayLoadOrStore() && "Expected a memory operation.");
4701 MachineOperand &OfsOp = LdSt.getOperand(LdSt.getNumExplicitOperands() - 1);
4702 assert(OfsOp.isImm() && "Offset operand wasn't immediate.");
4703 return OfsOp;
4704}
4705
4706bool AArch64InstrInfo::getMemOpInfo(unsigned Opcode, TypeSize &Scale,
4707 TypeSize &Width, int64_t &MinOffset,
4708 int64_t &MaxOffset) {
4709 switch (Opcode) {
4710 // Not a memory operation or something we want to handle.
4711 default:
4712 Scale = Width = TypeSize::getFixed(0);
4713 MinOffset = MaxOffset = 0;
4714 return false;
4715 // LDR / STR
4716 case AArch64::LDRQui:
4717 case AArch64::STRQui:
4718 Scale = Width = TypeSize::getFixed(16);
4719 MinOffset = 0;
4720 MaxOffset = 4095;
4721 break;
4722 case AArch64::LDRXui:
4723 case AArch64::LDRDui:
4724 case AArch64::STRXui:
4725 case AArch64::STRDui:
4726 case AArch64::PRFMui:
4727 Scale = Width = TypeSize::getFixed(8);
4728 MinOffset = 0;
4729 MaxOffset = 4095;
4730 break;
4731 case AArch64::LDRWui:
4732 case AArch64::LDRSui:
4733 case AArch64::LDRSWui:
4734 case AArch64::STRWui:
4735 case AArch64::STRSui:
4736 Scale = Width = TypeSize::getFixed(4);
4737 MinOffset = 0;
4738 MaxOffset = 4095;
4739 break;
4740 case AArch64::LDRHui:
4741 case AArch64::LDRHHui:
4742 case AArch64::LDRSHWui:
4743 case AArch64::LDRSHXui:
4744 case AArch64::STRHui:
4745 case AArch64::STRHHui:
4746 Scale = Width = TypeSize::getFixed(2);
4747 MinOffset = 0;
4748 MaxOffset = 4095;
4749 break;
4750 case AArch64::LDRBui:
4751 case AArch64::LDRBBui:
4752 case AArch64::LDRSBWui:
4753 case AArch64::LDRSBXui:
4754 case AArch64::STRBui:
4755 case AArch64::STRBBui:
4756 Scale = Width = TypeSize::getFixed(1);
4757 MinOffset = 0;
4758 MaxOffset = 4095;
4759 break;
4760 // post/pre inc
4761 case AArch64::STRQpre:
4762 case AArch64::LDRQpost:
4763 Scale = TypeSize::getFixed(1);
4764 Width = TypeSize::getFixed(16);
4765 MinOffset = -256;
4766 MaxOffset = 255;
4767 break;
4768 case AArch64::LDRDpost:
4769 case AArch64::LDRDpre:
4770 case AArch64::LDRXpost:
4771 case AArch64::LDRXpre:
4772 case AArch64::STRDpost:
4773 case AArch64::STRDpre:
4774 case AArch64::STRXpost:
4775 case AArch64::STRXpre:
4776 Scale = TypeSize::getFixed(1);
4777 Width = TypeSize::getFixed(8);
4778 MinOffset = -256;
4779 MaxOffset = 255;
4780 break;
4781 case AArch64::STRWpost:
4782 case AArch64::STRWpre:
4783 case AArch64::LDRWpost:
4784 case AArch64::LDRWpre:
4785 case AArch64::STRSpost:
4786 case AArch64::STRSpre:
4787 case AArch64::LDRSpost:
4788 case AArch64::LDRSpre:
4789 Scale = TypeSize::getFixed(1);
4790 Width = TypeSize::getFixed(4);
4791 MinOffset = -256;
4792 MaxOffset = 255;
4793 break;
4794 case AArch64::LDRHpost:
4795 case AArch64::LDRHpre:
4796 case AArch64::STRHpost:
4797 case AArch64::STRHpre:
4798 case AArch64::LDRHHpost:
4799 case AArch64::LDRHHpre:
4800 case AArch64::STRHHpost:
4801 case AArch64::STRHHpre:
4802 Scale = TypeSize::getFixed(1);
4803 Width = TypeSize::getFixed(2);
4804 MinOffset = -256;
4805 MaxOffset = 255;
4806 break;
4807 case AArch64::LDRBpost:
4808 case AArch64::LDRBpre:
4809 case AArch64::STRBpost:
4810 case AArch64::STRBpre:
4811 case AArch64::LDRBBpost:
4812 case AArch64::LDRBBpre:
4813 case AArch64::STRBBpost:
4814 case AArch64::STRBBpre:
4815 Scale = Width = TypeSize::getFixed(1);
4816 MinOffset = -256;
4817 MaxOffset = 255;
4818 break;
4819 // Unscaled
4820 case AArch64::LDURQi:
4821 case AArch64::STURQi:
4822 Scale = TypeSize::getFixed(1);
4823 Width = TypeSize::getFixed(16);
4824 MinOffset = -256;
4825 MaxOffset = 255;
4826 break;
4827 case AArch64::LDURXi:
4828 case AArch64::LDURDi:
4829 case AArch64::LDAPURXi:
4830 case AArch64::STURXi:
4831 case AArch64::STURDi:
4832 case AArch64::STLURXi:
4833 case AArch64::PRFUMi:
4834 Scale = TypeSize::getFixed(1);
4835 Width = TypeSize::getFixed(8);
4836 MinOffset = -256;
4837 MaxOffset = 255;
4838 break;
4839 case AArch64::LDURWi:
4840 case AArch64::LDURSi:
4841 case AArch64::LDURSWi:
4842 case AArch64::LDAPURi:
4843 case AArch64::LDAPURSWi:
4844 case AArch64::STURWi:
4845 case AArch64::STURSi:
4846 case AArch64::STLURWi:
4847 Scale = TypeSize::getFixed(1);
4848 Width = TypeSize::getFixed(4);
4849 MinOffset = -256;
4850 MaxOffset = 255;
4851 break;
4852 case AArch64::LDURHi:
4853 case AArch64::LDURHHi:
4854 case AArch64::LDURSHXi:
4855 case AArch64::LDURSHWi:
4856 case AArch64::LDAPURHi:
4857 case AArch64::LDAPURSHWi:
4858 case AArch64::LDAPURSHXi:
4859 case AArch64::STURHi:
4860 case AArch64::STURHHi:
4861 case AArch64::STLURHi:
4862 Scale = TypeSize::getFixed(1);
4863 Width = TypeSize::getFixed(2);
4864 MinOffset = -256;
4865 MaxOffset = 255;
4866 break;
4867 case AArch64::LDURBi:
4868 case AArch64::LDURBBi:
4869 case AArch64::LDURSBXi:
4870 case AArch64::LDURSBWi:
4871 case AArch64::LDAPURBi:
4872 case AArch64::LDAPURSBWi:
4873 case AArch64::LDAPURSBXi:
4874 case AArch64::STURBi:
4875 case AArch64::STURBBi:
4876 case AArch64::STLURBi:
4877 Scale = Width = TypeSize::getFixed(1);
4878 MinOffset = -256;
4879 MaxOffset = 255;
4880 break;
4881 // LDP / STP (including pre/post inc)
4882 case AArch64::LDPQi:
4883 case AArch64::LDNPQi:
4884 case AArch64::STPQi:
4885 case AArch64::STNPQi:
4886 case AArch64::LDPQpost:
4887 case AArch64::LDPQpre:
4888 case AArch64::STPQpost:
4889 case AArch64::STPQpre:
4890 Scale = TypeSize::getFixed(16);
4891 Width = TypeSize::getFixed(16 * 2);
4892 MinOffset = -64;
4893 MaxOffset = 63;
4894 break;
4895 case AArch64::LDPXi:
4896 case AArch64::LDPDi:
4897 case AArch64::LDNPXi:
4898 case AArch64::LDNPDi:
4899 case AArch64::STPXi:
4900 case AArch64::STPDi:
4901 case AArch64::STNPXi:
4902 case AArch64::STNPDi:
4903 case AArch64::LDPDpost:
4904 case AArch64::LDPDpre:
4905 case AArch64::LDPXpost:
4906 case AArch64::LDPXpre:
4907 case AArch64::STPDpost:
4908 case AArch64::STPDpre:
4909 case AArch64::STPXpost:
4910 case AArch64::STPXpre:
4911 Scale = TypeSize::getFixed(8);
4912 Width = TypeSize::getFixed(8 * 2);
4913 MinOffset = -64;
4914 MaxOffset = 63;
4915 break;
4916 case AArch64::LDPWi:
4917 case AArch64::LDPSi:
4918 case AArch64::LDNPWi:
4919 case AArch64::LDNPSi:
4920 case AArch64::STPWi:
4921 case AArch64::STPSi:
4922 case AArch64::STNPWi:
4923 case AArch64::STNPSi:
4924 case AArch64::LDPSpost:
4925 case AArch64::LDPSpre:
4926 case AArch64::LDPWpost:
4927 case AArch64::LDPWpre:
4928 case AArch64::STPSpost:
4929 case AArch64::STPSpre:
4930 case AArch64::STPWpost:
4931 case AArch64::STPWpre:
4932 Scale = TypeSize::getFixed(4);
4933 Width = TypeSize::getFixed(4 * 2);
4934 MinOffset = -64;
4935 MaxOffset = 63;
4936 break;
4937 case AArch64::StoreSwiftAsyncContext:
4938 // Store is an STRXui, but there might be an ADDXri in the expansion too.
4939 Scale = TypeSize::getFixed(1);
4940 Width = TypeSize::getFixed(8);
4941 MinOffset = 0;
4942 MaxOffset = 4095;
4943 break;
4944 case AArch64::ADDG:
4945 Scale = TypeSize::getFixed(16);
4946 Width = TypeSize::getFixed(0);
4947 MinOffset = 0;
4948 MaxOffset = 63;
4949 break;
4950 case AArch64::TAGPstack:
4951 Scale = TypeSize::getFixed(16);
4952 Width = TypeSize::getFixed(0);
4953 // TAGP with a negative offset turns into SUBP, which has a maximum offset
4954 // of 63 (not 64!).
4955 MinOffset = -63;
4956 MaxOffset = 63;
4957 break;
4958 case AArch64::LDG:
4959 case AArch64::STGi:
4960 case AArch64::STGPreIndex:
4961 case AArch64::STGPostIndex:
4962 case AArch64::STZGi:
4963 case AArch64::STZGPreIndex:
4964 case AArch64::STZGPostIndex:
4965 Scale = Width = TypeSize::getFixed(16);
4966 MinOffset = -256;
4967 MaxOffset = 255;
4968 break;
4969 // SVE
4970 case AArch64::STR_ZZZZXI:
4971 case AArch64::STR_ZZZZXI_STRIDED_CONTIGUOUS:
4972 case AArch64::LDR_ZZZZXI:
4973 case AArch64::LDR_ZZZZXI_STRIDED_CONTIGUOUS:
4974 Scale = TypeSize::getScalable(16);
4975 Width = TypeSize::getScalable(16 * 4);
4976 MinOffset = -256;
4977 MaxOffset = 252;
4978 break;
4979 case AArch64::STR_ZZZXI:
4980 case AArch64::LDR_ZZZXI:
4981 Scale = TypeSize::getScalable(16);
4982 Width = TypeSize::getScalable(16 * 3);
4983 MinOffset = -256;
4984 MaxOffset = 253;
4985 break;
4986 case AArch64::STR_ZZXI:
4987 case AArch64::STR_ZZXI_STRIDED_CONTIGUOUS:
4988 case AArch64::LDR_ZZXI:
4989 case AArch64::LDR_ZZXI_STRIDED_CONTIGUOUS:
4990 Scale = TypeSize::getScalable(16);
4991 Width = TypeSize::getScalable(16 * 2);
4992 MinOffset = -256;
4993 MaxOffset = 254;
4994 break;
4995 case AArch64::LDR_PXI:
4996 case AArch64::STR_PXI:
4997 Scale = Width = TypeSize::getScalable(2);
4998 MinOffset = -256;
4999 MaxOffset = 255;
5000 break;
5001 case AArch64::LDR_PPXI:
5002 case AArch64::STR_PPXI:
5003 Scale = TypeSize::getScalable(2);
5004 Width = TypeSize::getScalable(2 * 2);
5005 MinOffset = -256;
5006 MaxOffset = 254;
5007 break;
5008 case AArch64::LDR_ZXI:
5009 case AArch64::STR_ZXI:
5010 Scale = Width = TypeSize::getScalable(16);
5011 MinOffset = -256;
5012 MaxOffset = 255;
5013 break;
5014 case AArch64::LD1B_IMM:
5015 case AArch64::LD1H_IMM:
5016 case AArch64::LD1W_IMM:
5017 case AArch64::LD1D_IMM:
5018 case AArch64::LDNT1B_ZRI:
5019 case AArch64::LDNT1H_ZRI:
5020 case AArch64::LDNT1W_ZRI:
5021 case AArch64::LDNT1D_ZRI:
5022 case AArch64::ST1B_IMM:
5023 case AArch64::ST1H_IMM:
5024 case AArch64::ST1W_IMM:
5025 case AArch64::ST1D_IMM:
5026 case AArch64::STNT1B_ZRI:
5027 case AArch64::STNT1H_ZRI:
5028 case AArch64::STNT1W_ZRI:
5029 case AArch64::STNT1D_ZRI:
5030 case AArch64::LDNF1B_IMM:
5031 case AArch64::LDNF1H_IMM:
5032 case AArch64::LDNF1W_IMM:
5033 case AArch64::LDNF1D_IMM:
5034 // A full vectors worth of data
5035 // Width = mbytes * elements
5036 Scale = Width = TypeSize::getScalable(16);
5037 MinOffset = -8;
5038 MaxOffset = 7;
5039 break;
5040 case AArch64::LD2B_IMM:
5041 case AArch64::LD2H_IMM:
5042 case AArch64::LD2W_IMM:
5043 case AArch64::LD2D_IMM:
5044 case AArch64::ST2B_IMM:
5045 case AArch64::ST2H_IMM:
5046 case AArch64::ST2W_IMM:
5047 case AArch64::ST2D_IMM:
5048 case AArch64::LD1B_2Z_IMM:
5049 case AArch64::LD1B_2Z_STRIDED_IMM:
5050 case AArch64::LD1H_2Z_IMM:
5051 case AArch64::LD1H_2Z_STRIDED_IMM:
5052 case AArch64::LD1W_2Z_IMM:
5053 case AArch64::LD1W_2Z_STRIDED_IMM:
5054 case AArch64::LD1D_2Z_IMM:
5055 case AArch64::LD1D_2Z_STRIDED_IMM:
5056 case AArch64::LD1B_2Z_IMM_PSEUDO:
5057 case AArch64::LD1H_2Z_IMM_PSEUDO:
5058 case AArch64::LD1W_2Z_IMM_PSEUDO:
5059 case AArch64::LD1D_2Z_IMM_PSEUDO:
5060 case AArch64::ST1B_2Z_IMM:
5061 case AArch64::ST1B_2Z_STRIDED_IMM:
5062 case AArch64::ST1H_2Z_IMM:
5063 case AArch64::ST1H_2Z_STRIDED_IMM:
5064 case AArch64::ST1W_2Z_IMM:
5065 case AArch64::ST1W_2Z_STRIDED_IMM:
5066 case AArch64::ST1D_2Z_IMM:
5067 case AArch64::ST1D_2Z_STRIDED_IMM:
5068 case AArch64::LDNT1B_2Z_IMM_PSEUDO:
5069 case AArch64::LDNT1B_2Z_IMM:
5070 case AArch64::LDNT1B_2Z_STRIDED_IMM:
5071 case AArch64::LDNT1H_2Z_IMM_PSEUDO:
5072 case AArch64::LDNT1H_2Z_IMM:
5073 case AArch64::LDNT1H_2Z_STRIDED_IMM:
5074 case AArch64::LDNT1W_2Z_IMM_PSEUDO:
5075 case AArch64::LDNT1W_2Z_IMM:
5076 case AArch64::LDNT1W_2Z_STRIDED_IMM:
5077 case AArch64::LDNT1D_2Z_IMM_PSEUDO:
5078 case AArch64::LDNT1D_2Z_IMM:
5079 case AArch64::LDNT1D_2Z_STRIDED_IMM:
5080 case AArch64::STNT1B_2Z_IMM:
5081 case AArch64::STNT1B_2Z_STRIDED_IMM:
5082 case AArch64::STNT1H_2Z_IMM:
5083 case AArch64::STNT1H_2Z_STRIDED_IMM:
5084 case AArch64::STNT1W_2Z_IMM:
5085 case AArch64::STNT1W_2Z_STRIDED_IMM:
5086 case AArch64::STNT1D_2Z_IMM:
5087 case AArch64::STNT1D_2Z_STRIDED_IMM:
5088 case AArch64::ST1B_2Z_IMM_PSEUDO:
5089 case AArch64::ST1H_2Z_IMM_PSEUDO:
5090 case AArch64::ST1W_2Z_IMM_PSEUDO:
5091 case AArch64::ST1D_2Z_IMM_PSEUDO:
5092 case AArch64::STNT1B_2Z_IMM_PSEUDO:
5093 case AArch64::STNT1H_2Z_IMM_PSEUDO:
5094 case AArch64::STNT1W_2Z_IMM_PSEUDO:
5095 case AArch64::STNT1D_2Z_IMM_PSEUDO:
5096 Scale = Width = TypeSize::getScalable(16 * 2);
5097 MinOffset = -8;
5098 MaxOffset = 7;
5099 break;
5100 case AArch64::LD3B_IMM:
5101 case AArch64::LD3H_IMM:
5102 case AArch64::LD3W_IMM:
5103 case AArch64::LD3D_IMM:
5104 case AArch64::ST3B_IMM:
5105 case AArch64::ST3H_IMM:
5106 case AArch64::ST3W_IMM:
5107 case AArch64::ST3D_IMM:
5108 Scale = Width = TypeSize::getScalable(16 * 3);
5109 MinOffset = -8;
5110 MaxOffset = 7;
5111 break;
5112 case AArch64::LD4B_IMM:
5113 case AArch64::LD4H_IMM:
5114 case AArch64::LD4W_IMM:
5115 case AArch64::LD4D_IMM:
5116 case AArch64::ST4B_IMM:
5117 case AArch64::ST4H_IMM:
5118 case AArch64::ST4W_IMM:
5119 case AArch64::ST4D_IMM:
5120 case AArch64::LD1B_4Z_IMM:
5121 case AArch64::LD1B_4Z_STRIDED_IMM:
5122 case AArch64::LD1H_4Z_IMM:
5123 case AArch64::LD1H_4Z_STRIDED_IMM:
5124 case AArch64::LD1W_4Z_IMM:
5125 case AArch64::LD1W_4Z_STRIDED_IMM:
5126 case AArch64::LD1D_4Z_IMM:
5127 case AArch64::LD1D_4Z_STRIDED_IMM:
5128 case AArch64::LD1B_4Z_IMM_PSEUDO:
5129 case AArch64::LD1H_4Z_IMM_PSEUDO:
5130 case AArch64::LD1W_4Z_IMM_PSEUDO:
5131 case AArch64::LD1D_4Z_IMM_PSEUDO:
5132 case AArch64::ST1B_4Z_IMM:
5133 case AArch64::ST1B_4Z_STRIDED_IMM:
5134 case AArch64::ST1H_4Z_IMM:
5135 case AArch64::ST1H_4Z_STRIDED_IMM:
5136 case AArch64::ST1W_4Z_IMM:
5137 case AArch64::ST1W_4Z_STRIDED_IMM:
5138 case AArch64::ST1D_4Z_IMM:
5139 case AArch64::ST1D_4Z_STRIDED_IMM:
5140 case AArch64::LDNT1B_4Z_IMM_PSEUDO:
5141 case AArch64::LDNT1B_4Z_IMM:
5142 case AArch64::LDNT1B_4Z_STRIDED_IMM:
5143 case AArch64::LDNT1H_4Z_IMM_PSEUDO:
5144 case AArch64::LDNT1H_4Z_IMM:
5145 case AArch64::LDNT1H_4Z_STRIDED_IMM:
5146 case AArch64::LDNT1W_4Z_IMM_PSEUDO:
5147 case AArch64::LDNT1W_4Z_IMM:
5148 case AArch64::LDNT1W_4Z_STRIDED_IMM:
5149 case AArch64::LDNT1D_4Z_IMM_PSEUDO:
5150 case AArch64::LDNT1D_4Z_IMM:
5151 case AArch64::LDNT1D_4Z_STRIDED_IMM:
5152 case AArch64::STNT1B_4Z_IMM:
5153 case AArch64::STNT1B_4Z_STRIDED_IMM:
5154 case AArch64::STNT1H_4Z_IMM:
5155 case AArch64::STNT1H_4Z_STRIDED_IMM:
5156 case AArch64::STNT1W_4Z_IMM:
5157 case AArch64::STNT1W_4Z_STRIDED_IMM:
5158 case AArch64::STNT1D_4Z_IMM:
5159 case AArch64::STNT1D_4Z_STRIDED_IMM:
5160 case AArch64::ST1B_4Z_IMM_PSEUDO:
5161 case AArch64::ST1H_4Z_IMM_PSEUDO:
5162 case AArch64::ST1W_4Z_IMM_PSEUDO:
5163 case AArch64::ST1D_4Z_IMM_PSEUDO:
5164 case AArch64::STNT1B_4Z_IMM_PSEUDO:
5165 case AArch64::STNT1H_4Z_IMM_PSEUDO:
5166 case AArch64::STNT1W_4Z_IMM_PSEUDO:
5167 case AArch64::STNT1D_4Z_IMM_PSEUDO:
5168 Scale = Width = TypeSize::getScalable(16 * 4);
5169 MinOffset = -8;
5170 MaxOffset = 7;
5171 break;
5172 case AArch64::LD1B_H_IMM:
5173 case AArch64::LD1SB_H_IMM:
5174 case AArch64::LD1H_S_IMM:
5175 case AArch64::LD1SH_S_IMM:
5176 case AArch64::LD1W_D_IMM:
5177 case AArch64::LD1SW_D_IMM:
5178 case AArch64::ST1B_H_IMM:
5179 case AArch64::ST1H_S_IMM:
5180 case AArch64::ST1W_D_IMM:
5181 case AArch64::LDNF1B_H_IMM:
5182 case AArch64::LDNF1SB_H_IMM:
5183 case AArch64::LDNF1H_S_IMM:
5184 case AArch64::LDNF1SH_S_IMM:
5185 case AArch64::LDNF1W_D_IMM:
5186 case AArch64::LDNF1SW_D_IMM:
5187 // A half vector worth of data
5188 // Width = mbytes * elements
5189 Scale = Width = TypeSize::getScalable(8);
5190 MinOffset = -8;
5191 MaxOffset = 7;
5192 break;
5193 case AArch64::LD1B_S_IMM:
5194 case AArch64::LD1SB_S_IMM:
5195 case AArch64::LD1H_D_IMM:
5196 case AArch64::LD1SH_D_IMM:
5197 case AArch64::ST1B_S_IMM:
5198 case AArch64::ST1H_D_IMM:
5199 case AArch64::LDNF1B_S_IMM:
5200 case AArch64::LDNF1SB_S_IMM:
5201 case AArch64::LDNF1H_D_IMM:
5202 case AArch64::LDNF1SH_D_IMM:
5203 // A quarter vector worth of data
5204 // Width = mbytes * elements
5205 Scale = Width = TypeSize::getScalable(4);
5206 MinOffset = -8;
5207 MaxOffset = 7;
5208 break;
5209 case AArch64::LD1B_D_IMM:
5210 case AArch64::LD1SB_D_IMM:
5211 case AArch64::ST1B_D_IMM:
5212 case AArch64::LDNF1B_D_IMM:
5213 case AArch64::LDNF1SB_D_IMM:
5214 // A eighth vector worth of data
5215 // Width = mbytes * elements
5216 Scale = Width = TypeSize::getScalable(2);
5217 MinOffset = -8;
5218 MaxOffset = 7;
5219 break;
5220 case AArch64::ST2Gi:
5221 case AArch64::ST2GPreIndex:
5222 case AArch64::ST2GPostIndex:
5223 case AArch64::STZ2Gi:
5224 case AArch64::STZ2GPreIndex:
5225 case AArch64::STZ2GPostIndex:
5226 Scale = TypeSize::getFixed(16);
5227 Width = TypeSize::getFixed(32);
5228 MinOffset = -256;
5229 MaxOffset = 255;
5230 break;
5231 case AArch64::STGPi:
5232 case AArch64::STGPpost:
5233 case AArch64::STGPpre:
5234 Scale = Width = TypeSize::getFixed(16);
5235 MinOffset = -64;
5236 MaxOffset = 63;
5237 break;
5238 case AArch64::LD1RB_IMM:
5239 case AArch64::LD1RB_H_IMM:
5240 case AArch64::LD1RB_S_IMM:
5241 case AArch64::LD1RB_D_IMM:
5242 case AArch64::LD1RSB_H_IMM:
5243 case AArch64::LD1RSB_S_IMM:
5244 case AArch64::LD1RSB_D_IMM:
5245 Scale = Width = TypeSize::getFixed(1);
5246 MinOffset = 0;
5247 MaxOffset = 63;
5248 break;
5249 case AArch64::LD1RH_IMM:
5250 case AArch64::LD1RH_S_IMM:
5251 case AArch64::LD1RH_D_IMM:
5252 case AArch64::LD1RSH_S_IMM:
5253 case AArch64::LD1RSH_D_IMM:
5254 Scale = Width = TypeSize::getFixed(2);
5255 MinOffset = 0;
5256 MaxOffset = 63;
5257 break;
5258 case AArch64::LD1RW_IMM:
5259 case AArch64::LD1RW_D_IMM:
5260 case AArch64::LD1RSW_IMM:
5261 Scale = Width = TypeSize::getFixed(4);
5262 MinOffset = 0;
5263 MaxOffset = 63;
5264 break;
5265 case AArch64::LD1RD_IMM:
5266 Scale = Width = TypeSize::getFixed(8);
5267 MinOffset = 0;
5268 MaxOffset = 63;
5269 break;
5270 }
5271
5272 return true;
5273}
5274
5275// Scaling factor for unscaled load or store.
5277 switch (Opc) {
5278 default:
5279 llvm_unreachable("Opcode has unknown scale!");
5280 case AArch64::LDRBui:
5281 case AArch64::LDRBBui:
5282 case AArch64::LDURBBi:
5283 case AArch64::LDRSBWui:
5284 case AArch64::LDURSBWi:
5285 case AArch64::STRBui:
5286 case AArch64::STRBBui:
5287 case AArch64::STURBBi:
5288 return 1;
5289 case AArch64::LDRHui:
5290 case AArch64::LDRHHui:
5291 case AArch64::LDURHHi:
5292 case AArch64::LDRSHWui:
5293 case AArch64::LDURSHWi:
5294 case AArch64::STRHui:
5295 case AArch64::STRHHui:
5296 case AArch64::STURHHi:
5297 return 2;
5298 case AArch64::LDRSui:
5299 case AArch64::LDURSi:
5300 case AArch64::LDRSpre:
5301 case AArch64::LDRSWui:
5302 case AArch64::LDURSWi:
5303 case AArch64::LDRSWpre:
5304 case AArch64::LDRWpre:
5305 case AArch64::LDRWui:
5306 case AArch64::LDURWi:
5307 case AArch64::STRSui:
5308 case AArch64::STURSi:
5309 case AArch64::STRSpre:
5310 case AArch64::STRWui:
5311 case AArch64::STURWi:
5312 case AArch64::STRWpre:
5313 case AArch64::LDPSi:
5314 case AArch64::LDPSWi:
5315 case AArch64::LDPWi:
5316 case AArch64::STPSi:
5317 case AArch64::STPWi:
5318 return 4;
5319 case AArch64::LDRDui:
5320 case AArch64::LDURDi:
5321 case AArch64::LDRDpre:
5322 case AArch64::LDRXui:
5323 case AArch64::LDURXi:
5324 case AArch64::LDRXpre:
5325 case AArch64::STRDui:
5326 case AArch64::STURDi:
5327 case AArch64::STRDpre:
5328 case AArch64::STRXui:
5329 case AArch64::STURXi:
5330 case AArch64::STRXpre:
5331 case AArch64::LDPDi:
5332 case AArch64::LDPXi:
5333 case AArch64::STPDi:
5334 case AArch64::STPXi:
5335 return 8;
5336 case AArch64::LDRQui:
5337 case AArch64::LDURQi:
5338 case AArch64::STRQui:
5339 case AArch64::STURQi:
5340 case AArch64::STRQpre:
5341 case AArch64::LDPQi:
5342 case AArch64::LDRQpre:
5343 case AArch64::STPQi:
5344 case AArch64::STGi:
5345 case AArch64::STZGi:
5346 case AArch64::ST2Gi:
5347 case AArch64::STZ2Gi:
5348 case AArch64::STGPi:
5349 return 16;
5350 }
5351}
5352
5354 switch (MI.getOpcode()) {
5355 default:
5356 return false;
5357 case AArch64::LDRWpre:
5358 case AArch64::LDRXpre:
5359 case AArch64::LDRSWpre:
5360 case AArch64::LDRSpre:
5361 case AArch64::LDRDpre:
5362 case AArch64::LDRQpre:
5363 return true;
5364 }
5365}
5366
5368 switch (MI.getOpcode()) {
5369 default:
5370 return false;
5371 case AArch64::STRWpre:
5372 case AArch64::STRXpre:
5373 case AArch64::STRSpre:
5374 case AArch64::STRDpre:
5375 case AArch64::STRQpre:
5376 return true;
5377 }
5378}
5379
5381 return isPreLd(MI) || isPreSt(MI);
5382}
5383
5385 switch (MI.getOpcode()) {
5386 default:
5387 return false;
5388 case AArch64::LDURBBi:
5389 case AArch64::LDURHHi:
5390 case AArch64::LDURWi:
5391 case AArch64::LDRBBui:
5392 case AArch64::LDRHHui:
5393 case AArch64::LDRWui:
5394 case AArch64::LDRBBroX:
5395 case AArch64::LDRHHroX:
5396 case AArch64::LDRWroX:
5397 case AArch64::LDRBBroW:
5398 case AArch64::LDRHHroW:
5399 case AArch64::LDRWroW:
5400 return true;
5401 }
5402}
5403
5405 switch (MI.getOpcode()) {
5406 default:
5407 return false;
5408 case AArch64::LDURSBWi:
5409 case AArch64::LDURSHWi:
5410 case AArch64::LDURSBXi:
5411 case AArch64::LDURSHXi:
5412 case AArch64::LDURSWi:
5413 case AArch64::LDRSBWui:
5414 case AArch64::LDRSHWui:
5415 case AArch64::LDRSBXui:
5416 case AArch64::LDRSHXui:
5417 case AArch64::LDRSWui:
5418 case AArch64::LDRSBWroX:
5419 case AArch64::LDRSHWroX:
5420 case AArch64::LDRSBXroX:
5421 case AArch64::LDRSHXroX:
5422 case AArch64::LDRSWroX:
5423 case AArch64::LDRSBWroW:
5424 case AArch64::LDRSHWroW:
5425 case AArch64::LDRSBXroW:
5426 case AArch64::LDRSHXroW:
5427 case AArch64::LDRSWroW:
5428 return true;
5429 }
5430}
5431
5433 switch (MI.getOpcode()) {
5434 default:
5435 return false;
5436 case AArch64::LDPSi:
5437 case AArch64::LDPSWi:
5438 case AArch64::LDPDi:
5439 case AArch64::LDPQi:
5440 case AArch64::LDPWi:
5441 case AArch64::LDPXi:
5442 case AArch64::STPSi:
5443 case AArch64::STPDi:
5444 case AArch64::STPQi:
5445 case AArch64::STPWi:
5446 case AArch64::STPXi:
5447 case AArch64::STGPi:
5448 return true;
5449 }
5450}
5451
5453 assert(MI.mayLoadOrStore() && "Load or store instruction expected");
5454 unsigned Idx =
5456 : 1;
5457 return MI.getOperand(Idx);
5458}
5459
5460const MachineOperand &
5462 assert(MI.mayLoadOrStore() && "Load or store instruction expected");
5463 unsigned Idx =
5465 : 2;
5466 return MI.getOperand(Idx);
5467}
5468
5469const MachineOperand &
5471 switch (MI.getOpcode()) {
5472 default:
5473 llvm_unreachable("Unexpected opcode");
5474 case AArch64::LDRBroX:
5475 case AArch64::LDRBBroX:
5476 case AArch64::LDRSBXroX:
5477 case AArch64::LDRSBWroX:
5478 case AArch64::LDRHroX:
5479 case AArch64::LDRHHroX:
5480 case AArch64::LDRSHXroX:
5481 case AArch64::LDRSHWroX:
5482 case AArch64::LDRWroX:
5483 case AArch64::LDRSroX:
5484 case AArch64::LDRSWroX:
5485 case AArch64::LDRDroX:
5486 case AArch64::LDRXroX:
5487 case AArch64::LDRQroX:
5488 return MI.getOperand(4);
5489 }
5490}
5491
5493 Register Reg) {
5494 if (MI.getParent() == nullptr)
5495 return nullptr;
5496 const MachineFunction *MF = MI.getParent()->getParent();
5497 return MF ? MF->getRegInfo().getRegClassOrNull(Reg) : nullptr;
5498}
5499
5501 auto IsHFPR = [&](const MachineOperand &Op) {
5502 if (!Op.isReg())
5503 return false;
5504 auto Reg = Op.getReg();
5505 if (Reg.isPhysical())
5506 return AArch64::FPR16RegClass.contains(Reg);
5507 const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
5508 return TRC == &AArch64::FPR16RegClass ||
5509 TRC == &AArch64::FPR16_loRegClass;
5510 };
5511 return llvm::any_of(MI.operands(), IsHFPR);
5512}
5513
5515 auto IsQFPR = [&](const MachineOperand &Op) {
5516 if (!Op.isReg())
5517 return false;
5518 auto Reg = Op.getReg();
5519 if (Reg.isPhysical())
5520 return AArch64::FPR128RegClass.contains(Reg);
5521 const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
5522 return TRC == &AArch64::FPR128RegClass ||
5523 TRC == &AArch64::FPR128_loRegClass;
5524 };
5525 return llvm::any_of(MI.operands(), IsQFPR);
5526}
5527
5529 switch (MI.getOpcode()) {
5530 case AArch64::BRK:
5531 case AArch64::HLT:
5532 case AArch64::PACIASP:
5533 case AArch64::PACIBSP:
5534 // Implicit BTI behavior.
5535 return true;
5536 case AArch64::PAUTH_PROLOGUE:
5537 // PAUTH_PROLOGUE expands to PACI(A|B)SP.
5538 return true;
5539 case AArch64::HINT: {
5540 unsigned Imm = MI.getOperand(0).getImm();
5541 // Explicit BTI instruction.
5542 if (Imm == 32 || Imm == 34 || Imm == 36 || Imm == 38)
5543 return true;
5544 // PACI(A|B)SP instructions.
5545 if (Imm == 25 || Imm == 27)
5546 return true;
5547 return false;
5548 }
5549 default:
5550 return false;
5551 }
5552}
5553
5555 if (Reg == 0)
5556 return false;
5557 assert(Reg.isPhysical() && "Expected physical register in isFpOrNEON");
5558 return AArch64::FPR128RegClass.contains(Reg) ||
5559 AArch64::FPR64RegClass.contains(Reg) ||
5560 AArch64::FPR32RegClass.contains(Reg) ||
5561 AArch64::FPR16RegClass.contains(Reg) ||
5562 AArch64::FPR8RegClass.contains(Reg);
5563}
5564
5566 auto IsFPR = [&](const MachineOperand &Op) {
5567 if (!Op.isReg())
5568 return false;
5569 auto Reg = Op.getReg();
5570 if (Reg.isPhysical())
5571 return isFpOrNEON(Reg);
5572
5573 const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
5574 return TRC == &AArch64::FPR128RegClass ||
5575 TRC == &AArch64::FPR128_loRegClass ||
5576 TRC == &AArch64::FPR64RegClass ||
5577 TRC == &AArch64::FPR64_loRegClass ||
5578 TRC == &AArch64::FPR32RegClass || TRC == &AArch64::FPR16RegClass ||
5579 TRC == &AArch64::FPR8RegClass;
5580 };
5581 return llvm::any_of(MI.operands(), IsFPR);
5582}
5583
5584// Scale the unscaled offsets. Returns false if the unscaled offset can't be
5585// scaled.
5586static bool scaleOffset(unsigned Opc, int64_t &Offset) {
5588
5589 // If the byte-offset isn't a multiple of the stride, we can't scale this
5590 // offset.
5591 if (Offset % Scale != 0)
5592 return false;
5593
5594 // Convert the byte-offset used by unscaled into an "element" offset used
5595 // by the scaled pair load/store instructions.
5596 Offset /= Scale;
5597 return true;
5598}
5599
5600static bool canPairLdStOpc(unsigned FirstOpc, unsigned SecondOpc) {
5601 if (FirstOpc == SecondOpc)
5602 return true;
5603 // We can also pair sign-ext and zero-ext instructions.
5604 switch (FirstOpc) {
5605 default:
5606 return false;
5607 case AArch64::STRSui:
5608 case AArch64::STURSi:
5609 return SecondOpc == AArch64::STRSui || SecondOpc == AArch64::STURSi;
5610 case AArch64::STRDui:
5611 case AArch64::STURDi:
5612 return SecondOpc == AArch64::STRDui || SecondOpc == AArch64::STURDi;
5613 case AArch64::STRQui:
5614 case AArch64::STURQi:
5615 return SecondOpc == AArch64::STRQui || SecondOpc == AArch64::STURQi;
5616 case AArch64::STRWui:
5617 case AArch64::STURWi:
5618 return SecondOpc == AArch64::STRWui || SecondOpc == AArch64::STURWi;
5619 case AArch64::STRXui:
5620 case AArch64::STURXi:
5621 return SecondOpc == AArch64::STRXui || SecondOpc == AArch64::STURXi;
5622 case AArch64::LDRSui:
5623 case AArch64::LDURSi:
5624 return SecondOpc == AArch64::LDRSui || SecondOpc == AArch64::LDURSi;
5625 case AArch64::LDRDui:
5626 case AArch64::LDURDi:
5627 return SecondOpc == AArch64::LDRDui || SecondOpc == AArch64::LDURDi;
5628 case AArch64::LDRQui:
5629 case AArch64::LDURQi:
5630 return SecondOpc == AArch64::LDRQui || SecondOpc == AArch64::LDURQi;
5631 case AArch64::LDRWui:
5632 case AArch64::LDURWi:
5633 return SecondOpc == AArch64::LDRSWui || SecondOpc == AArch64::LDURSWi;
5634 case AArch64::LDRSWui:
5635 case AArch64::LDURSWi:
5636 return SecondOpc == AArch64::LDRWui || SecondOpc == AArch64::LDURWi;
5637 case AArch64::LDRXui:
5638 case AArch64::LDURXi:
5639 return SecondOpc == AArch64::LDRXui || SecondOpc == AArch64::LDURXi;
5640 }
5641 // These instructions can't be paired based on their opcodes.
5642 return false;
5643}
5644
5645static bool shouldClusterFI(const MachineFrameInfo &MFI, int FI1,
5646 int64_t Offset1, unsigned Opcode1, int FI2,
5647 int64_t Offset2, unsigned Opcode2) {
5648 // Accesses through fixed stack object frame indices may access a different
5649 // fixed stack slot. Check that the object offsets + offsets match.
5650 if (MFI.isFixedObjectIndex(FI1) && MFI.isFixedObjectIndex(FI2)) {
5651 int64_t ObjectOffset1 = MFI.getObjectOffset(FI1);
5652 int64_t ObjectOffset2 = MFI.getObjectOffset(FI2);
5653 assert(ObjectOffset1 <= ObjectOffset2 && "Object offsets are not ordered.");
5654 // Convert to scaled object offsets.
5655 int Scale1 = AArch64InstrInfo::getMemScale(Opcode1);
5656 if (ObjectOffset1 % Scale1 != 0)
5657 return false;
5658 ObjectOffset1 /= Scale1;
5659 int Scale2 = AArch64InstrInfo::getMemScale(Opcode2);
5660 if (ObjectOffset2 % Scale2 != 0)
5661 return false;
5662 ObjectOffset2 /= Scale2;
5663 ObjectOffset1 += Offset1;
5664 ObjectOffset2 += Offset2;
5665 return ObjectOffset1 + 1 == ObjectOffset2;
5666 }
5667
5668 return FI1 == FI2;
5669}
5670
5671/// Detect opportunities for ldp/stp formation.
5672///
5673/// Only called for LdSt for which getMemOperandWithOffset returns true.
5675 ArrayRef<const MachineOperand *> BaseOps1, int64_t OpOffset1,
5676 bool OffsetIsScalable1, ArrayRef<const MachineOperand *> BaseOps2,
5677 int64_t OpOffset2, bool OffsetIsScalable2, unsigned ClusterSize,
5678 unsigned NumBytes) const {
5679 assert(BaseOps1.size() == 1 && BaseOps2.size() == 1);
5680 const MachineOperand &BaseOp1 = *BaseOps1.front();
5681 const MachineOperand &BaseOp2 = *BaseOps2.front();
5682 const MachineInstr &FirstLdSt = *BaseOp1.getParent();
5683 const MachineInstr &SecondLdSt = *BaseOp2.getParent();
5684 if (BaseOp1.getType() != BaseOp2.getType())
5685 return false;
5686
5687 assert((BaseOp1.isReg() || BaseOp1.isFI()) &&
5688 "Only base registers and frame indices are supported.");
5689
5690 // Check for both base regs and base FI.
5691 if (BaseOp1.isReg() && BaseOp1.getReg() != BaseOp2.getReg())
5692 return false;
5693
5694 // Only cluster up to a single pair.
5695 if (ClusterSize > 2)
5696 return false;
5697
5698 if (!isPairableLdStInst(FirstLdSt) || !isPairableLdStInst(SecondLdSt))
5699 return false;
5700
5701 // Can we pair these instructions based on their opcodes?
5702 unsigned FirstOpc = FirstLdSt.getOpcode();
5703 unsigned SecondOpc = SecondLdSt.getOpcode();
5704 if (!canPairLdStOpc(FirstOpc, SecondOpc))
5705 return false;
5706
5707 // Can't merge volatiles or load/stores that have a hint to avoid pair
5708 // formation, for example.
5709 if (!isCandidateToMergeOrPair(FirstLdSt) ||
5710 !isCandidateToMergeOrPair(SecondLdSt))
5711 return false;
5712
5713 // isCandidateToMergeOrPair guarantees that operand 2 is an immediate.
5714 int64_t Offset1 = FirstLdSt.getOperand(2).getImm();
5715 if (hasUnscaledLdStOffset(FirstOpc) && !scaleOffset(FirstOpc, Offset1))
5716 return false;
5717
5718 int64_t Offset2 = SecondLdSt.getOperand(2).getImm();
5719 if (hasUnscaledLdStOffset(SecondOpc) && !scaleOffset(SecondOpc, Offset2))
5720 return false;
5721
5722 // Pairwise instructions have a 7-bit signed offset field.
5723 if (Offset1 > 63 || Offset1 < -64)
5724 return false;
5725
5726 // The caller should already have ordered First/SecondLdSt by offset.
5727 // Note: except for non-equal frame index bases
5728 if (BaseOp1.isFI()) {
5729 assert((!BaseOp1.isIdenticalTo(BaseOp2) || Offset1 <= Offset2) &&
5730 "Caller should have ordered offsets.");
5731
5732 const MachineFrameInfo &MFI =
5733 FirstLdSt.getParent()->getParent()->getFrameInfo();
5734 return shouldClusterFI(MFI, BaseOp1.getIndex(), Offset1, FirstOpc,
5735 BaseOp2.getIndex(), Offset2, SecondOpc);
5736 }
5737
5738 assert(Offset1 <= Offset2 && "Caller should have ordered offsets.");
5739
5740 return Offset1 + 1 == Offset2;
5741}
5742
5744 MCRegister Reg, unsigned SubIdx,
5745 RegState State,
5746 const TargetRegisterInfo *TRI) {
5747 if (!SubIdx)
5748 return MIB.addReg(Reg, State);
5749
5750 if (Reg.isPhysical())
5751 return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
5752 return MIB.addReg(Reg, State, SubIdx);
5753}
5754
5757 const DebugLoc &DL, MCRegister DestReg,
5758 MCRegister SrcReg, bool KillSrc,
5759 ArrayRef<unsigned> Indices) const {
5760 assert(Subtarget.hasNEON() && "Unexpected register copy without NEON");
5762 uint16_t DestEncoding = TRI->getEncodingValue(DestReg);
5763 uint16_t SrcEncoding = TRI->getEncodingValue(SrcReg);
5764 unsigned NumRegs = Indices.size();
5765 MCRegister DestSubReg = TRI->getSubReg(DestReg, Indices[0]);
5766 assert(!AArch64::PNRRegClass.contains(DestSubReg) &&
5767 "Unexpected predicate tuple copy");
5768 unsigned MaxRegs = AArch64::PPRRegClass.contains(DestSubReg) ? 15 : 31;
5769
5770 int SubReg = 0, End = NumRegs, Incr = 1;
5771 // Copy in reverse if a forward copy will clobber the tuple
5772 if (((DestEncoding - SrcEncoding) & MaxRegs) < NumRegs) {
5773 SubReg = NumRegs - 1;
5774 End = -1;
5775 Incr = -1;
5776 }
5777
5778 for (; SubReg != End; SubReg += Incr) {
5779 DestSubReg = TRI->getSubReg(DestReg, Indices[SubReg]);
5780 MCRegister SrcSubReg = TRI->getSubReg(SrcReg, Indices[SubReg]);
5781 copyPhysRegImpl(MBB, I, DL, DestSubReg, SrcSubReg, KillSrc);
5782 }
5783}
5784
5787 const DebugLoc &DL, MCRegister DestReg,
5788 MCRegister SrcReg, bool KillSrc,
5789 unsigned Opcode, unsigned ZeroReg,
5790 llvm::ArrayRef<unsigned> Indices) const {
5792 unsigned NumRegs = Indices.size();
5793
5794#ifndef NDEBUG
5795 uint16_t DestEncoding = TRI->getEncodingValue(DestReg);
5796 uint16_t SrcEncoding = TRI->getEncodingValue(SrcReg);
5797 assert(DestEncoding % NumRegs == 0 && SrcEncoding % NumRegs == 0 &&
5798 "GPR reg sequences should not be able to overlap");
5799#endif
5800
5801 for (unsigned SubReg = 0; SubReg != NumRegs; ++SubReg) {
5802 const MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opcode));
5803 AddSubReg(MIB, DestReg, Indices[SubReg], RegState::Define, TRI);
5804 MIB.addReg(ZeroReg);
5805 AddSubReg(MIB, SrcReg, Indices[SubReg], getKillRegState(KillSrc), TRI);
5806 MIB.addImm(0);
5807 }
5808}
5809
5810/// Returns true if the instruction at I is in a streaming call site region,
5811/// within a single basic block.
5812/// A "call site streaming region" starts after smstart and ends at smstop
5813/// around a call to a streaming function. This walks backward from I.
5816 MachineFunction &MF = *MBB.getParent();
5818 if (!AFI->hasStreamingModeChanges())
5819 return false;
5820 // Walk backwards to find smstart/smstop
5821 for (MachineInstr &MI : reverse(make_range(MBB.begin(), I))) {
5822 unsigned Opc = MI.getOpcode();
5823 if (Opc == AArch64::MSRpstatesvcrImm1 || Opc == AArch64::MSRpstatePseudo) {
5824 // Check if this is SM change (not ZA)
5825 int64_t PState = MI.getOperand(0).getImm();
5826 if (PState == AArch64SVCR::SVCRSM || PState == AArch64SVCR::SVCRSMZA) {
5827 // Operand 1 is 1 for start, 0 for stop
5828 return MI.getOperand(1).getImm() == 1;
5829 }
5830 }
5831 }
5832 return false;
5833}
5834
5835/// Returns true if in a streaming call site region without SME-FA64.
5836static bool mustAvoidNeonAtMBBI(const AArch64Subtarget &Subtarget,
5839 return !Subtarget.hasSMEFA64() && isInStreamingCallSiteRegion(MBB, I);
5840}
5841
5844 const DebugLoc &DL, Register DestReg,
5845 Register SrcReg, bool KillSrc,
5846 bool RenamableDest,
5847 bool RenamableSrc) const {
5848 if (AArch64::GPR32spRegClass.contains(DestReg) &&
5849 AArch64::GPR32spRegClass.contains(SrcReg)) {
5850 if (DestReg == AArch64::WSP || SrcReg == AArch64::WSP) {
5851 // If either operand is WSP, expand to ADD #0.
5852 if (Subtarget.hasZeroCycleRegMoveGPR64() &&
5853 !Subtarget.hasZeroCycleRegMoveGPR32()) {
5854 // Cyclone recognizes "ADD Xd, Xn, #0" as a zero-cycle register move.
5855 MCRegister DestRegX = RI.getMatchingSuperReg(DestReg, AArch64::sub_32,
5856 &AArch64::GPR64spRegClass);
5857 MCRegister SrcRegX = RI.getMatchingSuperReg(SrcReg, AArch64::sub_32,
5858 &AArch64::GPR64spRegClass);
5859 // This instruction is reading and writing X registers. This may upset
5860 // the register scavenger and machine verifier, so we need to indicate
5861 // that we are reading an undefined value from SrcRegX, but a proper
5862 // value from SrcReg.
5863 BuildMI(MBB, I, DL, get(AArch64::ADDXri), DestRegX)
5864 .addReg(SrcRegX, RegState::Undef)
5865 .addImm(0)
5867 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
5868 ++NumZCRegMoveInstrsGPR;
5869 } else {
5870 BuildMI(MBB, I, DL, get(AArch64::ADDWri), DestReg)
5871 .addReg(SrcReg, getKillRegState(KillSrc))
5872 .addImm(0)
5874 if (Subtarget.hasZeroCycleRegMoveGPR32())
5875 ++NumZCRegMoveInstrsGPR;
5876 }
5877 } else if (Subtarget.hasZeroCycleRegMoveGPR64() &&
5878 !Subtarget.hasZeroCycleRegMoveGPR32()) {
5879 // Cyclone recognizes "ORR Xd, XZR, Xm" as a zero-cycle register move.
5880 MCRegister DestRegX = RI.getMatchingSuperReg(DestReg, AArch64::sub_32,
5881 &AArch64::GPR64spRegClass);
5882 assert(DestRegX.isValid() && "Destination super-reg not valid");
5883 MCRegister SrcRegX = RI.getMatchingSuperReg(SrcReg, AArch64::sub_32,
5884 &AArch64::GPR64spRegClass);
5885 assert(SrcRegX.isValid() && "Source super-reg not valid");
5886 // This instruction is reading and writing X registers. This may upset
5887 // the register scavenger and machine verifier, so we need to indicate
5888 // that we are reading an undefined value from SrcRegX, but a proper
5889 // value from SrcReg.
5890 BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestRegX)
5891 .addReg(AArch64::XZR)
5892 .addReg(SrcRegX, RegState::Undef)
5893 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
5894 ++NumZCRegMoveInstrsGPR;
5895 } else {
5896 // Otherwise, expand to ORR WZR.
5897 BuildMI(MBB, I, DL, get(AArch64::ORRWrr), DestReg)
5898 .addReg(AArch64::WZR)
5899 .addReg(SrcReg, getKillRegState(KillSrc));
5900 if (Subtarget.hasZeroCycleRegMoveGPR32())
5901 ++NumZCRegMoveInstrsGPR;
5902 }
5903 return;
5904 }
5905
5906 // GPR32 zeroing
5907 if (AArch64::GPR32spRegClass.contains(DestReg) && SrcReg == AArch64::WZR) {
5908 if (Subtarget.hasZeroCycleZeroingGPR64() &&
5909 !Subtarget.hasZeroCycleZeroingGPR32()) {
5910 MCRegister DestRegX = RI.getMatchingSuperReg(DestReg, AArch64::sub_32,
5911 &AArch64::GPR64spRegClass);
5912 assert(DestRegX.isValid() && "Destination super-reg not valid");
5913 BuildMI(MBB, I, DL, get(AArch64::MOVZXi), DestRegX)
5914 .addImm(0)
5916 ++NumZCZeroingInstrsGPR;
5917 } else if (Subtarget.hasZeroCycleZeroingGPR32()) {
5918 BuildMI(MBB, I, DL, get(AArch64::MOVZWi), DestReg)
5919 .addImm(0)
5921 ++NumZCZeroingInstrsGPR;
5922 } else {
5923 BuildMI(MBB, I, DL, get(AArch64::ORRWrr), DestReg)
5924 .addReg(AArch64::WZR)
5925 .addReg(AArch64::WZR);
5926 }
5927 return;
5928 }
5929
5930 if (AArch64::GPR64spRegClass.contains(DestReg) &&
5931 AArch64::GPR64spRegClass.contains(SrcReg)) {
5932 if (DestReg == AArch64::SP || SrcReg == AArch64::SP) {
5933 // If either operand is SP, expand to ADD #0.
5934 BuildMI(MBB, I, DL, get(AArch64::ADDXri), DestReg)
5935 .addReg(SrcReg, getKillRegState(KillSrc))
5936 .addImm(0)
5938 if (Subtarget.hasZeroCycleRegMoveGPR64())
5939 ++NumZCRegMoveInstrsGPR;
5940 } else {
5941 // Otherwise, expand to ORR XZR.
5942 BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestReg)
5943 .addReg(AArch64::XZR)
5944 .addReg(SrcReg, getKillRegState(KillSrc));
5945 if (Subtarget.hasZeroCycleRegMoveGPR64())
5946 ++NumZCRegMoveInstrsGPR;
5947 }
5948 return;
5949 }
5950
5951 // GPR64 zeroing
5952 if (AArch64::GPR64spRegClass.contains(DestReg) && SrcReg == AArch64::XZR) {
5953 if (Subtarget.hasZeroCycleZeroingGPR64()) {
5954 BuildMI(MBB, I, DL, get(AArch64::MOVZXi), DestReg)
5955 .addImm(0)
5957 ++NumZCZeroingInstrsGPR;
5958 } else {
5959 BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestReg)
5960 .addReg(AArch64::XZR)
5961 .addReg(AArch64::XZR);
5962 }
5963 return;
5964 }
5965
5966 // Copy a Predicate register by ORRing with itself.
5967 if (AArch64::PPRRegClass.contains(DestReg) &&
5968 AArch64::PPRRegClass.contains(SrcReg)) {
5969 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
5970 "Unexpected SVE register.");
5971 BuildMI(MBB, I, DL, get(AArch64::ORR_PPzPP), DestReg)
5972 .addReg(SrcReg) // Pg
5973 .addReg(SrcReg)
5974 .addReg(SrcReg, getKillRegState(KillSrc));
5975 return;
5976 }
5977
5978 // Copy a predicate-as-counter register by ORRing with itself as if it
5979 // were a regular predicate (mask) register.
5980 bool DestIsPNR = AArch64::PNRRegClass.contains(DestReg);
5981 bool SrcIsPNR = AArch64::PNRRegClass.contains(SrcReg);
5982 if (DestIsPNR || SrcIsPNR) {
5983 auto ToPPR = [](MCRegister R) -> MCRegister {
5984 return (R - AArch64::PN0) + AArch64::P0;
5985 };
5986 MCRegister PPRSrcReg = SrcIsPNR ? ToPPR(SrcReg) : SrcReg.asMCReg();
5987 MCRegister PPRDestReg = DestIsPNR ? ToPPR(DestReg) : DestReg.asMCReg();
5988
5989 if (PPRSrcReg != PPRDestReg) {
5990 auto NewMI = BuildMI(MBB, I, DL, get(AArch64::ORR_PPzPP), PPRDestReg)
5991 .addReg(PPRSrcReg) // Pg
5992 .addReg(PPRSrcReg)
5993 .addReg(PPRSrcReg, getKillRegState(KillSrc));
5994 if (DestIsPNR)
5995 NewMI.addDef(DestReg, RegState::Implicit);
5996 }
5997 return;
5998 }
5999
6000 // Copy a predicate register pair by copying the individual sub-registers.
6001 if (AArch64::PPR2RegClass.contains(DestReg) &&
6002 AArch64::PPR2RegClass.contains(SrcReg)) {
6003 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6004 "Unexpected SVE predicate register.");
6005 static const unsigned Indices[] = {AArch64::psub0, AArch64::psub1};
6006 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6007 return;
6008 }
6009
6010 // Copy a Z register by ORRing with itself.
6011 if (AArch64::ZPRRegClass.contains(DestReg) &&
6012 AArch64::ZPRRegClass.contains(SrcReg)) {
6013 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6014 "Unexpected SVE register.");
6015 BuildMI(MBB, I, DL, get(AArch64::ORR_ZZZ), DestReg)
6016 .addReg(SrcReg)
6017 .addReg(SrcReg, getKillRegState(KillSrc));
6018 return;
6019 }
6020
6021 // Copy a Z register pair by copying the individual sub-registers.
6022 if ((AArch64::ZPR2RegClass.contains(DestReg) ||
6023 AArch64::ZPR2StridedOrContiguousRegClass.contains(DestReg)) &&
6024 (AArch64::ZPR2RegClass.contains(SrcReg) ||
6025 AArch64::ZPR2StridedOrContiguousRegClass.contains(SrcReg))) {
6026 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6027 "Unexpected SVE register.");
6028 static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1};
6029 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6030 return;
6031 }
6032
6033 // Copy a Z register triple by copying the individual sub-registers.
6034 if (AArch64::ZPR3RegClass.contains(DestReg) &&
6035 AArch64::ZPR3RegClass.contains(SrcReg)) {
6036 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6037 "Unexpected SVE register.");
6038 static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1,
6039 AArch64::zsub2};
6040 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6041 return;
6042 }
6043
6044 // Copy a Z register quad by copying the individual sub-registers.
6045 if ((AArch64::ZPR4RegClass.contains(DestReg) ||
6046 AArch64::ZPR4StridedOrContiguousRegClass.contains(DestReg)) &&
6047 (AArch64::ZPR4RegClass.contains(SrcReg) ||
6048 AArch64::ZPR4StridedOrContiguousRegClass.contains(SrcReg))) {
6049 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6050 "Unexpected SVE register.");
6051 static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1,
6052 AArch64::zsub2, AArch64::zsub3};
6053 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6054 return;
6055 }
6056
6057 // Copy a DDDD register quad by copying the individual sub-registers.
6058 if (AArch64::DDDDRegClass.contains(DestReg) &&
6059 AArch64::DDDDRegClass.contains(SrcReg)) {
6060 static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1,
6061 AArch64::dsub2, AArch64::dsub3};
6062 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6063 return;
6064 }
6065
6066 // Copy a DDD register triple by copying the individual sub-registers.
6067 if (AArch64::DDDRegClass.contains(DestReg) &&
6068 AArch64::DDDRegClass.contains(SrcReg)) {
6069 static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1,
6070 AArch64::dsub2};
6071 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6072 return;
6073 }
6074
6075 // Copy a DD register pair by copying the individual sub-registers.
6076 if (AArch64::DDRegClass.contains(DestReg) &&
6077 AArch64::DDRegClass.contains(SrcReg)) {
6078 static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1};
6079 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6080 return;
6081 }
6082
6083 // Copy a QQQQ register quad by copying the individual sub-registers.
6084 if (AArch64::QQQQRegClass.contains(DestReg) &&
6085 AArch64::QQQQRegClass.contains(SrcReg)) {
6086 static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1,
6087 AArch64::qsub2, AArch64::qsub3};
6088 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6089 return;
6090 }
6091
6092 // Copy a QQQ register triple by copying the individual sub-registers.
6093 if (AArch64::QQQRegClass.contains(DestReg) &&
6094 AArch64::QQQRegClass.contains(SrcReg)) {
6095 static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1,
6096 AArch64::qsub2};
6097 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6098 return;
6099 }
6100
6101 // Copy a QQ register pair by copying the individual sub-registers.
6102 if (AArch64::QQRegClass.contains(DestReg) &&
6103 AArch64::QQRegClass.contains(SrcReg)) {
6104 static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1};
6105 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6106 return;
6107 }
6108
6109 if (AArch64::XSeqPairsClassRegClass.contains(DestReg) &&
6110 AArch64::XSeqPairsClassRegClass.contains(SrcReg)) {
6111 static const unsigned Indices[] = {AArch64::sube64, AArch64::subo64};
6112 copyGPRRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRXrs,
6113 AArch64::XZR, Indices);
6114 return;
6115 }
6116
6117 if (AArch64::WSeqPairsClassRegClass.contains(DestReg) &&
6118 AArch64::WSeqPairsClassRegClass.contains(SrcReg)) {
6119 static const unsigned Indices[] = {AArch64::sube32, AArch64::subo32};
6120 copyGPRRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRWrs,
6121 AArch64::WZR, Indices);
6122 return;
6123 }
6124
6125 if (AArch64::FPR128RegClass.contains(DestReg) &&
6126 AArch64::FPR128RegClass.contains(SrcReg)) {
6127 // In streaming regions, NEON is illegal but streaming-SVE is available.
6128 // Use SVE for copies if we're in a streaming region and SME is available.
6129 // With +sme-fa64, NEON is legal in streaming mode so we can use it.
6130 if ((Subtarget.isSVEorStreamingSVEAvailable() &&
6131 !Subtarget.isNeonAvailable()) ||
6132 mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6133 BuildMI(MBB, I, DL, get(AArch64::ORR_ZZZ))
6134 .addReg(AArch64::Z0 + (DestReg - AArch64::Q0), RegState::Define)
6135 .addReg(AArch64::Z0 + (SrcReg - AArch64::Q0))
6136 .addReg(AArch64::Z0 + (SrcReg - AArch64::Q0));
6137 } else if (Subtarget.isNeonAvailable()) {
6138 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestReg)
6139 .addReg(SrcReg)
6140 .addReg(SrcReg, getKillRegState(KillSrc));
6141 if (Subtarget.hasZeroCycleRegMoveFPR128())
6142 ++NumZCRegMoveInstrsFPR;
6143 } else {
6144 BuildMI(MBB, I, DL, get(AArch64::STRQpre))
6145 .addReg(AArch64::SP, RegState::Define)
6146 .addReg(SrcReg, getKillRegState(KillSrc))
6147 .addReg(AArch64::SP)
6148 .addImm(-16);
6149 BuildMI(MBB, I, DL, get(AArch64::LDRQpost))
6150 .addReg(AArch64::SP, RegState::Define)
6151 .addReg(DestReg, RegState::Define)
6152 .addReg(AArch64::SP)
6153 .addImm(16);
6154 }
6155 return;
6156 }
6157
6158 if (AArch64::FPR64RegClass.contains(DestReg) &&
6159 AArch64::FPR64RegClass.contains(SrcReg)) {
6160 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6161 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6162 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6163 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6164 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::dsub,
6165 &AArch64::FPR128RegClass);
6166 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::dsub,
6167 &AArch64::FPR128RegClass);
6168 // This instruction is reading and writing Q registers. This may upset
6169 // the register scavenger and machine verifier, so we need to indicate
6170 // that we are reading an undefined value from SrcRegQ, but a proper
6171 // value from SrcReg.
6172 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6173 .addReg(SrcRegQ, RegState::Undef)
6174 .addReg(SrcRegQ, RegState::Undef)
6175 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6176 ++NumZCRegMoveInstrsFPR;
6177 } else {
6178 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestReg)
6179 .addReg(SrcReg, getKillRegState(KillSrc));
6180 if (Subtarget.hasZeroCycleRegMoveFPR64())
6181 ++NumZCRegMoveInstrsFPR;
6182 }
6183 return;
6184 }
6185
6186 if (AArch64::FPR32RegClass.contains(DestReg) &&
6187 AArch64::FPR32RegClass.contains(SrcReg)) {
6188 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6189 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6190 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6191 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6192 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::ssub,
6193 &AArch64::FPR128RegClass);
6194 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::ssub,
6195 &AArch64::FPR128RegClass);
6196 // This instruction is reading and writing Q registers. This may upset
6197 // the register scavenger and machine verifier, so we need to indicate
6198 // that we are reading an undefined value from SrcRegQ, but a proper
6199 // value from SrcReg.
6200 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6201 .addReg(SrcRegQ, RegState::Undef)
6202 .addReg(SrcRegQ, RegState::Undef)
6203 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6204 ++NumZCRegMoveInstrsFPR;
6205 } else if (Subtarget.hasZeroCycleRegMoveFPR64() &&
6206 !Subtarget.hasZeroCycleRegMoveFPR32()) {
6207 MCRegister DestRegD = RI.getMatchingSuperReg(DestReg, AArch64::ssub,
6208 &AArch64::FPR64RegClass);
6209 MCRegister SrcRegD = RI.getMatchingSuperReg(SrcReg, AArch64::ssub,
6210 &AArch64::FPR64RegClass);
6211 // This instruction is reading and writing D registers. This may upset
6212 // the register scavenger and machine verifier, so we need to indicate
6213 // that we are reading an undefined value from SrcRegD, but a proper
6214 // value from SrcReg.
6215 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestRegD)
6216 .addReg(SrcRegD, RegState::Undef)
6217 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6218 ++NumZCRegMoveInstrsFPR;
6219 } else {
6220 BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
6221 .addReg(SrcReg, getKillRegState(KillSrc));
6222 if (Subtarget.hasZeroCycleRegMoveFPR32())
6223 ++NumZCRegMoveInstrsFPR;
6224 }
6225 return;
6226 }
6227
6228 if (AArch64::FPR16RegClass.contains(DestReg) &&
6229 AArch64::FPR16RegClass.contains(SrcReg)) {
6230 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6231 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6232 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6233 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6234 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::hsub,
6235 &AArch64::FPR128RegClass);
6236 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::hsub,
6237 &AArch64::FPR128RegClass);
6238 // This instruction is reading and writing Q registers. This may upset
6239 // the register scavenger and machine verifier, so we need to indicate
6240 // that we are reading an undefined value from SrcRegQ, but a proper
6241 // value from SrcReg.
6242 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6243 .addReg(SrcRegQ, RegState::Undef)
6244 .addReg(SrcRegQ, RegState::Undef)
6245 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6246 } else if (Subtarget.hasZeroCycleRegMoveFPR64() &&
6247 !Subtarget.hasZeroCycleRegMoveFPR32()) {
6248 MCRegister DestRegD = RI.getMatchingSuperReg(DestReg, AArch64::hsub,
6249 &AArch64::FPR64RegClass);
6250 MCRegister SrcRegD = RI.getMatchingSuperReg(SrcReg, AArch64::hsub,
6251 &AArch64::FPR64RegClass);
6252 // This instruction is reading and writing D registers. This may upset
6253 // the register scavenger and machine verifier, so we need to indicate
6254 // that we are reading an undefined value from SrcRegD, but a proper
6255 // value from SrcReg.
6256 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestRegD)
6257 .addReg(SrcRegD, RegState::Undef)
6258 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6259 } else {
6260 DestReg = RI.getMatchingSuperReg(DestReg, AArch64::hsub,
6261 &AArch64::FPR32RegClass);
6262 SrcReg = RI.getMatchingSuperReg(SrcReg, AArch64::hsub,
6263 &AArch64::FPR32RegClass);
6264 BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
6265 .addReg(SrcReg, getKillRegState(KillSrc));
6266 }
6267 return;
6268 }
6269
6270 if (AArch64::FPR8RegClass.contains(DestReg) &&
6271 AArch64::FPR8RegClass.contains(SrcReg)) {
6272 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6273 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6274 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6275 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6276 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::bsub,
6277 &AArch64::FPR128RegClass);
6278 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::bsub,
6279 &AArch64::FPR128RegClass);
6280 // This instruction is reading and writing Q registers. This may upset
6281 // the register scavenger and machine verifier, so we need to indicate
6282 // that we are reading an undefined value from SrcRegQ, but a proper
6283 // value from SrcReg.
6284 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6285 .addReg(SrcRegQ, RegState::Undef)
6286 .addReg(SrcRegQ, RegState::Undef)
6287 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6288 } else if (Subtarget.hasZeroCycleRegMoveFPR64() &&
6289 !Subtarget.hasZeroCycleRegMoveFPR32()) {
6290 MCRegister DestRegD = RI.getMatchingSuperReg(DestReg, AArch64::bsub,
6291 &AArch64::FPR64RegClass);
6292 MCRegister SrcRegD = RI.getMatchingSuperReg(SrcReg, AArch64::bsub,
6293 &AArch64::FPR64RegClass);
6294 // This instruction is reading and writing D registers. This may upset
6295 // the register scavenger and machine verifier, so we need to indicate
6296 // that we are reading an undefined value from SrcRegD, but a proper
6297 // value from SrcReg.
6298 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestRegD)
6299 .addReg(SrcRegD, RegState::Undef)
6300 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6301 } else {
6302 DestReg = RI.getMatchingSuperReg(DestReg, AArch64::bsub,
6303 &AArch64::FPR32RegClass);
6304 SrcReg = RI.getMatchingSuperReg(SrcReg, AArch64::bsub,
6305 &AArch64::FPR32RegClass);
6306 BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
6307 .addReg(SrcReg, getKillRegState(KillSrc));
6308 }
6309 return;
6310 }
6311
6312 // Copies between GPR64 and FPR64.
6313 if (AArch64::FPR64RegClass.contains(DestReg) &&
6314 AArch64::GPR64RegClass.contains(SrcReg)) {
6315 if (AArch64::XZR == SrcReg) {
6316 BuildMI(MBB, I, DL, get(AArch64::FMOVD0), DestReg);
6317 } else {
6318 BuildMI(MBB, I, DL, get(AArch64::FMOVXDr), DestReg)
6319 .addReg(SrcReg, getKillRegState(KillSrc));
6320 }
6321 return;
6322 }
6323 if (AArch64::GPR64RegClass.contains(DestReg) &&
6324 AArch64::FPR64RegClass.contains(SrcReg)) {
6325 BuildMI(MBB, I, DL, get(AArch64::FMOVDXr), DestReg)
6326 .addReg(SrcReg, getKillRegState(KillSrc));
6327 return;
6328 }
6329 // Copies between GPR32 and FPR32.
6330 if (AArch64::FPR32RegClass.contains(DestReg) &&
6331 AArch64::GPR32RegClass.contains(SrcReg)) {
6332 if (AArch64::WZR == SrcReg) {
6333 BuildMI(MBB, I, DL, get(AArch64::FMOVS0), DestReg);
6334 } else {
6335 BuildMI(MBB, I, DL, get(AArch64::FMOVWSr), DestReg)
6336 .addReg(SrcReg, getKillRegState(KillSrc));
6337 }
6338 return;
6339 }
6340 if (AArch64::GPR32RegClass.contains(DestReg) &&
6341 AArch64::FPR32RegClass.contains(SrcReg)) {
6342 BuildMI(MBB, I, DL, get(AArch64::FMOVSWr), DestReg)
6343 .addReg(SrcReg, getKillRegState(KillSrc));
6344 return;
6345 }
6346
6347 if (DestReg == AArch64::NZCV) {
6348 assert(AArch64::GPR64RegClass.contains(SrcReg) && "Invalid NZCV copy");
6349 BuildMI(MBB, I, DL, get(AArch64::MSR))
6350 .addImm(AArch64SysReg::NZCV)
6351 .addReg(SrcReg, getKillRegState(KillSrc))
6352 .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define);
6353 return;
6354 }
6355
6356 if (SrcReg == AArch64::NZCV) {
6357 assert(AArch64::GPR64RegClass.contains(DestReg) && "Invalid NZCV copy");
6358 BuildMI(MBB, I, DL, get(AArch64::MRS), DestReg)
6359 .addImm(AArch64SysReg::NZCV)
6360 .addReg(AArch64::NZCV, RegState::Implicit | getKillRegState(KillSrc));
6361 return;
6362 }
6363
6364#ifndef NDEBUG
6365 errs() << RI.getRegAsmName(DestReg) << " = COPY " << RI.getRegAsmName(SrcReg)
6366 << "\n";
6367#endif
6368 llvm_unreachable("unimplemented reg-to-reg copy");
6369}
6370
6373 const DebugLoc &DL, Register DestReg,
6374 Register SrcReg, bool KillSrc,
6375 bool RenamableDest,
6376 bool RenamableSrc) const {
6377 ++NumCopyInstrs;
6378 copyPhysRegImpl(MBB, I, DL, DestReg, SrcReg, KillSrc, RenamableDest,
6379 RenamableSrc);
6380 return;
6381}
6382
6385 MachineBasicBlock::iterator InsertBefore,
6386 const MCInstrDesc &MCID,
6387 Register SrcReg, bool IsKill,
6388 unsigned SubIdx0, unsigned SubIdx1, int FI,
6389 MachineMemOperand *MMO) {
6390 Register SrcReg0 = SrcReg;
6391 Register SrcReg1 = SrcReg;
6392 if (SrcReg.isPhysical()) {
6393 SrcReg0 = TRI.getSubReg(SrcReg, SubIdx0);
6394 SubIdx0 = 0;
6395 SrcReg1 = TRI.getSubReg(SrcReg, SubIdx1);
6396 SubIdx1 = 0;
6397 }
6398 BuildMI(MBB, InsertBefore, DebugLoc(), MCID)
6399 .addReg(SrcReg0, getKillRegState(IsKill), SubIdx0)
6400 .addReg(SrcReg1, getKillRegState(IsKill), SubIdx1)
6401 .addFrameIndex(FI)
6402 .addImm(0)
6403 .addMemOperand(MMO);
6404}
6405
6408 Register SrcReg, bool isKill, int FI,
6409 const TargetRegisterClass *RC,
6410 Register VReg,
6411 MachineInstr::MIFlag Flags) const {
6412 MachineFunction &MF = *MBB.getParent();
6413 MachineFrameInfo &MFI = MF.getFrameInfo();
6414
6416 MachineMemOperand *MMO =
6418 MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
6419 unsigned Opc = 0;
6420 bool Offset = true;
6422 unsigned StackID = TargetStackID::Default;
6423 switch (RI.getSpillSize(*RC)) {
6424 case 1:
6425 if (AArch64::FPR8RegClass.hasSubClassEq(RC))
6426 Opc = AArch64::STRBui;
6427 break;
6428 case 2: {
6429 if (AArch64::FPR16RegClass.hasSubClassEq(RC))
6430 Opc = AArch64::STRHui;
6431 else if (AArch64::PNRRegClass.hasSubClassEq(RC) ||
6432 AArch64::PPRRegClass.hasSubClassEq(RC)) {
6433 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6434 "Unexpected register store without SVE store instructions");
6435 Opc = AArch64::STR_PXI;
6437 }
6438 break;
6439 }
6440 case 4:
6441 if (AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
6442 Opc = AArch64::STRWui;
6443 if (SrcReg.isVirtual())
6444 MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR32RegClass);
6445 else
6446 assert(SrcReg != AArch64::WSP);
6447 } else if (AArch64::FPR32RegClass.hasSubClassEq(RC))
6448 Opc = AArch64::STRSui;
6449 else if (AArch64::PPR2RegClass.hasSubClassEq(RC)) {
6450 Opc = AArch64::STR_PPXI;
6452 }
6453 break;
6454 case 8:
6455 if (AArch64::GPR64allRegClass.hasSubClassEq(RC)) {
6456 Opc = AArch64::STRXui;
6457 if (SrcReg.isVirtual())
6458 MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR64RegClass);
6459 else
6460 assert(SrcReg != AArch64::SP);
6461 } else if (AArch64::FPR64RegClass.hasSubClassEq(RC)) {
6462 Opc = AArch64::STRDui;
6463 } else if (AArch64::WSeqPairsClassRegClass.hasSubClassEq(RC)) {
6465 get(AArch64::STPWi), SrcReg, isKill,
6466 AArch64::sube32, AArch64::subo32, FI, MMO);
6467 return;
6468 }
6469 break;
6470 case 16:
6471 if (AArch64::FPR128RegClass.hasSubClassEq(RC))
6472 Opc = AArch64::STRQui;
6473 else if (AArch64::DDRegClass.hasSubClassEq(RC)) {
6474 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6475 Opc = AArch64::ST1Twov1d;
6476 Offset = false;
6477 } else if (AArch64::XSeqPairsClassRegClass.hasSubClassEq(RC)) {
6479 get(AArch64::STPXi), SrcReg, isKill,
6480 AArch64::sube64, AArch64::subo64, FI, MMO);
6481 return;
6482 } else if (AArch64::ZPRRegClass.hasSubClassEq(RC)) {
6483 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6484 "Unexpected register store without SVE store instructions");
6485 Opc = AArch64::STR_ZXI;
6487 }
6488 break;
6489 case 24:
6490 if (AArch64::DDDRegClass.hasSubClassEq(RC)) {
6491 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6492 Opc = AArch64::ST1Threev1d;
6493 Offset = false;
6494 }
6495 break;
6496 case 32:
6497 if (AArch64::DDDDRegClass.hasSubClassEq(RC)) {
6498 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6499 Opc = AArch64::ST1Fourv1d;
6500 Offset = false;
6501 } else if (AArch64::QQRegClass.hasSubClassEq(RC)) {
6502 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6503 Opc = AArch64::ST1Twov2d;
6504 Offset = false;
6505 } else if (AArch64::ZPR2StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6506 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6507 "Unexpected register store without SVE store instructions");
6508 Opc = AArch64::STR_ZZXI_STRIDED_CONTIGUOUS;
6510 } else if (AArch64::ZPR2RegClass.hasSubClassEq(RC)) {
6511 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6512 "Unexpected register store without SVE store instructions");
6513 Opc = AArch64::STR_ZZXI;
6515 }
6516 break;
6517 case 48:
6518 if (AArch64::QQQRegClass.hasSubClassEq(RC)) {
6519 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6520 Opc = AArch64::ST1Threev2d;
6521 Offset = false;
6522 } else if (AArch64::ZPR3RegClass.hasSubClassEq(RC)) {
6523 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6524 "Unexpected register store without SVE store instructions");
6525 Opc = AArch64::STR_ZZZXI;
6527 }
6528 break;
6529 case 64:
6530 if (AArch64::QQQQRegClass.hasSubClassEq(RC)) {
6531 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6532 Opc = AArch64::ST1Fourv2d;
6533 Offset = false;
6534 } else if (AArch64::ZPR4StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6535 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6536 "Unexpected register store without SVE store instructions");
6537 Opc = AArch64::STR_ZZZZXI_STRIDED_CONTIGUOUS;
6539 } else if (AArch64::ZPR4RegClass.hasSubClassEq(RC)) {
6540 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6541 "Unexpected register store without SVE store instructions");
6542 Opc = AArch64::STR_ZZZZXI;
6544 }
6545 break;
6546 }
6547 assert(Opc && "Unknown register class");
6548 MFI.setStackID(FI, StackID);
6549
6551 .addReg(SrcReg, getKillRegState(isKill))
6552 .addFrameIndex(FI);
6553
6554 if (Offset)
6555 MI.addImm(0);
6556 if (PNRReg.isValid())
6557 MI.addDef(PNRReg, RegState::Implicit);
6558 MI.addMemOperand(MMO);
6559}
6560
6563 MachineBasicBlock::iterator InsertBefore,
6564 const MCInstrDesc &MCID,
6565 Register DestReg, unsigned SubIdx0,
6566 unsigned SubIdx1, int FI,
6567 MachineMemOperand *MMO) {
6568 Register DestReg0 = DestReg;
6569 Register DestReg1 = DestReg;
6570 bool IsUndef = true;
6571 if (DestReg.isPhysical()) {
6572 DestReg0 = TRI.getSubReg(DestReg, SubIdx0);
6573 SubIdx0 = 0;
6574 DestReg1 = TRI.getSubReg(DestReg, SubIdx1);
6575 SubIdx1 = 0;
6576 IsUndef = false;
6577 }
6578 BuildMI(MBB, InsertBefore, DebugLoc(), MCID)
6579 .addReg(DestReg0, RegState::Define | getUndefRegState(IsUndef), SubIdx0)
6580 .addReg(DestReg1, RegState::Define | getUndefRegState(IsUndef), SubIdx1)
6581 .addFrameIndex(FI)
6582 .addImm(0)
6583 .addMemOperand(MMO);
6584}
6585
6588 Register DestReg, int FI,
6589 const TargetRegisterClass *RC,
6590 Register VReg, unsigned SubReg,
6591 MachineInstr::MIFlag Flags) const {
6592 MachineFunction &MF = *MBB.getParent();
6593 MachineFrameInfo &MFI = MF.getFrameInfo();
6595 MachineMemOperand *MMO =
6597 MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
6598
6599 unsigned Opc = 0;
6600 bool Offset = true;
6601 unsigned StackID = TargetStackID::Default;
6603 switch (TRI.getSpillSize(*RC)) {
6604 case 1:
6605 if (AArch64::FPR8RegClass.hasSubClassEq(RC))
6606 Opc = AArch64::LDRBui;
6607 break;
6608 case 2: {
6609 bool IsPNR = AArch64::PNRRegClass.hasSubClassEq(RC);
6610 if (AArch64::FPR16RegClass.hasSubClassEq(RC))
6611 Opc = AArch64::LDRHui;
6612 else if (IsPNR || AArch64::PPRRegClass.hasSubClassEq(RC)) {
6613 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6614 "Unexpected register load without SVE load instructions");
6615 if (IsPNR)
6616 PNRReg = DestReg;
6617 Opc = AArch64::LDR_PXI;
6619 }
6620 break;
6621 }
6622 case 4:
6623 if (AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
6624 Opc = AArch64::LDRWui;
6625 if (DestReg.isVirtual())
6626 MF.getRegInfo().constrainRegClass(DestReg, &AArch64::GPR32RegClass);
6627 else
6628 assert(DestReg != AArch64::WSP);
6629 } else if (AArch64::FPR32RegClass.hasSubClassEq(RC))
6630 Opc = AArch64::LDRSui;
6631 else if (AArch64::PPR2RegClass.hasSubClassEq(RC)) {
6632 Opc = AArch64::LDR_PPXI;
6634 }
6635 break;
6636 case 8:
6637 if (AArch64::GPR64allRegClass.hasSubClassEq(RC)) {
6638 Opc = AArch64::LDRXui;
6639 if (DestReg.isVirtual())
6640 MF.getRegInfo().constrainRegClass(DestReg, &AArch64::GPR64RegClass);
6641 else
6642 assert(DestReg != AArch64::SP);
6643 } else if (AArch64::FPR64RegClass.hasSubClassEq(RC)) {
6644 Opc = AArch64::LDRDui;
6645 } else if (AArch64::WSeqPairsClassRegClass.hasSubClassEq(RC)) {
6647 get(AArch64::LDPWi), DestReg, AArch64::sube32,
6648 AArch64::subo32, FI, MMO);
6649 return;
6650 }
6651 break;
6652 case 16:
6653 if (AArch64::FPR128RegClass.hasSubClassEq(RC))
6654 Opc = AArch64::LDRQui;
6655 else if (AArch64::DDRegClass.hasSubClassEq(RC)) {
6656 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6657 Opc = AArch64::LD1Twov1d;
6658 Offset = false;
6659 } else if (AArch64::XSeqPairsClassRegClass.hasSubClassEq(RC)) {
6661 get(AArch64::LDPXi), DestReg, AArch64::sube64,
6662 AArch64::subo64, FI, MMO);
6663 return;
6664 } else if (AArch64::ZPRRegClass.hasSubClassEq(RC)) {
6665 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6666 "Unexpected register load without SVE load instructions");
6667 Opc = AArch64::LDR_ZXI;
6669 }
6670 break;
6671 case 24:
6672 if (AArch64::DDDRegClass.hasSubClassEq(RC)) {
6673 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6674 Opc = AArch64::LD1Threev1d;
6675 Offset = false;
6676 }
6677 break;
6678 case 32:
6679 if (AArch64::DDDDRegClass.hasSubClassEq(RC)) {
6680 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6681 Opc = AArch64::LD1Fourv1d;
6682 Offset = false;
6683 } else if (AArch64::QQRegClass.hasSubClassEq(RC)) {
6684 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6685 Opc = AArch64::LD1Twov2d;
6686 Offset = false;
6687 } else if (AArch64::ZPR2StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6688 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6689 "Unexpected register load without SVE load instructions");
6690 Opc = AArch64::LDR_ZZXI_STRIDED_CONTIGUOUS;
6692 } else if (AArch64::ZPR2RegClass.hasSubClassEq(RC)) {
6693 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6694 "Unexpected register load without SVE load instructions");
6695 Opc = AArch64::LDR_ZZXI;
6697 }
6698 break;
6699 case 48:
6700 if (AArch64::QQQRegClass.hasSubClassEq(RC)) {
6701 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6702 Opc = AArch64::LD1Threev2d;
6703 Offset = false;
6704 } else if (AArch64::ZPR3RegClass.hasSubClassEq(RC)) {
6705 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6706 "Unexpected register load without SVE load instructions");
6707 Opc = AArch64::LDR_ZZZXI;
6709 }
6710 break;
6711 case 64:
6712 if (AArch64::QQQQRegClass.hasSubClassEq(RC)) {
6713 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6714 Opc = AArch64::LD1Fourv2d;
6715 Offset = false;
6716 } else if (AArch64::ZPR4StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6717 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6718 "Unexpected register load without SVE load instructions");
6719 Opc = AArch64::LDR_ZZZZXI_STRIDED_CONTIGUOUS;
6721 } else if (AArch64::ZPR4RegClass.hasSubClassEq(RC)) {
6722 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6723 "Unexpected register load without SVE load instructions");
6724 Opc = AArch64::LDR_ZZZZXI;
6726 }
6727 break;
6728 }
6729
6730 assert(Opc && "Unknown register class");
6731 MFI.setStackID(FI, StackID);
6732
6734 .addReg(DestReg, getDefRegState(true))
6735 .addFrameIndex(FI);
6736 if (Offset)
6737 MI.addImm(0);
6738 if (PNRReg.isValid() && !PNRReg.isVirtual())
6739 MI.addDef(PNRReg, RegState::Implicit);
6740 MI.addMemOperand(MMO);
6741}
6742
6744 const MachineInstr &UseMI,
6745 const TargetRegisterInfo *TRI) {
6746 return any_of(instructionsWithoutDebug(std::next(DefMI.getIterator()),
6747 UseMI.getIterator()),
6748 [TRI](const MachineInstr &I) {
6749 return I.modifiesRegister(AArch64::NZCV, TRI) ||
6750 I.readsRegister(AArch64::NZCV, TRI);
6751 });
6752}
6753
6754void AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(
6755 const StackOffset &Offset, int64_t &ByteSized, int64_t &VGSized) {
6756 // The smallest scalable element supported by scaled SVE addressing
6757 // modes are predicates, which are 2 scalable bytes in size. So the scalable
6758 // byte offset must always be a multiple of 2.
6759 assert(Offset.getScalable() % 2 == 0 && "Invalid frame offset");
6760
6761 // VGSized offsets are divided by '2', because the VG register is the
6762 // the number of 64bit granules as opposed to 128bit vector chunks,
6763 // which is how the 'n' in e.g. MVT::nxv1i8 is modelled.
6764 // So, for a stack offset of 16 MVT::nxv1i8's, the size is n x 16 bytes.
6765 // VG = n * 2 and the dwarf offset must be VG * 8 bytes.
6766 ByteSized = Offset.getFixed();
6767 VGSized = Offset.getScalable() / 2;
6768}
6769
6770/// Returns the offset in parts to which this frame offset can be
6771/// decomposed for the purpose of describing a frame offset.
6772/// For non-scalable offsets this is simply its byte size.
6773void AArch64InstrInfo::decomposeStackOffsetForFrameOffsets(
6774 const StackOffset &Offset, int64_t &NumBytes, int64_t &NumPredicateVectors,
6775 int64_t &NumDataVectors) {
6776 // The smallest scalable element supported by scaled SVE addressing
6777 // modes are predicates, which are 2 scalable bytes in size. So the scalable
6778 // byte offset must always be a multiple of 2.
6779 assert(Offset.getScalable() % 2 == 0 && "Invalid frame offset");
6780
6781 NumBytes = Offset.getFixed();
6782 NumDataVectors = 0;
6783 NumPredicateVectors = Offset.getScalable() / 2;
6784 // This method is used to get the offsets to adjust the frame offset.
6785 // If the function requires ADDPL to be used and needs more than two ADDPL
6786 // instructions, part of the offset is folded into NumDataVectors so that it
6787 // uses ADDVL for part of it, reducing the number of ADDPL instructions.
6788 if (NumPredicateVectors % 8 == 0 || NumPredicateVectors < -64 ||
6789 NumPredicateVectors > 62) {
6790 NumDataVectors = NumPredicateVectors / 8;
6791 NumPredicateVectors -= NumDataVectors * 8;
6792 }
6793}
6794
6795// Convenience function to create a DWARF expression for: Constant `Operation`.
6796// This helper emits compact sequences for common cases. For example, for`-15
6797// DW_OP_plus`, this helper would create DW_OP_lit15 DW_OP_minus.
6800 if (Operation == dwarf::DW_OP_plus && Constant < 0 && -Constant <= 31) {
6801 // -Constant (1 to 31)
6802 Expr.push_back(dwarf::DW_OP_lit0 - Constant);
6803 Operation = dwarf::DW_OP_minus;
6804 } else if (Constant >= 0 && Constant <= 31) {
6805 // Literal value 0 to 31
6806 Expr.push_back(dwarf::DW_OP_lit0 + Constant);
6807 } else {
6808 // Signed constant
6809 Expr.push_back(dwarf::DW_OP_consts);
6811 }
6812 return Expr.push_back(Operation);
6813}
6814
6815// Convenience function to create a DWARF expression for a register.
6816static void appendReadRegExpr(SmallVectorImpl<char> &Expr, unsigned RegNum) {
6817 Expr.push_back((char)dwarf::DW_OP_bregx);
6819 Expr.push_back(0);
6820}
6821
6822// Convenience function to create a DWARF expression for loading a register from
6823// a CFA offset.
6825 int64_t OffsetFromDefCFA) {
6826 // This assumes the top of the DWARF stack contains the CFA.
6827 Expr.push_back(dwarf::DW_OP_dup);
6828 // Add the offset to the register.
6829 appendConstantExpr(Expr, OffsetFromDefCFA, dwarf::DW_OP_plus);
6830 // Dereference the address (loads a 64 bit value)..
6831 Expr.push_back(dwarf::DW_OP_deref);
6832}
6833
6834// Convenience function to create a comment for
6835// (+/-) NumBytes (* RegScale)?
6836static void appendOffsetComment(int NumBytes, llvm::raw_string_ostream &Comment,
6837 StringRef RegScale = {}) {
6838 if (NumBytes) {
6839 Comment << (NumBytes < 0 ? " - " : " + ") << std::abs(NumBytes);
6840 if (!RegScale.empty())
6841 Comment << ' ' << RegScale;
6842 }
6843}
6844
6845// Creates an MCCFIInstruction:
6846// { DW_CFA_def_cfa_expression, ULEB128 (sizeof expr), expr }
6848 unsigned Reg,
6849 const StackOffset &Offset) {
6850 int64_t NumBytes, NumVGScaledBytes;
6851 AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(Offset, NumBytes,
6852 NumVGScaledBytes);
6853 std::string CommentBuffer;
6854 llvm::raw_string_ostream Comment(CommentBuffer);
6855
6856 if (Reg == AArch64::SP)
6857 Comment << "sp";
6858 else if (Reg == AArch64::FP)
6859 Comment << "fp";
6860 else
6861 Comment << printReg(Reg, &TRI);
6862
6863 // Build up the expression (Reg + NumBytes + VG * NumVGScaledBytes)
6864 SmallString<64> Expr;
6865 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
6866 assert(DwarfReg <= 31 && "DwarfReg out of bounds (0..31)");
6867 // Reg + NumBytes
6868 Expr.push_back(dwarf::DW_OP_breg0 + DwarfReg);
6869 appendLEB128<LEB128Sign::Signed>(Expr, NumBytes);
6870 appendOffsetComment(NumBytes, Comment);
6871 if (NumVGScaledBytes) {
6872 // + VG * NumVGScaledBytes
6873 appendOffsetComment(NumVGScaledBytes, Comment, "* VG");
6874 appendReadRegExpr(Expr, TRI.getDwarfRegNum(AArch64::VG, true));
6875 appendConstantExpr(Expr, NumVGScaledBytes, dwarf::DW_OP_mul);
6876 Expr.push_back(dwarf::DW_OP_plus);
6877 }
6878
6879 // Wrap this into DW_CFA_def_cfa.
6880 SmallString<64> DefCfaExpr;
6881 DefCfaExpr.push_back(dwarf::DW_CFA_def_cfa_expression);
6882 appendLEB128<LEB128Sign::Unsigned>(DefCfaExpr, Expr.size());
6883 DefCfaExpr.append(Expr.str());
6884 return MCCFIInstruction::createEscape(nullptr, DefCfaExpr.str(), SMLoc(),
6885 Comment.str());
6886}
6887
6889 unsigned FrameReg, unsigned Reg,
6890 const StackOffset &Offset,
6891 bool LastAdjustmentWasScalable) {
6892 if (Offset.getScalable())
6893 return createDefCFAExpression(TRI, Reg, Offset);
6894
6895 if (FrameReg == Reg && !LastAdjustmentWasScalable)
6896 return MCCFIInstruction::cfiDefCfaOffset(nullptr, int(Offset.getFixed()));
6897
6898 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
6899 return MCCFIInstruction::cfiDefCfa(nullptr, DwarfReg, (int)Offset.getFixed());
6900}
6901
6904 const StackOffset &OffsetFromDefCFA,
6905 std::optional<int64_t> IncomingVGOffsetFromDefCFA) {
6906 int64_t NumBytes, NumVGScaledBytes;
6907 AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(
6908 OffsetFromDefCFA, NumBytes, NumVGScaledBytes);
6909
6910 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
6911
6912 // Non-scalable offsets can use DW_CFA_offset directly.
6913 if (!NumVGScaledBytes)
6914 return MCCFIInstruction::createOffset(nullptr, DwarfReg, NumBytes);
6915
6916 std::string CommentBuffer;
6917 llvm::raw_string_ostream Comment(CommentBuffer);
6918 Comment << printReg(Reg, &TRI) << " @ cfa";
6919
6920 // Build up expression (CFA + VG * NumVGScaledBytes + NumBytes)
6921 assert(NumVGScaledBytes && "Expected scalable offset");
6922 SmallString<64> OffsetExpr;
6923 // + VG * NumVGScaledBytes
6924 StringRef VGRegScale;
6925 if (IncomingVGOffsetFromDefCFA) {
6926 appendLoadRegExpr(OffsetExpr, *IncomingVGOffsetFromDefCFA);
6927 VGRegScale = "* IncomingVG";
6928 } else {
6929 appendReadRegExpr(OffsetExpr, TRI.getDwarfRegNum(AArch64::VG, true));
6930 VGRegScale = "* VG";
6931 }
6932 appendConstantExpr(OffsetExpr, NumVGScaledBytes, dwarf::DW_OP_mul);
6933 appendOffsetComment(NumVGScaledBytes, Comment, VGRegScale);
6934 OffsetExpr.push_back(dwarf::DW_OP_plus);
6935 if (NumBytes) {
6936 // + NumBytes
6937 appendOffsetComment(NumBytes, Comment);
6938 appendConstantExpr(OffsetExpr, NumBytes, dwarf::DW_OP_plus);
6939 }
6940
6941 // Wrap this into DW_CFA_expression
6942 SmallString<64> CfaExpr;
6943 CfaExpr.push_back(dwarf::DW_CFA_expression);
6944 appendLEB128<LEB128Sign::Unsigned>(CfaExpr, DwarfReg);
6945 appendLEB128<LEB128Sign::Unsigned>(CfaExpr, OffsetExpr.size());
6946 CfaExpr.append(OffsetExpr.str());
6947
6948 return MCCFIInstruction::createEscape(nullptr, CfaExpr.str(), SMLoc(),
6949 Comment.str());
6950}
6951
6952// Helper function to emit a frame offset adjustment from a given
6953// pointer (SrcReg), stored into DestReg. This function is explicit
6954// in that it requires the opcode.
6957 const DebugLoc &DL, unsigned DestReg,
6958 unsigned SrcReg, int64_t Offset, unsigned Opc,
6959 const TargetInstrInfo *TII,
6960 MachineInstr::MIFlag Flag, bool NeedsWinCFI,
6961 bool *HasWinCFI, bool EmitCFAOffset,
6962 StackOffset CFAOffset, unsigned FrameReg) {
6963 int Sign = 1;
6964 unsigned MaxEncoding, ShiftSize;
6965 switch (Opc) {
6966 case AArch64::ADDXri:
6967 case AArch64::ADDSXri:
6968 case AArch64::SUBXri:
6969 case AArch64::SUBSXri:
6970 MaxEncoding = 0xfff;
6971 ShiftSize = 12;
6972 break;
6973 case AArch64::ADDVL_XXI:
6974 case AArch64::ADDPL_XXI:
6975 case AArch64::ADDSVL_XXI:
6976 case AArch64::ADDSPL_XXI:
6977 MaxEncoding = 31;
6978 ShiftSize = 0;
6979 if (Offset < 0) {
6980 MaxEncoding = 32;
6981 Sign = -1;
6982 Offset = -Offset;
6983 }
6984 break;
6985 default:
6986 llvm_unreachable("Unsupported opcode");
6987 }
6988
6989 // `Offset` can be in bytes or in "scalable bytes".
6990 int VScale = 1;
6991 if (Opc == AArch64::ADDVL_XXI || Opc == AArch64::ADDSVL_XXI)
6992 VScale = 16;
6993 else if (Opc == AArch64::ADDPL_XXI || Opc == AArch64::ADDSPL_XXI)
6994 VScale = 2;
6995
6996 // FIXME: If the offset won't fit in 24-bits, compute the offset into a
6997 // scratch register. If DestReg is a virtual register, use it as the
6998 // scratch register; otherwise, create a new virtual register (to be
6999 // replaced by the scavenger at the end of PEI). That case can be optimized
7000 // slightly if DestReg is SP which is always 16-byte aligned, so the scratch
7001 // register can be loaded with offset%8 and the add/sub can use an extending
7002 // instruction with LSL#3.
7003 // Currently the function handles any offsets but generates a poor sequence
7004 // of code.
7005 // assert(Offset < (1 << 24) && "unimplemented reg plus immediate");
7006
7007 const unsigned MaxEncodableValue = MaxEncoding << ShiftSize;
7008 Register TmpReg = DestReg;
7009 if (TmpReg == AArch64::XZR)
7010 TmpReg = MBB.getParent()->getRegInfo().createVirtualRegister(
7011 &AArch64::GPR64RegClass);
7012 do {
7013 uint64_t ThisVal = std::min<uint64_t>(Offset, MaxEncodableValue);
7014 unsigned LocalShiftSize = 0;
7015 if (ThisVal > MaxEncoding) {
7016 ThisVal = ThisVal >> ShiftSize;
7017 LocalShiftSize = ShiftSize;
7018 }
7019 assert((ThisVal >> ShiftSize) <= MaxEncoding &&
7020 "Encoding cannot handle value that big");
7021
7022 Offset -= ThisVal << LocalShiftSize;
7023 if (Offset == 0)
7024 TmpReg = DestReg;
7025 auto MBI = BuildMI(MBB, MBBI, DL, TII->get(Opc), TmpReg)
7026 .addReg(SrcReg)
7027 .addImm(Sign * (int)ThisVal);
7028 if (ShiftSize)
7029 MBI = MBI.addImm(
7031 MBI = MBI.setMIFlag(Flag);
7032
7033 auto Change =
7034 VScale == 1
7035 ? StackOffset::getFixed(ThisVal << LocalShiftSize)
7036 : StackOffset::getScalable(VScale * (ThisVal << LocalShiftSize));
7037 if (Sign == -1 || Opc == AArch64::SUBXri || Opc == AArch64::SUBSXri)
7038 CFAOffset += Change;
7039 else
7040 CFAOffset -= Change;
7041 if (EmitCFAOffset && DestReg == TmpReg) {
7042 MachineFunction &MF = *MBB.getParent();
7043 const TargetSubtargetInfo &STI = MF.getSubtarget();
7044 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
7045
7046 unsigned CFIIndex = MF.addFrameInst(
7047 createDefCFA(TRI, FrameReg, DestReg, CFAOffset, VScale != 1));
7048 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
7049 .addCFIIndex(CFIIndex)
7050 .setMIFlags(Flag);
7051 }
7052
7053 if (NeedsWinCFI) {
7054 int Imm = (int)(ThisVal << LocalShiftSize);
7055 if (VScale != 1 && DestReg == AArch64::SP) {
7056 if (HasWinCFI)
7057 *HasWinCFI = true;
7058 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_AllocZ))
7059 .addImm(ThisVal)
7060 .setMIFlag(Flag);
7061 } else if ((DestReg == AArch64::FP && SrcReg == AArch64::SP) ||
7062 (SrcReg == AArch64::FP && DestReg == AArch64::SP)) {
7063 assert(VScale == 1 && "Expected non-scalable operation");
7064 if (HasWinCFI)
7065 *HasWinCFI = true;
7066 if (Imm == 0)
7067 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_SetFP)).setMIFlag(Flag);
7068 else
7069 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_AddFP))
7070 .addImm(Imm)
7071 .setMIFlag(Flag);
7072 assert(Offset == 0 && "Expected remaining offset to be zero to "
7073 "emit a single SEH directive");
7074 } else if (DestReg == AArch64::SP) {
7075 assert(VScale == 1 && "Expected non-scalable operation");
7076 if (HasWinCFI)
7077 *HasWinCFI = true;
7078 assert(SrcReg == AArch64::SP && "Unexpected SrcReg for SEH_StackAlloc");
7079 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
7080 .addImm(Imm)
7081 .setMIFlag(Flag);
7082 }
7083 }
7084
7085 SrcReg = TmpReg;
7086 } while (Offset);
7087}
7088
7091 unsigned DestReg, unsigned SrcReg,
7093 MachineInstr::MIFlag Flag, bool SetNZCV,
7094 bool NeedsWinCFI, bool *HasWinCFI,
7095 bool EmitCFAOffset, StackOffset CFAOffset,
7096 unsigned FrameReg) {
7097 // If a function is marked as arm_locally_streaming, then the runtime value of
7098 // vscale in the prologue/epilogue is different the runtime value of vscale
7099 // in the function's body. To avoid having to consider multiple vscales,
7100 // we can use `addsvl` to allocate any scalable stack-slots, which under
7101 // most circumstances will be only locals, not callee-save slots.
7102 const Function &F = MBB.getParent()->getFunction();
7103 bool UseSVL = F.hasFnAttribute("aarch64_pstate_sm_body");
7104
7105 int64_t Bytes, NumPredicateVectors, NumDataVectors;
7106 AArch64InstrInfo::decomposeStackOffsetForFrameOffsets(
7107 Offset, Bytes, NumPredicateVectors, NumDataVectors);
7108
7109 // Insert ADDSXri for scalable offset at the end.
7110 bool NeedsFinalDefNZCV = SetNZCV && (NumPredicateVectors || NumDataVectors);
7111 if (NeedsFinalDefNZCV)
7112 SetNZCV = false;
7113
7114 // First emit non-scalable frame offsets, or a simple 'mov'.
7115 if (Bytes || (!Offset && SrcReg != DestReg)) {
7116 assert((DestReg != AArch64::SP || Bytes % 8 == 0) &&
7117 "SP increment/decrement not 8-byte aligned");
7118 unsigned Opc = SetNZCV ? AArch64::ADDSXri : AArch64::ADDXri;
7119 if (Bytes < 0) {
7120 Bytes = -Bytes;
7121 Opc = SetNZCV ? AArch64::SUBSXri : AArch64::SUBXri;
7122 }
7123 emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, Bytes, Opc, TII, Flag,
7124 NeedsWinCFI, HasWinCFI, EmitCFAOffset, CFAOffset,
7125 FrameReg);
7126 CFAOffset += (Opc == AArch64::ADDXri || Opc == AArch64::ADDSXri)
7127 ? StackOffset::getFixed(-Bytes)
7128 : StackOffset::getFixed(Bytes);
7129 SrcReg = DestReg;
7130 FrameReg = DestReg;
7131 }
7132
7133 assert(!(NeedsWinCFI && NumPredicateVectors) &&
7134 "WinCFI can't allocate fractions of an SVE data vector");
7135
7136 if (NumDataVectors) {
7137 emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, NumDataVectors,
7138 UseSVL ? AArch64::ADDSVL_XXI : AArch64::ADDVL_XXI, TII,
7139 Flag, NeedsWinCFI, HasWinCFI, EmitCFAOffset, CFAOffset,
7140 FrameReg);
7141 CFAOffset += StackOffset::getScalable(-NumDataVectors * 16);
7142 SrcReg = DestReg;
7143 }
7144
7145 if (NumPredicateVectors) {
7146 assert(DestReg != AArch64::SP && "Unaligned access to SP");
7147 emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, NumPredicateVectors,
7148 UseSVL ? AArch64::ADDSPL_XXI : AArch64::ADDPL_XXI, TII,
7149 Flag, NeedsWinCFI, HasWinCFI, EmitCFAOffset, CFAOffset,
7150 FrameReg);
7151 }
7152
7153 if (NeedsFinalDefNZCV)
7154 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ADDSXri), DestReg)
7155 .addReg(DestReg)
7156 .addImm(0)
7157 .addImm(0);
7158}
7159
7162 int FrameIndex, MachineInstr *&CopyMI, LiveIntervals *LIS,
7163 VirtRegMap *VRM) const {
7165 // This is a bit of a hack. Consider this instruction:
7166 //
7167 // %0 = COPY %sp; GPR64all:%0
7168 //
7169 // We explicitly chose GPR64all for the virtual register so such a copy might
7170 // be eliminated by RegisterCoalescer. However, that may not be possible, and
7171 // %0 may even spill. We can't spill %sp, and since it is in the GPR64all
7172 // register class, TargetInstrInfo::foldMemoryOperand() is going to try.
7173 //
7174 // To prevent that, we are going to constrain the %0 register class here.
7175 if (MI.isFullCopy()) {
7176 Register DstReg = MI.getOperand(0).getReg();
7177 Register SrcReg = MI.getOperand(1).getReg();
7178 if (SrcReg == AArch64::SP && DstReg.isVirtual()) {
7179 MF.getRegInfo().constrainRegClass(DstReg, &AArch64::GPR64RegClass);
7180 return nullptr;
7181 }
7182 if (DstReg == AArch64::SP && SrcReg.isVirtual()) {
7183 MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR64RegClass);
7184 return nullptr;
7185 }
7186 // Nothing can folded with copy from/to NZCV.
7187 if (SrcReg == AArch64::NZCV || DstReg == AArch64::NZCV)
7188 return nullptr;
7189 }
7190
7191 // Handle the case where a copy is being spilled or filled but the source
7192 // and destination register class don't match. For example:
7193 //
7194 // %0 = COPY %xzr; GPR64common:%0
7195 //
7196 // In this case we can still safely fold away the COPY and generate the
7197 // following spill code:
7198 //
7199 // STRXui %xzr, %stack.0
7200 //
7201 // This also eliminates spilled cross register class COPYs (e.g. between x and
7202 // d regs) of the same size. For example:
7203 //
7204 // %0 = COPY %1; GPR64:%0, FPR64:%1
7205 //
7206 // will be filled as
7207 //
7208 // LDRDui %0, fi<#0>
7209 //
7210 // instead of
7211 //
7212 // LDRXui %Temp, fi<#0>
7213 // %0 = FMOV %Temp
7214 //
7215 if (MI.isCopy() && Ops.size() == 1 &&
7216 // Make sure we're only folding the explicit COPY defs/uses.
7217 (Ops[0] == 0 || Ops[0] == 1)) {
7218 bool IsSpill = Ops[0] == 0;
7219 bool IsFill = !IsSpill;
7221 const MachineRegisterInfo &MRI = MF.getRegInfo();
7222 MachineBasicBlock &MBB = *MI.getParent();
7223 const MachineOperand &DstMO = MI.getOperand(0);
7224 const MachineOperand &SrcMO = MI.getOperand(1);
7225 Register DstReg = DstMO.getReg();
7226 Register SrcReg = SrcMO.getReg();
7227 // This is slightly expensive to compute for physical regs since
7228 // getMinimalPhysRegClass is slow.
7229 auto getRegClass = [&](unsigned Reg) {
7230 return Register::isVirtualRegister(Reg) ? MRI.getRegClass(Reg)
7231 : TRI.getMinimalPhysRegClass(Reg);
7232 };
7233
7234 if (DstMO.getSubReg() == 0 && SrcMO.getSubReg() == 0) {
7235 assert(TRI.getRegSizeInBits(*getRegClass(DstReg)) ==
7236 TRI.getRegSizeInBits(*getRegClass(SrcReg)) &&
7237 "Mismatched register size in non subreg COPY");
7238 if (IsSpill)
7239 storeRegToStackSlot(MBB, InsertPt, SrcReg, SrcMO.isKill(), FrameIndex,
7240 getRegClass(SrcReg), Register());
7241 else
7242 loadRegFromStackSlot(MBB, InsertPt, DstReg, FrameIndex,
7243 getRegClass(DstReg), Register());
7244 return &*--InsertPt;
7245 }
7246
7247 // Handle cases like spilling def of:
7248 //
7249 // %0:sub_32<def,read-undef> = COPY %wzr; GPR64common:%0
7250 //
7251 // where the physical register source can be widened and stored to the full
7252 // virtual reg destination stack slot, in this case producing:
7253 //
7254 // STRXui %xzr, %stack.0
7255 //
7256 if (IsSpill && DstMO.isUndef() && SrcReg == AArch64::WZR &&
7257 TRI.getRegSizeInBits(*getRegClass(DstReg)) == 64) {
7258 assert(SrcMO.getSubReg() == 0 &&
7259 "Unexpected subreg on physical register");
7260 storeRegToStackSlot(MBB, InsertPt, AArch64::XZR, SrcMO.isKill(),
7261 FrameIndex, &AArch64::GPR64RegClass, Register());
7262 return &*--InsertPt;
7263 }
7264
7265 // Handle cases like filling use of:
7266 //
7267 // %0:sub_32<def,read-undef> = COPY %1; GPR64:%0, GPR32:%1
7268 //
7269 // where we can load the full virtual reg source stack slot, into the subreg
7270 // destination, in this case producing:
7271 //
7272 // LDRWui %0:sub_32<def,read-undef>, %stack.0
7273 //
7274 if (IsFill && SrcMO.getSubReg() == 0 && DstMO.isUndef()) {
7275 const TargetRegisterClass *FillRC = nullptr;
7276 switch (DstMO.getSubReg()) {
7277 default:
7278 break;
7279 case AArch64::sub_32:
7280 if (AArch64::GPR64RegClass.hasSubClassEq(getRegClass(DstReg)))
7281 FillRC = &AArch64::GPR32RegClass;
7282 break;
7283 case AArch64::ssub:
7284 FillRC = &AArch64::FPR32RegClass;
7285 break;
7286 case AArch64::dsub:
7287 FillRC = &AArch64::FPR64RegClass;
7288 break;
7289 }
7290
7291 if (FillRC) {
7292 assert(TRI.getRegSizeInBits(*getRegClass(SrcReg)) ==
7293 TRI.getRegSizeInBits(*FillRC) &&
7294 "Mismatched regclass size on folded subreg COPY");
7295 loadRegFromStackSlot(MBB, InsertPt, DstReg, FrameIndex, FillRC,
7296 Register());
7297 MachineInstr &LoadMI = *--InsertPt;
7298 MachineOperand &LoadDst = LoadMI.getOperand(0);
7299 assert(LoadDst.getSubReg() == 0 && "unexpected subreg on fill load");
7300 LoadDst.setSubReg(DstMO.getSubReg());
7301 LoadDst.setIsUndef();
7302 return &LoadMI;
7303 }
7304 }
7305 }
7306
7307 // Cannot fold.
7308 return nullptr;
7309}
7310
7312 StackOffset &SOffset,
7313 bool *OutUseUnscaledOp,
7314 unsigned *OutUnscaledOp,
7315 int64_t *EmittableOffset) {
7316 // Set output values in case of early exit.
7317 if (EmittableOffset)
7318 *EmittableOffset = 0;
7319 if (OutUseUnscaledOp)
7320 *OutUseUnscaledOp = false;
7321 if (OutUnscaledOp)
7322 *OutUnscaledOp = 0;
7323
7324 // Exit early for structured vector spills/fills as they can't take an
7325 // immediate offset.
7326 switch (MI.getOpcode()) {
7327 default:
7328 break;
7329 case AArch64::LD1Rv1d:
7330 case AArch64::LD1Rv2s:
7331 case AArch64::LD1Rv2d:
7332 case AArch64::LD1Rv4h:
7333 case AArch64::LD1Rv4s:
7334 case AArch64::LD1Rv8b:
7335 case AArch64::LD1Rv8h:
7336 case AArch64::LD1Rv16b:
7337 case AArch64::LD1Twov2d:
7338 case AArch64::LD1Threev2d:
7339 case AArch64::LD1Fourv2d:
7340 case AArch64::LD1Twov1d:
7341 case AArch64::LD1Threev1d:
7342 case AArch64::LD1Fourv1d:
7343 case AArch64::ST1Twov2d:
7344 case AArch64::ST1Threev2d:
7345 case AArch64::ST1Fourv2d:
7346 case AArch64::ST1Twov1d:
7347 case AArch64::ST1Threev1d:
7348 case AArch64::ST1Fourv1d:
7349 case AArch64::ST1i8:
7350 case AArch64::ST1i16:
7351 case AArch64::ST1i32:
7352 case AArch64::ST1i64:
7353 case AArch64::IRG:
7354 case AArch64::IRGstack:
7355 case AArch64::STGloop:
7356 case AArch64::STZGloop:
7358 }
7359
7360 // Get the min/max offset and the scale.
7361 TypeSize ScaleValue(0U, false), Width(0U, false);
7362 int64_t MinOff, MaxOff;
7363 if (!AArch64InstrInfo::getMemOpInfo(MI.getOpcode(), ScaleValue, Width, MinOff,
7364 MaxOff))
7365 llvm_unreachable("unhandled opcode in isAArch64FrameOffsetLegal");
7366
7367 // Construct the complete offset.
7368 bool IsMulVL = ScaleValue.isScalable();
7369 unsigned Scale = ScaleValue.getKnownMinValue();
7370 int64_t Offset = IsMulVL ? SOffset.getScalable() : SOffset.getFixed();
7371
7372 const MachineOperand &ImmOpnd =
7373 MI.getOperand(AArch64InstrInfo::getLoadStoreImmIdx(MI.getOpcode()));
7374 Offset += ImmOpnd.getImm() * Scale;
7375
7376 // If the offset doesn't match the scale, we rewrite the instruction to
7377 // use the unscaled instruction instead. Likewise, if we have a negative
7378 // offset and there is an unscaled op to use.
7379 std::optional<unsigned> UnscaledOp =
7381 bool useUnscaledOp = UnscaledOp && (Offset % Scale || Offset < 0);
7382 if (useUnscaledOp &&
7383 !AArch64InstrInfo::getMemOpInfo(*UnscaledOp, ScaleValue, Width, MinOff,
7384 MaxOff))
7385 llvm_unreachable("unhandled opcode in isAArch64FrameOffsetLegal");
7386
7387 Scale = ScaleValue.getKnownMinValue();
7388 assert(IsMulVL == ScaleValue.isScalable() &&
7389 "Unscaled opcode has different value for scalable");
7390
7391 int64_t Remainder = Offset % Scale;
7392 assert(!(Remainder && useUnscaledOp) &&
7393 "Cannot have remainder when using unscaled op");
7394
7395 assert(MinOff < MaxOff && "Unexpected Min/Max offsets");
7396 int64_t NewOffset = Offset / Scale;
7397 if (MinOff <= NewOffset && NewOffset <= MaxOff)
7398 Offset = Remainder;
7399 else {
7400 // Try to minimise the number of instructions required to materialise the
7401 // offset calculation. Specifically, for fixed offsets, if masking out the
7402 // low 12 bits leaves a legal add immediate, we can realise the offset
7403 // calculation with a single add instruction. Whenever this is possible,
7404 // prefer this split.
7405 int64_t HighPart = Offset & ~0xFFF;
7406 int64_t LowPart = Offset & 0xFFF;
7407 int64_t LowScaled = LowPart / Scale;
7408 if (!IsMulVL && NewOffset >= 0 && LowPart % Scale == 0 &&
7409 MinOff <= LowScaled && LowScaled <= MaxOff &&
7411 NewOffset = LowScaled;
7412 Offset = HighPart;
7413 } else {
7414 // Default to a greedy split: take the memop immediate to be maximum /
7415 // minimum expressible offset and materialise the remainder.
7416 NewOffset = NewOffset < 0 ? MinOff : MaxOff;
7417 Offset = Offset - (NewOffset * Scale);
7418 }
7419 }
7420
7421 if (EmittableOffset)
7422 *EmittableOffset = NewOffset;
7423 if (OutUseUnscaledOp)
7424 *OutUseUnscaledOp = useUnscaledOp;
7425 if (OutUnscaledOp && UnscaledOp)
7426 *OutUnscaledOp = *UnscaledOp;
7427
7428 if (IsMulVL)
7429 SOffset = StackOffset::get(SOffset.getFixed(), Offset);
7430 else
7431 SOffset = StackOffset::get(Offset, SOffset.getScalable());
7433 (SOffset ? 0 : AArch64FrameOffsetIsLegal);
7434}
7435
7437 unsigned FrameReg, StackOffset &Offset,
7438 const AArch64InstrInfo *TII) {
7439 unsigned Opcode = MI.getOpcode();
7440 unsigned ImmIdx = FrameRegIdx + 1;
7441
7442 if (Opcode == AArch64::ADDSXri || Opcode == AArch64::ADDXri) {
7443 Offset += StackOffset::getFixed(MI.getOperand(ImmIdx).getImm());
7444 emitFrameOffset(*MI.getParent(), MI, MI.getDebugLoc(),
7445 MI.getOperand(0).getReg(), FrameReg, Offset, TII,
7446 MachineInstr::NoFlags, (Opcode == AArch64::ADDSXri));
7447 MI.eraseFromParent();
7448 Offset = StackOffset();
7449 return true;
7450 }
7451
7452 int64_t NewOffset;
7453 unsigned UnscaledOp;
7454 bool UseUnscaledOp;
7455 int Status = isAArch64FrameOffsetLegal(MI, Offset, &UseUnscaledOp,
7456 &UnscaledOp, &NewOffset);
7459 // Replace the FrameIndex with FrameReg.
7460 MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
7461 if (UseUnscaledOp)
7462 MI.setDesc(TII->get(UnscaledOp));
7463
7464 MI.getOperand(ImmIdx).ChangeToImmediate(NewOffset);
7465 return !Offset;
7466 }
7467
7468 return false;
7469}
7470
7476
7477MCInst AArch64InstrInfo::getNop() const { return MCInstBuilder(AArch64::NOP); }
7478
7479// AArch64 supports MachineCombiner.
7480bool AArch64InstrInfo::useMachineCombiner() const { return true; }
7481
7482// True when Opc sets flag
7483static bool isCombineInstrSettingFlag(unsigned Opc) {
7484 switch (Opc) {
7485 case AArch64::ADDSWrr:
7486 case AArch64::ADDSWri:
7487 case AArch64::ADDSXrr:
7488 case AArch64::ADDSXri:
7489 case AArch64::SUBSWrr:
7490 case AArch64::SUBSXrr:
7491 // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
7492 case AArch64::SUBSWri:
7493 case AArch64::SUBSXri:
7494 return true;
7495 default:
7496 break;
7497 }
7498 return false;
7499}
7500
7501// 32b Opcodes that can be combined with a MUL
7502static bool isCombineInstrCandidate32(unsigned Opc) {
7503 switch (Opc) {
7504 case AArch64::ADDWrr:
7505 case AArch64::ADDWri:
7506 case AArch64::SUBWrr:
7507 case AArch64::ADDSWrr:
7508 case AArch64::ADDSWri:
7509 case AArch64::SUBSWrr:
7510 // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
7511 case AArch64::SUBWri:
7512 case AArch64::SUBSWri:
7513 return true;
7514 default:
7515 break;
7516 }
7517 return false;
7518}
7519
7520// 64b Opcodes that can be combined with a MUL
7521static bool isCombineInstrCandidate64(unsigned Opc) {
7522 switch (Opc) {
7523 case AArch64::ADDXrr:
7524 case AArch64::ADDXri:
7525 case AArch64::SUBXrr:
7526 case AArch64::ADDSXrr:
7527 case AArch64::ADDSXri:
7528 case AArch64::SUBSXrr:
7529 // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
7530 case AArch64::SUBXri:
7531 case AArch64::SUBSXri:
7532 case AArch64::ADDv8i8:
7533 case AArch64::ADDv16i8:
7534 case AArch64::ADDv4i16:
7535 case AArch64::ADDv8i16:
7536 case AArch64::ADDv2i32:
7537 case AArch64::ADDv4i32:
7538 case AArch64::SUBv8i8:
7539 case AArch64::SUBv16i8:
7540 case AArch64::SUBv4i16:
7541 case AArch64::SUBv8i16:
7542 case AArch64::SUBv2i32:
7543 case AArch64::SUBv4i32:
7544 return true;
7545 default:
7546 break;
7547 }
7548 return false;
7549}
7550
7551// FP Opcodes that can be combined with a FMUL.
7552static bool isCombineInstrCandidateFP(const MachineInstr &Inst) {
7553 switch (Inst.getOpcode()) {
7554 default:
7555 break;
7556 case AArch64::FADDHrr:
7557 case AArch64::FADDSrr:
7558 case AArch64::FADDDrr:
7559 case AArch64::FADDv4f16:
7560 case AArch64::FADDv8f16:
7561 case AArch64::FADDv2f32:
7562 case AArch64::FADDv2f64:
7563 case AArch64::FADDv4f32:
7564 case AArch64::FSUBHrr:
7565 case AArch64::FSUBSrr:
7566 case AArch64::FSUBDrr:
7567 case AArch64::FSUBv4f16:
7568 case AArch64::FSUBv8f16:
7569 case AArch64::FSUBv2f32:
7570 case AArch64::FSUBv2f64:
7571 case AArch64::FSUBv4f32:
7573 // We can fuse FADD/FSUB with FMUL, if fusion is either allowed globally by
7574 // the target options or if FADD/FSUB has the contract fast-math flag.
7575 return Options.AllowFPOpFusion == FPOpFusion::Fast ||
7577 }
7578 return false;
7579}
7580
7581// Opcodes that can be combined with a MUL
7585
7586//
7587// Utility routine that checks if \param MO is defined by an
7588// \param CombineOpc instruction in the basic block \param MBB
7590 unsigned CombineOpc, unsigned ZeroReg = 0,
7591 bool CheckZeroReg = false) {
7592 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
7593 MachineInstr *MI = nullptr;
7594
7595 if (MO.isReg() && MO.getReg().isVirtual())
7596 MI = MRI.getUniqueVRegDef(MO.getReg());
7597 // And it needs to be in the trace (otherwise, it won't have a depth).
7598 if (!MI || MI->getParent() != &MBB || MI->getOpcode() != CombineOpc)
7599 return false;
7600 // Must only used by the user we combine with.
7601 if (!MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()))
7602 return false;
7603
7604 if (CheckZeroReg) {
7605 assert(MI->getNumOperands() >= 4 && MI->getOperand(0).isReg() &&
7606 MI->getOperand(1).isReg() && MI->getOperand(2).isReg() &&
7607 MI->getOperand(3).isReg() && "MAdd/MSub must have a least 4 regs");
7608 // The third input reg must be zero.
7609 if (MI->getOperand(3).getReg() != ZeroReg)
7610 return false;
7611 }
7612
7613 if (isCombineInstrSettingFlag(CombineOpc) &&
7614 MI->findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true) == -1)
7615 return false;
7616
7617 return true;
7618}
7619
7620//
7621// Is \param MO defined by an integer multiply and can be combined?
7623 unsigned MulOpc, unsigned ZeroReg) {
7624 return canCombine(MBB, MO, MulOpc, ZeroReg, true);
7625}
7626
7627//
7628// Is \param MO defined by a floating-point multiply and can be combined?
7630 unsigned MulOpc) {
7631 return canCombine(MBB, MO, MulOpc);
7632}
7633
7634// TODO: There are many more machine instruction opcodes to match:
7635// 1. Other data types (integer, vectors)
7636// 2. Other math / logic operations (xor, or)
7637// 3. Other forms of the same operation (intrinsics and other variants)
7638bool AArch64InstrInfo::isAssociativeAndCommutative(const MachineInstr &Inst,
7639 bool Invert) const {
7640 if (Invert)
7641 return false;
7642 switch (Inst.getOpcode()) {
7643 // == Floating-point types ==
7644 // -- Floating-point instructions --
7645 case AArch64::FADDHrr:
7646 case AArch64::FADDSrr:
7647 case AArch64::FADDDrr:
7648 case AArch64::FMULHrr:
7649 case AArch64::FMULSrr:
7650 case AArch64::FMULDrr:
7651 case AArch64::FMULX16:
7652 case AArch64::FMULX32:
7653 case AArch64::FMULX64:
7654 // -- Advanced SIMD instructions --
7655 case AArch64::FADDv4f16:
7656 case AArch64::FADDv8f16:
7657 case AArch64::FADDv2f32:
7658 case AArch64::FADDv4f32:
7659 case AArch64::FADDv2f64:
7660 case AArch64::FMULv4f16:
7661 case AArch64::FMULv8f16:
7662 case AArch64::FMULv2f32:
7663 case AArch64::FMULv4f32:
7664 case AArch64::FMULv2f64:
7665 case AArch64::FMULXv4f16:
7666 case AArch64::FMULXv8f16:
7667 case AArch64::FMULXv2f32:
7668 case AArch64::FMULXv4f32:
7669 case AArch64::FMULXv2f64:
7670 // -- SVE instructions --
7671 // Opcodes FMULX_ZZZ_? don't exist because there is no unpredicated FMULX
7672 // in the SVE instruction set (though there are predicated ones).
7673 case AArch64::FADD_ZZZ_H:
7674 case AArch64::FADD_ZZZ_S:
7675 case AArch64::FADD_ZZZ_D:
7676 case AArch64::FMUL_ZZZ_H:
7677 case AArch64::FMUL_ZZZ_S:
7678 case AArch64::FMUL_ZZZ_D:
7681
7682 // == Integer types ==
7683 // -- Base instructions --
7684 // Opcodes MULWrr and MULXrr don't exist because
7685 // `MUL <Wd>, <Wn>, <Wm>` and `MUL <Xd>, <Xn>, <Xm>` are aliases of
7686 // `MADD <Wd>, <Wn>, <Wm>, WZR` and `MADD <Xd>, <Xn>, <Xm>, XZR` respectively.
7687 // The machine-combiner does not support three-source-operands machine
7688 // instruction. So we cannot reassociate MULs.
7689 case AArch64::ADDWrr:
7690 case AArch64::ADDXrr:
7691 case AArch64::ANDWrr:
7692 case AArch64::ANDXrr:
7693 case AArch64::ORRWrr:
7694 case AArch64::ORRXrr:
7695 case AArch64::EORWrr:
7696 case AArch64::EORXrr:
7697 case AArch64::EONWrr:
7698 case AArch64::EONXrr:
7699 // -- Advanced SIMD instructions --
7700 // Opcodes MULv1i64 and MULv2i64 don't exist because there is no 64-bit MUL
7701 // in the Advanced SIMD instruction set.
7702 case AArch64::ADDv8i8:
7703 case AArch64::ADDv16i8:
7704 case AArch64::ADDv4i16:
7705 case AArch64::ADDv8i16:
7706 case AArch64::ADDv2i32:
7707 case AArch64::ADDv4i32:
7708 case AArch64::ADDv1i64:
7709 case AArch64::ADDv2i64:
7710 case AArch64::MULv8i8:
7711 case AArch64::MULv16i8:
7712 case AArch64::MULv4i16:
7713 case AArch64::MULv8i16:
7714 case AArch64::MULv2i32:
7715 case AArch64::MULv4i32:
7716 case AArch64::ANDv8i8:
7717 case AArch64::ANDv16i8:
7718 case AArch64::ORRv8i8:
7719 case AArch64::ORRv16i8:
7720 case AArch64::EORv8i8:
7721 case AArch64::EORv16i8:
7722 // -- SVE instructions --
7723 case AArch64::ADD_ZZZ_B:
7724 case AArch64::ADD_ZZZ_H:
7725 case AArch64::ADD_ZZZ_S:
7726 case AArch64::ADD_ZZZ_D:
7727 case AArch64::MUL_ZZZ_B:
7728 case AArch64::MUL_ZZZ_H:
7729 case AArch64::MUL_ZZZ_S:
7730 case AArch64::MUL_ZZZ_D:
7731 case AArch64::AND_ZZZ:
7732 case AArch64::ORR_ZZZ:
7733 case AArch64::EOR_ZZZ:
7734 return true;
7735
7736 default:
7737 return false;
7738 }
7739}
7740
7741/// Find instructions that can be turned into madd.
7743 SmallVectorImpl<unsigned> &Patterns) {
7744 unsigned Opc = Root.getOpcode();
7745 MachineBasicBlock &MBB = *Root.getParent();
7746 bool Found = false;
7747
7749 return false;
7751 int Cmp_NZCV =
7752 Root.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true);
7753 // When NZCV is live bail out.
7754 if (Cmp_NZCV == -1)
7755 return false;
7756 unsigned NewOpc = convertToNonFlagSettingOpc(Root);
7757 // When opcode can't change bail out.
7758 // CHECKME: do we miss any cases for opcode conversion?
7759 if (NewOpc == Opc)
7760 return false;
7761 Opc = NewOpc;
7762 }
7763
7764 auto setFound = [&](int Opcode, int Operand, unsigned ZeroReg,
7765 unsigned Pattern) {
7766 if (canCombineWithMUL(MBB, Root.getOperand(Operand), Opcode, ZeroReg)) {
7767 Patterns.push_back(Pattern);
7768 Found = true;
7769 }
7770 };
7771
7772 auto setVFound = [&](int Opcode, int Operand, unsigned Pattern) {
7773 if (canCombine(MBB, Root.getOperand(Operand), Opcode)) {
7774 Patterns.push_back(Pattern);
7775 Found = true;
7776 }
7777 };
7778
7780
7781 switch (Opc) {
7782 default:
7783 break;
7784 case AArch64::ADDWrr:
7785 assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
7786 "ADDWrr does not have register operands");
7787 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULADDW_OP1);
7788 setFound(AArch64::MADDWrrr, 2, AArch64::WZR, MCP::MULADDW_OP2);
7789 break;
7790 case AArch64::ADDXrr:
7791 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULADDX_OP1);
7792 setFound(AArch64::MADDXrrr, 2, AArch64::XZR, MCP::MULADDX_OP2);
7793 break;
7794 case AArch64::SUBWrr:
7795 setFound(AArch64::MADDWrrr, 2, AArch64::WZR, MCP::MULSUBW_OP2);
7796 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULSUBW_OP1);
7797 break;
7798 case AArch64::SUBXrr:
7799 setFound(AArch64::MADDXrrr, 2, AArch64::XZR, MCP::MULSUBX_OP2);
7800 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULSUBX_OP1);
7801 break;
7802 case AArch64::ADDWri:
7803 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULADDWI_OP1);
7804 break;
7805 case AArch64::ADDXri:
7806 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULADDXI_OP1);
7807 break;
7808 case AArch64::SUBWri:
7809 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULSUBWI_OP1);
7810 break;
7811 case AArch64::SUBXri:
7812 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULSUBXI_OP1);
7813 break;
7814 case AArch64::ADDv8i8:
7815 setVFound(AArch64::MULv8i8, 1, MCP::MULADDv8i8_OP1);
7816 setVFound(AArch64::MULv8i8, 2, MCP::MULADDv8i8_OP2);
7817 break;
7818 case AArch64::ADDv16i8:
7819 setVFound(AArch64::MULv16i8, 1, MCP::MULADDv16i8_OP1);
7820 setVFound(AArch64::MULv16i8, 2, MCP::MULADDv16i8_OP2);
7821 break;
7822 case AArch64::ADDv4i16:
7823 setVFound(AArch64::MULv4i16, 1, MCP::MULADDv4i16_OP1);
7824 setVFound(AArch64::MULv4i16, 2, MCP::MULADDv4i16_OP2);
7825 setVFound(AArch64::MULv4i16_indexed, 1, MCP::MULADDv4i16_indexed_OP1);
7826 setVFound(AArch64::MULv4i16_indexed, 2, MCP::MULADDv4i16_indexed_OP2);
7827 break;
7828 case AArch64::ADDv8i16:
7829 setVFound(AArch64::MULv8i16, 1, MCP::MULADDv8i16_OP1);
7830 setVFound(AArch64::MULv8i16, 2, MCP::MULADDv8i16_OP2);
7831 setVFound(AArch64::MULv8i16_indexed, 1, MCP::MULADDv8i16_indexed_OP1);
7832 setVFound(AArch64::MULv8i16_indexed, 2, MCP::MULADDv8i16_indexed_OP2);
7833 break;
7834 case AArch64::ADDv2i32:
7835 setVFound(AArch64::MULv2i32, 1, MCP::MULADDv2i32_OP1);
7836 setVFound(AArch64::MULv2i32, 2, MCP::MULADDv2i32_OP2);
7837 setVFound(AArch64::MULv2i32_indexed, 1, MCP::MULADDv2i32_indexed_OP1);
7838 setVFound(AArch64::MULv2i32_indexed, 2, MCP::MULADDv2i32_indexed_OP2);
7839 break;
7840 case AArch64::ADDv4i32:
7841 setVFound(AArch64::MULv4i32, 1, MCP::MULADDv4i32_OP1);
7842 setVFound(AArch64::MULv4i32, 2, MCP::MULADDv4i32_OP2);
7843 setVFound(AArch64::MULv4i32_indexed, 1, MCP::MULADDv4i32_indexed_OP1);
7844 setVFound(AArch64::MULv4i32_indexed, 2, MCP::MULADDv4i32_indexed_OP2);
7845 break;
7846 case AArch64::SUBv8i8:
7847 setVFound(AArch64::MULv8i8, 1, MCP::MULSUBv8i8_OP1);
7848 setVFound(AArch64::MULv8i8, 2, MCP::MULSUBv8i8_OP2);
7849 break;
7850 case AArch64::SUBv16i8:
7851 setVFound(AArch64::MULv16i8, 1, MCP::MULSUBv16i8_OP1);
7852 setVFound(AArch64::MULv16i8, 2, MCP::MULSUBv16i8_OP2);
7853 break;
7854 case AArch64::SUBv4i16:
7855 setVFound(AArch64::MULv4i16, 1, MCP::MULSUBv4i16_OP1);
7856 setVFound(AArch64::MULv4i16, 2, MCP::MULSUBv4i16_OP2);
7857 setVFound(AArch64::MULv4i16_indexed, 1, MCP::MULSUBv4i16_indexed_OP1);
7858 setVFound(AArch64::MULv4i16_indexed, 2, MCP::MULSUBv4i16_indexed_OP2);
7859 break;
7860 case AArch64::SUBv8i16:
7861 setVFound(AArch64::MULv8i16, 1, MCP::MULSUBv8i16_OP1);
7862 setVFound(AArch64::MULv8i16, 2, MCP::MULSUBv8i16_OP2);
7863 setVFound(AArch64::MULv8i16_indexed, 1, MCP::MULSUBv8i16_indexed_OP1);
7864 setVFound(AArch64::MULv8i16_indexed, 2, MCP::MULSUBv8i16_indexed_OP2);
7865 break;
7866 case AArch64::SUBv2i32:
7867 setVFound(AArch64::MULv2i32, 1, MCP::MULSUBv2i32_OP1);
7868 setVFound(AArch64::MULv2i32, 2, MCP::MULSUBv2i32_OP2);
7869 setVFound(AArch64::MULv2i32_indexed, 1, MCP::MULSUBv2i32_indexed_OP1);
7870 setVFound(AArch64::MULv2i32_indexed, 2, MCP::MULSUBv2i32_indexed_OP2);
7871 break;
7872 case AArch64::SUBv4i32:
7873 setVFound(AArch64::MULv4i32, 1, MCP::MULSUBv4i32_OP1);
7874 setVFound(AArch64::MULv4i32, 2, MCP::MULSUBv4i32_OP2);
7875 setVFound(AArch64::MULv4i32_indexed, 1, MCP::MULSUBv4i32_indexed_OP1);
7876 setVFound(AArch64::MULv4i32_indexed, 2, MCP::MULSUBv4i32_indexed_OP2);
7877 break;
7878 }
7879 return Found;
7880}
7881
7882bool AArch64InstrInfo::isAccumulationOpcode(unsigned Opcode) const {
7883 switch (Opcode) {
7884 default:
7885 break;
7886 case AArch64::UABALB_ZZZ_D:
7887 case AArch64::UABALB_ZZZ_H:
7888 case AArch64::UABALB_ZZZ_S:
7889 case AArch64::UABALT_ZZZ_D:
7890 case AArch64::UABALT_ZZZ_H:
7891 case AArch64::UABALT_ZZZ_S:
7892 case AArch64::SABALB_ZZZ_D:
7893 case AArch64::SABALB_ZZZ_S:
7894 case AArch64::SABALB_ZZZ_H:
7895 case AArch64::SABALT_ZZZ_D:
7896 case AArch64::SABALT_ZZZ_S:
7897 case AArch64::SABALT_ZZZ_H:
7898 case AArch64::UABALv16i8_v8i16:
7899 case AArch64::UABALv2i32_v2i64:
7900 case AArch64::UABALv4i16_v4i32:
7901 case AArch64::UABALv4i32_v2i64:
7902 case AArch64::UABALv8i16_v4i32:
7903 case AArch64::UABALv8i8_v8i16:
7904 case AArch64::UABAv16i8:
7905 case AArch64::UABAv2i32:
7906 case AArch64::UABAv4i16:
7907 case AArch64::UABAv4i32:
7908 case AArch64::UABAv8i16:
7909 case AArch64::UABAv8i8:
7910 case AArch64::SABALv16i8_v8i16:
7911 case AArch64::SABALv2i32_v2i64:
7912 case AArch64::SABALv4i16_v4i32:
7913 case AArch64::SABALv4i32_v2i64:
7914 case AArch64::SABALv8i16_v4i32:
7915 case AArch64::SABALv8i8_v8i16:
7916 case AArch64::SABAv16i8:
7917 case AArch64::SABAv2i32:
7918 case AArch64::SABAv4i16:
7919 case AArch64::SABAv4i32:
7920 case AArch64::SABAv8i16:
7921 case AArch64::SABAv8i8:
7922 return true;
7923 }
7924
7925 return false;
7926}
7927
7928unsigned AArch64InstrInfo::getAccumulationStartOpcode(
7929 unsigned AccumulationOpcode) const {
7930 switch (AccumulationOpcode) {
7931 default:
7932 llvm_unreachable("Unsupported accumulation Opcode!");
7933 case AArch64::UABALB_ZZZ_D:
7934 return AArch64::UABDLB_ZZZ_D;
7935 case AArch64::UABALB_ZZZ_H:
7936 return AArch64::UABDLB_ZZZ_H;
7937 case AArch64::UABALB_ZZZ_S:
7938 return AArch64::UABDLB_ZZZ_S;
7939 case AArch64::UABALT_ZZZ_D:
7940 return AArch64::UABDLT_ZZZ_D;
7941 case AArch64::UABALT_ZZZ_H:
7942 return AArch64::UABDLT_ZZZ_H;
7943 case AArch64::UABALT_ZZZ_S:
7944 return AArch64::UABDLT_ZZZ_S;
7945 case AArch64::UABALv16i8_v8i16:
7946 return AArch64::UABDLv16i8_v8i16;
7947 case AArch64::UABALv2i32_v2i64:
7948 return AArch64::UABDLv2i32_v2i64;
7949 case AArch64::UABALv4i16_v4i32:
7950 return AArch64::UABDLv4i16_v4i32;
7951 case AArch64::UABALv4i32_v2i64:
7952 return AArch64::UABDLv4i32_v2i64;
7953 case AArch64::UABALv8i16_v4i32:
7954 return AArch64::UABDLv8i16_v4i32;
7955 case AArch64::UABALv8i8_v8i16:
7956 return AArch64::UABDLv8i8_v8i16;
7957 case AArch64::UABAv16i8:
7958 return AArch64::UABDv16i8;
7959 case AArch64::UABAv2i32:
7960 return AArch64::UABDv2i32;
7961 case AArch64::UABAv4i16:
7962 return AArch64::UABDv4i16;
7963 case AArch64::UABAv4i32:
7964 return AArch64::UABDv4i32;
7965 case AArch64::UABAv8i16:
7966 return AArch64::UABDv8i16;
7967 case AArch64::UABAv8i8:
7968 return AArch64::UABDv8i8;
7969 case AArch64::SABALB_ZZZ_D:
7970 return AArch64::SABDLB_ZZZ_D;
7971 case AArch64::SABALB_ZZZ_S:
7972 return AArch64::SABDLB_ZZZ_S;
7973 case AArch64::SABALB_ZZZ_H:
7974 return AArch64::SABDLB_ZZZ_H;
7975 case AArch64::SABALT_ZZZ_D:
7976 return AArch64::SABDLT_ZZZ_D;
7977 case AArch64::SABALT_ZZZ_S:
7978 return AArch64::SABDLT_ZZZ_S;
7979 case AArch64::SABALT_ZZZ_H:
7980 return AArch64::SABDLT_ZZZ_H;
7981 case AArch64::SABALv16i8_v8i16:
7982 return AArch64::SABDLv16i8_v8i16;
7983 case AArch64::SABALv2i32_v2i64:
7984 return AArch64::SABDLv2i32_v2i64;
7985 case AArch64::SABALv4i16_v4i32:
7986 return AArch64::SABDLv4i16_v4i32;
7987 case AArch64::SABALv4i32_v2i64:
7988 return AArch64::SABDLv4i32_v2i64;
7989 case AArch64::SABALv8i16_v4i32:
7990 return AArch64::SABDLv8i16_v4i32;
7991 case AArch64::SABALv8i8_v8i16:
7992 return AArch64::SABDLv8i8_v8i16;
7993 case AArch64::SABAv16i8:
7994 return AArch64::SABDv16i8;
7995 case AArch64::SABAv2i32:
7996 return AArch64::SABAv2i32;
7997 case AArch64::SABAv4i16:
7998 return AArch64::SABDv4i16;
7999 case AArch64::SABAv4i32:
8000 return AArch64::SABDv4i32;
8001 case AArch64::SABAv8i16:
8002 return AArch64::SABDv8i16;
8003 case AArch64::SABAv8i8:
8004 return AArch64::SABDv8i8;
8005 }
8006}
8007
8008/// Floating-Point Support
8009
8010/// Find instructions that can be turned into madd.
8012 SmallVectorImpl<unsigned> &Patterns) {
8013
8014 if (!isCombineInstrCandidateFP(Root))
8015 return false;
8016
8017 MachineBasicBlock &MBB = *Root.getParent();
8018 bool Found = false;
8019
8020 auto Match = [&](int Opcode, int Operand, unsigned Pattern) -> bool {
8021 if (canCombineWithFMUL(MBB, Root.getOperand(Operand), Opcode)) {
8022 Patterns.push_back(Pattern);
8023 return true;
8024 }
8025 return false;
8026 };
8027
8029
8030 switch (Root.getOpcode()) {
8031 default:
8032 assert(false && "Unsupported FP instruction in combiner\n");
8033 break;
8034 case AArch64::FADDHrr:
8035 assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
8036 "FADDHrr does not have register operands");
8037
8038 Found = Match(AArch64::FMULHrr, 1, MCP::FMULADDH_OP1);
8039 Found |= Match(AArch64::FMULHrr, 2, MCP::FMULADDH_OP2);
8040 break;
8041 case AArch64::FADDSrr:
8042 assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
8043 "FADDSrr does not have register operands");
8044
8045 Found |= Match(AArch64::FMULSrr, 1, MCP::FMULADDS_OP1) ||
8046 Match(AArch64::FMULv1i32_indexed, 1, MCP::FMLAv1i32_indexed_OP1);
8047
8048 Found |= Match(AArch64::FMULSrr, 2, MCP::FMULADDS_OP2) ||
8049 Match(AArch64::FMULv1i32_indexed, 2, MCP::FMLAv1i32_indexed_OP2);
8050 break;
8051 case AArch64::FADDDrr:
8052 Found |= Match(AArch64::FMULDrr, 1, MCP::FMULADDD_OP1) ||
8053 Match(AArch64::FMULv1i64_indexed, 1, MCP::FMLAv1i64_indexed_OP1);
8054
8055 Found |= Match(AArch64::FMULDrr, 2, MCP::FMULADDD_OP2) ||
8056 Match(AArch64::FMULv1i64_indexed, 2, MCP::FMLAv1i64_indexed_OP2);
8057 break;
8058 case AArch64::FADDv4f16:
8059 Found |= Match(AArch64::FMULv4i16_indexed, 1, MCP::FMLAv4i16_indexed_OP1) ||
8060 Match(AArch64::FMULv4f16, 1, MCP::FMLAv4f16_OP1);
8061
8062 Found |= Match(AArch64::FMULv4i16_indexed, 2, MCP::FMLAv4i16_indexed_OP2) ||
8063 Match(AArch64::FMULv4f16, 2, MCP::FMLAv4f16_OP2);
8064 break;
8065 case AArch64::FADDv8f16:
8066 Found |= Match(AArch64::FMULv8i16_indexed, 1, MCP::FMLAv8i16_indexed_OP1) ||
8067 Match(AArch64::FMULv8f16, 1, MCP::FMLAv8f16_OP1);
8068
8069 Found |= Match(AArch64::FMULv8i16_indexed, 2, MCP::FMLAv8i16_indexed_OP2) ||
8070 Match(AArch64::FMULv8f16, 2, MCP::FMLAv8f16_OP2);
8071 break;
8072 case AArch64::FADDv2f32:
8073 Found |= Match(AArch64::FMULv2i32_indexed, 1, MCP::FMLAv2i32_indexed_OP1) ||
8074 Match(AArch64::FMULv2f32, 1, MCP::FMLAv2f32_OP1);
8075
8076 Found |= Match(AArch64::FMULv2i32_indexed, 2, MCP::FMLAv2i32_indexed_OP2) ||
8077 Match(AArch64::FMULv2f32, 2, MCP::FMLAv2f32_OP2);
8078 break;
8079 case AArch64::FADDv2f64:
8080 Found |= Match(AArch64::FMULv2i64_indexed, 1, MCP::FMLAv2i64_indexed_OP1) ||
8081 Match(AArch64::FMULv2f64, 1, MCP::FMLAv2f64_OP1);
8082
8083 Found |= Match(AArch64::FMULv2i64_indexed, 2, MCP::FMLAv2i64_indexed_OP2) ||
8084 Match(AArch64::FMULv2f64, 2, MCP::FMLAv2f64_OP2);
8085 break;
8086 case AArch64::FADDv4f32:
8087 Found |= Match(AArch64::FMULv4i32_indexed, 1, MCP::FMLAv4i32_indexed_OP1) ||
8088 Match(AArch64::FMULv4f32, 1, MCP::FMLAv4f32_OP1);
8089
8090 Found |= Match(AArch64::FMULv4i32_indexed, 2, MCP::FMLAv4i32_indexed_OP2) ||
8091 Match(AArch64::FMULv4f32, 2, MCP::FMLAv4f32_OP2);
8092 break;
8093 case AArch64::FSUBHrr:
8094 Found = Match(AArch64::FMULHrr, 1, MCP::FMULSUBH_OP1);
8095 Found |= Match(AArch64::FMULHrr, 2, MCP::FMULSUBH_OP2);
8096 Found |= Match(AArch64::FNMULHrr, 1, MCP::FNMULSUBH_OP1);
8097 break;
8098 case AArch64::FSUBSrr:
8099 Found = Match(AArch64::FMULSrr, 1, MCP::FMULSUBS_OP1);
8100
8101 Found |= Match(AArch64::FMULSrr, 2, MCP::FMULSUBS_OP2) ||
8102 Match(AArch64::FMULv1i32_indexed, 2, MCP::FMLSv1i32_indexed_OP2);
8103
8104 Found |= Match(AArch64::FNMULSrr, 1, MCP::FNMULSUBS_OP1);
8105 break;
8106 case AArch64::FSUBDrr:
8107 Found = Match(AArch64::FMULDrr, 1, MCP::FMULSUBD_OP1);
8108
8109 Found |= Match(AArch64::FMULDrr, 2, MCP::FMULSUBD_OP2) ||
8110 Match(AArch64::FMULv1i64_indexed, 2, MCP::FMLSv1i64_indexed_OP2);
8111
8112 Found |= Match(AArch64::FNMULDrr, 1, MCP::FNMULSUBD_OP1);
8113 break;
8114 case AArch64::FSUBv4f16:
8115 Found |= Match(AArch64::FMULv4i16_indexed, 2, MCP::FMLSv4i16_indexed_OP2) ||
8116 Match(AArch64::FMULv4f16, 2, MCP::FMLSv4f16_OP2);
8117
8118 Found |= Match(AArch64::FMULv4i16_indexed, 1, MCP::FMLSv4i16_indexed_OP1) ||
8119 Match(AArch64::FMULv4f16, 1, MCP::FMLSv4f16_OP1);
8120 break;
8121 case AArch64::FSUBv8f16:
8122 Found |= Match(AArch64::FMULv8i16_indexed, 2, MCP::FMLSv8i16_indexed_OP2) ||
8123 Match(AArch64::FMULv8f16, 2, MCP::FMLSv8f16_OP2);
8124
8125 Found |= Match(AArch64::FMULv8i16_indexed, 1, MCP::FMLSv8i16_indexed_OP1) ||
8126 Match(AArch64::FMULv8f16, 1, MCP::FMLSv8f16_OP1);
8127 break;
8128 case AArch64::FSUBv2f32:
8129 Found |= Match(AArch64::FMULv2i32_indexed, 2, MCP::FMLSv2i32_indexed_OP2) ||
8130 Match(AArch64::FMULv2f32, 2, MCP::FMLSv2f32_OP2);
8131
8132 Found |= Match(AArch64::FMULv2i32_indexed, 1, MCP::FMLSv2i32_indexed_OP1) ||
8133 Match(AArch64::FMULv2f32, 1, MCP::FMLSv2f32_OP1);
8134 break;
8135 case AArch64::FSUBv2f64:
8136 Found |= Match(AArch64::FMULv2i64_indexed, 2, MCP::FMLSv2i64_indexed_OP2) ||
8137 Match(AArch64::FMULv2f64, 2, MCP::FMLSv2f64_OP2);
8138
8139 Found |= Match(AArch64::FMULv2i64_indexed, 1, MCP::FMLSv2i64_indexed_OP1) ||
8140 Match(AArch64::FMULv2f64, 1, MCP::FMLSv2f64_OP1);
8141 break;
8142 case AArch64::FSUBv4f32:
8143 Found |= Match(AArch64::FMULv4i32_indexed, 2, MCP::FMLSv4i32_indexed_OP2) ||
8144 Match(AArch64::FMULv4f32, 2, MCP::FMLSv4f32_OP2);
8145
8146 Found |= Match(AArch64::FMULv4i32_indexed, 1, MCP::FMLSv4i32_indexed_OP1) ||
8147 Match(AArch64::FMULv4f32, 1, MCP::FMLSv4f32_OP1);
8148 break;
8149 }
8150 return Found;
8151}
8152
8154 SmallVectorImpl<unsigned> &Patterns) {
8155 MachineBasicBlock &MBB = *Root.getParent();
8156 bool Found = false;
8157
8158 auto Match = [&](unsigned Opcode, int Operand, unsigned Pattern) -> bool {
8159 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
8160 MachineOperand &MO = Root.getOperand(Operand);
8161 MachineInstr *MI = nullptr;
8162 if (MO.isReg() && MO.getReg().isVirtual())
8163 MI = MRI.getUniqueVRegDef(MO.getReg());
8164 // Ignore No-op COPYs in FMUL(COPY(DUP(..)))
8165 if (MI && MI->getOpcode() == TargetOpcode::COPY &&
8166 MI->getOperand(1).getReg().isVirtual())
8167 MI = MRI.getUniqueVRegDef(MI->getOperand(1).getReg());
8168 if (MI && MI->getOpcode() == Opcode) {
8169 Patterns.push_back(Pattern);
8170 return true;
8171 }
8172 return false;
8173 };
8174
8176
8177 switch (Root.getOpcode()) {
8178 default:
8179 return false;
8180 case AArch64::FMULv2f32:
8181 Found = Match(AArch64::DUPv2i32lane, 1, MCP::FMULv2i32_indexed_OP1);
8182 Found |= Match(AArch64::DUPv2i32lane, 2, MCP::FMULv2i32_indexed_OP2);
8183 break;
8184 case AArch64::FMULv2f64:
8185 Found = Match(AArch64::DUPv2i64lane, 1, MCP::FMULv2i64_indexed_OP1);
8186 Found |= Match(AArch64::DUPv2i64lane, 2, MCP::FMULv2i64_indexed_OP2);
8187 break;
8188 case AArch64::FMULv4f16:
8189 Found = Match(AArch64::DUPv4i16lane, 1, MCP::FMULv4i16_indexed_OP1);
8190 Found |= Match(AArch64::DUPv4i16lane, 2, MCP::FMULv4i16_indexed_OP2);
8191 break;
8192 case AArch64::FMULv4f32:
8193 Found = Match(AArch64::DUPv4i32lane, 1, MCP::FMULv4i32_indexed_OP1);
8194 Found |= Match(AArch64::DUPv4i32lane, 2, MCP::FMULv4i32_indexed_OP2);
8195 break;
8196 case AArch64::FMULv8f16:
8197 Found = Match(AArch64::DUPv8i16lane, 1, MCP::FMULv8i16_indexed_OP1);
8198 Found |= Match(AArch64::DUPv8i16lane, 2, MCP::FMULv8i16_indexed_OP2);
8199 break;
8200 }
8201
8202 return Found;
8203}
8204
8206 SmallVectorImpl<unsigned> &Patterns) {
8207 unsigned Opc = Root.getOpcode();
8208 MachineBasicBlock &MBB = *Root.getParent();
8209 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
8210
8211 auto Match = [&](unsigned Opcode, unsigned Pattern) -> bool {
8212 MachineOperand &MO = Root.getOperand(1);
8214 if (MI != nullptr && (MI->getOpcode() == Opcode) &&
8215 MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()) &&
8219 MI->getFlag(MachineInstr::MIFlag::FmNsz)) {
8220 Patterns.push_back(Pattern);
8221 return true;
8222 }
8223 return false;
8224 };
8225
8226 switch (Opc) {
8227 default:
8228 break;
8229 case AArch64::FNEGDr:
8230 return Match(AArch64::FMADDDrrr, AArch64MachineCombinerPattern::FNMADD);
8231 case AArch64::FNEGSr:
8232 return Match(AArch64::FMADDSrrr, AArch64MachineCombinerPattern::FNMADD);
8233 }
8234
8235 return false;
8236}
8237
8238/// Return true when a code sequence can improve throughput. It
8239/// should be called only for instructions in loops.
8240/// \param Pattern - combiner pattern
8242 switch (Pattern) {
8243 default:
8244 break;
8350 return true;
8351 } // end switch (Pattern)
8352 return false;
8353}
8354
8355/// Find other MI combine patterns.
8357 SmallVectorImpl<unsigned> &Patterns) {
8358 // A - (B + C) ==> (A - B) - C or (A - C) - B
8359 unsigned Opc = Root.getOpcode();
8360 MachineBasicBlock &MBB = *Root.getParent();
8361
8362 switch (Opc) {
8363 case AArch64::SUBWrr:
8364 case AArch64::SUBSWrr:
8365 case AArch64::SUBXrr:
8366 case AArch64::SUBSXrr:
8367 // Found candidate root.
8368 break;
8369 default:
8370 return false;
8371 }
8372
8374 Root.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true) ==
8375 -1)
8376 return false;
8377
8378 if (canCombine(MBB, Root.getOperand(2), AArch64::ADDWrr) ||
8379 canCombine(MBB, Root.getOperand(2), AArch64::ADDSWrr) ||
8380 canCombine(MBB, Root.getOperand(2), AArch64::ADDXrr) ||
8381 canCombine(MBB, Root.getOperand(2), AArch64::ADDSXrr)) {
8384 return true;
8385 }
8386
8387 return false;
8388}
8389
8390/// Check if the given instruction forms a gather load pattern that can be
8391/// optimized for better Memory-Level Parallelism (MLP). This function
8392/// identifies chains of NEON lane load instructions that load data from
8393/// different memory addresses into individual lanes of a 128-bit vector
8394/// register, then attempts to split the pattern into parallel loads to break
8395/// the serial dependency between instructions.
8396///
8397/// Pattern Matched:
8398/// Initial scalar load -> SUBREG_TO_REG (lane 0) -> LD1i* (lane 1) ->
8399/// LD1i* (lane 2) -> ... -> LD1i* (lane N-1, Root)
8400///
8401/// Transformed Into:
8402/// Two parallel vector loads using fewer lanes each, followed by ZIP1v2i64
8403/// to combine the results, enabling better memory-level parallelism.
8404///
8405/// Supported Element Types:
8406/// - 32-bit elements (LD1i32, 4 lanes total)
8407/// - 16-bit elements (LD1i16, 8 lanes total)
8408/// - 8-bit elements (LD1i8, 16 lanes total)
8410 SmallVectorImpl<unsigned> &Patterns,
8411 unsigned LoadLaneOpCode, unsigned NumLanes) {
8412 const MachineFunction *MF = Root.getMF();
8413
8414 // Early exit if optimizing for size.
8415 if (MF->getFunction().hasMinSize())
8416 return false;
8417
8418 const MachineRegisterInfo &MRI = MF->getRegInfo();
8420
8421 // The root of the pattern must load into the last lane of the vector.
8422 if (Root.getOperand(2).getImm() != NumLanes - 1)
8423 return false;
8424
8425 // Check that we have load into all lanes except lane 0.
8426 // For each load we also want to check that:
8427 // 1. It has a single non-debug use (since we will be replacing the virtual
8428 // register)
8429 // 2. That the addressing mode only uses a single pointer operand
8430 auto *CurrInstr = MRI.getUniqueVRegDef(Root.getOperand(1).getReg());
8431 auto Range = llvm::seq<unsigned>(1, NumLanes - 1);
8432 SmallSet<unsigned, 16> RemainingLanes(Range.begin(), Range.end());
8434 while (!RemainingLanes.empty() && CurrInstr &&
8435 CurrInstr->getOpcode() == LoadLaneOpCode &&
8436 MRI.hasOneNonDBGUse(CurrInstr->getOperand(0).getReg()) &&
8437 CurrInstr->getNumOperands() == 4) {
8438 RemainingLanes.erase(CurrInstr->getOperand(2).getImm());
8439 LoadInstrs.push_back(CurrInstr);
8440 CurrInstr = MRI.getUniqueVRegDef(CurrInstr->getOperand(1).getReg());
8441 }
8442
8443 // Check that we have found a match for lanes N-1.. 1.
8444 if (!RemainingLanes.empty())
8445 return false;
8446
8447 // Match the SUBREG_TO_REG sequence.
8448 if (CurrInstr->getOpcode() != TargetOpcode::SUBREG_TO_REG)
8449 return false;
8450
8451 // Verify that the subreg to reg loads an integer into the first lane.
8452 auto Lane0LoadReg = CurrInstr->getOperand(1).getReg();
8453 unsigned SingleLaneSizeInBits = 128 / NumLanes;
8454 if (TRI->getRegSizeInBits(Lane0LoadReg, MRI) != SingleLaneSizeInBits)
8455 return false;
8456
8457 // Verify that it also has a single non debug use.
8458 if (!MRI.hasOneNonDBGUse(Lane0LoadReg))
8459 return false;
8460
8461 LoadInstrs.push_back(MRI.getUniqueVRegDef(Lane0LoadReg));
8462
8463 // If there is any chance of aliasing, do not apply the pattern.
8464 // Walk backward through the MBB starting from Root.
8465 // Exit early if we've encountered all load instructions or hit the search
8466 // limit.
8467 auto MBBItr = Root.getIterator();
8468 unsigned RemainingSteps = GatherOptSearchLimit;
8469 SmallPtrSet<const MachineInstr *, 16> RemainingLoadInstrs;
8470 RemainingLoadInstrs.insert(LoadInstrs.begin(), LoadInstrs.end());
8471 const MachineBasicBlock *MBB = Root.getParent();
8472
8473 for (; MBBItr != MBB->begin() && RemainingSteps > 0 &&
8474 !RemainingLoadInstrs.empty();
8475 --MBBItr, --RemainingSteps) {
8476 const MachineInstr &CurrInstr = *MBBItr;
8477
8478 // Remove this instruction from remaining loads if it's one we're tracking.
8479 RemainingLoadInstrs.erase(&CurrInstr);
8480
8481 // Check for potential aliasing with any of the load instructions to
8482 // optimize.
8483 if (CurrInstr.isLoadFoldBarrier())
8484 return false;
8485 }
8486
8487 // If we hit the search limit without finding all load instructions,
8488 // don't match the pattern.
8489 if (RemainingSteps == 0 && !RemainingLoadInstrs.empty())
8490 return false;
8491
8492 switch (NumLanes) {
8493 case 4:
8495 break;
8496 case 8:
8498 break;
8499 case 16:
8501 break;
8502 default:
8503 llvm_unreachable("Got bad number of lanes for gather pattern.");
8504 }
8505
8506 return true;
8507}
8508
8509/// Search for patterns of LD instructions we can optimize.
8511 SmallVectorImpl<unsigned> &Patterns) {
8512
8513 // The pattern searches for loads into single lanes.
8514 switch (Root.getOpcode()) {
8515 case AArch64::LD1i32:
8516 return getGatherLanePattern(Root, Patterns, Root.getOpcode(), 4);
8517 case AArch64::LD1i16:
8518 return getGatherLanePattern(Root, Patterns, Root.getOpcode(), 8);
8519 case AArch64::LD1i8:
8520 return getGatherLanePattern(Root, Patterns, Root.getOpcode(), 16);
8521 default:
8522 return false;
8523 }
8524}
8525
8526/// Generate optimized instruction sequence for gather load patterns to improve
8527/// Memory-Level Parallelism (MLP). This function transforms a chain of
8528/// sequential NEON lane loads into parallel vector loads that can execute
8529/// concurrently.
8530static void
8534 DenseMap<Register, unsigned> &InstrIdxForVirtReg,
8535 unsigned Pattern, unsigned NumLanes) {
8536 MachineFunction &MF = *Root.getParent()->getParent();
8537 MachineRegisterInfo &MRI = MF.getRegInfo();
8539
8540 // Gather the initial load instructions to build the pattern.
8541 SmallVector<MachineInstr *, 16> LoadToLaneInstrs;
8542 MachineInstr *CurrInstr = &Root;
8543 for (unsigned i = 0; i < NumLanes - 1; ++i) {
8544 LoadToLaneInstrs.push_back(CurrInstr);
8545 CurrInstr = MRI.getUniqueVRegDef(CurrInstr->getOperand(1).getReg());
8546 }
8547
8548 // Sort the load instructions according to the lane.
8549 llvm::sort(LoadToLaneInstrs,
8550 [](const MachineInstr *A, const MachineInstr *B) {
8551 return A->getOperand(2).getImm() > B->getOperand(2).getImm();
8552 });
8553
8554 MachineInstr *SubregToReg = CurrInstr;
8555 LoadToLaneInstrs.push_back(
8556 MRI.getUniqueVRegDef(SubregToReg->getOperand(1).getReg()));
8557 auto LoadToLaneInstrsAscending = llvm::reverse(LoadToLaneInstrs);
8558
8559 const TargetRegisterClass *FPR128RegClass =
8560 MRI.getRegClass(Root.getOperand(0).getReg());
8561
8562 // Helper lambda to create a LD1 instruction.
8563 auto CreateLD1Instruction = [&](MachineInstr *OriginalInstr,
8564 Register SrcRegister, unsigned Lane,
8565 Register OffsetRegister,
8566 bool OffsetRegisterKillState) {
8567 auto NewRegister = MRI.createVirtualRegister(FPR128RegClass);
8568 MachineInstrBuilder LoadIndexIntoRegister =
8569 BuildMI(MF, MIMetadata(*OriginalInstr), TII->get(Root.getOpcode()),
8570 NewRegister)
8571 .addReg(SrcRegister)
8572 .addImm(Lane)
8573 .addReg(OffsetRegister, getKillRegState(OffsetRegisterKillState))
8574 .setMemRefs(OriginalInstr->memoperands());
8575 InstrIdxForVirtReg.insert(std::make_pair(NewRegister, InsInstrs.size()));
8576 InsInstrs.push_back(LoadIndexIntoRegister);
8577 return NewRegister;
8578 };
8579
8580 // Helper to create load instruction based on the NumLanes in the NEON
8581 // register we are rewriting.
8582 auto CreateLDRInstruction =
8583 [&](unsigned NumLanes, Register DestReg, Register OffsetReg,
8585 unsigned Opcode;
8586 switch (NumLanes) {
8587 case 4:
8588 Opcode = AArch64::LDRSui;
8589 break;
8590 case 8:
8591 Opcode = AArch64::LDRHui;
8592 break;
8593 case 16:
8594 Opcode = AArch64::LDRBui;
8595 break;
8596 default:
8598 "Got unsupported number of lanes in machine-combiner gather pattern");
8599 }
8600 // Immediate offset load
8601 return BuildMI(MF, MIMetadata(Root), TII->get(Opcode), DestReg)
8602 .addReg(OffsetReg)
8603 .addImm(0)
8604 .setMemRefs(MMOs);
8605 };
8606
8607 // Load the remaining lanes into register 0.
8608 auto LanesToLoadToReg0 =
8609 llvm::make_range(LoadToLaneInstrsAscending.begin() + 1,
8610 LoadToLaneInstrsAscending.begin() + NumLanes / 2);
8611 Register PrevReg = SubregToReg->getOperand(0).getReg();
8612 for (auto [Index, LoadInstr] : llvm::enumerate(LanesToLoadToReg0)) {
8613 const MachineOperand &OffsetRegOperand = LoadInstr->getOperand(3);
8614 PrevReg = CreateLD1Instruction(LoadInstr, PrevReg, Index + 1,
8615 OffsetRegOperand.getReg(),
8616 OffsetRegOperand.isKill());
8617 DelInstrs.push_back(LoadInstr);
8618 }
8619 Register LastLoadReg0 = PrevReg;
8620
8621 // First load into register 1. Perform an integer load to zero out the upper
8622 // lanes in a single instruction.
8623 MachineInstr *Lane0Load = *LoadToLaneInstrsAscending.begin();
8624 MachineInstr *OriginalSplitLoad =
8625 *std::next(LoadToLaneInstrsAscending.begin(), NumLanes / 2);
8626 Register DestRegForMiddleIndex = MRI.createVirtualRegister(
8627 MRI.getRegClass(Lane0Load->getOperand(0).getReg()));
8628
8629 const MachineOperand &OriginalSplitToLoadOffsetOperand =
8630 OriginalSplitLoad->getOperand(3);
8631 MachineInstrBuilder MiddleIndexLoadInstr =
8632 CreateLDRInstruction(NumLanes, DestRegForMiddleIndex,
8633 OriginalSplitToLoadOffsetOperand.getReg(),
8634 OriginalSplitLoad->memoperands());
8635
8636 InstrIdxForVirtReg.insert(
8637 std::make_pair(DestRegForMiddleIndex, InsInstrs.size()));
8638 InsInstrs.push_back(MiddleIndexLoadInstr);
8639 DelInstrs.push_back(OriginalSplitLoad);
8640
8641 // Subreg To Reg instruction for register 1.
8642 Register DestRegForSubregToReg = MRI.createVirtualRegister(FPR128RegClass);
8643 unsigned SubregType;
8644 switch (NumLanes) {
8645 case 4:
8646 SubregType = AArch64::ssub;
8647 break;
8648 case 8:
8649 SubregType = AArch64::hsub;
8650 break;
8651 case 16:
8652 SubregType = AArch64::bsub;
8653 break;
8654 default:
8656 "Got invalid NumLanes for machine-combiner gather pattern");
8657 }
8658
8659 auto SubRegToRegInstr =
8660 BuildMI(MF, MIMetadata(Root), TII->get(SubregToReg->getOpcode()),
8661 DestRegForSubregToReg)
8662 .addReg(DestRegForMiddleIndex, getKillRegState(true))
8663 .addImm(SubregType);
8664 InstrIdxForVirtReg.insert(
8665 std::make_pair(DestRegForSubregToReg, InsInstrs.size()));
8666 InsInstrs.push_back(SubRegToRegInstr);
8667
8668 // Load remaining lanes into register 1.
8669 auto LanesToLoadToReg1 =
8670 llvm::make_range(LoadToLaneInstrsAscending.begin() + NumLanes / 2 + 1,
8671 LoadToLaneInstrsAscending.end());
8672 PrevReg = SubRegToRegInstr->getOperand(0).getReg();
8673 for (auto [Index, LoadInstr] : llvm::enumerate(LanesToLoadToReg1)) {
8674 const MachineOperand &OffsetRegOperand = LoadInstr->getOperand(3);
8675 PrevReg = CreateLD1Instruction(LoadInstr, PrevReg, Index + 1,
8676 OffsetRegOperand.getReg(),
8677 OffsetRegOperand.isKill());
8678
8679 // Do not add the last reg to DelInstrs - it will be removed later.
8680 if (Index == NumLanes / 2 - 2) {
8681 break;
8682 }
8683 DelInstrs.push_back(LoadInstr);
8684 }
8685 Register LastLoadReg1 = PrevReg;
8686
8687 // Create the final zip instruction to combine the results.
8688 MachineInstrBuilder ZipInstr =
8689 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::ZIP1v2i64),
8690 Root.getOperand(0).getReg())
8691 .addReg(LastLoadReg0)
8692 .addReg(LastLoadReg1);
8693 InsInstrs.push_back(ZipInstr);
8694}
8695
8709
8710/// Return true when there is potentially a faster code sequence for an
8711/// instruction chain ending in \p Root. All potential patterns are listed in
8712/// the \p Pattern vector. Pattern should be sorted in priority order since the
8713/// pattern evaluator stops checking as soon as it finds a faster sequence.
8714
8715bool AArch64InstrInfo::getMachineCombinerPatterns(
8716 MachineInstr &Root, SmallVectorImpl<unsigned> &Patterns,
8717 bool DoRegPressureReduce) const {
8718 // Integer patterns
8719 if (getMaddPatterns(Root, Patterns))
8720 return true;
8721 // Floating point patterns
8722 if (getFMULPatterns(Root, Patterns))
8723 return true;
8724 if (getFMAPatterns(Root, Patterns))
8725 return true;
8726 if (getFNEGPatterns(Root, Patterns))
8727 return true;
8728
8729 // Other patterns
8730 if (getMiscPatterns(Root, Patterns))
8731 return true;
8732
8733 // Load patterns
8734 if (getLoadPatterns(Root, Patterns))
8735 return true;
8736
8737 return TargetInstrInfo::getMachineCombinerPatterns(Root, Patterns,
8738 DoRegPressureReduce);
8739}
8740
8742/// genFusedMultiply - Generate fused multiply instructions.
8743/// This function supports both integer and floating point instructions.
8744/// A typical example:
8745/// F|MUL I=A,B,0
8746/// F|ADD R,I,C
8747/// ==> F|MADD R,A,B,C
8748/// \param MF Containing MachineFunction
8749/// \param MRI Register information
8750/// \param TII Target information
8751/// \param Root is the F|ADD instruction
8752/// \param [out] InsInstrs is a vector of machine instructions and will
8753/// contain the generated madd instruction
8754/// \param IdxMulOpd is index of operand in Root that is the result of
8755/// the F|MUL. In the example above IdxMulOpd is 1.
8756/// \param MaddOpc the opcode fo the f|madd instruction
8757/// \param RC Register class of operands
8758/// \param kind of fma instruction (addressing mode) to be generated
8759/// \param ReplacedAddend is the result register from the instruction
8760/// replacing the non-combined operand, if any.
8761static MachineInstr *
8763 const TargetInstrInfo *TII, MachineInstr &Root,
8764 SmallVectorImpl<MachineInstr *> &InsInstrs, unsigned IdxMulOpd,
8765 unsigned MaddOpc, const TargetRegisterClass *RC,
8767 const Register *ReplacedAddend = nullptr) {
8768 assert(IdxMulOpd == 1 || IdxMulOpd == 2);
8769
8770 unsigned IdxOtherOpd = IdxMulOpd == 1 ? 2 : 1;
8771 MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(IdxMulOpd).getReg());
8772 Register ResultReg = Root.getOperand(0).getReg();
8773 Register SrcReg0 = MUL->getOperand(1).getReg();
8774 bool Src0IsKill = MUL->getOperand(1).isKill();
8775 Register SrcReg1 = MUL->getOperand(2).getReg();
8776 bool Src1IsKill = MUL->getOperand(2).isKill();
8777
8778 Register SrcReg2;
8779 bool Src2IsKill;
8780 if (ReplacedAddend) {
8781 // If we just generated a new addend, we must be it's only use.
8782 SrcReg2 = *ReplacedAddend;
8783 Src2IsKill = true;
8784 } else {
8785 SrcReg2 = Root.getOperand(IdxOtherOpd).getReg();
8786 Src2IsKill = Root.getOperand(IdxOtherOpd).isKill();
8787 }
8788
8789 if (ResultReg.isVirtual())
8790 MRI.constrainRegClass(ResultReg, RC);
8791 if (SrcReg0.isVirtual())
8792 MRI.constrainRegClass(SrcReg0, RC);
8793 if (SrcReg1.isVirtual())
8794 MRI.constrainRegClass(SrcReg1, RC);
8795 if (SrcReg2.isVirtual())
8796 MRI.constrainRegClass(SrcReg2, RC);
8797
8799 if (kind == FMAInstKind::Default)
8800 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
8801 .addReg(SrcReg0, getKillRegState(Src0IsKill))
8802 .addReg(SrcReg1, getKillRegState(Src1IsKill))
8803 .addReg(SrcReg2, getKillRegState(Src2IsKill));
8804 else if (kind == FMAInstKind::Indexed)
8805 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
8806 .addReg(SrcReg2, getKillRegState(Src2IsKill))
8807 .addReg(SrcReg0, getKillRegState(Src0IsKill))
8808 .addReg(SrcReg1, getKillRegState(Src1IsKill))
8809 .addImm(MUL->getOperand(3).getImm());
8810 else if (kind == FMAInstKind::Accumulator)
8811 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
8812 .addReg(SrcReg2, getKillRegState(Src2IsKill))
8813 .addReg(SrcReg0, getKillRegState(Src0IsKill))
8814 .addReg(SrcReg1, getKillRegState(Src1IsKill));
8815 else
8816 assert(false && "Invalid FMA instruction kind \n");
8817 // Insert the MADD (MADD, FMA, FMS, FMLA, FMSL)
8818 InsInstrs.push_back(MIB);
8819 return MUL;
8820}
8821
8822static MachineInstr *
8824 const TargetInstrInfo *TII, MachineInstr &Root,
8826 MachineInstr *MAD = MRI.getUniqueVRegDef(Root.getOperand(1).getReg());
8827
8828 unsigned Opc = 0;
8829 const TargetRegisterClass *RC = MRI.getRegClass(MAD->getOperand(0).getReg());
8830 if (AArch64::FPR32RegClass.hasSubClassEq(RC))
8831 Opc = AArch64::FNMADDSrrr;
8832 else if (AArch64::FPR64RegClass.hasSubClassEq(RC))
8833 Opc = AArch64::FNMADDDrrr;
8834 else
8835 return nullptr;
8836
8837 Register ResultReg = Root.getOperand(0).getReg();
8838 Register SrcReg0 = MAD->getOperand(1).getReg();
8839 Register SrcReg1 = MAD->getOperand(2).getReg();
8840 Register SrcReg2 = MAD->getOperand(3).getReg();
8841 bool Src0IsKill = MAD->getOperand(1).isKill();
8842 bool Src1IsKill = MAD->getOperand(2).isKill();
8843 bool Src2IsKill = MAD->getOperand(3).isKill();
8844 if (ResultReg.isVirtual())
8845 MRI.constrainRegClass(ResultReg, RC);
8846 if (SrcReg0.isVirtual())
8847 MRI.constrainRegClass(SrcReg0, RC);
8848 if (SrcReg1.isVirtual())
8849 MRI.constrainRegClass(SrcReg1, RC);
8850 if (SrcReg2.isVirtual())
8851 MRI.constrainRegClass(SrcReg2, RC);
8852
8854 BuildMI(MF, MIMetadata(Root), TII->get(Opc), ResultReg)
8855 .addReg(SrcReg0, getKillRegState(Src0IsKill))
8856 .addReg(SrcReg1, getKillRegState(Src1IsKill))
8857 .addReg(SrcReg2, getKillRegState(Src2IsKill));
8858 InsInstrs.push_back(MIB);
8859
8860 return MAD;
8861}
8862
8863/// Fold (FMUL x (DUP y lane)) into (FMUL_indexed x y lane)
8864static MachineInstr *
8867 unsigned IdxDupOp, unsigned MulOpc,
8868 const TargetRegisterClass *RC, MachineRegisterInfo &MRI) {
8869 assert(((IdxDupOp == 1) || (IdxDupOp == 2)) &&
8870 "Invalid index of FMUL operand");
8871
8872 MachineFunction &MF = *Root.getMF();
8874
8875 MachineInstr *Dup =
8876 MF.getRegInfo().getUniqueVRegDef(Root.getOperand(IdxDupOp).getReg());
8877
8878 if (Dup->getOpcode() == TargetOpcode::COPY)
8879 Dup = MRI.getUniqueVRegDef(Dup->getOperand(1).getReg());
8880
8881 Register DupSrcReg = Dup->getOperand(1).getReg();
8882 MRI.clearKillFlags(DupSrcReg);
8883 MRI.constrainRegClass(DupSrcReg, RC);
8884
8885 unsigned DupSrcLane = Dup->getOperand(2).getImm();
8886
8887 unsigned IdxMulOp = IdxDupOp == 1 ? 2 : 1;
8888 MachineOperand &MulOp = Root.getOperand(IdxMulOp);
8889
8890 Register ResultReg = Root.getOperand(0).getReg();
8891
8893 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MulOpc), ResultReg)
8894 .add(MulOp)
8895 .addReg(DupSrcReg)
8896 .addImm(DupSrcLane);
8897
8898 InsInstrs.push_back(MIB);
8899 return &Root;
8900}
8901
8902/// genFusedMultiplyAcc - Helper to generate fused multiply accumulate
8903/// instructions.
8904///
8905/// \see genFusedMultiply
8909 unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC) {
8910 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
8912}
8913
8914/// genNeg - Helper to generate an intermediate negation of the second operand
8915/// of Root
8917 const TargetInstrInfo *TII, MachineInstr &Root,
8919 DenseMap<Register, unsigned> &InstrIdxForVirtReg,
8920 unsigned MnegOpc, const TargetRegisterClass *RC) {
8921 Register NewVR = MRI.createVirtualRegister(RC);
8923 BuildMI(MF, MIMetadata(Root), TII->get(MnegOpc), NewVR)
8924 .add(Root.getOperand(2));
8925 InsInstrs.push_back(MIB);
8926
8927 assert(InstrIdxForVirtReg.empty());
8928 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
8929
8930 return NewVR;
8931}
8932
8933/// genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate
8934/// instructions with an additional negation of the accumulator
8938 DenseMap<Register, unsigned> &InstrIdxForVirtReg, unsigned IdxMulOpd,
8939 unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC) {
8940 assert(IdxMulOpd == 1);
8941
8942 Register NewVR =
8943 genNeg(MF, MRI, TII, Root, InsInstrs, InstrIdxForVirtReg, MnegOpc, RC);
8944 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
8945 FMAInstKind::Accumulator, &NewVR);
8946}
8947
8948/// genFusedMultiplyIdx - Helper to generate fused multiply accumulate
8949/// instructions.
8950///
8951/// \see genFusedMultiply
8955 unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC) {
8956 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
8958}
8959
8960/// genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate
8961/// instructions with an additional negation of the accumulator
8965 DenseMap<Register, unsigned> &InstrIdxForVirtReg, unsigned IdxMulOpd,
8966 unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC) {
8967 assert(IdxMulOpd == 1);
8968
8969 Register NewVR =
8970 genNeg(MF, MRI, TII, Root, InsInstrs, InstrIdxForVirtReg, MnegOpc, RC);
8971
8972 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
8973 FMAInstKind::Indexed, &NewVR);
8974}
8975
8976/// genMaddR - Generate madd instruction and combine mul and add using
8977/// an extra virtual register
8978/// Example - an ADD intermediate needs to be stored in a register:
8979/// MUL I=A,B,0
8980/// ADD R,I,Imm
8981/// ==> ORR V, ZR, Imm
8982/// ==> MADD R,A,B,V
8983/// \param MF Containing MachineFunction
8984/// \param MRI Register information
8985/// \param TII Target information
8986/// \param Root is the ADD instruction
8987/// \param [out] InsInstrs is a vector of machine instructions and will
8988/// contain the generated madd instruction
8989/// \param IdxMulOpd is index of operand in Root that is the result of
8990/// the MUL. In the example above IdxMulOpd is 1.
8991/// \param MaddOpc the opcode fo the madd instruction
8992/// \param VR is a virtual register that holds the value of an ADD operand
8993/// (V in the example above).
8994/// \param RC Register class of operands
8996 const TargetInstrInfo *TII, MachineInstr &Root,
8998 unsigned IdxMulOpd, unsigned MaddOpc, unsigned VR,
8999 const TargetRegisterClass *RC) {
9000 assert(IdxMulOpd == 1 || IdxMulOpd == 2);
9001
9002 MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(IdxMulOpd).getReg());
9003 Register ResultReg = Root.getOperand(0).getReg();
9004 Register SrcReg0 = MUL->getOperand(1).getReg();
9005 bool Src0IsKill = MUL->getOperand(1).isKill();
9006 Register SrcReg1 = MUL->getOperand(2).getReg();
9007 bool Src1IsKill = MUL->getOperand(2).isKill();
9008
9009 if (ResultReg.isVirtual())
9010 MRI.constrainRegClass(ResultReg, RC);
9011 if (SrcReg0.isVirtual())
9012 MRI.constrainRegClass(SrcReg0, RC);
9013 if (SrcReg1.isVirtual())
9014 MRI.constrainRegClass(SrcReg1, RC);
9016 MRI.constrainRegClass(VR, RC);
9017
9019 BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
9020 .addReg(SrcReg0, getKillRegState(Src0IsKill))
9021 .addReg(SrcReg1, getKillRegState(Src1IsKill))
9022 .addReg(VR);
9023 // Insert the MADD
9024 InsInstrs.push_back(MIB);
9025 return MUL;
9026}
9027
9028/// Do the following transformation
9029/// A - (B + C) ==> (A - B) - C
9030/// A - (B + C) ==> (A - C) - B
9032 const TargetInstrInfo *TII, MachineInstr &Root,
9035 unsigned IdxOpd1,
9036 DenseMap<Register, unsigned> &InstrIdxForVirtReg) {
9037 assert(IdxOpd1 == 1 || IdxOpd1 == 2);
9038 unsigned IdxOtherOpd = IdxOpd1 == 1 ? 2 : 1;
9039 MachineInstr *AddMI = MRI.getUniqueVRegDef(Root.getOperand(2).getReg());
9040
9041 Register ResultReg = Root.getOperand(0).getReg();
9042 Register RegA = Root.getOperand(1).getReg();
9043 bool RegAIsKill = Root.getOperand(1).isKill();
9044 Register RegB = AddMI->getOperand(IdxOpd1).getReg();
9045 bool RegBIsKill = AddMI->getOperand(IdxOpd1).isKill();
9046 Register RegC = AddMI->getOperand(IdxOtherOpd).getReg();
9047 bool RegCIsKill = AddMI->getOperand(IdxOtherOpd).isKill();
9048 Register NewVR =
9050
9051 unsigned Opcode = Root.getOpcode();
9052 if (Opcode == AArch64::SUBSWrr)
9053 Opcode = AArch64::SUBWrr;
9054 else if (Opcode == AArch64::SUBSXrr)
9055 Opcode = AArch64::SUBXrr;
9056 else
9057 assert((Opcode == AArch64::SUBWrr || Opcode == AArch64::SUBXrr) &&
9058 "Unexpected instruction opcode.");
9059
9060 uint32_t Flags = Root.mergeFlagsWith(*AddMI);
9061 Flags &= ~MachineInstr::NoSWrap;
9062 Flags &= ~MachineInstr::NoUWrap;
9063
9064 MachineInstrBuilder MIB1 =
9065 BuildMI(MF, MIMetadata(Root), TII->get(Opcode), NewVR)
9066 .addReg(RegA, getKillRegState(RegAIsKill))
9067 .addReg(RegB, getKillRegState(RegBIsKill))
9068 .setMIFlags(Flags);
9069 MachineInstrBuilder MIB2 =
9070 BuildMI(MF, MIMetadata(Root), TII->get(Opcode), ResultReg)
9071 .addReg(NewVR, getKillRegState(true))
9072 .addReg(RegC, getKillRegState(RegCIsKill))
9073 .setMIFlags(Flags);
9074
9075 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9076 InsInstrs.push_back(MIB1);
9077 InsInstrs.push_back(MIB2);
9078 DelInstrs.push_back(AddMI);
9079 DelInstrs.push_back(&Root);
9080}
9081
9082unsigned AArch64InstrInfo::getReduceOpcodeForAccumulator(
9083 unsigned int AccumulatorOpCode) const {
9084 switch (AccumulatorOpCode) {
9085 case AArch64::UABALB_ZZZ_D:
9086 case AArch64::SABALB_ZZZ_D:
9087 case AArch64::UABALT_ZZZ_D:
9088 case AArch64::SABALT_ZZZ_D:
9089 return AArch64::ADD_ZZZ_D;
9090 case AArch64::UABALB_ZZZ_H:
9091 case AArch64::SABALB_ZZZ_H:
9092 case AArch64::UABALT_ZZZ_H:
9093 case AArch64::SABALT_ZZZ_H:
9094 return AArch64::ADD_ZZZ_H;
9095 case AArch64::UABALB_ZZZ_S:
9096 case AArch64::SABALB_ZZZ_S:
9097 case AArch64::UABALT_ZZZ_S:
9098 case AArch64::SABALT_ZZZ_S:
9099 return AArch64::ADD_ZZZ_S;
9100 case AArch64::UABALv16i8_v8i16:
9101 case AArch64::SABALv8i8_v8i16:
9102 case AArch64::SABAv8i16:
9103 case AArch64::UABAv8i16:
9104 return AArch64::ADDv8i16;
9105 case AArch64::SABALv2i32_v2i64:
9106 case AArch64::UABALv2i32_v2i64:
9107 case AArch64::SABALv4i32_v2i64:
9108 return AArch64::ADDv2i64;
9109 case AArch64::UABALv4i16_v4i32:
9110 case AArch64::SABALv4i16_v4i32:
9111 case AArch64::SABALv8i16_v4i32:
9112 case AArch64::SABAv4i32:
9113 case AArch64::UABAv4i32:
9114 return AArch64::ADDv4i32;
9115 case AArch64::UABALv4i32_v2i64:
9116 return AArch64::ADDv2i64;
9117 case AArch64::UABALv8i16_v4i32:
9118 return AArch64::ADDv4i32;
9119 case AArch64::UABALv8i8_v8i16:
9120 case AArch64::SABALv16i8_v8i16:
9121 return AArch64::ADDv8i16;
9122 case AArch64::UABAv16i8:
9123 case AArch64::SABAv16i8:
9124 return AArch64::ADDv16i8;
9125 case AArch64::UABAv4i16:
9126 case AArch64::SABAv4i16:
9127 return AArch64::ADDv4i16;
9128 case AArch64::UABAv2i32:
9129 case AArch64::SABAv2i32:
9130 return AArch64::ADDv2i32;
9131 case AArch64::UABAv8i8:
9132 case AArch64::SABAv8i8:
9133 return AArch64::ADDv8i8;
9134 default:
9135 llvm_unreachable("Unknown accumulator opcode");
9136 }
9137}
9138
9139/// When getMachineCombinerPatterns() finds potential patterns,
9140/// this function generates the instructions that could replace the
9141/// original code sequence
9142void AArch64InstrInfo::genAlternativeCodeSequence(
9143 MachineInstr &Root, unsigned Pattern,
9146 DenseMap<Register, unsigned> &InstrIdxForVirtReg) const {
9147 MachineBasicBlock &MBB = *Root.getParent();
9148 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9149 MachineFunction &MF = *MBB.getParent();
9150 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9151
9152 MachineInstr *MUL = nullptr;
9153 const TargetRegisterClass *RC;
9154 unsigned Opc;
9155 switch (Pattern) {
9156 default:
9157 // Reassociate instructions.
9158 TargetInstrInfo::genAlternativeCodeSequence(Root, Pattern, InsInstrs,
9159 DelInstrs, InstrIdxForVirtReg);
9160 return;
9162 // A - (B + C)
9163 // ==> (A - B) - C
9164 genSubAdd2SubSub(MF, MRI, TII, Root, InsInstrs, DelInstrs, 1,
9165 InstrIdxForVirtReg);
9166 return;
9168 // A - (B + C)
9169 // ==> (A - C) - B
9170 genSubAdd2SubSub(MF, MRI, TII, Root, InsInstrs, DelInstrs, 2,
9171 InstrIdxForVirtReg);
9172 return;
9175 // MUL I=A,B,0
9176 // ADD R,I,C
9177 // ==> MADD R,A,B,C
9178 // --- Create(MADD);
9180 Opc = AArch64::MADDWrrr;
9181 RC = &AArch64::GPR32RegClass;
9182 } else {
9183 Opc = AArch64::MADDXrrr;
9184 RC = &AArch64::GPR64RegClass;
9185 }
9186 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9187 break;
9190 // MUL I=A,B,0
9191 // ADD R,C,I
9192 // ==> MADD R,A,B,C
9193 // --- Create(MADD);
9195 Opc = AArch64::MADDWrrr;
9196 RC = &AArch64::GPR32RegClass;
9197 } else {
9198 Opc = AArch64::MADDXrrr;
9199 RC = &AArch64::GPR64RegClass;
9200 }
9201 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9202 break;
9207 // MUL I=A,B,0
9208 // ADD/SUB R,I,Imm
9209 // ==> MOV V, Imm/-Imm
9210 // ==> MADD R,A,B,V
9211 // --- Create(MADD);
9212 const TargetRegisterClass *RC;
9213 unsigned BitSize, MovImm;
9216 MovImm = AArch64::MOVi32imm;
9217 RC = &AArch64::GPR32spRegClass;
9218 BitSize = 32;
9219 Opc = AArch64::MADDWrrr;
9220 RC = &AArch64::GPR32RegClass;
9221 } else {
9222 MovImm = AArch64::MOVi64imm;
9223 RC = &AArch64::GPR64spRegClass;
9224 BitSize = 64;
9225 Opc = AArch64::MADDXrrr;
9226 RC = &AArch64::GPR64RegClass;
9227 }
9228 Register NewVR = MRI.createVirtualRegister(RC);
9229 uint64_t Imm = Root.getOperand(2).getImm();
9230
9231 if (Root.getOperand(3).isImm()) {
9232 unsigned Val = Root.getOperand(3).getImm();
9233 Imm = Imm << Val;
9234 }
9235 bool IsSub = Pattern == AArch64MachineCombinerPattern::MULSUBWI_OP1 ||
9237 uint64_t UImm = SignExtend64(IsSub ? -Imm : Imm, BitSize);
9238 // Check that the immediate can be composed via a single instruction.
9240 AArch64_IMM::expandMOVImm(UImm, BitSize, Insn);
9241 if (Insn.size() != 1)
9242 return;
9243 MachineInstrBuilder MIB1 =
9244 BuildMI(MF, MIMetadata(Root), TII->get(MovImm), NewVR)
9245 .addImm(IsSub ? -Imm : Imm);
9246 InsInstrs.push_back(MIB1);
9247 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9248 MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC);
9249 break;
9250 }
9253 // MUL I=A,B,0
9254 // SUB R,I, C
9255 // ==> SUB V, 0, C
9256 // ==> MADD R,A,B,V // = -C + A*B
9257 // --- Create(MADD);
9258 const TargetRegisterClass *SubRC;
9259 unsigned SubOpc, ZeroReg;
9261 SubOpc = AArch64::SUBWrr;
9262 SubRC = &AArch64::GPR32spRegClass;
9263 ZeroReg = AArch64::WZR;
9264 Opc = AArch64::MADDWrrr;
9265 RC = &AArch64::GPR32RegClass;
9266 } else {
9267 SubOpc = AArch64::SUBXrr;
9268 SubRC = &AArch64::GPR64spRegClass;
9269 ZeroReg = AArch64::XZR;
9270 Opc = AArch64::MADDXrrr;
9271 RC = &AArch64::GPR64RegClass;
9272 }
9273 Register NewVR = MRI.createVirtualRegister(SubRC);
9274 // SUB NewVR, 0, C
9275 MachineInstrBuilder MIB1 =
9276 BuildMI(MF, MIMetadata(Root), TII->get(SubOpc), NewVR)
9277 .addReg(ZeroReg)
9278 .add(Root.getOperand(2));
9279 InsInstrs.push_back(MIB1);
9280 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9281 MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC);
9282 break;
9283 }
9286 // MUL I=A,B,0
9287 // SUB R,C,I
9288 // ==> MSUB R,A,B,C (computes C - A*B)
9289 // --- Create(MSUB);
9291 Opc = AArch64::MSUBWrrr;
9292 RC = &AArch64::GPR32RegClass;
9293 } else {
9294 Opc = AArch64::MSUBXrrr;
9295 RC = &AArch64::GPR64RegClass;
9296 }
9297 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9298 break;
9300 Opc = AArch64::MLAv8i8;
9301 RC = &AArch64::FPR64RegClass;
9302 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9303 break;
9305 Opc = AArch64::MLAv8i8;
9306 RC = &AArch64::FPR64RegClass;
9307 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9308 break;
9310 Opc = AArch64::MLAv16i8;
9311 RC = &AArch64::FPR128RegClass;
9312 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9313 break;
9315 Opc = AArch64::MLAv16i8;
9316 RC = &AArch64::FPR128RegClass;
9317 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9318 break;
9320 Opc = AArch64::MLAv4i16;
9321 RC = &AArch64::FPR64RegClass;
9322 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9323 break;
9325 Opc = AArch64::MLAv4i16;
9326 RC = &AArch64::FPR64RegClass;
9327 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9328 break;
9330 Opc = AArch64::MLAv8i16;
9331 RC = &AArch64::FPR128RegClass;
9332 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9333 break;
9335 Opc = AArch64::MLAv8i16;
9336 RC = &AArch64::FPR128RegClass;
9337 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9338 break;
9340 Opc = AArch64::MLAv2i32;
9341 RC = &AArch64::FPR64RegClass;
9342 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9343 break;
9345 Opc = AArch64::MLAv2i32;
9346 RC = &AArch64::FPR64RegClass;
9347 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9348 break;
9350 Opc = AArch64::MLAv4i32;
9351 RC = &AArch64::FPR128RegClass;
9352 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9353 break;
9355 Opc = AArch64::MLAv4i32;
9356 RC = &AArch64::FPR128RegClass;
9357 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9358 break;
9359
9361 Opc = AArch64::MLAv8i8;
9362 RC = &AArch64::FPR64RegClass;
9363 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9364 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i8,
9365 RC);
9366 break;
9368 Opc = AArch64::MLSv8i8;
9369 RC = &AArch64::FPR64RegClass;
9370 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9371 break;
9373 Opc = AArch64::MLAv16i8;
9374 RC = &AArch64::FPR128RegClass;
9375 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9376 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv16i8,
9377 RC);
9378 break;
9380 Opc = AArch64::MLSv16i8;
9381 RC = &AArch64::FPR128RegClass;
9382 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9383 break;
9385 Opc = AArch64::MLAv4i16;
9386 RC = &AArch64::FPR64RegClass;
9387 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9388 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i16,
9389 RC);
9390 break;
9392 Opc = AArch64::MLSv4i16;
9393 RC = &AArch64::FPR64RegClass;
9394 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9395 break;
9397 Opc = AArch64::MLAv8i16;
9398 RC = &AArch64::FPR128RegClass;
9399 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9400 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i16,
9401 RC);
9402 break;
9404 Opc = AArch64::MLSv8i16;
9405 RC = &AArch64::FPR128RegClass;
9406 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9407 break;
9409 Opc = AArch64::MLAv2i32;
9410 RC = &AArch64::FPR64RegClass;
9411 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9412 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv2i32,
9413 RC);
9414 break;
9416 Opc = AArch64::MLSv2i32;
9417 RC = &AArch64::FPR64RegClass;
9418 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9419 break;
9421 Opc = AArch64::MLAv4i32;
9422 RC = &AArch64::FPR128RegClass;
9423 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9424 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i32,
9425 RC);
9426 break;
9428 Opc = AArch64::MLSv4i32;
9429 RC = &AArch64::FPR128RegClass;
9430 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9431 break;
9432
9434 Opc = AArch64::MLAv4i16_indexed;
9435 RC = &AArch64::FPR64RegClass;
9436 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9437 break;
9439 Opc = AArch64::MLAv4i16_indexed;
9440 RC = &AArch64::FPR64RegClass;
9441 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9442 break;
9444 Opc = AArch64::MLAv8i16_indexed;
9445 RC = &AArch64::FPR128RegClass;
9446 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9447 break;
9449 Opc = AArch64::MLAv8i16_indexed;
9450 RC = &AArch64::FPR128RegClass;
9451 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9452 break;
9454 Opc = AArch64::MLAv2i32_indexed;
9455 RC = &AArch64::FPR64RegClass;
9456 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9457 break;
9459 Opc = AArch64::MLAv2i32_indexed;
9460 RC = &AArch64::FPR64RegClass;
9461 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9462 break;
9464 Opc = AArch64::MLAv4i32_indexed;
9465 RC = &AArch64::FPR128RegClass;
9466 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9467 break;
9469 Opc = AArch64::MLAv4i32_indexed;
9470 RC = &AArch64::FPR128RegClass;
9471 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9472 break;
9473
9475 Opc = AArch64::MLAv4i16_indexed;
9476 RC = &AArch64::FPR64RegClass;
9477 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9478 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i16,
9479 RC);
9480 break;
9482 Opc = AArch64::MLSv4i16_indexed;
9483 RC = &AArch64::FPR64RegClass;
9484 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9485 break;
9487 Opc = AArch64::MLAv8i16_indexed;
9488 RC = &AArch64::FPR128RegClass;
9489 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9490 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i16,
9491 RC);
9492 break;
9494 Opc = AArch64::MLSv8i16_indexed;
9495 RC = &AArch64::FPR128RegClass;
9496 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9497 break;
9499 Opc = AArch64::MLAv2i32_indexed;
9500 RC = &AArch64::FPR64RegClass;
9501 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9502 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv2i32,
9503 RC);
9504 break;
9506 Opc = AArch64::MLSv2i32_indexed;
9507 RC = &AArch64::FPR64RegClass;
9508 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9509 break;
9511 Opc = AArch64::MLAv4i32_indexed;
9512 RC = &AArch64::FPR128RegClass;
9513 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9514 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i32,
9515 RC);
9516 break;
9518 Opc = AArch64::MLSv4i32_indexed;
9519 RC = &AArch64::FPR128RegClass;
9520 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9521 break;
9522
9523 // Floating Point Support
9525 Opc = AArch64::FMADDHrrr;
9526 RC = &AArch64::FPR16RegClass;
9527 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9528 break;
9530 Opc = AArch64::FMADDSrrr;
9531 RC = &AArch64::FPR32RegClass;
9532 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9533 break;
9535 Opc = AArch64::FMADDDrrr;
9536 RC = &AArch64::FPR64RegClass;
9537 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9538 break;
9539
9541 Opc = AArch64::FMADDHrrr;
9542 RC = &AArch64::FPR16RegClass;
9543 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9544 break;
9546 Opc = AArch64::FMADDSrrr;
9547 RC = &AArch64::FPR32RegClass;
9548 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9549 break;
9551 Opc = AArch64::FMADDDrrr;
9552 RC = &AArch64::FPR64RegClass;
9553 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9554 break;
9555
9557 Opc = AArch64::FMLAv1i32_indexed;
9558 RC = &AArch64::FPR32RegClass;
9559 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9561 break;
9563 Opc = AArch64::FMLAv1i32_indexed;
9564 RC = &AArch64::FPR32RegClass;
9565 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9567 break;
9568
9570 Opc = AArch64::FMLAv1i64_indexed;
9571 RC = &AArch64::FPR64RegClass;
9572 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9574 break;
9576 Opc = AArch64::FMLAv1i64_indexed;
9577 RC = &AArch64::FPR64RegClass;
9578 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9580 break;
9581
9583 RC = &AArch64::FPR64RegClass;
9584 Opc = AArch64::FMLAv4i16_indexed;
9585 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9587 break;
9589 RC = &AArch64::FPR64RegClass;
9590 Opc = AArch64::FMLAv4f16;
9591 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9593 break;
9595 RC = &AArch64::FPR64RegClass;
9596 Opc = AArch64::FMLAv4i16_indexed;
9597 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9599 break;
9601 RC = &AArch64::FPR64RegClass;
9602 Opc = AArch64::FMLAv4f16;
9603 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9605 break;
9606
9609 RC = &AArch64::FPR64RegClass;
9611 Opc = AArch64::FMLAv2i32_indexed;
9612 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9614 } else {
9615 Opc = AArch64::FMLAv2f32;
9616 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9618 }
9619 break;
9622 RC = &AArch64::FPR64RegClass;
9624 Opc = AArch64::FMLAv2i32_indexed;
9625 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9627 } else {
9628 Opc = AArch64::FMLAv2f32;
9629 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9631 }
9632 break;
9633
9635 RC = &AArch64::FPR128RegClass;
9636 Opc = AArch64::FMLAv8i16_indexed;
9637 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9639 break;
9641 RC = &AArch64::FPR128RegClass;
9642 Opc = AArch64::FMLAv8f16;
9643 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9645 break;
9647 RC = &AArch64::FPR128RegClass;
9648 Opc = AArch64::FMLAv8i16_indexed;
9649 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9651 break;
9653 RC = &AArch64::FPR128RegClass;
9654 Opc = AArch64::FMLAv8f16;
9655 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9657 break;
9658
9661 RC = &AArch64::FPR128RegClass;
9663 Opc = AArch64::FMLAv2i64_indexed;
9664 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9666 } else {
9667 Opc = AArch64::FMLAv2f64;
9668 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9670 }
9671 break;
9674 RC = &AArch64::FPR128RegClass;
9676 Opc = AArch64::FMLAv2i64_indexed;
9677 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9679 } else {
9680 Opc = AArch64::FMLAv2f64;
9681 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9683 }
9684 break;
9685
9688 RC = &AArch64::FPR128RegClass;
9690 Opc = AArch64::FMLAv4i32_indexed;
9691 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9693 } else {
9694 Opc = AArch64::FMLAv4f32;
9695 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9697 }
9698 break;
9699
9702 RC = &AArch64::FPR128RegClass;
9704 Opc = AArch64::FMLAv4i32_indexed;
9705 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9707 } else {
9708 Opc = AArch64::FMLAv4f32;
9709 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9711 }
9712 break;
9713
9715 Opc = AArch64::FNMSUBHrrr;
9716 RC = &AArch64::FPR16RegClass;
9717 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9718 break;
9720 Opc = AArch64::FNMSUBSrrr;
9721 RC = &AArch64::FPR32RegClass;
9722 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9723 break;
9725 Opc = AArch64::FNMSUBDrrr;
9726 RC = &AArch64::FPR64RegClass;
9727 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9728 break;
9729
9731 Opc = AArch64::FNMADDHrrr;
9732 RC = &AArch64::FPR16RegClass;
9733 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9734 break;
9736 Opc = AArch64::FNMADDSrrr;
9737 RC = &AArch64::FPR32RegClass;
9738 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9739 break;
9741 Opc = AArch64::FNMADDDrrr;
9742 RC = &AArch64::FPR64RegClass;
9743 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9744 break;
9745
9747 Opc = AArch64::FMSUBHrrr;
9748 RC = &AArch64::FPR16RegClass;
9749 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9750 break;
9752 Opc = AArch64::FMSUBSrrr;
9753 RC = &AArch64::FPR32RegClass;
9754 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9755 break;
9757 Opc = AArch64::FMSUBDrrr;
9758 RC = &AArch64::FPR64RegClass;
9759 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9760 break;
9761
9763 Opc = AArch64::FMLSv1i32_indexed;
9764 RC = &AArch64::FPR32RegClass;
9765 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9767 break;
9768
9770 Opc = AArch64::FMLSv1i64_indexed;
9771 RC = &AArch64::FPR64RegClass;
9772 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9774 break;
9775
9778 RC = &AArch64::FPR64RegClass;
9779 Register NewVR = MRI.createVirtualRegister(RC);
9780 MachineInstrBuilder MIB1 =
9781 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv4f16), NewVR)
9782 .add(Root.getOperand(2));
9783 InsInstrs.push_back(MIB1);
9784 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9786 Opc = AArch64::FMLAv4f16;
9787 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9788 FMAInstKind::Accumulator, &NewVR);
9789 } else {
9790 Opc = AArch64::FMLAv4i16_indexed;
9791 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9792 FMAInstKind::Indexed, &NewVR);
9793 }
9794 break;
9795 }
9797 RC = &AArch64::FPR64RegClass;
9798 Opc = AArch64::FMLSv4f16;
9799 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9801 break;
9803 RC = &AArch64::FPR64RegClass;
9804 Opc = AArch64::FMLSv4i16_indexed;
9805 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9807 break;
9808
9811 RC = &AArch64::FPR64RegClass;
9813 Opc = AArch64::FMLSv2i32_indexed;
9814 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9816 } else {
9817 Opc = AArch64::FMLSv2f32;
9818 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9820 }
9821 break;
9822
9825 RC = &AArch64::FPR128RegClass;
9826 Register NewVR = MRI.createVirtualRegister(RC);
9827 MachineInstrBuilder MIB1 =
9828 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv8f16), NewVR)
9829 .add(Root.getOperand(2));
9830 InsInstrs.push_back(MIB1);
9831 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9833 Opc = AArch64::FMLAv8f16;
9834 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9835 FMAInstKind::Accumulator, &NewVR);
9836 } else {
9837 Opc = AArch64::FMLAv8i16_indexed;
9838 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9839 FMAInstKind::Indexed, &NewVR);
9840 }
9841 break;
9842 }
9844 RC = &AArch64::FPR128RegClass;
9845 Opc = AArch64::FMLSv8f16;
9846 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9848 break;
9850 RC = &AArch64::FPR128RegClass;
9851 Opc = AArch64::FMLSv8i16_indexed;
9852 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9854 break;
9855
9858 RC = &AArch64::FPR128RegClass;
9860 Opc = AArch64::FMLSv2i64_indexed;
9861 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9863 } else {
9864 Opc = AArch64::FMLSv2f64;
9865 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9867 }
9868 break;
9869
9872 RC = &AArch64::FPR128RegClass;
9874 Opc = AArch64::FMLSv4i32_indexed;
9875 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9877 } else {
9878 Opc = AArch64::FMLSv4f32;
9879 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9881 }
9882 break;
9885 RC = &AArch64::FPR64RegClass;
9886 Register NewVR = MRI.createVirtualRegister(RC);
9887 MachineInstrBuilder MIB1 =
9888 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv2f32), NewVR)
9889 .add(Root.getOperand(2));
9890 InsInstrs.push_back(MIB1);
9891 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9893 Opc = AArch64::FMLAv2i32_indexed;
9894 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9895 FMAInstKind::Indexed, &NewVR);
9896 } else {
9897 Opc = AArch64::FMLAv2f32;
9898 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9899 FMAInstKind::Accumulator, &NewVR);
9900 }
9901 break;
9902 }
9905 RC = &AArch64::FPR128RegClass;
9906 Register NewVR = MRI.createVirtualRegister(RC);
9907 MachineInstrBuilder MIB1 =
9908 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv4f32), NewVR)
9909 .add(Root.getOperand(2));
9910 InsInstrs.push_back(MIB1);
9911 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9913 Opc = AArch64::FMLAv4i32_indexed;
9914 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9915 FMAInstKind::Indexed, &NewVR);
9916 } else {
9917 Opc = AArch64::FMLAv4f32;
9918 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9919 FMAInstKind::Accumulator, &NewVR);
9920 }
9921 break;
9922 }
9925 RC = &AArch64::FPR128RegClass;
9926 Register NewVR = MRI.createVirtualRegister(RC);
9927 MachineInstrBuilder MIB1 =
9928 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv2f64), NewVR)
9929 .add(Root.getOperand(2));
9930 InsInstrs.push_back(MIB1);
9931 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9933 Opc = AArch64::FMLAv2i64_indexed;
9934 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9935 FMAInstKind::Indexed, &NewVR);
9936 } else {
9937 Opc = AArch64::FMLAv2f64;
9938 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9939 FMAInstKind::Accumulator, &NewVR);
9940 }
9941 break;
9942 }
9945 unsigned IdxDupOp =
9947 : 2;
9948 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv2i32_indexed,
9949 &AArch64::FPR128RegClass, MRI);
9950 break;
9951 }
9954 unsigned IdxDupOp =
9956 : 2;
9957 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv2i64_indexed,
9958 &AArch64::FPR128RegClass, MRI);
9959 break;
9960 }
9963 unsigned IdxDupOp =
9965 : 2;
9966 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv4i16_indexed,
9967 &AArch64::FPR128_loRegClass, MRI);
9968 break;
9969 }
9972 unsigned IdxDupOp =
9974 : 2;
9975 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv4i32_indexed,
9976 &AArch64::FPR128RegClass, MRI);
9977 break;
9978 }
9981 unsigned IdxDupOp =
9983 : 2;
9984 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv8i16_indexed,
9985 &AArch64::FPR128_loRegClass, MRI);
9986 break;
9987 }
9989 MUL = genFNegatedMAD(MF, MRI, TII, Root, InsInstrs);
9990 break;
9991 }
9993 generateGatherLanePattern(Root, InsInstrs, DelInstrs, InstrIdxForVirtReg,
9994 Pattern, 4);
9995 break;
9996 }
9998 generateGatherLanePattern(Root, InsInstrs, DelInstrs, InstrIdxForVirtReg,
9999 Pattern, 8);
10000 break;
10001 }
10003 generateGatherLanePattern(Root, InsInstrs, DelInstrs, InstrIdxForVirtReg,
10004 Pattern, 16);
10005 break;
10006 }
10007
10008 } // end switch (Pattern)
10009 // Record MUL and ADD/SUB for deletion
10010 if (MUL)
10011 DelInstrs.push_back(MUL);
10012 DelInstrs.push_back(&Root);
10013
10014 // Set the flags on the inserted instructions to be the merged flags of the
10015 // instructions that we have combined.
10016 uint32_t Flags = Root.getFlags();
10017 if (MUL)
10018 Flags = Root.mergeFlagsWith(*MUL);
10019 for (auto *MI : InsInstrs)
10020 MI->setFlags(Flags);
10021}
10022
10023/// Replace csincr-branch sequence by simple conditional branch
10024///
10025/// Examples:
10026/// 1. \code
10027/// csinc w9, wzr, wzr, <condition code>
10028/// tbnz w9, #0, 0x44
10029/// \endcode
10030/// to
10031/// \code
10032/// b.<inverted condition code>
10033/// \endcode
10034///
10035/// 2. \code
10036/// csinc w9, wzr, wzr, <condition code>
10037/// tbz w9, #0, 0x44
10038/// \endcode
10039/// to
10040/// \code
10041/// b.<condition code>
10042/// \endcode
10043///
10044/// Replace compare and branch sequence by TBZ/TBNZ instruction when the
10045/// compare's constant operand is power of 2.
10046///
10047/// Examples:
10048/// \code
10049/// and w8, w8, #0x400
10050/// cbnz w8, L1
10051/// \endcode
10052/// to
10053/// \code
10054/// tbnz w8, #10, L1
10055/// \endcode
10056///
10057/// \param MI Conditional Branch
10058/// \return True when the simple conditional branch is generated
10059///
10061 bool IsNegativeBranch = false;
10062 bool IsTestAndBranch = false;
10063 unsigned TargetBBInMI = 0;
10064 switch (MI.getOpcode()) {
10065 default:
10066 llvm_unreachable("Unknown branch instruction?");
10067 case AArch64::Bcc:
10068 case AArch64::CBWPri:
10069 case AArch64::CBXPri:
10070 case AArch64::CBBAssertExt:
10071 case AArch64::CBHAssertExt:
10072 case AArch64::CBWPrr:
10073 case AArch64::CBXPrr:
10074 return false;
10075 case AArch64::CBZW:
10076 case AArch64::CBZX:
10077 TargetBBInMI = 1;
10078 break;
10079 case AArch64::CBNZW:
10080 case AArch64::CBNZX:
10081 TargetBBInMI = 1;
10082 IsNegativeBranch = true;
10083 break;
10084 case AArch64::TBZW:
10085 case AArch64::TBZX:
10086 TargetBBInMI = 2;
10087 IsTestAndBranch = true;
10088 break;
10089 case AArch64::TBNZW:
10090 case AArch64::TBNZX:
10091 TargetBBInMI = 2;
10092 IsNegativeBranch = true;
10093 IsTestAndBranch = true;
10094 break;
10095 }
10096 // So we increment a zero register and test for bits other
10097 // than bit 0? Conservatively bail out in case the verifier
10098 // missed this case.
10099 if (IsTestAndBranch && MI.getOperand(1).getImm())
10100 return false;
10101
10102 // Find Definition.
10103 assert(MI.getParent() && "Incomplete machine instruction\n");
10104 MachineBasicBlock *MBB = MI.getParent();
10105 MachineFunction *MF = MBB->getParent();
10106 MachineRegisterInfo *MRI = &MF->getRegInfo();
10107 Register VReg = MI.getOperand(0).getReg();
10108 if (!VReg.isVirtual())
10109 return false;
10110
10111 MachineInstr *DefMI = MRI->getVRegDef(VReg);
10112 if (!DefMI)
10113 return false;
10114
10115 // Look through COPY instructions to find definition.
10116 while (DefMI->isCopy()) {
10117 Register CopyVReg = DefMI->getOperand(1).getReg();
10118 if (!CopyVReg.isVirtual())
10119 return false;
10120 if (!MRI->hasOneNonDBGUse(CopyVReg))
10121 return false;
10122 DefMI = MRI->getVRegDef(CopyVReg);
10123 if (!DefMI)
10124 return false;
10125 }
10126
10127 switch (DefMI->getOpcode()) {
10128 default:
10129 return false;
10130 // Fold AND into a TBZ/TBNZ if constant operand is power of 2.
10131 case AArch64::ANDWri:
10132 case AArch64::ANDXri: {
10133 if (IsTestAndBranch)
10134 return false;
10135 if (DefMI->getParent() != MBB)
10136 return false;
10137 if (!MRI->hasOneNonDBGUse(VReg))
10138 return false;
10139
10140 bool Is32Bit = (DefMI->getOpcode() == AArch64::ANDWri);
10141 uint64_t Mask = AArch64_AM::decodeLogicalImmediate(
10142 DefMI->getOperand(2).getImm(), Is32Bit ? 32 : 64);
10143 if (!isPowerOf2_64(Mask))
10144 return false;
10145
10146 MachineOperand &MO = DefMI->getOperand(1);
10147 Register NewReg = MO.getReg();
10148 if (!NewReg.isVirtual())
10149 return false;
10150
10151 if (!MRI->getVRegDef(NewReg))
10152 return false;
10153
10154 MachineBasicBlock &RefToMBB = *MBB;
10155 MachineBasicBlock *TBB = MI.getOperand(1).getMBB();
10156 DebugLoc DL = MI.getDebugLoc();
10157 unsigned Imm = Log2_64(Mask);
10158 unsigned Opc = (Imm < 32)
10159 ? (IsNegativeBranch ? AArch64::TBNZW : AArch64::TBZW)
10160 : (IsNegativeBranch ? AArch64::TBNZX : AArch64::TBZX);
10161 MachineInstr *NewMI = BuildMI(RefToMBB, MI, DL, get(Opc))
10162 .addReg(NewReg)
10163 .addImm(Imm)
10164 .addMBB(TBB);
10165 // Register lives on to the CBZ now.
10166 MO.setIsKill(false);
10167
10168 // For immediate smaller than 32, we need to use the 32-bit
10169 // variant (W) in all cases. Indeed the 64-bit variant does not
10170 // allow to encode them.
10171 // Therefore, if the input register is 64-bit, we need to take the
10172 // 32-bit sub-part.
10173 if (!Is32Bit && Imm < 32)
10174 NewMI->getOperand(0).setSubReg(AArch64::sub_32);
10175 MI.eraseFromParent();
10176 return true;
10177 }
10178 // Look for CSINC
10179 case AArch64::CSINCWr:
10180 case AArch64::CSINCXr: {
10181 if (!(DefMI->getOperand(1).getReg() == AArch64::WZR &&
10182 DefMI->getOperand(2).getReg() == AArch64::WZR) &&
10183 !(DefMI->getOperand(1).getReg() == AArch64::XZR &&
10184 DefMI->getOperand(2).getReg() == AArch64::XZR))
10185 return false;
10186
10187 if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr,
10188 true) != -1)
10189 return false;
10190
10191 AArch64CC::CondCode CC = (AArch64CC::CondCode)DefMI->getOperand(3).getImm();
10192 // Convert only when the condition code is not modified between
10193 // the CSINC and the branch. The CC may be used by other
10194 // instructions in between.
10196 return false;
10197 MachineBasicBlock &RefToMBB = *MBB;
10198 MachineBasicBlock *TBB = MI.getOperand(TargetBBInMI).getMBB();
10199 DebugLoc DL = MI.getDebugLoc();
10200 if (IsNegativeBranch)
10202 BuildMI(RefToMBB, MI, DL, get(AArch64::Bcc)).addImm(CC).addMBB(TBB);
10203 MI.eraseFromParent();
10204 return true;
10205 }
10206 }
10207}
10208
10209std::pair<unsigned, unsigned>
10210AArch64InstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
10211 const unsigned Mask = AArch64II::MO_FRAGMENT;
10212 return std::make_pair(TF & Mask, TF & ~Mask);
10213}
10214
10216AArch64InstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
10217 using namespace AArch64II;
10218
10219 static const std::pair<unsigned, const char *> TargetFlags[] = {
10220 {MO_PAGE, "aarch64-page"}, {MO_PAGEOFF, "aarch64-pageoff"},
10221 {MO_G3, "aarch64-g3"}, {MO_G2, "aarch64-g2"},
10222 {MO_G1, "aarch64-g1"}, {MO_G0, "aarch64-g0"},
10223 {MO_HI12, "aarch64-hi12"}};
10224 return ArrayRef(TargetFlags);
10225}
10226
10228AArch64InstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
10229 using namespace AArch64II;
10230
10231 static const std::pair<unsigned, const char *> TargetFlags[] = {
10232 {MO_COFFSTUB, "aarch64-coffstub"},
10233 {MO_GOT, "aarch64-got"},
10234 {MO_NC, "aarch64-nc"},
10235 {MO_S, "aarch64-s"},
10236 {MO_TLS, "aarch64-tls"},
10237 {MO_DLLIMPORT, "aarch64-dllimport"},
10238 {MO_PREL, "aarch64-prel"},
10239 {MO_TAGGED, "aarch64-tagged"},
10240 {MO_ARM64EC_CALLMANGLE, "aarch64-arm64ec-callmangle"},
10241 };
10242 return ArrayRef(TargetFlags);
10243}
10244
10246AArch64InstrInfo::getSerializableMachineMemOperandTargetFlags() const {
10247 static const std::pair<MachineMemOperand::Flags, const char *> TargetFlags[] =
10248 {{MOSuppressPair, "aarch64-suppress-pair"},
10249 {MOStridedAccess, "aarch64-strided-access"}};
10250 return ArrayRef(TargetFlags);
10251}
10252
10253/// Constants defining how certain sequences should be outlined.
10254/// This encompasses how an outlined function should be called, and what kind of
10255/// frame should be emitted for that outlined function.
10256///
10257/// \p MachineOutlinerDefault implies that the function should be called with
10258/// a save and restore of LR to the stack.
10259///
10260/// That is,
10261///
10262/// I1 Save LR OUTLINED_FUNCTION:
10263/// I2 --> BL OUTLINED_FUNCTION I1
10264/// I3 Restore LR I2
10265/// I3
10266/// RET
10267///
10268/// * Call construction overhead: 3 (save + BL + restore)
10269/// * Frame construction overhead: 1 (ret)
10270/// * Requires stack fixups? Yes
10271///
10272/// \p MachineOutlinerTailCall implies that the function is being created from
10273/// a sequence of instructions ending in a return.
10274///
10275/// That is,
10276///
10277/// I1 OUTLINED_FUNCTION:
10278/// I2 --> B OUTLINED_FUNCTION I1
10279/// RET I2
10280/// RET
10281///
10282/// * Call construction overhead: 1 (B)
10283/// * Frame construction overhead: 0 (Return included in sequence)
10284/// * Requires stack fixups? No
10285///
10286/// \p MachineOutlinerNoLRSave implies that the function should be called using
10287/// a BL instruction, but doesn't require LR to be saved and restored. This
10288/// happens when LR is known to be dead.
10289///
10290/// That is,
10291///
10292/// I1 OUTLINED_FUNCTION:
10293/// I2 --> BL OUTLINED_FUNCTION I1
10294/// I3 I2
10295/// I3
10296/// RET
10297///
10298/// * Call construction overhead: 1 (BL)
10299/// * Frame construction overhead: 1 (RET)
10300/// * Requires stack fixups? No
10301///
10302/// \p MachineOutlinerThunk implies that the function is being created from
10303/// a sequence of instructions ending in a call. The outlined function is
10304/// called with a BL instruction, and the outlined function tail-calls the
10305/// original call destination.
10306///
10307/// That is,
10308///
10309/// I1 OUTLINED_FUNCTION:
10310/// I2 --> BL OUTLINED_FUNCTION I1
10311/// BL f I2
10312/// B f
10313/// * Call construction overhead: 1 (BL)
10314/// * Frame construction overhead: 0
10315/// * Requires stack fixups? No
10316///
10317/// \p MachineOutlinerRegSave implies that the function should be called with a
10318/// save and restore of LR to an available register. This allows us to avoid
10319/// stack fixups. Note that this outlining variant is compatible with the
10320/// NoLRSave case.
10321///
10322/// That is,
10323///
10324/// I1 Save LR OUTLINED_FUNCTION:
10325/// I2 --> BL OUTLINED_FUNCTION I1
10326/// I3 Restore LR I2
10327/// I3
10328/// RET
10329///
10330/// * Call construction overhead: 3 (save + BL + restore)
10331/// * Frame construction overhead: 1 (ret)
10332/// * Requires stack fixups? No
10334 MachineOutlinerDefault, /// Emit a save, restore, call, and return.
10335 MachineOutlinerTailCall, /// Only emit a branch.
10336 MachineOutlinerNoLRSave, /// Emit a call and return.
10337 MachineOutlinerThunk, /// Emit a call and tail-call.
10338 MachineOutlinerRegSave /// Same as default, but save to a register.
10339};
10340
10346
10347/// Return true if the frame-record form of the outlined prologue is enabled for
10348/// the target of \p MF.
10349///
10350/// A non-leaf outlined function must save LR. On MachO, saving LR alone
10351/// (str x30) has no compact unwind encoding, so we get a large DWARF FDE
10352/// instead. Saving FP and LR as a frame record (stp x29, x30 ; mov x29, sp)
10353/// gets the small FRAME encoding, and costs one extra instruction.
10358
10359/// Return true if the outlined function in \p MBB should save FP and LR as a
10360/// frame record instead of saving LR alone.
10362 const MachineBasicBlock &MBB) {
10363 const MachineFunction &MF = *MBB.getParent();
10364
10365 // Only worth it if the function has unwind info to shrink.
10368 return false;
10369
10370 // Only safe if the outlined code never touches FP, since we overwrite it.
10372 for (const MachineInstr &MI : MBB.instrs())
10373 LRU.accumulate(MI);
10374 return LRU.available(AArch64::FP);
10375}
10376
10377/// Predict what the above will answer, for use while costing candidates. The
10378/// outlined function does not exist yet, so answer from \p RepeatedSequenceLocs
10379/// instead. This is only an estimate; buildOutlinedFrame() makes the call.
10381 std::vector<outliner::Candidate> &RepeatedSequenceLocs,
10382 const TargetRegisterInfo &TRI) {
10383 if (!isCompactUnwindFrameRecordEnabled(*RepeatedSequenceLocs.front().getMF()))
10384 return false;
10385
10386 // The outlined function is nounwind only if every candidate is, so it has
10387 // unwind info if any candidate does.
10388 if (llvm::none_of(RepeatedSequenceLocs, [](outliner::Candidate &C) {
10389 const MachineFunction &MF = *C.getMF();
10390 return MF.getInfo<AArch64FunctionInfo>()->needsDwarfUnwindInfo(MF);
10391 }))
10392 return false;
10393
10394 // FP is free in the outlined function only if it is free in every candidate.
10395 return llvm::all_of(RepeatedSequenceLocs, [&TRI](outliner::Candidate &C) {
10396 return C.isAvailableInsideSeq(AArch64::FP, TRI);
10397 });
10398}
10399
10401AArch64InstrInfo::findRegisterToSaveLRTo(outliner::Candidate &C) const {
10402 MachineFunction *MF = C.getMF();
10403 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
10404 const AArch64RegisterInfo *ARI =
10405 static_cast<const AArch64RegisterInfo *>(&TRI);
10406 // Check if there is an available register across the sequence that we can
10407 // use.
10408 for (unsigned Reg : AArch64::GPR64RegClass) {
10409 if (!ARI->isReservedReg(*MF, Reg) &&
10410 Reg != AArch64::LR && // LR is not reserved, but don't use it.
10411 Reg != AArch64::X16 && // X16 is not guaranteed to be preserved.
10412 Reg != AArch64::X17 && // Ditto for X17.
10413 C.isAvailableAcrossAndOutOfSeq(Reg, TRI) &&
10414 C.isAvailableInsideSeq(Reg, TRI))
10415 return Reg;
10416 }
10417 return Register();
10418}
10419
10420static bool
10422 const outliner::Candidate &b) {
10423 const auto &MFIa = a.getMF()->getInfo<AArch64FunctionInfo>();
10424 const auto &MFIb = b.getMF()->getInfo<AArch64FunctionInfo>();
10425
10426 return MFIa->getSignReturnAddressCondition() ==
10428}
10429
10430static bool
10432 const outliner::Candidate &b) {
10433 const auto &MFIa = a.getMF()->getInfo<AArch64FunctionInfo>();
10434 const auto &MFIb = b.getMF()->getInfo<AArch64FunctionInfo>();
10435
10436 return MFIa->shouldSignWithBKey() == MFIb->shouldSignWithBKey();
10437}
10438
10440 const outliner::Candidate &b) {
10441 const AArch64Subtarget &SubtargetA =
10443 const AArch64Subtarget &SubtargetB =
10444 b.getMF()->getSubtarget<AArch64Subtarget>();
10445 return SubtargetA.hasV8_3aOps() == SubtargetB.hasV8_3aOps();
10446}
10447
10448std::optional<std::unique_ptr<outliner::OutlinedFunction>>
10449AArch64InstrInfo::getOutliningCandidateInfo(
10450 const MachineModuleInfo &MMI,
10451 std::vector<outliner::Candidate> &RepeatedSequenceLocs,
10452 unsigned MinRepeats) const {
10453 unsigned SequenceSize = 0;
10454 for (auto &MI : RepeatedSequenceLocs[0])
10455 SequenceSize += getInstSizeInBytes(MI);
10456
10457 unsigned NumBytesToCreateFrame = 0;
10458
10459 // Avoid splitting ADRP ADD/LDR pair into outlined functions.
10460 // These instructions are fused together by the scheduler.
10461 // Any candidate where ADRP is the last instruction should be rejected
10462 // as that will lead to splitting ADRP pair.
10463 MachineInstr &LastMI = RepeatedSequenceLocs[0].back();
10464 MachineInstr &FirstMI = RepeatedSequenceLocs[0].front();
10465 if (LastMI.getOpcode() == AArch64::ADRP &&
10466 (LastMI.getOperand(1).getTargetFlags() & AArch64II::MO_PAGE) != 0 &&
10467 (LastMI.getOperand(1).getTargetFlags() & AArch64II::MO_GOT) != 0) {
10468 return std::nullopt;
10469 }
10470
10471 // Similarly any candidate where the first instruction is ADD/LDR with a
10472 // page offset should be rejected to avoid ADRP splitting.
10473 if ((FirstMI.getOpcode() == AArch64::ADDXri ||
10474 FirstMI.getOpcode() == AArch64::LDRXui) &&
10475 (FirstMI.getOperand(2).getTargetFlags() & AArch64II::MO_PAGEOFF) != 0 &&
10476 (FirstMI.getOperand(2).getTargetFlags() & AArch64II::MO_GOT) != 0) {
10477 return std::nullopt;
10478 }
10479
10480 // We only allow outlining for functions having exactly matching return
10481 // address signing attributes, i.e., all share the same value for the
10482 // attribute "sign-return-address" and all share the same type of key they
10483 // are signed with.
10484 // Additionally we require all functions to simultaneously either support
10485 // v8.3a features or not. Otherwise an outlined function could get signed
10486 // using dedicated v8.3 instructions and a call from a function that doesn't
10487 // support v8.3 instructions would therefore be invalid.
10488 if (std::adjacent_find(
10489 RepeatedSequenceLocs.begin(), RepeatedSequenceLocs.end(),
10490 [](const outliner::Candidate &a, const outliner::Candidate &b) {
10491 // Return true if a and b are non-equal w.r.t. return address
10492 // signing or support of v8.3a features
10493 if (outliningCandidatesSigningScopeConsensus(a, b) &&
10494 outliningCandidatesSigningKeyConsensus(a, b) &&
10495 outliningCandidatesV8_3OpsConsensus(a, b)) {
10496 return false;
10497 }
10498 return true;
10499 }) != RepeatedSequenceLocs.end()) {
10500 return std::nullopt;
10501 }
10502
10503 // Since at this point all candidates agree on their return address signing
10504 // picking just one is fine. If the candidate functions potentially sign their
10505 // return addresses, the outlined function should do the same. Note that in
10506 // the case of "sign-return-address"="non-leaf" this is an assumption: It is
10507 // not certainly true that the outlined function will have to sign its return
10508 // address but this decision is made later, when the decision to outline
10509 // has already been made.
10510 // The same holds for the number of additional instructions we need: On
10511 // v8.3a RET can be replaced by RETAA/RETAB and no AUT instruction is
10512 // necessary. However, at this point we don't know if the outlined function
10513 // will have a RET instruction so we assume the worst.
10514 const TargetRegisterInfo &TRI = getRegisterInfo();
10515 // Performing a tail call may require extra checks when PAuth is enabled.
10516 // If PAuth is disabled, set it to zero for uniformity.
10517 unsigned NumBytesToCheckLRInTCEpilogue = 0;
10518 const auto RASignCondition = RepeatedSequenceLocs[0]
10519 .getMF()
10520 ->getInfo<AArch64FunctionInfo>()
10521 ->getSignReturnAddressCondition();
10522 if (RASignCondition != SignReturnAddress::None) {
10523 // One PAC and one AUT instructions
10524 NumBytesToCreateFrame += 8;
10525
10526 // PAuth is enabled - set extra tail call cost, if any.
10527 auto LRCheckMethod = Subtarget.getAuthenticatedLRCheckMethod(
10528 *RepeatedSequenceLocs[0].getMF());
10529 NumBytesToCheckLRInTCEpilogue =
10531 // Checking the authenticated LR value may significantly impact
10532 // SequenceSize, so account for it for more precise results.
10533 if (isTailCallReturnInst(RepeatedSequenceLocs[0].back()))
10534 SequenceSize += NumBytesToCheckLRInTCEpilogue;
10535
10536 // We have to check if sp modifying instructions would get outlined.
10537 // If so we only allow outlining if sp is unchanged overall, so matching
10538 // sub and add instructions are okay to outline, all other sp modifications
10539 // are not
10540 auto hasIllegalSPModification = [&TRI](outliner::Candidate &C) {
10541 int SPValue = 0;
10542 for (auto &MI : C) {
10543 if (MI.modifiesRegister(AArch64::SP, &TRI)) {
10544 switch (MI.getOpcode()) {
10545 case AArch64::ADDXri:
10546 case AArch64::ADDWri:
10547 assert(MI.getNumOperands() == 4 && "Wrong number of operands");
10548 assert(MI.getOperand(2).isImm() &&
10549 "Expected operand to be immediate");
10550 assert(MI.getOperand(1).isReg() &&
10551 "Expected operand to be a register");
10552 // Check if the add just increments sp. If so, we search for
10553 // matching sub instructions that decrement sp. If not, the
10554 // modification is illegal
10555 if (MI.getOperand(1).getReg() == AArch64::SP)
10556 SPValue += MI.getOperand(2).getImm();
10557 else
10558 return true;
10559 break;
10560 case AArch64::SUBXri:
10561 case AArch64::SUBWri:
10562 assert(MI.getNumOperands() == 4 && "Wrong number of operands");
10563 assert(MI.getOperand(2).isImm() &&
10564 "Expected operand to be immediate");
10565 assert(MI.getOperand(1).isReg() &&
10566 "Expected operand to be a register");
10567 // Check if the sub just decrements sp. If so, we search for
10568 // matching add instructions that increment sp. If not, the
10569 // modification is illegal
10570 if (MI.getOperand(1).getReg() == AArch64::SP)
10571 SPValue -= MI.getOperand(2).getImm();
10572 else
10573 return true;
10574 break;
10575 default:
10576 return true;
10577 }
10578 }
10579 }
10580 if (SPValue)
10581 return true;
10582 return false;
10583 };
10584 // Remove candidates with illegal stack modifying instructions
10585 llvm::erase_if(RepeatedSequenceLocs, hasIllegalSPModification);
10586
10587 // If the sequence doesn't have enough candidates left, then we're done.
10588 if (RepeatedSequenceLocs.size() < MinRepeats)
10589 return std::nullopt;
10590 }
10591
10592 // Properties about candidate MBBs that hold for all of them.
10593 unsigned FlagsSetInAll = 0xF;
10594
10595 // Compute liveness information for each candidate, and set FlagsSetInAll.
10596 for (outliner::Candidate &C : RepeatedSequenceLocs)
10597 FlagsSetInAll &= C.Flags;
10598
10599 unsigned LastInstrOpcode = RepeatedSequenceLocs[0].back().getOpcode();
10600
10601 // Helper lambda which sets call information for every candidate.
10602 auto SetCandidateCallInfo =
10603 [&RepeatedSequenceLocs](unsigned CallID, unsigned NumBytesForCall) {
10604 for (outliner::Candidate &C : RepeatedSequenceLocs)
10605 C.setCallInfo(CallID, NumBytesForCall);
10606 };
10607
10608 unsigned FrameID = MachineOutlinerDefault;
10609 NumBytesToCreateFrame += 4;
10610
10611 bool HasBTI = any_of(RepeatedSequenceLocs, [](outliner::Candidate &C) {
10612 return C.getMF()->getInfo<AArch64FunctionInfo>()->branchTargetEnforcement();
10613 });
10614
10615 // We check to see if CFI Instructions are present, and if they are
10616 // we find the number of CFI Instructions in the candidates.
10617 unsigned CFICount = 0;
10618 for (auto &I : RepeatedSequenceLocs[0]) {
10619 if (I.isCFIInstruction())
10620 CFICount++;
10621 }
10622
10623 // We compare the number of found CFI Instructions to the number of CFI
10624 // instructions in the parent function for each candidate. We must check this
10625 // since if we outline one of the CFI instructions in a function, we have to
10626 // outline them all for correctness. If we do not, the address offsets will be
10627 // incorrect between the two sections of the program.
10628 for (outliner::Candidate &C : RepeatedSequenceLocs) {
10629 std::vector<MCCFIInstruction> CFIInstructions =
10630 C.getMF()->getFrameInstructions();
10631
10632 if (CFICount > 0 && CFICount != CFIInstructions.size())
10633 return std::nullopt;
10634 }
10635
10636 // Returns true if an instructions is safe to fix up, false otherwise.
10637 auto IsSafeToFixup = [this, &TRI](MachineInstr &MI) {
10638 if (MI.isCall())
10639 return true;
10640
10641 if (!MI.modifiesRegister(AArch64::SP, &TRI) &&
10642 !MI.readsRegister(AArch64::SP, &TRI))
10643 return true;
10644
10645 // Any modification of SP will break our code to save/restore LR.
10646 // FIXME: We could handle some instructions which add a constant
10647 // offset to SP, with a bit more work.
10648 if (MI.modifiesRegister(AArch64::SP, &TRI))
10649 return false;
10650
10651 // At this point, we have a stack instruction that we might need to
10652 // fix up. We'll handle it if it's a load or store.
10653 if (MI.mayLoadOrStore()) {
10654 const MachineOperand *Base; // Filled with the base operand of MI.
10655 int64_t Offset; // Filled with the offset of MI.
10656 bool OffsetIsScalable;
10657
10658 // Does it allow us to offset the base operand and is the base the
10659 // register SP?
10660 if (!getMemOperandWithOffset(MI, Base, Offset, OffsetIsScalable, &TRI) ||
10661 !Base->isReg() || Base->getReg() != AArch64::SP)
10662 return false;
10663
10664 // Fixe-up code below assumes bytes.
10665 if (OffsetIsScalable)
10666 return false;
10667
10668 // Find the minimum/maximum offset for this instruction and check
10669 // if fixing it up would be in range.
10670 int64_t MinOffset,
10671 MaxOffset; // Unscaled offsets for the instruction.
10672 // The scale to multiply the offsets by.
10673 TypeSize Scale(0U, false), DummyWidth(0U, false);
10674 getMemOpInfo(MI.getOpcode(), Scale, DummyWidth, MinOffset, MaxOffset);
10675
10676 Offset += 16; // Update the offset to what it would be if we outlined.
10677 if (Offset < MinOffset * (int64_t)Scale.getFixedValue() ||
10678 Offset > MaxOffset * (int64_t)Scale.getFixedValue())
10679 return false;
10680
10681 // It's in range, so we can outline it.
10682 return true;
10683 }
10684
10685 // FIXME: Add handling for instructions like "add x0, sp, #8".
10686
10687 // We can't fix it up, so don't outline it.
10688 return false;
10689 };
10690
10691 // True if it's possible to fix up each stack instruction in this sequence.
10692 // Important for frames/call variants that modify the stack.
10693 bool AllStackInstrsSafe =
10694 llvm::all_of(RepeatedSequenceLocs[0], IsSafeToFixup);
10695
10696 // If the last instruction in any candidate is a terminator, then we should
10697 // tail call all of the candidates.
10698 if (RepeatedSequenceLocs[0].back().isTerminator()) {
10699 FrameID = MachineOutlinerTailCall;
10700 NumBytesToCreateFrame = 0;
10701 unsigned NumBytesForCall = 4 + NumBytesToCheckLRInTCEpilogue;
10702 SetCandidateCallInfo(MachineOutlinerTailCall, NumBytesForCall);
10703 }
10704
10705 else if (LastInstrOpcode == AArch64::BL ||
10706 ((LastInstrOpcode == AArch64::BLR ||
10707 LastInstrOpcode == AArch64::BLRNoIP) &&
10708 !HasBTI)) {
10709 // FIXME: Do we need to check if the code after this uses the value of LR?
10710 FrameID = MachineOutlinerThunk;
10711 NumBytesToCreateFrame = NumBytesToCheckLRInTCEpilogue;
10712 SetCandidateCallInfo(MachineOutlinerThunk, 4);
10713 }
10714
10715 else {
10716 // We need to decide how to emit calls + frames. We can always emit the same
10717 // frame if we don't need to save to the stack. If we have to save to the
10718 // stack, then we need a different frame.
10719 unsigned NumBytesNoStackCalls = 0;
10720 std::vector<outliner::Candidate> CandidatesWithoutStackFixups;
10721
10722 // Check if we have to save LR.
10723 for (outliner::Candidate &C : RepeatedSequenceLocs) {
10724 bool LRAvailable =
10726 ? C.isAvailableAcrossAndOutOfSeq(AArch64::LR, TRI)
10727 : true;
10728 // If we have a noreturn caller, then we're going to be conservative and
10729 // say that we have to save LR. If we don't have a ret at the end of the
10730 // block, then we can't reason about liveness accurately.
10731 //
10732 // FIXME: We can probably do better than always disabling this in
10733 // noreturn functions by fixing up the liveness info.
10734 bool IsNoReturn =
10735 C.getMF()->getFunction().hasFnAttribute(Attribute::NoReturn);
10736
10737 // Is LR available? If so, we don't need a save.
10738 if (LRAvailable && !IsNoReturn) {
10739 NumBytesNoStackCalls += 4;
10740 C.setCallInfo(MachineOutlinerNoLRSave, 4);
10741 CandidatesWithoutStackFixups.push_back(C);
10742 }
10743
10744 // Is an unused register available? If so, we won't modify the stack, so
10745 // we can outline with the same frame type as those that don't save LR.
10746 else if (findRegisterToSaveLRTo(C)) {
10747 NumBytesNoStackCalls += 12;
10748 C.setCallInfo(MachineOutlinerRegSave, 12);
10749 CandidatesWithoutStackFixups.push_back(C);
10750 }
10751
10752 // Is SP used in the sequence at all? If not, we don't have to modify
10753 // the stack, so we are guaranteed to get the same frame.
10754 else if (C.isAvailableInsideSeq(AArch64::SP, TRI)) {
10755 NumBytesNoStackCalls += 12;
10756 C.setCallInfo(MachineOutlinerDefault, 12);
10757 CandidatesWithoutStackFixups.push_back(C);
10758 }
10759
10760 // If we outline this, we need to modify the stack. Pretend we don't
10761 // outline this by saving all of its bytes.
10762 else {
10763 NumBytesNoStackCalls += SequenceSize;
10764 }
10765 }
10766
10767 // If there are no places where we have to save LR, then note that we
10768 // don't have to update the stack. Otherwise, give every candidate the
10769 // default call type, as long as it's safe to do so.
10770 if (!AllStackInstrsSafe ||
10771 NumBytesNoStackCalls <= RepeatedSequenceLocs.size() * 12) {
10772 RepeatedSequenceLocs = CandidatesWithoutStackFixups;
10773 FrameID = MachineOutlinerNoLRSave;
10774 if (RepeatedSequenceLocs.size() < MinRepeats)
10775 return std::nullopt;
10776 } else {
10777 SetCandidateCallInfo(MachineOutlinerDefault, 12);
10778
10779 // Bugzilla ID: 46767
10780 // TODO: Check if fixing up the stack more than once is safe so we can
10781 // outline these.
10782 //
10783 // An outline resulting in a caller that requires stack fixups at the
10784 // callsite to a callee that also requires stack fixups can happen when
10785 // there are no available registers at the candidate callsite for a
10786 // candidate that itself also has calls.
10787 //
10788 // In other words if function_containing_sequence in the following pseudo
10789 // assembly requires that we save LR at the point of the call, but there
10790 // are no available registers: in this case we save using SP and as a
10791 // result the SP offsets requires stack fixups by multiples of 16.
10792 //
10793 // function_containing_sequence:
10794 // ...
10795 // save LR to SP <- Requires stack instr fixups in OUTLINED_FUNCTION_N
10796 // call OUTLINED_FUNCTION_N
10797 // restore LR from SP
10798 // ...
10799 //
10800 // OUTLINED_FUNCTION_N:
10801 // save LR to SP <- Requires stack instr fixups in OUTLINED_FUNCTION_N
10802 // ...
10803 // bl foo
10804 // restore LR from SP
10805 // ret
10806 //
10807 // Because the code to handle more than one stack fixup does not
10808 // currently have the proper checks for legality, these cases will assert
10809 // in the AArch64 MachineOutliner. This is because the code to do this
10810 // needs more hardening, testing, better checks that generated code is
10811 // legal, etc and because it is only verified to handle a single pass of
10812 // stack fixup.
10813 //
10814 // The assert happens in AArch64InstrInfo::buildOutlinedFrame to catch
10815 // these cases until they are known to be handled. Bugzilla 46767 is
10816 // referenced in comments at the assert site.
10817 //
10818 // To avoid asserting (or generating non-legal code on noassert builds)
10819 // we remove all candidates which would need more than one stack fixup by
10820 // pruning the cases where the candidate has calls while also having no
10821 // available LR and having no available general purpose registers to copy
10822 // LR to (ie one extra stack save/restore).
10823 //
10824 if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) {
10825 erase_if(RepeatedSequenceLocs, [this, &TRI](outliner::Candidate &C) {
10826 auto IsCall = [](const MachineInstr &MI) { return MI.isCall(); };
10827 return (llvm::any_of(C, IsCall)) &&
10828 (!C.isAvailableAcrossAndOutOfSeq(AArch64::LR, TRI) ||
10829 !findRegisterToSaveLRTo(C));
10830 });
10831 }
10832 }
10833
10834 // If we dropped all of the candidates, bail out here.
10835 if (RepeatedSequenceLocs.size() < MinRepeats)
10836 return std::nullopt;
10837 }
10838
10839 // Does every candidate's MBB contain a call? If so, then we might have a call
10840 // in the range.
10841 if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) {
10842 // Check if the range contains a call. These require a save + restore of the
10843 // link register.
10844 outliner::Candidate &FirstCand = RepeatedSequenceLocs[0];
10845 bool ModStackToSaveLR = false;
10846 if (any_of(drop_end(FirstCand),
10847 [](const MachineInstr &MI) { return MI.isCall(); }))
10848 ModStackToSaveLR = true;
10849
10850 // Handle the last instruction separately. If this is a tail call, then the
10851 // last instruction is a call. We don't want to save + restore in this case.
10852 // However, it could be possible that the last instruction is a call without
10853 // it being valid to tail call this sequence. We should consider this as
10854 // well.
10855 else if (FrameID != MachineOutlinerThunk &&
10856 FrameID != MachineOutlinerTailCall && FirstCand.back().isCall())
10857 ModStackToSaveLR = true;
10858
10859 if (ModStackToSaveLR) {
10860 // We can't fix up the stack. Bail out.
10861 if (!AllStackInstrsSafe)
10862 return std::nullopt;
10863
10864 // Save + restore LR.
10865 NumBytesToCreateFrame += 8;
10866
10867 // Add the extra mov if we will save a frame record instead of just LR.
10869 RepeatedSequenceLocs, TRI))
10870 NumBytesToCreateFrame += 4;
10871 }
10872 }
10873
10874 // If we have CFI instructions, we can only outline if the outlined section
10875 // can be a tail call
10876 if (FrameID != MachineOutlinerTailCall && CFICount > 0)
10877 return std::nullopt;
10878
10879 return std::make_unique<outliner::OutlinedFunction>(
10880 RepeatedSequenceLocs, SequenceSize, NumBytesToCreateFrame, FrameID);
10881}
10882
10883void AArch64InstrInfo::mergeOutliningCandidateAttributes(
10884 Function &F, std::vector<outliner::Candidate> &Candidates) const {
10885 // If a bunch of candidates reach this point they must agree on their return
10886 // address signing. It is therefore enough to just consider the signing
10887 // behaviour of one of them
10888 const auto &CFn = Candidates.front().getMF()->getFunction();
10889
10890 if (CFn.hasFnAttribute("ptrauth-returns"))
10891 F.addFnAttr(CFn.getFnAttribute("ptrauth-returns"));
10892 if (CFn.hasFnAttribute("ptrauth-auth-traps"))
10893 F.addFnAttr(CFn.getFnAttribute("ptrauth-auth-traps"));
10894 // Since all candidates belong to the same module, just copy the
10895 // function-level attributes of an arbitrary function.
10896 if (CFn.hasFnAttribute("sign-return-address"))
10897 F.addFnAttr(CFn.getFnAttribute("sign-return-address"));
10898 if (CFn.hasFnAttribute("sign-return-address-key"))
10899 F.addFnAttr(CFn.getFnAttribute("sign-return-address-key"));
10900
10901 AArch64GenInstrInfo::mergeOutliningCandidateAttributes(F, Candidates);
10902}
10903
10904bool AArch64InstrInfo::isFunctionSafeToOutlineFrom(
10905 MachineFunction &MF, bool OutlineFromLinkOnceODRs) const {
10906 const Function &F = MF.getFunction();
10907
10908 // Can F be deduplicated by the linker? If it can, don't outline from it.
10909 if (!OutlineFromLinkOnceODRs && F.hasLinkOnceODRLinkage())
10910 return false;
10911
10912 // Don't outline from functions with section markings; the program could
10913 // expect that all the code is in the named section.
10914 // FIXME: Allow outlining from multiple functions with the same section
10915 // marking.
10916 if (F.hasSection())
10917 return false;
10918
10919 // Outlining from functions with redzones is unsafe since the outliner may
10920 // modify the stack. Check if hasRedZone is true or unknown; if yes, don't
10921 // outline from it.
10922 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
10923 if (!AFI || AFI->hasRedZone().value_or(true))
10924 return false;
10925
10926 // FIXME: Determine whether it is safe to outline from functions which contain
10927 // streaming-mode changes. We may need to ensure any smstart/smstop pairs are
10928 // outlined together and ensure it is safe to outline with async unwind info,
10929 // required for saving & restoring VG around calls.
10930 if (AFI->hasStreamingModeChanges())
10931 return false;
10932
10933 // FIXME: Teach the outliner to generate/handle Windows unwind info.
10935 return false;
10936
10937 // It's safe to outline from MF.
10938 return true;
10939}
10940
10942AArch64InstrInfo::getOutlinableRanges(MachineBasicBlock &MBB,
10943 unsigned &Flags) const {
10945 "Must track liveness!");
10947 std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>>
10948 Ranges;
10949 // According to the AArch64 Procedure Call Standard, the following are
10950 // undefined on entry/exit from a function call:
10951 //
10952 // * Registers x16, x17, (and thus w16, w17)
10953 // * Condition codes (and thus the NZCV register)
10954 //
10955 // If any of these registers are used inside or live across an outlined
10956 // function, then they may be modified later, either by the compiler or
10957 // some other tool (like the linker).
10958 //
10959 // To avoid outlining in these situations, partition each block into ranges
10960 // where these registers are dead. We will only outline from those ranges.
10961 LiveRegUnits LRU(getRegisterInfo());
10962 auto AreAllUnsafeRegsDead = [&LRU]() {
10963 return LRU.available(AArch64::W16) && LRU.available(AArch64::W17) &&
10964 LRU.available(AArch64::NZCV);
10965 };
10966
10967 // We need to know if LR is live across an outlining boundary later on in
10968 // order to decide how we'll create the outlined call, frame, etc.
10969 //
10970 // It's pretty expensive to check this for *every candidate* within a block.
10971 // That's some potentially n^2 behaviour, since in the worst case, we'd need
10972 // to compute liveness from the end of the block for O(n) candidates within
10973 // the block.
10974 //
10975 // So, to improve the average case, let's keep track of liveness from the end
10976 // of the block to the beginning of *every outlinable range*. If we know that
10977 // LR is available in every range we could outline from, then we know that
10978 // we don't need to check liveness for any candidate within that range.
10979 bool LRAvailableEverywhere = true;
10980 // Compute liveness bottom-up.
10981 LRU.addLiveOuts(MBB);
10982 // Update flags that require info about the entire MBB.
10983 auto UpdateWholeMBBFlags = [&Flags](const MachineInstr &MI) {
10984 if (MI.isCall() && !MI.isTerminator())
10986 };
10987 // Range: [RangeBegin, RangeEnd)
10988 MachineBasicBlock::instr_iterator RangeBegin, RangeEnd;
10989 unsigned RangeLen;
10990 auto CreateNewRangeStartingAt =
10991 [&RangeBegin, &RangeEnd,
10992 &RangeLen](MachineBasicBlock::instr_iterator NewBegin) {
10993 RangeBegin = NewBegin;
10994 RangeEnd = std::next(RangeBegin);
10995 RangeLen = 0;
10996 };
10997 auto SaveRangeIfNonEmpty = [&RangeLen, &Ranges, &RangeBegin, &RangeEnd]() {
10998 // At least one unsafe register is not dead. We do not want to outline at
10999 // this point. If it is long enough to outline from and does not cross a
11000 // bundle boundary, save the range [RangeBegin, RangeEnd).
11001 if (RangeLen <= 1)
11002 return;
11003 if (!RangeBegin.isEnd() && RangeBegin->isBundledWithPred())
11004 return;
11005 if (!RangeEnd.isEnd() && RangeEnd->isBundledWithPred())
11006 return;
11007 Ranges.emplace_back(RangeBegin, RangeEnd);
11008 };
11009 // Find the first point where all unsafe registers are dead.
11010 // FIND: <safe instr> <-- end of first potential range
11011 // SKIP: <unsafe def>
11012 // SKIP: ... everything between ...
11013 // SKIP: <unsafe use>
11014 auto FirstPossibleEndPt = MBB.instr_rbegin();
11015 for (; FirstPossibleEndPt != MBB.instr_rend(); ++FirstPossibleEndPt) {
11016 if (!FirstPossibleEndPt->isDebugInstr())
11017 LRU.stepBackward(*FirstPossibleEndPt);
11018 // Update flags that impact how we outline across the entire block,
11019 // regardless of safety.
11020 UpdateWholeMBBFlags(*FirstPossibleEndPt);
11021 if (AreAllUnsafeRegsDead())
11022 break;
11023 }
11024 // If we exhausted the entire block, we have no safe ranges to outline.
11025 if (FirstPossibleEndPt == MBB.instr_rend())
11026 return Ranges;
11027 // Current range.
11028 CreateNewRangeStartingAt(FirstPossibleEndPt->getIterator());
11029 // StartPt points to the first place where all unsafe registers
11030 // are dead (if there is any such point). Begin partitioning the MBB into
11031 // ranges.
11032 for (auto &MI : make_range(FirstPossibleEndPt, MBB.instr_rend())) {
11033 if (!MI.isDebugInstr())
11034 LRU.stepBackward(MI);
11035 UpdateWholeMBBFlags(MI);
11036 if (!AreAllUnsafeRegsDead()) {
11037 SaveRangeIfNonEmpty();
11038 CreateNewRangeStartingAt(MI.getIterator());
11039 continue;
11040 }
11041 LRAvailableEverywhere &= LRU.available(AArch64::LR);
11042 RangeBegin = MI.getIterator();
11043 ++RangeLen;
11044 }
11045 // Above loop misses the last (or only) range. If we are still safe, then
11046 // let's save the range.
11047 if (AreAllUnsafeRegsDead())
11048 SaveRangeIfNonEmpty();
11049 if (Ranges.empty())
11050 return Ranges;
11051 // We found the ranges bottom-up. Mapping expects the top-down. Reverse
11052 // the order.
11053 std::reverse(Ranges.begin(), Ranges.end());
11054 // If there is at least one outlinable range where LR is unavailable
11055 // somewhere, remember that.
11056 if (!LRAvailableEverywhere)
11058 return Ranges;
11059}
11060
11062AArch64InstrInfo::getOutliningTypeImpl(const MachineModuleInfo &MMI,
11064 unsigned Flags) const {
11065 MachineInstr &MI = *MIT;
11066
11067 // Don't outline anything used for return address signing. The outlined
11068 // function will get signed later if needed
11069 switch (MI.getOpcode()) {
11070 case AArch64::PACM:
11071 case AArch64::PACIASP:
11072 case AArch64::PACIBSP:
11073 case AArch64::PACIASPPC:
11074 case AArch64::PACIBSPPC:
11075 case AArch64::AUTIASP:
11076 case AArch64::AUTIBSP:
11077 case AArch64::AUTIASPPCi:
11078 case AArch64::AUTIASPPCr:
11079 case AArch64::AUTIBSPPCi:
11080 case AArch64::AUTIBSPPCr:
11081 case AArch64::RETAA:
11082 case AArch64::RETAB:
11083 case AArch64::RETAASPPCi:
11084 case AArch64::RETAASPPCr:
11085 case AArch64::RETABSPPCi:
11086 case AArch64::RETABSPPCr:
11087 case AArch64::EMITBKEY:
11088 case AArch64::PAUTH_PROLOGUE:
11089 case AArch64::PAUTH_EPILOGUE:
11091 }
11092
11093 // We can only outline these if we will tail call the outlined function, or
11094 // fix up the CFI offsets. Currently, CFI instructions are outlined only if
11095 // in a tail call.
11096 //
11097 // FIXME: If the proper fixups for the offset are implemented, this should be
11098 // possible.
11099 if (MI.isCFIInstruction())
11101
11102 // Is this a terminator for a basic block?
11103 if (MI.isTerminator())
11104 // TargetInstrInfo::getOutliningType has already filtered out anything
11105 // that would break this, so we can allow it here.
11107
11108 // Make sure none of the operands are un-outlinable.
11109 for (const MachineOperand &MOP : MI.operands()) {
11110 // A check preventing CFI indices was here before, but only CFI
11111 // instructions should have those.
11112 assert(!MOP.isCFIIndex());
11113
11114 // If it uses LR or W30 explicitly, then don't touch it.
11115 if (MOP.isReg() && !MOP.isImplicit() &&
11116 (MOP.getReg() == AArch64::LR || MOP.getReg() == AArch64::W30))
11118 }
11119
11120 // Special cases for instructions that can always be outlined, but will fail
11121 // the later tests. e.g, ADRPs, which are PC-relative use LR, but can always
11122 // be outlined because they don't require a *specific* value to be in LR.
11123 if (MI.getOpcode() == AArch64::ADRP)
11125
11126 // If MI is a call we might be able to outline it. We don't want to outline
11127 // any calls that rely on the position of items on the stack. When we outline
11128 // something containing a call, we have to emit a save and restore of LR in
11129 // the outlined function. Currently, this always happens by saving LR to the
11130 // stack. Thus, if we outline, say, half the parameters for a function call
11131 // plus the call, then we'll break the callee's expectations for the layout
11132 // of the stack.
11133 //
11134 // FIXME: Allow calls to functions which construct a stack frame, as long
11135 // as they don't access arguments on the stack.
11136 // FIXME: Figure out some way to analyze functions defined in other modules.
11137 // We should be able to compute the memory usage based on the IR calling
11138 // convention, even if we can't see the definition.
11139 if (MI.isCall()) {
11140 // Get the function associated with the call. Look at each operand and find
11141 // the one that represents the callee and get its name.
11142 const Function *Callee = nullptr;
11143 for (const MachineOperand &MOP : MI.operands()) {
11144 if (MOP.isGlobal()) {
11145 Callee = dyn_cast<Function>(MOP.getGlobal());
11146 break;
11147 }
11148 }
11149
11150 // Never outline calls to mcount. There isn't any rule that would require
11151 // this, but the Linux kernel's "ftrace" feature depends on it.
11152 if (Callee && Callee->getName() == "\01_mcount")
11154
11155 // If we don't know anything about the callee, assume it depends on the
11156 // stack layout of the caller. In that case, it's only legal to outline
11157 // as a tail-call. Explicitly list the call instructions we know about so we
11158 // don't get unexpected results with call pseudo-instructions.
11159 auto UnknownCallOutlineType = outliner::InstrType::Illegal;
11160 if (MI.getOpcode() == AArch64::BLR ||
11161 MI.getOpcode() == AArch64::BLRNoIP || MI.getOpcode() == AArch64::BL)
11162 UnknownCallOutlineType = outliner::InstrType::LegalTerminator;
11163
11164 if (!Callee)
11165 return UnknownCallOutlineType;
11166
11167 // We have a function we have information about. Check it if it's something
11168 // can safely outline.
11169 MachineFunction *CalleeMF = MMI.getMachineFunction(*Callee);
11170
11171 // We don't know what's going on with the callee at all. Don't touch it.
11172 if (!CalleeMF)
11173 return UnknownCallOutlineType;
11174
11175 // Check if we know anything about the callee saves on the function. If we
11176 // don't, then don't touch it, since that implies that we haven't
11177 // computed anything about its stack frame yet.
11178 MachineFrameInfo &MFI = CalleeMF->getFrameInfo();
11179 if (!MFI.isCalleeSavedInfoValid() || MFI.getStackSize() > 0 ||
11180 MFI.getNumObjects() > 0)
11181 return UnknownCallOutlineType;
11182
11183 // At this point, we can say that CalleeMF ought to not pass anything on the
11184 // stack. Therefore, we can outline it.
11186 }
11187
11188 // Don't touch the link register or W30.
11189 if (MI.readsRegister(AArch64::W30, &getRegisterInfo()) ||
11190 MI.modifiesRegister(AArch64::W30, &getRegisterInfo()))
11192
11193 // Don't outline BTI instructions, because that will prevent the outlining
11194 // site from being indirectly callable.
11195 if (hasBTISemantics(MI))
11197
11199}
11200
11201void AArch64InstrInfo::fixupPostOutline(MachineBasicBlock &MBB) const {
11202 for (MachineInstr &MI : MBB) {
11203 const MachineOperand *Base;
11204 TypeSize Width(0, false);
11205 int64_t Offset;
11206 bool OffsetIsScalable;
11207
11208 // Is this a load or store with an immediate offset with SP as the base?
11209 if (!MI.mayLoadOrStore() ||
11210 !getMemOperandWithOffsetWidth(MI, Base, Offset, OffsetIsScalable, Width,
11211 &RI) ||
11212 (Base->isReg() && Base->getReg() != AArch64::SP))
11213 continue;
11214
11215 // It is, so we have to fix it up.
11216 TypeSize Scale(0U, false);
11217 int64_t Dummy1, Dummy2;
11218
11219 MachineOperand &StackOffsetOperand = getMemOpBaseRegImmOfsOffsetOperand(MI);
11220 assert(StackOffsetOperand.isImm() && "Stack offset wasn't immediate!");
11221 getMemOpInfo(MI.getOpcode(), Scale, Width, Dummy1, Dummy2);
11222 assert(Scale != 0 && "Unexpected opcode!");
11223 assert(!OffsetIsScalable && "Expected offset to be a byte offset");
11224
11225 // We've pushed the return address to the stack, so add 16 to the offset.
11226 // This is safe, since we already checked if it would overflow when we
11227 // checked if this instruction was legal to outline.
11228 int64_t NewImm = (Offset + 16) / (int64_t)Scale.getFixedValue();
11229 StackOffsetOperand.setImm(NewImm);
11230 }
11231}
11232
11234 const AArch64InstrInfo *TII,
11235 bool ShouldSignReturnAddr) {
11236 if (!ShouldSignReturnAddr)
11237 return;
11238
11239 BuildMI(MBB, MBB.begin(), DebugLoc(), TII->get(AArch64::PAUTH_PROLOGUE))
11241 TII->createPauthEpilogueInstr(MBB, DebugLoc());
11242}
11243
11244void AArch64InstrInfo::buildOutlinedFrame(
11246 const outliner::OutlinedFunction &OF) const {
11247
11248 AArch64FunctionInfo *FI = MF.getInfo<AArch64FunctionInfo>();
11249
11250 if (OF.FrameConstructionID == MachineOutlinerTailCall)
11251 FI->setOutliningStyle("Tail Call");
11252 else if (OF.FrameConstructionID == MachineOutlinerThunk) {
11253 // For thunk outlining, rewrite the last instruction from a call to a
11254 // tail-call.
11255 MachineInstr *Call = &*--MBB.instr_end();
11256 unsigned TailOpcode;
11257 if (Call->getOpcode() == AArch64::BL) {
11258 TailOpcode = AArch64::TCRETURNdi;
11259 } else {
11260 assert(Call->getOpcode() == AArch64::BLR ||
11261 Call->getOpcode() == AArch64::BLRNoIP);
11262 TailOpcode = AArch64::TCRETURNriALL;
11263 }
11264 MachineInstr *TC = BuildMI(MF, DebugLoc(), get(TailOpcode))
11265 .add(Call->getOperand(0))
11266 .addImm(0);
11267 MBB.insert(MBB.end(), TC);
11269
11270 FI->setOutliningStyle("Thunk");
11271 }
11272
11273 bool IsLeafFunction = true;
11274
11275 // Is there a call in the outlined range?
11276 auto IsNonTailCall = [](const MachineInstr &MI) {
11277 return MI.isCall() && !MI.isReturn();
11278 };
11279
11280 if (llvm::any_of(MBB.instrs(), IsNonTailCall)) {
11281 // Fix up the instructions in the range, since we're going to modify the
11282 // stack.
11283
11284 // Bugzilla ID: 46767
11285 // TODO: Check if fixing up twice is safe so we can outline these.
11286 assert(OF.FrameConstructionID != MachineOutlinerDefault &&
11287 "Can only fix up stack references once");
11288 fixupPostOutline(MBB);
11289
11290 IsLeafFunction = false;
11291
11292 // LR has to be a live in so that we can save it.
11293 if (!MBB.isLiveIn(AArch64::LR))
11294 MBB.addLiveIn(AArch64::LR);
11295
11298
11299 if (OF.FrameConstructionID == MachineOutlinerTailCall ||
11300 OF.FrameConstructionID == MachineOutlinerThunk)
11301 Et = std::prev(MBB.end());
11302
11303 // There is a call in the range, so we must save LR. Save it as part of a
11304 // frame record when that gives us a smaller compact unwind encoding.
11306 // FP is saved here, so it must be live-in.
11307 if (!MBB.isLiveIn(AArch64::FP))
11308 MBB.addLiveIn(AArch64::FP);
11309
11310 // stp x29, x30, [sp, #-16]! (the pre-index imm is scaled by 8: -2 * 8)
11311 MachineInstr *STPXpre = BuildMI(MF, DebugLoc(), get(AArch64::STPXpre))
11312 .addReg(AArch64::SP, RegState::Define)
11313 .addReg(AArch64::FP)
11314 .addReg(AArch64::LR)
11315 .addReg(AArch64::SP)
11316 .addImm(-2);
11317 It = MBB.insert(It, STPXpre);
11318
11319 // mov x29, sp (add x29, sp, #0), so x29 points at the frame record.
11320 MachineInstr *SetFP = BuildMI(MF, DebugLoc(), get(AArch64::ADDXri))
11321 .addReg(AArch64::FP, RegState::Define)
11322 .addReg(AArch64::SP)
11323 .addImm(0)
11324 .addImm(0);
11325 MBB.insertAfter(It, SetFP);
11326
11327 // Describe the frame record with FP as the CFA. The encoder needs all
11328 // three to pick FRAME. No need to check for unwind info here: we only
11329 // get here if the function has it.
11330 CFIInstBuilder CFIBuilder(MBB, std::next(SetFP->getIterator()),
11332 CFIBuilder.buildDefCFA(AArch64::FP, 16);
11333 CFIBuilder.buildOffset(AArch64::LR, -8);
11334 CFIBuilder.buildOffset(AArch64::FP, -16);
11335
11336 // ldp x29, x30, [sp], #16
11337 MachineInstr *LDPXpost = BuildMI(MF, DebugLoc(), get(AArch64::LDPXpost))
11338 .addReg(AArch64::SP, RegState::Define)
11339 .addReg(AArch64::FP, RegState::Define)
11340 .addReg(AArch64::LR, RegState::Define)
11341 .addReg(AArch64::SP)
11342 .addImm(2);
11343 Et = MBB.insert(Et, LDPXpost);
11344 } else {
11345 // Insert a save before the outlined region
11346 MachineInstr *STRXpre = BuildMI(MF, DebugLoc(), get(AArch64::STRXpre))
11347 .addReg(AArch64::SP, RegState::Define)
11348 .addReg(AArch64::LR)
11349 .addReg(AArch64::SP)
11350 .addImm(-16);
11351 It = MBB.insert(It, STRXpre);
11352
11353 if (MF.getInfo<AArch64FunctionInfo>()->needsDwarfUnwindInfo(MF)) {
11354 CFIInstBuilder CFIBuilder(MBB, It, MachineInstr::FrameSetup);
11355
11356 // Add a CFI saying the stack was moved 16 B down.
11357 CFIBuilder.buildDefCFAOffset(16);
11358
11359 // Add a CFI saying that the LR that we want to find is now 16 B higher
11360 // than before.
11361 CFIBuilder.buildOffset(AArch64::LR, -16);
11362 }
11363
11364 // Insert a restore before the terminator for the function.
11365 MachineInstr *LDRXpost = BuildMI(MF, DebugLoc(), get(AArch64::LDRXpost))
11366 .addReg(AArch64::SP, RegState::Define)
11367 .addReg(AArch64::LR, RegState::Define)
11368 .addReg(AArch64::SP)
11369 .addImm(16);
11370 Et = MBB.insert(Et, LDRXpost);
11371 }
11372 }
11373
11374 auto RASignCondition = FI->getSignReturnAddressCondition();
11375 bool ShouldSignReturnAddr = AArch64FunctionInfo::shouldSignReturnAddress(
11376 RASignCondition, !IsLeafFunction);
11377
11378 // If this is a tail call outlined function, then there's already a return.
11379 if (OF.FrameConstructionID == MachineOutlinerTailCall ||
11380 OF.FrameConstructionID == MachineOutlinerThunk) {
11381 signOutlinedFunction(MF, MBB, this, ShouldSignReturnAddr);
11382 return;
11383 }
11384
11385 // It's not a tail call, so we have to insert the return ourselves.
11386
11387 // LR has to be a live in so that we can return to it.
11388 if (!MBB.isLiveIn(AArch64::LR))
11389 MBB.addLiveIn(AArch64::LR);
11390
11391 MachineInstr *ret = BuildMI(MF, DebugLoc(), get(AArch64::RET))
11392 .addReg(AArch64::LR);
11393 MBB.insert(MBB.end(), ret);
11394
11395 signOutlinedFunction(MF, MBB, this, ShouldSignReturnAddr);
11396
11397 FI->setOutliningStyle("Function");
11398
11399 // Did we have to modify the stack by saving the link register?
11400 if (OF.FrameConstructionID != MachineOutlinerDefault)
11401 return;
11402
11403 // We modified the stack.
11404 // Walk over the basic block and fix up all the stack accesses.
11405 fixupPostOutline(MBB);
11406}
11407
11408MachineBasicBlock::iterator AArch64InstrInfo::insertOutlinedCall(
11411
11412 // Are we tail calling?
11413 if (C.CallConstructionID == MachineOutlinerTailCall) {
11414 // If yes, then we can just branch to the label.
11415 It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::TCRETURNdi))
11416 .addGlobalAddress(M.getNamedValue(MF.getName()))
11417 .addImm(0));
11418 return It;
11419 }
11420
11421 // Are we saving the link register?
11422 if (C.CallConstructionID == MachineOutlinerNoLRSave ||
11423 C.CallConstructionID == MachineOutlinerThunk) {
11424 // No, so just insert the call.
11425 It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::BL))
11426 .addGlobalAddress(M.getNamedValue(MF.getName())));
11427 return It;
11428 }
11429
11430 // We want to return the spot where we inserted the call.
11432
11433 // Instructions for saving and restoring LR around the call instruction we're
11434 // going to insert.
11435 MachineInstr *Save;
11436 MachineInstr *Restore;
11437 // Can we save to a register?
11438 if (C.CallConstructionID == MachineOutlinerRegSave) {
11439 // FIXME: This logic should be sunk into a target-specific interface so that
11440 // we don't have to recompute the register.
11441 Register Reg = findRegisterToSaveLRTo(C);
11442 assert(Reg && "No callee-saved register available?");
11443
11444 // LR has to be a live in so that we can save it.
11445 if (!MBB.isLiveIn(AArch64::LR))
11446 MBB.addLiveIn(AArch64::LR);
11447
11448 // Save and restore LR from Reg.
11449 Save = BuildMI(MF, DebugLoc(), get(AArch64::ORRXrs), Reg)
11450 .addReg(AArch64::XZR)
11451 .addReg(AArch64::LR)
11452 .addImm(0);
11453 Restore = BuildMI(MF, DebugLoc(), get(AArch64::ORRXrs), AArch64::LR)
11454 .addReg(AArch64::XZR)
11455 .addReg(Reg)
11456 .addImm(0);
11457 } else {
11458 // We have the default case. Save and restore from SP.
11459 Save = BuildMI(MF, DebugLoc(), get(AArch64::STRXpre))
11460 .addReg(AArch64::SP, RegState::Define)
11461 .addReg(AArch64::LR)
11462 .addReg(AArch64::SP)
11463 .addImm(-16);
11464 Restore = BuildMI(MF, DebugLoc(), get(AArch64::LDRXpost))
11465 .addReg(AArch64::SP, RegState::Define)
11466 .addReg(AArch64::LR, RegState::Define)
11467 .addReg(AArch64::SP)
11468 .addImm(16);
11469 }
11470
11471 It = MBB.insert(It, Save);
11472 It++;
11473
11474 // Insert the call.
11475 It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::BL))
11476 .addGlobalAddress(M.getNamedValue(MF.getName())));
11477 CallPt = It;
11478 It++;
11479
11480 It = MBB.insert(It, Restore);
11481 return CallPt;
11482}
11483
11484bool AArch64InstrInfo::shouldOutlineFromFunctionByDefault(
11485 MachineFunction &MF) const {
11486 return MF.getFunction().hasMinSize();
11487}
11488
11489void AArch64InstrInfo::buildClearRegister(Register Reg, MachineBasicBlock &MBB,
11491 DebugLoc &DL,
11492 bool AllowSideEffects) const {
11493 const MachineFunction &MF = *MBB.getParent();
11494 const AArch64Subtarget &STI = MF.getSubtarget<AArch64Subtarget>();
11495 const AArch64RegisterInfo &TRI = *STI.getRegisterInfo();
11496
11497 if (TRI.isGeneralPurposeRegister(MF, Reg)) {
11498 BuildMI(MBB, Iter, DL, get(AArch64::MOVZXi), Reg).addImm(0).addImm(0);
11499 } else if (STI.isSVEorStreamingSVEAvailable()) {
11500 BuildMI(MBB, Iter, DL, get(AArch64::DUP_ZI_D), Reg)
11501 .addImm(0)
11502 .addImm(0);
11503 } else if (STI.isNeonAvailable()) {
11504 BuildMI(MBB, Iter, DL, get(AArch64::MOVIv2d_ns), Reg)
11505 .addImm(0);
11506 } else {
11507 // No Advanced SIMD (streaming-compatible without SVE, or +nosimd), so use
11508 // `fmov d...` instead of `movi v...`; writing `d` also clears the upper
11509 // 64 bits.
11510 assert(STI.hasFPARMv8() && "Expected FP to be available.");
11511 Register Reg64 = TRI.getSubReg(Reg, AArch64::dsub);
11512 BuildMI(MBB, Iter, DL, get(AArch64::FMOVD0), Reg64);
11513 }
11514}
11515
11516std::optional<DestSourcePair>
11518
11519 // AArch64::ORRWrs and AArch64::ORRXrs with WZR/XZR reg
11520 // and zero immediate operands used as an alias for mov instruction.
11521 if ((MI.getOpcode() == AArch64::ORRWrs &&
11522 MI.getOperand(1).getReg() == AArch64::WZR &&
11523 MI.getOperand(3).getImm() == 0x0) ||
11524 (MI.getOpcode() == AArch64::ORRWrr &&
11525 MI.getOperand(1).getReg() == AArch64::WZR)) {
11526 // Check that the w->w move is not a zero-extending w->x mov.
11527 if ((MI.getOperand(0).getReg().isPhysical() &&
11528 MI.findRegisterDefOperandIdx(
11529 getXRegFromWReg(MI.getOperand(0).getReg()),
11530 /*TRI=*/nullptr) == -1) ||
11531 (MI.getOperand(0).getReg().isVirtual() &&
11532 !MI.getOperand(0).getSubReg()))
11533 return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
11534 }
11535
11536 if (MI.getOpcode() == AArch64::ORRXrs &&
11537 MI.getOperand(1).getReg() == AArch64::XZR &&
11538 MI.getOperand(3).getImm() == 0x0)
11539 return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
11540
11541 return std::nullopt;
11542}
11543
11544std::optional<DestSourcePair>
11546 if ((MI.getOpcode() == AArch64::ORRWrs &&
11547 MI.getOperand(1).getReg() == AArch64::WZR &&
11548 MI.getOperand(3).getImm() == 0x0) ||
11549 (MI.getOpcode() == AArch64::ORRWrr &&
11550 MI.getOperand(1).getReg() == AArch64::WZR))
11551 return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
11552 return std::nullopt;
11553}
11554
11555std::optional<RegImmPair>
11556AArch64InstrInfo::isAddImmediate(const MachineInstr &MI, Register Reg) const {
11557 int Sign = 1;
11558 int64_t Offset = 0;
11559
11560 // TODO: Handle cases where Reg is a super- or sub-register of the
11561 // destination register.
11562 const MachineOperand &Op0 = MI.getOperand(0);
11563 if (!Op0.isReg() || Reg != Op0.getReg())
11564 return std::nullopt;
11565
11566 switch (MI.getOpcode()) {
11567 default:
11568 return std::nullopt;
11569 case AArch64::SUBWri:
11570 case AArch64::SUBXri:
11571 case AArch64::SUBSWri:
11572 case AArch64::SUBSXri:
11573 Sign *= -1;
11574 [[fallthrough]];
11575 case AArch64::ADDSWri:
11576 case AArch64::ADDSXri:
11577 case AArch64::ADDWri:
11578 case AArch64::ADDXri: {
11579 // TODO: Third operand can be global address (usually some string).
11580 if (!MI.getOperand(0).isReg() || !MI.getOperand(1).isReg() ||
11581 !MI.getOperand(2).isImm())
11582 return std::nullopt;
11583 int Shift = MI.getOperand(3).getImm();
11584 assert((Shift == 0 || Shift == 12) && "Shift can be either 0 or 12");
11585 Offset = Sign * (MI.getOperand(2).getImm() << Shift);
11586 }
11587 }
11588 return RegImmPair{MI.getOperand(1).getReg(), Offset};
11589}
11590
11591/// If the given ORR instruction is a copy, and \p DescribedReg overlaps with
11592/// the destination register then, if possible, describe the value in terms of
11593/// the source register.
11594static std::optional<ParamLoadedValue>
11596 const TargetInstrInfo *TII,
11597 const TargetRegisterInfo *TRI) {
11598 auto DestSrc = TII->isCopyLikeInstr(MI);
11599 if (!DestSrc)
11600 return std::nullopt;
11601
11602 Register DestReg = DestSrc->Destination->getReg();
11603 Register SrcReg = DestSrc->Source->getReg();
11604
11605 if (!DestReg.isValid() || !SrcReg.isValid())
11606 return std::nullopt;
11607
11608 auto Expr = DIExpression::get(MI.getMF()->getFunction().getContext(), {});
11609
11610 // If the described register is the destination, just return the source.
11611 if (DestReg == DescribedReg)
11612 return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
11613
11614 // ORRWrs zero-extends to 64-bits, so we need to consider such cases.
11615 if (MI.getOpcode() == AArch64::ORRWrs &&
11616 TRI->isSuperRegister(DestReg, DescribedReg))
11617 return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
11618
11619 // We may need to describe the lower part of a ORRXrs move.
11620 if (MI.getOpcode() == AArch64::ORRXrs &&
11621 TRI->isSubRegister(DestReg, DescribedReg)) {
11622 Register SrcSubReg = TRI->getSubReg(SrcReg, AArch64::sub_32);
11623 return ParamLoadedValue(MachineOperand::CreateReg(SrcSubReg, false), Expr);
11624 }
11625
11626 assert(!TRI->isSuperOrSubRegisterEq(DestReg, DescribedReg) &&
11627 "Unhandled ORR[XW]rs copy case");
11628
11629 return std::nullopt;
11630}
11631
11632bool AArch64InstrInfo::isFunctionSafeToSplit(const MachineFunction &MF) const {
11633 // Functions cannot be split to different sections on AArch64 if they have
11634 // a red zone. This is because relaxing a cross-section branch may require
11635 // incrementing the stack pointer to spill a register, which would overwrite
11636 // the red zone.
11637 if (MF.getInfo<AArch64FunctionInfo>()->hasRedZone().value_or(true))
11638 return false;
11639
11641}
11642
11643bool AArch64InstrInfo::isMBBSafeToSplitToCold(
11644 const MachineBasicBlock &MBB) const {
11645 // Asm Goto blocks can contain conditional branches to goto labels, which can
11646 // get moved out of range of the branch instruction.
11647 auto isAsmGoto = [](const MachineInstr &MI) {
11648 return MI.getOpcode() == AArch64::INLINEASM_BR;
11649 };
11650 if (llvm::any_of(MBB, isAsmGoto) || MBB.isInlineAsmBrIndirectTarget())
11651 return false;
11652
11653 // Because jump tables are label-relative instead of table-relative, they all
11654 // must be in the same section or relocation fixup handling will fail.
11655
11656 // Check if MBB is a jump table target
11657 const MachineJumpTableInfo *MJTI = MBB.getParent()->getJumpTableInfo();
11658 auto containsMBB = [&MBB](const MachineJumpTableEntry &JTE) {
11659 return llvm::is_contained(JTE.MBBs, &MBB);
11660 };
11661 if (MJTI != nullptr && llvm::any_of(MJTI->getJumpTables(), containsMBB))
11662 return false;
11663
11664 // Check if MBB contains a jump table lookup
11665 for (const MachineInstr &MI : MBB) {
11666 switch (MI.getOpcode()) {
11667 case TargetOpcode::G_BRJT:
11668 case AArch64::JumpTableDest32:
11669 case AArch64::JumpTableDest16:
11670 case AArch64::JumpTableDest8:
11671 return false;
11672 default:
11673 continue;
11674 }
11675 }
11676
11677 // MBB isn't a special case, so it's safe to be split to the cold section.
11678 return true;
11679}
11680
11681std::optional<ParamLoadedValue>
11682AArch64InstrInfo::describeLoadedValue(const MachineInstr &MI,
11683 Register Reg) const {
11684 const MachineFunction *MF = MI.getMF();
11685 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
11686 switch (MI.getOpcode()) {
11687 case AArch64::MOVZWi:
11688 case AArch64::MOVZXi: {
11689 // MOVZWi may be used for producing zero-extended 32-bit immediates in
11690 // 64-bit parameters, so we need to consider super-registers.
11691 if (!TRI->isSuperRegisterEq(MI.getOperand(0).getReg(), Reg))
11692 return std::nullopt;
11693
11694 if (!MI.getOperand(1).isImm())
11695 return std::nullopt;
11696 int64_t Immediate = MI.getOperand(1).getImm();
11697 int Shift = MI.getOperand(2).getImm();
11698 return ParamLoadedValue(MachineOperand::CreateImm(Immediate << Shift),
11699 nullptr);
11700 }
11701 case AArch64::ORRWrs:
11702 case AArch64::ORRXrs:
11703 return describeORRLoadedValue(MI, Reg, this, TRI);
11704 }
11705
11707}
11708
11709bool AArch64InstrInfo::isExtendLikelyToBeFolded(
11710 MachineInstr &ExtMI, MachineRegisterInfo &MRI) const {
11711 assert(ExtMI.getOpcode() == TargetOpcode::G_SEXT ||
11712 ExtMI.getOpcode() == TargetOpcode::G_ZEXT ||
11713 ExtMI.getOpcode() == TargetOpcode::G_ANYEXT);
11714
11715 // Anyexts are nops.
11716 if (ExtMI.getOpcode() == TargetOpcode::G_ANYEXT)
11717 return true;
11718
11719 Register DefReg = ExtMI.getOperand(0).getReg();
11720 if (!MRI.hasOneNonDBGUse(DefReg))
11721 return false;
11722
11723 // It's likely that a sext/zext as a G_PTR_ADD offset will be folded into an
11724 // addressing mode.
11725 auto *UserMI = &*MRI.use_instr_nodbg_begin(DefReg);
11726 return UserMI->getOpcode() == TargetOpcode::G_PTR_ADD;
11727}
11728
11729uint64_t AArch64InstrInfo::getElementSizeForOpcode(unsigned Opc) const {
11730 return get(Opc).TSFlags & AArch64::ElementSizeMask;
11731}
11732
11733bool AArch64InstrInfo::isPTestLikeOpcode(unsigned Opc) const {
11734 return get(Opc).TSFlags & AArch64::InstrFlagIsPTestLike;
11735}
11736
11737bool AArch64InstrInfo::isWhileOpcode(unsigned Opc) const {
11738 return get(Opc).TSFlags & AArch64::InstrFlagIsWhile;
11739}
11740
11741unsigned int
11742AArch64InstrInfo::getTailDuplicateSize(CodeGenOptLevel OptLevel) const {
11743 return OptLevel >= CodeGenOptLevel::Aggressive ? 6 : 2;
11744}
11745
11746bool AArch64InstrInfo::isLegalAddressingMode(unsigned NumBytes, int64_t Offset,
11747 unsigned Scale) const {
11748 if (Offset && Scale)
11749 return false;
11750
11751 // Check Reg + Imm
11752 if (!Scale) {
11753 // 9-bit signed offset
11754 if (isInt<9>(Offset))
11755 return true;
11756
11757 // 12-bit unsigned offset
11758 unsigned Shift = Log2_64(NumBytes);
11759 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
11760 // Must be a multiple of NumBytes (NumBytes is a power of 2)
11761 (Offset >> Shift) << Shift == Offset)
11762 return true;
11763 return false;
11764 }
11765
11766 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
11767 return Scale == 1 || (Scale > 0 && Scale == NumBytes);
11768}
11769
11771 if (MF.getSubtarget<AArch64Subtarget>().hardenSlsBlr())
11772 return AArch64::BLRNoIP;
11773 else
11774 return AArch64::BLR;
11775}
11776
11778 DebugLoc DL) const {
11779 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
11780 auto Builder = BuildMI(MBB, InsertPt, DL, get(AArch64::PAUTH_EPILOGUE))
11782
11783 MachineFunction &MF = *MBB.getParent();
11784 const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
11785 auto &AFL = *static_cast<const AArch64FrameLowering *>(
11786 MF.getSubtarget().getFrameLowering());
11787 if (AFL.getArgumentStackToRestore(MF, MBB)) {
11788 Builder.addReg(AArch64::X17, RegState::ImplicitDefine);
11789 Builder.addReg(AArch64::X16, RegState::ImplicitDefine);
11790 if (AFI->branchProtectionPAuthLR())
11791 Builder.addReg(AArch64::X15, RegState::ImplicitDefine);
11792 return;
11793 }
11794
11795 if (AFI->branchProtectionPAuthLR() && !Subtarget.hasPAuthLR())
11796 Builder.addReg(AArch64::X16, RegState::ImplicitDefine);
11797}
11798
11800AArch64InstrInfo::probedStackAlloc(MachineBasicBlock::iterator MBBI,
11801 Register TargetReg, bool FrameSetup) const {
11802 assert(TargetReg != AArch64::SP && "New top of stack cannot already be in SP");
11803
11804 MachineBasicBlock &MBB = *MBBI->getParent();
11805 MachineFunction &MF = *MBB.getParent();
11806 const AArch64InstrInfo *TII =
11807 MF.getSubtarget<AArch64Subtarget>().getInstrInfo();
11808 int64_t ProbeSize = MF.getInfo<AArch64FunctionInfo>()->getStackProbeSize();
11809 DebugLoc DL = MBB.findDebugLoc(MBBI);
11810
11811 MachineFunction::iterator MBBInsertPoint = std::next(MBB.getIterator());
11812 MachineBasicBlock *LoopTestMBB =
11813 MF.CreateMachineBasicBlock(MBB.getBasicBlock());
11814 MF.insert(MBBInsertPoint, LoopTestMBB);
11815 MachineBasicBlock *LoopBodyMBB =
11816 MF.CreateMachineBasicBlock(MBB.getBasicBlock());
11817 MF.insert(MBBInsertPoint, LoopBodyMBB);
11818 MachineBasicBlock *ExitMBB = MF.CreateMachineBasicBlock(MBB.getBasicBlock());
11819 MF.insert(MBBInsertPoint, ExitMBB);
11820 MachineInstr::MIFlag Flags =
11822
11823 // LoopTest:
11824 // SUB SP, SP, #ProbeSize
11825 emitFrameOffset(*LoopTestMBB, LoopTestMBB->end(), DL, AArch64::SP,
11826 AArch64::SP, StackOffset::getFixed(-ProbeSize), TII, Flags);
11827
11828 // CMP SP, TargetReg
11829 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(AArch64::SUBSXrx64),
11830 AArch64::XZR)
11831 .addReg(AArch64::SP)
11832 .addReg(TargetReg)
11834 .setMIFlags(Flags);
11835
11836 // B.<Cond> LoopExit
11837 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(AArch64::Bcc))
11839 .addMBB(ExitMBB)
11840 .setMIFlags(Flags);
11841
11842 // LDR XZR, [SP]
11843 BuildMI(*LoopBodyMBB, LoopBodyMBB->end(), DL, TII->get(AArch64::LDRXui))
11844 .addDef(AArch64::XZR)
11845 .addReg(AArch64::SP)
11846 .addImm(0)
11850 Align(8)))
11851 .setMIFlags(Flags);
11852
11853 // B loop
11854 BuildMI(*LoopBodyMBB, LoopBodyMBB->end(), DL, TII->get(AArch64::B))
11855 .addMBB(LoopTestMBB)
11856 .setMIFlags(Flags);
11857
11858 // LoopExit:
11859 // MOV SP, TargetReg
11860 BuildMI(*ExitMBB, ExitMBB->end(), DL, TII->get(AArch64::ADDXri), AArch64::SP)
11861 .addReg(TargetReg)
11862 .addImm(0)
11864 .setMIFlags(Flags);
11865
11866 // LDR XZR, [SP]
11867 BuildMI(*ExitMBB, ExitMBB->end(), DL, TII->get(AArch64::LDRXui))
11868 .addReg(AArch64::XZR, RegState::Define)
11869 .addReg(AArch64::SP)
11870 .addImm(0)
11871 .setMIFlags(Flags);
11872
11873 ExitMBB->splice(ExitMBB->end(), &MBB, std::next(MBBI), MBB.end());
11875
11876 LoopTestMBB->addSuccessor(ExitMBB);
11877 LoopTestMBB->addSuccessor(LoopBodyMBB);
11878 LoopBodyMBB->addSuccessor(LoopTestMBB);
11879 MBB.addSuccessor(LoopTestMBB);
11880
11881 // Update liveins.
11882 if (MF.getRegInfo().reservedRegsFrozen())
11883 fullyRecomputeLiveIns({ExitMBB, LoopBodyMBB, LoopTestMBB});
11884
11885 return ExitMBB->begin();
11886}
11887
11888namespace {
11889class AArch64PipelinerLoopInfo : public TargetInstrInfo::PipelinerLoopInfo {
11890 MachineFunction *MF;
11891 const TargetInstrInfo *TII;
11892 const TargetRegisterInfo *TRI;
11893 MachineRegisterInfo &MRI;
11894
11895 /// The block of the loop
11896 MachineBasicBlock *LoopBB;
11897 /// The conditional branch of the loop
11898 MachineInstr *CondBranch;
11899 /// The compare instruction for loop control
11900 MachineInstr *Comp;
11901 /// The number of the operand of the loop counter value in Comp
11902 unsigned CompCounterOprNum;
11903 /// The instruction that updates the loop counter value
11904 MachineInstr *Update;
11905 /// The number of the operand of the loop counter value in Update
11906 unsigned UpdateCounterOprNum;
11907 /// The initial value of the loop counter
11908 Register Init;
11909 /// True iff Update is a predecessor of Comp
11910 bool IsUpdatePriorComp;
11911
11912 /// The normalized condition used by createTripCountGreaterCondition()
11914
11915public:
11916 AArch64PipelinerLoopInfo(MachineBasicBlock *LoopBB, MachineInstr *CondBranch,
11917 MachineInstr *Comp, unsigned CompCounterOprNum,
11918 MachineInstr *Update, unsigned UpdateCounterOprNum,
11919 Register Init, bool IsUpdatePriorComp,
11920 const SmallVectorImpl<MachineOperand> &Cond)
11921 : MF(Comp->getParent()->getParent()),
11922 TII(MF->getSubtarget().getInstrInfo()),
11923 TRI(MF->getSubtarget().getRegisterInfo()), MRI(MF->getRegInfo()),
11924 LoopBB(LoopBB), CondBranch(CondBranch), Comp(Comp),
11925 CompCounterOprNum(CompCounterOprNum), Update(Update),
11926 UpdateCounterOprNum(UpdateCounterOprNum), Init(Init),
11927 IsUpdatePriorComp(IsUpdatePriorComp), Cond(Cond.begin(), Cond.end()) {}
11928
11929 bool shouldIgnoreForPipelining(const MachineInstr *MI) const override {
11930 // Make the instructions for loop control be placed in stage 0.
11931 // The predecessors of Comp are considered by the caller.
11932 return MI == Comp;
11933 }
11934
11935 std::optional<bool> createTripCountGreaterCondition(
11936 int TC, MachineBasicBlock &MBB,
11937 SmallVectorImpl<MachineOperand> &CondParam) override {
11938 // A branch instruction will be inserted as "if (Cond) goto epilogue".
11939 // Cond is normalized for such use.
11940 // The predecessors of the branch are assumed to have already been inserted.
11941 CondParam = Cond;
11942 return {};
11943 }
11944
11945 void createRemainingIterationsGreaterCondition(
11946 int TC, MachineBasicBlock &MBB, SmallVectorImpl<MachineOperand> &Cond,
11947 DenseMap<MachineInstr *, MachineInstr *> &LastStage0Insts) override;
11948
11949 void setPreheader(MachineBasicBlock *NewPreheader) override {}
11950
11951 void adjustTripCount(int TripCountAdjust) override {}
11952
11953 bool isMVEExpanderSupported() override { return true; }
11954};
11955} // namespace
11956
11957/// Clone an instruction from MI. The register of ReplaceOprNum-th operand
11958/// is replaced by ReplaceReg. The output register is newly created.
11959/// The other operands are unchanged from MI.
11960static Register cloneInstr(const MachineInstr *MI, unsigned ReplaceOprNum,
11961 Register ReplaceReg, MachineBasicBlock &MBB,
11962 MachineBasicBlock::iterator InsertTo) {
11963 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
11964 const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
11965 MachineInstr *NewMI = MBB.getParent()->CloneMachineInstr(MI);
11966 Register Result = 0;
11967 for (unsigned I = 0; I < NewMI->getNumOperands(); ++I) {
11968 if (I == 0 && NewMI->getOperand(0).getReg().isVirtual()) {
11969 Result = MRI.createVirtualRegister(
11970 MRI.getRegClass(NewMI->getOperand(0).getReg()));
11971 NewMI->getOperand(I).setReg(Result);
11972 } else if (I == ReplaceOprNum) {
11973 MRI.constrainRegClass(ReplaceReg, TII->getRegClass(NewMI->getDesc(), I));
11974 NewMI->getOperand(I).setReg(ReplaceReg);
11975 }
11976 }
11977 MBB.insert(InsertTo, NewMI);
11978 return Result;
11979}
11980
11981void AArch64PipelinerLoopInfo::createRemainingIterationsGreaterCondition(
11984 // Create and accumulate conditions for next TC iterations.
11985 // Example:
11986 // SUBSXrr N, counter, implicit-def $nzcv # compare instruction for the last
11987 // # iteration of the kernel
11988 //
11989 // # insert the following instructions
11990 // cond = CSINCXr 0, 0, C, implicit $nzcv
11991 // counter = ADDXri counter, 1 # clone from this->Update
11992 // SUBSXrr n, counter, implicit-def $nzcv # clone from this->Comp
11993 // cond = CSINCXr cond, cond, C, implicit $nzcv
11994 // ... (repeat TC times)
11995 // SUBSXri cond, 0, implicit-def $nzcv
11996
11997 assert(CondBranch->getOpcode() == AArch64::Bcc);
11998 // CondCode to exit the loop
12000 (AArch64CC::CondCode)CondBranch->getOperand(0).getImm();
12001 if (CondBranch->getOperand(1).getMBB() == LoopBB)
12003
12004 // Accumulate conditions to exit the loop
12005 Register AccCond = AArch64::XZR;
12006
12007 // If CC holds, CurCond+1 is returned; otherwise CurCond is returned.
12008 auto AccumulateCond = [&](Register CurCond,
12010 Register NewCond = MRI.createVirtualRegister(&AArch64::GPR64commonRegClass);
12011 BuildMI(MBB, MBB.end(), Comp->getDebugLoc(), TII->get(AArch64::CSINCXr))
12012 .addReg(NewCond, RegState::Define)
12013 .addReg(CurCond)
12014 .addReg(CurCond)
12016 return NewCond;
12017 };
12018
12019 if (!LastStage0Insts.empty() && LastStage0Insts[Comp]->getParent() == &MBB) {
12020 // Update and Comp for I==0 are already exists in MBB
12021 // (MBB is an unrolled kernel)
12022 Register Counter;
12023 for (int I = 0; I <= TC; ++I) {
12024 Register NextCounter;
12025 if (I != 0)
12026 NextCounter =
12027 cloneInstr(Comp, CompCounterOprNum, Counter, MBB, MBB.end());
12028
12029 AccCond = AccumulateCond(AccCond, CC);
12030
12031 if (I != TC) {
12032 if (I == 0) {
12033 if (Update != Comp && IsUpdatePriorComp) {
12034 Counter =
12035 LastStage0Insts[Comp]->getOperand(CompCounterOprNum).getReg();
12036 NextCounter = cloneInstr(Update, UpdateCounterOprNum, Counter, MBB,
12037 MBB.end());
12038 } else {
12039 // can use already calculated value
12040 NextCounter = LastStage0Insts[Update]->getOperand(0).getReg();
12041 }
12042 } else if (Update != Comp) {
12043 NextCounter =
12044 cloneInstr(Update, UpdateCounterOprNum, Counter, MBB, MBB.end());
12045 }
12046 }
12047 Counter = NextCounter;
12048 }
12049 } else {
12050 Register Counter;
12051 if (LastStage0Insts.empty()) {
12052 // use initial counter value (testing if the trip count is sufficient to
12053 // be executed by pipelined code)
12054 Counter = Init;
12055 if (IsUpdatePriorComp)
12056 Counter =
12057 cloneInstr(Update, UpdateCounterOprNum, Counter, MBB, MBB.end());
12058 } else {
12059 // MBB is an epilogue block. LastStage0Insts[Comp] is in the kernel block.
12060 Counter = LastStage0Insts[Comp]->getOperand(CompCounterOprNum).getReg();
12061 }
12062
12063 for (int I = 0; I <= TC; ++I) {
12064 Register NextCounter;
12065 NextCounter =
12066 cloneInstr(Comp, CompCounterOprNum, Counter, MBB, MBB.end());
12067 AccCond = AccumulateCond(AccCond, CC);
12068 if (I != TC && Update != Comp)
12069 NextCounter =
12070 cloneInstr(Update, UpdateCounterOprNum, Counter, MBB, MBB.end());
12071 Counter = NextCounter;
12072 }
12073 }
12074
12075 // If AccCond == 0, the remainder is greater than TC.
12076 BuildMI(MBB, MBB.end(), Comp->getDebugLoc(), TII->get(AArch64::SUBSXri))
12077 .addReg(AArch64::XZR, RegState::Define | RegState::Dead)
12078 .addReg(AccCond)
12079 .addImm(0)
12080 .addImm(0);
12081 Cond.clear();
12083}
12084
12085static void extractPhiReg(const MachineInstr &Phi, const MachineBasicBlock *MBB,
12086 Register &RegMBB, Register &RegOther) {
12087 assert(Phi.getNumOperands() == 5);
12088 if (Phi.getOperand(2).getMBB() == MBB) {
12089 RegMBB = Phi.getOperand(1).getReg();
12090 RegOther = Phi.getOperand(3).getReg();
12091 } else {
12092 assert(Phi.getOperand(4).getMBB() == MBB);
12093 RegMBB = Phi.getOperand(3).getReg();
12094 RegOther = Phi.getOperand(1).getReg();
12095 }
12096}
12097
12099 if (!Reg.isVirtual())
12100 return false;
12101 const MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
12102 return MRI.getDefBlock(Reg) != BB;
12103}
12104
12105/// If Reg is an induction variable, return true and set some parameters
12106static bool getIndVarInfo(Register Reg, const MachineBasicBlock *LoopBB,
12107 MachineInstr *&UpdateInst,
12108 unsigned &UpdateCounterOprNum, Register &InitReg,
12109 bool &IsUpdatePriorComp) {
12110 // Example:
12111 //
12112 // Preheader:
12113 // InitReg = ...
12114 // LoopBB:
12115 // Reg0 = PHI (InitReg, Preheader), (Reg1, LoopBB)
12116 // Reg = COPY Reg0 ; COPY is ignored.
12117 // Reg1 = ADD Reg, #1; UpdateInst. Incremented by a loop invariant value.
12118 // ; Reg is the value calculated in the previous
12119 // ; iteration, so IsUpdatePriorComp == false.
12120
12121 if (LoopBB->pred_size() != 2)
12122 return false;
12123 if (!Reg.isVirtual())
12124 return false;
12125 const MachineRegisterInfo &MRI = LoopBB->getParent()->getRegInfo();
12126 UpdateInst = nullptr;
12127 UpdateCounterOprNum = 0;
12128 InitReg = 0;
12129 IsUpdatePriorComp = true;
12130 Register CurReg = Reg;
12131 while (true) {
12132 MachineInstr *Def = MRI.getVRegDef(CurReg);
12133 if (Def->getParent() != LoopBB)
12134 return false;
12135 if (Def->isCopy()) {
12136 // Ignore copy instructions unless they contain subregisters
12137 if (Def->getOperand(0).getSubReg() || Def->getOperand(1).getSubReg())
12138 return false;
12139 CurReg = Def->getOperand(1).getReg();
12140 } else if (Def->isPHI()) {
12141 if (InitReg != 0)
12142 return false;
12143 if (!UpdateInst)
12144 IsUpdatePriorComp = false;
12145 extractPhiReg(*Def, LoopBB, CurReg, InitReg);
12146 } else {
12147 if (UpdateInst)
12148 return false;
12149 switch (Def->getOpcode()) {
12150 case AArch64::ADDSXri:
12151 case AArch64::ADDSWri:
12152 case AArch64::SUBSXri:
12153 case AArch64::SUBSWri:
12154 case AArch64::ADDXri:
12155 case AArch64::ADDWri:
12156 case AArch64::SUBXri:
12157 case AArch64::SUBWri:
12158 UpdateInst = Def;
12159 UpdateCounterOprNum = 1;
12160 break;
12161 case AArch64::ADDSXrr:
12162 case AArch64::ADDSWrr:
12163 case AArch64::SUBSXrr:
12164 case AArch64::SUBSWrr:
12165 case AArch64::ADDXrr:
12166 case AArch64::ADDWrr:
12167 case AArch64::SUBXrr:
12168 case AArch64::SUBWrr:
12169 UpdateInst = Def;
12170 if (isDefinedOutside(Def->getOperand(2).getReg(), LoopBB))
12171 UpdateCounterOprNum = 1;
12172 else if (isDefinedOutside(Def->getOperand(1).getReg(), LoopBB))
12173 UpdateCounterOprNum = 2;
12174 else
12175 return false;
12176 break;
12177 default:
12178 return false;
12179 }
12180 CurReg = Def->getOperand(UpdateCounterOprNum).getReg();
12181 }
12182
12183 if (!CurReg.isVirtual())
12184 return false;
12185 if (Reg == CurReg)
12186 break;
12187 }
12188
12189 if (!UpdateInst)
12190 return false;
12191
12192 return true;
12193}
12194
12195std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo>
12197 // Accept loops that meet the following conditions
12198 // * The conditional branch is BCC
12199 // * The compare instruction is ADDS/SUBS/WHILEXX
12200 // * One operand of the compare is an induction variable and the other is a
12201 // loop invariant value
12202 // * The induction variable is incremented/decremented by a single instruction
12203 // * Does not contain CALL or instructions which have unmodeled side effects
12204
12205 for (MachineInstr &MI : *LoopBB)
12206 if (MI.isCall() || MI.hasUnmodeledSideEffects())
12207 // This instruction may use NZCV, which interferes with the instruction to
12208 // be inserted for loop control.
12209 return nullptr;
12210
12211 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
12213 if (analyzeBranch(*LoopBB, TBB, FBB, Cond))
12214 return nullptr;
12215
12216 // Infinite loops are not supported
12217 if (TBB == LoopBB && FBB == LoopBB)
12218 return nullptr;
12219
12220 // Must be conditional branch
12221 if (TBB != LoopBB && FBB == nullptr)
12222 return nullptr;
12223
12224 assert((TBB == LoopBB || FBB == LoopBB) &&
12225 "The Loop must be a single-basic-block loop");
12226
12227 MachineInstr *CondBranch = &*LoopBB->getFirstTerminator();
12229
12230 if (CondBranch->getOpcode() != AArch64::Bcc)
12231 return nullptr;
12232
12233 // Normalization for createTripCountGreaterCondition()
12234 if (TBB == LoopBB)
12236
12237 MachineInstr *Comp = nullptr;
12238 unsigned CompCounterOprNum = 0;
12239 for (MachineInstr &MI : reverse(*LoopBB)) {
12240 if (MI.modifiesRegister(AArch64::NZCV, &TRI)) {
12241 // Guarantee that the compare is SUBS/ADDS/WHILEXX and that one of the
12242 // operands is a loop invariant value
12243
12244 switch (MI.getOpcode()) {
12245 case AArch64::SUBSXri:
12246 case AArch64::SUBSWri:
12247 case AArch64::ADDSXri:
12248 case AArch64::ADDSWri:
12249 Comp = &MI;
12250 CompCounterOprNum = 1;
12251 break;
12252 case AArch64::ADDSWrr:
12253 case AArch64::ADDSXrr:
12254 case AArch64::SUBSWrr:
12255 case AArch64::SUBSXrr:
12256 Comp = &MI;
12257 break;
12258 default:
12259 if (isWhileOpcode(MI.getOpcode())) {
12260 Comp = &MI;
12261 break;
12262 }
12263 return nullptr;
12264 }
12265
12266 if (CompCounterOprNum == 0) {
12267 if (isDefinedOutside(Comp->getOperand(1).getReg(), LoopBB))
12268 CompCounterOprNum = 2;
12269 else if (isDefinedOutside(Comp->getOperand(2).getReg(), LoopBB))
12270 CompCounterOprNum = 1;
12271 else
12272 return nullptr;
12273 }
12274 break;
12275 }
12276 }
12277 if (!Comp)
12278 return nullptr;
12279
12280 MachineInstr *Update = nullptr;
12281 Register Init;
12282 bool IsUpdatePriorComp;
12283 unsigned UpdateCounterOprNum;
12284 if (!getIndVarInfo(Comp->getOperand(CompCounterOprNum).getReg(), LoopBB,
12285 Update, UpdateCounterOprNum, Init, IsUpdatePriorComp))
12286 return nullptr;
12287
12288 return std::make_unique<AArch64PipelinerLoopInfo>(
12289 LoopBB, CondBranch, Comp, CompCounterOprNum, Update, UpdateCounterOprNum,
12290 Init, IsUpdatePriorComp, Cond);
12291}
12292
12293/// verifyInstruction - Perform target specific instruction verification.
12294bool AArch64InstrInfo::verifyInstruction(const MachineInstr &MI,
12295 StringRef &ErrInfo) const {
12296 // Verify that immediate offsets on load/store instructions are within range.
12297 // Stack objects with an FI operand are excluded as they can be fixed up
12298 // during PEI.
12299 TypeSize Scale(0U, false), Width(0U, false);
12300 int64_t MinOffset, MaxOffset;
12301 if (getMemOpInfo(MI.getOpcode(), Scale, Width, MinOffset, MaxOffset)) {
12302 unsigned ImmIdx = getLoadStoreImmIdx(MI.getOpcode());
12303 if (MI.getOperand(ImmIdx).isImm() && !MI.getOperand(ImmIdx - 1).isFI()) {
12304 int64_t Imm = MI.getOperand(ImmIdx).getImm();
12305 if (Imm < MinOffset || Imm > MaxOffset) {
12306 ErrInfo = "Unexpected immediate on load/store instruction";
12307 return false;
12308 }
12309 }
12310 }
12311
12312 const MCInstrDesc &MCID = MI.getDesc();
12313 for (unsigned Op = 0; Op < MCID.getNumOperands(); Op++) {
12314 const MachineOperand &MO = MI.getOperand(Op);
12315 switch (MCID.operands()[Op].OperandType) {
12317 if (!MO.isImm() || MO.getImm() != 0) {
12318 ErrInfo = "OPERAND_IMPLICIT_IMM_0 should be 0";
12319 return false;
12320 }
12321 break;
12323 if (!MO.isImm() ||
12325 (AArch64_AM::getShiftValue(MO.getImm()) != 8 &&
12326 AArch64_AM::getShiftValue(MO.getImm()) != 16)) {
12327 ErrInfo = "OPERAND_SHIFT_MSL should be msl shift of 8 or 16";
12328 return false;
12329 }
12330 break;
12332 if (!MO.isImm() || (MO.getImm() != 0 && MO.getImm() != 1)) {
12333 ErrInfo = "OPERAND_IMM_UINT1 should be 0 or 1";
12334 return false;
12335 }
12336 break;
12338 if (!MO.isImm() || MO.getImm() <= 0 || MO.getImm() > 16) {
12339 ErrInfo = "OPERAND_IMM_UINT4plus1 should be in the range 1 to 16";
12340 return false;
12341 }
12342 break;
12344 if (!MO.isImm() || !isUInt<5>(MO.getImm())) {
12345 ErrInfo = "OPERAND_IMM_UINT5 should be in the range 0 to 31";
12346 return false;
12347 }
12348 break;
12350 if (!MO.isImm() || !isUInt<8>(MO.getImm())) {
12351 ErrInfo = "OPERAND_IMM_UINT8 should be in the range 0 to 255";
12352 return false;
12353 }
12354 break;
12355 default:
12356 break;
12357 }
12358 }
12359 return true;
12360}
12361
12362#define GET_INSTRINFO_HELPERS
12363#define GET_INSTRMAP_INFO
12364#include "AArch64GenInstrInfo.inc"
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
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 bool predictCompactUnwindFrameRecordForOutlinedFunction(std::vector< outliner::Candidate > &RepeatedSequenceLocs, const TargetRegisterInfo &TRI)
Predict what the above will answer, for use while costing candidates.
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 cl::opt< bool > UseCompactUnwindFrameRecordForOutlinedFunctions("aarch64-outliner-compact-unwind-frame", cl::Hidden, cl::init(true), cl::desc("Use a frame record for Mach-O non-leaf outlined functions"))
static bool shouldUseCompactUnwindFrameRecordForOutlinedFunction(const MachineBasicBlock &MBB)
Return true if the outlined function in MBB should save FP and LR as a frame record instead of saving...
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 bool isCompactUnwindFrameRecordEnabled(const MachineFunction &MF)
Return true if the frame-record form of the outlined prologue is enabled for the target of MF.
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!")
unsigned Imm
unsigned uint64_t
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static const Function * getParent(const Value *V)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< 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.
A set of register units.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
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)
bool needsDwarfUnwindInfo(const MachineFunction &MF) const
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 copyPhysRegImpl(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register DestReg, Register SrcReg, bool KillSrc, bool RenamableDest=false, bool RenamableSrc=false) const
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
void copyPhysRegTuple(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, MCRegister DestReg, MCRegister SrcReg, bool KillSrc, llvm::ArrayRef< unsigned > Indices) const
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
AArch64CC::CondCode insertCmpForCondBr(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL, ArrayRef< MachineOperand > Cond) const
Inserts the compare instruction needed to un-fuse a fused conditional branch instruction and returns ...
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.
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:699
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:696
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.
A set of register units used to track register liveness.
bool available(MCRegister Reg) const
Returns true if no part of physical register Reg is live.
LLVM_ABI void accumulate(const MachineInstr &MI)
Adds all register units used, defined or clobbered in MI.
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:67
bool usesWindowsCFI() const
Definition MCAsmInfo.h:675
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:628
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:670
static MCCFIInstruction cfiDefCfaOffset(MCSymbol *L, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa_offset modifies a rule for computing CFA.
Definition MCDwarf.h:643
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:756
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:1567
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.
iterator insertAfter(iterator I, MachineInstr *MI)
Insert MI into the instruction list after I.
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.
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...
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
const 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 LLVM_READONLY 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.
MachineBasicBlock * getDefBlock(Register Reg) const
Return the machine basic block in which the specified virtual register is defined,...
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...
use_instr_nodbg_iterator use_instr_nodbg_begin(Register RegNo) const
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 LLVM_READONLY 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:68
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 Triple & getTargetTriple() const
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.
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Definition Triple.h:874
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.
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:389
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:577
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:166
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:285
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:332
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.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
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:190
std::optional< UsedNZCV > examineCFlagsUse(MachineInstr &MI, MachineInstr &CmpInstr, const TargetRegisterInfo &TRI, SmallVectorImpl< MachineInstr * > *CCUseInstrs=nullptr)
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:149
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
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
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:249
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:567
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 ...
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.