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"
55#include "llvm/Support/LEB128.h"
59#include <cassert>
60#include <cstdint>
61#include <iterator>
62#include <utility>
63
64using namespace llvm;
65
66#define GET_INSTRINFO_CTOR_DTOR
67#include "AArch64GenInstrInfo.inc"
68
69#define DEBUG_TYPE "AArch64InstrInfo"
70
71STATISTIC(NumCopyInstrs, "Number of COPY instructions expanded");
72STATISTIC(NumZCRegMoveInstrsGPR, "Number of zero-cycle GPR register move "
73 "instructions expanded from canonical COPY");
74STATISTIC(NumZCRegMoveInstrsFPR, "Number of zero-cycle FPR register move "
75 "instructions expanded from canonical COPY");
76STATISTIC(NumZCZeroingInstrsGPR, "Number of zero-cycle GPR zeroing "
77 "instructions expanded from canonical COPY");
78// NumZCZeroingInstrsFPR is counted at AArch64AsmPrinter
79
81 : AArch64GenInstrInfo(STI, RI, AArch64::ADJCALLSTACKDOWN,
82 AArch64::ADJCALLSTACKUP, AArch64::CATCHRET),
83 RI(STI.getTargetTriple(), STI.getHwMode()), Subtarget(STI) {}
84
85/// Return the maximum number of bytes of code the specified instruction may be
86/// after LFI rewriting. If the instruction is not rewritten, std::nullopt is
87/// returned (use default sizing).
88///
89/// NOTE: the size estimates here must be kept in sync with the rewrites in
90/// AArch64MCLFIRewriter.cpp. Sizes may be overestimates of the rewritten
91/// instruction sequences.
92static std::optional<unsigned> getLFIInstSizeInBytes(const MachineInstr &MI) {
93 switch (MI.getOpcode()) {
94 case AArch64::SVC:
95 // SVC expands to 4 instructions.
96 return 16;
97 case AArch64::BR:
98 case AArch64::BLR:
99 // Indirect branches/calls expand to 2 instructions (guard + br/blr).
100 return 8;
101 case AArch64::RET:
102 // RET through another register expands to 2 instructions (guard + ret).
103 // RET through LR may also expand to 2 instructions if a deferred LR guard
104 // is flushed before the return.
105 return 8;
106 case AArch64::RETAA:
107 case AArch64::RETAB:
108 // Authenticated returns expand to 3 instructions (authenticate + guard +
109 // ret).
110 return 12;
111 case AArch64::BRAA:
112 case AArch64::BRAAZ:
113 case AArch64::BRAB:
114 case AArch64::BRABZ:
115 case AArch64::BLRAA:
116 case AArch64::BLRAAZ:
117 case AArch64::BLRAB:
118 case AArch64::BLRABZ:
119 // Authenticated branches/calls expand to 3 instructions (authenticate +
120 // guard + branch).
121 return 12;
122 case AArch64::AUTIASP:
123 case AArch64::AUTIBSP:
124 case AArch64::AUTIAZ:
125 case AArch64::AUTIBZ:
126 case AArch64::XPACLRI:
127 // Authenticating LR expands to the instruction plus a deferred LR guard.
128 return 8;
129 case AArch64::SYSxt:
130 // VA-based DC/IC ops (op1=3, Cn=7, op2=1) expand to 2 instructions.
131 if (MI.getOperand(0).getImm() == 3 && MI.getOperand(1).getImm() == 7 &&
132 MI.getOperand(3).getImm() == 1)
133 return 8;
134 return std::nullopt;
135 default:
136 break;
137 }
138
139 // Detect instructions that explicitly define SP or LR.
140 bool ModifiesLR = false;
141 bool ModifiesSP = false;
142 for (const MachineOperand &MO : MI.defs()) {
143 if (!MO.isReg())
144 continue;
145 if (MO.getReg() == AArch64::LR)
146 ModifiesLR = true;
147 else if (MO.getReg() == AArch64::SP)
148 ModifiesSP = true;
149 }
150
151 // Memory accesses expand to a base-register guard plus the rewritten access
152 // (8 bytes), with an extra base-register update for pre/post-index forms (12
153 // bytes total). If the access also defines LR, an LR mask is appended (+4
154 // bytes). Depending on additional optimizations that the rewriter performs,
155 // this may be an overestimate.
156 if (MI.mayLoadOrStore()) {
157 unsigned Size = isLFIPrePostMemAccess(MI.getOpcode()) ? 12 : 8;
158 if (ModifiesLR)
159 Size += 4;
160 return Size;
161 }
162
163 // Non memory operations that modify LR or SP expand to 2 instructions.
164 if (ModifiesSP || ModifiesLR)
165 return 8;
166
167 // Default case: instructions that don't cause expansion.
168 // - TP accesses in LFI are a single load/store, so no expansion.
169 // - All remaining instructions are not rewritten.
170 return std::nullopt;
171}
172
173/// GetInstSize - Return the number of bytes of code the specified
174/// instruction may be. This returns the maximum number of bytes.
176 const MCInstrDesc &Desc = MI.getDesc();
177 if (!Desc.isPseudo() && !Subtarget.isLFI()) {
178 assert(Desc.getSize() == 4 && "Unexpected instruction size");
179 return 4;
180 }
181
182 const MachineBasicBlock &MBB = *MI.getParent();
183 const MachineFunction *MF = MBB.getParent();
184 const Function &F = MF->getFunction();
185 const MCAsmInfo &MAI = MF->getTarget().getMCAsmInfo();
186
187 {
188 auto Op = MI.getOpcode();
189 if (Op == AArch64::INLINEASM || Op == AArch64::INLINEASM_BR)
190 return getInlineAsmLength(MI.getOperand(0).getSymbolName(), MAI);
191 }
192
193 // Meta-instructions emit no code.
194 if (MI.isMetaInstruction())
195 return 0;
196
197 // FIXME: We currently only handle pseudoinstructions that don't get expanded
198 // before the assembly printer.
199 unsigned NumBytes = 0;
200
201 // LFI rewriter expansions that supersede normal sizing.
202 const auto &STI = MF->getSubtarget<AArch64Subtarget>();
203 if (STI.isLFI())
204 if (auto Size = getLFIInstSizeInBytes(MI))
205 return *Size;
206
207 if (!MI.isBundle() && isTailCallReturnInst(MI)) {
208 NumBytes = Desc.getSize() ? Desc.getSize() : 4;
209
210 const auto *MFI = MF->getInfo<AArch64FunctionInfo>();
211 if (!MFI->shouldSignReturnAddress(*MF))
212 return NumBytes;
213
214 auto Method = STI.getAuthenticatedLRCheckMethod(*MF);
215 NumBytes += AArch64PAuth::getCheckerSizeInBytes(Method);
216 return NumBytes;
217 }
218
219 // Size should be preferably set in
220 // llvm/lib/Target/AArch64/AArch64InstrInfo.td (default case).
221 // Specific cases handle instructions of variable sizes
222 switch (Desc.getOpcode()) {
223 default:
224 if (Desc.getSize())
225 return Desc.getSize();
226
227 // Anything not explicitly designated otherwise (i.e. pseudo-instructions
228 // with fixed constant size but not specified in .td file) is a normal
229 // 4-byte insn.
230 NumBytes = 4;
231 break;
232 case TargetOpcode::STACKMAP:
233 // The upper bound for a stackmap intrinsic is the full length of its shadow
234 NumBytes = StackMapOpers(&MI).getNumPatchBytes();
235 assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
236 break;
237 case TargetOpcode::PATCHPOINT:
238 // The size of the patchpoint intrinsic is the number of bytes requested
239 NumBytes = PatchPointOpers(&MI).getNumPatchBytes();
240 assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
241 break;
242 case TargetOpcode::STATEPOINT:
243 NumBytes = StatepointOpers(&MI).getNumPatchBytes();
244 assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
245 // No patch bytes means a normal call inst is emitted
246 if (NumBytes == 0)
247 NumBytes = 4;
248 break;
249 case TargetOpcode::PATCHABLE_FUNCTION_ENTER:
250 // If `patchable-function-entry` is set, PATCHABLE_FUNCTION_ENTER
251 // instructions are expanded to the specified number of NOPs. Otherwise,
252 // they are expanded to 36-byte XRay sleds.
253 NumBytes =
254 F.getFnAttributeAsParsedInteger("patchable-function-entry", 9) * 4;
255 break;
256 case TargetOpcode::PATCHABLE_FUNCTION_EXIT:
257 case TargetOpcode::PATCHABLE_TAIL_CALL:
258 case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
259 // An XRay sled can be 4 bytes of alignment plus a 32-byte block.
260 NumBytes = 36;
261 break;
262 case TargetOpcode::PATCHABLE_EVENT_CALL:
263 // EVENT_CALL XRay sleds are exactly 6 instructions long (no alignment).
264 NumBytes = 24;
265 break;
266
267 case AArch64::SPACE:
268 NumBytes = MI.getOperand(1).getImm();
269 break;
270 case AArch64::MOVaddr:
271 case AArch64::MOVaddrJT:
272 case AArch64::MOVaddrCP:
273 case AArch64::MOVaddrBA:
274 case AArch64::MOVaddrTLS:
275 case AArch64::MOVaddrEXT: {
276 // Use the same logic as the pseudo expansion to count instructions.
279 MI.getOperand(1).getTargetFlags(),
280 Subtarget.isTargetMachO(), Insn);
281 NumBytes = Insn.size() * 4;
282 break;
283 }
284
285 case AArch64::MOVi32imm:
286 case AArch64::MOVi64imm: {
287 // Use the same logic as the pseudo expansion to count instructions.
288 unsigned BitSize = Desc.getOpcode() == AArch64::MOVi32imm ? 32 : 64;
290 AArch64_IMM::expandMOVImm(MI.getOperand(1).getImm(), BitSize, Insn);
291 NumBytes = Insn.size() * 4;
292 break;
293 }
294
295 case TargetOpcode::BUNDLE:
296 NumBytes = getInstBundleSize(MI);
297 break;
298 }
299
300 return NumBytes;
301}
302
305 // Block ends with fall-through condbranch.
306 switch (LastInst->getOpcode()) {
307 default:
308 llvm_unreachable("Unknown branch instruction?");
309 case AArch64::Bcc:
310 Target = LastInst->getOperand(1).getMBB();
311 Cond.push_back(LastInst->getOperand(0));
312 break;
313 case AArch64::CBZW:
314 case AArch64::CBZX:
315 case AArch64::CBNZW:
316 case AArch64::CBNZX:
317 Target = LastInst->getOperand(1).getMBB();
318 Cond.push_back(MachineOperand::CreateImm(-1));
319 Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
320 Cond.push_back(LastInst->getOperand(0));
321 break;
322 case AArch64::TBZW:
323 case AArch64::TBZX:
324 case AArch64::TBNZW:
325 case AArch64::TBNZX:
326 Target = LastInst->getOperand(2).getMBB();
327 Cond.push_back(MachineOperand::CreateImm(-1));
328 Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
329 Cond.push_back(LastInst->getOperand(0));
330 Cond.push_back(LastInst->getOperand(1));
331 break;
332 case AArch64::CBWPri:
333 case AArch64::CBXPri:
334 case AArch64::CBWPrr:
335 case AArch64::CBXPrr:
336 Target = LastInst->getOperand(3).getMBB();
337 Cond.push_back(MachineOperand::CreateImm(-1));
338 Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
339 Cond.push_back(LastInst->getOperand(0));
340 Cond.push_back(LastInst->getOperand(1));
341 Cond.push_back(LastInst->getOperand(2));
342 break;
343 case AArch64::CBBAssertExt:
344 case AArch64::CBHAssertExt:
345 Target = LastInst->getOperand(3).getMBB();
346 Cond.push_back(MachineOperand::CreateImm(-1)); // -1
347 Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode())); // Opc
348 Cond.push_back(LastInst->getOperand(0)); // Cond
349 Cond.push_back(LastInst->getOperand(1)); // Op0
350 Cond.push_back(LastInst->getOperand(2)); // Op1
351 Cond.push_back(LastInst->getOperand(4)); // Ext0
352 Cond.push_back(LastInst->getOperand(5)); // Ext1
353 break;
354 }
355}
356
357static unsigned getBranchDisplacementBits(const AArch64Options &CLOpts,
358 unsigned Opc) {
359 switch (Opc) {
360 default:
361 llvm_unreachable("unexpected opcode!");
362 case AArch64::B:
363 return CLOpts.b_offset_bits;
364 case AArch64::TBNZW:
365 case AArch64::TBZW:
366 case AArch64::TBNZX:
367 case AArch64::TBZX:
368 return CLOpts.tbz_offset_bits;
369 case AArch64::CBNZW:
370 case AArch64::CBZW:
371 case AArch64::CBNZX:
372 case AArch64::CBZX:
373 return CLOpts.cbz_offset_bits;
374 case AArch64::Bcc:
375 return CLOpts.bcc_offset_bits;
376 case AArch64::CBWPri:
377 case AArch64::CBXPri:
378 case AArch64::CBBAssertExt:
379 case AArch64::CBHAssertExt:
380 case AArch64::CBWPrr:
381 case AArch64::CBXPrr:
382 return CLOpts.cb_offset_bits;
383 }
384}
385
387 int64_t BrOffset) const {
388 unsigned Bits = getBranchDisplacementBits(Subtarget.getCLOpts(), BranchOp);
389 assert(Bits >= 3 && "max branch displacement must be enough to jump"
390 "over conditional branch expansion");
391 return isIntN(Bits, BrOffset / 4);
392}
393
396 switch (MI.getOpcode()) {
397 default:
398 llvm_unreachable("unexpected opcode!");
399 case AArch64::B:
400 return MI.getOperand(0).getMBB();
401 case AArch64::TBZW:
402 case AArch64::TBNZW:
403 case AArch64::TBZX:
404 case AArch64::TBNZX:
405 return MI.getOperand(2).getMBB();
406 case AArch64::CBZW:
407 case AArch64::CBNZW:
408 case AArch64::CBZX:
409 case AArch64::CBNZX:
410 case AArch64::Bcc:
411 return MI.getOperand(1).getMBB();
412 case AArch64::CBWPri:
413 case AArch64::CBXPri:
414 case AArch64::CBBAssertExt:
415 case AArch64::CBHAssertExt:
416 case AArch64::CBWPrr:
417 case AArch64::CBXPrr:
418 return MI.getOperand(3).getMBB();
419 }
420}
421
423 MachineBasicBlock &NewDestBB,
424 MachineBasicBlock &RestoreBB,
425 const DebugLoc &DL,
426 int64_t BrOffset,
427 RegScavenger *RS) const {
428 assert(RS && "RegScavenger required for long branching");
429 assert(MBB.empty() &&
430 "new block should be inserted for expanding unconditional branch");
431 assert(MBB.pred_size() == 1);
432 assert(RestoreBB.empty() &&
433 "restore block should be inserted for restoring clobbered registers");
434
435 auto buildIndirectBranch = [&](Register Reg, MachineBasicBlock &DestBB) {
436 // Offsets outside of the signed 33-bit range are not supported for ADRP +
437 // ADD.
438 if (!isInt<33>(BrOffset))
440 "Branch offsets outside of the signed 33-bit range not supported");
441
442 BuildMI(MBB, MBB.end(), DL, get(AArch64::ADRP), Reg)
443 .addSym(DestBB.getSymbol(), AArch64II::MO_PAGE);
444 BuildMI(MBB, MBB.end(), DL, get(AArch64::ADDXri), Reg)
445 .addReg(Reg)
446 .addSym(DestBB.getSymbol(), AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
447 .addImm(0);
448 BuildMI(MBB, MBB.end(), DL, get(AArch64::BR)).addReg(Reg);
449 };
450
451 RS->enterBasicBlockEnd(MBB);
452 // If X16 is unused, we can rely on the linker to insert a range extension
453 // thunk if NewDestBB is out of range of a single B instruction.
454 constexpr Register Reg = AArch64::X16;
455 if (!RS->isRegUsed(Reg)) {
456 insertUnconditionalBranch(MBB, &NewDestBB, DL);
457 RS->setRegUsed(Reg);
458 return;
459 }
460
461 // In a cold block without BTI, insert the indirect branch if a register is
462 // free. Skip this if BTI is enabled to avoid inserting a BTI at the target,
463 // prioritizing a dynamic cost in cold code over a static cost in hot code.
464 AArch64FunctionInfo *AFI = MBB.getParent()->getInfo<AArch64FunctionInfo>();
465 bool HasBTI = AFI && AFI->branchTargetEnforcement();
466 if (MBB.getSectionID() == MBBSectionID::ColdSectionID && !HasBTI) {
467 Register Scavenged = RS->FindUnusedReg(&AArch64::GPR64RegClass);
468 if (Scavenged.isValid()) {
469 buildIndirectBranch(Scavenged, NewDestBB);
470 RS->setRegUsed(Scavenged);
471 return;
472 }
473 }
474
475 // Note: Spilling X16 briefly moves the stack pointer, making it incompatible
476 // with red zones.
477 if (!AFI || AFI->hasRedZone().value_or(true))
479 "Unable to insert indirect branch inside function that has red zone");
480
481 // Otherwise, spill X16 and defer range extension to the linker.
482 BuildMI(MBB, MBB.end(), DL, get(AArch64::STRXpre))
483 .addReg(AArch64::SP, RegState::Define)
484 .addReg(Reg)
485 .addReg(AArch64::SP)
486 .addImm(-16);
487
488 BuildMI(MBB, MBB.end(), DL, get(AArch64::B)).addMBB(&RestoreBB);
489
490 BuildMI(RestoreBB, RestoreBB.end(), DL, get(AArch64::LDRXpost))
491 .addReg(AArch64::SP, RegState::Define)
493 .addReg(AArch64::SP)
494 .addImm(16);
495}
496
497// Branch analysis.
500 MachineBasicBlock *&FBB,
502 bool AllowModify) const {
503 // If the block has no terminators, it just falls into the block after it.
504 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
505 if (I == MBB.end())
506 return false;
507
508 // Skip over SpeculationBarrierEndBB terminators
509 if (I->getOpcode() == AArch64::SpeculationBarrierISBDSBEndBB ||
510 I->getOpcode() == AArch64::SpeculationBarrierSBEndBB) {
511 --I;
512 }
513
514 if (!isUnpredicatedTerminator(*I))
515 return false;
516
517 // Get the last instruction in the block.
518 MachineInstr *LastInst = &*I;
519
520 // If there is only one terminator instruction, process it.
521 unsigned LastOpc = LastInst->getOpcode();
522 if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
523 if (isUncondBranchOpcode(LastOpc)) {
524 TBB = LastInst->getOperand(0).getMBB();
525 return false;
526 }
527 if (isCondBranchOpcode(LastOpc)) {
528 // Block ends with fall-through condbranch.
529 parseCondBranch(LastInst, TBB, Cond);
530 return false;
531 }
532 return true; // Can't handle indirect branch.
533 }
534
535 // Get the instruction before it if it is a terminator.
536 MachineInstr *SecondLastInst = &*I;
537 unsigned SecondLastOpc = SecondLastInst->getOpcode();
538
539 // If AllowModify is true and the block ends with two or more unconditional
540 // branches, delete all but the first unconditional branch.
541 if (AllowModify && isUncondBranchOpcode(LastOpc)) {
542 while (isUncondBranchOpcode(SecondLastOpc)) {
543 LastInst->eraseFromParent();
544 LastInst = SecondLastInst;
545 LastOpc = LastInst->getOpcode();
546 if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
547 // Return now the only terminator is an unconditional branch.
548 TBB = LastInst->getOperand(0).getMBB();
549 return false;
550 }
551 SecondLastInst = &*I;
552 SecondLastOpc = SecondLastInst->getOpcode();
553 }
554 }
555
556 // If we're allowed to modify and the block ends in a unconditional branch
557 // which could simply fallthrough, remove the branch. (Note: This case only
558 // matters when we can't understand the whole sequence, otherwise it's also
559 // handled by BranchFolding.cpp.)
560 if (AllowModify && isUncondBranchOpcode(LastOpc) &&
561 MBB.isLayoutSuccessor(getBranchDestBlock(*LastInst))) {
562 LastInst->eraseFromParent();
563 LastInst = SecondLastInst;
564 LastOpc = LastInst->getOpcode();
565 if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
566 assert(!isUncondBranchOpcode(LastOpc) &&
567 "unreachable unconditional branches removed above");
568
569 if (isCondBranchOpcode(LastOpc)) {
570 // Block ends with fall-through condbranch.
571 parseCondBranch(LastInst, TBB, Cond);
572 return false;
573 }
574 return true; // Can't handle indirect branch.
575 }
576 SecondLastInst = &*I;
577 SecondLastOpc = SecondLastInst->getOpcode();
578 }
579
580 // If there are three terminators, we don't know what sort of block this is.
581 if (SecondLastInst && I != MBB.begin() && isUnpredicatedTerminator(*--I))
582 return true;
583
584 // If the block ends with a B and a Bcc, handle it.
585 if (isCondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
586 parseCondBranch(SecondLastInst, TBB, Cond);
587 FBB = LastInst->getOperand(0).getMBB();
588 return false;
589 }
590
591 // If the block ends with two unconditional branches, handle it. The second
592 // one is not executed, so remove it.
593 if (isUncondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
594 TBB = SecondLastInst->getOperand(0).getMBB();
595 I = LastInst;
596 if (AllowModify)
597 I->eraseFromParent();
598 return false;
599 }
600
601 // ...likewise if it ends with an indirect branch followed by an unconditional
602 // branch.
603 if (isIndirectBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
604 I = LastInst;
605 if (AllowModify)
606 I->eraseFromParent();
607 return true;
608 }
609
610 // Otherwise, can't handle this.
611 return true;
612}
613
615 MachineBranchPredicate &MBP,
616 bool AllowModify) const {
617 // Use analyzeBranch to validate the branch pattern.
618 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
620 if (analyzeBranch(MBB, TBB, FBB, Cond, AllowModify))
621 return true;
622
623 // analyzeBranch returns success with empty Cond for unconditional branches.
624 if (Cond.empty())
625 return true;
626
627 MBP.TrueDest = TBB;
628 assert(MBP.TrueDest && "expected!");
629 MBP.FalseDest = FBB ? FBB : MBB.getNextNode();
630
631 MBP.ConditionDef = nullptr;
632 MBP.SingleUseCondition = false;
633
634 // Find the conditional branch. After analyzeBranch succeeds with non-empty
635 // Cond, there's exactly one conditional branch - either last (fallthrough)
636 // or second-to-last (followed by unconditional B).
637 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
638 if (I == MBB.end())
639 return true;
640
641 if (isUncondBranchOpcode(I->getOpcode())) {
642 if (I == MBB.begin())
643 return true;
644 --I;
645 }
646
647 MachineInstr *CondBranch = &*I;
648 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
649
650 switch (CondBranch->getOpcode()) {
651 default:
652 return true;
653
654 case AArch64::Bcc:
655 // Bcc takes the NZCV flag as the operand to branch on, walk up the
656 // instruction stream to find the last instruction to define NZCV.
658 if (MI.modifiesRegister(AArch64::NZCV, /*TRI=*/nullptr)) {
659 MBP.ConditionDef = &MI;
660 break;
661 }
662 }
663 return false;
664
665 case AArch64::CBZW:
666 case AArch64::CBZX:
667 case AArch64::CBNZW:
668 case AArch64::CBNZX: {
669 MBP.LHS = CondBranch->getOperand(0);
670 MBP.RHS = MachineOperand::CreateImm(0);
671 unsigned Opc = CondBranch->getOpcode();
672 MBP.Predicate = (Opc == AArch64::CBNZX || Opc == AArch64::CBNZW)
673 ? MachineBranchPredicate::PRED_NE
674 : MachineBranchPredicate::PRED_EQ;
675 Register CondReg = MBP.LHS.getReg();
676 if (CondReg.isVirtual())
677 MBP.ConditionDef = MRI.getVRegDef(CondReg);
678 return false;
679 }
680
681 case AArch64::TBZW:
682 case AArch64::TBZX:
683 case AArch64::TBNZW:
684 case AArch64::TBNZX: {
685 Register CondReg = CondBranch->getOperand(0).getReg();
686 if (CondReg.isVirtual())
687 MBP.ConditionDef = MRI.getVRegDef(CondReg);
688 return false;
689 }
690 }
691}
692
695 if (Cond[0].getImm() != -1) {
696 // Regular Bcc
699 } else {
700 // Folded compare-and-branch
701 switch (Cond[1].getImm()) {
702 default:
703 llvm_unreachable("Unknown conditional branch!");
704 case AArch64::CBZW:
705 Cond[1].setImm(AArch64::CBNZW);
706 break;
707 case AArch64::CBNZW:
708 Cond[1].setImm(AArch64::CBZW);
709 break;
710 case AArch64::CBZX:
711 Cond[1].setImm(AArch64::CBNZX);
712 break;
713 case AArch64::CBNZX:
714 Cond[1].setImm(AArch64::CBZX);
715 break;
716 case AArch64::TBZW:
717 Cond[1].setImm(AArch64::TBNZW);
718 break;
719 case AArch64::TBNZW:
720 Cond[1].setImm(AArch64::TBZW);
721 break;
722 case AArch64::TBZX:
723 Cond[1].setImm(AArch64::TBNZX);
724 break;
725 case AArch64::TBNZX:
726 Cond[1].setImm(AArch64::TBZX);
727 break;
728
729 // Cond is { -1, Opcode, CC, Op0, Op1, ... }
730 case AArch64::CBWPri:
731 case AArch64::CBXPri:
732 case AArch64::CBBAssertExt:
733 case AArch64::CBHAssertExt:
734 case AArch64::CBWPrr:
735 case AArch64::CBXPrr: {
736 // Pseudos using standard 4bit Arm condition codes
738 static_cast<AArch64CC::CondCode>(Cond[2].getImm());
740 }
741 }
742 }
743
744 return false;
745}
746
748 int *BytesRemoved) const {
749 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
750 if (I == MBB.end())
751 return 0;
752
753 if (!isUncondBranchOpcode(I->getOpcode()) &&
754 !isCondBranchOpcode(I->getOpcode()))
755 return 0;
756
757 // Remove the branch.
758 I->eraseFromParent();
759
760 I = MBB.end();
761
762 if (I == MBB.begin()) {
763 if (BytesRemoved)
764 *BytesRemoved = 4;
765 return 1;
766 }
767 --I;
768 if (!isCondBranchOpcode(I->getOpcode())) {
769 if (BytesRemoved)
770 *BytesRemoved = 4;
771 return 1;
772 }
773
774 // Remove the branch.
775 I->eraseFromParent();
776 if (BytesRemoved)
777 *BytesRemoved = 8;
778
779 return 2;
780}
781
782void AArch64InstrInfo::instantiateCondBranch(
785 if (Cond[0].getImm() != -1) {
786 // Regular Bcc
787 BuildMI(&MBB, DL, get(AArch64::Bcc)).addImm(Cond[0].getImm()).addMBB(TBB);
788 } else {
789 // Folded compare-and-branch
790 // Note that we use addOperand instead of addReg to keep the flags.
791
792 // cbz, cbnz
793 const MachineInstrBuilder MIB =
794 BuildMI(&MBB, DL, get(Cond[1].getImm())).add(Cond[2]);
795
796 // tbz/tbnz
797 if (Cond.size() > 3)
798 MIB.add(Cond[3]);
799
800 // cb
801 if (Cond.size() > 4)
802 MIB.add(Cond[4]);
803
804 MIB.addMBB(TBB);
805
806 // cb[b,h]
807 if (Cond.size() > 5) {
808 MIB.addImm(Cond[5].getImm());
809 MIB.addImm(Cond[6].getImm());
810 }
811 }
812}
813
816 ArrayRef<MachineOperand> Cond, const DebugLoc &DL, int *BytesAdded) const {
817 // Shouldn't be a fall through.
818 assert(TBB && "insertBranch must not be told to insert a fallthrough");
819
820 if (!FBB) {
821 if (Cond.empty()) // Unconditional branch?
822 BuildMI(&MBB, DL, get(AArch64::B)).addMBB(TBB);
823 else
824 instantiateCondBranch(MBB, DL, TBB, Cond);
825
826 if (BytesAdded)
827 *BytesAdded = 4;
828
829 return 1;
830 }
831
832 // Two-way conditional branch.
833 instantiateCondBranch(MBB, DL, TBB, Cond);
834 BuildMI(&MBB, DL, get(AArch64::B)).addMBB(FBB);
835
836 if (BytesAdded)
837 *BytesAdded = 8;
838
839 return 2;
840}
841
842#ifndef NDEBUG
844 switch (Ext) {
845 default:
846 return false;
847 case AArch64_AM::UXTB:
848 case AArch64_AM::SXTB:
849 return Opc == AArch64::CBBAssertExt;
850 case AArch64_AM::UXTH:
851 case AArch64_AM::SXTH:
852 return Opc == AArch64::CBHAssertExt;
853 }
854}
855#endif
856
860 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
861
862 // Parse the condition code, see parseCondBranch() above.
864 switch (Cond.size()) {
865 default:
866 llvm_unreachable("Unknown condition opcode in Cond");
867 case 1: // b.cc
869 break;
870 case 3: { // cbz/cbnz
871 // We must insert a compare against 0.
872 bool Is64Bit;
873 switch (Cond[1].getImm()) {
874 default:
875 llvm_unreachable("Unknown branch opcode in Cond");
876 case AArch64::CBZW:
877 Is64Bit = false;
879 break;
880 case AArch64::CBZX:
881 Is64Bit = true;
883 break;
884 case AArch64::CBNZW:
885 Is64Bit = false;
887 break;
888 case AArch64::CBNZX:
889 Is64Bit = true;
891 break;
892 }
893 Register SrcReg = Cond[2].getReg();
894 if (Is64Bit) {
895 // cmp reg, #0 is actually subs xzr, reg, #0.
896 MRI.constrainRegClass(SrcReg, &AArch64::GPR64spRegClass);
897 BuildMI(MBB, MI, DL, get(AArch64::SUBSXri), AArch64::XZR)
898 .addReg(SrcReg)
899 .addImm(0)
900 .addImm(0);
901 } else {
902 MRI.constrainRegClass(SrcReg, &AArch64::GPR32spRegClass);
903 BuildMI(MBB, MI, DL, get(AArch64::SUBSWri), AArch64::WZR)
904 .addReg(SrcReg)
905 .addImm(0)
906 .addImm(0);
907 }
908 } break;
909 case 4: { // tbz/tbnz
910 // We must insert a tst instruction.
911 switch (Cond[1].getImm()) {
912 default:
913 llvm_unreachable("Unknown branch opcode in Cond");
914 case AArch64::TBZW:
915 case AArch64::TBZX:
917 break;
918 case AArch64::TBNZW:
919 case AArch64::TBNZX:
921 break;
922 }
923 // cmp reg, #foo is actually ands xzr, reg, #1<<foo.
924 if (Cond[1].getImm() == AArch64::TBZW || Cond[1].getImm() == AArch64::TBNZW)
925 BuildMI(MBB, MI, DL, get(AArch64::ANDSWri), AArch64::WZR)
926 .addReg(Cond[2].getReg())
927 .addImm(
929 else
930 BuildMI(MBB, MI, DL, get(AArch64::ANDSXri), AArch64::XZR)
931 .addReg(Cond[2].getReg())
932 .addImm(
934 } break;
935 case 5: { // cb
936 // We must insert a cmp, that is a subs
937 // 0 1 2 3 4
938 // Cond is { -1, Opcode, CC, Op0, Op1 }
939 unsigned SubsOpc, SubsDestReg;
940 bool IsImm = false;
941 CC = static_cast<AArch64CC::CondCode>(Cond[2].getImm());
942 switch (Cond[1].getImm()) {
943 default:
944 llvm_unreachable("Unknown branch opcode in Cond");
945 case AArch64::CBWPri:
946 SubsOpc = AArch64::SUBSWri;
947 SubsDestReg = AArch64::WZR;
948 IsImm = true;
949 break;
950 case AArch64::CBXPri:
951 SubsOpc = AArch64::SUBSXri;
952 SubsDestReg = AArch64::XZR;
953 IsImm = true;
954 break;
955 case AArch64::CBWPrr:
956 SubsOpc = AArch64::SUBSWrr;
957 SubsDestReg = AArch64::WZR;
958 IsImm = false;
959 break;
960 case AArch64::CBXPrr:
961 SubsOpc = AArch64::SUBSXrr;
962 SubsDestReg = AArch64::XZR;
963 IsImm = false;
964 break;
965 }
966
967 if (IsImm) {
968 MRI.constrainRegClass(Cond[3].getReg(), getRegClass(get(SubsOpc), 1));
969 BuildMI(MBB, MI, DL, get(SubsOpc), SubsDestReg)
970 .addReg(Cond[3].getReg())
971 .addImm(Cond[4].getImm())
972 .addImm(0);
973 } else {
974 MRI.constrainRegClass(Cond[3].getReg(), getRegClass(get(SubsOpc), 1));
975 MRI.constrainRegClass(Cond[4].getReg(), getRegClass(get(SubsOpc), 2));
976 BuildMI(MBB, MI, DL, get(SubsOpc), SubsDestReg)
977 .addReg(Cond[3].getReg())
978 .addReg(Cond[4].getReg());
979 }
980 } break;
981 case 7: { // cb[b,h]
982 // We must insert a cmp, that is a subs, but also zero- or sign-extensions
983 // that have been folded. For the first operand we codegen an explicit
984 // extension, for the second operand we fold the extension into cmp.
985 // 0 1 2 3 4 5 6
986 // Cond is { -1, Opcode, CC, Op0, Op1, Ext0, Ext1 }
987
988 // We need a new register for the now explicitly extended register
989 Register Reg = Cond[3].getReg();
991 unsigned ExtOpc;
992 unsigned ExtBits;
993 AArch64_AM::ShiftExtendType ExtendType =
995 assert(isValidCBExtend(Cond[1].getImm(), ExtendType) &&
996 "Unexpected compare-and-branch instruction for extend type");
997 switch (ExtendType) {
998 default:
999 llvm_unreachable("Unknown shift-extend for CB instruction");
1000 case AArch64_AM::SXTB:
1001 ExtOpc = AArch64::SBFMWri;
1002 ExtBits = AArch64_AM::encodeLogicalImmediate(0xff, 32);
1003 break;
1004 case AArch64_AM::SXTH:
1005 ExtOpc = AArch64::SBFMWri;
1006 ExtBits = AArch64_AM::encodeLogicalImmediate(0xffff, 32);
1007 break;
1008 case AArch64_AM::UXTB:
1009 ExtOpc = AArch64::ANDWri;
1010 ExtBits = AArch64_AM::encodeLogicalImmediate(0xff, 32);
1011 break;
1012 case AArch64_AM::UXTH:
1013 ExtOpc = AArch64::ANDWri;
1014 ExtBits = AArch64_AM::encodeLogicalImmediate(0xffff, 32);
1015 break;
1016 }
1017
1018 // Build the explicit extension of the first operand
1019 Reg = MRI.createVirtualRegister(&AArch64::GPR32commonRegClass);
1021 BuildMI(MBB, MI, DL, get(ExtOpc), Reg).addReg(Cond[3].getReg());
1022 if (ExtOpc != AArch64::ANDWri)
1023 MBBI.addImm(0);
1024 MBBI.addImm(ExtBits);
1025 }
1026
1027 // Now, subs with an extended second operand
1029 MRI.constrainRegClass(Reg, &AArch64::GPR32commonRegClass);
1030 AArch64_AM::ShiftExtendType ExtendType =
1032 assert(isValidCBExtend(Cond[1].getImm(), ExtendType) &&
1033 "Unexpected compare-and-branch instruction for extend type");
1034 BuildMI(MBB, MI, DL, get(AArch64::SUBSWrx), AArch64::WZR)
1035 .addReg(Reg)
1036 .addReg(Cond[4].getReg())
1037 .addImm(AArch64_AM::getArithExtendImm(ExtendType, 0));
1038 } // If no extension is needed, just a regular subs
1039 else {
1040 BuildMI(MBB, MI, DL, get(AArch64::SUBSWrr), AArch64::WZR)
1041 .addReg(Reg)
1042 .addReg(Cond[4].getReg());
1043 }
1044
1045 CC = static_cast<AArch64CC::CondCode>(Cond[2].getImm());
1046 } break;
1047 }
1048 return CC;
1049}
1050
1052 const TargetInstrInfo &TII) {
1053 for (MachineInstr &MI : MBB->terminators()) {
1054 unsigned Opc = MI.getOpcode();
1055 switch (Opc) {
1056 case AArch64::CBZW:
1057 case AArch64::CBZX:
1058 case AArch64::TBZW:
1059 case AArch64::TBZX:
1060 // CBZ/TBZ with WZR/XZR -> unconditional B
1061 if (MI.getOperand(0).getReg() == AArch64::WZR ||
1062 MI.getOperand(0).getReg() == AArch64::XZR) {
1063 DEBUG_WITH_TYPE("optimizeTerminators",
1064 dbgs() << "Removing always taken branch: " << MI);
1065 MachineBasicBlock *Target = TII.getBranchDestBlock(MI);
1066 SmallVector<MachineBasicBlock *> Succs(MBB->successors());
1067 for (auto *S : Succs)
1068 if (S != Target)
1069 MBB->removeSuccessor(S);
1070 DebugLoc DL = MI.getDebugLoc();
1071 while (MBB->rbegin() != &MI)
1072 MBB->rbegin()->eraseFromParent();
1073 MI.eraseFromParent();
1074 BuildMI(MBB, DL, TII.get(AArch64::B)).addMBB(Target);
1075 return true;
1076 }
1077 break;
1078 case AArch64::CBNZW:
1079 case AArch64::CBNZX:
1080 case AArch64::TBNZW:
1081 case AArch64::TBNZX:
1082 // CBNZ/TBNZ with WZR/XZR -> never taken, remove branch and successor
1083 if (MI.getOperand(0).getReg() == AArch64::WZR ||
1084 MI.getOperand(0).getReg() == AArch64::XZR) {
1085 DEBUG_WITH_TYPE("optimizeTerminators",
1086 dbgs() << "Removing never taken branch: " << MI);
1087 MachineBasicBlock *Target = TII.getBranchDestBlock(MI);
1088 MI.getParent()->removeSuccessor(Target);
1089 MI.eraseFromParent();
1090 return true;
1091 }
1092 break;
1093 }
1094 }
1095 return false;
1096}
1097
1098// Find the original register that VReg is copied from.
1099static unsigned removeCopies(const MachineRegisterInfo &MRI, unsigned VReg) {
1100 while (Register::isVirtualRegister(VReg)) {
1101 const MachineInstr *DefMI = MRI.getVRegDef(VReg);
1102 if (!DefMI || !DefMI->isFullCopy())
1103 return VReg;
1104 VReg = DefMI->getOperand(1).getReg();
1105 }
1106 return VReg;
1107}
1108
1109// Determine if VReg is defined by an instruction that can be folded into a
1110// csel instruction. If so, return the folded opcode, and the replacement
1111// register.
1112static unsigned canFoldIntoCSel(const MachineRegisterInfo &MRI, unsigned VReg,
1113 unsigned *NewReg = nullptr) {
1114 VReg = removeCopies(MRI, VReg);
1115 if (!Register::isVirtualRegister(VReg))
1116 return 0;
1117
1118 bool Is64Bit = AArch64::GPR64allRegClass.hasSubClassEq(MRI.getRegClass(VReg));
1119 const MachineInstr *DefMI = MRI.getVRegDef(VReg);
1120 if (!DefMI)
1121 return 0;
1122 unsigned Opc = 0;
1123 unsigned SrcReg = 0;
1124 switch (DefMI->getOpcode()) {
1125 case AArch64::SUBREG_TO_REG:
1126 // Check for the following way to define an 64-bit immediate:
1127 // %0:gpr32 = MOVi32imm 1
1128 // %1:gpr64 = SUBREG_TO_REG %0:gpr32, %subreg.sub_32
1129 if (!DefMI->getOperand(1).isReg())
1130 return 0;
1131 if (!DefMI->getOperand(2).isImm() ||
1132 DefMI->getOperand(2).getImm() != AArch64::sub_32)
1133 return 0;
1134 DefMI = MRI.getVRegDef(DefMI->getOperand(1).getReg());
1135 if (DefMI->getOpcode() != AArch64::MOVi32imm)
1136 return 0;
1137 if (!DefMI->getOperand(1).isImm() || DefMI->getOperand(1).getImm() != 1)
1138 return 0;
1139 assert(Is64Bit);
1140 SrcReg = AArch64::XZR;
1141 Opc = AArch64::CSINCXr;
1142 break;
1143
1144 case AArch64::MOVi32imm:
1145 case AArch64::MOVi64imm:
1146 if (!DefMI->getOperand(1).isImm() || DefMI->getOperand(1).getImm() != 1)
1147 return 0;
1148 SrcReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1149 Opc = Is64Bit ? AArch64::CSINCXr : AArch64::CSINCWr;
1150 break;
1151
1152 case AArch64::ADDSXri:
1153 case AArch64::ADDSWri:
1154 // if NZCV is used, do not fold.
1155 if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr,
1156 true) == -1)
1157 return 0;
1158 // fall-through to ADDXri and ADDWri.
1159 [[fallthrough]];
1160 case AArch64::ADDXri:
1161 case AArch64::ADDWri:
1162 // add x, 1 -> csinc.
1163 if (!DefMI->getOperand(2).isImm() || DefMI->getOperand(2).getImm() != 1 ||
1164 DefMI->getOperand(3).getImm() != 0)
1165 return 0;
1166 SrcReg = DefMI->getOperand(1).getReg();
1167 Opc = Is64Bit ? AArch64::CSINCXr : AArch64::CSINCWr;
1168 break;
1169
1170 case AArch64::ORNXrr:
1171 case AArch64::ORNWrr: {
1172 // not x -> csinv, represented as orn dst, xzr, src.
1173 unsigned ZReg = removeCopies(MRI, DefMI->getOperand(1).getReg());
1174 if (ZReg != AArch64::XZR && ZReg != AArch64::WZR)
1175 return 0;
1176 SrcReg = DefMI->getOperand(2).getReg();
1177 Opc = Is64Bit ? AArch64::CSINVXr : AArch64::CSINVWr;
1178 break;
1179 }
1180
1181 case AArch64::SUBSXrr:
1182 case AArch64::SUBSWrr:
1183 // if NZCV is used, do not fold.
1184 if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr,
1185 true) == -1)
1186 return 0;
1187 // fall-through to SUBXrr and SUBWrr.
1188 [[fallthrough]];
1189 case AArch64::SUBXrr:
1190 case AArch64::SUBWrr: {
1191 // neg x -> csneg, represented as sub dst, xzr, src.
1192 unsigned ZReg = removeCopies(MRI, DefMI->getOperand(1).getReg());
1193 if (ZReg != AArch64::XZR && ZReg != AArch64::WZR)
1194 return 0;
1195 SrcReg = DefMI->getOperand(2).getReg();
1196 Opc = Is64Bit ? AArch64::CSNEGXr : AArch64::CSNEGWr;
1197 break;
1198 }
1199 default:
1200 return 0;
1201 }
1202 assert(Opc && SrcReg && "Missing parameters");
1203
1204 if (NewReg)
1205 *NewReg = SrcReg;
1206 return Opc;
1207}
1208
1211 Register DstReg, Register TrueReg,
1212 Register FalseReg,
1213 SelectExpansion &Exp) const {
1214 // Check register classes.
1215 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1216 const TargetRegisterClass *RC =
1217 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
1218 if (!RC)
1219 return false;
1220
1221 // Also need to check the dest regclass, in case we're trying to optimize
1222 // something like:
1223 // %1(gpr) = PHI %2(fpr), bb1, %(fpr), bb2
1224 if (!RI.getCommonSubClass(RC, MRI.getRegClass(DstReg)))
1225 return false;
1226
1227 // Expanding cbz/tbz requires a flag setting instruction in addition to the
1228 // select, adding an extra cycle of latency on the condition.
1229 unsigned ExtraCondLat = Cond.size() != 1;
1230 Exp.NumInsts = 1 + ExtraCondLat;
1231 if (ExtraCondLat)
1232 Exp.ClobberedPhysRegs.push_back(AArch64::NZCV);
1233
1234 // GPRs are handled by csel.
1235 // FIXME: Fold in x+1, -x, and ~x when applicable.
1236 if (AArch64::GPR64allRegClass.hasSubClassEq(RC) ||
1237 AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
1238 // Single-cycle csel, csinc, csinv, and csneg.
1239 Exp.CondCycles = 1 + ExtraCondLat;
1240 Exp.TrueCycles = Exp.FalseCycles = 1;
1241 if (canFoldIntoCSel(MRI, TrueReg))
1242 Exp.TrueCycles = 0;
1243 else if (canFoldIntoCSel(MRI, FalseReg))
1244 Exp.FalseCycles = 0;
1245 return true;
1246 }
1247
1248 // Scalar floating point is handled by fcsel.
1249 // FIXME: Form fabs, fmin, and fmax when applicable.
1250 if (AArch64::FPR64RegClass.hasSubClassEq(RC) ||
1251 AArch64::FPR32RegClass.hasSubClassEq(RC)) {
1252 Exp.CondCycles = 5 + ExtraCondLat;
1253 Exp.TrueCycles = Exp.FalseCycles = 2;
1254 return true;
1255 }
1256
1257 // No single conditional move for a 128-bit vector, but we can emit a sequence
1258 // of csetm (~1), dup (~5, cross domain), bsl (~2).
1259 if (AArch64::FPR128RegClass.hasSubClassEq(RC) &&
1260 Subtarget.isNeonAvailable() &&
1261 !MBB.getParent()->getFunction().hasMinSize()) {
1262 Exp.CondCycles = 8 + ExtraCondLat;
1263 Exp.TrueCycles = Exp.FalseCycles = 2;
1264 Exp.NumInsts = 3 + ExtraCondLat;
1265 return true;
1266 }
1267
1268 return false;
1269}
1270
1273 const DebugLoc &DL, Register DstReg,
1275 Register TrueReg, Register FalseReg) const {
1276
1277 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1279
1280 // A 128-bit vector has no conditional move so blend the operands with a mask
1281 // built from the flags.
1282 if (MRI.constrainRegClass(DstReg, &AArch64::FPR128RegClass)) {
1283 assert(Subtarget.isNeonAvailable() && "Expected NEON for a vector select");
1284 MRI.constrainRegClass(TrueReg, &AArch64::FPR128RegClass);
1285 MRI.constrainRegClass(FalseReg, &AArch64::FPR128RegClass);
1286 Register CondSet = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
1287 BuildMI(MBB, I, DL, get(AArch64::CSINVXr), CondSet)
1288 .addReg(AArch64::XZR)
1289 .addReg(AArch64::XZR)
1291 Register Mask = MRI.createVirtualRegister(&AArch64::FPR128RegClass);
1292 BuildMI(MBB, I, DL, get(AArch64::DUPv2i64gpr), Mask).addReg(CondSet);
1293 BuildMI(MBB, I, DL, get(AArch64::BSPv16i8), DstReg)
1294 .addReg(Mask)
1295 .addReg(TrueReg)
1296 .addReg(FalseReg);
1297 return;
1298 }
1299
1300 unsigned Opc = 0;
1301 const TargetRegisterClass *RC = nullptr;
1302 bool TryFold = false;
1303 if (MRI.constrainRegClass(DstReg, &AArch64::GPR64RegClass)) {
1304 RC = &AArch64::GPR64RegClass;
1305 Opc = AArch64::CSELXr;
1306 TryFold = true;
1307 } else if (MRI.constrainRegClass(DstReg, &AArch64::GPR32RegClass)) {
1308 RC = &AArch64::GPR32RegClass;
1309 Opc = AArch64::CSELWr;
1310 TryFold = true;
1311 } else if (MRI.constrainRegClass(DstReg, &AArch64::FPR64RegClass)) {
1312 RC = &AArch64::FPR64RegClass;
1313 Opc = AArch64::FCSELDrrr;
1314 } else if (MRI.constrainRegClass(DstReg, &AArch64::FPR32RegClass)) {
1315 RC = &AArch64::FPR32RegClass;
1316 Opc = AArch64::FCSELSrrr;
1317 }
1318 assert(RC && "Unsupported regclass");
1319
1320 // Try folding simple instructions into the csel.
1321 if (TryFold) {
1322 unsigned NewReg = 0;
1323 unsigned FoldedOpc = canFoldIntoCSel(MRI, TrueReg, &NewReg);
1324 if (FoldedOpc) {
1325 // The folded opcodes csinc, csinc and csneg apply the operation to
1326 // FalseReg, so we need to invert the condition.
1328 TrueReg = FalseReg;
1329 } else
1330 FoldedOpc = canFoldIntoCSel(MRI, FalseReg, &NewReg);
1331
1332 // Fold the operation. Leave any dead instructions for DCE to clean up.
1333 if (FoldedOpc) {
1334 FalseReg = NewReg;
1335 Opc = FoldedOpc;
1336 }
1337 }
1338
1339 // Pull all virtual register into the appropriate class.
1340 MRI.constrainRegClass(TrueReg, RC);
1341 // FalseReg might be WZR or XZR if the folded operand is a literal 1.
1342 assert(
1343 (FalseReg.isVirtual() || FalseReg == AArch64::WZR ||
1344 FalseReg == AArch64::XZR) &&
1345 "FalseReg was folded into a non-virtual register other than WZR or XZR");
1346 if (FalseReg.isVirtual())
1347 MRI.constrainRegClass(FalseReg, RC);
1348
1349 // Insert the csel.
1350 BuildMI(MBB, I, DL, get(Opc), DstReg)
1351 .addReg(TrueReg)
1352 .addReg(FalseReg)
1353 .addImm(CC);
1354}
1355
1356// Return true if Imm can be loaded into a register by a "cheap" sequence of
1357// instructions. For now, "cheap" means at most two instructions.
1358static bool isCheapImmediate(const MachineInstr &MI, unsigned BitSize) {
1359 if (BitSize == 32)
1360 return true;
1361
1362 assert(BitSize == 64 && "Only bit sizes of 32 or 64 allowed");
1363 uint64_t Imm = static_cast<uint64_t>(MI.getOperand(1).getImm());
1365 AArch64_IMM::expandMOVImm(Imm, BitSize, Is);
1366
1367 return Is.size() <= 2;
1368}
1369
1370// Check if a COPY instruction is cheap.
1371static bool isCheapCopy(const MachineInstr &MI, const AArch64RegisterInfo &RI) {
1372 assert(MI.isCopy() && "Expected COPY instruction");
1373 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1374
1375 // Cross-bank copies (e.g., between GPR and FPR) are expensive on AArch64,
1376 // typically requiring an FMOV instruction with a 2-6 cycle latency.
1377 auto GetRegClass = [&](Register Reg) -> const TargetRegisterClass * {
1378 if (Reg.isVirtual())
1379 return MRI.getRegClass(Reg);
1380 if (Reg.isPhysical())
1381 return RI.getMinimalPhysRegClass(Reg);
1382 return nullptr;
1383 };
1384 const TargetRegisterClass *DstRC = GetRegClass(MI.getOperand(0).getReg());
1385 const TargetRegisterClass *SrcRC = GetRegClass(MI.getOperand(1).getReg());
1386 if (DstRC && SrcRC && !RI.getCommonSubClass(DstRC, SrcRC))
1387 return false;
1388
1389 return MI.isAsCheapAsAMove();
1390}
1391
1392// FIXME: this implementation should be micro-architecture dependent, so a
1393// micro-architecture target hook should be introduced here in future.
1395 if (Subtarget.hasExynosCheapAsMoveHandling()) {
1396 if (isExynosCheapAsMove(MI))
1397 return true;
1398 return MI.isAsCheapAsAMove();
1399 }
1400
1401 switch (MI.getOpcode()) {
1402 default:
1403 return MI.isAsCheapAsAMove();
1404
1405 case TargetOpcode::COPY:
1406 return isCheapCopy(MI, RI);
1407
1408 case AArch64::ADDWrs:
1409 case AArch64::ADDXrs:
1410 case AArch64::SUBWrs:
1411 case AArch64::SUBXrs:
1412 return Subtarget.hasALULSLFast() && MI.getOperand(3).getImm() <= 4;
1413
1414 // If MOVi32imm or MOVi64imm can be expanded into ORRWri or
1415 // ORRXri, it is as cheap as MOV.
1416 // Likewise if it can be expanded to MOVZ/MOVN/MOVK.
1417 case AArch64::MOVi32imm:
1418 return isCheapImmediate(MI, 32);
1419 case AArch64::MOVi64imm:
1420 return isCheapImmediate(MI, 64);
1421 }
1422}
1423
1424bool AArch64InstrInfo::isFalkorShiftExtFast(const MachineInstr &MI) {
1425 switch (MI.getOpcode()) {
1426 default:
1427 return false;
1428
1429 case AArch64::ADDWrs:
1430 case AArch64::ADDXrs:
1431 case AArch64::ADDSWrs:
1432 case AArch64::ADDSXrs: {
1433 unsigned Imm = MI.getOperand(3).getImm();
1434 unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
1435 if (ShiftVal == 0)
1436 return true;
1437 return AArch64_AM::getShiftType(Imm) == AArch64_AM::LSL && ShiftVal <= 5;
1438 }
1439
1440 case AArch64::ADDWrx:
1441 case AArch64::ADDXrx:
1442 case AArch64::ADDXrx64:
1443 case AArch64::ADDSWrx:
1444 case AArch64::ADDSXrx:
1445 case AArch64::ADDSXrx64: {
1446 unsigned Imm = MI.getOperand(3).getImm();
1448 default:
1449 return false;
1450 case AArch64_AM::UXTB:
1451 case AArch64_AM::UXTH:
1452 case AArch64_AM::UXTW:
1453 case AArch64_AM::UXTX:
1455 }
1456 }
1457
1458 case AArch64::SUBWrs:
1459 case AArch64::SUBSWrs: {
1460 unsigned Imm = MI.getOperand(3).getImm();
1461 unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
1462 return ShiftVal == 0 ||
1463 (AArch64_AM::getShiftType(Imm) == AArch64_AM::ASR && ShiftVal == 31);
1464 }
1465
1466 case AArch64::SUBXrs:
1467 case AArch64::SUBSXrs: {
1468 unsigned Imm = MI.getOperand(3).getImm();
1469 unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
1470 return ShiftVal == 0 ||
1471 (AArch64_AM::getShiftType(Imm) == AArch64_AM::ASR && ShiftVal == 63);
1472 }
1473
1474 case AArch64::SUBWrx:
1475 case AArch64::SUBXrx:
1476 case AArch64::SUBXrx64:
1477 case AArch64::SUBSWrx:
1478 case AArch64::SUBSXrx:
1479 case AArch64::SUBSXrx64: {
1480 unsigned Imm = MI.getOperand(3).getImm();
1482 default:
1483 return false;
1484 case AArch64_AM::UXTB:
1485 case AArch64_AM::UXTH:
1486 case AArch64_AM::UXTW:
1487 case AArch64_AM::UXTX:
1489 }
1490 }
1491
1492 case AArch64::LDRBBroW:
1493 case AArch64::LDRBBroX:
1494 case AArch64::LDRBroW:
1495 case AArch64::LDRBroX:
1496 case AArch64::LDRDroW:
1497 case AArch64::LDRDroX:
1498 case AArch64::LDRHHroW:
1499 case AArch64::LDRHHroX:
1500 case AArch64::LDRHroW:
1501 case AArch64::LDRHroX:
1502 case AArch64::LDRQroW:
1503 case AArch64::LDRQroX:
1504 case AArch64::LDRSBWroW:
1505 case AArch64::LDRSBWroX:
1506 case AArch64::LDRSBXroW:
1507 case AArch64::LDRSBXroX:
1508 case AArch64::LDRSHWroW:
1509 case AArch64::LDRSHWroX:
1510 case AArch64::LDRSHXroW:
1511 case AArch64::LDRSHXroX:
1512 case AArch64::LDRSWroW:
1513 case AArch64::LDRSWroX:
1514 case AArch64::LDRSroW:
1515 case AArch64::LDRSroX:
1516 case AArch64::LDRWroW:
1517 case AArch64::LDRWroX:
1518 case AArch64::LDRXroW:
1519 case AArch64::LDRXroX:
1520 case AArch64::PRFMroW:
1521 case AArch64::PRFMroX:
1522 case AArch64::STRBBroW:
1523 case AArch64::STRBBroX:
1524 case AArch64::STRBroW:
1525 case AArch64::STRBroX:
1526 case AArch64::STRDroW:
1527 case AArch64::STRDroX:
1528 case AArch64::STRHHroW:
1529 case AArch64::STRHHroX:
1530 case AArch64::STRHroW:
1531 case AArch64::STRHroX:
1532 case AArch64::STRQroW:
1533 case AArch64::STRQroX:
1534 case AArch64::STRSroW:
1535 case AArch64::STRSroX:
1536 case AArch64::STRWroW:
1537 case AArch64::STRWroX:
1538 case AArch64::STRXroW:
1539 case AArch64::STRXroX: {
1540 unsigned IsSigned = MI.getOperand(3).getImm();
1541 return !IsSigned;
1542 }
1543 }
1544}
1545
1546bool AArch64InstrInfo::isSEHInstruction(const MachineInstr &MI) {
1547 unsigned Opc = MI.getOpcode();
1548 switch (Opc) {
1549 default:
1550 return false;
1551 case AArch64::SEH_EndC:
1552 case AArch64::SEH_StackAlloc:
1553 case AArch64::SEH_SaveFPLR:
1554 case AArch64::SEH_SaveFPLR_X:
1555 case AArch64::SEH_SaveReg:
1556 case AArch64::SEH_SaveReg_X:
1557 case AArch64::SEH_SaveRegP:
1558 case AArch64::SEH_SaveRegP_X:
1559 case AArch64::SEH_SaveFReg:
1560 case AArch64::SEH_SaveFReg_X:
1561 case AArch64::SEH_SaveFRegP:
1562 case AArch64::SEH_SaveFRegP_X:
1563 case AArch64::SEH_SetFP:
1564 case AArch64::SEH_AddFP:
1565 case AArch64::SEH_Nop:
1566 case AArch64::SEH_PrologEnd:
1567 case AArch64::SEH_EpilogStart:
1568 case AArch64::SEH_EpilogEnd:
1569 case AArch64::SEH_PACSignLR:
1570 case AArch64::SEH_SaveAnyRegI:
1571 case AArch64::SEH_SaveAnyRegIP:
1572 case AArch64::SEH_SaveAnyRegQ:
1573 case AArch64::SEH_SaveAnyRegQX:
1574 case AArch64::SEH_SaveAnyRegQP:
1575 case AArch64::SEH_SaveAnyRegQPX:
1576 case AArch64::SEH_AllocZ:
1577 case AArch64::SEH_SaveZReg:
1578 case AArch64::SEH_SavePReg:
1579 return true;
1580 }
1581}
1582
1584 Register &SrcReg, Register &DstReg,
1585 unsigned &SubIdx) const {
1586 switch (MI.getOpcode()) {
1587 default:
1588 return false;
1589 case AArch64::SBFMXri: // aka sxtw
1590 case AArch64::UBFMXri: // aka uxtw
1591 // Check for the 32 -> 64 bit extension case, these instructions can do
1592 // much more.
1593 if (MI.getOperand(2).getImm() != 0 || MI.getOperand(3).getImm() != 31)
1594 return false;
1595 // This is a signed or unsigned 32 -> 64 bit extension.
1596 SrcReg = MI.getOperand(1).getReg();
1597 DstReg = MI.getOperand(0).getReg();
1598 SubIdx = AArch64::sub_32;
1599 return true;
1600 }
1601}
1602
1604 const MachineInstr &MIa, const MachineInstr &MIb) const {
1605 const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr;
1606 int64_t OffsetA = 0, OffsetB = 0;
1607 TypeSize WidthA(0, false), WidthB(0, false);
1608 bool OffsetAIsScalable = false, OffsetBIsScalable = false;
1609
1610 assert(MIa.mayLoadOrStore() && "MIa must be a load or store.");
1611 assert(MIb.mayLoadOrStore() && "MIb must be a load or store.");
1612
1615 return false;
1616
1617 // Retrieve the base, offset from the base and width. Width
1618 // is the size of memory that is being loaded/stored (e.g. 1, 2, 4, 8). If
1619 // base are identical, and the offset of a lower memory access +
1620 // the width doesn't overlap the offset of a higher memory access,
1621 // then the memory accesses are different.
1622 // If OffsetAIsScalable and OffsetBIsScalable are both true, they
1623 // are assumed to have the same scale (vscale).
1624 if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, OffsetAIsScalable,
1625 WidthA) &&
1626 getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, OffsetBIsScalable,
1627 WidthB)) {
1628 if (BaseOpA->isIdenticalTo(*BaseOpB) &&
1629 OffsetAIsScalable == OffsetBIsScalable) {
1630 int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
1631 int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
1632 TypeSize LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
1633 if (LowWidth.isScalable() == OffsetAIsScalable &&
1634 LowOffset + (int)LowWidth.getKnownMinValue() <= HighOffset)
1635 return true;
1636 }
1637 }
1638 return false;
1639}
1640
1642 const MachineBasicBlock *MBB,
1643 const MachineFunction &MF) const {
1645 return true;
1646
1647 // Do not move an instruction that can be recognized as a branch target.
1648 if (hasBTISemantics(MI))
1649 return true;
1650
1651 switch (MI.getOpcode()) {
1652 case AArch64::PAUTH_EPILOGUE:
1653 // Keep authentication after the other epilogue instructions and close to
1654 // the return, allowing them to combine into an authenticated return.
1655 return true;
1656 case AArch64::HINT:
1657 // CSDB hints are scheduling barriers.
1658 if (MI.getOperand(0).getImm() == 0x14)
1659 return true;
1660 break;
1661 case AArch64::DSB:
1662 case AArch64::ISB:
1663 // DSB and ISB also are scheduling barriers.
1664 return true;
1665 case AArch64::MSRpstatesvcrImm1:
1666 // SMSTART and SMSTOP are also scheduling barriers.
1667 return true;
1668 default:;
1669 }
1670 if (isSEHInstruction(MI))
1671 return true;
1672 // Skip debug instructions and pseudo probes so they do not change
1673 // scheduling regions.
1674 auto Next = next_nodbg(MI.getIterator(), MBB->instr_end());
1675 return Next != MBB->instr_end() && Next->isCFIInstruction();
1676}
1677
1678/// analyzeCompare - For a comparison instruction, return the source registers
1679/// in SrcReg and SrcReg2, and the value it compares against in CmpValue.
1680/// Return true if the comparison instruction can be analyzed.
1682 Register &SrcReg2, int64_t &CmpMask,
1683 int64_t &CmpValue) const {
1684 // The first operand can be a frame index where we'd normally expect a
1685 // register.
1686 // FIXME: Pass subregisters out of analyzeCompare
1687 assert(MI.getNumOperands() >= 2 && "All AArch64 cmps should have 2 operands");
1688 if (!MI.getOperand(1).isReg() || MI.getOperand(1).getSubReg())
1689 return false;
1690
1691 switch (MI.getOpcode()) {
1692 default:
1693 break;
1694 case AArch64::PTEST_PP:
1695 case AArch64::PTEST_PP_ANY:
1696 case AArch64::PTEST_PP_FIRST:
1697 SrcReg = MI.getOperand(0).getReg();
1698 SrcReg2 = MI.getOperand(1).getReg();
1699 if (MI.getOperand(2).getSubReg())
1700 return false;
1701
1702 // Not sure about the mask and value for now...
1703 CmpMask = ~0;
1704 CmpValue = 0;
1705 return true;
1706 case AArch64::SUBSWrr:
1707 case AArch64::SUBSWrs:
1708 case AArch64::SUBSWrx:
1709 case AArch64::SUBSXrr:
1710 case AArch64::SUBSXrs:
1711 case AArch64::SUBSXrx:
1712 case AArch64::ADDSWrr:
1713 case AArch64::ADDSWrs:
1714 case AArch64::ADDSWrx:
1715 case AArch64::ADDSXrr:
1716 case AArch64::ADDSXrs:
1717 case AArch64::ADDSXrx:
1718 // Replace SUBSWrr with SUBWrr if NZCV is not used.
1719 SrcReg = MI.getOperand(1).getReg();
1720 SrcReg2 = MI.getOperand(2).getReg();
1721
1722 // FIXME: Pass subregisters out of analyzeCompare
1723 if (MI.getOperand(2).getSubReg())
1724 return false;
1725
1726 CmpMask = ~0;
1727 CmpValue = 0;
1728 return true;
1729 case AArch64::SUBSWri:
1730 case AArch64::ADDSWri:
1731 case AArch64::SUBSXri:
1732 case AArch64::ADDSXri:
1733 SrcReg = MI.getOperand(1).getReg();
1734 SrcReg2 = 0;
1735 CmpMask = ~0;
1736 CmpValue = MI.getOperand(2).getImm();
1737 return true;
1738 case AArch64::ANDSWri:
1739 case AArch64::ANDSXri:
1740 // ANDS does not use the same encoding scheme as the others xxxS
1741 // instructions.
1742 SrcReg = MI.getOperand(1).getReg();
1743 SrcReg2 = 0;
1744 CmpMask = ~0;
1746 MI.getOperand(2).getImm(),
1747 MI.getOpcode() == AArch64::ANDSWri ? 32 : 64);
1748 return true;
1749 }
1750
1751 return false;
1752}
1753
1755 MachineBasicBlock *MBB = Instr.getParent();
1756 assert(MBB && "Can't get MachineBasicBlock here");
1757 MachineFunction *MF = MBB->getParent();
1758 assert(MF && "Can't get MachineFunction here");
1762
1763 for (const auto &[OpIdx, MO] : enumerate(Instr.operands())) {
1764 if (!MO.isReg() || !MO.getReg().isVirtual())
1765 continue;
1766
1767 Register Reg = MO.getReg();
1768 const TargetRegisterClass *NewRC = Instr.getRegClassConstraintEffect(
1769 OpIdx, MRI->getRegClass(Reg), TII, TRI);
1770 if (!NewRC || !MRI->constrainRegClass(Reg, NewRC))
1771 llvm_unreachable("Operand register classes are incompatible");
1772 }
1773}
1774
1775/// Return the opcode that does not set flags when possible - otherwise
1776/// return the original opcode. The caller is responsible to do the actual
1777/// substitution and legality checking.
1779 // Don't convert all compare instructions, because for some the zero register
1780 // encoding becomes the sp register.
1781 bool MIDefinesZeroReg = false;
1782 if (MI.definesRegister(AArch64::WZR, /*TRI=*/nullptr) ||
1783 MI.definesRegister(AArch64::XZR, /*TRI=*/nullptr))
1784 MIDefinesZeroReg = true;
1785
1786 switch (MI.getOpcode()) {
1787 default:
1788 return MI.getOpcode();
1789 case AArch64::ADDSWrr:
1790 return AArch64::ADDWrr;
1791 case AArch64::ADDSWri:
1792 return MIDefinesZeroReg ? AArch64::ADDSWri : AArch64::ADDWri;
1793 case AArch64::ADDSWrs:
1794 return MIDefinesZeroReg ? AArch64::ADDSWrs : AArch64::ADDWrs;
1795 case AArch64::ADDSWrx:
1796 return AArch64::ADDWrx;
1797 case AArch64::ADDSXrr:
1798 return AArch64::ADDXrr;
1799 case AArch64::ADDSXri:
1800 return MIDefinesZeroReg ? AArch64::ADDSXri : AArch64::ADDXri;
1801 case AArch64::ADDSXrs:
1802 return MIDefinesZeroReg ? AArch64::ADDSXrs : AArch64::ADDXrs;
1803 case AArch64::ADDSXrx:
1804 return AArch64::ADDXrx;
1805 case AArch64::SUBSWrr:
1806 return AArch64::SUBWrr;
1807 case AArch64::SUBSWri:
1808 return MIDefinesZeroReg ? AArch64::SUBSWri : AArch64::SUBWri;
1809 case AArch64::SUBSWrs:
1810 return MIDefinesZeroReg ? AArch64::SUBSWrs : AArch64::SUBWrs;
1811 case AArch64::SUBSWrx:
1812 return AArch64::SUBWrx;
1813 case AArch64::SUBSXrr:
1814 return AArch64::SUBXrr;
1815 case AArch64::SUBSXri:
1816 return MIDefinesZeroReg ? AArch64::SUBSXri : AArch64::SUBXri;
1817 case AArch64::SUBSXrs:
1818 return MIDefinesZeroReg ? AArch64::SUBSXrs : AArch64::SUBXrs;
1819 case AArch64::SUBSXrx:
1820 return AArch64::SUBXrx;
1821 }
1822}
1823
1824enum AccessKind { AK_Write = 0x01, AK_Read = 0x10, AK_All = 0x11 };
1825
1826/// True when condition flags are accessed (either by writing or reading)
1827/// on the instruction trace starting at From and ending at To.
1828///
1829/// Note: If From and To are from different blocks it's assumed CC are accessed
1830/// on the path.
1833 const TargetRegisterInfo *TRI, const AccessKind AccessToCheck = AK_All) {
1834 // Early exit if To is at the beginning of the BB.
1835 if (To == To->getParent()->begin())
1836 return true;
1837
1838 // Check whether the instructions are in the same basic block
1839 // If not, assume the condition flags might get modified somewhere.
1840 if (To->getParent() != From->getParent())
1841 return true;
1842
1843 // From must be above To.
1844 assert(std::any_of(
1845 ++To.getReverse(), To->getParent()->rend(),
1846 [From](MachineInstr &MI) { return MI.getIterator() == From; }));
1847
1848 // We iterate backward starting at \p To until we hit \p From.
1849 for (const MachineInstr &Instr :
1851 if (((AccessToCheck & AK_Write) &&
1852 Instr.modifiesRegister(AArch64::NZCV, TRI)) ||
1853 ((AccessToCheck & AK_Read) && Instr.readsRegister(AArch64::NZCV, TRI)))
1854 return true;
1855 }
1856 return false;
1857}
1858
1859std::optional<unsigned>
1860AArch64InstrInfo::canRemovePTestInstr(MachineInstr *PTest, MachineInstr *Mask,
1862 const MachineRegisterInfo *MRI) const {
1863 unsigned MaskOpcode = Mask->getOpcode();
1864 unsigned PredOpcode = Pred->getOpcode();
1865 bool PredIsPTestLike = isPTestLikeOpcode(PredOpcode);
1866 bool PredIsWhileLike = isWhileOpcode(PredOpcode);
1867
1868 if (PredIsWhileLike) {
1869 // For PTEST(PG, PG), PTEST is redundant when PG is the result of a WHILEcc
1870 // instruction and the condition is "any" since WHILcc does an implicit
1871 // PTEST(ALL, PG) check and PG is always a subset of ALL.
1872 if ((Mask == Pred) && PTest->getOpcode() == AArch64::PTEST_PP_ANY)
1873 return PredOpcode;
1874
1875 // For PTEST(PTRUE_ALL, WHILE), if the element size matches, the PTEST is
1876 // redundant since WHILE performs an implicit PTEST with an all active
1877 // mask.
1878 if (isPTrueOpcode(MaskOpcode) && Mask->getOperand(1).getImm() == 31 &&
1879 getElementSizeForOpcode(MaskOpcode) ==
1880 getElementSizeForOpcode(PredOpcode))
1881 return PredOpcode;
1882
1883 // For PTEST_FIRST(PTRUE_ALL, WHILE), the PTEST_FIRST is redundant since
1884 // WHILEcc performs an implicit PTEST with an all active mask, setting
1885 // the N flag as the PTEST_FIRST would.
1886 if (PTest->getOpcode() == AArch64::PTEST_PP_FIRST &&
1887 isPTrueOpcode(MaskOpcode) && Mask->getOperand(1).getImm() == 31)
1888 return PredOpcode;
1889
1890 return {};
1891 }
1892
1893 if (PredIsPTestLike) {
1894 // For PTEST(PG, PG), PTEST is redundant when PG is the result of an
1895 // instruction that sets the flags as PTEST would and the condition is
1896 // "any" since PG is always a subset of the governing predicate of the
1897 // ptest-like instruction.
1898 if ((Mask == Pred) && PTest->getOpcode() == AArch64::PTEST_PP_ANY)
1899 return PredOpcode;
1900
1901 auto PTestLikeMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
1902
1903 // If the PTEST like instruction's general predicate is not `Mask`, attempt
1904 // to look through a copy and try again. This is because some instructions
1905 // take a predicate whose register class is a subset of its result class.
1906 if (Mask != PTestLikeMask && PTestLikeMask->isFullCopy() &&
1907 PTestLikeMask->getOperand(1).getReg().isVirtual())
1908 PTestLikeMask =
1909 MRI->getUniqueVRegDef(PTestLikeMask->getOperand(1).getReg());
1910
1911 // For PTEST(PTRUE_ALL, PTEST_LIKE), the PTEST is redundant if the
1912 // the element size matches and either the PTEST_LIKE instruction uses
1913 // the same all active mask or the condition is "any".
1914 if (isPTrueOpcode(MaskOpcode) && Mask->getOperand(1).getImm() == 31 &&
1915 getElementSizeForOpcode(MaskOpcode) ==
1916 getElementSizeForOpcode(PredOpcode)) {
1917 if (Mask == PTestLikeMask || PTest->getOpcode() == AArch64::PTEST_PP_ANY)
1918 return PredOpcode;
1919 }
1920
1921 // For PTEST(PG, PTEST_LIKE(PG, ...)), the PTEST is redundant since the
1922 // flags are set based on the same mask 'PG', but PTEST_LIKE must operate
1923 // on 8-bit predicates like the PTEST. Otherwise, for instructions like
1924 // compare that also support 16/32/64-bit predicates, the implicit PTEST
1925 // performed by the compare could consider fewer lanes for these element
1926 // sizes.
1927 //
1928 // For example, consider
1929 //
1930 // ptrue p0.b ; P0=1111-1111-1111-1111
1931 // index z0.s, #0, #1 ; Z0=<0,1,2,3>
1932 // index z1.s, #1, #1 ; Z1=<1,2,3,4>
1933 // cmphi p1.s, p0/z, z1.s, z0.s ; P1=0001-0001-0001-0001
1934 // ; ^ last active
1935 // ptest p0, p1.b ; P1=0001-0001-0001-0001
1936 // ; ^ last active
1937 //
1938 // where the compare generates a canonical all active 32-bit predicate
1939 // (equivalent to 'ptrue p1.s, all'). The implicit PTEST sets the last
1940 // active flag, whereas the PTEST instruction with the same mask doesn't.
1941 // For PTEST_ANY this doesn't apply as the flags in this case would be
1942 // identical regardless of element size.
1943 uint64_t PredElementSize = getElementSizeForOpcode(PredOpcode);
1944 if (Mask == PTestLikeMask && (PredElementSize == AArch64::ElementSizeB ||
1945 PTest->getOpcode() == AArch64::PTEST_PP_ANY))
1946 return PredOpcode;
1947
1948 return {};
1949 }
1950
1951 // If OP in PTEST(PG, OP(PG, ...)) has a flag-setting variant change the
1952 // opcode so the PTEST becomes redundant.
1953 switch (PredOpcode) {
1954 case AArch64::AND_PPzPP:
1955 case AArch64::BIC_PPzPP:
1956 case AArch64::EOR_PPzPP:
1957 case AArch64::NAND_PPzPP:
1958 case AArch64::NOR_PPzPP:
1959 case AArch64::ORN_PPzPP:
1960 case AArch64::ORR_PPzPP:
1961 case AArch64::BRKA_PPzP:
1962 case AArch64::BRKPA_PPzPP:
1963 case AArch64::BRKB_PPzP:
1964 case AArch64::BRKPB_PPzPP:
1965 case AArch64::RDFFR_PPz: {
1966 // Check to see if our mask is the same. If not the resulting flag bits
1967 // may be different and we can't remove the ptest.
1968 auto *PredMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
1969 if (Mask != PredMask)
1970 return {};
1971 break;
1972 }
1973 case AArch64::BRKN_PPzP: {
1974 // BRKN uses an all active implicit mask to set flags unlike the other
1975 // flag-setting instructions.
1976 // PTEST(PTRUE_B(31), BRKN(PG, A, B)) -> BRKNS(PG, A, B).
1977 if ((MaskOpcode != AArch64::PTRUE_B) ||
1978 (Mask->getOperand(1).getImm() != 31))
1979 return {};
1980 break;
1981 }
1982 case AArch64::PTRUE_B:
1983 // PTEST(OP=PTRUE_B(A), OP) -> PTRUES_B(A)
1984 break;
1985 default:
1986 // Bail out if we don't recognize the input
1987 return {};
1988 }
1989
1990 return convertToFlagSettingOpc(PredOpcode);
1991}
1992
1993/// optimizePTestInstr - Attempt to remove a ptest of a predicate-generating
1994/// operation which could set the flags in an identical manner
1995bool AArch64InstrInfo::optimizePTestInstr(
1996 MachineInstr *PTest, unsigned MaskReg, unsigned PredReg,
1997 const MachineRegisterInfo *MRI) const {
1998 auto *Mask = MRI->getUniqueVRegDef(MaskReg);
1999 auto *Pred = MRI->getUniqueVRegDef(PredReg);
2000
2001 if (Pred->isCopy() && PTest->getOpcode() == AArch64::PTEST_PP_FIRST) {
2002 // Instructions which return a multi-vector (e.g. WHILECC_x2) require copies
2003 // before the branch to extract each subregister.
2004 auto Op = Pred->getOperand(1);
2005 if (Op.isReg() && Op.getReg().isVirtual() &&
2006 Op.getSubReg() == AArch64::psub0)
2007 Pred = MRI->getUniqueVRegDef(Op.getReg());
2008 }
2009
2010 unsigned PredOpcode = Pred->getOpcode();
2011 auto NewOp = canRemovePTestInstr(PTest, Mask, Pred, MRI);
2012 if (!NewOp)
2013 return false;
2014
2015 const TargetRegisterInfo *TRI = &getRegisterInfo();
2016
2017 // If another instruction between Pred and PTest accesses flags, don't remove
2018 // the ptest or update the earlier instruction to modify them.
2020 return false;
2021
2022 // If we pass all the checks, it's safe to remove the PTEST and use the flags
2023 // as they are prior to PTEST. Sometimes this requires the tested PTEST
2024 // operand to be replaced with an equivalent instruction that also sets the
2025 // flags.
2026 PTest->eraseFromParent();
2027 if (*NewOp != PredOpcode) {
2028 Pred->setDesc(get(*NewOp));
2030 Pred->addRegisterDefined(AArch64::NZCV, TRI);
2031 }
2032
2033 // Ensure that the flags def is live.
2034 if (Pred->registerDefIsDead(AArch64::NZCV, TRI)) {
2035 unsigned i = 0, e = Pred->getNumOperands();
2036 for (; i != e; ++i) {
2037 MachineOperand &MO = Pred->getOperand(i);
2038 if (MO.isReg() && MO.isDef() && MO.getReg() == AArch64::NZCV) {
2039 MO.setIsDead(false);
2040 break;
2041 }
2042 }
2043 }
2044 return true;
2045}
2046
2047/// Try to optimize a compare instruction. A compare instruction is an
2048/// instruction which produces AArch64::NZCV. It can be truly compare
2049/// instruction
2050/// when there are no uses of its destination register.
2051///
2052/// The following steps are tried in order:
2053/// 1. Convert CmpInstr into an unconditional version.
2054/// 2. Remove CmpInstr if above there is an instruction producing a needed
2055/// condition code or an instruction which can be converted into such an
2056/// instruction.
2057/// Only comparison with zero is supported.
2059 MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2, int64_t CmpMask,
2060 int64_t CmpValue, const MachineRegisterInfo *MRI) const {
2061 assert(CmpInstr.getParent());
2062 assert(MRI);
2063
2064 // Replace SUBSWrr with SUBWrr if NZCV is not used.
2065 int DeadNZCVIdx =
2066 CmpInstr.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true);
2067 if (DeadNZCVIdx != -1) {
2068 if (CmpInstr.definesRegister(AArch64::WZR, /*TRI=*/nullptr) ||
2069 CmpInstr.definesRegister(AArch64::XZR, /*TRI=*/nullptr)) {
2070 CmpInstr.eraseFromParent();
2071 return true;
2072 }
2073 unsigned Opc = CmpInstr.getOpcode();
2074 unsigned NewOpc = convertToNonFlagSettingOpc(CmpInstr);
2075 if (NewOpc == Opc)
2076 return false;
2077 const MCInstrDesc &MCID = get(NewOpc);
2078 CmpInstr.setDesc(MCID);
2079 CmpInstr.removeOperand(DeadNZCVIdx);
2080 updateOperandRegClass(CmpInstr);
2081 return true;
2082 }
2083
2084 if (CmpInstr.getOpcode() == AArch64::PTEST_PP ||
2085 CmpInstr.getOpcode() == AArch64::PTEST_PP_ANY ||
2086 CmpInstr.getOpcode() == AArch64::PTEST_PP_FIRST)
2087 return optimizePTestInstr(&CmpInstr, SrcReg, SrcReg2, MRI);
2088
2089 if (SrcReg2 != 0)
2090 return false;
2091
2092 // CmpInstr is a Compare instruction if destination register is not used.
2093 if (!MRI->use_nodbg_empty(CmpInstr.getOperand(0).getReg()))
2094 return false;
2095
2096 if (CmpValue == 0 && substituteCmpToZero(CmpInstr, SrcReg, *MRI))
2097 return true;
2098 return (CmpValue == 0 || CmpValue == 1) &&
2099 removeCmpToZeroOrOne(CmpInstr, SrcReg, CmpValue, *MRI);
2100}
2101
2102/// Get opcode of S version of Instr.
2103/// If Instr is S version its opcode is returned.
2104/// AArch64::INSTRUCTION_LIST_END is returned if Instr does not have S version
2105/// or we are not interested in it.
2106static unsigned sForm(MachineInstr &Instr) {
2107 switch (Instr.getOpcode()) {
2108 default:
2109 return AArch64::INSTRUCTION_LIST_END;
2110
2111 case AArch64::ADDSWrr:
2112 case AArch64::ADDSWri:
2113 case AArch64::ADDSXrr:
2114 case AArch64::ADDSXri:
2115 case AArch64::ADDSWrx:
2116 case AArch64::ADDSXrx:
2117 case AArch64::ADDSWrs:
2118 case AArch64::ADDSXrs:
2119 case AArch64::SUBSWrr:
2120 case AArch64::SUBSWri:
2121 case AArch64::SUBSWrx:
2122 case AArch64::SUBSWrs:
2123 case AArch64::SUBSXrr:
2124 case AArch64::SUBSXri:
2125 case AArch64::SUBSXrx:
2126 case AArch64::SUBSXrs:
2127 case AArch64::ANDSWri:
2128 case AArch64::ANDSWrr:
2129 case AArch64::ANDSWrs:
2130 case AArch64::ANDSXri:
2131 case AArch64::ANDSXrr:
2132 case AArch64::ANDSXrs:
2133 case AArch64::BICSWrr:
2134 case AArch64::BICSXrr:
2135 case AArch64::BICSWrs:
2136 case AArch64::BICSXrs:
2137 case AArch64::ADCSWr:
2138 case AArch64::ADCSXr:
2139 case AArch64::SBCSWr:
2140 case AArch64::SBCSXr:
2141 return Instr.getOpcode();
2142
2143 case AArch64::ADDWrr:
2144 return AArch64::ADDSWrr;
2145 case AArch64::ADDWri:
2146 return AArch64::ADDSWri;
2147 case AArch64::ADDXrr:
2148 return AArch64::ADDSXrr;
2149 case AArch64::ADDXri:
2150 return AArch64::ADDSXri;
2151 case AArch64::ADDWrx:
2152 return AArch64::ADDSWrx;
2153 case AArch64::ADDXrx:
2154 return AArch64::ADDSXrx;
2155 case AArch64::ADDWrs:
2156 return AArch64::ADDSWrs;
2157 case AArch64::ADDXrs:
2158 return AArch64::ADDSXrs;
2159 case AArch64::ADCWr:
2160 return AArch64::ADCSWr;
2161 case AArch64::ADCXr:
2162 return AArch64::ADCSXr;
2163 case AArch64::SUBWrr:
2164 return AArch64::SUBSWrr;
2165 case AArch64::SUBWri:
2166 return AArch64::SUBSWri;
2167 case AArch64::SUBXrr:
2168 return AArch64::SUBSXrr;
2169 case AArch64::SUBXri:
2170 return AArch64::SUBSXri;
2171 case AArch64::SUBWrx:
2172 return AArch64::SUBSWrx;
2173 case AArch64::SUBXrx:
2174 return AArch64::SUBSXrx;
2175 case AArch64::SUBWrs:
2176 return AArch64::SUBSWrs;
2177 case AArch64::SUBXrs:
2178 return AArch64::SUBSXrs;
2179 case AArch64::SBCWr:
2180 return AArch64::SBCSWr;
2181 case AArch64::SBCXr:
2182 return AArch64::SBCSXr;
2183 case AArch64::ANDWri:
2184 return AArch64::ANDSWri;
2185 case AArch64::ANDXri:
2186 return AArch64::ANDSXri;
2187 case AArch64::ANDWrr:
2188 return AArch64::ANDSWrr;
2189 case AArch64::ANDWrs:
2190 return AArch64::ANDSWrs;
2191 case AArch64::ANDXrr:
2192 return AArch64::ANDSXrr;
2193 case AArch64::ANDXrs:
2194 return AArch64::ANDSXrs;
2195 case AArch64::BICWrr:
2196 return AArch64::BICSWrr;
2197 case AArch64::BICXrr:
2198 return AArch64::BICSXrr;
2199 case AArch64::BICWrs:
2200 return AArch64::BICSWrs;
2201 case AArch64::BICXrs:
2202 return AArch64::BICSXrs;
2203 }
2204}
2205
2206/// Check if AArch64::NZCV should be alive in successors of MBB.
2208 for (auto *BB : MBB->successors())
2209 if (BB->isLiveIn(AArch64::NZCV))
2210 return true;
2211 return false;
2212}
2213
2214/// \returns The condition code operand index for \p Instr if it is a branch
2215/// or select and -1 otherwise.
2216int AArch64InstrInfo::findCondCodeUseOperandIdxForBranchOrSelect(
2217 const MachineInstr &Instr) {
2218 switch (Instr.getOpcode()) {
2219 default:
2220 return -1;
2221
2222 case AArch64::Bcc: {
2223 int Idx = Instr.findRegisterUseOperandIdx(AArch64::NZCV, /*TRI=*/nullptr);
2224 assert(Idx >= 2);
2225 return Idx - 2;
2226 }
2227
2228 case AArch64::CSINVWr:
2229 case AArch64::CSINVXr:
2230 case AArch64::CSINCWr:
2231 case AArch64::CSINCXr:
2232 case AArch64::CSELWr:
2233 case AArch64::CSELXr:
2234 case AArch64::CSNEGWr:
2235 case AArch64::CSNEGXr:
2236 case AArch64::FCSELSrrr:
2237 case AArch64::FCSELDrrr: {
2238 int Idx = Instr.findRegisterUseOperandIdx(AArch64::NZCV, /*TRI=*/nullptr);
2239 assert(Idx >= 1);
2240 return Idx - 1;
2241 }
2242 }
2243}
2244
2245/// Find a condition code used by the instruction.
2246/// Returns AArch64CC::Invalid if either the instruction does not use condition
2247/// codes or we don't optimize CmpInstr in the presence of such instructions.
2249 int CCIdx =
2250 AArch64InstrInfo::findCondCodeUseOperandIdxForBranchOrSelect(Instr);
2251 return CCIdx >= 0 ? static_cast<AArch64CC::CondCode>(
2252 Instr.getOperand(CCIdx).getImm())
2254}
2255
2258 UsedNZCV UsedFlags;
2259 switch (CC) {
2260 default:
2261 break;
2262
2263 case AArch64CC::EQ: // Z set
2264 case AArch64CC::NE: // Z clear
2265 UsedFlags.Z = true;
2266 break;
2267
2268 case AArch64CC::HI: // Z clear and C set
2269 case AArch64CC::LS: // Z set or C clear
2270 UsedFlags.Z = true;
2271 [[fallthrough]];
2272 case AArch64CC::HS: // C set
2273 case AArch64CC::LO: // C clear
2274 UsedFlags.C = true;
2275 break;
2276
2277 case AArch64CC::MI: // N set
2278 case AArch64CC::PL: // N clear
2279 UsedFlags.N = true;
2280 break;
2281
2282 case AArch64CC::VS: // V set
2283 case AArch64CC::VC: // V clear
2284 UsedFlags.V = true;
2285 break;
2286
2287 case AArch64CC::GT: // Z clear, N and V the same
2288 case AArch64CC::LE: // Z set, N and V differ
2289 UsedFlags.Z = true;
2290 [[fallthrough]];
2291 case AArch64CC::GE: // N and V the same
2292 case AArch64CC::LT: // N and V differ
2293 UsedFlags.N = true;
2294 UsedFlags.V = true;
2295 break;
2296 }
2297 return UsedFlags;
2298}
2299
2300/// \returns Conditions flags used after \p CmpInstr in its MachineBB if NZCV
2301/// flags are not alive in successors of the same \p CmpInstr and \p MI parent.
2302/// \returns std::nullopt otherwise.
2303///
2304/// Collect instructions using that flags in \p CCUseInstrs if provided.
2305std::optional<UsedNZCV>
2307 const TargetRegisterInfo &TRI,
2308 SmallVectorImpl<MachineInstr *> *CCUseInstrs) {
2309 MachineBasicBlock *CmpParent = CmpInstr.getParent();
2310 if (MI.getParent() != CmpParent)
2311 return std::nullopt;
2312
2313 if (areCFlagsAliveInSuccessors(CmpParent))
2314 return std::nullopt;
2315
2316 UsedNZCV NZCVUsedAfterCmp;
2318 std::next(CmpInstr.getIterator()), CmpParent->instr_end())) {
2319 if (Instr.readsRegister(AArch64::NZCV, &TRI)) {
2321 if (CC == AArch64CC::Invalid) // Unsupported conditional instruction
2322 return std::nullopt;
2323 NZCVUsedAfterCmp |= getUsedNZCV(CC);
2324 if (CCUseInstrs)
2325 CCUseInstrs->push_back(&Instr);
2326 }
2327 if (Instr.modifiesRegister(AArch64::NZCV, &TRI))
2328 break;
2329 }
2330 return NZCVUsedAfterCmp;
2331}
2332
2333static bool isADDSRegImm(unsigned Opcode) {
2334 return Opcode == AArch64::ADDSWri || Opcode == AArch64::ADDSXri;
2335}
2336
2337static bool isSUBSRegImm(unsigned Opcode) {
2338 return Opcode == AArch64::SUBSWri || Opcode == AArch64::SUBSXri;
2339}
2340
2342 unsigned Opc = sForm(MI);
2343 switch (Opc) {
2344 case AArch64::ANDSWri:
2345 case AArch64::ANDSWrr:
2346 case AArch64::ANDSWrs:
2347 case AArch64::ANDSXri:
2348 case AArch64::ANDSXrr:
2349 case AArch64::ANDSXrs:
2350 case AArch64::BICSWrr:
2351 case AArch64::BICSXrr:
2352 case AArch64::BICSWrs:
2353 case AArch64::BICSXrs:
2354 return true;
2355 default:
2356 return false;
2357 }
2358}
2359
2360/// Check if CmpInstr can be substituted by MI.
2361///
2362/// CmpInstr can be substituted:
2363/// - CmpInstr is either 'ADDS %vreg, 0' or 'SUBS %vreg, 0'
2364/// - and, MI and CmpInstr are from the same MachineBB
2365/// - and, condition flags are not alive in successors of the CmpInstr parent
2366/// - and, if MI opcode is the S form there must be no defs of flags between
2367/// MI and CmpInstr
2368/// or if MI opcode is not the S form there must be neither defs of flags
2369/// nor uses of flags between MI and CmpInstr.
2370/// - and, C is not used after CmpInstr; CmpInstr's C is from adds/subs #0 on
2371/// SrcReg and can differ from MI (e.g. carry out of ADCS/SBCS).
2372/// - and, V is not used after CmpInstr unless MI is AND/BIC (V cleared) or MI
2373/// has NoSWrap (overflow is poison and the fold is still safe).
2375 const TargetRegisterInfo &TRI) {
2376 // MI is an opcode sForm maps (add/sub/adc/sbc/and/bic and their S forms).
2377 assert(sForm(MI) != AArch64::INSTRUCTION_LIST_END);
2378
2379 const unsigned CmpOpcode = CmpInstr.getOpcode();
2380 if (!isADDSRegImm(CmpOpcode) && !isSUBSRegImm(CmpOpcode))
2381 return false;
2382
2383 assert((CmpInstr.getOperand(2).isImm() &&
2384 CmpInstr.getOperand(2).getImm() == 0) &&
2385 "Caller guarantees that CmpInstr compares with constant 0");
2386
2387 std::optional<UsedNZCV> NZVCUsed = examineCFlagsUse(MI, CmpInstr, TRI);
2388 if (!NZVCUsed || NZVCUsed->C)
2389 return false;
2390
2391 // CmpInstr is ADDS/SUBS with immediate 0 on SrcReg (compare SrcReg to zero).
2392 // After the fold, users see NZCV from MI (or its S form), not from CmpInstr.
2393 // N/Z match CmpInstr for the value in SrcReg; C/V need not match in general
2394 // (e.g. ADCS vs adds #0), so we require C unused after CmpInstr and gate V
2395 // as below. NoSWrap makes signed overflow poison; AND/BIC clear V.
2396 if (NZVCUsed->V && !MI.getFlag(MachineInstr::NoSWrap) && !isANDOpcode(MI))
2397 return false;
2398
2399 AccessKind AccessToCheck = AK_Write;
2400 if (sForm(MI) != MI.getOpcode())
2401 AccessToCheck = AK_All;
2402 return !areCFlagsAccessedBetweenInstrs(&MI, &CmpInstr, &TRI, AccessToCheck);
2403}
2404
2405/// Substitute an instruction comparing to zero with another instruction
2406/// which produces needed condition flags.
2407///
2408/// Return true on success.
2409bool AArch64InstrInfo::substituteCmpToZero(
2410 MachineInstr &CmpInstr, unsigned SrcReg,
2411 const MachineRegisterInfo &MRI) const {
2412 // Get the unique definition of SrcReg.
2413 MachineInstr *MI = MRI.getUniqueVRegDef(SrcReg);
2414 if (!MI)
2415 return false;
2416
2417 const TargetRegisterInfo &TRI = getRegisterInfo();
2418
2419 unsigned NewOpc = sForm(*MI);
2420 if (NewOpc == AArch64::INSTRUCTION_LIST_END)
2421 return false;
2422
2423 if (!canInstrSubstituteCmpInstr(*MI, CmpInstr, TRI))
2424 return false;
2425
2426 // Update the instruction to set NZCV.
2427 MI->setDesc(get(NewOpc));
2428 CmpInstr.eraseFromParent();
2430 MI->addRegisterDefined(AArch64::NZCV, &TRI);
2431 return true;
2432}
2433
2434/// \returns True if \p CmpInstr can be removed.
2435///
2436/// \p IsInvertCC is true if, after removing \p CmpInstr, condition
2437/// codes used in \p CCUseInstrs must be inverted.
2439 int CmpValue, const TargetRegisterInfo &TRI,
2441 bool &IsInvertCC) {
2442 assert((CmpValue == 0 || CmpValue == 1) &&
2443 "Only comparisons to 0 or 1 considered for removal!");
2444
2445 // MI is 'CSINCWr %vreg, wzr, wzr, <cc>' or 'CSINCXr %vreg, xzr, xzr, <cc>'
2446 unsigned MIOpc = MI.getOpcode();
2447 if (MIOpc == AArch64::CSINCWr) {
2448 if (MI.getOperand(1).getReg() != AArch64::WZR ||
2449 MI.getOperand(2).getReg() != AArch64::WZR)
2450 return false;
2451 } else if (MIOpc == AArch64::CSINCXr) {
2452 if (MI.getOperand(1).getReg() != AArch64::XZR ||
2453 MI.getOperand(2).getReg() != AArch64::XZR)
2454 return false;
2455 } else {
2456 return false;
2457 }
2459 if (MICC == AArch64CC::Invalid)
2460 return false;
2461
2462 // NZCV needs to be defined
2463 if (MI.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true) != -1)
2464 return false;
2465
2466 // CmpInstr is 'ADDS %vreg, 0' or 'SUBS %vreg, 0' or 'SUBS %vreg, 1'
2467 const unsigned CmpOpcode = CmpInstr.getOpcode();
2468 bool IsSubsRegImm = isSUBSRegImm(CmpOpcode);
2469 if (CmpValue && !IsSubsRegImm)
2470 return false;
2471 if (!CmpValue && !IsSubsRegImm && !isADDSRegImm(CmpOpcode))
2472 return false;
2473
2474 // MI conditions allowed: eq, ne, mi, pl
2475 UsedNZCV MIUsedNZCV = getUsedNZCV(MICC);
2476 if (MIUsedNZCV.C || MIUsedNZCV.V)
2477 return false;
2478
2479 std::optional<UsedNZCV> NZCVUsedAfterCmp =
2480 examineCFlagsUse(MI, CmpInstr, TRI, &CCUseInstrs);
2481 // Condition flags are not used in CmpInstr basic block successors and only
2482 // Z or N flags allowed to be used after CmpInstr within its basic block
2483 if (!NZCVUsedAfterCmp || NZCVUsedAfterCmp->C || NZCVUsedAfterCmp->V)
2484 return false;
2485 // Z or N flag used after CmpInstr must correspond to the flag used in MI
2486 if ((MIUsedNZCV.Z && NZCVUsedAfterCmp->N) ||
2487 (MIUsedNZCV.N && NZCVUsedAfterCmp->Z))
2488 return false;
2489 // If CmpInstr is comparison to zero MI conditions are limited to eq, ne
2490 if (MIUsedNZCV.N && !CmpValue)
2491 return false;
2492
2493 // There must be no defs of flags between MI and CmpInstr
2494 if (areCFlagsAccessedBetweenInstrs(&MI, &CmpInstr, &TRI, AK_Write))
2495 return false;
2496
2497 // Condition code is inverted in the following cases:
2498 // 1. MI condition is ne; CmpInstr is 'ADDS %vreg, 0' or 'SUBS %vreg, 0'
2499 // 2. MI condition is eq, pl; CmpInstr is 'SUBS %vreg, 1'
2500 IsInvertCC = (CmpValue && (MICC == AArch64CC::EQ || MICC == AArch64CC::PL)) ||
2501 (!CmpValue && MICC == AArch64CC::NE);
2502 return true;
2503}
2504
2505/// Remove comparison in csinc-cmp sequence
2506///
2507/// Examples:
2508/// 1. \code
2509/// csinc w9, wzr, wzr, ne
2510/// cmp w9, #0
2511/// b.eq
2512/// \endcode
2513/// to
2514/// \code
2515/// csinc w9, wzr, wzr, ne
2516/// b.ne
2517/// \endcode
2518///
2519/// 2. \code
2520/// csinc x2, xzr, xzr, mi
2521/// cmp x2, #1
2522/// b.pl
2523/// \endcode
2524/// to
2525/// \code
2526/// csinc x2, xzr, xzr, mi
2527/// b.pl
2528/// \endcode
2529///
2530/// \param CmpInstr comparison instruction
2531/// \return True when comparison removed
2532bool AArch64InstrInfo::removeCmpToZeroOrOne(
2533 MachineInstr &CmpInstr, unsigned SrcReg, int CmpValue,
2534 const MachineRegisterInfo &MRI) const {
2535 MachineInstr *MI = MRI.getUniqueVRegDef(SrcReg);
2536 if (!MI)
2537 return false;
2538 const TargetRegisterInfo &TRI = getRegisterInfo();
2539 SmallVector<MachineInstr *, 4> CCUseInstrs;
2540 bool IsInvertCC = false;
2541 if (!canCmpInstrBeRemoved(*MI, CmpInstr, CmpValue, TRI, CCUseInstrs,
2542 IsInvertCC))
2543 return false;
2544 // Make transformation
2545 CmpInstr.eraseFromParent();
2546 if (IsInvertCC) {
2547 // Invert condition codes in CmpInstr CC users
2548 for (MachineInstr *CCUseInstr : CCUseInstrs) {
2549 int Idx = findCondCodeUseOperandIdxForBranchOrSelect(*CCUseInstr);
2550 assert(Idx >= 0 && "Unexpected instruction using CC.");
2551 MachineOperand &CCOperand = CCUseInstr->getOperand(Idx);
2553 static_cast<AArch64CC::CondCode>(CCOperand.getImm()));
2554 CCOperand.setImm(CCUse);
2555 }
2556 }
2557 return true;
2558}
2559
2560bool AArch64InstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
2561 if (MI.getOpcode() != TargetOpcode::LOAD_STACK_GUARD &&
2562 MI.getOpcode() != AArch64::CATCHRET &&
2563 MI.getOpcode() != AArch64::STACK_GUARD_UNMIX)
2564 return false;
2565
2566 MachineBasicBlock &MBB = *MI.getParent();
2567 auto &Subtarget = MBB.getParent()->getSubtarget<AArch64Subtarget>();
2568 auto TRI = Subtarget.getRegisterInfo();
2569 DebugLoc DL = MI.getDebugLoc();
2570
2571 if (MI.getOpcode() == AArch64::STACK_GUARD_UNMIX) {
2572 // Expand STACK_GUARD_UNMIX to: sub Rd, fp, Rs
2573 // This computes FP - stored_mixed_value to unmix the cookie
2574 Register DstReg = MI.getOperand(0).getReg();
2575 Register SrcReg = MI.getOperand(1).getReg();
2576
2577 BuildMI(MBB, MI, DL, get(AArch64::SUBXrr), DstReg)
2578 .addReg(AArch64::FP)
2579 .addReg(SrcReg);
2580
2581 MBB.erase(MI);
2582 return true;
2583 }
2584
2585 if (MI.getOpcode() == AArch64::CATCHRET) {
2586 // Skip to the first instruction before the epilog.
2587 const TargetInstrInfo *TII =
2589 MachineBasicBlock *TargetMBB = MI.getOperand(0).getMBB();
2591 MachineBasicBlock::iterator FirstEpilogSEH = std::prev(MBBI);
2592 while (FirstEpilogSEH->getFlag(MachineInstr::FrameDestroy) &&
2593 FirstEpilogSEH != MBB.begin())
2594 FirstEpilogSEH = std::prev(FirstEpilogSEH);
2595 if (FirstEpilogSEH != MBB.begin())
2596 FirstEpilogSEH = std::next(FirstEpilogSEH);
2597 BuildMI(MBB, FirstEpilogSEH, DL, TII->get(AArch64::ADRP))
2598 .addReg(AArch64::X0, RegState::Define)
2599 .addMBB(TargetMBB, AArch64II::MO_PAGE);
2600 BuildMI(MBB, FirstEpilogSEH, DL, TII->get(AArch64::ADDXri))
2601 .addReg(AArch64::X0, RegState::Define)
2602 .addReg(AArch64::X0)
2604 .addImm(0);
2605 TargetMBB->setMachineBlockAddressTaken();
2606 return true;
2607 }
2608
2609 Register Reg = MI.getOperand(0).getReg();
2611 if (M.getStackProtectorGuard() == "sysreg") {
2612 const AArch64SysReg::SysReg *SrcReg =
2613 AArch64SysReg::lookupSysRegByName(M.getStackProtectorGuardReg());
2614 if (!SrcReg)
2615 report_fatal_error("Unknown SysReg for Stack Protector Guard Register");
2616
2617 // mrs xN, sysreg
2618 BuildMI(MBB, MI, DL, get(AArch64::MRS))
2620 .addImm(SrcReg->Encoding);
2621 int Offset = M.getStackProtectorGuardOffset();
2622 if (Offset >= 0 && Offset <= 32760 && Offset % 8 == 0) {
2623 // ldr xN, [xN, #offset]
2624 BuildMI(MBB, MI, DL, get(AArch64::LDRXui))
2625 .addDef(Reg)
2627 .addImm(Offset / 8);
2628 } else if (Offset >= -256 && Offset <= 255) {
2629 // ldur xN, [xN, #offset]
2630 BuildMI(MBB, MI, DL, get(AArch64::LDURXi))
2631 .addDef(Reg)
2633 .addImm(Offset);
2634 } else if (Offset >= -4095 && Offset <= 4095) {
2635 if (Offset > 0) {
2636 // add xN, xN, #offset
2637 BuildMI(MBB, MI, DL, get(AArch64::ADDXri))
2638 .addDef(Reg)
2640 .addImm(Offset)
2641 .addImm(0);
2642 } else {
2643 // sub xN, xN, #offset
2644 BuildMI(MBB, MI, DL, get(AArch64::SUBXri))
2645 .addDef(Reg)
2647 .addImm(-Offset)
2648 .addImm(0);
2649 }
2650 // ldr xN, [xN]
2651 BuildMI(MBB, MI, DL, get(AArch64::LDRXui))
2652 .addDef(Reg)
2654 .addImm(0);
2655 } else {
2656 // Cases that are larger than +/- 4095 and not a multiple of 8, or larger
2657 // than 23760.
2658 // It might be nice to use AArch64::MOVi32imm here, which would get
2659 // expanded in PreSched2 after PostRA, but our lone scratch Reg already
2660 // contains the MRS result. findScratchNonCalleeSaveRegister() in
2661 // AArch64FrameLowering might help us find such a scratch register
2662 // though. If we failed to find a scratch register, we could emit a
2663 // stream of add instructions to build up the immediate. Or, we could try
2664 // to insert a AArch64::MOVi32imm before register allocation so that we
2665 // didn't need to scavenge for a scratch register.
2666 report_fatal_error("Unable to encode Stack Protector Guard Offset");
2667 }
2668 MBB.erase(MI);
2669 return true;
2670 }
2671
2672 const GlobalValue *GV =
2673 cast<GlobalValue>((*MI.memoperands_begin())->getValue());
2674 const TargetMachine &TM = MBB.getParent()->getTarget();
2675 unsigned OpFlags = Subtarget.ClassifyGlobalReference(GV, TM);
2676 const unsigned char MO_NC = AArch64II::MO_NC;
2677
2678 unsigned GuardWidth = M.getStackProtectorGuardValueWidth().value_or(
2679 Subtarget.isTargetILP32() ? 4 : 8);
2680 if (GuardWidth != 4 && GuardWidth != 8)
2681 report_fatal_error("Unsupported stack protector value width");
2682 if ((OpFlags & AArch64II::MO_GOT) != 0) {
2683 BuildMI(MBB, MI, DL, get(AArch64::LOADgot), Reg)
2684 .addGlobalAddress(GV, 0, OpFlags);
2685 if (GuardWidth == 4) {
2686 unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
2687 BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
2688 .addDef(Reg32)
2690 .addImm(0)
2691 .addMemOperand(*MI.memoperands_begin())
2693 } else {
2694 BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
2696 .addImm(0)
2697 .addMemOperand(*MI.memoperands_begin());
2698 }
2699 } else if (TM.getCodeModel() == CodeModel::Large) {
2700 BuildMI(MBB, MI, DL, get(AArch64::MOVZXi), Reg)
2701 .addGlobalAddress(GV, 0, AArch64II::MO_G0 | MO_NC)
2702 .addImm(0);
2703 BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
2705 .addGlobalAddress(GV, 0, AArch64II::MO_G1 | MO_NC)
2706 .addImm(16);
2707 BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
2709 .addGlobalAddress(GV, 0, AArch64II::MO_G2 | MO_NC)
2710 .addImm(32);
2711 BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
2714 .addImm(48);
2715 if (GuardWidth == 4) {
2716 unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
2717 BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
2718 .addDef(Reg32)
2720 .addImm(0)
2721 .addMemOperand(*MI.memoperands_begin())
2723 } else {
2724 BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
2726 .addImm(0)
2727 .addMemOperand(*MI.memoperands_begin());
2728 }
2729 } else {
2730 BuildMI(MBB, MI, DL, get(AArch64::ADRP), Reg)
2731 .addGlobalAddress(GV, 0, OpFlags | AArch64II::MO_PAGE);
2732 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | MO_NC;
2733 if (GuardWidth == 4) {
2734 unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
2735 BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
2736 .addDef(Reg32)
2738 .addGlobalAddress(GV, 0, LoFlags)
2739 .addMemOperand(*MI.memoperands_begin())
2741 } else {
2742 BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
2744 .addGlobalAddress(GV, 0, LoFlags)
2745 .addMemOperand(*MI.memoperands_begin());
2746 }
2747 }
2748 // To match MSVC. Unlike x86_64 which uses xor instruction to mix the cookie,
2749 // we use sub instruction to mix the cookie on aarch64.
2750 // The mixing happens here in expandPostRAPseudo (after RA) to ensure we use
2751 // the final frame pointer value.
2752 if (Subtarget.getTargetTriple().isOSMSVCRT())
2753 BuildMI(MBB, MI, DL, get(AArch64::SUBXrr), Reg)
2754 .addReg(AArch64::FP)
2756
2757 MBB.erase(MI);
2758
2759 return true;
2760}
2761
2762// Return true if this instruction simply sets its single destination register
2763// to zero. This is equivalent to a register rename of the zero-register.
2765 switch (MI.getOpcode()) {
2766 default:
2767 break;
2768 case AArch64::MOVZWi:
2769 case AArch64::MOVZXi: // movz Rd, #0 (LSL #0)
2770 if (MI.getOperand(1).isImm() && MI.getOperand(1).getImm() == 0) {
2771 assert(MI.getDesc().getNumOperands() == 3 &&
2772 MI.getOperand(2).getImm() == 0 && "invalid MOVZi operands");
2773 return true;
2774 }
2775 break;
2776 case AArch64::ANDWri: // and Rd, Rzr, #imm
2777 return MI.getOperand(1).getReg() == AArch64::WZR;
2778 case AArch64::ANDXri:
2779 return MI.getOperand(1).getReg() == AArch64::XZR;
2780 case TargetOpcode::COPY:
2781 return MI.getOperand(1).getReg() == AArch64::WZR;
2782 }
2783 return false;
2784}
2785
2786// Return true if this instruction simply renames a general register without
2787// modifying bits.
2789 switch (MI.getOpcode()) {
2790 default:
2791 break;
2792 case TargetOpcode::COPY: {
2793 // GPR32 copies will by lowered to ORRXrs
2794 Register DstReg = MI.getOperand(0).getReg();
2795 return (AArch64::GPR32RegClass.contains(DstReg) ||
2796 AArch64::GPR64RegClass.contains(DstReg));
2797 }
2798 case AArch64::ORRXrs: // orr Xd, Xzr, Xm (LSL #0)
2799 if (MI.getOperand(1).getReg() == AArch64::XZR) {
2800 assert(MI.getDesc().getNumOperands() == 4 &&
2801 MI.getOperand(3).getImm() == 0 && "invalid ORRrs operands");
2802 return true;
2803 }
2804 break;
2805 case AArch64::ADDXri: // add Xd, Xn, #0 (LSL #0)
2806 if (MI.getOperand(2).getImm() == 0) {
2807 assert(MI.getDesc().getNumOperands() == 4 &&
2808 MI.getOperand(3).getImm() == 0 && "invalid ADDXri operands");
2809 return true;
2810 }
2811 break;
2812 }
2813 return false;
2814}
2815
2816// Return true if this instruction simply renames a general register without
2817// modifying bits.
2819 switch (MI.getOpcode()) {
2820 default:
2821 break;
2822 case TargetOpcode::COPY: {
2823 Register DstReg = MI.getOperand(0).getReg();
2824 return AArch64::FPR128RegClass.contains(DstReg);
2825 }
2826 case AArch64::ORRv16i8:
2827 if (MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) {
2828 assert(MI.getDesc().getNumOperands() == 3 && MI.getOperand(0).isReg() &&
2829 "invalid ORRv16i8 operands");
2830 return true;
2831 }
2832 break;
2833 }
2834 return false;
2835}
2836
2837static bool isFrameLoadOpcode(int Opcode) {
2838 switch (Opcode) {
2839 default:
2840 return false;
2841 case AArch64::LDRWui:
2842 case AArch64::LDRXui:
2843 case AArch64::LDRBui:
2844 case AArch64::LDRHui:
2845 case AArch64::LDRSui:
2846 case AArch64::LDRDui:
2847 case AArch64::LDRQui:
2848 case AArch64::LDR_PXI:
2849 return true;
2850 }
2851}
2852
2854 int &FrameIndex) const {
2855 if (!isFrameLoadOpcode(MI.getOpcode()))
2856 return Register();
2857
2858 if (MI.getOperand(0).getSubReg() == 0 && MI.getOperand(1).isFI() &&
2859 MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) {
2860 FrameIndex = MI.getOperand(1).getIndex();
2861 return MI.getOperand(0).getReg();
2862 }
2863 return Register();
2864}
2865
2866static bool isFrameStoreOpcode(int Opcode) {
2867 switch (Opcode) {
2868 default:
2869 return false;
2870 case AArch64::STRWui:
2871 case AArch64::STRXui:
2872 case AArch64::STRBui:
2873 case AArch64::STRHui:
2874 case AArch64::STRSui:
2875 case AArch64::STRDui:
2876 case AArch64::STRQui:
2877 case AArch64::STR_PXI:
2878 return true;
2879 }
2880}
2881
2883 int &FrameIndex) const {
2884 if (!isFrameStoreOpcode(MI.getOpcode()))
2885 return Register();
2886
2887 if (MI.getOperand(0).getSubReg() == 0 && MI.getOperand(1).isFI() &&
2888 MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) {
2889 FrameIndex = MI.getOperand(1).getIndex();
2890 return MI.getOperand(0).getReg();
2891 }
2892 return Register();
2893}
2894
2896 int &FrameIndex) const {
2897 if (!isFrameStoreOpcode(MI.getOpcode()))
2898 return Register();
2899
2900 if (Register Reg = isStoreToStackSlot(MI, FrameIndex))
2901 return Reg;
2902
2904 if (hasStoreToStackSlot(MI, Accesses)) {
2905 if (Accesses.size() > 1)
2906 return Register();
2907
2908 FrameIndex =
2909 cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
2910 ->getFrameIndex();
2911 return MI.getOperand(0).getReg();
2912 }
2913 return Register();
2914}
2915
2917 int &FrameIndex) const {
2918 if (!isFrameLoadOpcode(MI.getOpcode()))
2919 return Register();
2920
2921 if (Register Reg = isLoadFromStackSlot(MI, FrameIndex))
2922 return Reg;
2923
2925 if (hasLoadFromStackSlot(MI, Accesses)) {
2926 if (Accesses.size() > 1)
2927 return Register();
2928
2929 FrameIndex =
2930 cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
2931 ->getFrameIndex();
2932 return MI.getOperand(0).getReg();
2933 }
2934 return Register();
2935}
2936
2937/// Check all MachineMemOperands for a hint to suppress pairing.
2939 return llvm::any_of(MI.memoperands(), [](MachineMemOperand *MMO) {
2940 return MMO->getFlags() & MOSuppressPair;
2941 });
2942}
2943
2944/// Set a flag on the first MachineMemOperand to suppress pairing.
2946 if (MI.memoperands_empty())
2947 return;
2948 (*MI.memoperands_begin())->setFlags(MOSuppressPair);
2949}
2950
2951/// Check all MachineMemOperands for a hint that the load/store is strided.
2953 return llvm::any_of(MI.memoperands(), [](MachineMemOperand *MMO) {
2954 return MMO->getFlags() & MOStridedAccess;
2955 });
2956}
2957
2959 switch (Opc) {
2960 default:
2961 return false;
2962 case AArch64::STURSi:
2963 case AArch64::STRSpre:
2964 case AArch64::STURDi:
2965 case AArch64::STRDpre:
2966 case AArch64::STURQi:
2967 case AArch64::STRQpre:
2968 case AArch64::STURBBi:
2969 case AArch64::STURHHi:
2970 case AArch64::STURWi:
2971 case AArch64::STRWpre:
2972 case AArch64::STURXi:
2973 case AArch64::STRXpre:
2974 case AArch64::LDURSi:
2975 case AArch64::LDRSpre:
2976 case AArch64::LDURDi:
2977 case AArch64::LDRDpre:
2978 case AArch64::LDURQi:
2979 case AArch64::LDRQpre:
2980 case AArch64::LDURWi:
2981 case AArch64::LDRWpre:
2982 case AArch64::LDURXi:
2983 case AArch64::LDRXpre:
2984 case AArch64::LDRSWpre:
2985 case AArch64::LDURSWi:
2986 case AArch64::LDURHHi:
2987 case AArch64::LDURBBi:
2988 case AArch64::LDURSBWi:
2989 case AArch64::LDURSHWi:
2990 return true;
2991 }
2992}
2993
2994std::optional<unsigned> AArch64InstrInfo::getUnscaledLdSt(unsigned Opc) {
2995 switch (Opc) {
2996 default: return {};
2997 case AArch64::PRFMui: return AArch64::PRFUMi;
2998 case AArch64::LDRXui: return AArch64::LDURXi;
2999 case AArch64::LDRWui: return AArch64::LDURWi;
3000 case AArch64::LDRBui: return AArch64::LDURBi;
3001 case AArch64::LDRHui: return AArch64::LDURHi;
3002 case AArch64::LDRSui: return AArch64::LDURSi;
3003 case AArch64::LDRDui: return AArch64::LDURDi;
3004 case AArch64::LDRQui: return AArch64::LDURQi;
3005 case AArch64::LDRBBui: return AArch64::LDURBBi;
3006 case AArch64::LDRHHui: return AArch64::LDURHHi;
3007 case AArch64::LDRSBXui: return AArch64::LDURSBXi;
3008 case AArch64::LDRSBWui: return AArch64::LDURSBWi;
3009 case AArch64::LDRSHXui: return AArch64::LDURSHXi;
3010 case AArch64::LDRSHWui: return AArch64::LDURSHWi;
3011 case AArch64::LDRSWui: return AArch64::LDURSWi;
3012 case AArch64::STRXui: return AArch64::STURXi;
3013 case AArch64::STRWui: return AArch64::STURWi;
3014 case AArch64::STRBui: return AArch64::STURBi;
3015 case AArch64::STRHui: return AArch64::STURHi;
3016 case AArch64::STRSui: return AArch64::STURSi;
3017 case AArch64::STRDui: return AArch64::STURDi;
3018 case AArch64::STRQui: return AArch64::STURQi;
3019 case AArch64::STRBBui: return AArch64::STURBBi;
3020 case AArch64::STRHHui: return AArch64::STURHHi;
3021 }
3022}
3023
3025 switch (Opc) {
3026 default:
3027 llvm_unreachable("Unhandled Opcode in getLoadStoreImmIdx");
3028 case AArch64::ADDG:
3029 case AArch64::LDAPURBi:
3030 case AArch64::LDAPURHi:
3031 case AArch64::LDAPURi:
3032 case AArch64::LDAPURSBWi:
3033 case AArch64::LDAPURSBXi:
3034 case AArch64::LDAPURSHWi:
3035 case AArch64::LDAPURSHXi:
3036 case AArch64::LDAPURSWi:
3037 case AArch64::LDAPURXi:
3038 case AArch64::LDR_PPXI:
3039 case AArch64::LDR_PXI:
3040 case AArch64::LDR_ZXI:
3041 case AArch64::LDR_ZZXI:
3042 case AArch64::LDR_ZZXI_STRIDED_CONTIGUOUS:
3043 case AArch64::LDR_ZZZXI:
3044 case AArch64::LDR_ZZZZXI:
3045 case AArch64::LDR_ZZZZXI_STRIDED_CONTIGUOUS:
3046 case AArch64::LDRBBui:
3047 case AArch64::LDRBui:
3048 case AArch64::LDRDui:
3049 case AArch64::LDRHHui:
3050 case AArch64::LDRHui:
3051 case AArch64::LDRQui:
3052 case AArch64::LDRSBWui:
3053 case AArch64::LDRSBXui:
3054 case AArch64::LDRSHWui:
3055 case AArch64::LDRSHXui:
3056 case AArch64::LDRSui:
3057 case AArch64::LDRSWui:
3058 case AArch64::LDRWui:
3059 case AArch64::LDRXui:
3060 case AArch64::LDURBBi:
3061 case AArch64::LDURBi:
3062 case AArch64::LDURDi:
3063 case AArch64::LDURHHi:
3064 case AArch64::LDURHi:
3065 case AArch64::LDURQi:
3066 case AArch64::LDURSBWi:
3067 case AArch64::LDURSBXi:
3068 case AArch64::LDURSHWi:
3069 case AArch64::LDURSHXi:
3070 case AArch64::LDURSi:
3071 case AArch64::LDURSWi:
3072 case AArch64::LDURWi:
3073 case AArch64::LDURXi:
3074 case AArch64::PRFMui:
3075 case AArch64::PRFUMi:
3076 case AArch64::ST2Gi:
3077 case AArch64::STGi:
3078 case AArch64::STLURBi:
3079 case AArch64::STLURHi:
3080 case AArch64::STLURWi:
3081 case AArch64::STLURXi:
3082 case AArch64::StoreSwiftAsyncContext:
3083 case AArch64::STR_PPXI:
3084 case AArch64::STR_PXI:
3085 case AArch64::STR_ZXI:
3086 case AArch64::STR_ZZXI:
3087 case AArch64::STR_ZZXI_STRIDED_CONTIGUOUS:
3088 case AArch64::STR_ZZZXI:
3089 case AArch64::STR_ZZZZXI:
3090 case AArch64::STR_ZZZZXI_STRIDED_CONTIGUOUS:
3091 case AArch64::STRBBui:
3092 case AArch64::STRBui:
3093 case AArch64::STRDui:
3094 case AArch64::STRHHui:
3095 case AArch64::STRHui:
3096 case AArch64::STRQui:
3097 case AArch64::STRSui:
3098 case AArch64::STRWui:
3099 case AArch64::STRXui:
3100 case AArch64::STURBBi:
3101 case AArch64::STURBi:
3102 case AArch64::STURDi:
3103 case AArch64::STURHHi:
3104 case AArch64::STURHi:
3105 case AArch64::STURQi:
3106 case AArch64::STURSi:
3107 case AArch64::STURWi:
3108 case AArch64::STURXi:
3109 case AArch64::STZ2Gi:
3110 case AArch64::STZGi:
3111 case AArch64::TAGPstack:
3112 case AArch64::ATOMIC_STORE_HINT_Bi:
3113 case AArch64::ATOMIC_STORE_HINT_Hi:
3114 case AArch64::ATOMIC_STORE_HINT_Wi:
3115 case AArch64::ATOMIC_STORE_HINT_Si:
3116 case AArch64::ATOMIC_STORE_HINT_Xi:
3117 case AArch64::ATOMIC_STORE_HINT_Di:
3118 case AArch64::ATOMIC_STORE_HINT_Bui:
3119 case AArch64::ATOMIC_STORE_HINT_Hui:
3120 case AArch64::ATOMIC_STORE_HINT_Wui:
3121 case AArch64::ATOMIC_STORE_HINT_Sui:
3122 case AArch64::ATOMIC_STORE_HINT_Xui:
3123 case AArch64::ATOMIC_STORE_HINT_Dui:
3124 return 2;
3125 case AArch64::LD1B_D_IMM:
3126 case AArch64::LD1B_H_IMM:
3127 case AArch64::LD1B_IMM:
3128 case AArch64::LD1B_S_IMM:
3129 case AArch64::LD1D_IMM:
3130 case AArch64::LD1H_D_IMM:
3131 case AArch64::LD1H_IMM:
3132 case AArch64::LD1H_S_IMM:
3133 case AArch64::LD1RB_D_IMM:
3134 case AArch64::LD1RB_H_IMM:
3135 case AArch64::LD1RB_IMM:
3136 case AArch64::LD1RB_S_IMM:
3137 case AArch64::LD1RD_IMM:
3138 case AArch64::LD1RH_D_IMM:
3139 case AArch64::LD1RH_IMM:
3140 case AArch64::LD1RH_S_IMM:
3141 case AArch64::LD1RSB_D_IMM:
3142 case AArch64::LD1RSB_H_IMM:
3143 case AArch64::LD1RSB_S_IMM:
3144 case AArch64::LD1RSH_D_IMM:
3145 case AArch64::LD1RSH_S_IMM:
3146 case AArch64::LD1RSW_IMM:
3147 case AArch64::LD1RW_D_IMM:
3148 case AArch64::LD1RW_IMM:
3149 case AArch64::LD1SB_D_IMM:
3150 case AArch64::LD1SB_H_IMM:
3151 case AArch64::LD1SB_S_IMM:
3152 case AArch64::LD1SH_D_IMM:
3153 case AArch64::LD1SH_S_IMM:
3154 case AArch64::LD1SW_D_IMM:
3155 case AArch64::LD1W_D_IMM:
3156 case AArch64::LD1W_IMM:
3157 case AArch64::LD2B_IMM:
3158 case AArch64::LD2D_IMM:
3159 case AArch64::LD2H_IMM:
3160 case AArch64::LD2W_IMM:
3161 case AArch64::LD3B_IMM:
3162 case AArch64::LD3D_IMM:
3163 case AArch64::LD3H_IMM:
3164 case AArch64::LD3W_IMM:
3165 case AArch64::LD4B_IMM:
3166 case AArch64::LD4D_IMM:
3167 case AArch64::LD4H_IMM:
3168 case AArch64::LD4W_IMM:
3169 case AArch64::LDG:
3170 case AArch64::LDNF1B_D_IMM:
3171 case AArch64::LDNF1B_H_IMM:
3172 case AArch64::LDNF1B_IMM:
3173 case AArch64::LDNF1B_S_IMM:
3174 case AArch64::LDNF1D_IMM:
3175 case AArch64::LDNF1H_D_IMM:
3176 case AArch64::LDNF1H_IMM:
3177 case AArch64::LDNF1H_S_IMM:
3178 case AArch64::LDNF1SB_D_IMM:
3179 case AArch64::LDNF1SB_H_IMM:
3180 case AArch64::LDNF1SB_S_IMM:
3181 case AArch64::LDNF1SH_D_IMM:
3182 case AArch64::LDNF1SH_S_IMM:
3183 case AArch64::LDNF1SW_D_IMM:
3184 case AArch64::LDNF1W_D_IMM:
3185 case AArch64::LDNF1W_IMM:
3186 case AArch64::LDNPDi:
3187 case AArch64::LDNPQi:
3188 case AArch64::LDNPSi:
3189 case AArch64::LDNPWi:
3190 case AArch64::LDNPXi:
3191 case AArch64::LDNT1B_ZRI:
3192 case AArch64::LDNT1D_ZRI:
3193 case AArch64::LDNT1H_ZRI:
3194 case AArch64::LDNT1W_ZRI:
3195 case AArch64::LDPDi:
3196 case AArch64::LDPQi:
3197 case AArch64::LDPSi:
3198 case AArch64::LDPWi:
3199 case AArch64::LDPXi:
3200 case AArch64::LDRBBpost:
3201 case AArch64::LDRBBpre:
3202 case AArch64::LDRBpost:
3203 case AArch64::LDRBpre:
3204 case AArch64::LDRDpost:
3205 case AArch64::LDRDpre:
3206 case AArch64::LDRHHpost:
3207 case AArch64::LDRHHpre:
3208 case AArch64::LDRHpost:
3209 case AArch64::LDRHpre:
3210 case AArch64::LDRQpost:
3211 case AArch64::LDRQpre:
3212 case AArch64::LDRSpost:
3213 case AArch64::LDRSpre:
3214 case AArch64::LDRWpost:
3215 case AArch64::LDRWpre:
3216 case AArch64::LDRXpost:
3217 case AArch64::LDRXpre:
3218 case AArch64::ST1B_D_IMM:
3219 case AArch64::ST1B_H_IMM:
3220 case AArch64::ST1B_IMM:
3221 case AArch64::ST1B_S_IMM:
3222 case AArch64::ST1D_IMM:
3223 case AArch64::ST1H_D_IMM:
3224 case AArch64::ST1H_IMM:
3225 case AArch64::ST1H_S_IMM:
3226 case AArch64::ST1W_D_IMM:
3227 case AArch64::ST1W_IMM:
3228 case AArch64::ST2B_IMM:
3229 case AArch64::ST2D_IMM:
3230 case AArch64::ST2H_IMM:
3231 case AArch64::ST2W_IMM:
3232 case AArch64::ST3B_IMM:
3233 case AArch64::ST3D_IMM:
3234 case AArch64::ST3H_IMM:
3235 case AArch64::ST3W_IMM:
3236 case AArch64::ST4B_IMM:
3237 case AArch64::ST4D_IMM:
3238 case AArch64::ST4H_IMM:
3239 case AArch64::ST4W_IMM:
3240 case AArch64::STGPi:
3241 case AArch64::STGPreIndex:
3242 case AArch64::STZGPreIndex:
3243 case AArch64::ST2GPreIndex:
3244 case AArch64::STZ2GPreIndex:
3245 case AArch64::STGPostIndex:
3246 case AArch64::STZGPostIndex:
3247 case AArch64::ST2GPostIndex:
3248 case AArch64::STZ2GPostIndex:
3249 case AArch64::STNPDi:
3250 case AArch64::STNPQi:
3251 case AArch64::STNPSi:
3252 case AArch64::STNPWi:
3253 case AArch64::STNPXi:
3254 case AArch64::STNT1B_ZRI:
3255 case AArch64::STNT1D_ZRI:
3256 case AArch64::STNT1H_ZRI:
3257 case AArch64::STNT1W_ZRI:
3258 case AArch64::STPDi:
3259 case AArch64::STPQi:
3260 case AArch64::STPSi:
3261 case AArch64::STPWi:
3262 case AArch64::STPXi:
3263 case AArch64::STRBBpost:
3264 case AArch64::STRBBpre:
3265 case AArch64::STRBpost:
3266 case AArch64::STRBpre:
3267 case AArch64::STRDpost:
3268 case AArch64::STRDpre:
3269 case AArch64::STRHHpost:
3270 case AArch64::STRHHpre:
3271 case AArch64::STRHpost:
3272 case AArch64::STRHpre:
3273 case AArch64::STRQpost:
3274 case AArch64::STRQpre:
3275 case AArch64::STRSpost:
3276 case AArch64::STRSpre:
3277 case AArch64::STRWpost:
3278 case AArch64::STRWpre:
3279 case AArch64::STRXpost:
3280 case AArch64::STRXpre:
3281 case AArch64::LD1B_2Z_IMM:
3282 case AArch64::LD1B_2Z_STRIDED_IMM:
3283 case AArch64::LD1H_2Z_IMM:
3284 case AArch64::LD1H_2Z_STRIDED_IMM:
3285 case AArch64::LD1W_2Z_IMM:
3286 case AArch64::LD1W_2Z_STRIDED_IMM:
3287 case AArch64::LD1D_2Z_IMM:
3288 case AArch64::LD1D_2Z_STRIDED_IMM:
3289 case AArch64::LD1B_4Z_IMM:
3290 case AArch64::LD1B_4Z_STRIDED_IMM:
3291 case AArch64::LD1H_4Z_IMM:
3292 case AArch64::LD1H_4Z_STRIDED_IMM:
3293 case AArch64::LD1W_4Z_IMM:
3294 case AArch64::LD1W_4Z_STRIDED_IMM:
3295 case AArch64::LD1D_4Z_IMM:
3296 case AArch64::LD1D_4Z_STRIDED_IMM:
3297 case AArch64::LD1B_2Z_IMM_PSEUDO:
3298 case AArch64::LD1H_2Z_IMM_PSEUDO:
3299 case AArch64::LD1W_2Z_IMM_PSEUDO:
3300 case AArch64::LD1D_2Z_IMM_PSEUDO:
3301 case AArch64::LD1B_4Z_IMM_PSEUDO:
3302 case AArch64::LD1H_4Z_IMM_PSEUDO:
3303 case AArch64::LD1W_4Z_IMM_PSEUDO:
3304 case AArch64::LD1D_4Z_IMM_PSEUDO:
3305 case AArch64::ST1B_2Z_IMM:
3306 case AArch64::ST1B_2Z_STRIDED_IMM:
3307 case AArch64::ST1H_2Z_IMM:
3308 case AArch64::ST1H_2Z_STRIDED_IMM:
3309 case AArch64::ST1W_2Z_IMM:
3310 case AArch64::ST1W_2Z_STRIDED_IMM:
3311 case AArch64::ST1D_2Z_IMM:
3312 case AArch64::ST1D_2Z_STRIDED_IMM:
3313 case AArch64::LDNT1B_2Z_IMM_PSEUDO:
3314 case AArch64::LDNT1B_2Z_IMM:
3315 case AArch64::LDNT1B_2Z_STRIDED_IMM:
3316 case AArch64::LDNT1H_2Z_IMM_PSEUDO:
3317 case AArch64::LDNT1H_2Z_IMM:
3318 case AArch64::LDNT1H_2Z_STRIDED_IMM:
3319 case AArch64::LDNT1W_2Z_IMM_PSEUDO:
3320 case AArch64::LDNT1W_2Z_IMM:
3321 case AArch64::LDNT1W_2Z_STRIDED_IMM:
3322 case AArch64::LDNT1D_2Z_IMM_PSEUDO:
3323 case AArch64::LDNT1D_2Z_IMM:
3324 case AArch64::LDNT1D_2Z_STRIDED_IMM:
3325 case AArch64::STNT1B_2Z_IMM:
3326 case AArch64::STNT1B_2Z_STRIDED_IMM:
3327 case AArch64::STNT1H_2Z_IMM:
3328 case AArch64::STNT1H_2Z_STRIDED_IMM:
3329 case AArch64::STNT1W_2Z_IMM:
3330 case AArch64::STNT1W_2Z_STRIDED_IMM:
3331 case AArch64::STNT1D_2Z_IMM:
3332 case AArch64::STNT1D_2Z_STRIDED_IMM:
3333 case AArch64::ST1B_2Z_IMM_PSEUDO:
3334 case AArch64::ST1H_2Z_IMM_PSEUDO:
3335 case AArch64::ST1W_2Z_IMM_PSEUDO:
3336 case AArch64::ST1D_2Z_IMM_PSEUDO:
3337 case AArch64::STNT1B_2Z_IMM_PSEUDO:
3338 case AArch64::STNT1H_2Z_IMM_PSEUDO:
3339 case AArch64::STNT1W_2Z_IMM_PSEUDO:
3340 case AArch64::STNT1D_2Z_IMM_PSEUDO:
3341 case AArch64::ST1B_4Z_IMM:
3342 case AArch64::ST1B_4Z_STRIDED_IMM:
3343 case AArch64::ST1H_4Z_IMM:
3344 case AArch64::ST1H_4Z_STRIDED_IMM:
3345 case AArch64::ST1W_4Z_IMM:
3346 case AArch64::ST1W_4Z_STRIDED_IMM:
3347 case AArch64::ST1D_4Z_IMM:
3348 case AArch64::ST1D_4Z_STRIDED_IMM:
3349 case AArch64::LDNT1B_4Z_IMM_PSEUDO:
3350 case AArch64::LDNT1B_4Z_IMM:
3351 case AArch64::LDNT1B_4Z_STRIDED_IMM:
3352 case AArch64::LDNT1H_4Z_IMM_PSEUDO:
3353 case AArch64::LDNT1H_4Z_IMM:
3354 case AArch64::LDNT1H_4Z_STRIDED_IMM:
3355 case AArch64::LDNT1W_4Z_IMM_PSEUDO:
3356 case AArch64::LDNT1W_4Z_IMM:
3357 case AArch64::LDNT1W_4Z_STRIDED_IMM:
3358 case AArch64::LDNT1D_4Z_IMM_PSEUDO:
3359 case AArch64::LDNT1D_4Z_IMM:
3360 case AArch64::LDNT1D_4Z_STRIDED_IMM:
3361 case AArch64::STNT1B_4Z_IMM:
3362 case AArch64::STNT1B_4Z_STRIDED_IMM:
3363 case AArch64::STNT1H_4Z_IMM:
3364 case AArch64::STNT1H_4Z_STRIDED_IMM:
3365 case AArch64::STNT1W_4Z_IMM:
3366 case AArch64::STNT1W_4Z_STRIDED_IMM:
3367 case AArch64::STNT1D_4Z_IMM:
3368 case AArch64::STNT1D_4Z_STRIDED_IMM:
3369 case AArch64::ST1B_4Z_IMM_PSEUDO:
3370 case AArch64::ST1H_4Z_IMM_PSEUDO:
3371 case AArch64::ST1W_4Z_IMM_PSEUDO:
3372 case AArch64::ST1D_4Z_IMM_PSEUDO:
3373 case AArch64::STNT1B_4Z_IMM_PSEUDO:
3374 case AArch64::STNT1H_4Z_IMM_PSEUDO:
3375 case AArch64::STNT1W_4Z_IMM_PSEUDO:
3376 case AArch64::STNT1D_4Z_IMM_PSEUDO:
3377 return 3;
3378 case AArch64::LDPDpost:
3379 case AArch64::LDPDpre:
3380 case AArch64::LDPQpost:
3381 case AArch64::LDPQpre:
3382 case AArch64::LDPSpost:
3383 case AArch64::LDPSpre:
3384 case AArch64::LDPWpost:
3385 case AArch64::LDPWpre:
3386 case AArch64::LDPXpost:
3387 case AArch64::LDPXpre:
3388 case AArch64::STGPpre:
3389 case AArch64::STGPpost:
3390 case AArch64::STPDpost:
3391 case AArch64::STPDpre:
3392 case AArch64::STPQpost:
3393 case AArch64::STPQpre:
3394 case AArch64::STPSpost:
3395 case AArch64::STPSpre:
3396 case AArch64::STPWpost:
3397 case AArch64::STPWpre:
3398 case AArch64::STPXpost:
3399 case AArch64::STPXpre:
3400 return 4;
3401 }
3402}
3403
3405 switch (MI.getOpcode()) {
3406 default:
3407 return false;
3408 // Scaled instructions.
3409 case AArch64::STRSui:
3410 case AArch64::STRDui:
3411 case AArch64::STRQui:
3412 case AArch64::STRXui:
3413 case AArch64::STRWui:
3414 case AArch64::LDRSui:
3415 case AArch64::LDRDui:
3416 case AArch64::LDRQui:
3417 case AArch64::LDRXui:
3418 case AArch64::LDRWui:
3419 case AArch64::LDRSWui:
3420 // Unscaled instructions.
3421 case AArch64::STURSi:
3422 case AArch64::STRSpre:
3423 case AArch64::STURDi:
3424 case AArch64::STRDpre:
3425 case AArch64::STURQi:
3426 case AArch64::STRQpre:
3427 case AArch64::STURWi:
3428 case AArch64::STRWpre:
3429 case AArch64::STURXi:
3430 case AArch64::STRXpre:
3431 case AArch64::LDURSi:
3432 case AArch64::LDRSpre:
3433 case AArch64::LDURDi:
3434 case AArch64::LDRDpre:
3435 case AArch64::LDURQi:
3436 case AArch64::LDRQpre:
3437 case AArch64::LDURWi:
3438 case AArch64::LDRWpre:
3439 case AArch64::LDURXi:
3440 case AArch64::LDRXpre:
3441 case AArch64::LDURSWi:
3442 case AArch64::LDRSWpre:
3443 // SVE instructions.
3444 case AArch64::LDR_ZXI:
3445 case AArch64::STR_ZXI:
3446 return true;
3447 }
3448}
3449
3451 switch (MI.getOpcode()) {
3452 default:
3453 assert((!MI.isCall() || !MI.isReturn()) &&
3454 "Unexpected instruction - was a new tail call opcode introduced?");
3455 return false;
3456 case AArch64::TCRETURNdi:
3457 case AArch64::TCRETURNri:
3458 case AArch64::TCRETURNrix16x17:
3459 case AArch64::TCRETURNrix17:
3460 case AArch64::TCRETURNrinotx16:
3461 case AArch64::TCRETURNriALL:
3462 case AArch64::AUTH_TCRETURN:
3463 case AArch64::AUTH_TCRETURN_BTI:
3464 return true;
3465 }
3466}
3467
3469 switch (Opc) {
3470 default:
3471 llvm_unreachable("Opcode has no flag setting equivalent!");
3472 // 32-bit cases:
3473 case AArch64::ADDWri:
3474 return AArch64::ADDSWri;
3475 case AArch64::ADDWrr:
3476 return AArch64::ADDSWrr;
3477 case AArch64::ADDWrs:
3478 return AArch64::ADDSWrs;
3479 case AArch64::ADDWrx:
3480 return AArch64::ADDSWrx;
3481 case AArch64::ANDWri:
3482 return AArch64::ANDSWri;
3483 case AArch64::ANDWrr:
3484 return AArch64::ANDSWrr;
3485 case AArch64::ANDWrs:
3486 return AArch64::ANDSWrs;
3487 case AArch64::BICWrr:
3488 return AArch64::BICSWrr;
3489 case AArch64::BICWrs:
3490 return AArch64::BICSWrs;
3491 case AArch64::SUBWri:
3492 return AArch64::SUBSWri;
3493 case AArch64::SUBWrr:
3494 return AArch64::SUBSWrr;
3495 case AArch64::SUBWrs:
3496 return AArch64::SUBSWrs;
3497 case AArch64::SUBWrx:
3498 return AArch64::SUBSWrx;
3499 // 64-bit cases:
3500 case AArch64::ADDXri:
3501 return AArch64::ADDSXri;
3502 case AArch64::ADDXrr:
3503 return AArch64::ADDSXrr;
3504 case AArch64::ADDXrs:
3505 return AArch64::ADDSXrs;
3506 case AArch64::ADDXrx:
3507 return AArch64::ADDSXrx;
3508 case AArch64::ANDXri:
3509 return AArch64::ANDSXri;
3510 case AArch64::ANDXrr:
3511 return AArch64::ANDSXrr;
3512 case AArch64::ANDXrs:
3513 return AArch64::ANDSXrs;
3514 case AArch64::BICXrr:
3515 return AArch64::BICSXrr;
3516 case AArch64::BICXrs:
3517 return AArch64::BICSXrs;
3518 case AArch64::SUBXri:
3519 return AArch64::SUBSXri;
3520 case AArch64::SUBXrr:
3521 return AArch64::SUBSXrr;
3522 case AArch64::SUBXrs:
3523 return AArch64::SUBSXrs;
3524 case AArch64::SUBXrx:
3525 return AArch64::SUBSXrx;
3526 // SVE instructions:
3527 case AArch64::AND_PPzPP:
3528 return AArch64::ANDS_PPzPP;
3529 case AArch64::BIC_PPzPP:
3530 return AArch64::BICS_PPzPP;
3531 case AArch64::EOR_PPzPP:
3532 return AArch64::EORS_PPzPP;
3533 case AArch64::NAND_PPzPP:
3534 return AArch64::NANDS_PPzPP;
3535 case AArch64::NOR_PPzPP:
3536 return AArch64::NORS_PPzPP;
3537 case AArch64::ORN_PPzPP:
3538 return AArch64::ORNS_PPzPP;
3539 case AArch64::ORR_PPzPP:
3540 return AArch64::ORRS_PPzPP;
3541 case AArch64::BRKA_PPzP:
3542 return AArch64::BRKAS_PPzP;
3543 case AArch64::BRKPA_PPzPP:
3544 return AArch64::BRKPAS_PPzPP;
3545 case AArch64::BRKB_PPzP:
3546 return AArch64::BRKBS_PPzP;
3547 case AArch64::BRKPB_PPzPP:
3548 return AArch64::BRKPBS_PPzPP;
3549 case AArch64::BRKN_PPzP:
3550 return AArch64::BRKNS_PPzP;
3551 case AArch64::RDFFR_PPz:
3552 return AArch64::RDFFRS_PPz;
3553 case AArch64::PTRUE_B:
3554 return AArch64::PTRUES_B;
3555 }
3556}
3557
3558// Is this a candidate for ld/st merging or pairing? For example, we don't
3559// touch volatiles or load/stores that have a hint to avoid pair formation.
3561
3562 bool IsPreLdSt = isPreLdSt(MI);
3563
3564 // If this is a volatile load/store, don't mess with it.
3565 if (MI.hasOrderedMemoryRef())
3566 return false;
3567
3568 // Make sure this is a reg/fi+imm (as opposed to an address reloc).
3569 // For Pre-inc LD/ST, the operand is shifted by one.
3570 assert((MI.getOperand(IsPreLdSt ? 2 : 1).isReg() ||
3571 MI.getOperand(IsPreLdSt ? 2 : 1).isFI()) &&
3572 "Expected a reg or frame index operand.");
3573
3574 // For Pre-indexed addressing quadword instructions, the third operand is the
3575 // immediate value.
3576 bool IsImmPreLdSt = IsPreLdSt && MI.getOperand(3).isImm();
3577
3578 if (!MI.getOperand(2).isImm() && !IsImmPreLdSt)
3579 return false;
3580
3581 // Can't merge/pair if the instruction modifies the base register.
3582 // e.g., ldr x0, [x0]
3583 // This case will never occur with an FI base.
3584 // However, if the instruction is an LDR<S,D,Q,W,X,SW>pre or
3585 // STR<S,D,Q,W,X>pre, it can be merged.
3586 // For example:
3587 // ldr q0, [x11, #32]!
3588 // ldr q1, [x11, #16]
3589 // to
3590 // ldp q0, q1, [x11, #32]!
3591 if (MI.getOperand(1).isReg() && !IsPreLdSt) {
3592 Register BaseReg = MI.getOperand(1).getReg();
3594 if (MI.modifiesRegister(BaseReg, TRI))
3595 return false;
3596 }
3597
3598 // Pairing SVE fills/spills is only valid for little-endian targets that
3599 // implement VLS 128.
3600 switch (MI.getOpcode()) {
3601 default:
3602 break;
3603 case AArch64::LDR_ZXI:
3604 case AArch64::STR_ZXI:
3605 if (!Subtarget.isLittleEndian() ||
3606 Subtarget.getSVEVectorSizeInBits() != 128)
3607 return false;
3608 }
3609
3610 // Check if this load/store has a hint to avoid pair formation.
3611 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
3613 return false;
3614
3615 // Do not pair any callee-save store/reload instructions in the
3616 // prologue/epilogue if the CFI information encoded the operations as separate
3617 // instructions, as that will cause the size of the actual prologue to mismatch
3618 // with the prologue size recorded in the Windows CFI.
3619 if ((MI.getFlag(MachineInstr::FrameSetup) ||
3620 MI.getFlag(MachineInstr::FrameDestroy)) &&
3621 MI.getMF()->needsWinCFI())
3622 return false;
3623
3624 // On some CPUs quad load/store pairs are slower than two single load/stores.
3625 if (Subtarget.isPaired128Slow()) {
3626 switch (MI.getOpcode()) {
3627 default:
3628 break;
3629 case AArch64::LDURQi:
3630 case AArch64::STURQi:
3631 case AArch64::LDRQui:
3632 case AArch64::STRQui:
3633 return false;
3634 }
3635 }
3636
3637 return true;
3638}
3639
3642 int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width) const {
3643 if (!LdSt.mayLoadOrStore())
3644 return false;
3645
3646 const MachineOperand *BaseOp;
3647 TypeSize WidthN(0, false);
3648 if (!getMemOperandWithOffsetWidth(LdSt, BaseOp, Offset, OffsetIsScalable,
3649 WidthN))
3650 return false;
3651 // The maximum vscale is 16 under AArch64, return the maximal extent for the
3652 // vector.
3653 Width = LocationSize::precise(WidthN);
3654 BaseOps.push_back(BaseOp);
3655 return true;
3656}
3657
3658std::optional<ExtAddrMode>
3660 const MachineOperand *Base; // Filled with the base operand of MI.
3661 int64_t Offset; // Filled with the offset of MI.
3662 bool OffsetIsScalable;
3663 if (!getMemOperandWithOffset(MemI, Base, Offset, OffsetIsScalable))
3664 return std::nullopt;
3665
3666 if (!Base->isReg())
3667 return std::nullopt;
3668 ExtAddrMode AM;
3669 AM.BaseReg = Base->getReg();
3670 AM.Displacement = Offset;
3671 AM.ScaledReg = 0;
3672 AM.Scale = 0;
3673 return AM;
3674}
3675
3677 Register Reg,
3678 const MachineInstr &AddrI,
3679 ExtAddrMode &AM) const {
3680 // Filter out instructions into which we cannot fold.
3681 unsigned NumBytes;
3682 int64_t OffsetScale = 1;
3683 switch (MemI.getOpcode()) {
3684 default:
3685 return false;
3686
3687 case AArch64::LDURQi:
3688 case AArch64::STURQi:
3689 NumBytes = 16;
3690 break;
3691
3692 case AArch64::LDURDi:
3693 case AArch64::STURDi:
3694 case AArch64::LDURXi:
3695 case AArch64::STURXi:
3696 NumBytes = 8;
3697 break;
3698
3699 case AArch64::LDURSi:
3700 case AArch64::STURSi:
3701 case AArch64::LDURWi:
3702 case AArch64::LDURSWi:
3703 case AArch64::STURWi:
3704 NumBytes = 4;
3705 break;
3706
3707 case AArch64::LDURHi:
3708 case AArch64::STURHi:
3709 case AArch64::LDURHHi:
3710 case AArch64::STURHHi:
3711 case AArch64::LDURSHXi:
3712 case AArch64::LDURSHWi:
3713 NumBytes = 2;
3714 break;
3715
3716 case AArch64::LDRBroX:
3717 case AArch64::LDRBBroX:
3718 case AArch64::LDRSBXroX:
3719 case AArch64::LDRSBWroX:
3720 case AArch64::STRBroX:
3721 case AArch64::STRBBroX:
3722 case AArch64::LDURBi:
3723 case AArch64::LDURBBi:
3724 case AArch64::LDURSBXi:
3725 case AArch64::LDURSBWi:
3726 case AArch64::STURBi:
3727 case AArch64::STURBBi:
3728 case AArch64::LDRBui:
3729 case AArch64::LDRBBui:
3730 case AArch64::LDRSBXui:
3731 case AArch64::LDRSBWui:
3732 case AArch64::STRBui:
3733 case AArch64::STRBBui:
3734 NumBytes = 1;
3735 break;
3736
3737 case AArch64::LDRQroX:
3738 case AArch64::STRQroX:
3739 case AArch64::LDRQui:
3740 case AArch64::STRQui:
3741 NumBytes = 16;
3742 OffsetScale = 16;
3743 break;
3744
3745 case AArch64::LDRDroX:
3746 case AArch64::STRDroX:
3747 case AArch64::LDRXroX:
3748 case AArch64::STRXroX:
3749 case AArch64::LDRDui:
3750 case AArch64::STRDui:
3751 case AArch64::LDRXui:
3752 case AArch64::STRXui:
3753 NumBytes = 8;
3754 OffsetScale = 8;
3755 break;
3756
3757 case AArch64::LDRSroX:
3758 case AArch64::STRSroX:
3759 case AArch64::LDRWroX:
3760 case AArch64::LDRSWroX:
3761 case AArch64::STRWroX:
3762 case AArch64::LDRSui:
3763 case AArch64::STRSui:
3764 case AArch64::LDRWui:
3765 case AArch64::LDRSWui:
3766 case AArch64::STRWui:
3767 NumBytes = 4;
3768 OffsetScale = 4;
3769 break;
3770
3771 case AArch64::LDRHroX:
3772 case AArch64::STRHroX:
3773 case AArch64::LDRHHroX:
3774 case AArch64::STRHHroX:
3775 case AArch64::LDRSHXroX:
3776 case AArch64::LDRSHWroX:
3777 case AArch64::LDRHui:
3778 case AArch64::STRHui:
3779 case AArch64::LDRHHui:
3780 case AArch64::STRHHui:
3781 case AArch64::LDRSHXui:
3782 case AArch64::LDRSHWui:
3783 NumBytes = 2;
3784 OffsetScale = 2;
3785 break;
3786 }
3787
3788 // Check the fold operand is not the loaded/stored value.
3789 const MachineOperand &BaseRegOp = MemI.getOperand(0);
3790 if (BaseRegOp.isReg() && BaseRegOp.getReg() == Reg)
3791 return false;
3792
3793 // Handle memory instructions with a [Reg, Reg] addressing mode.
3794 if (MemI.getOperand(2).isReg()) {
3795 // Bail if the addressing mode already includes extension of the offset
3796 // register.
3797 if (MemI.getOperand(3).getImm())
3798 return false;
3799
3800 // Check if we actually have a scaled offset.
3801 if (MemI.getOperand(4).getImm() == 0)
3802 OffsetScale = 1;
3803
3804 // If the address instructions is folded into the base register, then the
3805 // addressing mode must not have a scale. Then we can swap the base and the
3806 // scaled registers.
3807 if (MemI.getOperand(1).getReg() == Reg && OffsetScale != 1)
3808 return false;
3809
3810 switch (AddrI.getOpcode()) {
3811 default:
3812 return false;
3813
3814 case AArch64::SBFMXri:
3815 // sxtw Xa, Wm
3816 // ldr Xd, [Xn, Xa, lsl #N]
3817 // ->
3818 // ldr Xd, [Xn, Wm, sxtw #N]
3819 if (AddrI.getOperand(2).getImm() != 0 ||
3820 AddrI.getOperand(3).getImm() != 31)
3821 return false;
3822
3823 AM.BaseReg = MemI.getOperand(1).getReg();
3824 if (AM.BaseReg == Reg)
3825 AM.BaseReg = MemI.getOperand(2).getReg();
3826 AM.ScaledReg = AddrI.getOperand(1).getReg();
3827 AM.Scale = OffsetScale;
3828 AM.Displacement = 0;
3830 return true;
3831
3832 case TargetOpcode::SUBREG_TO_REG: {
3833 // mov Wa, Wm
3834 // ldr Xd, [Xn, Xa, lsl #N]
3835 // ->
3836 // ldr Xd, [Xn, Wm, uxtw #N]
3837
3838 // Zero-extension looks like an ORRWrs followed by a SUBREG_TO_REG.
3839 if (AddrI.getOperand(2).getImm() != AArch64::sub_32)
3840 return false;
3841
3842 const MachineRegisterInfo &MRI = AddrI.getMF()->getRegInfo();
3843 Register OffsetReg = AddrI.getOperand(1).getReg();
3844 if (!OffsetReg.isVirtual() || !MRI.hasOneNonDBGUse(OffsetReg))
3845 return false;
3846
3847 const MachineInstr &DefMI = *MRI.getVRegDef(OffsetReg);
3848 if (DefMI.getOpcode() != AArch64::ORRWrs ||
3849 DefMI.getOperand(1).getReg() != AArch64::WZR ||
3850 DefMI.getOperand(3).getImm() != 0)
3851 return false;
3852
3853 AM.BaseReg = MemI.getOperand(1).getReg();
3854 if (AM.BaseReg == Reg)
3855 AM.BaseReg = MemI.getOperand(2).getReg();
3856 AM.ScaledReg = DefMI.getOperand(2).getReg();
3857 AM.Scale = OffsetScale;
3858 AM.Displacement = 0;
3860 return true;
3861 }
3862 }
3863 }
3864
3865 // Handle memory instructions with a [Reg, #Imm] addressing mode.
3866
3867 // Check we are not breaking a potential conversion to an LDP.
3868 auto validateOffsetForLDP = [](unsigned NumBytes, int64_t OldOffset,
3869 int64_t NewOffset) -> bool {
3870 int64_t MinOffset, MaxOffset;
3871 switch (NumBytes) {
3872 default:
3873 return true;
3874 case 4:
3875 MinOffset = -256;
3876 MaxOffset = 252;
3877 break;
3878 case 8:
3879 MinOffset = -512;
3880 MaxOffset = 504;
3881 break;
3882 case 16:
3883 MinOffset = -1024;
3884 MaxOffset = 1008;
3885 break;
3886 }
3887 return OldOffset < MinOffset || OldOffset > MaxOffset ||
3888 (NewOffset >= MinOffset && NewOffset <= MaxOffset);
3889 };
3890 auto canFoldAddSubImmIntoAddrMode = [&](int64_t Disp) -> bool {
3891 int64_t OldOffset = MemI.getOperand(2).getImm() * OffsetScale;
3892 int64_t NewOffset = OldOffset + Disp;
3893 if (!isLegalAddressingMode(NumBytes, NewOffset, /* Scale */ 0))
3894 return false;
3895 // If the old offset would fit into an LDP, but the new offset wouldn't,
3896 // bail out.
3897 if (!validateOffsetForLDP(NumBytes, OldOffset, NewOffset))
3898 return false;
3899 AM.BaseReg = AddrI.getOperand(1).getReg();
3900 AM.ScaledReg = 0;
3901 AM.Scale = 0;
3902 AM.Displacement = NewOffset;
3904 return true;
3905 };
3906
3907 auto canFoldAddRegIntoAddrMode =
3908 [&](int64_t Scale,
3910 if (MemI.getOperand(2).getImm() != 0)
3911 return false;
3912 if ((unsigned)Scale != Scale)
3913 return false;
3914 if (!isLegalAddressingMode(NumBytes, /* Offset */ 0, Scale))
3915 return false;
3916 AM.BaseReg = AddrI.getOperand(1).getReg();
3917 AM.ScaledReg = AddrI.getOperand(2).getReg();
3918 AM.Scale = Scale;
3919 AM.Displacement = 0;
3920 AM.Form = Form;
3921 return true;
3922 };
3923
3924 auto avoidSlowSTRQ = [&](const MachineInstr &MemI) {
3925 unsigned Opcode = MemI.getOpcode();
3926 return (Opcode == AArch64::STURQi || Opcode == AArch64::STRQui) &&
3927 Subtarget.isSTRQroSlow();
3928 };
3929
3930 int64_t Disp = 0;
3931 const bool OptSize = MemI.getMF()->getFunction().hasOptSize();
3932 switch (AddrI.getOpcode()) {
3933 default:
3934 return false;
3935
3936 case AArch64::ADDXri:
3937 // add Xa, Xn, #N
3938 // ldr Xd, [Xa, #M]
3939 // ->
3940 // ldr Xd, [Xn, #N'+M]
3941 Disp = AddrI.getOperand(2).getImm() << AddrI.getOperand(3).getImm();
3942 return canFoldAddSubImmIntoAddrMode(Disp);
3943
3944 case AArch64::SUBXri:
3945 // sub Xa, Xn, #N
3946 // ldr Xd, [Xa, #M]
3947 // ->
3948 // ldr Xd, [Xn, #N'+M]
3949 Disp = AddrI.getOperand(2).getImm() << AddrI.getOperand(3).getImm();
3950 return canFoldAddSubImmIntoAddrMode(-Disp);
3951
3952 case AArch64::ADDXrs: {
3953 // add Xa, Xn, Xm, lsl #N
3954 // ldr Xd, [Xa]
3955 // ->
3956 // ldr Xd, [Xn, Xm, lsl #N]
3957
3958 // Don't fold the add if the result would be slower, unless optimising for
3959 // size.
3960 unsigned Shift = static_cast<unsigned>(AddrI.getOperand(3).getImm());
3962 return false;
3963 Shift = AArch64_AM::getShiftValue(Shift);
3964 if (!OptSize) {
3965 if (Shift != 2 && Shift != 3 && Subtarget.hasAddrLSLSlow14())
3966 return false;
3967 if (avoidSlowSTRQ(MemI))
3968 return false;
3969 }
3970 return canFoldAddRegIntoAddrMode(1ULL << Shift);
3971 }
3972
3973 case AArch64::ADDXrr:
3974 // add Xa, Xn, Xm
3975 // ldr Xd, [Xa]
3976 // ->
3977 // ldr Xd, [Xn, Xm, lsl #0]
3978
3979 // Don't fold the add if the result would be slower, unless optimising for
3980 // size.
3981 if (!OptSize && avoidSlowSTRQ(MemI))
3982 return false;
3983 return canFoldAddRegIntoAddrMode(1);
3984
3985 case AArch64::ADDXrx:
3986 // add Xa, Xn, Wm, {s,u}xtw #N
3987 // ldr Xd, [Xa]
3988 // ->
3989 // ldr Xd, [Xn, Wm, {s,u}xtw #N]
3990
3991 // Don't fold the add if the result would be slower, unless optimising for
3992 // size.
3993 if (!OptSize && avoidSlowSTRQ(MemI))
3994 return false;
3995
3996 // Can fold only sign-/zero-extend of a word.
3997 unsigned Imm = static_cast<unsigned>(AddrI.getOperand(3).getImm());
3999 if (Extend != AArch64_AM::UXTW && Extend != AArch64_AM::SXTW)
4000 return false;
4001
4002 return canFoldAddRegIntoAddrMode(
4006 }
4007}
4008
4009// Given an opcode for an instruction with a [Reg, #Imm] addressing mode,
4010// return the opcode of an instruction performing the same operation, but using
4011// the [Reg, Reg] addressing mode.
4012static unsigned regOffsetOpcode(unsigned Opcode) {
4013 switch (Opcode) {
4014 default:
4015 llvm_unreachable("Address folding not implemented for instruction");
4016
4017 case AArch64::LDURQi:
4018 case AArch64::LDRQui:
4019 return AArch64::LDRQroX;
4020 case AArch64::STURQi:
4021 case AArch64::STRQui:
4022 return AArch64::STRQroX;
4023 case AArch64::LDURDi:
4024 case AArch64::LDRDui:
4025 return AArch64::LDRDroX;
4026 case AArch64::STURDi:
4027 case AArch64::STRDui:
4028 return AArch64::STRDroX;
4029 case AArch64::LDURXi:
4030 case AArch64::LDRXui:
4031 return AArch64::LDRXroX;
4032 case AArch64::STURXi:
4033 case AArch64::STRXui:
4034 return AArch64::STRXroX;
4035 case AArch64::LDURSi:
4036 case AArch64::LDRSui:
4037 return AArch64::LDRSroX;
4038 case AArch64::STURSi:
4039 case AArch64::STRSui:
4040 return AArch64::STRSroX;
4041 case AArch64::LDURWi:
4042 case AArch64::LDRWui:
4043 return AArch64::LDRWroX;
4044 case AArch64::LDURSWi:
4045 case AArch64::LDRSWui:
4046 return AArch64::LDRSWroX;
4047 case AArch64::STURWi:
4048 case AArch64::STRWui:
4049 return AArch64::STRWroX;
4050 case AArch64::LDURHi:
4051 case AArch64::LDRHui:
4052 return AArch64::LDRHroX;
4053 case AArch64::STURHi:
4054 case AArch64::STRHui:
4055 return AArch64::STRHroX;
4056 case AArch64::LDURHHi:
4057 case AArch64::LDRHHui:
4058 return AArch64::LDRHHroX;
4059 case AArch64::STURHHi:
4060 case AArch64::STRHHui:
4061 return AArch64::STRHHroX;
4062 case AArch64::LDURSHXi:
4063 case AArch64::LDRSHXui:
4064 return AArch64::LDRSHXroX;
4065 case AArch64::LDURSHWi:
4066 case AArch64::LDRSHWui:
4067 return AArch64::LDRSHWroX;
4068 case AArch64::LDURBi:
4069 case AArch64::LDRBui:
4070 return AArch64::LDRBroX;
4071 case AArch64::LDURBBi:
4072 case AArch64::LDRBBui:
4073 return AArch64::LDRBBroX;
4074 case AArch64::LDURSBXi:
4075 case AArch64::LDRSBXui:
4076 return AArch64::LDRSBXroX;
4077 case AArch64::LDURSBWi:
4078 case AArch64::LDRSBWui:
4079 return AArch64::LDRSBWroX;
4080 case AArch64::STURBi:
4081 case AArch64::STRBui:
4082 return AArch64::STRBroX;
4083 case AArch64::STURBBi:
4084 case AArch64::STRBBui:
4085 return AArch64::STRBBroX;
4086 }
4087}
4088
4089// Given an opcode for an instruction with a [Reg, #Imm] addressing mode, return
4090// the opcode of an instruction performing the same operation, but using the
4091// [Reg, #Imm] addressing mode with scaled offset.
4092unsigned scaledOffsetOpcode(unsigned Opcode, unsigned &Scale) {
4093 switch (Opcode) {
4094 default:
4095 llvm_unreachable("Address folding not implemented for instruction");
4096
4097 case AArch64::LDURQi:
4098 Scale = 16;
4099 return AArch64::LDRQui;
4100 case AArch64::STURQi:
4101 Scale = 16;
4102 return AArch64::STRQui;
4103 case AArch64::LDURDi:
4104 Scale = 8;
4105 return AArch64::LDRDui;
4106 case AArch64::STURDi:
4107 Scale = 8;
4108 return AArch64::STRDui;
4109 case AArch64::LDURXi:
4110 Scale = 8;
4111 return AArch64::LDRXui;
4112 case AArch64::STURXi:
4113 Scale = 8;
4114 return AArch64::STRXui;
4115 case AArch64::LDURSi:
4116 Scale = 4;
4117 return AArch64::LDRSui;
4118 case AArch64::STURSi:
4119 Scale = 4;
4120 return AArch64::STRSui;
4121 case AArch64::LDURWi:
4122 Scale = 4;
4123 return AArch64::LDRWui;
4124 case AArch64::LDURSWi:
4125 Scale = 4;
4126 return AArch64::LDRSWui;
4127 case AArch64::STURWi:
4128 Scale = 4;
4129 return AArch64::STRWui;
4130 case AArch64::LDURHi:
4131 Scale = 2;
4132 return AArch64::LDRHui;
4133 case AArch64::STURHi:
4134 Scale = 2;
4135 return AArch64::STRHui;
4136 case AArch64::LDURHHi:
4137 Scale = 2;
4138 return AArch64::LDRHHui;
4139 case AArch64::STURHHi:
4140 Scale = 2;
4141 return AArch64::STRHHui;
4142 case AArch64::LDURSHXi:
4143 Scale = 2;
4144 return AArch64::LDRSHXui;
4145 case AArch64::LDURSHWi:
4146 Scale = 2;
4147 return AArch64::LDRSHWui;
4148 case AArch64::LDURBi:
4149 Scale = 1;
4150 return AArch64::LDRBui;
4151 case AArch64::LDURBBi:
4152 Scale = 1;
4153 return AArch64::LDRBBui;
4154 case AArch64::LDURSBXi:
4155 Scale = 1;
4156 return AArch64::LDRSBXui;
4157 case AArch64::LDURSBWi:
4158 Scale = 1;
4159 return AArch64::LDRSBWui;
4160 case AArch64::STURBi:
4161 Scale = 1;
4162 return AArch64::STRBui;
4163 case AArch64::STURBBi:
4164 Scale = 1;
4165 return AArch64::STRBBui;
4166 case AArch64::LDRQui:
4167 case AArch64::STRQui:
4168 Scale = 16;
4169 return Opcode;
4170 case AArch64::LDRDui:
4171 case AArch64::STRDui:
4172 case AArch64::LDRXui:
4173 case AArch64::STRXui:
4174 Scale = 8;
4175 return Opcode;
4176 case AArch64::LDRSui:
4177 case AArch64::STRSui:
4178 case AArch64::LDRWui:
4179 case AArch64::LDRSWui:
4180 case AArch64::STRWui:
4181 Scale = 4;
4182 return Opcode;
4183 case AArch64::LDRHui:
4184 case AArch64::STRHui:
4185 case AArch64::LDRHHui:
4186 case AArch64::STRHHui:
4187 case AArch64::LDRSHXui:
4188 case AArch64::LDRSHWui:
4189 Scale = 2;
4190 return Opcode;
4191 case AArch64::LDRBui:
4192 case AArch64::LDRBBui:
4193 case AArch64::LDRSBXui:
4194 case AArch64::LDRSBWui:
4195 case AArch64::STRBui:
4196 case AArch64::STRBBui:
4197 Scale = 1;
4198 return Opcode;
4199 }
4200}
4201
4202// Given an opcode for an instruction with a [Reg, #Imm] addressing mode, return
4203// the opcode of an instruction performing the same operation, but using the
4204// [Reg, #Imm] addressing mode with unscaled offset.
4205unsigned unscaledOffsetOpcode(unsigned Opcode) {
4206 switch (Opcode) {
4207 default:
4208 llvm_unreachable("Address folding not implemented for instruction");
4209
4210 case AArch64::LDURQi:
4211 case AArch64::STURQi:
4212 case AArch64::LDURDi:
4213 case AArch64::STURDi:
4214 case AArch64::LDURXi:
4215 case AArch64::STURXi:
4216 case AArch64::LDURSi:
4217 case AArch64::STURSi:
4218 case AArch64::LDURWi:
4219 case AArch64::LDURSWi:
4220 case AArch64::STURWi:
4221 case AArch64::LDURHi:
4222 case AArch64::STURHi:
4223 case AArch64::LDURHHi:
4224 case AArch64::STURHHi:
4225 case AArch64::LDURSHXi:
4226 case AArch64::LDURSHWi:
4227 case AArch64::LDURBi:
4228 case AArch64::STURBi:
4229 case AArch64::LDURBBi:
4230 case AArch64::STURBBi:
4231 case AArch64::LDURSBWi:
4232 case AArch64::LDURSBXi:
4233 return Opcode;
4234 case AArch64::LDRQui:
4235 return AArch64::LDURQi;
4236 case AArch64::STRQui:
4237 return AArch64::STURQi;
4238 case AArch64::LDRDui:
4239 return AArch64::LDURDi;
4240 case AArch64::STRDui:
4241 return AArch64::STURDi;
4242 case AArch64::LDRXui:
4243 return AArch64::LDURXi;
4244 case AArch64::STRXui:
4245 return AArch64::STURXi;
4246 case AArch64::LDRSui:
4247 return AArch64::LDURSi;
4248 case AArch64::STRSui:
4249 return AArch64::STURSi;
4250 case AArch64::LDRWui:
4251 return AArch64::LDURWi;
4252 case AArch64::LDRSWui:
4253 return AArch64::LDURSWi;
4254 case AArch64::STRWui:
4255 return AArch64::STURWi;
4256 case AArch64::LDRHui:
4257 return AArch64::LDURHi;
4258 case AArch64::STRHui:
4259 return AArch64::STURHi;
4260 case AArch64::LDRHHui:
4261 return AArch64::LDURHHi;
4262 case AArch64::STRHHui:
4263 return AArch64::STURHHi;
4264 case AArch64::LDRSHXui:
4265 return AArch64::LDURSHXi;
4266 case AArch64::LDRSHWui:
4267 return AArch64::LDURSHWi;
4268 case AArch64::LDRBBui:
4269 return AArch64::LDURBBi;
4270 case AArch64::LDRBui:
4271 return AArch64::LDURBi;
4272 case AArch64::STRBBui:
4273 return AArch64::STURBBi;
4274 case AArch64::STRBui:
4275 return AArch64::STURBi;
4276 case AArch64::LDRSBWui:
4277 return AArch64::LDURSBWi;
4278 case AArch64::LDRSBXui:
4279 return AArch64::LDURSBXi;
4280 }
4281}
4282
4283// Given the opcode of a memory load/store instruction, return the opcode of an
4284// instruction performing the same operation, but using
4285// the [Reg, Reg, {s,u}xtw #N] addressing mode with sign-/zero-extend of the
4286// offset register.
4287static unsigned offsetExtendOpcode(unsigned Opcode) {
4288 switch (Opcode) {
4289 default:
4290 llvm_unreachable("Address folding not implemented for instruction");
4291
4292 case AArch64::LDRQroX:
4293 case AArch64::LDURQi:
4294 case AArch64::LDRQui:
4295 return AArch64::LDRQroW;
4296 case AArch64::STRQroX:
4297 case AArch64::STURQi:
4298 case AArch64::STRQui:
4299 return AArch64::STRQroW;
4300 case AArch64::LDRDroX:
4301 case AArch64::LDURDi:
4302 case AArch64::LDRDui:
4303 return AArch64::LDRDroW;
4304 case AArch64::STRDroX:
4305 case AArch64::STURDi:
4306 case AArch64::STRDui:
4307 return AArch64::STRDroW;
4308 case AArch64::LDRXroX:
4309 case AArch64::LDURXi:
4310 case AArch64::LDRXui:
4311 return AArch64::LDRXroW;
4312 case AArch64::STRXroX:
4313 case AArch64::STURXi:
4314 case AArch64::STRXui:
4315 return AArch64::STRXroW;
4316 case AArch64::LDRSroX:
4317 case AArch64::LDURSi:
4318 case AArch64::LDRSui:
4319 return AArch64::LDRSroW;
4320 case AArch64::STRSroX:
4321 case AArch64::STURSi:
4322 case AArch64::STRSui:
4323 return AArch64::STRSroW;
4324 case AArch64::LDRWroX:
4325 case AArch64::LDURWi:
4326 case AArch64::LDRWui:
4327 return AArch64::LDRWroW;
4328 case AArch64::LDRSWroX:
4329 case AArch64::LDURSWi:
4330 case AArch64::LDRSWui:
4331 return AArch64::LDRSWroW;
4332 case AArch64::STRWroX:
4333 case AArch64::STURWi:
4334 case AArch64::STRWui:
4335 return AArch64::STRWroW;
4336 case AArch64::LDRHroX:
4337 case AArch64::LDURHi:
4338 case AArch64::LDRHui:
4339 return AArch64::LDRHroW;
4340 case AArch64::STRHroX:
4341 case AArch64::STURHi:
4342 case AArch64::STRHui:
4343 return AArch64::STRHroW;
4344 case AArch64::LDRHHroX:
4345 case AArch64::LDURHHi:
4346 case AArch64::LDRHHui:
4347 return AArch64::LDRHHroW;
4348 case AArch64::STRHHroX:
4349 case AArch64::STURHHi:
4350 case AArch64::STRHHui:
4351 return AArch64::STRHHroW;
4352 case AArch64::LDRSHXroX:
4353 case AArch64::LDURSHXi:
4354 case AArch64::LDRSHXui:
4355 return AArch64::LDRSHXroW;
4356 case AArch64::LDRSHWroX:
4357 case AArch64::LDURSHWi:
4358 case AArch64::LDRSHWui:
4359 return AArch64::LDRSHWroW;
4360 case AArch64::LDRBroX:
4361 case AArch64::LDURBi:
4362 case AArch64::LDRBui:
4363 return AArch64::LDRBroW;
4364 case AArch64::LDRBBroX:
4365 case AArch64::LDURBBi:
4366 case AArch64::LDRBBui:
4367 return AArch64::LDRBBroW;
4368 case AArch64::LDRSBXroX:
4369 case AArch64::LDURSBXi:
4370 case AArch64::LDRSBXui:
4371 return AArch64::LDRSBXroW;
4372 case AArch64::LDRSBWroX:
4373 case AArch64::LDURSBWi:
4374 case AArch64::LDRSBWui:
4375 return AArch64::LDRSBWroW;
4376 case AArch64::STRBroX:
4377 case AArch64::STURBi:
4378 case AArch64::STRBui:
4379 return AArch64::STRBroW;
4380 case AArch64::STRBBroX:
4381 case AArch64::STURBBi:
4382 case AArch64::STRBBui:
4383 return AArch64::STRBBroW;
4384 }
4385}
4386
4388 const ExtAddrMode &AM) const {
4389
4390 const DebugLoc &DL = MemI.getDebugLoc();
4391 MachineBasicBlock &MBB = *MemI.getParent();
4393
4395 if (AM.ScaledReg) {
4396 // The new instruction will be in the form `ldr Rt, [Xn, Xm, lsl #imm]`.
4397 unsigned Opcode = regOffsetOpcode(MemI.getOpcode());
4398 MRI.constrainRegClass(AM.BaseReg, &AArch64::GPR64spRegClass);
4399 auto B = BuildMI(MBB, MemI, DL, get(Opcode))
4400 .addReg(MemI.getOperand(0).getReg(),
4401 getDefRegState(MemI.mayLoad()))
4402 .addReg(AM.BaseReg)
4403 .addReg(AM.ScaledReg)
4404 .addImm(0)
4405 .addImm(AM.Scale > 1)
4406 .setMemRefs(MemI.memoperands())
4407 .setMIFlags(MemI.getFlags());
4408 return B.getInstr();
4409 }
4410
4411 assert(AM.ScaledReg == 0 && AM.Scale == 0 &&
4412 "Addressing mode not supported for folding");
4413
4414 // The new instruction will be in the form `ld[u]r Rt, [Xn, #imm]`.
4415 unsigned Scale = 1;
4416 unsigned Opcode = MemI.getOpcode();
4417 if (isInt<9>(AM.Displacement))
4418 Opcode = unscaledOffsetOpcode(Opcode);
4419 else
4420 Opcode = scaledOffsetOpcode(Opcode, Scale);
4421
4422 auto B =
4423 BuildMI(MBB, MemI, DL, get(Opcode))
4424 .addReg(MemI.getOperand(0).getReg(), getDefRegState(MemI.mayLoad()))
4425 .addReg(AM.BaseReg)
4426 .addImm(AM.Displacement / Scale)
4427 .setMemRefs(MemI.memoperands())
4428 .setMIFlags(MemI.getFlags());
4429 return B.getInstr();
4430 }
4431
4434 // The new instruction will be in the form `ldr Rt, [Xn, Wm, {s,u}xtw #N]`.
4435 assert(AM.ScaledReg && !AM.Displacement &&
4436 "Address offset can be a register or an immediate, but not both");
4437 unsigned Opcode = offsetExtendOpcode(MemI.getOpcode());
4438 MRI.constrainRegClass(AM.BaseReg, &AArch64::GPR64spRegClass);
4439 // Make sure the offset register is in the correct register class.
4440 Register OffsetReg = AM.ScaledReg;
4441 const TargetRegisterClass *RC = MRI.getRegClass(OffsetReg);
4442 if (RC->hasSuperClassEq(&AArch64::GPR64RegClass)) {
4443 OffsetReg = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
4444 BuildMI(MBB, MemI, DL, get(TargetOpcode::COPY), OffsetReg)
4445 .addReg(AM.ScaledReg, {}, AArch64::sub_32);
4446 }
4447 auto B =
4448 BuildMI(MBB, MemI, DL, get(Opcode))
4449 .addReg(MemI.getOperand(0).getReg(), getDefRegState(MemI.mayLoad()))
4450 .addReg(AM.BaseReg)
4451 .addReg(OffsetReg)
4453 .addImm(AM.Scale != 1)
4454 .setMemRefs(MemI.memoperands())
4455 .setMIFlags(MemI.getFlags());
4456
4457 return B.getInstr();
4458 }
4459
4461 "Function must not be called with an addressing mode it can't handle");
4462}
4463
4464/// Return true if the opcode is a post-index ld/st instruction, which really
4465/// loads from base+0.
4466static bool isPostIndexLdStOpcode(unsigned Opcode) {
4467 switch (Opcode) {
4468 default:
4469 return false;
4470 case AArch64::LD1Fourv16b_POST:
4471 case AArch64::LD1Fourv1d_POST:
4472 case AArch64::LD1Fourv2d_POST:
4473 case AArch64::LD1Fourv2s_POST:
4474 case AArch64::LD1Fourv4h_POST:
4475 case AArch64::LD1Fourv4s_POST:
4476 case AArch64::LD1Fourv8b_POST:
4477 case AArch64::LD1Fourv8h_POST:
4478 case AArch64::LD1Onev16b_POST:
4479 case AArch64::LD1Onev1d_POST:
4480 case AArch64::LD1Onev2d_POST:
4481 case AArch64::LD1Onev2s_POST:
4482 case AArch64::LD1Onev4h_POST:
4483 case AArch64::LD1Onev4s_POST:
4484 case AArch64::LD1Onev8b_POST:
4485 case AArch64::LD1Onev8h_POST:
4486 case AArch64::LD1Rv16b_POST:
4487 case AArch64::LD1Rv1d_POST:
4488 case AArch64::LD1Rv2d_POST:
4489 case AArch64::LD1Rv2s_POST:
4490 case AArch64::LD1Rv4h_POST:
4491 case AArch64::LD1Rv4s_POST:
4492 case AArch64::LD1Rv8b_POST:
4493 case AArch64::LD1Rv8h_POST:
4494 case AArch64::LD1Threev16b_POST:
4495 case AArch64::LD1Threev1d_POST:
4496 case AArch64::LD1Threev2d_POST:
4497 case AArch64::LD1Threev2s_POST:
4498 case AArch64::LD1Threev4h_POST:
4499 case AArch64::LD1Threev4s_POST:
4500 case AArch64::LD1Threev8b_POST:
4501 case AArch64::LD1Threev8h_POST:
4502 case AArch64::LD1Twov16b_POST:
4503 case AArch64::LD1Twov1d_POST:
4504 case AArch64::LD1Twov2d_POST:
4505 case AArch64::LD1Twov2s_POST:
4506 case AArch64::LD1Twov4h_POST:
4507 case AArch64::LD1Twov4s_POST:
4508 case AArch64::LD1Twov8b_POST:
4509 case AArch64::LD1Twov8h_POST:
4510 case AArch64::LD1i16_POST:
4511 case AArch64::LD1i32_POST:
4512 case AArch64::LD1i64_POST:
4513 case AArch64::LD1i8_POST:
4514 case AArch64::LD2Rv16b_POST:
4515 case AArch64::LD2Rv1d_POST:
4516 case AArch64::LD2Rv2d_POST:
4517 case AArch64::LD2Rv2s_POST:
4518 case AArch64::LD2Rv4h_POST:
4519 case AArch64::LD2Rv4s_POST:
4520 case AArch64::LD2Rv8b_POST:
4521 case AArch64::LD2Rv8h_POST:
4522 case AArch64::LD2Twov16b_POST:
4523 case AArch64::LD2Twov2d_POST:
4524 case AArch64::LD2Twov2s_POST:
4525 case AArch64::LD2Twov4h_POST:
4526 case AArch64::LD2Twov4s_POST:
4527 case AArch64::LD2Twov8b_POST:
4528 case AArch64::LD2Twov8h_POST:
4529 case AArch64::LD2i16_POST:
4530 case AArch64::LD2i32_POST:
4531 case AArch64::LD2i64_POST:
4532 case AArch64::LD2i8_POST:
4533 case AArch64::LD3Rv16b_POST:
4534 case AArch64::LD3Rv1d_POST:
4535 case AArch64::LD3Rv2d_POST:
4536 case AArch64::LD3Rv2s_POST:
4537 case AArch64::LD3Rv4h_POST:
4538 case AArch64::LD3Rv4s_POST:
4539 case AArch64::LD3Rv8b_POST:
4540 case AArch64::LD3Rv8h_POST:
4541 case AArch64::LD3Threev16b_POST:
4542 case AArch64::LD3Threev2d_POST:
4543 case AArch64::LD3Threev2s_POST:
4544 case AArch64::LD3Threev4h_POST:
4545 case AArch64::LD3Threev4s_POST:
4546 case AArch64::LD3Threev8b_POST:
4547 case AArch64::LD3Threev8h_POST:
4548 case AArch64::LD3i16_POST:
4549 case AArch64::LD3i32_POST:
4550 case AArch64::LD3i64_POST:
4551 case AArch64::LD3i8_POST:
4552 case AArch64::LD4Fourv16b_POST:
4553 case AArch64::LD4Fourv2d_POST:
4554 case AArch64::LD4Fourv2s_POST:
4555 case AArch64::LD4Fourv4h_POST:
4556 case AArch64::LD4Fourv4s_POST:
4557 case AArch64::LD4Fourv8b_POST:
4558 case AArch64::LD4Fourv8h_POST:
4559 case AArch64::LD4Rv16b_POST:
4560 case AArch64::LD4Rv1d_POST:
4561 case AArch64::LD4Rv2d_POST:
4562 case AArch64::LD4Rv2s_POST:
4563 case AArch64::LD4Rv4h_POST:
4564 case AArch64::LD4Rv4s_POST:
4565 case AArch64::LD4Rv8b_POST:
4566 case AArch64::LD4Rv8h_POST:
4567 case AArch64::LD4i16_POST:
4568 case AArch64::LD4i32_POST:
4569 case AArch64::LD4i64_POST:
4570 case AArch64::LD4i8_POST:
4571 case AArch64::LDAPRWpost:
4572 case AArch64::LDAPRXpost:
4573 case AArch64::LDIAPPWpost:
4574 case AArch64::LDIAPPXpost:
4575 case AArch64::LDPDpost:
4576 case AArch64::LDPQpost:
4577 case AArch64::LDPSWpost:
4578 case AArch64::LDPSpost:
4579 case AArch64::LDPWpost:
4580 case AArch64::LDPXpost:
4581 case AArch64::LDRBBpost:
4582 case AArch64::LDRBpost:
4583 case AArch64::LDRDpost:
4584 case AArch64::LDRHHpost:
4585 case AArch64::LDRHpost:
4586 case AArch64::LDRQpost:
4587 case AArch64::LDRSBWpost:
4588 case AArch64::LDRSBXpost:
4589 case AArch64::LDRSHWpost:
4590 case AArch64::LDRSHXpost:
4591 case AArch64::LDRSWpost:
4592 case AArch64::LDRSpost:
4593 case AArch64::LDRWpost:
4594 case AArch64::LDRXpost:
4595 case AArch64::ST1Fourv16b_POST:
4596 case AArch64::ST1Fourv1d_POST:
4597 case AArch64::ST1Fourv2d_POST:
4598 case AArch64::ST1Fourv2s_POST:
4599 case AArch64::ST1Fourv4h_POST:
4600 case AArch64::ST1Fourv4s_POST:
4601 case AArch64::ST1Fourv8b_POST:
4602 case AArch64::ST1Fourv8h_POST:
4603 case AArch64::ST1Onev16b_POST:
4604 case AArch64::ST1Onev1d_POST:
4605 case AArch64::ST1Onev2d_POST:
4606 case AArch64::ST1Onev2s_POST:
4607 case AArch64::ST1Onev4h_POST:
4608 case AArch64::ST1Onev4s_POST:
4609 case AArch64::ST1Onev8b_POST:
4610 case AArch64::ST1Onev8h_POST:
4611 case AArch64::ST1Threev16b_POST:
4612 case AArch64::ST1Threev1d_POST:
4613 case AArch64::ST1Threev2d_POST:
4614 case AArch64::ST1Threev2s_POST:
4615 case AArch64::ST1Threev4h_POST:
4616 case AArch64::ST1Threev4s_POST:
4617 case AArch64::ST1Threev8b_POST:
4618 case AArch64::ST1Threev8h_POST:
4619 case AArch64::ST1Twov16b_POST:
4620 case AArch64::ST1Twov1d_POST:
4621 case AArch64::ST1Twov2d_POST:
4622 case AArch64::ST1Twov2s_POST:
4623 case AArch64::ST1Twov4h_POST:
4624 case AArch64::ST1Twov4s_POST:
4625 case AArch64::ST1Twov8b_POST:
4626 case AArch64::ST1Twov8h_POST:
4627 case AArch64::ST1i16_POST:
4628 case AArch64::ST1i32_POST:
4629 case AArch64::ST1i64_POST:
4630 case AArch64::ST1i8_POST:
4631 case AArch64::ST2GPostIndex:
4632 case AArch64::ST2Twov16b_POST:
4633 case AArch64::ST2Twov2d_POST:
4634 case AArch64::ST2Twov2s_POST:
4635 case AArch64::ST2Twov4h_POST:
4636 case AArch64::ST2Twov4s_POST:
4637 case AArch64::ST2Twov8b_POST:
4638 case AArch64::ST2Twov8h_POST:
4639 case AArch64::ST2i16_POST:
4640 case AArch64::ST2i32_POST:
4641 case AArch64::ST2i64_POST:
4642 case AArch64::ST2i8_POST:
4643 case AArch64::ST3Threev16b_POST:
4644 case AArch64::ST3Threev2d_POST:
4645 case AArch64::ST3Threev2s_POST:
4646 case AArch64::ST3Threev4h_POST:
4647 case AArch64::ST3Threev4s_POST:
4648 case AArch64::ST3Threev8b_POST:
4649 case AArch64::ST3Threev8h_POST:
4650 case AArch64::ST3i16_POST:
4651 case AArch64::ST3i32_POST:
4652 case AArch64::ST3i64_POST:
4653 case AArch64::ST3i8_POST:
4654 case AArch64::ST4Fourv16b_POST:
4655 case AArch64::ST4Fourv2d_POST:
4656 case AArch64::ST4Fourv2s_POST:
4657 case AArch64::ST4Fourv4h_POST:
4658 case AArch64::ST4Fourv4s_POST:
4659 case AArch64::ST4Fourv8b_POST:
4660 case AArch64::ST4Fourv8h_POST:
4661 case AArch64::ST4i16_POST:
4662 case AArch64::ST4i32_POST:
4663 case AArch64::ST4i64_POST:
4664 case AArch64::ST4i8_POST:
4665 case AArch64::STGPostIndex:
4666 case AArch64::STGPpost:
4667 case AArch64::STPDpost:
4668 case AArch64::STPQpost:
4669 case AArch64::STPSpost:
4670 case AArch64::STPWpost:
4671 case AArch64::STPXpost:
4672 case AArch64::STRBBpost:
4673 case AArch64::STRBpost:
4674 case AArch64::STRDpost:
4675 case AArch64::STRHHpost:
4676 case AArch64::STRHpost:
4677 case AArch64::STRQpost:
4678 case AArch64::STRSpost:
4679 case AArch64::STRWpost:
4680 case AArch64::STRXpost:
4681 case AArch64::STZ2GPostIndex:
4682 case AArch64::STZGPostIndex:
4683 return true;
4684 }
4685}
4686
4688 const MachineInstr &LdSt, const MachineOperand *&BaseOp, int64_t &Offset,
4689 bool &OffsetIsScalable, TypeSize &Width) const {
4690 assert(LdSt.mayLoadOrStore() && "Expected a memory operation.");
4691 // Handle only loads/stores with base register followed by immediate offset.
4692 if (LdSt.getNumExplicitOperands() == 3) {
4693 // Non-paired instruction (e.g., ldr x1, [x0, #8]).
4694 if ((!LdSt.getOperand(1).isReg() && !LdSt.getOperand(1).isFI()) ||
4695 !LdSt.getOperand(2).isImm())
4696 return false;
4697 } else if (LdSt.getNumExplicitOperands() == 4) {
4698 // Paired instruction (e.g., ldp x1, x2, [x0, #8]).
4699 if (!LdSt.getOperand(1).isReg() ||
4700 (!LdSt.getOperand(2).isReg() && !LdSt.getOperand(2).isFI()) ||
4701 !LdSt.getOperand(3).isImm())
4702 return false;
4703 } else
4704 return false;
4705
4706 // Get the scaling factor for the instruction and set the width for the
4707 // instruction.
4708 TypeSize Scale(0U, false);
4709 int64_t Dummy1, Dummy2;
4710
4711 // If this returns false, then it's an instruction we don't want to handle.
4712 if (!getMemOpInfo(LdSt.getOpcode(), Scale, Width, Dummy1, Dummy2))
4713 return false;
4714
4715 // Compute the offset. Offset is calculated as the immediate operand
4716 // multiplied by the scaling factor. Unscaled instructions have scaling factor
4717 // set to 1. Postindex are a special case which have an offset of 0.
4718 if (isPostIndexLdStOpcode(LdSt.getOpcode())) {
4719 BaseOp = &LdSt.getOperand(2);
4720 Offset = 0;
4721 } else if (LdSt.getNumExplicitOperands() == 3) {
4722 BaseOp = &LdSt.getOperand(1);
4723 Offset = LdSt.getOperand(2).getImm() * Scale.getKnownMinValue();
4724 } else {
4725 assert(LdSt.getNumExplicitOperands() == 4 && "invalid number of operands");
4726 BaseOp = &LdSt.getOperand(2);
4727 Offset = LdSt.getOperand(3).getImm() * Scale.getKnownMinValue();
4728 }
4729 OffsetIsScalable = Scale.isScalable();
4730
4731 return BaseOp->isReg() || BaseOp->isFI();
4732}
4733
4736 assert(LdSt.mayLoadOrStore() && "Expected a memory operation.");
4737 MachineOperand &OfsOp = LdSt.getOperand(LdSt.getNumExplicitOperands() - 1);
4738 assert(OfsOp.isImm() && "Offset operand wasn't immediate.");
4739 return OfsOp;
4740}
4741
4742bool AArch64InstrInfo::getMemOpInfo(unsigned Opcode, TypeSize &Scale,
4743 TypeSize &Width, int64_t &MinOffset,
4744 int64_t &MaxOffset) {
4745 switch (Opcode) {
4746 // Not a memory operation or something we want to handle.
4747 default:
4748 Scale = Width = TypeSize::getFixed(0);
4749 MinOffset = MaxOffset = 0;
4750 return false;
4751 // LDR / STR
4752 case AArch64::LDRQui:
4753 case AArch64::STRQui:
4754 Scale = Width = TypeSize::getFixed(16);
4755 MinOffset = 0;
4756 MaxOffset = 4095;
4757 break;
4758 case AArch64::LDRXui:
4759 case AArch64::LDRDui:
4760 case AArch64::STRXui:
4761 case AArch64::STRDui:
4762 case AArch64::PRFMui:
4763 case AArch64::ATOMIC_STORE_HINT_Xui:
4764 case AArch64::ATOMIC_STORE_HINT_Dui:
4765 Scale = Width = TypeSize::getFixed(8);
4766 MinOffset = 0;
4767 MaxOffset = 4095;
4768 break;
4769 case AArch64::LDRWui:
4770 case AArch64::LDRSui:
4771 case AArch64::LDRSWui:
4772 case AArch64::STRWui:
4773 case AArch64::STRSui:
4774 case AArch64::ATOMIC_STORE_HINT_Wui:
4775 case AArch64::ATOMIC_STORE_HINT_Sui:
4776 Scale = Width = TypeSize::getFixed(4);
4777 MinOffset = 0;
4778 MaxOffset = 4095;
4779 break;
4780 case AArch64::LDRHui:
4781 case AArch64::LDRHHui:
4782 case AArch64::LDRSHWui:
4783 case AArch64::LDRSHXui:
4784 case AArch64::STRHui:
4785 case AArch64::STRHHui:
4786 case AArch64::ATOMIC_STORE_HINT_Hui:
4787 Scale = Width = TypeSize::getFixed(2);
4788 MinOffset = 0;
4789 MaxOffset = 4095;
4790 break;
4791 case AArch64::LDRBui:
4792 case AArch64::LDRBBui:
4793 case AArch64::LDRSBWui:
4794 case AArch64::LDRSBXui:
4795 case AArch64::STRBui:
4796 case AArch64::STRBBui:
4797 case AArch64::ATOMIC_STORE_HINT_Bui:
4798 Scale = Width = TypeSize::getFixed(1);
4799 MinOffset = 0;
4800 MaxOffset = 4095;
4801 break;
4802 // post/pre inc
4803 case AArch64::STRQpre:
4804 case AArch64::LDRQpost:
4805 Scale = TypeSize::getFixed(1);
4806 Width = TypeSize::getFixed(16);
4807 MinOffset = -256;
4808 MaxOffset = 255;
4809 break;
4810 case AArch64::LDRDpost:
4811 case AArch64::LDRDpre:
4812 case AArch64::LDRXpost:
4813 case AArch64::LDRXpre:
4814 case AArch64::STRDpost:
4815 case AArch64::STRDpre:
4816 case AArch64::STRXpost:
4817 case AArch64::STRXpre:
4818 Scale = TypeSize::getFixed(1);
4819 Width = TypeSize::getFixed(8);
4820 MinOffset = -256;
4821 MaxOffset = 255;
4822 break;
4823 case AArch64::STRWpost:
4824 case AArch64::STRWpre:
4825 case AArch64::LDRWpost:
4826 case AArch64::LDRWpre:
4827 case AArch64::STRSpost:
4828 case AArch64::STRSpre:
4829 case AArch64::LDRSpost:
4830 case AArch64::LDRSpre:
4831 Scale = TypeSize::getFixed(1);
4832 Width = TypeSize::getFixed(4);
4833 MinOffset = -256;
4834 MaxOffset = 255;
4835 break;
4836 case AArch64::LDRHpost:
4837 case AArch64::LDRHpre:
4838 case AArch64::STRHpost:
4839 case AArch64::STRHpre:
4840 case AArch64::LDRHHpost:
4841 case AArch64::LDRHHpre:
4842 case AArch64::STRHHpost:
4843 case AArch64::STRHHpre:
4844 Scale = TypeSize::getFixed(1);
4845 Width = TypeSize::getFixed(2);
4846 MinOffset = -256;
4847 MaxOffset = 255;
4848 break;
4849 case AArch64::LDRBpost:
4850 case AArch64::LDRBpre:
4851 case AArch64::STRBpost:
4852 case AArch64::STRBpre:
4853 case AArch64::LDRBBpost:
4854 case AArch64::LDRBBpre:
4855 case AArch64::STRBBpost:
4856 case AArch64::STRBBpre:
4857 Scale = Width = TypeSize::getFixed(1);
4858 MinOffset = -256;
4859 MaxOffset = 255;
4860 break;
4861 // Unscaled
4862 case AArch64::LDURQi:
4863 case AArch64::STURQi:
4864 Scale = TypeSize::getFixed(1);
4865 Width = TypeSize::getFixed(16);
4866 MinOffset = -256;
4867 MaxOffset = 255;
4868 break;
4869 case AArch64::LDURXi:
4870 case AArch64::LDURDi:
4871 case AArch64::LDAPURXi:
4872 case AArch64::STURXi:
4873 case AArch64::STURDi:
4874 case AArch64::STLURXi:
4875 case AArch64::PRFUMi:
4876 case AArch64::ATOMIC_STORE_HINT_Xi:
4877 case AArch64::ATOMIC_STORE_HINT_Di:
4878 Scale = TypeSize::getFixed(1);
4879 Width = TypeSize::getFixed(8);
4880 MinOffset = -256;
4881 MaxOffset = 255;
4882 break;
4883 case AArch64::LDURWi:
4884 case AArch64::LDURSi:
4885 case AArch64::LDURSWi:
4886 case AArch64::LDAPURi:
4887 case AArch64::LDAPURSWi:
4888 case AArch64::STURWi:
4889 case AArch64::STURSi:
4890 case AArch64::STLURWi:
4891 case AArch64::ATOMIC_STORE_HINT_Wi:
4892 case AArch64::ATOMIC_STORE_HINT_Si:
4893 Scale = TypeSize::getFixed(1);
4894 Width = TypeSize::getFixed(4);
4895 MinOffset = -256;
4896 MaxOffset = 255;
4897 break;
4898 case AArch64::LDURHi:
4899 case AArch64::LDURHHi:
4900 case AArch64::LDURSHXi:
4901 case AArch64::LDURSHWi:
4902 case AArch64::LDAPURHi:
4903 case AArch64::LDAPURSHWi:
4904 case AArch64::LDAPURSHXi:
4905 case AArch64::STURHi:
4906 case AArch64::STURHHi:
4907 case AArch64::STLURHi:
4908 case AArch64::ATOMIC_STORE_HINT_Hi:
4909 Scale = TypeSize::getFixed(1);
4910 Width = TypeSize::getFixed(2);
4911 MinOffset = -256;
4912 MaxOffset = 255;
4913 break;
4914 case AArch64::LDURBi:
4915 case AArch64::LDURBBi:
4916 case AArch64::LDURSBXi:
4917 case AArch64::LDURSBWi:
4918 case AArch64::LDAPURBi:
4919 case AArch64::LDAPURSBWi:
4920 case AArch64::LDAPURSBXi:
4921 case AArch64::STURBi:
4922 case AArch64::STURBBi:
4923 case AArch64::STLURBi:
4924 case AArch64::ATOMIC_STORE_HINT_Bi:
4925 Scale = Width = TypeSize::getFixed(1);
4926 MinOffset = -256;
4927 MaxOffset = 255;
4928 break;
4929 // LDP / STP (including pre/post inc)
4930 case AArch64::LDPQi:
4931 case AArch64::LDNPQi:
4932 case AArch64::STPQi:
4933 case AArch64::STNPQi:
4934 case AArch64::LDPQpost:
4935 case AArch64::LDPQpre:
4936 case AArch64::STPQpost:
4937 case AArch64::STPQpre:
4938 Scale = TypeSize::getFixed(16);
4939 Width = TypeSize::getFixed(16 * 2);
4940 MinOffset = -64;
4941 MaxOffset = 63;
4942 break;
4943 case AArch64::LDPXi:
4944 case AArch64::LDPDi:
4945 case AArch64::LDNPXi:
4946 case AArch64::LDNPDi:
4947 case AArch64::STPXi:
4948 case AArch64::STPDi:
4949 case AArch64::STNPXi:
4950 case AArch64::STNPDi:
4951 case AArch64::LDPDpost:
4952 case AArch64::LDPDpre:
4953 case AArch64::LDPXpost:
4954 case AArch64::LDPXpre:
4955 case AArch64::STPDpost:
4956 case AArch64::STPDpre:
4957 case AArch64::STPXpost:
4958 case AArch64::STPXpre:
4959 Scale = TypeSize::getFixed(8);
4960 Width = TypeSize::getFixed(8 * 2);
4961 MinOffset = -64;
4962 MaxOffset = 63;
4963 break;
4964 case AArch64::LDPWi:
4965 case AArch64::LDPSi:
4966 case AArch64::LDNPWi:
4967 case AArch64::LDNPSi:
4968 case AArch64::STPWi:
4969 case AArch64::STPSi:
4970 case AArch64::STNPWi:
4971 case AArch64::STNPSi:
4972 case AArch64::LDPSpost:
4973 case AArch64::LDPSpre:
4974 case AArch64::LDPWpost:
4975 case AArch64::LDPWpre:
4976 case AArch64::STPSpost:
4977 case AArch64::STPSpre:
4978 case AArch64::STPWpost:
4979 case AArch64::STPWpre:
4980 Scale = TypeSize::getFixed(4);
4981 Width = TypeSize::getFixed(4 * 2);
4982 MinOffset = -64;
4983 MaxOffset = 63;
4984 break;
4985 case AArch64::StoreSwiftAsyncContext:
4986 // Store is an STRXui, but there might be an ADDXri in the expansion too.
4987 Scale = TypeSize::getFixed(1);
4988 Width = TypeSize::getFixed(8);
4989 MinOffset = 0;
4990 MaxOffset = 4095;
4991 break;
4992 case AArch64::ADDG:
4993 Scale = TypeSize::getFixed(16);
4994 Width = TypeSize::getFixed(0);
4995 MinOffset = 0;
4996 MaxOffset = 63;
4997 break;
4998 case AArch64::TAGPstack:
4999 Scale = TypeSize::getFixed(16);
5000 Width = TypeSize::getFixed(0);
5001 // TAGP with a negative offset turns into SUBP, which has a maximum offset
5002 // of 63 (not 64!).
5003 MinOffset = -63;
5004 MaxOffset = 63;
5005 break;
5006 case AArch64::LDG:
5007 case AArch64::STGi:
5008 case AArch64::STGPreIndex:
5009 case AArch64::STGPostIndex:
5010 case AArch64::STZGi:
5011 case AArch64::STZGPreIndex:
5012 case AArch64::STZGPostIndex:
5013 Scale = Width = TypeSize::getFixed(16);
5014 MinOffset = -256;
5015 MaxOffset = 255;
5016 break;
5017 // SVE
5018 case AArch64::STR_ZZZZXI:
5019 case AArch64::STR_ZZZZXI_STRIDED_CONTIGUOUS:
5020 case AArch64::LDR_ZZZZXI:
5021 case AArch64::LDR_ZZZZXI_STRIDED_CONTIGUOUS:
5022 Scale = TypeSize::getScalable(16);
5023 Width = TypeSize::getScalable(16 * 4);
5024 MinOffset = -256;
5025 MaxOffset = 252;
5026 break;
5027 case AArch64::STR_ZZZXI:
5028 case AArch64::LDR_ZZZXI:
5029 Scale = TypeSize::getScalable(16);
5030 Width = TypeSize::getScalable(16 * 3);
5031 MinOffset = -256;
5032 MaxOffset = 253;
5033 break;
5034 case AArch64::STR_ZZXI:
5035 case AArch64::STR_ZZXI_STRIDED_CONTIGUOUS:
5036 case AArch64::LDR_ZZXI:
5037 case AArch64::LDR_ZZXI_STRIDED_CONTIGUOUS:
5038 Scale = TypeSize::getScalable(16);
5039 Width = TypeSize::getScalable(16 * 2);
5040 MinOffset = -256;
5041 MaxOffset = 254;
5042 break;
5043 case AArch64::LDR_PXI:
5044 case AArch64::STR_PXI:
5045 Scale = Width = TypeSize::getScalable(2);
5046 MinOffset = -256;
5047 MaxOffset = 255;
5048 break;
5049 case AArch64::LDR_PPXI:
5050 case AArch64::STR_PPXI:
5051 Scale = TypeSize::getScalable(2);
5052 Width = TypeSize::getScalable(2 * 2);
5053 MinOffset = -256;
5054 MaxOffset = 254;
5055 break;
5056 case AArch64::LDR_ZXI:
5057 case AArch64::STR_ZXI:
5058 Scale = Width = TypeSize::getScalable(16);
5059 MinOffset = -256;
5060 MaxOffset = 255;
5061 break;
5062 case AArch64::LD1B_IMM:
5063 case AArch64::LD1H_IMM:
5064 case AArch64::LD1W_IMM:
5065 case AArch64::LD1D_IMM:
5066 case AArch64::LDNT1B_ZRI:
5067 case AArch64::LDNT1H_ZRI:
5068 case AArch64::LDNT1W_ZRI:
5069 case AArch64::LDNT1D_ZRI:
5070 case AArch64::ST1B_IMM:
5071 case AArch64::ST1H_IMM:
5072 case AArch64::ST1W_IMM:
5073 case AArch64::ST1D_IMM:
5074 case AArch64::STNT1B_ZRI:
5075 case AArch64::STNT1H_ZRI:
5076 case AArch64::STNT1W_ZRI:
5077 case AArch64::STNT1D_ZRI:
5078 case AArch64::LDNF1B_IMM:
5079 case AArch64::LDNF1H_IMM:
5080 case AArch64::LDNF1W_IMM:
5081 case AArch64::LDNF1D_IMM:
5082 // A full vectors worth of data
5083 // Width = mbytes * elements
5084 Scale = Width = TypeSize::getScalable(16);
5085 MinOffset = -8;
5086 MaxOffset = 7;
5087 break;
5088 case AArch64::LD2B_IMM:
5089 case AArch64::LD2H_IMM:
5090 case AArch64::LD2W_IMM:
5091 case AArch64::LD2D_IMM:
5092 case AArch64::ST2B_IMM:
5093 case AArch64::ST2H_IMM:
5094 case AArch64::ST2W_IMM:
5095 case AArch64::ST2D_IMM:
5096 case AArch64::LD1B_2Z_IMM:
5097 case AArch64::LD1B_2Z_STRIDED_IMM:
5098 case AArch64::LD1H_2Z_IMM:
5099 case AArch64::LD1H_2Z_STRIDED_IMM:
5100 case AArch64::LD1W_2Z_IMM:
5101 case AArch64::LD1W_2Z_STRIDED_IMM:
5102 case AArch64::LD1D_2Z_IMM:
5103 case AArch64::LD1D_2Z_STRIDED_IMM:
5104 case AArch64::LD1B_2Z_IMM_PSEUDO:
5105 case AArch64::LD1H_2Z_IMM_PSEUDO:
5106 case AArch64::LD1W_2Z_IMM_PSEUDO:
5107 case AArch64::LD1D_2Z_IMM_PSEUDO:
5108 case AArch64::ST1B_2Z_IMM:
5109 case AArch64::ST1B_2Z_STRIDED_IMM:
5110 case AArch64::ST1H_2Z_IMM:
5111 case AArch64::ST1H_2Z_STRIDED_IMM:
5112 case AArch64::ST1W_2Z_IMM:
5113 case AArch64::ST1W_2Z_STRIDED_IMM:
5114 case AArch64::ST1D_2Z_IMM:
5115 case AArch64::ST1D_2Z_STRIDED_IMM:
5116 case AArch64::LDNT1B_2Z_IMM_PSEUDO:
5117 case AArch64::LDNT1B_2Z_IMM:
5118 case AArch64::LDNT1B_2Z_STRIDED_IMM:
5119 case AArch64::LDNT1H_2Z_IMM_PSEUDO:
5120 case AArch64::LDNT1H_2Z_IMM:
5121 case AArch64::LDNT1H_2Z_STRIDED_IMM:
5122 case AArch64::LDNT1W_2Z_IMM_PSEUDO:
5123 case AArch64::LDNT1W_2Z_IMM:
5124 case AArch64::LDNT1W_2Z_STRIDED_IMM:
5125 case AArch64::LDNT1D_2Z_IMM_PSEUDO:
5126 case AArch64::LDNT1D_2Z_IMM:
5127 case AArch64::LDNT1D_2Z_STRIDED_IMM:
5128 case AArch64::STNT1B_2Z_IMM:
5129 case AArch64::STNT1B_2Z_STRIDED_IMM:
5130 case AArch64::STNT1H_2Z_IMM:
5131 case AArch64::STNT1H_2Z_STRIDED_IMM:
5132 case AArch64::STNT1W_2Z_IMM:
5133 case AArch64::STNT1W_2Z_STRIDED_IMM:
5134 case AArch64::STNT1D_2Z_IMM:
5135 case AArch64::STNT1D_2Z_STRIDED_IMM:
5136 case AArch64::ST1B_2Z_IMM_PSEUDO:
5137 case AArch64::ST1H_2Z_IMM_PSEUDO:
5138 case AArch64::ST1W_2Z_IMM_PSEUDO:
5139 case AArch64::ST1D_2Z_IMM_PSEUDO:
5140 case AArch64::STNT1B_2Z_IMM_PSEUDO:
5141 case AArch64::STNT1H_2Z_IMM_PSEUDO:
5142 case AArch64::STNT1W_2Z_IMM_PSEUDO:
5143 case AArch64::STNT1D_2Z_IMM_PSEUDO:
5144 Scale = Width = TypeSize::getScalable(16 * 2);
5145 MinOffset = -8;
5146 MaxOffset = 7;
5147 break;
5148 case AArch64::LD3B_IMM:
5149 case AArch64::LD3H_IMM:
5150 case AArch64::LD3W_IMM:
5151 case AArch64::LD3D_IMM:
5152 case AArch64::ST3B_IMM:
5153 case AArch64::ST3H_IMM:
5154 case AArch64::ST3W_IMM:
5155 case AArch64::ST3D_IMM:
5156 Scale = Width = TypeSize::getScalable(16 * 3);
5157 MinOffset = -8;
5158 MaxOffset = 7;
5159 break;
5160 case AArch64::LD4B_IMM:
5161 case AArch64::LD4H_IMM:
5162 case AArch64::LD4W_IMM:
5163 case AArch64::LD4D_IMM:
5164 case AArch64::ST4B_IMM:
5165 case AArch64::ST4H_IMM:
5166 case AArch64::ST4W_IMM:
5167 case AArch64::ST4D_IMM:
5168 case AArch64::LD1B_4Z_IMM:
5169 case AArch64::LD1B_4Z_STRIDED_IMM:
5170 case AArch64::LD1H_4Z_IMM:
5171 case AArch64::LD1H_4Z_STRIDED_IMM:
5172 case AArch64::LD1W_4Z_IMM:
5173 case AArch64::LD1W_4Z_STRIDED_IMM:
5174 case AArch64::LD1D_4Z_IMM:
5175 case AArch64::LD1D_4Z_STRIDED_IMM:
5176 case AArch64::LD1B_4Z_IMM_PSEUDO:
5177 case AArch64::LD1H_4Z_IMM_PSEUDO:
5178 case AArch64::LD1W_4Z_IMM_PSEUDO:
5179 case AArch64::LD1D_4Z_IMM_PSEUDO:
5180 case AArch64::ST1B_4Z_IMM:
5181 case AArch64::ST1B_4Z_STRIDED_IMM:
5182 case AArch64::ST1H_4Z_IMM:
5183 case AArch64::ST1H_4Z_STRIDED_IMM:
5184 case AArch64::ST1W_4Z_IMM:
5185 case AArch64::ST1W_4Z_STRIDED_IMM:
5186 case AArch64::ST1D_4Z_IMM:
5187 case AArch64::ST1D_4Z_STRIDED_IMM:
5188 case AArch64::LDNT1B_4Z_IMM_PSEUDO:
5189 case AArch64::LDNT1B_4Z_IMM:
5190 case AArch64::LDNT1B_4Z_STRIDED_IMM:
5191 case AArch64::LDNT1H_4Z_IMM_PSEUDO:
5192 case AArch64::LDNT1H_4Z_IMM:
5193 case AArch64::LDNT1H_4Z_STRIDED_IMM:
5194 case AArch64::LDNT1W_4Z_IMM_PSEUDO:
5195 case AArch64::LDNT1W_4Z_IMM:
5196 case AArch64::LDNT1W_4Z_STRIDED_IMM:
5197 case AArch64::LDNT1D_4Z_IMM_PSEUDO:
5198 case AArch64::LDNT1D_4Z_IMM:
5199 case AArch64::LDNT1D_4Z_STRIDED_IMM:
5200 case AArch64::STNT1B_4Z_IMM:
5201 case AArch64::STNT1B_4Z_STRIDED_IMM:
5202 case AArch64::STNT1H_4Z_IMM:
5203 case AArch64::STNT1H_4Z_STRIDED_IMM:
5204 case AArch64::STNT1W_4Z_IMM:
5205 case AArch64::STNT1W_4Z_STRIDED_IMM:
5206 case AArch64::STNT1D_4Z_IMM:
5207 case AArch64::STNT1D_4Z_STRIDED_IMM:
5208 case AArch64::ST1B_4Z_IMM_PSEUDO:
5209 case AArch64::ST1H_4Z_IMM_PSEUDO:
5210 case AArch64::ST1W_4Z_IMM_PSEUDO:
5211 case AArch64::ST1D_4Z_IMM_PSEUDO:
5212 case AArch64::STNT1B_4Z_IMM_PSEUDO:
5213 case AArch64::STNT1H_4Z_IMM_PSEUDO:
5214 case AArch64::STNT1W_4Z_IMM_PSEUDO:
5215 case AArch64::STNT1D_4Z_IMM_PSEUDO:
5216 Scale = Width = TypeSize::getScalable(16 * 4);
5217 MinOffset = -8;
5218 MaxOffset = 7;
5219 break;
5220 case AArch64::LD1B_H_IMM:
5221 case AArch64::LD1SB_H_IMM:
5222 case AArch64::LD1H_S_IMM:
5223 case AArch64::LD1SH_S_IMM:
5224 case AArch64::LD1W_D_IMM:
5225 case AArch64::LD1SW_D_IMM:
5226 case AArch64::ST1B_H_IMM:
5227 case AArch64::ST1H_S_IMM:
5228 case AArch64::ST1W_D_IMM:
5229 case AArch64::LDNF1B_H_IMM:
5230 case AArch64::LDNF1SB_H_IMM:
5231 case AArch64::LDNF1H_S_IMM:
5232 case AArch64::LDNF1SH_S_IMM:
5233 case AArch64::LDNF1W_D_IMM:
5234 case AArch64::LDNF1SW_D_IMM:
5235 // A half vector worth of data
5236 // Width = mbytes * elements
5237 Scale = Width = TypeSize::getScalable(8);
5238 MinOffset = -8;
5239 MaxOffset = 7;
5240 break;
5241 case AArch64::LD1B_S_IMM:
5242 case AArch64::LD1SB_S_IMM:
5243 case AArch64::LD1H_D_IMM:
5244 case AArch64::LD1SH_D_IMM:
5245 case AArch64::ST1B_S_IMM:
5246 case AArch64::ST1H_D_IMM:
5247 case AArch64::LDNF1B_S_IMM:
5248 case AArch64::LDNF1SB_S_IMM:
5249 case AArch64::LDNF1H_D_IMM:
5250 case AArch64::LDNF1SH_D_IMM:
5251 // A quarter vector worth of data
5252 // Width = mbytes * elements
5253 Scale = Width = TypeSize::getScalable(4);
5254 MinOffset = -8;
5255 MaxOffset = 7;
5256 break;
5257 case AArch64::LD1B_D_IMM:
5258 case AArch64::LD1SB_D_IMM:
5259 case AArch64::ST1B_D_IMM:
5260 case AArch64::LDNF1B_D_IMM:
5261 case AArch64::LDNF1SB_D_IMM:
5262 // A eighth vector worth of data
5263 // Width = mbytes * elements
5264 Scale = Width = TypeSize::getScalable(2);
5265 MinOffset = -8;
5266 MaxOffset = 7;
5267 break;
5268 case AArch64::ST2Gi:
5269 case AArch64::ST2GPreIndex:
5270 case AArch64::ST2GPostIndex:
5271 case AArch64::STZ2Gi:
5272 case AArch64::STZ2GPreIndex:
5273 case AArch64::STZ2GPostIndex:
5274 Scale = TypeSize::getFixed(16);
5275 Width = TypeSize::getFixed(32);
5276 MinOffset = -256;
5277 MaxOffset = 255;
5278 break;
5279 case AArch64::STGPi:
5280 case AArch64::STGPpost:
5281 case AArch64::STGPpre:
5282 Scale = Width = TypeSize::getFixed(16);
5283 MinOffset = -64;
5284 MaxOffset = 63;
5285 break;
5286 case AArch64::LD1RB_IMM:
5287 case AArch64::LD1RB_H_IMM:
5288 case AArch64::LD1RB_S_IMM:
5289 case AArch64::LD1RB_D_IMM:
5290 case AArch64::LD1RSB_H_IMM:
5291 case AArch64::LD1RSB_S_IMM:
5292 case AArch64::LD1RSB_D_IMM:
5293 Scale = Width = TypeSize::getFixed(1);
5294 MinOffset = 0;
5295 MaxOffset = 63;
5296 break;
5297 case AArch64::LD1RH_IMM:
5298 case AArch64::LD1RH_S_IMM:
5299 case AArch64::LD1RH_D_IMM:
5300 case AArch64::LD1RSH_S_IMM:
5301 case AArch64::LD1RSH_D_IMM:
5302 Scale = Width = TypeSize::getFixed(2);
5303 MinOffset = 0;
5304 MaxOffset = 63;
5305 break;
5306 case AArch64::LD1RW_IMM:
5307 case AArch64::LD1RW_D_IMM:
5308 case AArch64::LD1RSW_IMM:
5309 Scale = Width = TypeSize::getFixed(4);
5310 MinOffset = 0;
5311 MaxOffset = 63;
5312 break;
5313 case AArch64::LD1RD_IMM:
5314 Scale = Width = TypeSize::getFixed(8);
5315 MinOffset = 0;
5316 MaxOffset = 63;
5317 break;
5318 }
5319
5320 return true;
5321}
5322
5323// Scaling factor for unscaled load or store.
5325 switch (Opc) {
5326 default:
5327 llvm_unreachable("Opcode has unknown scale!");
5328 case AArch64::LDRBui:
5329 case AArch64::LDRBBui:
5330 case AArch64::LDURBBi:
5331 case AArch64::LDRSBWui:
5332 case AArch64::LDURSBWi:
5333 case AArch64::STRBui:
5334 case AArch64::STRBBui:
5335 case AArch64::STURBBi:
5336 return 1;
5337 case AArch64::LDRHui:
5338 case AArch64::LDRHHui:
5339 case AArch64::LDURHHi:
5340 case AArch64::LDRSHWui:
5341 case AArch64::LDURSHWi:
5342 case AArch64::STRHui:
5343 case AArch64::STRHHui:
5344 case AArch64::STURHHi:
5345 return 2;
5346 case AArch64::LDRSui:
5347 case AArch64::LDURSi:
5348 case AArch64::LDRSpre:
5349 case AArch64::LDRSWui:
5350 case AArch64::LDURSWi:
5351 case AArch64::LDRSWpre:
5352 case AArch64::LDRWpre:
5353 case AArch64::LDRWui:
5354 case AArch64::LDURWi:
5355 case AArch64::STRSui:
5356 case AArch64::STURSi:
5357 case AArch64::STRSpre:
5358 case AArch64::STRWui:
5359 case AArch64::STURWi:
5360 case AArch64::STRWpre:
5361 case AArch64::LDPSi:
5362 case AArch64::LDPSWi:
5363 case AArch64::LDPWi:
5364 case AArch64::STPSi:
5365 case AArch64::STPWi:
5366 return 4;
5367 case AArch64::LDRDui:
5368 case AArch64::LDURDi:
5369 case AArch64::LDRDpre:
5370 case AArch64::LDRXui:
5371 case AArch64::LDURXi:
5372 case AArch64::LDRXpre:
5373 case AArch64::STRDui:
5374 case AArch64::STURDi:
5375 case AArch64::STRDpre:
5376 case AArch64::STRXui:
5377 case AArch64::STURXi:
5378 case AArch64::STRXpre:
5379 case AArch64::LDPDi:
5380 case AArch64::LDPXi:
5381 case AArch64::STPDi:
5382 case AArch64::STPXi:
5383 return 8;
5384 case AArch64::LDRQui:
5385 case AArch64::LDURQi:
5386 case AArch64::STRQui:
5387 case AArch64::STURQi:
5388 case AArch64::STRQpre:
5389 case AArch64::LDPQi:
5390 case AArch64::LDRQpre:
5391 case AArch64::STPQi:
5392 case AArch64::STGi:
5393 case AArch64::STZGi:
5394 case AArch64::ST2Gi:
5395 case AArch64::STZ2Gi:
5396 case AArch64::STGPi:
5397 return 16;
5398 }
5399}
5400
5402 switch (MI.getOpcode()) {
5403 default:
5404 return false;
5405 case AArch64::LDRWpre:
5406 case AArch64::LDRXpre:
5407 case AArch64::LDRSWpre:
5408 case AArch64::LDRSpre:
5409 case AArch64::LDRDpre:
5410 case AArch64::LDRQpre:
5411 return true;
5412 }
5413}
5414
5416 switch (MI.getOpcode()) {
5417 default:
5418 return false;
5419 case AArch64::STRWpre:
5420 case AArch64::STRXpre:
5421 case AArch64::STRSpre:
5422 case AArch64::STRDpre:
5423 case AArch64::STRQpre:
5424 return true;
5425 }
5426}
5427
5429 return isPreLd(MI) || isPreSt(MI);
5430}
5431
5433 switch (MI.getOpcode()) {
5434 default:
5435 return false;
5436 case AArch64::LDURBBi:
5437 case AArch64::LDURHHi:
5438 case AArch64::LDURWi:
5439 case AArch64::LDRBBui:
5440 case AArch64::LDRHHui:
5441 case AArch64::LDRWui:
5442 case AArch64::LDRBBroX:
5443 case AArch64::LDRHHroX:
5444 case AArch64::LDRWroX:
5445 case AArch64::LDRBBroW:
5446 case AArch64::LDRHHroW:
5447 case AArch64::LDRWroW:
5448 return true;
5449 }
5450}
5451
5453 switch (MI.getOpcode()) {
5454 default:
5455 return false;
5456 case AArch64::LDURSBWi:
5457 case AArch64::LDURSHWi:
5458 case AArch64::LDURSBXi:
5459 case AArch64::LDURSHXi:
5460 case AArch64::LDURSWi:
5461 case AArch64::LDRSBWui:
5462 case AArch64::LDRSHWui:
5463 case AArch64::LDRSBXui:
5464 case AArch64::LDRSHXui:
5465 case AArch64::LDRSWui:
5466 case AArch64::LDRSBWroX:
5467 case AArch64::LDRSHWroX:
5468 case AArch64::LDRSBXroX:
5469 case AArch64::LDRSHXroX:
5470 case AArch64::LDRSWroX:
5471 case AArch64::LDRSBWroW:
5472 case AArch64::LDRSHWroW:
5473 case AArch64::LDRSBXroW:
5474 case AArch64::LDRSHXroW:
5475 case AArch64::LDRSWroW:
5476 return true;
5477 }
5478}
5479
5481 switch (MI.getOpcode()) {
5482 default:
5483 return false;
5484 case AArch64::LDPSi:
5485 case AArch64::LDPSWi:
5486 case AArch64::LDPDi:
5487 case AArch64::LDPQi:
5488 case AArch64::LDPWi:
5489 case AArch64::LDPXi:
5490 case AArch64::STPSi:
5491 case AArch64::STPDi:
5492 case AArch64::STPQi:
5493 case AArch64::STPWi:
5494 case AArch64::STPXi:
5495 case AArch64::STGPi:
5496 return true;
5497 }
5498}
5499
5501 assert(MI.mayLoadOrStore() && "Load or store instruction expected");
5502 unsigned Idx =
5504 : 1;
5505 return MI.getOperand(Idx);
5506}
5507
5508const MachineOperand &
5510 assert(MI.mayLoadOrStore() && "Load or store instruction expected");
5511 unsigned Idx =
5513 : 2;
5514 return MI.getOperand(Idx);
5515}
5516
5517const MachineOperand &
5519 switch (MI.getOpcode()) {
5520 default:
5521 llvm_unreachable("Unexpected opcode");
5522 case AArch64::LDRBroX:
5523 case AArch64::LDRBBroX:
5524 case AArch64::LDRSBXroX:
5525 case AArch64::LDRSBWroX:
5526 case AArch64::LDRHroX:
5527 case AArch64::LDRHHroX:
5528 case AArch64::LDRSHXroX:
5529 case AArch64::LDRSHWroX:
5530 case AArch64::LDRWroX:
5531 case AArch64::LDRSroX:
5532 case AArch64::LDRSWroX:
5533 case AArch64::LDRDroX:
5534 case AArch64::LDRXroX:
5535 case AArch64::LDRQroX:
5536 return MI.getOperand(4);
5537 }
5538}
5539
5541 Register Reg) {
5542 if (MI.getParent() == nullptr)
5543 return nullptr;
5544 const MachineFunction *MF = MI.getParent()->getParent();
5545 return MF ? MF->getRegInfo().getRegClassOrNull(Reg) : nullptr;
5546}
5547
5549 auto IsHFPR = [&](const MachineOperand &Op) {
5550 if (!Op.isReg())
5551 return false;
5552 auto Reg = Op.getReg();
5553 if (Reg.isPhysical())
5554 return AArch64::FPR16RegClass.contains(Reg);
5555 const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
5556 return TRC == &AArch64::FPR16RegClass ||
5557 TRC == &AArch64::FPR16_loRegClass;
5558 };
5559 return llvm::any_of(MI.operands(), IsHFPR);
5560}
5561
5563 auto IsQFPR = [&](const MachineOperand &Op) {
5564 if (!Op.isReg())
5565 return false;
5566 auto Reg = Op.getReg();
5567 if (Reg.isPhysical())
5568 return AArch64::FPR128RegClass.contains(Reg);
5569 const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
5570 return TRC == &AArch64::FPR128RegClass ||
5571 TRC == &AArch64::FPR128_loRegClass;
5572 };
5573 return llvm::any_of(MI.operands(), IsQFPR);
5574}
5575
5577 switch (MI.getOpcode()) {
5578 case AArch64::BRK:
5579 case AArch64::HLT:
5580 case AArch64::PACIASP:
5581 case AArch64::PACIBSP:
5582 case AArch64::PACIASPPC:
5583 case AArch64::PACIBSPPC:
5584 // Implicit BTI behavior.
5585 return true;
5586 case AArch64::PAUTH_PROLOGUE:
5587 // PAUTH_PROLOGUE expands to PACI(A|B)SP.
5588 return true;
5589 case AArch64::HINT: {
5590 unsigned Imm = MI.getOperand(0).getImm();
5591 // Explicit BTI instruction.
5592 if (Imm == 32 || Imm == 34 || Imm == 36 || Imm == 38)
5593 return true;
5594 // PACI(A|B)SP instructions.
5595 if (Imm == 25 || Imm == 27)
5596 return true;
5597 return false;
5598 }
5599 default:
5600 return false;
5601 }
5602}
5603
5605 if (Reg == 0)
5606 return false;
5607 assert(Reg.isPhysical() && "Expected physical register in isFpOrNEON");
5608 return AArch64::FPR128RegClass.contains(Reg) ||
5609 AArch64::FPR64RegClass.contains(Reg) ||
5610 AArch64::FPR32RegClass.contains(Reg) ||
5611 AArch64::FPR16RegClass.contains(Reg) ||
5612 AArch64::FPR8RegClass.contains(Reg);
5613}
5614
5616 auto IsFPR = [&](const MachineOperand &Op) {
5617 if (!Op.isReg())
5618 return false;
5619 auto Reg = Op.getReg();
5620 if (Reg.isPhysical())
5621 return isFpOrNEON(Reg);
5622
5623 const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
5624 return TRC == &AArch64::FPR128RegClass ||
5625 TRC == &AArch64::FPR128_loRegClass ||
5626 TRC == &AArch64::FPR64RegClass ||
5627 TRC == &AArch64::FPR64_loRegClass ||
5628 TRC == &AArch64::FPR32RegClass || TRC == &AArch64::FPR16RegClass ||
5629 TRC == &AArch64::FPR8RegClass;
5630 };
5631 return llvm::any_of(MI.operands(), IsFPR);
5632}
5633
5634// Scale the unscaled offsets. Returns false if the unscaled offset can't be
5635// scaled.
5636static bool scaleOffset(unsigned Opc, int64_t &Offset) {
5638
5639 // If the byte-offset isn't a multiple of the stride, we can't scale this
5640 // offset.
5641 if (Offset % Scale != 0)
5642 return false;
5643
5644 // Convert the byte-offset used by unscaled into an "element" offset used
5645 // by the scaled pair load/store instructions.
5646 Offset /= Scale;
5647 return true;
5648}
5649
5650static bool canPairLdStOpc(unsigned FirstOpc, unsigned SecondOpc) {
5651 if (FirstOpc == SecondOpc)
5652 return true;
5653 // We can also pair sign-ext and zero-ext instructions.
5654 switch (FirstOpc) {
5655 default:
5656 return false;
5657 case AArch64::STRSui:
5658 case AArch64::STURSi:
5659 return SecondOpc == AArch64::STRSui || SecondOpc == AArch64::STURSi;
5660 case AArch64::STRDui:
5661 case AArch64::STURDi:
5662 return SecondOpc == AArch64::STRDui || SecondOpc == AArch64::STURDi;
5663 case AArch64::STRQui:
5664 case AArch64::STURQi:
5665 return SecondOpc == AArch64::STRQui || SecondOpc == AArch64::STURQi;
5666 case AArch64::STRWui:
5667 case AArch64::STURWi:
5668 return SecondOpc == AArch64::STRWui || SecondOpc == AArch64::STURWi;
5669 case AArch64::STRXui:
5670 case AArch64::STURXi:
5671 return SecondOpc == AArch64::STRXui || SecondOpc == AArch64::STURXi;
5672 case AArch64::LDRSui:
5673 case AArch64::LDURSi:
5674 return SecondOpc == AArch64::LDRSui || SecondOpc == AArch64::LDURSi;
5675 case AArch64::LDRDui:
5676 case AArch64::LDURDi:
5677 return SecondOpc == AArch64::LDRDui || SecondOpc == AArch64::LDURDi;
5678 case AArch64::LDRQui:
5679 case AArch64::LDURQi:
5680 return SecondOpc == AArch64::LDRQui || SecondOpc == AArch64::LDURQi;
5681 case AArch64::LDRWui:
5682 case AArch64::LDURWi:
5683 return SecondOpc == AArch64::LDRSWui || SecondOpc == AArch64::LDURSWi;
5684 case AArch64::LDRSWui:
5685 case AArch64::LDURSWi:
5686 return SecondOpc == AArch64::LDRWui || SecondOpc == AArch64::LDURWi;
5687 case AArch64::LDRXui:
5688 case AArch64::LDURXi:
5689 return SecondOpc == AArch64::LDRXui || SecondOpc == AArch64::LDURXi;
5690 }
5691 // These instructions can't be paired based on their opcodes.
5692 return false;
5693}
5694
5695static bool shouldClusterFI(const MachineFrameInfo &MFI, int FI1,
5696 int64_t Offset1, unsigned Opcode1, int FI2,
5697 int64_t Offset2, unsigned Opcode2) {
5698 // Accesses through fixed stack object frame indices may access a different
5699 // fixed stack slot. Check that the object offsets + offsets match.
5700 if (MFI.isFixedObjectIndex(FI1) && MFI.isFixedObjectIndex(FI2)) {
5701 int64_t ObjectOffset1 = MFI.getObjectOffset(FI1);
5702 int64_t ObjectOffset2 = MFI.getObjectOffset(FI2);
5703 assert(ObjectOffset1 <= ObjectOffset2 && "Object offsets are not ordered.");
5704 // Convert to scaled object offsets.
5705 int Scale1 = AArch64InstrInfo::getMemScale(Opcode1);
5706 if (ObjectOffset1 % Scale1 != 0)
5707 return false;
5708 ObjectOffset1 /= Scale1;
5709 int Scale2 = AArch64InstrInfo::getMemScale(Opcode2);
5710 if (ObjectOffset2 % Scale2 != 0)
5711 return false;
5712 ObjectOffset2 /= Scale2;
5713 ObjectOffset1 += Offset1;
5714 ObjectOffset2 += Offset2;
5715 return ObjectOffset1 + 1 == ObjectOffset2;
5716 }
5717
5718 return FI1 == FI2;
5719}
5720
5721/// Detect opportunities for ldp/stp formation.
5722///
5723/// Only called for LdSt for which getMemOperandWithOffset returns true.
5725 ArrayRef<const MachineOperand *> BaseOps1, int64_t OpOffset1,
5726 bool OffsetIsScalable1, ArrayRef<const MachineOperand *> BaseOps2,
5727 int64_t OpOffset2, bool OffsetIsScalable2, unsigned ClusterSize,
5728 unsigned NumBytes) const {
5729 assert(BaseOps1.size() == 1 && BaseOps2.size() == 1);
5730 const MachineOperand &BaseOp1 = *BaseOps1.front();
5731 const MachineOperand &BaseOp2 = *BaseOps2.front();
5732 const MachineInstr &FirstLdSt = *BaseOp1.getParent();
5733 const MachineInstr &SecondLdSt = *BaseOp2.getParent();
5734 if (BaseOp1.getType() != BaseOp2.getType())
5735 return false;
5736
5737 assert((BaseOp1.isReg() || BaseOp1.isFI()) &&
5738 "Only base registers and frame indices are supported.");
5739
5740 // Check for both base regs and base FI.
5741 if (BaseOp1.isReg() && BaseOp1.getReg() != BaseOp2.getReg())
5742 return false;
5743
5744 // Only cluster up to a single pair.
5745 if (ClusterSize > 2)
5746 return false;
5747
5748 if (!isPairableLdStInst(FirstLdSt) || !isPairableLdStInst(SecondLdSt))
5749 return false;
5750
5751 // Can we pair these instructions based on their opcodes?
5752 unsigned FirstOpc = FirstLdSt.getOpcode();
5753 unsigned SecondOpc = SecondLdSt.getOpcode();
5754 if (!canPairLdStOpc(FirstOpc, SecondOpc))
5755 return false;
5756
5757 // Can't merge volatiles or load/stores that have a hint to avoid pair
5758 // formation, for example.
5759 if (!isCandidateToMergeOrPair(FirstLdSt) ||
5760 !isCandidateToMergeOrPair(SecondLdSt))
5761 return false;
5762
5763 // isCandidateToMergeOrPair guarantees that operand 2 is an immediate.
5764 int64_t Offset1 = FirstLdSt.getOperand(2).getImm();
5765 if (hasUnscaledLdStOffset(FirstOpc) && !scaleOffset(FirstOpc, Offset1))
5766 return false;
5767
5768 int64_t Offset2 = SecondLdSt.getOperand(2).getImm();
5769 if (hasUnscaledLdStOffset(SecondOpc) && !scaleOffset(SecondOpc, Offset2))
5770 return false;
5771
5772 // Pairwise instructions have a 7-bit signed offset field.
5773 if (Offset1 > 63 || Offset1 < -64)
5774 return false;
5775
5776 // The caller should already have ordered First/SecondLdSt by offset.
5777 // Note: except for non-equal frame index bases
5778 if (BaseOp1.isFI()) {
5779 assert((!BaseOp1.isIdenticalTo(BaseOp2) || Offset1 <= Offset2) &&
5780 "Caller should have ordered offsets.");
5781
5782 const MachineFrameInfo &MFI =
5783 FirstLdSt.getParent()->getParent()->getFrameInfo();
5784 return shouldClusterFI(MFI, BaseOp1.getIndex(), Offset1, FirstOpc,
5785 BaseOp2.getIndex(), Offset2, SecondOpc);
5786 }
5787
5788 assert(Offset1 <= Offset2 && "Caller should have ordered offsets.");
5789
5790 return Offset1 + 1 == Offset2;
5791}
5792
5794 MCRegister Reg, unsigned SubIdx,
5795 RegState State,
5796 const TargetRegisterInfo *TRI) {
5797 if (!SubIdx)
5798 return MIB.addReg(Reg, State);
5799
5800 if (Reg.isPhysical())
5801 return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
5802 return MIB.addReg(Reg, State, SubIdx);
5803}
5804
5807 const DebugLoc &DL, MCRegister DestReg,
5808 MCRegister SrcReg, bool KillSrc,
5809 ArrayRef<unsigned> Indices) const {
5810 assert(Subtarget.hasNEON() && "Unexpected register copy without NEON");
5812 uint16_t DestEncoding = TRI->getEncodingValue(DestReg);
5813 uint16_t SrcEncoding = TRI->getEncodingValue(SrcReg);
5814 unsigned NumRegs = Indices.size();
5815 MCRegister DestSubReg = TRI->getSubReg(DestReg, Indices[0]);
5816 assert(!AArch64::PNRRegClass.contains(DestSubReg) &&
5817 "Unexpected predicate tuple copy");
5818 unsigned MaxRegs = AArch64::PPRRegClass.contains(DestSubReg) ? 15 : 31;
5819
5820 int SubReg = 0, End = NumRegs, Incr = 1;
5821 // Copy in reverse if a forward copy will clobber the tuple
5822 if (((DestEncoding - SrcEncoding) & MaxRegs) < NumRegs) {
5823 SubReg = NumRegs - 1;
5824 End = -1;
5825 Incr = -1;
5826 }
5827
5828 for (; SubReg != End; SubReg += Incr) {
5829 DestSubReg = TRI->getSubReg(DestReg, Indices[SubReg]);
5830 MCRegister SrcSubReg = TRI->getSubReg(SrcReg, Indices[SubReg]);
5831 copyPhysRegImpl(MBB, I, DL, DestSubReg, SrcSubReg, KillSrc);
5832 }
5833}
5834
5837 const DebugLoc &DL, MCRegister DestReg,
5838 MCRegister SrcReg, bool KillSrc,
5839 unsigned Opcode, unsigned ZeroReg,
5840 llvm::ArrayRef<unsigned> Indices) const {
5842 unsigned NumRegs = Indices.size();
5843
5844#ifndef NDEBUG
5845 uint16_t DestEncoding = TRI->getEncodingValue(DestReg);
5846 uint16_t SrcEncoding = TRI->getEncodingValue(SrcReg);
5847 assert(DestEncoding % NumRegs == 0 && SrcEncoding % NumRegs == 0 &&
5848 "GPR reg sequences should not be able to overlap");
5849#endif
5850
5851 for (unsigned SubReg = 0; SubReg != NumRegs; ++SubReg) {
5852 const MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opcode));
5853 AddSubReg(MIB, DestReg, Indices[SubReg], RegState::Define, TRI);
5854 MIB.addReg(ZeroReg);
5855 AddSubReg(MIB, SrcReg, Indices[SubReg], getKillRegState(KillSrc), TRI);
5856 MIB.addImm(0);
5857 }
5858}
5859
5860/// Returns true if the instruction at I is in a streaming call site region,
5861/// within a single basic block.
5862/// A "call site streaming region" starts after smstart and ends at smstop
5863/// around a call to a streaming function. This walks backward from I.
5866 MachineFunction &MF = *MBB.getParent();
5868 if (!AFI->hasStreamingModeChanges())
5869 return false;
5870 // Walk backwards to find smstart/smstop
5871 for (MachineInstr &MI : reverse(make_range(MBB.begin(), I))) {
5872 unsigned Opc = MI.getOpcode();
5873 if (Opc == AArch64::MSRpstatesvcrImm1 || Opc == AArch64::MSRpstatePseudo) {
5874 // Check if this is SM change (not ZA)
5875 int64_t PState = MI.getOperand(0).getImm();
5876 if (PState == AArch64SVCR::SVCRSM || PState == AArch64SVCR::SVCRSMZA) {
5877 // Operand 1 is 1 for start, 0 for stop
5878 return MI.getOperand(1).getImm() == 1;
5879 }
5880 }
5881 }
5882 return false;
5883}
5884
5885/// Returns true if in a streaming call site region without SME-FA64.
5891
5894 const DebugLoc &DL, Register DestReg,
5895 Register SrcReg, bool KillSrc,
5896 bool RenamableDest,
5897 bool RenamableSrc) const {
5898 if (AArch64::GPR32spRegClass.contains(DestReg) &&
5899 AArch64::GPR32spRegClass.contains(SrcReg)) {
5900 if (DestReg == AArch64::WSP || SrcReg == AArch64::WSP) {
5901 // If either operand is WSP, expand to ADD #0.
5902 if (Subtarget.hasZeroCycleRegMoveGPR64() &&
5903 !Subtarget.hasZeroCycleRegMoveGPR32()) {
5904 // Cyclone recognizes "ADD Xd, Xn, #0" as a zero-cycle register move.
5905 MCRegister DestRegX = RI.getMatchingSuperReg(DestReg, AArch64::sub_32,
5906 &AArch64::GPR64spRegClass);
5907 MCRegister SrcRegX = RI.getMatchingSuperReg(SrcReg, AArch64::sub_32,
5908 &AArch64::GPR64spRegClass);
5909 // This instruction is reading and writing X registers. This may upset
5910 // the register scavenger and machine verifier, so we need to indicate
5911 // that we are reading an undefined value from SrcRegX, but a proper
5912 // value from SrcReg.
5913 BuildMI(MBB, I, DL, get(AArch64::ADDXri), DestRegX)
5914 .addReg(SrcRegX, RegState::Undef)
5915 .addImm(0)
5917 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
5918 ++NumZCRegMoveInstrsGPR;
5919 } else {
5920 BuildMI(MBB, I, DL, get(AArch64::ADDWri), DestReg)
5921 .addReg(SrcReg, getKillRegState(KillSrc))
5922 .addImm(0)
5924 if (Subtarget.hasZeroCycleRegMoveGPR32())
5925 ++NumZCRegMoveInstrsGPR;
5926 }
5927 } else if (Subtarget.hasZeroCycleRegMoveGPR64() &&
5928 !Subtarget.hasZeroCycleRegMoveGPR32()) {
5929 // Cyclone recognizes "ORR Xd, XZR, Xm" as a zero-cycle register move.
5930 MCRegister DestRegX = RI.getMatchingSuperReg(DestReg, AArch64::sub_32,
5931 &AArch64::GPR64spRegClass);
5932 assert(DestRegX.isValid() && "Destination super-reg not valid");
5933 MCRegister SrcRegX = RI.getMatchingSuperReg(SrcReg, AArch64::sub_32,
5934 &AArch64::GPR64spRegClass);
5935 assert(SrcRegX.isValid() && "Source super-reg not valid");
5936 // This instruction is reading and writing X registers. This may upset
5937 // the register scavenger and machine verifier, so we need to indicate
5938 // that we are reading an undefined value from SrcRegX, but a proper
5939 // value from SrcReg.
5940 BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestRegX)
5941 .addReg(AArch64::XZR)
5942 .addReg(SrcRegX, RegState::Undef)
5943 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
5944 ++NumZCRegMoveInstrsGPR;
5945 } else {
5946 // Otherwise, expand to ORR WZR.
5947 BuildMI(MBB, I, DL, get(AArch64::ORRWrr), DestReg)
5948 .addReg(AArch64::WZR)
5949 .addReg(SrcReg, getKillRegState(KillSrc));
5950 if (Subtarget.hasZeroCycleRegMoveGPR32())
5951 ++NumZCRegMoveInstrsGPR;
5952 }
5953 return;
5954 }
5955
5956 // GPR32 zeroing
5957 if (AArch64::GPR32spRegClass.contains(DestReg) && SrcReg == AArch64::WZR) {
5958 if (Subtarget.hasZeroCycleZeroingGPR64() &&
5959 !Subtarget.hasZeroCycleZeroingGPR32()) {
5960 MCRegister DestRegX = RI.getMatchingSuperReg(DestReg, AArch64::sub_32,
5961 &AArch64::GPR64spRegClass);
5962 assert(DestRegX.isValid() && "Destination super-reg not valid");
5963 BuildMI(MBB, I, DL, get(AArch64::MOVZXi), DestRegX)
5964 .addImm(0)
5966 ++NumZCZeroingInstrsGPR;
5967 } else if (Subtarget.hasZeroCycleZeroingGPR32()) {
5968 BuildMI(MBB, I, DL, get(AArch64::MOVZWi), DestReg)
5969 .addImm(0)
5971 ++NumZCZeroingInstrsGPR;
5972 } else {
5973 BuildMI(MBB, I, DL, get(AArch64::ORRWrr), DestReg)
5974 .addReg(AArch64::WZR)
5975 .addReg(AArch64::WZR);
5976 }
5977 return;
5978 }
5979
5980 if (AArch64::GPR64spRegClass.contains(DestReg) &&
5981 AArch64::GPR64spRegClass.contains(SrcReg)) {
5982 if (DestReg == AArch64::SP || SrcReg == AArch64::SP) {
5983 // If either operand is SP, expand to ADD #0.
5984 BuildMI(MBB, I, DL, get(AArch64::ADDXri), DestReg)
5985 .addReg(SrcReg, getKillRegState(KillSrc))
5986 .addImm(0)
5988 if (Subtarget.hasZeroCycleRegMoveGPR64())
5989 ++NumZCRegMoveInstrsGPR;
5990 } else {
5991 // Otherwise, expand to ORR XZR.
5992 BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestReg)
5993 .addReg(AArch64::XZR)
5994 .addReg(SrcReg, getKillRegState(KillSrc));
5995 if (Subtarget.hasZeroCycleRegMoveGPR64())
5996 ++NumZCRegMoveInstrsGPR;
5997 }
5998 return;
5999 }
6000
6001 // GPR64 zeroing
6002 if (AArch64::GPR64spRegClass.contains(DestReg) && SrcReg == AArch64::XZR) {
6003 if (Subtarget.hasZeroCycleZeroingGPR64()) {
6004 BuildMI(MBB, I, DL, get(AArch64::MOVZXi), DestReg)
6005 .addImm(0)
6007 ++NumZCZeroingInstrsGPR;
6008 } else {
6009 BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestReg)
6010 .addReg(AArch64::XZR)
6011 .addReg(AArch64::XZR);
6012 }
6013 return;
6014 }
6015
6016 // Copy a Predicate register by ORRing with itself.
6017 if (AArch64::PPRRegClass.contains(DestReg) &&
6018 AArch64::PPRRegClass.contains(SrcReg)) {
6019 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6020 "Unexpected SVE register.");
6021 BuildMI(MBB, I, DL, get(AArch64::ORR_PPzPP), DestReg)
6022 .addReg(SrcReg) // Pg
6023 .addReg(SrcReg)
6024 .addReg(SrcReg, getKillRegState(KillSrc));
6025 return;
6026 }
6027
6028 // Copy a predicate-as-counter register by ORRing with itself as if it
6029 // were a regular predicate (mask) register.
6030 bool DestIsPNR = AArch64::PNRRegClass.contains(DestReg);
6031 bool SrcIsPNR = AArch64::PNRRegClass.contains(SrcReg);
6032 if (DestIsPNR || SrcIsPNR) {
6033 auto ToPPR = [](MCRegister R) -> MCRegister {
6034 return (R - AArch64::PN0) + AArch64::P0;
6035 };
6036 MCRegister PPRSrcReg = SrcIsPNR ? ToPPR(SrcReg) : SrcReg.asMCReg();
6037 MCRegister PPRDestReg = DestIsPNR ? ToPPR(DestReg) : DestReg.asMCReg();
6038
6039 if (PPRSrcReg != PPRDestReg) {
6040 auto NewMI = BuildMI(MBB, I, DL, get(AArch64::ORR_PPzPP), PPRDestReg)
6041 .addReg(PPRSrcReg) // Pg
6042 .addReg(PPRSrcReg)
6043 .addReg(PPRSrcReg, getKillRegState(KillSrc));
6044 if (DestIsPNR)
6045 NewMI.addDef(DestReg, RegState::Implicit);
6046 }
6047 return;
6048 }
6049
6050 // Copy a predicate register pair by copying the individual sub-registers.
6051 if (AArch64::PPR2RegClass.contains(DestReg) &&
6052 AArch64::PPR2RegClass.contains(SrcReg)) {
6053 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6054 "Unexpected SVE predicate register.");
6055 static const unsigned Indices[] = {AArch64::psub0, AArch64::psub1};
6056 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6057 return;
6058 }
6059
6060 // Copy a Z register by ORRing with itself.
6061 if (AArch64::ZPRRegClass.contains(DestReg) &&
6062 AArch64::ZPRRegClass.contains(SrcReg)) {
6063 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6064 "Unexpected SVE register.");
6065 BuildMI(MBB, I, DL, get(AArch64::ORR_ZZZ), DestReg)
6066 .addReg(SrcReg)
6067 .addReg(SrcReg, getKillRegState(KillSrc));
6068 return;
6069 }
6070
6071 // Copy a Z register pair by copying the individual sub-registers.
6072 if ((AArch64::ZPR2RegClass.contains(DestReg) ||
6073 AArch64::ZPR2StridedOrContiguousRegClass.contains(DestReg)) &&
6074 (AArch64::ZPR2RegClass.contains(SrcReg) ||
6075 AArch64::ZPR2StridedOrContiguousRegClass.contains(SrcReg))) {
6076 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6077 "Unexpected SVE register.");
6078 static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1};
6079 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6080 return;
6081 }
6082
6083 // Copy a Z register triple by copying the individual sub-registers.
6084 if (AArch64::ZPR3RegClass.contains(DestReg) &&
6085 AArch64::ZPR3RegClass.contains(SrcReg)) {
6086 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6087 "Unexpected SVE register.");
6088 static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1,
6089 AArch64::zsub2};
6090 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6091 return;
6092 }
6093
6094 // Copy a Z register quad by copying the individual sub-registers.
6095 if ((AArch64::ZPR4RegClass.contains(DestReg) ||
6096 AArch64::ZPR4StridedOrContiguousRegClass.contains(DestReg)) &&
6097 (AArch64::ZPR4RegClass.contains(SrcReg) ||
6098 AArch64::ZPR4StridedOrContiguousRegClass.contains(SrcReg))) {
6099 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6100 "Unexpected SVE register.");
6101 static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1,
6102 AArch64::zsub2, AArch64::zsub3};
6103 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6104 return;
6105 }
6106
6107 // Copy a DDDD register quad by copying the individual sub-registers.
6108 if (AArch64::DDDDRegClass.contains(DestReg) &&
6109 AArch64::DDDDRegClass.contains(SrcReg)) {
6110 static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1,
6111 AArch64::dsub2, AArch64::dsub3};
6112 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6113 return;
6114 }
6115
6116 // Copy a DDD register triple by copying the individual sub-registers.
6117 if (AArch64::DDDRegClass.contains(DestReg) &&
6118 AArch64::DDDRegClass.contains(SrcReg)) {
6119 static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1,
6120 AArch64::dsub2};
6121 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6122 return;
6123 }
6124
6125 // Copy a DD register pair by copying the individual sub-registers.
6126 if (AArch64::DDRegClass.contains(DestReg) &&
6127 AArch64::DDRegClass.contains(SrcReg)) {
6128 static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1};
6129 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6130 return;
6131 }
6132
6133 // Copy a QQQQ register quad by copying the individual sub-registers.
6134 if (AArch64::QQQQRegClass.contains(DestReg) &&
6135 AArch64::QQQQRegClass.contains(SrcReg)) {
6136 static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1,
6137 AArch64::qsub2, AArch64::qsub3};
6138 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6139 return;
6140 }
6141
6142 // Copy a QQQ register triple by copying the individual sub-registers.
6143 if (AArch64::QQQRegClass.contains(DestReg) &&
6144 AArch64::QQQRegClass.contains(SrcReg)) {
6145 static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1,
6146 AArch64::qsub2};
6147 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6148 return;
6149 }
6150
6151 // Copy a QQ register pair by copying the individual sub-registers.
6152 if (AArch64::QQRegClass.contains(DestReg) &&
6153 AArch64::QQRegClass.contains(SrcReg)) {
6154 static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1};
6155 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6156 return;
6157 }
6158
6159 if (AArch64::XSeqPairsClassRegClass.contains(DestReg) &&
6160 AArch64::XSeqPairsClassRegClass.contains(SrcReg)) {
6161 static const unsigned Indices[] = {AArch64::sube64, AArch64::subo64};
6162 copyGPRRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRXrs,
6163 AArch64::XZR, Indices);
6164 return;
6165 }
6166
6167 if (AArch64::WSeqPairsClassRegClass.contains(DestReg) &&
6168 AArch64::WSeqPairsClassRegClass.contains(SrcReg)) {
6169 static const unsigned Indices[] = {AArch64::sube32, AArch64::subo32};
6170 copyGPRRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRWrs,
6171 AArch64::WZR, Indices);
6172 return;
6173 }
6174
6175 if (AArch64::FPR128RegClass.contains(DestReg) &&
6176 AArch64::FPR128RegClass.contains(SrcReg)) {
6177 // In streaming regions, NEON is illegal but streaming-SVE is available.
6178 // Use SVE for copies if we're in a streaming region and SME is available.
6179 // With +sme-fa64, NEON is legal in streaming mode so we can use it.
6180 if ((Subtarget.isSVEorStreamingSVEAvailable() &&
6181 !Subtarget.isNeonAvailable()) ||
6182 mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6183 BuildMI(MBB, I, DL, get(AArch64::ORR_ZZZ))
6184 .addReg(AArch64::Z0 + (DestReg - AArch64::Q0), RegState::Define)
6185 .addReg(AArch64::Z0 + (SrcReg - AArch64::Q0))
6186 .addReg(AArch64::Z0 + (SrcReg - AArch64::Q0));
6187 } else if (Subtarget.isNeonAvailable()) {
6188 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestReg)
6189 .addReg(SrcReg)
6190 .addReg(SrcReg, getKillRegState(KillSrc));
6191 if (Subtarget.hasZeroCycleRegMoveFPR128())
6192 ++NumZCRegMoveInstrsFPR;
6193 } else {
6194 BuildMI(MBB, I, DL, get(AArch64::STRQpre))
6195 .addReg(AArch64::SP, RegState::Define)
6196 .addReg(SrcReg, getKillRegState(KillSrc))
6197 .addReg(AArch64::SP)
6198 .addImm(-16);
6199 BuildMI(MBB, I, DL, get(AArch64::LDRQpost))
6200 .addReg(AArch64::SP, RegState::Define)
6201 .addReg(DestReg, RegState::Define)
6202 .addReg(AArch64::SP)
6203 .addImm(16);
6204 }
6205 return;
6206 }
6207
6208 if (AArch64::FPR64RegClass.contains(DestReg) &&
6209 AArch64::FPR64RegClass.contains(SrcReg)) {
6210 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6211 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6212 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6213 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6214 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::dsub,
6215 &AArch64::FPR128RegClass);
6216 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::dsub,
6217 &AArch64::FPR128RegClass);
6218 // This instruction is reading and writing Q registers. This may upset
6219 // the register scavenger and machine verifier, so we need to indicate
6220 // that we are reading an undefined value from SrcRegQ, but a proper
6221 // value from SrcReg.
6222 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6223 .addReg(SrcRegQ, RegState::Undef)
6224 .addReg(SrcRegQ, RegState::Undef)
6225 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6226 ++NumZCRegMoveInstrsFPR;
6227 } else {
6228 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestReg)
6229 .addReg(SrcReg, getKillRegState(KillSrc));
6230 if (Subtarget.hasZeroCycleRegMoveFPR64())
6231 ++NumZCRegMoveInstrsFPR;
6232 }
6233 return;
6234 }
6235
6236 if (AArch64::FPR32RegClass.contains(DestReg) &&
6237 AArch64::FPR32RegClass.contains(SrcReg)) {
6238 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6239 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6240 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6241 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6242 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::ssub,
6243 &AArch64::FPR128RegClass);
6244 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::ssub,
6245 &AArch64::FPR128RegClass);
6246 // This instruction is reading and writing Q registers. This may upset
6247 // the register scavenger and machine verifier, so we need to indicate
6248 // that we are reading an undefined value from SrcRegQ, but a proper
6249 // value from SrcReg.
6250 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6251 .addReg(SrcRegQ, RegState::Undef)
6252 .addReg(SrcRegQ, RegState::Undef)
6253 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6254 ++NumZCRegMoveInstrsFPR;
6255 } else if (Subtarget.hasZeroCycleRegMoveFPR64() &&
6256 !Subtarget.hasZeroCycleRegMoveFPR32()) {
6257 MCRegister DestRegD = RI.getMatchingSuperReg(DestReg, AArch64::ssub,
6258 &AArch64::FPR64RegClass);
6259 MCRegister SrcRegD = RI.getMatchingSuperReg(SrcReg, AArch64::ssub,
6260 &AArch64::FPR64RegClass);
6261 // This instruction is reading and writing D registers. This may upset
6262 // the register scavenger and machine verifier, so we need to indicate
6263 // that we are reading an undefined value from SrcRegD, but a proper
6264 // value from SrcReg.
6265 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestRegD)
6266 .addReg(SrcRegD, RegState::Undef)
6267 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6268 ++NumZCRegMoveInstrsFPR;
6269 } else {
6270 BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
6271 .addReg(SrcReg, getKillRegState(KillSrc));
6272 if (Subtarget.hasZeroCycleRegMoveFPR32())
6273 ++NumZCRegMoveInstrsFPR;
6274 }
6275 return;
6276 }
6277
6278 if (AArch64::FPR16RegClass.contains(DestReg) &&
6279 AArch64::FPR16RegClass.contains(SrcReg)) {
6280 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6281 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6282 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6283 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6284 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::hsub,
6285 &AArch64::FPR128RegClass);
6286 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::hsub,
6287 &AArch64::FPR128RegClass);
6288 // This instruction is reading and writing Q registers. This may upset
6289 // the register scavenger and machine verifier, so we need to indicate
6290 // that we are reading an undefined value from SrcRegQ, but a proper
6291 // value from SrcReg.
6292 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6293 .addReg(SrcRegQ, RegState::Undef)
6294 .addReg(SrcRegQ, RegState::Undef)
6295 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6296 } else if (Subtarget.hasZeroCycleRegMoveFPR64() &&
6297 !Subtarget.hasZeroCycleRegMoveFPR32()) {
6298 MCRegister DestRegD = RI.getMatchingSuperReg(DestReg, AArch64::hsub,
6299 &AArch64::FPR64RegClass);
6300 MCRegister SrcRegD = RI.getMatchingSuperReg(SrcReg, AArch64::hsub,
6301 &AArch64::FPR64RegClass);
6302 // This instruction is reading and writing D registers. This may upset
6303 // the register scavenger and machine verifier, so we need to indicate
6304 // that we are reading an undefined value from SrcRegD, but a proper
6305 // value from SrcReg.
6306 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestRegD)
6307 .addReg(SrcRegD, RegState::Undef)
6308 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6309 } else {
6310 DestReg = RI.getMatchingSuperReg(DestReg, AArch64::hsub,
6311 &AArch64::FPR32RegClass);
6312 SrcReg = RI.getMatchingSuperReg(SrcReg, AArch64::hsub,
6313 &AArch64::FPR32RegClass);
6314 BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
6315 .addReg(SrcReg, getKillRegState(KillSrc));
6316 }
6317 return;
6318 }
6319
6320 if (AArch64::FPR8RegClass.contains(DestReg) &&
6321 AArch64::FPR8RegClass.contains(SrcReg)) {
6322 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6323 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6324 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6325 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6326 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::bsub,
6327 &AArch64::FPR128RegClass);
6328 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::bsub,
6329 &AArch64::FPR128RegClass);
6330 // This instruction is reading and writing Q registers. This may upset
6331 // the register scavenger and machine verifier, so we need to indicate
6332 // that we are reading an undefined value from SrcRegQ, but a proper
6333 // value from SrcReg.
6334 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6335 .addReg(SrcRegQ, RegState::Undef)
6336 .addReg(SrcRegQ, RegState::Undef)
6337 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6338 } else if (Subtarget.hasZeroCycleRegMoveFPR64() &&
6339 !Subtarget.hasZeroCycleRegMoveFPR32()) {
6340 MCRegister DestRegD = RI.getMatchingSuperReg(DestReg, AArch64::bsub,
6341 &AArch64::FPR64RegClass);
6342 MCRegister SrcRegD = RI.getMatchingSuperReg(SrcReg, AArch64::bsub,
6343 &AArch64::FPR64RegClass);
6344 // This instruction is reading and writing D registers. This may upset
6345 // the register scavenger and machine verifier, so we need to indicate
6346 // that we are reading an undefined value from SrcRegD, but a proper
6347 // value from SrcReg.
6348 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestRegD)
6349 .addReg(SrcRegD, RegState::Undef)
6350 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6351 } else {
6352 DestReg = RI.getMatchingSuperReg(DestReg, AArch64::bsub,
6353 &AArch64::FPR32RegClass);
6354 SrcReg = RI.getMatchingSuperReg(SrcReg, AArch64::bsub,
6355 &AArch64::FPR32RegClass);
6356 BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
6357 .addReg(SrcReg, getKillRegState(KillSrc));
6358 }
6359 return;
6360 }
6361
6362 // Copies between GPR64 and FPR64.
6363 if (AArch64::FPR64RegClass.contains(DestReg) &&
6364 AArch64::GPR64RegClass.contains(SrcReg)) {
6365 if (AArch64::XZR == SrcReg) {
6366 BuildMI(MBB, I, DL, get(AArch64::FMOVD0), DestReg);
6367 } else {
6368 BuildMI(MBB, I, DL, get(AArch64::FMOVXDr), DestReg)
6369 .addReg(SrcReg, getKillRegState(KillSrc));
6370 }
6371 return;
6372 }
6373 if (AArch64::GPR64RegClass.contains(DestReg) &&
6374 AArch64::FPR64RegClass.contains(SrcReg)) {
6375 BuildMI(MBB, I, DL, get(AArch64::FMOVDXr), DestReg)
6376 .addReg(SrcReg, getKillRegState(KillSrc));
6377 return;
6378 }
6379 // Copies between GPR32 and FPR32.
6380 if (AArch64::FPR32RegClass.contains(DestReg) &&
6381 AArch64::GPR32RegClass.contains(SrcReg)) {
6382 if (AArch64::WZR == SrcReg) {
6383 BuildMI(MBB, I, DL, get(AArch64::FMOVS0), DestReg);
6384 } else {
6385 BuildMI(MBB, I, DL, get(AArch64::FMOVWSr), DestReg)
6386 .addReg(SrcReg, getKillRegState(KillSrc));
6387 }
6388 return;
6389 }
6390 if (AArch64::GPR32RegClass.contains(DestReg) &&
6391 AArch64::FPR32RegClass.contains(SrcReg)) {
6392 BuildMI(MBB, I, DL, get(AArch64::FMOVSWr), DestReg)
6393 .addReg(SrcReg, getKillRegState(KillSrc));
6394 return;
6395 }
6396
6397 if (DestReg == AArch64::NZCV) {
6398 assert(AArch64::GPR64RegClass.contains(SrcReg) && "Invalid NZCV copy");
6399 BuildMI(MBB, I, DL, get(AArch64::MSR))
6400 .addImm(AArch64SysReg::NZCV)
6401 .addReg(SrcReg, getKillRegState(KillSrc))
6402 .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define);
6403 return;
6404 }
6405
6406 if (SrcReg == AArch64::NZCV) {
6407 assert(AArch64::GPR64RegClass.contains(DestReg) && "Invalid NZCV copy");
6408 BuildMI(MBB, I, DL, get(AArch64::MRS), DestReg)
6409 .addImm(AArch64SysReg::NZCV)
6410 .addReg(AArch64::NZCV, RegState::Implicit | getKillRegState(KillSrc));
6411 return;
6412 }
6413
6414#ifndef NDEBUG
6415 errs() << RI.getRegAsmName(DestReg) << " = COPY " << RI.getRegAsmName(SrcReg)
6416 << "\n";
6417#endif
6418 llvm_unreachable("unimplemented reg-to-reg copy");
6419}
6420
6423 const DebugLoc &DL, Register DestReg,
6424 Register SrcReg, bool KillSrc,
6425 bool RenamableDest,
6426 bool RenamableSrc) const {
6427 ++NumCopyInstrs;
6428 copyPhysRegImpl(MBB, I, DL, DestReg, SrcReg, KillSrc, RenamableDest,
6429 RenamableSrc);
6430 return;
6431}
6432
6435 MachineBasicBlock::iterator InsertBefore,
6436 const MCInstrDesc &MCID,
6437 Register SrcReg, bool IsKill,
6438 unsigned SubIdx0, unsigned SubIdx1, int FI,
6439 MachineMemOperand *MMO) {
6440 Register SrcReg0 = SrcReg;
6441 Register SrcReg1 = SrcReg;
6442 if (SrcReg.isPhysical()) {
6443 SrcReg0 = TRI.getSubReg(SrcReg, SubIdx0);
6444 SubIdx0 = 0;
6445 SrcReg1 = TRI.getSubReg(SrcReg, SubIdx1);
6446 SubIdx1 = 0;
6447 }
6448 BuildMI(MBB, InsertBefore, DebugLoc(), MCID)
6449 .addReg(SrcReg0, getKillRegState(IsKill), SubIdx0)
6450 .addReg(SrcReg1, getKillRegState(IsKill), SubIdx1)
6451 .addFrameIndex(FI)
6452 .addImm(0)
6453 .addMemOperand(MMO);
6454}
6455
6458 Register SrcReg, bool isKill, int FI,
6459 const TargetRegisterClass *RC,
6460 Register VReg,
6461 MachineInstr::MIFlag Flags) const {
6462 MachineFunction &MF = *MBB.getParent();
6463 MachineFrameInfo &MFI = MF.getFrameInfo();
6464
6466 MachineMemOperand *MMO =
6468 MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
6469 unsigned Opc = 0;
6470 bool Offset = true;
6472 unsigned StackID = TargetStackID::Default;
6473 switch (RI.getSpillSize(*RC)) {
6474 case 1:
6475 if (AArch64::FPR8RegClass.hasSubClassEq(RC))
6476 Opc = AArch64::STRBui;
6477 break;
6478 case 2: {
6479 if (AArch64::FPR16RegClass.hasSubClassEq(RC))
6480 Opc = AArch64::STRHui;
6481 else if (AArch64::PNRRegClass.hasSubClassEq(RC) ||
6482 AArch64::PPRRegClass.hasSubClassEq(RC)) {
6483 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6484 "Unexpected register store without SVE store instructions");
6485 Opc = AArch64::STR_PXI;
6487 }
6488 break;
6489 }
6490 case 4:
6491 if (AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
6492 Opc = AArch64::STRWui;
6493 if (SrcReg.isVirtual())
6494 MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR32RegClass);
6495 else
6496 assert(SrcReg != AArch64::WSP);
6497 } else if (AArch64::FPR32RegClass.hasSubClassEq(RC))
6498 Opc = AArch64::STRSui;
6499 else if (AArch64::PPR2RegClass.hasSubClassEq(RC)) {
6500 Opc = AArch64::STR_PPXI;
6502 }
6503 break;
6504 case 8:
6505 if (AArch64::GPR64allRegClass.hasSubClassEq(RC)) {
6506 Opc = AArch64::STRXui;
6507 if (SrcReg.isVirtual())
6508 MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR64RegClass);
6509 else
6510 assert(SrcReg != AArch64::SP);
6511 } else if (AArch64::FPR64RegClass.hasSubClassEq(RC)) {
6512 Opc = AArch64::STRDui;
6513 } else if (AArch64::WSeqPairsClassRegClass.hasSubClassEq(RC)) {
6515 get(AArch64::STPWi), SrcReg, isKill,
6516 AArch64::sube32, AArch64::subo32, FI, MMO);
6517 return;
6518 }
6519 break;
6520 case 16:
6521 if (AArch64::FPR128RegClass.hasSubClassEq(RC))
6522 Opc = AArch64::STRQui;
6523 else if (AArch64::DDRegClass.hasSubClassEq(RC)) {
6524 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6525 Opc = AArch64::ST1Twov1d;
6526 Offset = false;
6527 } else if (AArch64::XSeqPairsClassRegClass.hasSubClassEq(RC)) {
6529 get(AArch64::STPXi), SrcReg, isKill,
6530 AArch64::sube64, AArch64::subo64, FI, MMO);
6531 return;
6532 } else if (AArch64::ZPRRegClass.hasSubClassEq(RC)) {
6533 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6534 "Unexpected register store without SVE store instructions");
6535 Opc = AArch64::STR_ZXI;
6537 }
6538 break;
6539 case 24:
6540 if (AArch64::DDDRegClass.hasSubClassEq(RC)) {
6541 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6542 Opc = AArch64::ST1Threev1d;
6543 Offset = false;
6544 }
6545 break;
6546 case 32:
6547 if (AArch64::DDDDRegClass.hasSubClassEq(RC)) {
6548 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6549 Opc = AArch64::ST1Fourv1d;
6550 Offset = false;
6551 } else if (AArch64::QQRegClass.hasSubClassEq(RC)) {
6552 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6553 Opc = AArch64::ST1Twov2d;
6554 Offset = false;
6555 } else if (AArch64::ZPR2StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6556 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6557 "Unexpected register store without SVE store instructions");
6558 Opc = AArch64::STR_ZZXI_STRIDED_CONTIGUOUS;
6560 } else if (AArch64::ZPR2RegClass.hasSubClassEq(RC)) {
6561 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6562 "Unexpected register store without SVE store instructions");
6563 Opc = AArch64::STR_ZZXI;
6565 }
6566 break;
6567 case 48:
6568 if (AArch64::QQQRegClass.hasSubClassEq(RC)) {
6569 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6570 Opc = AArch64::ST1Threev2d;
6571 Offset = false;
6572 } else if (AArch64::ZPR3RegClass.hasSubClassEq(RC)) {
6573 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6574 "Unexpected register store without SVE store instructions");
6575 Opc = AArch64::STR_ZZZXI;
6577 }
6578 break;
6579 case 64:
6580 if (AArch64::QQQQRegClass.hasSubClassEq(RC)) {
6581 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6582 Opc = AArch64::ST1Fourv2d;
6583 Offset = false;
6584 } else if (AArch64::ZPR4StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6585 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6586 "Unexpected register store without SVE store instructions");
6587 Opc = AArch64::STR_ZZZZXI_STRIDED_CONTIGUOUS;
6589 } else if (AArch64::ZPR4RegClass.hasSubClassEq(RC)) {
6590 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6591 "Unexpected register store without SVE store instructions");
6592 Opc = AArch64::STR_ZZZZXI;
6594 }
6595 break;
6596 }
6597 assert(Opc && "Unknown register class");
6598 MFI.setStackID(FI, StackID);
6599
6601 .addReg(SrcReg, getKillRegState(isKill))
6602 .addFrameIndex(FI);
6603
6604 if (Offset)
6605 MI.addImm(0);
6606 if (PNRReg.isValid())
6607 MI.addDef(PNRReg, RegState::Implicit);
6608 MI.addMemOperand(MMO);
6609}
6610
6613 MachineBasicBlock::iterator InsertBefore,
6614 const MCInstrDesc &MCID,
6615 Register DestReg, unsigned SubIdx0,
6616 unsigned SubIdx1, int FI,
6617 MachineMemOperand *MMO) {
6618 Register DestReg0 = DestReg;
6619 Register DestReg1 = DestReg;
6620 bool IsUndef = true;
6621 if (DestReg.isPhysical()) {
6622 DestReg0 = TRI.getSubReg(DestReg, SubIdx0);
6623 SubIdx0 = 0;
6624 DestReg1 = TRI.getSubReg(DestReg, SubIdx1);
6625 SubIdx1 = 0;
6626 IsUndef = false;
6627 }
6628 BuildMI(MBB, InsertBefore, DebugLoc(), MCID)
6629 .addReg(DestReg0, RegState::Define | getUndefRegState(IsUndef), SubIdx0)
6630 .addReg(DestReg1, RegState::Define | getUndefRegState(IsUndef), SubIdx1)
6631 .addFrameIndex(FI)
6632 .addImm(0)
6633 .addMemOperand(MMO);
6634}
6635
6638 Register DestReg, int FI,
6639 const TargetRegisterClass *RC,
6640 Register VReg, unsigned SubReg,
6641 MachineInstr::MIFlag Flags) const {
6642 MachineFunction &MF = *MBB.getParent();
6643 MachineFrameInfo &MFI = MF.getFrameInfo();
6645 MachineMemOperand *MMO =
6647 MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
6648
6649 unsigned Opc = 0;
6650 bool Offset = true;
6651 unsigned StackID = TargetStackID::Default;
6652 Register PNRReg;
6653 switch (TRI.getSpillSize(*RC)) {
6654 case 1:
6655 if (AArch64::FPR8RegClass.hasSubClassEq(RC))
6656 Opc = AArch64::LDRBui;
6657 break;
6658 case 2: {
6659 bool IsPNR = AArch64::PNRRegClass.hasSubClassEq(RC);
6660 if (AArch64::FPR16RegClass.hasSubClassEq(RC))
6661 Opc = AArch64::LDRHui;
6662 else if (IsPNR || AArch64::PPRRegClass.hasSubClassEq(RC)) {
6663 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6664 "Unexpected register load without SVE load instructions");
6665 if (IsPNR)
6666 PNRReg = DestReg;
6667 Opc = AArch64::LDR_PXI;
6669 }
6670 break;
6671 }
6672 case 4:
6673 if (AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
6674 Opc = AArch64::LDRWui;
6675 if (DestReg.isVirtual())
6676 MF.getRegInfo().constrainRegClass(DestReg, &AArch64::GPR32RegClass);
6677 else
6678 assert(DestReg != AArch64::WSP);
6679 } else if (AArch64::FPR32RegClass.hasSubClassEq(RC))
6680 Opc = AArch64::LDRSui;
6681 else if (AArch64::PPR2RegClass.hasSubClassEq(RC)) {
6682 Opc = AArch64::LDR_PPXI;
6684 }
6685 break;
6686 case 8:
6687 if (AArch64::GPR64allRegClass.hasSubClassEq(RC)) {
6688 Opc = AArch64::LDRXui;
6689 if (DestReg.isVirtual())
6690 MF.getRegInfo().constrainRegClass(DestReg, &AArch64::GPR64RegClass);
6691 else
6692 assert(DestReg != AArch64::SP);
6693 } else if (AArch64::FPR64RegClass.hasSubClassEq(RC)) {
6694 Opc = AArch64::LDRDui;
6695 } else if (AArch64::WSeqPairsClassRegClass.hasSubClassEq(RC)) {
6697 get(AArch64::LDPWi), DestReg, AArch64::sube32,
6698 AArch64::subo32, FI, MMO);
6699 return;
6700 }
6701 break;
6702 case 16:
6703 if (AArch64::FPR128RegClass.hasSubClassEq(RC))
6704 Opc = AArch64::LDRQui;
6705 else if (AArch64::DDRegClass.hasSubClassEq(RC)) {
6706 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6707 Opc = AArch64::LD1Twov1d;
6708 Offset = false;
6709 } else if (AArch64::XSeqPairsClassRegClass.hasSubClassEq(RC)) {
6711 get(AArch64::LDPXi), DestReg, AArch64::sube64,
6712 AArch64::subo64, FI, MMO);
6713 return;
6714 } else if (AArch64::ZPRRegClass.hasSubClassEq(RC)) {
6715 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6716 "Unexpected register load without SVE load instructions");
6717 Opc = AArch64::LDR_ZXI;
6719 }
6720 break;
6721 case 24:
6722 if (AArch64::DDDRegClass.hasSubClassEq(RC)) {
6723 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6724 Opc = AArch64::LD1Threev1d;
6725 Offset = false;
6726 }
6727 break;
6728 case 32:
6729 if (AArch64::DDDDRegClass.hasSubClassEq(RC)) {
6730 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6731 Opc = AArch64::LD1Fourv1d;
6732 Offset = false;
6733 } else if (AArch64::QQRegClass.hasSubClassEq(RC)) {
6734 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6735 Opc = AArch64::LD1Twov2d;
6736 Offset = false;
6737 } else if (AArch64::ZPR2StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6738 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6739 "Unexpected register load without SVE load instructions");
6740 Opc = AArch64::LDR_ZZXI_STRIDED_CONTIGUOUS;
6742 } else if (AArch64::ZPR2RegClass.hasSubClassEq(RC)) {
6743 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6744 "Unexpected register load without SVE load instructions");
6745 Opc = AArch64::LDR_ZZXI;
6747 }
6748 break;
6749 case 48:
6750 if (AArch64::QQQRegClass.hasSubClassEq(RC)) {
6751 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6752 Opc = AArch64::LD1Threev2d;
6753 Offset = false;
6754 } else if (AArch64::ZPR3RegClass.hasSubClassEq(RC)) {
6755 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6756 "Unexpected register load without SVE load instructions");
6757 Opc = AArch64::LDR_ZZZXI;
6759 }
6760 break;
6761 case 64:
6762 if (AArch64::QQQQRegClass.hasSubClassEq(RC)) {
6763 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6764 Opc = AArch64::LD1Fourv2d;
6765 Offset = false;
6766 } else if (AArch64::ZPR4StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6767 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6768 "Unexpected register load without SVE load instructions");
6769 Opc = AArch64::LDR_ZZZZXI_STRIDED_CONTIGUOUS;
6771 } else if (AArch64::ZPR4RegClass.hasSubClassEq(RC)) {
6772 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6773 "Unexpected register load without SVE load instructions");
6774 Opc = AArch64::LDR_ZZZZXI;
6776 }
6777 break;
6778 }
6779
6780 assert(Opc && "Unknown register class");
6781 MFI.setStackID(FI, StackID);
6782
6784 .addReg(DestReg, getDefRegState(true))
6785 .addFrameIndex(FI);
6786 if (Offset)
6787 MI.addImm(0);
6788 if (PNRReg.isValid() && !PNRReg.isVirtual())
6789 MI.addDef(PNRReg, RegState::Implicit);
6790 MI.addMemOperand(MMO);
6791}
6792
6794 const MachineInstr &UseMI,
6795 const TargetRegisterInfo *TRI) {
6796 return any_of(instructionsWithoutDebug(std::next(DefMI.getIterator()),
6797 UseMI.getIterator()),
6798 [TRI](const MachineInstr &I) {
6799 return I.modifiesRegister(AArch64::NZCV, TRI) ||
6800 I.readsRegister(AArch64::NZCV, TRI);
6801 });
6802}
6803
6804void AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(
6805 const StackOffset &Offset, int64_t &ByteSized, int64_t &VGSized) {
6806 // The smallest scalable element supported by scaled SVE addressing
6807 // modes are predicates, which are 2 scalable bytes in size. So the scalable
6808 // byte offset must always be a multiple of 2.
6809 assert(Offset.getScalable() % 2 == 0 && "Invalid frame offset");
6810
6811 // VGSized offsets are divided by '2', because the VG register is the
6812 // the number of 64bit granules as opposed to 128bit vector chunks,
6813 // which is how the 'n' in e.g. MVT::nxv1i8 is modelled.
6814 // So, for a stack offset of 16 MVT::nxv1i8's, the size is n x 16 bytes.
6815 // VG = n * 2 and the dwarf offset must be VG * 8 bytes.
6816 ByteSized = Offset.getFixed();
6817 VGSized = Offset.getScalable() / 2;
6818}
6819
6820/// Returns the offset in parts to which this frame offset can be
6821/// decomposed for the purpose of describing a frame offset.
6822/// For non-scalable offsets this is simply its byte size.
6823void AArch64InstrInfo::decomposeStackOffsetForFrameOffsets(
6824 const StackOffset &Offset, int64_t &NumBytes, int64_t &NumPredicateVectors,
6825 int64_t &NumDataVectors) {
6826 // The smallest scalable element supported by scaled SVE addressing
6827 // modes are predicates, which are 2 scalable bytes in size. So the scalable
6828 // byte offset must always be a multiple of 2.
6829 assert(Offset.getScalable() % 2 == 0 && "Invalid frame offset");
6830
6831 NumBytes = Offset.getFixed();
6832 NumDataVectors = 0;
6833 NumPredicateVectors = Offset.getScalable() / 2;
6834 // This method is used to get the offsets to adjust the frame offset.
6835 // If the function requires ADDPL to be used and needs more than two ADDPL
6836 // instructions, part of the offset is folded into NumDataVectors so that it
6837 // uses ADDVL for part of it, reducing the number of ADDPL instructions.
6838 if (NumPredicateVectors % 8 == 0 || NumPredicateVectors < -64 ||
6839 NumPredicateVectors > 62) {
6840 NumDataVectors = NumPredicateVectors / 8;
6841 NumPredicateVectors -= NumDataVectors * 8;
6842 }
6843}
6844
6845// Convenience function to create a DWARF expression for: Constant `Operation`.
6846// This helper emits compact sequences for common cases. For example, for`-15
6847// DW_OP_plus`, this helper would create DW_OP_lit15 DW_OP_minus.
6850 if (Operation == dwarf::DW_OP_plus && Constant < 0 && -Constant <= 31) {
6851 // -Constant (1 to 31)
6852 Expr.push_back(dwarf::DW_OP_lit0 - Constant);
6853 Operation = dwarf::DW_OP_minus;
6854 } else if (Constant >= 0 && Constant <= 31) {
6855 // Literal value 0 to 31
6856 Expr.push_back(dwarf::DW_OP_lit0 + Constant);
6857 } else {
6858 // Signed constant
6859 Expr.push_back(dwarf::DW_OP_consts);
6861 }
6862 return Expr.push_back(Operation);
6863}
6864
6865// Convenience function to create a DWARF expression for a register.
6866static void appendReadRegExpr(SmallVectorImpl<char> &Expr, unsigned RegNum) {
6867 Expr.push_back((char)dwarf::DW_OP_bregx);
6869 Expr.push_back(0);
6870}
6871
6872// Convenience function to create a DWARF expression for loading a register from
6873// a CFA offset.
6875 int64_t OffsetFromDefCFA) {
6876 // This assumes the top of the DWARF stack contains the CFA.
6877 Expr.push_back(dwarf::DW_OP_dup);
6878 // Add the offset to the register.
6879 appendConstantExpr(Expr, OffsetFromDefCFA, dwarf::DW_OP_plus);
6880 // Dereference the address (loads a 64 bit value)..
6881 Expr.push_back(dwarf::DW_OP_deref);
6882}
6883
6884// Convenience function to create a comment for
6885// (+/-) NumBytes (* RegScale)?
6886static void appendOffsetComment(int NumBytes, llvm::raw_string_ostream &Comment,
6887 StringRef RegScale = {}) {
6888 if (NumBytes) {
6889 Comment << (NumBytes < 0 ? " - " : " + ") << std::abs(NumBytes);
6890 if (!RegScale.empty())
6891 Comment << ' ' << RegScale;
6892 }
6893}
6894
6895// Creates an MCCFIInstruction:
6896// { DW_CFA_def_cfa_expression, ULEB128 (sizeof expr), expr }
6898 unsigned Reg,
6899 const StackOffset &Offset) {
6900 int64_t NumBytes, NumVGScaledBytes;
6901 AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(Offset, NumBytes,
6902 NumVGScaledBytes);
6903 std::string CommentBuffer;
6904 llvm::raw_string_ostream Comment(CommentBuffer);
6905
6906 if (Reg == AArch64::SP)
6907 Comment << "sp";
6908 else if (Reg == AArch64::FP)
6909 Comment << "fp";
6910 else
6911 Comment << printReg(Reg, &TRI);
6912
6913 // Build up the expression (Reg + NumBytes + VG * NumVGScaledBytes)
6914 SmallString<64> Expr;
6915 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
6916 assert(DwarfReg <= 31 && "DwarfReg out of bounds (0..31)");
6917 // Reg + NumBytes
6918 Expr.push_back(dwarf::DW_OP_breg0 + DwarfReg);
6919 appendLEB128<LEB128Sign::Signed>(Expr, NumBytes);
6920 appendOffsetComment(NumBytes, Comment);
6921 if (NumVGScaledBytes) {
6922 // + VG * NumVGScaledBytes
6923 appendOffsetComment(NumVGScaledBytes, Comment, "* VG");
6924 appendReadRegExpr(Expr, TRI.getDwarfRegNum(AArch64::VG, true));
6925 appendConstantExpr(Expr, NumVGScaledBytes, dwarf::DW_OP_mul);
6926 Expr.push_back(dwarf::DW_OP_plus);
6927 }
6928
6929 // Wrap this into DW_CFA_def_cfa.
6930 SmallString<64> DefCfaExpr;
6931 DefCfaExpr.push_back(dwarf::DW_CFA_def_cfa_expression);
6932 appendLEB128<LEB128Sign::Unsigned>(DefCfaExpr, Expr.size());
6933 DefCfaExpr.append(Expr.str());
6934 return MCCFIInstruction::createEscape(nullptr, DefCfaExpr.str(), SMLoc(),
6935 Comment.str());
6936}
6937
6939 unsigned FrameReg, unsigned Reg,
6940 const StackOffset &Offset,
6941 bool LastAdjustmentWasScalable) {
6942 if (Offset.getScalable())
6943 return createDefCFAExpression(TRI, Reg, Offset);
6944
6945 if (FrameReg == Reg && !LastAdjustmentWasScalable)
6946 return MCCFIInstruction::cfiDefCfaOffset(nullptr, int(Offset.getFixed()));
6947
6948 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
6949 return MCCFIInstruction::cfiDefCfa(nullptr, DwarfReg, (int)Offset.getFixed());
6950}
6951
6954 const StackOffset &OffsetFromDefCFA,
6955 std::optional<int64_t> IncomingVGOffsetFromDefCFA) {
6956 int64_t NumBytes, NumVGScaledBytes;
6957 AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(
6958 OffsetFromDefCFA, NumBytes, NumVGScaledBytes);
6959
6960 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
6961
6962 // Non-scalable offsets can use DW_CFA_offset directly.
6963 if (!NumVGScaledBytes)
6964 return MCCFIInstruction::createOffset(nullptr, DwarfReg, NumBytes);
6965
6966 std::string CommentBuffer;
6967 llvm::raw_string_ostream Comment(CommentBuffer);
6968 Comment << printReg(Reg, &TRI) << " @ cfa";
6969
6970 // Build up expression (CFA + VG * NumVGScaledBytes + NumBytes)
6971 assert(NumVGScaledBytes && "Expected scalable offset");
6972 SmallString<64> OffsetExpr;
6973 // + VG * NumVGScaledBytes
6974 StringRef VGRegScale;
6975 if (IncomingVGOffsetFromDefCFA) {
6976 appendLoadRegExpr(OffsetExpr, *IncomingVGOffsetFromDefCFA);
6977 VGRegScale = "* IncomingVG";
6978 } else {
6979 appendReadRegExpr(OffsetExpr, TRI.getDwarfRegNum(AArch64::VG, true));
6980 VGRegScale = "* VG";
6981 }
6982 appendConstantExpr(OffsetExpr, NumVGScaledBytes, dwarf::DW_OP_mul);
6983 appendOffsetComment(NumVGScaledBytes, Comment, VGRegScale);
6984 OffsetExpr.push_back(dwarf::DW_OP_plus);
6985 if (NumBytes) {
6986 // + NumBytes
6987 appendOffsetComment(NumBytes, Comment);
6988 appendConstantExpr(OffsetExpr, NumBytes, dwarf::DW_OP_plus);
6989 }
6990
6991 // Wrap this into DW_CFA_expression
6992 SmallString<64> CfaExpr;
6993 CfaExpr.push_back(dwarf::DW_CFA_expression);
6994 appendLEB128<LEB128Sign::Unsigned>(CfaExpr, DwarfReg);
6995 appendLEB128<LEB128Sign::Unsigned>(CfaExpr, OffsetExpr.size());
6996 CfaExpr.append(OffsetExpr.str());
6997
6998 return MCCFIInstruction::createEscape(nullptr, CfaExpr.str(), SMLoc(),
6999 Comment.str());
7000}
7001
7002// Helper function to emit a frame offset adjustment from a given
7003// pointer (SrcReg), stored into DestReg. This function is explicit
7004// in that it requires the opcode.
7007 const DebugLoc &DL, unsigned DestReg,
7008 unsigned SrcReg, int64_t Offset, unsigned Opc,
7009 const TargetInstrInfo *TII,
7010 MachineInstr::MIFlag Flag, bool NeedsWinCFI,
7011 bool *HasWinCFI, bool EmitCFAOffset,
7012 StackOffset CFAOffset, unsigned FrameReg) {
7013 int Sign = 1;
7014 unsigned MaxEncoding, ShiftSize;
7015 switch (Opc) {
7016 case AArch64::ADDXri:
7017 case AArch64::ADDSXri:
7018 case AArch64::SUBXri:
7019 case AArch64::SUBSXri:
7020 MaxEncoding = 0xfff;
7021 ShiftSize = 12;
7022 break;
7023 case AArch64::ADDVL_XXI:
7024 case AArch64::ADDPL_XXI:
7025 case AArch64::ADDSVL_XXI:
7026 case AArch64::ADDSPL_XXI:
7027 MaxEncoding = 31;
7028 ShiftSize = 0;
7029 if (Offset < 0) {
7030 MaxEncoding = 32;
7031 Sign = -1;
7032 Offset = -Offset;
7033 }
7034 break;
7035 default:
7036 llvm_unreachable("Unsupported opcode");
7037 }
7038
7039 // `Offset` can be in bytes or in "scalable bytes".
7040 int VScale = 1;
7041 if (Opc == AArch64::ADDVL_XXI || Opc == AArch64::ADDSVL_XXI)
7042 VScale = 16;
7043 else if (Opc == AArch64::ADDPL_XXI || Opc == AArch64::ADDSPL_XXI)
7044 VScale = 2;
7045
7046 // FIXME: If the offset won't fit in 24-bits, compute the offset into a
7047 // scratch register. If DestReg is a virtual register, use it as the
7048 // scratch register; otherwise, create a new virtual register (to be
7049 // replaced by the scavenger at the end of PEI). That case can be optimized
7050 // slightly if DestReg is SP which is always 16-byte aligned, so the scratch
7051 // register can be loaded with offset%8 and the add/sub can use an extending
7052 // instruction with LSL#3.
7053 // Currently the function handles any offsets but generates a poor sequence
7054 // of code.
7055 // assert(Offset < (1 << 24) && "unimplemented reg plus immediate");
7056
7057 const unsigned MaxEncodableValue = MaxEncoding << ShiftSize;
7058 Register TmpReg = DestReg;
7059 if (TmpReg == AArch64::XZR)
7060 TmpReg = MBB.getParent()->getRegInfo().createVirtualRegister(
7061 &AArch64::GPR64RegClass);
7062 do {
7063 uint64_t ThisVal = std::min<uint64_t>(Offset, MaxEncodableValue);
7064 unsigned LocalShiftSize = 0;
7065 if (ThisVal > MaxEncoding) {
7066 ThisVal = ThisVal >> ShiftSize;
7067 LocalShiftSize = ShiftSize;
7068 }
7069 assert((ThisVal >> ShiftSize) <= MaxEncoding &&
7070 "Encoding cannot handle value that big");
7071
7072 Offset -= ThisVal << LocalShiftSize;
7073 if (Offset == 0)
7074 TmpReg = DestReg;
7075 auto MBI = BuildMI(MBB, MBBI, DL, TII->get(Opc), TmpReg)
7076 .addReg(SrcReg)
7077 .addImm(Sign * (int)ThisVal);
7078 if (ShiftSize)
7079 MBI = MBI.addImm(
7081 MBI = MBI.setMIFlag(Flag);
7082
7083 auto Change =
7084 VScale == 1
7085 ? StackOffset::getFixed(ThisVal << LocalShiftSize)
7086 : StackOffset::getScalable(VScale * (ThisVal << LocalShiftSize));
7087 if (Sign == -1 || Opc == AArch64::SUBXri || Opc == AArch64::SUBSXri)
7088 CFAOffset += Change;
7089 else
7090 CFAOffset -= Change;
7091 if (EmitCFAOffset && DestReg == TmpReg) {
7092 MachineFunction &MF = *MBB.getParent();
7093 const TargetSubtargetInfo &STI = MF.getSubtarget();
7094 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
7095
7096 unsigned CFIIndex = MF.addFrameInst(
7097 createDefCFA(TRI, FrameReg, DestReg, CFAOffset, VScale != 1));
7098 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
7099 .addCFIIndex(CFIIndex)
7100 .setMIFlags(Flag);
7101 }
7102
7103 if (NeedsWinCFI) {
7104 int Imm = (int)(ThisVal << LocalShiftSize);
7105 if (VScale != 1 && DestReg == AArch64::SP) {
7106 if (HasWinCFI)
7107 *HasWinCFI = true;
7108 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_AllocZ))
7109 .addImm(ThisVal)
7110 .setMIFlag(Flag);
7111 } else if ((DestReg == AArch64::FP && SrcReg == AArch64::SP) ||
7112 (SrcReg == AArch64::FP && DestReg == AArch64::SP)) {
7113 assert(VScale == 1 && "Expected non-scalable operation");
7114 if (HasWinCFI)
7115 *HasWinCFI = true;
7116 if (Imm == 0)
7117 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_SetFP)).setMIFlag(Flag);
7118 else
7119 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_AddFP))
7120 .addImm(Imm)
7121 .setMIFlag(Flag);
7122 assert(Offset == 0 && "Expected remaining offset to be zero to "
7123 "emit a single SEH directive");
7124 } else if (DestReg == AArch64::SP) {
7125 assert(VScale == 1 && "Expected non-scalable operation");
7126 if (HasWinCFI)
7127 *HasWinCFI = true;
7128 assert(SrcReg == AArch64::SP && "Unexpected SrcReg for SEH_StackAlloc");
7129 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
7130 .addImm(Imm)
7131 .setMIFlag(Flag);
7132 }
7133 }
7134
7135 SrcReg = TmpReg;
7136 } while (Offset);
7137}
7138
7141 unsigned DestReg, unsigned SrcReg,
7143 MachineInstr::MIFlag Flag, bool SetNZCV,
7144 bool NeedsWinCFI, bool *HasWinCFI,
7145 bool EmitCFAOffset, StackOffset CFAOffset,
7146 unsigned FrameReg) {
7147 // If a function is marked as arm_locally_streaming, then the runtime value of
7148 // vscale in the prologue/epilogue is different the runtime value of vscale
7149 // in the function's body. To avoid having to consider multiple vscales,
7150 // we can use `addsvl` to allocate any scalable stack-slots, which under
7151 // most circumstances will be only locals, not callee-save slots.
7152 const Function &F = MBB.getParent()->getFunction();
7153 bool UseSVL = F.hasFnAttribute("aarch64_pstate_sm_body");
7154
7155 int64_t Bytes, NumPredicateVectors, NumDataVectors;
7156 AArch64InstrInfo::decomposeStackOffsetForFrameOffsets(
7157 Offset, Bytes, NumPredicateVectors, NumDataVectors);
7158
7159 // Insert ADDSXri for scalable offset at the end.
7160 bool NeedsFinalDefNZCV = SetNZCV && (NumPredicateVectors || NumDataVectors);
7161 if (NeedsFinalDefNZCV)
7162 SetNZCV = false;
7163
7164 // First emit non-scalable frame offsets, or a simple 'mov'.
7165 if (Bytes || (!Offset && SrcReg != DestReg)) {
7166 assert((DestReg != AArch64::SP || Bytes % 8 == 0) &&
7167 "SP increment/decrement not 8-byte aligned");
7168 unsigned Opc = SetNZCV ? AArch64::ADDSXri : AArch64::ADDXri;
7169 if (Bytes < 0) {
7170 Bytes = -Bytes;
7171 Opc = SetNZCV ? AArch64::SUBSXri : AArch64::SUBXri;
7172 }
7173 emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, Bytes, Opc, TII, Flag,
7174 NeedsWinCFI, HasWinCFI, EmitCFAOffset, CFAOffset,
7175 FrameReg);
7176 CFAOffset += (Opc == AArch64::ADDXri || Opc == AArch64::ADDSXri)
7177 ? StackOffset::getFixed(-Bytes)
7178 : StackOffset::getFixed(Bytes);
7179 SrcReg = DestReg;
7180 FrameReg = DestReg;
7181 }
7182
7183 assert(!(NeedsWinCFI && NumPredicateVectors) &&
7184 "WinCFI can't allocate fractions of an SVE data vector");
7185
7186 if (NumDataVectors) {
7187 emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, NumDataVectors,
7188 UseSVL ? AArch64::ADDSVL_XXI : AArch64::ADDVL_XXI, TII,
7189 Flag, NeedsWinCFI, HasWinCFI, EmitCFAOffset, CFAOffset,
7190 FrameReg);
7191 CFAOffset += StackOffset::getScalable(-NumDataVectors * 16);
7192 SrcReg = DestReg;
7193 }
7194
7195 if (NumPredicateVectors) {
7196 assert(DestReg != AArch64::SP && "Unaligned access to SP");
7197 emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, NumPredicateVectors,
7198 UseSVL ? AArch64::ADDSPL_XXI : AArch64::ADDPL_XXI, TII,
7199 Flag, NeedsWinCFI, HasWinCFI, EmitCFAOffset, CFAOffset,
7200 FrameReg);
7201 }
7202
7203 if (NeedsFinalDefNZCV)
7204 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ADDSXri), DestReg)
7205 .addReg(DestReg)
7206 .addImm(0)
7207 .addImm(0);
7208}
7209
7212 int FrameIndex, MachineInstr *&CopyMI, LiveIntervals *LIS,
7213 VirtRegMap *VRM) const {
7215 // This is a bit of a hack. Consider this instruction:
7216 //
7217 // %0 = COPY %sp; GPR64all:%0
7218 //
7219 // We explicitly chose GPR64all for the virtual register so such a copy might
7220 // be eliminated by RegisterCoalescer. However, that may not be possible, and
7221 // %0 may even spill. We can't spill %sp, and since it is in the GPR64all
7222 // register class, TargetInstrInfo::foldMemoryOperand() is going to try.
7223 //
7224 // To prevent that, we are going to constrain the %0 register class here.
7225 if (MI.isFullCopy()) {
7226 Register DstReg = MI.getOperand(0).getReg();
7227 Register SrcReg = MI.getOperand(1).getReg();
7228 if (SrcReg == AArch64::SP && DstReg.isVirtual()) {
7229 MF.getRegInfo().constrainRegClass(DstReg, &AArch64::GPR64RegClass);
7230 return nullptr;
7231 }
7232 if (DstReg == AArch64::SP && SrcReg.isVirtual()) {
7233 MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR64RegClass);
7234 return nullptr;
7235 }
7236 // Nothing can folded with copy from/to NZCV.
7237 if (SrcReg == AArch64::NZCV || DstReg == AArch64::NZCV)
7238 return nullptr;
7239 }
7240
7241 // Handle the case where a copy is being spilled or filled but the source
7242 // and destination register class don't match. For example:
7243 //
7244 // %0 = COPY %xzr; GPR64common:%0
7245 //
7246 // In this case we can still safely fold away the COPY and generate the
7247 // following spill code:
7248 //
7249 // STRXui %xzr, %stack.0
7250 //
7251 // This also eliminates spilled cross register class COPYs (e.g. between x and
7252 // d regs) of the same size. For example:
7253 //
7254 // %0 = COPY %1; GPR64:%0, FPR64:%1
7255 //
7256 // will be filled as
7257 //
7258 // LDRDui %0, fi<#0>
7259 //
7260 // instead of
7261 //
7262 // LDRXui %Temp, fi<#0>
7263 // %0 = FMOV %Temp
7264 //
7265 if (MI.isCopy() && Ops.size() == 1 &&
7266 // Make sure we're only folding the explicit COPY defs/uses.
7267 (Ops[0] == 0 || Ops[0] == 1)) {
7268 bool IsSpill = Ops[0] == 0;
7269 bool IsFill = !IsSpill;
7271 const MachineRegisterInfo &MRI = MF.getRegInfo();
7272 MachineBasicBlock &MBB = *MI.getParent();
7273 const MachineOperand &DstMO = MI.getOperand(0);
7274 const MachineOperand &SrcMO = MI.getOperand(1);
7275 Register DstReg = DstMO.getReg();
7276 Register SrcReg = SrcMO.getReg();
7277 // This is slightly expensive to compute for physical regs since
7278 // getMinimalPhysRegClass is slow.
7279 auto getRegClass = [&](unsigned Reg) {
7280 return Register::isVirtualRegister(Reg) ? MRI.getRegClass(Reg)
7281 : TRI.getMinimalPhysRegClass(Reg);
7282 };
7283
7284 if (DstMO.getSubReg() == 0 && SrcMO.getSubReg() == 0) {
7285 assert(TRI.getRegSizeInBits(*getRegClass(DstReg)) ==
7286 TRI.getRegSizeInBits(*getRegClass(SrcReg)) &&
7287 "Mismatched register size in non subreg COPY");
7288 if (IsSpill)
7289 storeRegToStackSlot(MBB, InsertPt, SrcReg, SrcMO.isKill(), FrameIndex,
7290 getRegClass(SrcReg), Register());
7291 else
7292 loadRegFromStackSlot(MBB, InsertPt, DstReg, FrameIndex,
7293 getRegClass(DstReg), Register());
7294 return &*--InsertPt;
7295 }
7296
7297 // Handle cases like spilling def of:
7298 //
7299 // %0:sub_32<def,read-undef> = COPY %wzr; GPR64common:%0
7300 //
7301 // where the physical register source can be widened and stored to the full
7302 // virtual reg destination stack slot, in this case producing:
7303 //
7304 // STRXui %xzr, %stack.0
7305 //
7306 if (IsSpill && DstMO.isUndef() && SrcReg == AArch64::WZR &&
7307 TRI.getRegSizeInBits(*getRegClass(DstReg)) == 64) {
7308 assert(SrcMO.getSubReg() == 0 &&
7309 "Unexpected subreg on physical register");
7310 storeRegToStackSlot(MBB, InsertPt, AArch64::XZR, SrcMO.isKill(),
7311 FrameIndex, &AArch64::GPR64RegClass, Register());
7312 return &*--InsertPt;
7313 }
7314
7315 // Handle cases like filling use of:
7316 //
7317 // %0:sub_32<def,read-undef> = COPY %1; GPR64:%0, GPR32:%1
7318 //
7319 // where we can load the full virtual reg source stack slot, into the subreg
7320 // destination, in this case producing:
7321 //
7322 // LDRWui %0:sub_32<def,read-undef>, %stack.0
7323 //
7324 if (IsFill && SrcMO.getSubReg() == 0 && DstMO.isUndef()) {
7325 const TargetRegisterClass *FillRC = nullptr;
7326 switch (DstMO.getSubReg()) {
7327 default:
7328 break;
7329 case AArch64::sub_32:
7330 if (AArch64::GPR64RegClass.hasSubClassEq(getRegClass(DstReg)))
7331 FillRC = &AArch64::GPR32RegClass;
7332 break;
7333 case AArch64::ssub:
7334 FillRC = &AArch64::FPR32RegClass;
7335 break;
7336 case AArch64::dsub:
7337 FillRC = &AArch64::FPR64RegClass;
7338 break;
7339 }
7340
7341 if (FillRC) {
7342 assert(TRI.getRegSizeInBits(*getRegClass(SrcReg)) ==
7343 TRI.getRegSizeInBits(*FillRC) &&
7344 "Mismatched regclass size on folded subreg COPY");
7345 loadRegFromStackSlot(MBB, InsertPt, DstReg, FrameIndex, FillRC,
7346 Register());
7347 MachineInstr &LoadMI = *--InsertPt;
7348 MachineOperand &LoadDst = LoadMI.getOperand(0);
7349 assert(LoadDst.getSubReg() == 0 && "unexpected subreg on fill load");
7350 LoadDst.setSubReg(DstMO.getSubReg());
7351 LoadDst.setIsUndef();
7352 return &LoadMI;
7353 }
7354 }
7355 }
7356
7357 // Cannot fold.
7358 return nullptr;
7359}
7360
7362 StackOffset &SOffset,
7363 bool *OutUseUnscaledOp,
7364 unsigned *OutUnscaledOp,
7365 int64_t *EmittableOffset) {
7366 // Set output values in case of early exit.
7367 if (EmittableOffset)
7368 *EmittableOffset = 0;
7369 if (OutUseUnscaledOp)
7370 *OutUseUnscaledOp = false;
7371 if (OutUnscaledOp)
7372 *OutUnscaledOp = 0;
7373
7374 // Exit early for structured vector spills/fills as they can't take an
7375 // immediate offset.
7376 switch (MI.getOpcode()) {
7377 default:
7378 break;
7379 case AArch64::LD1Rv1d:
7380 case AArch64::LD1Rv2s:
7381 case AArch64::LD1Rv2d:
7382 case AArch64::LD1Rv4h:
7383 case AArch64::LD1Rv4s:
7384 case AArch64::LD1Rv8b:
7385 case AArch64::LD1Rv8h:
7386 case AArch64::LD1Rv16b:
7387 case AArch64::LD1Twov2d:
7388 case AArch64::LD1Threev2d:
7389 case AArch64::LD1Fourv2d:
7390 case AArch64::LD1Twov1d:
7391 case AArch64::LD1Threev1d:
7392 case AArch64::LD1Fourv1d:
7393 case AArch64::ST1Twov2d:
7394 case AArch64::ST1Threev2d:
7395 case AArch64::ST1Fourv2d:
7396 case AArch64::ST1Twov1d:
7397 case AArch64::ST1Threev1d:
7398 case AArch64::ST1Fourv1d:
7399 case AArch64::ST1i8:
7400 case AArch64::ST1i16:
7401 case AArch64::ST1i32:
7402 case AArch64::ST1i64:
7403 case AArch64::IRG:
7404 case AArch64::IRGstack:
7405 case AArch64::STGloop:
7406 case AArch64::STZGloop:
7408 }
7409
7410 // Get the min/max offset and the scale.
7411 TypeSize ScaleValue(0U, false), Width(0U, false);
7412 int64_t MinOff, MaxOff;
7413 if (!AArch64InstrInfo::getMemOpInfo(MI.getOpcode(), ScaleValue, Width, MinOff,
7414 MaxOff))
7415 llvm_unreachable("unhandled opcode in isAArch64FrameOffsetLegal");
7416
7417 // Construct the complete offset.
7418 bool IsMulVL = ScaleValue.isScalable();
7419 unsigned Scale = ScaleValue.getKnownMinValue();
7420 int64_t Offset = IsMulVL ? SOffset.getScalable() : SOffset.getFixed();
7421
7422 const MachineOperand &ImmOpnd =
7423 MI.getOperand(AArch64InstrInfo::getLoadStoreImmIdx(MI.getOpcode()));
7424 Offset += ImmOpnd.getImm() * Scale;
7425
7426 // If the offset doesn't match the scale, we rewrite the instruction to
7427 // use the unscaled instruction instead. Likewise, if we have a negative
7428 // offset and there is an unscaled op to use.
7429 std::optional<unsigned> UnscaledOp =
7431 bool useUnscaledOp = UnscaledOp && (Offset % Scale || Offset < 0);
7432 if (useUnscaledOp &&
7433 !AArch64InstrInfo::getMemOpInfo(*UnscaledOp, ScaleValue, Width, MinOff,
7434 MaxOff))
7435 llvm_unreachable("unhandled opcode in isAArch64FrameOffsetLegal");
7436
7437 Scale = ScaleValue.getKnownMinValue();
7438 assert(IsMulVL == ScaleValue.isScalable() &&
7439 "Unscaled opcode has different value for scalable");
7440
7441 int64_t Remainder = Offset % Scale;
7442 assert(!(Remainder && useUnscaledOp) &&
7443 "Cannot have remainder when using unscaled op");
7444
7445 assert(MinOff < MaxOff && "Unexpected Min/Max offsets");
7446 int64_t NewOffset = Offset / Scale;
7447 if (MinOff <= NewOffset && NewOffset <= MaxOff)
7448 Offset = Remainder;
7449 else {
7450 // Try to minimise the number of instructions required to materialise the
7451 // offset calculation. Specifically, for fixed offsets, if masking out the
7452 // low 12 bits leaves a legal add immediate, we can realise the offset
7453 // calculation with a single add instruction. Whenever this is possible,
7454 // prefer this split.
7455 int64_t HighPart = Offset & ~0xFFF;
7456 int64_t LowPart = Offset & 0xFFF;
7457 int64_t LowScaled = LowPart / Scale;
7458 if (!IsMulVL && NewOffset >= 0 && LowPart % Scale == 0 &&
7459 MinOff <= LowScaled && LowScaled <= MaxOff &&
7461 NewOffset = LowScaled;
7462 Offset = HighPart;
7463 } else {
7464 // Default to a greedy split: take the memop immediate to be maximum /
7465 // minimum expressible offset and materialise the remainder.
7466 NewOffset = NewOffset < 0 ? MinOff : MaxOff;
7467 Offset = Offset - (NewOffset * Scale);
7468 }
7469 }
7470
7471 if (EmittableOffset)
7472 *EmittableOffset = NewOffset;
7473 if (OutUseUnscaledOp)
7474 *OutUseUnscaledOp = useUnscaledOp;
7475 if (OutUnscaledOp && UnscaledOp)
7476 *OutUnscaledOp = *UnscaledOp;
7477
7478 if (IsMulVL)
7479 SOffset = StackOffset::get(SOffset.getFixed(), Offset);
7480 else
7481 SOffset = StackOffset::get(Offset, SOffset.getScalable());
7483 (SOffset ? 0 : AArch64FrameOffsetIsLegal);
7484}
7485
7487 unsigned FrameReg, StackOffset &Offset,
7488 const AArch64InstrInfo *TII) {
7489 unsigned Opcode = MI.getOpcode();
7490 unsigned ImmIdx = FrameRegIdx + 1;
7491
7492 if (Opcode == AArch64::ADDSXri || Opcode == AArch64::ADDXri) {
7493 Offset += StackOffset::getFixed(MI.getOperand(ImmIdx).getImm());
7494 emitFrameOffset(*MI.getParent(), MI, MI.getDebugLoc(),
7495 MI.getOperand(0).getReg(), FrameReg, Offset, TII,
7496 MachineInstr::NoFlags, (Opcode == AArch64::ADDSXri));
7497 MI.eraseFromParent();
7498 Offset = StackOffset();
7499 return true;
7500 }
7501
7502 int64_t NewOffset;
7503 unsigned UnscaledOp;
7504 bool UseUnscaledOp;
7505 int Status = isAArch64FrameOffsetLegal(MI, Offset, &UseUnscaledOp,
7506 &UnscaledOp, &NewOffset);
7509 // Replace the FrameIndex with FrameReg.
7510 MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
7511 if (UseUnscaledOp)
7512 MI.setDesc(TII->get(UnscaledOp));
7513
7514 MI.getOperand(ImmIdx).ChangeToImmediate(NewOffset);
7515 return !Offset;
7516 }
7517
7518 return false;
7519}
7520
7526
7527MCInst AArch64InstrInfo::getNop() const { return MCInstBuilder(AArch64::NOP); }
7528
7529// AArch64 supports MachineCombiner.
7530bool AArch64InstrInfo::useMachineCombiner() const { return true; }
7531
7532// True when Opc sets flag
7533static bool isCombineInstrSettingFlag(unsigned Opc) {
7534 switch (Opc) {
7535 case AArch64::ADDSWrr:
7536 case AArch64::ADDSWri:
7537 case AArch64::ADDSXrr:
7538 case AArch64::ADDSXri:
7539 case AArch64::SUBSWrr:
7540 case AArch64::SUBSXrr:
7541 // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
7542 case AArch64::SUBSWri:
7543 case AArch64::SUBSXri:
7544 return true;
7545 default:
7546 break;
7547 }
7548 return false;
7549}
7550
7551// 32b Opcodes that can be combined with a MUL
7552static bool isCombineInstrCandidate32(unsigned Opc) {
7553 switch (Opc) {
7554 case AArch64::ADDWrr:
7555 case AArch64::ADDWri:
7556 case AArch64::ADDWrs:
7557 case AArch64::SUBWrr:
7558 case AArch64::ADDSWrr:
7559 case AArch64::ADDSWri:
7560 case AArch64::SUBSWrr:
7561 // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
7562 case AArch64::SUBWri:
7563 case AArch64::SUBSWri:
7564 return true;
7565 default:
7566 break;
7567 }
7568 return false;
7569}
7570
7571// 64b Opcodes that can be combined with a MUL
7572static bool isCombineInstrCandidate64(unsigned Opc) {
7573 switch (Opc) {
7574 case AArch64::ADDXrr:
7575 case AArch64::ADDXri:
7576 case AArch64::ADDXrs:
7577 case AArch64::SUBXrr:
7578 case AArch64::ADDSXrr:
7579 case AArch64::ADDSXri:
7580 case AArch64::SUBSXrr:
7581 // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
7582 case AArch64::SUBXri:
7583 case AArch64::SUBSXri:
7584 case AArch64::ADDv8i8:
7585 case AArch64::ADDv16i8:
7586 case AArch64::ADDv4i16:
7587 case AArch64::ADDv8i16:
7588 case AArch64::ADDv2i32:
7589 case AArch64::ADDv4i32:
7590 case AArch64::SUBv8i8:
7591 case AArch64::SUBv16i8:
7592 case AArch64::SUBv4i16:
7593 case AArch64::SUBv8i16:
7594 case AArch64::SUBv2i32:
7595 case AArch64::SUBv4i32:
7596 return true;
7597 default:
7598 break;
7599 }
7600 return false;
7601}
7602
7603// FP Opcodes that can be combined with a FMUL.
7604static bool isCombineInstrCandidateFP(const MachineInstr &Inst) {
7605 switch (Inst.getOpcode()) {
7606 default:
7607 break;
7608 case AArch64::FADDHrr:
7609 case AArch64::FADDSrr:
7610 case AArch64::FADDDrr:
7611 case AArch64::FADDv4f16:
7612 case AArch64::FADDv8f16:
7613 case AArch64::FADDv2f32:
7614 case AArch64::FADDv2f64:
7615 case AArch64::FADDv4f32:
7616 case AArch64::FSUBHrr:
7617 case AArch64::FSUBSrr:
7618 case AArch64::FSUBDrr:
7619 case AArch64::FSUBv4f16:
7620 case AArch64::FSUBv8f16:
7621 case AArch64::FSUBv2f32:
7622 case AArch64::FSUBv2f64:
7623 case AArch64::FSUBv4f32:
7624 // We can fuse FADD/FSUB with FMUL, if FADD/FSUB has the contract fast-math
7625 // flag.
7626 return Inst.getFlag(MachineInstr::FmContract);
7627 }
7628 return false;
7629}
7630
7631// Opcodes that can be combined with a MUL
7635
7636//
7637// Utility routine that checks if \param MO is defined by an
7638// \param CombineOpc instruction in the basic block \param MBB
7640 unsigned CombineOpc, unsigned ZeroReg = 0,
7641 bool CheckZeroReg = false) {
7642 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
7643 MachineInstr *MI = nullptr;
7644
7645 if (MO.isReg() && MO.getReg().isVirtual())
7646 MI = MRI.getUniqueVRegDef(MO.getReg());
7647 // And it needs to be in the trace (otherwise, it won't have a depth).
7648 if (!MI || MI->getParent() != &MBB || MI->getOpcode() != CombineOpc)
7649 return false;
7650 // Must only used by the user we combine with.
7651 if (!MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()))
7652 return false;
7653
7654 if (CheckZeroReg) {
7655 assert(MI->getNumOperands() >= 4 && MI->getOperand(0).isReg() &&
7656 MI->getOperand(1).isReg() && MI->getOperand(2).isReg() &&
7657 MI->getOperand(3).isReg() && "MAdd/MSub must have a least 4 regs");
7658 // The third input reg must be zero.
7659 if (MI->getOperand(3).getReg() != ZeroReg)
7660 return false;
7661 }
7662
7663 if (isCombineInstrSettingFlag(CombineOpc) &&
7664 MI->findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true) == -1)
7665 return false;
7666
7667 return true;
7668}
7669
7670//
7671// Is \param MO defined by an integer multiply and can be combined?
7673 unsigned MulOpc, unsigned ZeroReg) {
7674 return canCombine(MBB, MO, MulOpc, ZeroReg, true);
7675}
7676
7677//
7678// Is \param MO defined by a floating-point multiply and can be combined?
7680 unsigned MulOpc) {
7681 return canCombine(MBB, MO, MulOpc);
7682}
7683
7684// TODO: There are many more machine instruction opcodes to match:
7685// 1. Other data types (integer, vectors)
7686// 2. Other math / logic operations (xor, or)
7687// 3. Other forms of the same operation (intrinsics and other variants)
7688bool AArch64InstrInfo::isAssociativeAndCommutative(const MachineInstr &Inst,
7689 bool Invert) const {
7690 if (Invert)
7691 return false;
7692 switch (Inst.getOpcode()) {
7693 // == Floating-point types ==
7694 // -- Floating-point instructions --
7695 case AArch64::FADDHrr:
7696 case AArch64::FADDSrr:
7697 case AArch64::FADDDrr:
7698 case AArch64::FMULHrr:
7699 case AArch64::FMULSrr:
7700 case AArch64::FMULDrr:
7701 case AArch64::FMULX16:
7702 case AArch64::FMULX32:
7703 case AArch64::FMULX64:
7704 // -- Advanced SIMD instructions --
7705 case AArch64::FADDv4f16:
7706 case AArch64::FADDv8f16:
7707 case AArch64::FADDv2f32:
7708 case AArch64::FADDv4f32:
7709 case AArch64::FADDv2f64:
7710 case AArch64::FMULv4f16:
7711 case AArch64::FMULv8f16:
7712 case AArch64::FMULv2f32:
7713 case AArch64::FMULv4f32:
7714 case AArch64::FMULv2f64:
7715 case AArch64::FMULXv4f16:
7716 case AArch64::FMULXv8f16:
7717 case AArch64::FMULXv2f32:
7718 case AArch64::FMULXv4f32:
7719 case AArch64::FMULXv2f64:
7720 // -- SVE instructions --
7721 // Opcodes FMULX_ZZZ_? don't exist because there is no unpredicated FMULX
7722 // in the SVE instruction set (though there are predicated ones).
7723 case AArch64::FADD_ZZZ_H:
7724 case AArch64::FADD_ZZZ_S:
7725 case AArch64::FADD_ZZZ_D:
7726 case AArch64::FMUL_ZZZ_H:
7727 case AArch64::FMUL_ZZZ_S:
7728 case AArch64::FMUL_ZZZ_D:
7731
7732 // == Integer types ==
7733 // -- Base instructions --
7734 // Opcodes MULWrr and MULXrr don't exist because
7735 // `MUL <Wd>, <Wn>, <Wm>` and `MUL <Xd>, <Xn>, <Xm>` are aliases of
7736 // `MADD <Wd>, <Wn>, <Wm>, WZR` and `MADD <Xd>, <Xn>, <Xm>, XZR` respectively.
7737 // The machine-combiner does not support three-source-operands machine
7738 // instruction. So we cannot reassociate MULs.
7739 case AArch64::ADDWrr:
7740 case AArch64::ADDXrr:
7741 case AArch64::ANDWrr:
7742 case AArch64::ANDXrr:
7743 case AArch64::ORRWrr:
7744 case AArch64::ORRXrr:
7745 case AArch64::EORWrr:
7746 case AArch64::EORXrr:
7747 case AArch64::EONWrr:
7748 case AArch64::EONXrr:
7749 // -- Advanced SIMD instructions --
7750 // Opcodes MULv1i64 and MULv2i64 don't exist because there is no 64-bit MUL
7751 // in the Advanced SIMD instruction set.
7752 case AArch64::ADDv8i8:
7753 case AArch64::ADDv16i8:
7754 case AArch64::ADDv4i16:
7755 case AArch64::ADDv8i16:
7756 case AArch64::ADDv2i32:
7757 case AArch64::ADDv4i32:
7758 case AArch64::ADDv1i64:
7759 case AArch64::ADDv2i64:
7760 case AArch64::MULv8i8:
7761 case AArch64::MULv16i8:
7762 case AArch64::MULv4i16:
7763 case AArch64::MULv8i16:
7764 case AArch64::MULv2i32:
7765 case AArch64::MULv4i32:
7766 case AArch64::ANDv8i8:
7767 case AArch64::ANDv16i8:
7768 case AArch64::ORRv8i8:
7769 case AArch64::ORRv16i8:
7770 case AArch64::EORv8i8:
7771 case AArch64::EORv16i8:
7772 // -- SVE instructions --
7773 case AArch64::ADD_ZZZ_B:
7774 case AArch64::ADD_ZZZ_H:
7775 case AArch64::ADD_ZZZ_S:
7776 case AArch64::ADD_ZZZ_D:
7777 case AArch64::MUL_ZZZ_B:
7778 case AArch64::MUL_ZZZ_H:
7779 case AArch64::MUL_ZZZ_S:
7780 case AArch64::MUL_ZZZ_D:
7781 case AArch64::AND_ZZZ:
7782 case AArch64::ORR_ZZZ:
7783 case AArch64::EOR_ZZZ:
7784 return true;
7785
7786 default:
7787 return false;
7788 }
7789}
7790
7791/// Find instructions that can be turned into madd.
7793 SmallVectorImpl<unsigned> &Patterns) {
7794 unsigned Opc = Root.getOpcode();
7795 MachineBasicBlock &MBB = *Root.getParent();
7796 bool Found = false;
7797
7799 return false;
7801 int Cmp_NZCV =
7802 Root.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true);
7803 // When NZCV is live bail out.
7804 if (Cmp_NZCV == -1)
7805 return false;
7806 unsigned NewOpc = convertToNonFlagSettingOpc(Root);
7807 // When opcode can't change bail out.
7808 // CHECKME: do we miss any cases for opcode conversion?
7809 if (NewOpc == Opc)
7810 return false;
7811 Opc = NewOpc;
7812 }
7813
7814 auto setFound = [&](int Opcode, int Operand, unsigned ZeroReg,
7815 unsigned Pattern) {
7816 if (canCombineWithMUL(MBB, Root.getOperand(Operand), Opcode, ZeroReg)) {
7817 Patterns.push_back(Pattern);
7818 Found = true;
7819 }
7820 };
7821
7822 const AArch64Subtarget &STI =
7823 MBB.getParent()->getSubtarget<AArch64Subtarget>();
7824 auto setShfFound = [&](int Opcode, unsigned ZeroReg, unsigned Pattern) {
7825 // TODO: Currently its not possible to reject the combine for Apple targets
7826 // based on the scheduling model, because we have gaps in modeling and
7827 // analysis. Once we fill the gaps, remove the subtarget feature and the
7828 // associated check here.
7829 if (STI.hasShiftMaddSlow())
7830 return;
7831
7832 unsigned ShiftImm = Root.getOperand(3).getImm();
7834
7835 if ((ShiftTy != AArch64_AM::LSL && ShiftTy != AArch64_AM::LSR &&
7836 ShiftTy != AArch64_AM::ASR) ||
7837 AArch64_AM::getShiftValue(ShiftImm) == 0)
7838 return;
7839
7840 if (!canCombineWithMUL(MBB, Root.getOperand(1), Opcode, ZeroReg))
7841 return;
7842
7843 Patterns.push_back(Pattern);
7844 Found = true;
7845 };
7846
7847 auto setVFound = [&](int Opcode, int Operand, unsigned Pattern) {
7848 if (canCombine(MBB, Root.getOperand(Operand), Opcode)) {
7849 Patterns.push_back(Pattern);
7850 Found = true;
7851 }
7852 };
7853
7855
7856 switch (Opc) {
7857 default:
7858 break;
7859 case AArch64::ADDWrr:
7860 assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
7861 "ADDWrr does not have register operands");
7862 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULADDW_OP1);
7863 setFound(AArch64::MADDWrrr, 2, AArch64::WZR, MCP::MULADDW_OP2);
7864 break;
7865 case AArch64::ADDXrr:
7866 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULADDX_OP1);
7867 setFound(AArch64::MADDXrrr, 2, AArch64::XZR, MCP::MULADDX_OP2);
7868 break;
7869 case AArch64::SUBWrr:
7870 setFound(AArch64::MADDWrrr, 2, AArch64::WZR, MCP::MULSUBW_OP2);
7871 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULSUBW_OP1);
7872 break;
7873 case AArch64::SUBXrr:
7874 setFound(AArch64::MADDXrrr, 2, AArch64::XZR, MCP::MULSUBX_OP2);
7875 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULSUBX_OP1);
7876 break;
7877 case AArch64::ADDWri:
7878 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULADDWI_OP1);
7879 break;
7880 case AArch64::ADDXri:
7881 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULADDXI_OP1);
7882 break;
7883 case AArch64::SUBWri:
7884 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULSUBWI_OP1);
7885 break;
7886 case AArch64::SUBXri:
7887 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULSUBXI_OP1);
7888 break;
7889 case AArch64::ADDWrs:
7890 setShfFound(AArch64::MADDWrrr, AArch64::WZR, MCP::MULADDWS_OP1);
7891 break;
7892 case AArch64::ADDXrs:
7893 setShfFound(AArch64::MADDXrrr, AArch64::XZR, MCP::MULADDXS_OP1);
7894 break;
7895 case AArch64::ADDv8i8:
7896 setVFound(AArch64::MULv8i8, 1, MCP::MULADDv8i8_OP1);
7897 setVFound(AArch64::MULv8i8, 2, MCP::MULADDv8i8_OP2);
7898 break;
7899 case AArch64::ADDv16i8:
7900 setVFound(AArch64::MULv16i8, 1, MCP::MULADDv16i8_OP1);
7901 setVFound(AArch64::MULv16i8, 2, MCP::MULADDv16i8_OP2);
7902 break;
7903 case AArch64::ADDv4i16:
7904 setVFound(AArch64::MULv4i16, 1, MCP::MULADDv4i16_OP1);
7905 setVFound(AArch64::MULv4i16, 2, MCP::MULADDv4i16_OP2);
7906 setVFound(AArch64::MULv4i16_indexed, 1, MCP::MULADDv4i16_indexed_OP1);
7907 setVFound(AArch64::MULv4i16_indexed, 2, MCP::MULADDv4i16_indexed_OP2);
7908 break;
7909 case AArch64::ADDv8i16:
7910 setVFound(AArch64::MULv8i16, 1, MCP::MULADDv8i16_OP1);
7911 setVFound(AArch64::MULv8i16, 2, MCP::MULADDv8i16_OP2);
7912 setVFound(AArch64::MULv8i16_indexed, 1, MCP::MULADDv8i16_indexed_OP1);
7913 setVFound(AArch64::MULv8i16_indexed, 2, MCP::MULADDv8i16_indexed_OP2);
7914 break;
7915 case AArch64::ADDv2i32:
7916 setVFound(AArch64::MULv2i32, 1, MCP::MULADDv2i32_OP1);
7917 setVFound(AArch64::MULv2i32, 2, MCP::MULADDv2i32_OP2);
7918 setVFound(AArch64::MULv2i32_indexed, 1, MCP::MULADDv2i32_indexed_OP1);
7919 setVFound(AArch64::MULv2i32_indexed, 2, MCP::MULADDv2i32_indexed_OP2);
7920 break;
7921 case AArch64::ADDv4i32:
7922 setVFound(AArch64::MULv4i32, 1, MCP::MULADDv4i32_OP1);
7923 setVFound(AArch64::MULv4i32, 2, MCP::MULADDv4i32_OP2);
7924 setVFound(AArch64::MULv4i32_indexed, 1, MCP::MULADDv4i32_indexed_OP1);
7925 setVFound(AArch64::MULv4i32_indexed, 2, MCP::MULADDv4i32_indexed_OP2);
7926 break;
7927 case AArch64::SUBv8i8:
7928 setVFound(AArch64::MULv8i8, 1, MCP::MULSUBv8i8_OP1);
7929 setVFound(AArch64::MULv8i8, 2, MCP::MULSUBv8i8_OP2);
7930 break;
7931 case AArch64::SUBv16i8:
7932 setVFound(AArch64::MULv16i8, 1, MCP::MULSUBv16i8_OP1);
7933 setVFound(AArch64::MULv16i8, 2, MCP::MULSUBv16i8_OP2);
7934 break;
7935 case AArch64::SUBv4i16:
7936 setVFound(AArch64::MULv4i16, 1, MCP::MULSUBv4i16_OP1);
7937 setVFound(AArch64::MULv4i16, 2, MCP::MULSUBv4i16_OP2);
7938 setVFound(AArch64::MULv4i16_indexed, 1, MCP::MULSUBv4i16_indexed_OP1);
7939 setVFound(AArch64::MULv4i16_indexed, 2, MCP::MULSUBv4i16_indexed_OP2);
7940 break;
7941 case AArch64::SUBv8i16:
7942 setVFound(AArch64::MULv8i16, 1, MCP::MULSUBv8i16_OP1);
7943 setVFound(AArch64::MULv8i16, 2, MCP::MULSUBv8i16_OP2);
7944 setVFound(AArch64::MULv8i16_indexed, 1, MCP::MULSUBv8i16_indexed_OP1);
7945 setVFound(AArch64::MULv8i16_indexed, 2, MCP::MULSUBv8i16_indexed_OP2);
7946 break;
7947 case AArch64::SUBv2i32:
7948 setVFound(AArch64::MULv2i32, 1, MCP::MULSUBv2i32_OP1);
7949 setVFound(AArch64::MULv2i32, 2, MCP::MULSUBv2i32_OP2);
7950 setVFound(AArch64::MULv2i32_indexed, 1, MCP::MULSUBv2i32_indexed_OP1);
7951 setVFound(AArch64::MULv2i32_indexed, 2, MCP::MULSUBv2i32_indexed_OP2);
7952 break;
7953 case AArch64::SUBv4i32:
7954 setVFound(AArch64::MULv4i32, 1, MCP::MULSUBv4i32_OP1);
7955 setVFound(AArch64::MULv4i32, 2, MCP::MULSUBv4i32_OP2);
7956 setVFound(AArch64::MULv4i32_indexed, 1, MCP::MULSUBv4i32_indexed_OP1);
7957 setVFound(AArch64::MULv4i32_indexed, 2, MCP::MULSUBv4i32_indexed_OP2);
7958 break;
7959 }
7960 return Found;
7961}
7962
7963bool AArch64InstrInfo::isAccumulationOpcode(unsigned Opcode) const {
7964 switch (Opcode) {
7965 default:
7966 break;
7967 case AArch64::UABALB_ZZZ_D:
7968 case AArch64::UABALB_ZZZ_H:
7969 case AArch64::UABALB_ZZZ_S:
7970 case AArch64::UABALT_ZZZ_D:
7971 case AArch64::UABALT_ZZZ_H:
7972 case AArch64::UABALT_ZZZ_S:
7973 case AArch64::SABALB_ZZZ_D:
7974 case AArch64::SABALB_ZZZ_S:
7975 case AArch64::SABALB_ZZZ_H:
7976 case AArch64::SABALT_ZZZ_D:
7977 case AArch64::SABALT_ZZZ_S:
7978 case AArch64::SABALT_ZZZ_H:
7979 case AArch64::UABALv16i8_v8i16:
7980 case AArch64::UABALv2i32_v2i64:
7981 case AArch64::UABALv4i16_v4i32:
7982 case AArch64::UABALv4i32_v2i64:
7983 case AArch64::UABALv8i16_v4i32:
7984 case AArch64::UABALv8i8_v8i16:
7985 case AArch64::UABAv16i8:
7986 case AArch64::UABAv2i32:
7987 case AArch64::UABAv4i16:
7988 case AArch64::UABAv4i32:
7989 case AArch64::UABAv8i16:
7990 case AArch64::UABAv8i8:
7991 case AArch64::SABALv16i8_v8i16:
7992 case AArch64::SABALv2i32_v2i64:
7993 case AArch64::SABALv4i16_v4i32:
7994 case AArch64::SABALv4i32_v2i64:
7995 case AArch64::SABALv8i16_v4i32:
7996 case AArch64::SABALv8i8_v8i16:
7997 case AArch64::SABAv16i8:
7998 case AArch64::SABAv2i32:
7999 case AArch64::SABAv4i16:
8000 case AArch64::SABAv4i32:
8001 case AArch64::SABAv8i16:
8002 case AArch64::SABAv8i8:
8003 return true;
8004 }
8005
8006 return false;
8007}
8008
8009unsigned AArch64InstrInfo::getAccumulationStartOpcode(
8010 unsigned AccumulationOpcode) const {
8011 switch (AccumulationOpcode) {
8012 default:
8013 llvm_unreachable("Unsupported accumulation Opcode!");
8014 case AArch64::UABALB_ZZZ_D:
8015 return AArch64::UABDLB_ZZZ_D;
8016 case AArch64::UABALB_ZZZ_H:
8017 return AArch64::UABDLB_ZZZ_H;
8018 case AArch64::UABALB_ZZZ_S:
8019 return AArch64::UABDLB_ZZZ_S;
8020 case AArch64::UABALT_ZZZ_D:
8021 return AArch64::UABDLT_ZZZ_D;
8022 case AArch64::UABALT_ZZZ_H:
8023 return AArch64::UABDLT_ZZZ_H;
8024 case AArch64::UABALT_ZZZ_S:
8025 return AArch64::UABDLT_ZZZ_S;
8026 case AArch64::UABALv16i8_v8i16:
8027 return AArch64::UABDLv16i8_v8i16;
8028 case AArch64::UABALv2i32_v2i64:
8029 return AArch64::UABDLv2i32_v2i64;
8030 case AArch64::UABALv4i16_v4i32:
8031 return AArch64::UABDLv4i16_v4i32;
8032 case AArch64::UABALv4i32_v2i64:
8033 return AArch64::UABDLv4i32_v2i64;
8034 case AArch64::UABALv8i16_v4i32:
8035 return AArch64::UABDLv8i16_v4i32;
8036 case AArch64::UABALv8i8_v8i16:
8037 return AArch64::UABDLv8i8_v8i16;
8038 case AArch64::UABAv16i8:
8039 return AArch64::UABDv16i8;
8040 case AArch64::UABAv2i32:
8041 return AArch64::UABDv2i32;
8042 case AArch64::UABAv4i16:
8043 return AArch64::UABDv4i16;
8044 case AArch64::UABAv4i32:
8045 return AArch64::UABDv4i32;
8046 case AArch64::UABAv8i16:
8047 return AArch64::UABDv8i16;
8048 case AArch64::UABAv8i8:
8049 return AArch64::UABDv8i8;
8050 case AArch64::SABALB_ZZZ_D:
8051 return AArch64::SABDLB_ZZZ_D;
8052 case AArch64::SABALB_ZZZ_S:
8053 return AArch64::SABDLB_ZZZ_S;
8054 case AArch64::SABALB_ZZZ_H:
8055 return AArch64::SABDLB_ZZZ_H;
8056 case AArch64::SABALT_ZZZ_D:
8057 return AArch64::SABDLT_ZZZ_D;
8058 case AArch64::SABALT_ZZZ_S:
8059 return AArch64::SABDLT_ZZZ_S;
8060 case AArch64::SABALT_ZZZ_H:
8061 return AArch64::SABDLT_ZZZ_H;
8062 case AArch64::SABALv16i8_v8i16:
8063 return AArch64::SABDLv16i8_v8i16;
8064 case AArch64::SABALv2i32_v2i64:
8065 return AArch64::SABDLv2i32_v2i64;
8066 case AArch64::SABALv4i16_v4i32:
8067 return AArch64::SABDLv4i16_v4i32;
8068 case AArch64::SABALv4i32_v2i64:
8069 return AArch64::SABDLv4i32_v2i64;
8070 case AArch64::SABALv8i16_v4i32:
8071 return AArch64::SABDLv8i16_v4i32;
8072 case AArch64::SABALv8i8_v8i16:
8073 return AArch64::SABDLv8i8_v8i16;
8074 case AArch64::SABAv16i8:
8075 return AArch64::SABDv16i8;
8076 case AArch64::SABAv2i32:
8077 return AArch64::SABDv2i32;
8078 case AArch64::SABAv4i16:
8079 return AArch64::SABDv4i16;
8080 case AArch64::SABAv4i32:
8081 return AArch64::SABDv4i32;
8082 case AArch64::SABAv8i16:
8083 return AArch64::SABDv8i16;
8084 case AArch64::SABAv8i8:
8085 return AArch64::SABDv8i8;
8086 }
8087}
8088
8089/// Floating-Point Support
8090
8091/// Find instructions that can be turned into madd.
8093 SmallVectorImpl<unsigned> &Patterns) {
8094
8095 if (!isCombineInstrCandidateFP(Root))
8096 return false;
8097
8098 MachineBasicBlock &MBB = *Root.getParent();
8099 bool Found = false;
8100
8101 auto Match = [&](int Opcode, int Operand, unsigned Pattern) -> bool {
8102 if (canCombineWithFMUL(MBB, Root.getOperand(Operand), Opcode)) {
8103 Patterns.push_back(Pattern);
8104 return true;
8105 }
8106 return false;
8107 };
8108
8110
8111 switch (Root.getOpcode()) {
8112 default:
8113 assert(false && "Unsupported FP instruction in combiner\n");
8114 break;
8115 case AArch64::FADDHrr:
8116 assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
8117 "FADDHrr does not have register operands");
8118
8119 Found = Match(AArch64::FMULHrr, 1, MCP::FMULADDH_OP1);
8120 Found |= Match(AArch64::FMULHrr, 2, MCP::FMULADDH_OP2);
8121 break;
8122 case AArch64::FADDSrr:
8123 assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
8124 "FADDSrr does not have register operands");
8125
8126 Found |= Match(AArch64::FMULSrr, 1, MCP::FMULADDS_OP1) ||
8127 Match(AArch64::FMULv1i32_indexed, 1, MCP::FMLAv1i32_indexed_OP1);
8128
8129 Found |= Match(AArch64::FMULSrr, 2, MCP::FMULADDS_OP2) ||
8130 Match(AArch64::FMULv1i32_indexed, 2, MCP::FMLAv1i32_indexed_OP2);
8131 break;
8132 case AArch64::FADDDrr:
8133 Found |= Match(AArch64::FMULDrr, 1, MCP::FMULADDD_OP1) ||
8134 Match(AArch64::FMULv1i64_indexed, 1, MCP::FMLAv1i64_indexed_OP1);
8135
8136 Found |= Match(AArch64::FMULDrr, 2, MCP::FMULADDD_OP2) ||
8137 Match(AArch64::FMULv1i64_indexed, 2, MCP::FMLAv1i64_indexed_OP2);
8138 break;
8139 case AArch64::FADDv4f16:
8140 Found |= Match(AArch64::FMULv4i16_indexed, 1, MCP::FMLAv4i16_indexed_OP1) ||
8141 Match(AArch64::FMULv4f16, 1, MCP::FMLAv4f16_OP1);
8142
8143 Found |= Match(AArch64::FMULv4i16_indexed, 2, MCP::FMLAv4i16_indexed_OP2) ||
8144 Match(AArch64::FMULv4f16, 2, MCP::FMLAv4f16_OP2);
8145 break;
8146 case AArch64::FADDv8f16:
8147 Found |= Match(AArch64::FMULv8i16_indexed, 1, MCP::FMLAv8i16_indexed_OP1) ||
8148 Match(AArch64::FMULv8f16, 1, MCP::FMLAv8f16_OP1);
8149
8150 Found |= Match(AArch64::FMULv8i16_indexed, 2, MCP::FMLAv8i16_indexed_OP2) ||
8151 Match(AArch64::FMULv8f16, 2, MCP::FMLAv8f16_OP2);
8152 break;
8153 case AArch64::FADDv2f32:
8154 Found |= Match(AArch64::FMULv2i32_indexed, 1, MCP::FMLAv2i32_indexed_OP1) ||
8155 Match(AArch64::FMULv2f32, 1, MCP::FMLAv2f32_OP1);
8156
8157 Found |= Match(AArch64::FMULv2i32_indexed, 2, MCP::FMLAv2i32_indexed_OP2) ||
8158 Match(AArch64::FMULv2f32, 2, MCP::FMLAv2f32_OP2);
8159 break;
8160 case AArch64::FADDv2f64:
8161 Found |= Match(AArch64::FMULv2i64_indexed, 1, MCP::FMLAv2i64_indexed_OP1) ||
8162 Match(AArch64::FMULv2f64, 1, MCP::FMLAv2f64_OP1);
8163
8164 Found |= Match(AArch64::FMULv2i64_indexed, 2, MCP::FMLAv2i64_indexed_OP2) ||
8165 Match(AArch64::FMULv2f64, 2, MCP::FMLAv2f64_OP2);
8166 break;
8167 case AArch64::FADDv4f32:
8168 Found |= Match(AArch64::FMULv4i32_indexed, 1, MCP::FMLAv4i32_indexed_OP1) ||
8169 Match(AArch64::FMULv4f32, 1, MCP::FMLAv4f32_OP1);
8170
8171 Found |= Match(AArch64::FMULv4i32_indexed, 2, MCP::FMLAv4i32_indexed_OP2) ||
8172 Match(AArch64::FMULv4f32, 2, MCP::FMLAv4f32_OP2);
8173 break;
8174 case AArch64::FSUBHrr:
8175 Found = Match(AArch64::FMULHrr, 1, MCP::FMULSUBH_OP1);
8176 Found |= Match(AArch64::FMULHrr, 2, MCP::FMULSUBH_OP2);
8177 Found |= Match(AArch64::FNMULHrr, 1, MCP::FNMULSUBH_OP1);
8178 break;
8179 case AArch64::FSUBSrr:
8180 Found = Match(AArch64::FMULSrr, 1, MCP::FMULSUBS_OP1);
8181
8182 Found |= Match(AArch64::FMULSrr, 2, MCP::FMULSUBS_OP2) ||
8183 Match(AArch64::FMULv1i32_indexed, 2, MCP::FMLSv1i32_indexed_OP2);
8184
8185 Found |= Match(AArch64::FNMULSrr, 1, MCP::FNMULSUBS_OP1);
8186 break;
8187 case AArch64::FSUBDrr:
8188 Found = Match(AArch64::FMULDrr, 1, MCP::FMULSUBD_OP1);
8189
8190 Found |= Match(AArch64::FMULDrr, 2, MCP::FMULSUBD_OP2) ||
8191 Match(AArch64::FMULv1i64_indexed, 2, MCP::FMLSv1i64_indexed_OP2);
8192
8193 Found |= Match(AArch64::FNMULDrr, 1, MCP::FNMULSUBD_OP1);
8194 break;
8195 case AArch64::FSUBv4f16:
8196 Found |= Match(AArch64::FMULv4i16_indexed, 2, MCP::FMLSv4i16_indexed_OP2) ||
8197 Match(AArch64::FMULv4f16, 2, MCP::FMLSv4f16_OP2);
8198
8199 Found |= Match(AArch64::FMULv4i16_indexed, 1, MCP::FMLSv4i16_indexed_OP1) ||
8200 Match(AArch64::FMULv4f16, 1, MCP::FMLSv4f16_OP1);
8201 break;
8202 case AArch64::FSUBv8f16:
8203 Found |= Match(AArch64::FMULv8i16_indexed, 2, MCP::FMLSv8i16_indexed_OP2) ||
8204 Match(AArch64::FMULv8f16, 2, MCP::FMLSv8f16_OP2);
8205
8206 Found |= Match(AArch64::FMULv8i16_indexed, 1, MCP::FMLSv8i16_indexed_OP1) ||
8207 Match(AArch64::FMULv8f16, 1, MCP::FMLSv8f16_OP1);
8208 break;
8209 case AArch64::FSUBv2f32:
8210 Found |= Match(AArch64::FMULv2i32_indexed, 2, MCP::FMLSv2i32_indexed_OP2) ||
8211 Match(AArch64::FMULv2f32, 2, MCP::FMLSv2f32_OP2);
8212
8213 Found |= Match(AArch64::FMULv2i32_indexed, 1, MCP::FMLSv2i32_indexed_OP1) ||
8214 Match(AArch64::FMULv2f32, 1, MCP::FMLSv2f32_OP1);
8215 break;
8216 case AArch64::FSUBv2f64:
8217 Found |= Match(AArch64::FMULv2i64_indexed, 2, MCP::FMLSv2i64_indexed_OP2) ||
8218 Match(AArch64::FMULv2f64, 2, MCP::FMLSv2f64_OP2);
8219
8220 Found |= Match(AArch64::FMULv2i64_indexed, 1, MCP::FMLSv2i64_indexed_OP1) ||
8221 Match(AArch64::FMULv2f64, 1, MCP::FMLSv2f64_OP1);
8222 break;
8223 case AArch64::FSUBv4f32:
8224 Found |= Match(AArch64::FMULv4i32_indexed, 2, MCP::FMLSv4i32_indexed_OP2) ||
8225 Match(AArch64::FMULv4f32, 2, MCP::FMLSv4f32_OP2);
8226
8227 Found |= Match(AArch64::FMULv4i32_indexed, 1, MCP::FMLSv4i32_indexed_OP1) ||
8228 Match(AArch64::FMULv4f32, 1, MCP::FMLSv4f32_OP1);
8229 break;
8230 }
8231 return Found;
8232}
8233
8235 SmallVectorImpl<unsigned> &Patterns) {
8236 MachineBasicBlock &MBB = *Root.getParent();
8237 bool Found = false;
8238
8239 auto Match = [&](unsigned Opcode, int Operand, unsigned Pattern) -> bool {
8240 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
8241 MachineOperand &MO = Root.getOperand(Operand);
8242 MachineInstr *MI = nullptr;
8243 if (MO.isReg() && MO.getReg().isVirtual())
8244 MI = MRI.getUniqueVRegDef(MO.getReg());
8245 // Ignore No-op COPYs in FMUL(COPY(DUP(..)))
8246 if (MI && MI->getOpcode() == TargetOpcode::COPY &&
8247 MI->getOperand(1).getReg().isVirtual())
8248 MI = MRI.getUniqueVRegDef(MI->getOperand(1).getReg());
8249 if (MI && MI->getOpcode() == Opcode) {
8250 Patterns.push_back(Pattern);
8251 return true;
8252 }
8253 return false;
8254 };
8255
8257
8258 switch (Root.getOpcode()) {
8259 default:
8260 return false;
8261 case AArch64::FMULv2f32:
8262 Found = Match(AArch64::DUPv2i32lane, 1, MCP::FMULv2i32_indexed_OP1);
8263 Found |= Match(AArch64::DUPv2i32lane, 2, MCP::FMULv2i32_indexed_OP2);
8264 break;
8265 case AArch64::FMULv2f64:
8266 Found = Match(AArch64::DUPv2i64lane, 1, MCP::FMULv2i64_indexed_OP1);
8267 Found |= Match(AArch64::DUPv2i64lane, 2, MCP::FMULv2i64_indexed_OP2);
8268 break;
8269 case AArch64::FMULv4f16:
8270 Found = Match(AArch64::DUPv4i16lane, 1, MCP::FMULv4i16_indexed_OP1);
8271 Found |= Match(AArch64::DUPv4i16lane, 2, MCP::FMULv4i16_indexed_OP2);
8272 break;
8273 case AArch64::FMULv4f32:
8274 Found = Match(AArch64::DUPv4i32lane, 1, MCP::FMULv4i32_indexed_OP1);
8275 Found |= Match(AArch64::DUPv4i32lane, 2, MCP::FMULv4i32_indexed_OP2);
8276 break;
8277 case AArch64::FMULv8f16:
8278 Found = Match(AArch64::DUPv8i16lane, 1, MCP::FMULv8i16_indexed_OP1);
8279 Found |= Match(AArch64::DUPv8i16lane, 2, MCP::FMULv8i16_indexed_OP2);
8280 break;
8281 }
8282
8283 return Found;
8284}
8285
8287 SmallVectorImpl<unsigned> &Patterns) {
8288 unsigned Opc = Root.getOpcode();
8289 MachineBasicBlock &MBB = *Root.getParent();
8290 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
8291
8292 auto Match = [&](unsigned Opcode, unsigned Pattern) -> bool {
8293 MachineOperand &MO = Root.getOperand(1);
8294 MachineInstr *MI = MRI.getUniqueVRegDef(MO.getReg());
8295 if (MI != nullptr && (MI->getOpcode() == Opcode) &&
8296 MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()) &&
8300 MI->getFlag(MachineInstr::MIFlag::FmNsz)) {
8301 Patterns.push_back(Pattern);
8302 return true;
8303 }
8304 return false;
8305 };
8306
8307 switch (Opc) {
8308 default:
8309 break;
8310 case AArch64::FNEGDr:
8311 return Match(AArch64::FMADDDrrr, AArch64MachineCombinerPattern::FNMADD);
8312 case AArch64::FNEGSr:
8313 return Match(AArch64::FMADDSrrr, AArch64MachineCombinerPattern::FNMADD);
8314 }
8315
8316 return false;
8317}
8318
8319/// Return true when a code sequence can improve throughput. It
8320/// should be called only for instructions in loops.
8321/// \param Pattern - combiner pattern
8323 switch (Pattern) {
8324 default:
8325 break;
8431 return true;
8432 } // end switch (Pattern)
8433 return false;
8434}
8435
8436/// Find other MI combine patterns.
8438 SmallVectorImpl<unsigned> &Patterns) {
8439 // A - (B + C) ==> (A - B) - C or (A - C) - B
8440 unsigned Opc = Root.getOpcode();
8441 MachineBasicBlock &MBB = *Root.getParent();
8442
8443 switch (Opc) {
8444 case AArch64::SUBWrr:
8445 case AArch64::SUBSWrr:
8446 case AArch64::SUBXrr:
8447 case AArch64::SUBSXrr:
8448 // Found candidate root.
8449 break;
8450 default:
8451 return false;
8452 }
8453
8455 Root.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true) ==
8456 -1)
8457 return false;
8458
8459 if (canCombine(MBB, Root.getOperand(2), AArch64::ADDWrr) ||
8460 canCombine(MBB, Root.getOperand(2), AArch64::ADDSWrr) ||
8461 canCombine(MBB, Root.getOperand(2), AArch64::ADDXrr) ||
8462 canCombine(MBB, Root.getOperand(2), AArch64::ADDSXrr)) {
8465 return true;
8466 }
8467
8468 return false;
8469}
8470
8471/// Check if the given instruction forms a gather load pattern that can be
8472/// optimized for better Memory-Level Parallelism (MLP). This function
8473/// identifies chains of NEON lane load instructions that load data from
8474/// different memory addresses into individual lanes of a 128-bit vector
8475/// register, then attempts to split the pattern into parallel loads to break
8476/// the serial dependency between instructions.
8477///
8478/// Pattern Matched:
8479/// Initial scalar load -> SUBREG_TO_REG (lane 0) -> LD1i* (lane 1) ->
8480/// LD1i* (lane 2) -> ... -> LD1i* (lane N-1, Root)
8481///
8482/// Transformed Into:
8483/// Two parallel vector loads using fewer lanes each, followed by ZIP1v2i64
8484/// to combine the results, enabling better memory-level parallelism.
8485///
8486/// Supported Element Types:
8487/// - 32-bit elements (LD1i32, 4 lanes total)
8488/// - 16-bit elements (LD1i16, 8 lanes total)
8489/// - 8-bit elements (LD1i8, 16 lanes total)
8491 SmallVectorImpl<unsigned> &Patterns,
8492 unsigned LoadLaneOpCode, unsigned NumLanes) {
8493 const MachineFunction *MF = Root.getMF();
8494
8495 // Early exit if optimizing for size.
8496 if (MF->getFunction().hasMinSize())
8497 return false;
8498
8499 const MachineRegisterInfo &MRI = MF->getRegInfo();
8501
8502 // The root of the pattern must load into the last lane of the vector.
8503 if (Root.getOperand(2).getImm() != NumLanes - 1)
8504 return false;
8505
8506 // Check that we have load into all lanes except lane 0.
8507 // For each load we also want to check that:
8508 // 1. It has a single non-debug use (since we will be replacing the virtual
8509 // register)
8510 // 2. That the addressing mode only uses a single pointer operand
8511 auto *CurrInstr = MRI.getUniqueVRegDef(Root.getOperand(1).getReg());
8512 auto Range = llvm::seq<unsigned>(1, NumLanes - 1);
8513 SmallSet<unsigned, 16> RemainingLanes(Range.begin(), Range.end());
8515 while (!RemainingLanes.empty() && CurrInstr &&
8516 CurrInstr->getOpcode() == LoadLaneOpCode &&
8517 MRI.hasOneNonDBGUse(CurrInstr->getOperand(0).getReg()) &&
8518 CurrInstr->getNumOperands() == 4) {
8519 RemainingLanes.erase(CurrInstr->getOperand(2).getImm());
8520 LoadInstrs.push_back(CurrInstr);
8521 CurrInstr = MRI.getUniqueVRegDef(CurrInstr->getOperand(1).getReg());
8522 }
8523
8524 // Check that we have found a match for lanes N-1.. 1.
8525 if (!RemainingLanes.empty())
8526 return false;
8527
8528 // Match the SUBREG_TO_REG sequence.
8529 if (CurrInstr->getOpcode() != TargetOpcode::SUBREG_TO_REG)
8530 return false;
8531
8532 // Verify that the subreg to reg loads an integer into the first lane.
8533 auto Lane0LoadReg = CurrInstr->getOperand(1).getReg();
8534 unsigned SingleLaneSizeInBits = 128 / NumLanes;
8535 if (TRI->getRegSizeInBits(Lane0LoadReg, MRI) != SingleLaneSizeInBits)
8536 return false;
8537
8538 // Verify that it also has a single non debug use.
8539 if (!MRI.hasOneNonDBGUse(Lane0LoadReg))
8540 return false;
8541
8542 LoadInstrs.push_back(MRI.getUniqueVRegDef(Lane0LoadReg));
8543
8544 // If there is any chance of aliasing, do not apply the pattern.
8545 // Walk backward through the MBB starting from Root.
8546 // Exit early if we've encountered all load instructions or hit the search
8547 // limit.
8548 auto MBBItr = Root.getIterator();
8549 unsigned RemainingSteps =
8550 MF->getSubtarget<AArch64Subtarget>().getCLOpts().search_limit;
8551 SmallPtrSet<const MachineInstr *, 16> RemainingLoadInstrs;
8552 RemainingLoadInstrs.insert(LoadInstrs.begin(), LoadInstrs.end());
8553 const MachineBasicBlock *MBB = Root.getParent();
8554
8555 for (; MBBItr != MBB->begin() && RemainingSteps > 0 &&
8556 !RemainingLoadInstrs.empty();
8557 --MBBItr, --RemainingSteps) {
8558 const MachineInstr &CurrInstr = *MBBItr;
8559
8560 // Remove this instruction from remaining loads if it's one we're tracking.
8561 RemainingLoadInstrs.erase(&CurrInstr);
8562
8563 // Check for potential aliasing with any of the load instructions to
8564 // optimize.
8565 if (CurrInstr.isLoadFoldBarrier())
8566 return false;
8567 }
8568
8569 // If we hit the search limit without finding all load instructions,
8570 // don't match the pattern.
8571 if (RemainingSteps == 0 && !RemainingLoadInstrs.empty())
8572 return false;
8573
8574 switch (NumLanes) {
8575 case 4:
8577 break;
8578 case 8:
8580 break;
8581 case 16:
8583 break;
8584 default:
8585 llvm_unreachable("Got bad number of lanes for gather pattern.");
8586 }
8587
8588 return true;
8589}
8590
8591/// Search for patterns of LD instructions we can optimize.
8593 SmallVectorImpl<unsigned> &Patterns) {
8594
8595 // The pattern searches for loads into single lanes.
8596 switch (Root.getOpcode()) {
8597 case AArch64::LD1i32:
8598 return getGatherLanePattern(Root, Patterns, Root.getOpcode(), 4);
8599 case AArch64::LD1i16:
8600 return getGatherLanePattern(Root, Patterns, Root.getOpcode(), 8);
8601 case AArch64::LD1i8:
8602 return getGatherLanePattern(Root, Patterns, Root.getOpcode(), 16);
8603 default:
8604 return false;
8605 }
8606}
8607
8608/// Generate optimized instruction sequence for gather load patterns to improve
8609/// Memory-Level Parallelism (MLP). This function transforms a chain of
8610/// sequential NEON lane loads into parallel vector loads that can execute
8611/// concurrently.
8612static void
8616 DenseMap<Register, unsigned> &InstrIdxForVirtReg,
8617 unsigned Pattern, unsigned NumLanes) {
8618 MachineFunction &MF = *Root.getParent()->getParent();
8621
8622 // Gather the initial load instructions to build the pattern.
8623 SmallVector<MachineInstr *, 16> LoadToLaneInstrs;
8624 MachineInstr *CurrInstr = &Root;
8625 for (unsigned i = 0; i < NumLanes - 1; ++i) {
8626 LoadToLaneInstrs.push_back(CurrInstr);
8627 CurrInstr = MRI.getUniqueVRegDef(CurrInstr->getOperand(1).getReg());
8628 }
8629
8630 // Sort the load instructions according to the lane.
8631 llvm::sort(LoadToLaneInstrs,
8632 [](const MachineInstr *A, const MachineInstr *B) {
8633 return A->getOperand(2).getImm() > B->getOperand(2).getImm();
8634 });
8635
8636 MachineInstr *SubregToReg = CurrInstr;
8637 LoadToLaneInstrs.push_back(
8638 MRI.getUniqueVRegDef(SubregToReg->getOperand(1).getReg()));
8639 auto LoadToLaneInstrsAscending = llvm::reverse(LoadToLaneInstrs);
8640
8641 const TargetRegisterClass *FPR128RegClass =
8642 MRI.getRegClass(Root.getOperand(0).getReg());
8643
8644 // Helper lambda to create a LD1 instruction.
8645 auto CreateLD1Instruction = [&](MachineInstr *OriginalInstr,
8646 Register SrcRegister, unsigned Lane,
8647 Register OffsetRegister) {
8648 auto NewRegister = MRI.createVirtualRegister(FPR128RegClass);
8649 MachineInstrBuilder LoadIndexIntoRegister =
8650 BuildMI(MF, MIMetadata(*OriginalInstr), TII->get(Root.getOpcode()),
8651 NewRegister)
8652 .addReg(SrcRegister)
8653 .addImm(Lane)
8654 .addReg(OffsetRegister)
8655 .setMemRefs(OriginalInstr->memoperands());
8656 InstrIdxForVirtReg.insert(std::make_pair(NewRegister, InsInstrs.size()));
8657 InsInstrs.push_back(LoadIndexIntoRegister);
8658 return NewRegister;
8659 };
8660
8661 // Helper to create load instruction based on the NumLanes in the NEON
8662 // register we are rewriting.
8663 auto CreateLDRInstruction =
8664 [&](unsigned NumLanes, Register DestReg, Register OffsetReg,
8666 unsigned Opcode;
8667 switch (NumLanes) {
8668 case 4:
8669 Opcode = AArch64::LDRSui;
8670 break;
8671 case 8:
8672 Opcode = AArch64::LDRHui;
8673 break;
8674 case 16:
8675 Opcode = AArch64::LDRBui;
8676 break;
8677 default:
8679 "Got unsupported number of lanes in machine-combiner gather pattern");
8680 }
8681 // Immediate offset load
8682 return BuildMI(MF, MIMetadata(Root), TII->get(Opcode), DestReg)
8683 .addReg(OffsetReg)
8684 .addImm(0)
8685 .setMemRefs(MMOs);
8686 };
8687
8688 // Load the remaining lanes into register 0.
8689 auto LanesToLoadToReg0 =
8690 llvm::make_range(LoadToLaneInstrsAscending.begin() + 1,
8691 LoadToLaneInstrsAscending.begin() + NumLanes / 2);
8692 Register PrevReg = SubregToReg->getOperand(0).getReg();
8693 for (auto [Index, LoadInstr] : llvm::enumerate(LanesToLoadToReg0)) {
8694 const MachineOperand &OffsetRegOperand = LoadInstr->getOperand(3);
8695 PrevReg = CreateLD1Instruction(LoadInstr, PrevReg, Index + 1,
8696 OffsetRegOperand.getReg());
8697 DelInstrs.push_back(LoadInstr);
8698 }
8699 Register LastLoadReg0 = PrevReg;
8700
8701 // First load into register 1. Perform an integer load to zero out the upper
8702 // lanes in a single instruction.
8703 MachineInstr *Lane0Load = *LoadToLaneInstrsAscending.begin();
8704 MachineInstr *OriginalSplitLoad =
8705 *std::next(LoadToLaneInstrsAscending.begin(), NumLanes / 2);
8706 Register DestRegForMiddleIndex = MRI.createVirtualRegister(
8707 MRI.getRegClass(Lane0Load->getOperand(0).getReg()));
8708
8709 const MachineOperand &OriginalSplitToLoadOffsetOperand =
8710 OriginalSplitLoad->getOperand(3);
8711 MachineInstrBuilder MiddleIndexLoadInstr =
8712 CreateLDRInstruction(NumLanes, DestRegForMiddleIndex,
8713 OriginalSplitToLoadOffsetOperand.getReg(),
8714 OriginalSplitLoad->memoperands());
8715
8716 InstrIdxForVirtReg.insert(
8717 std::make_pair(DestRegForMiddleIndex, InsInstrs.size()));
8718 InsInstrs.push_back(MiddleIndexLoadInstr);
8719 DelInstrs.push_back(OriginalSplitLoad);
8720
8721 // Subreg To Reg instruction for register 1.
8722 Register DestRegForSubregToReg = MRI.createVirtualRegister(FPR128RegClass);
8723 unsigned SubregType;
8724 switch (NumLanes) {
8725 case 4:
8726 SubregType = AArch64::ssub;
8727 break;
8728 case 8:
8729 SubregType = AArch64::hsub;
8730 break;
8731 case 16:
8732 SubregType = AArch64::bsub;
8733 break;
8734 default:
8736 "Got invalid NumLanes for machine-combiner gather pattern");
8737 }
8738
8739 auto SubRegToRegInstr =
8740 BuildMI(MF, MIMetadata(Root), TII->get(SubregToReg->getOpcode()),
8741 DestRegForSubregToReg)
8742 .addReg(DestRegForMiddleIndex)
8743 .addImm(SubregType);
8744 InstrIdxForVirtReg.insert(
8745 std::make_pair(DestRegForSubregToReg, InsInstrs.size()));
8746 InsInstrs.push_back(SubRegToRegInstr);
8747
8748 // Load remaining lanes into register 1.
8749 auto LanesToLoadToReg1 =
8750 llvm::make_range(LoadToLaneInstrsAscending.begin() + NumLanes / 2 + 1,
8751 LoadToLaneInstrsAscending.end());
8752 PrevReg = SubRegToRegInstr->getOperand(0).getReg();
8753 for (auto [Index, LoadInstr] : llvm::enumerate(LanesToLoadToReg1)) {
8754 const MachineOperand &OffsetRegOperand = LoadInstr->getOperand(3);
8755 PrevReg = CreateLD1Instruction(LoadInstr, PrevReg, Index + 1,
8756 OffsetRegOperand.getReg());
8757
8758 // Do not add the last reg to DelInstrs - it will be removed later.
8759 if (Index == NumLanes / 2 - 2) {
8760 break;
8761 }
8762 DelInstrs.push_back(LoadInstr);
8763 }
8764 Register LastLoadReg1 = PrevReg;
8765
8766 // Create the final zip instruction to combine the results.
8767 MachineInstrBuilder ZipInstr =
8768 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::ZIP1v2i64),
8769 Root.getOperand(0).getReg())
8770 .addReg(LastLoadReg0)
8771 .addReg(LastLoadReg1);
8772 InsInstrs.push_back(ZipInstr);
8773}
8774
8788
8789/// Return true when there is potentially a faster code sequence for an
8790/// instruction chain ending in \p Root. All potential patterns are listed in
8791/// the \p Pattern vector. Pattern should be sorted in priority order since the
8792/// pattern evaluator stops checking as soon as it finds a faster sequence.
8793
8794bool AArch64InstrInfo::getMachineCombinerPatterns(
8795 MachineInstr &Root, SmallVectorImpl<unsigned> &Patterns,
8796 bool DoRegPressureReduce) const {
8797 // Integer patterns
8798 if (getMaddPatterns(Root, Patterns))
8799 return true;
8800 // Floating point patterns
8801 if (getFMULPatterns(Root, Patterns))
8802 return true;
8803 if (getFMAPatterns(Root, Patterns))
8804 return true;
8805 if (getFNEGPatterns(Root, Patterns))
8806 return true;
8807
8808 // Other patterns
8809 if (getMiscPatterns(Root, Patterns))
8810 return true;
8811
8812 // Load patterns
8813 if (getLoadPatterns(Root, Patterns))
8814 return true;
8815
8816 return TargetInstrInfo::getMachineCombinerPatterns(Root, Patterns,
8817 DoRegPressureReduce);
8818}
8819
8821/// genFusedMultiply - Generate fused multiply instructions.
8822/// This function supports both integer and floating point instructions.
8823/// A typical example:
8824/// F|MUL I=A,B,0
8825/// F|ADD R,I,C
8826/// ==> F|MADD R,A,B,C
8827/// \param MF Containing MachineFunction
8828/// \param MRI Register information
8829/// \param TII Target information
8830/// \param Root is the F|ADD instruction
8831/// \param [out] InsInstrs is a vector of machine instructions and will
8832/// contain the generated madd instruction
8833/// \param IdxMulOpd is index of operand in Root that is the result of
8834/// the F|MUL. In the example above IdxMulOpd is 1.
8835/// \param MaddOpc the opcode fo the f|madd instruction
8836/// \param RC Register class of operands
8837/// \param kind of fma instruction (addressing mode) to be generated
8838/// \param ReplacedAddend is the result register from the instruction
8839/// replacing the non-combined operand, if any.
8840static MachineInstr *
8842 const TargetInstrInfo *TII, MachineInstr &Root,
8843 SmallVectorImpl<MachineInstr *> &InsInstrs, unsigned IdxMulOpd,
8844 unsigned MaddOpc, const TargetRegisterClass *RC,
8846 const Register *ReplacedAddend = nullptr) {
8847 assert(IdxMulOpd == 1 || IdxMulOpd == 2);
8848
8849 unsigned IdxOtherOpd = IdxMulOpd == 1 ? 2 : 1;
8850 MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(IdxMulOpd).getReg());
8851 Register ResultReg = Root.getOperand(0).getReg();
8852 Register SrcReg0 = MUL->getOperand(1).getReg();
8853 Register SrcReg1 = MUL->getOperand(2).getReg();
8854
8855 Register SrcReg2 =
8856 ReplacedAddend ? *ReplacedAddend : Root.getOperand(IdxOtherOpd).getReg();
8857
8858 if (ResultReg.isVirtual())
8859 MRI.constrainRegClass(ResultReg, RC);
8860 if (SrcReg0.isVirtual())
8861 MRI.constrainRegClass(SrcReg0, RC);
8862 if (SrcReg1.isVirtual())
8863 MRI.constrainRegClass(SrcReg1, RC);
8864 if (SrcReg2.isVirtual())
8865 MRI.constrainRegClass(SrcReg2, RC);
8866
8868 if (kind == FMAInstKind::Default)
8869 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
8870 .addReg(SrcReg0)
8871 .addReg(SrcReg1)
8872 .addReg(SrcReg2);
8873 else if (kind == FMAInstKind::Indexed)
8874 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
8875 .addReg(SrcReg2)
8876 .addReg(SrcReg0)
8877 .addReg(SrcReg1)
8878 .addImm(MUL->getOperand(3).getImm());
8879 else if (kind == FMAInstKind::Accumulator)
8880 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
8881 .addReg(SrcReg2)
8882 .addReg(SrcReg0)
8883 .addReg(SrcReg1);
8884 else
8885 assert(false && "Invalid FMA instruction kind \n");
8886 // Insert the MADD (MADD, FMA, FMS, FMLA, FMSL)
8887 InsInstrs.push_back(MIB);
8888 return MUL;
8889}
8890
8891/// MUL I=A,B,0
8892/// ADDrs R,I,C,shift
8893/// ==>
8894/// SBFM/UBFM J=C,shift
8895/// MADD R,A,B,J
8897 const TargetInstrInfo *TII, MachineInstr &Root,
8900 unsigned MaddOpc, bool Is64Bit,
8901 DenseMap<Register, unsigned> &InstrIdxForVirtReg) {
8902 const TargetRegisterClass *RC =
8903 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
8904 MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(1).getReg());
8905 Register ResultReg = Root.getOperand(0).getReg();
8906 Register SrcReg0 = MUL->getOperand(1).getReg();
8907 Register SrcReg1 = MUL->getOperand(2).getReg();
8908 Register ShiftedReg = Root.getOperand(2).getReg();
8909
8910 if (ResultReg.isVirtual())
8911 MRI.constrainRegClass(ResultReg, RC);
8912 if (SrcReg0.isVirtual())
8913 MRI.constrainRegClass(SrcReg0, RC);
8914 if (SrcReg1.isVirtual())
8915 MRI.constrainRegClass(SrcReg1, RC);
8916 if (ShiftedReg.isVirtual())
8917 MRI.constrainRegClass(ShiftedReg, RC);
8918
8919 unsigned ShiftImm = Root.getOperand(3).getImm();
8920 unsigned ShiftVal = AArch64_AM::getShiftValue(ShiftImm);
8921 unsigned RegSize = Is64Bit ? 64 : 32;
8922 unsigned BFMOpc;
8923 unsigned ImmR, ImmS;
8924 switch (AArch64_AM::getShiftType(ShiftImm)) {
8925 case AArch64_AM::ASR:
8926 BFMOpc = Is64Bit ? AArch64::SBFMXri : AArch64::SBFMWri;
8927 ImmR = ShiftVal;
8928 ImmS = RegSize - 1;
8929 break;
8930 case AArch64_AM::LSR:
8931 BFMOpc = Is64Bit ? AArch64::UBFMXri : AArch64::UBFMWri;
8932 ImmR = ShiftVal;
8933 ImmS = RegSize - 1;
8934 break;
8935 case AArch64_AM::LSL:
8936 BFMOpc = Is64Bit ? AArch64::UBFMXri : AArch64::UBFMWri;
8937 ImmR = (RegSize - ShiftVal) % RegSize;
8938 ImmS = RegSize - 1 - ShiftVal;
8939 break;
8940 default:
8941 llvm_unreachable("Unexpected shift type");
8942 }
8943
8944 Register ShiftReg = MRI.createVirtualRegister(RC);
8945 MachineInstrBuilder MIB1 =
8946 BuildMI(MF, MIMetadata(Root), TII->get(BFMOpc), ShiftReg)
8947 .addReg(ShiftedReg)
8948 .addImm(ImmR)
8949 .addImm(ImmS);
8950 InstrIdxForVirtReg.insert(std::make_pair(ShiftReg, InsInstrs.size()));
8951 InsInstrs.push_back(MIB1);
8952
8953 uint32_t Flags = Root.getFlags() & MUL->getFlags() &
8955
8956 MachineInstrBuilder MIB2 =
8957 BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
8958 .addReg(SrcReg0)
8959 .addReg(SrcReg1)
8960 .addReg(ShiftReg)
8961 .setMIFlags(Flags);
8962
8963 InsInstrs.push_back(MIB2);
8964 DelInstrs.push_back(MUL);
8965 DelInstrs.push_back(&Root);
8966}
8967
8968static MachineInstr *
8970 const TargetInstrInfo *TII, MachineInstr &Root,
8972 MachineInstr *MAD = MRI.getUniqueVRegDef(Root.getOperand(1).getReg());
8973
8974 unsigned Opc = 0;
8975 const TargetRegisterClass *RC = MRI.getRegClass(MAD->getOperand(0).getReg());
8976 if (AArch64::FPR32RegClass.hasSubClassEq(RC))
8977 Opc = AArch64::FNMADDSrrr;
8978 else if (AArch64::FPR64RegClass.hasSubClassEq(RC))
8979 Opc = AArch64::FNMADDDrrr;
8980 else
8981 return nullptr;
8982
8983 Register ResultReg = Root.getOperand(0).getReg();
8984 Register SrcReg0 = MAD->getOperand(1).getReg();
8985 Register SrcReg1 = MAD->getOperand(2).getReg();
8986 Register SrcReg2 = MAD->getOperand(3).getReg();
8987 if (ResultReg.isVirtual())
8988 MRI.constrainRegClass(ResultReg, RC);
8989 if (SrcReg0.isVirtual())
8990 MRI.constrainRegClass(SrcReg0, RC);
8991 if (SrcReg1.isVirtual())
8992 MRI.constrainRegClass(SrcReg1, RC);
8993 if (SrcReg2.isVirtual())
8994 MRI.constrainRegClass(SrcReg2, RC);
8995
8997 BuildMI(MF, MIMetadata(Root), TII->get(Opc), ResultReg)
8998 .addReg(SrcReg0)
8999 .addReg(SrcReg1)
9000 .addReg(SrcReg2);
9001 InsInstrs.push_back(MIB);
9002
9003 return MAD;
9004}
9005
9006/// Fold (FMUL x (DUP y lane)) into (FMUL_indexed x y lane)
9007static MachineInstr *
9010 unsigned IdxDupOp, unsigned MulOpc,
9012 assert(((IdxDupOp == 1) || (IdxDupOp == 2)) &&
9013 "Invalid index of FMUL operand");
9014
9015 MachineFunction &MF = *Root.getMF();
9017
9018 MachineInstr *Dup =
9019 MF.getRegInfo().getUniqueVRegDef(Root.getOperand(IdxDupOp).getReg());
9020
9021 if (Dup->getOpcode() == TargetOpcode::COPY)
9022 Dup = MRI.getUniqueVRegDef(Dup->getOperand(1).getReg());
9023
9024 Register DupSrcReg = Dup->getOperand(1).getReg();
9025 MRI.constrainRegClass(DupSrcReg, RC);
9026
9027 unsigned DupSrcLane = Dup->getOperand(2).getImm();
9028
9029 unsigned IdxMulOp = IdxDupOp == 1 ? 2 : 1;
9030 MachineOperand &MulOp = Root.getOperand(IdxMulOp);
9031
9032 Register ResultReg = Root.getOperand(0).getReg();
9033
9035 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MulOpc), ResultReg)
9036 .add(MulOp)
9037 .addReg(DupSrcReg)
9038 .addImm(DupSrcLane);
9039
9040 InsInstrs.push_back(MIB);
9041 return &Root;
9042}
9043
9044/// genFusedMultiplyAcc - Helper to generate fused multiply accumulate
9045/// instructions.
9046///
9047/// \see genFusedMultiply
9051 unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC) {
9052 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
9054}
9055
9056/// genNeg - Helper to generate an intermediate negation of the second operand
9057/// of Root
9059 const TargetInstrInfo *TII, MachineInstr &Root,
9061 DenseMap<Register, unsigned> &InstrIdxForVirtReg,
9062 unsigned MnegOpc, const TargetRegisterClass *RC) {
9063 Register NewVR = MRI.createVirtualRegister(RC);
9065 BuildMI(MF, MIMetadata(Root), TII->get(MnegOpc), NewVR)
9066 .add(Root.getOperand(2));
9067 InsInstrs.push_back(MIB);
9068
9069 assert(InstrIdxForVirtReg.empty());
9070 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9071
9072 return NewVR;
9073}
9074
9075/// genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate
9076/// instructions with an additional negation of the accumulator
9080 DenseMap<Register, unsigned> &InstrIdxForVirtReg, unsigned IdxMulOpd,
9081 unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC) {
9082 assert(IdxMulOpd == 1);
9083
9084 Register NewVR =
9085 genNeg(MF, MRI, TII, Root, InsInstrs, InstrIdxForVirtReg, MnegOpc, RC);
9086 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
9087 FMAInstKind::Accumulator, &NewVR);
9088}
9089
9090/// genFusedMultiplyIdx - Helper to generate fused multiply accumulate
9091/// instructions.
9092///
9093/// \see genFusedMultiply
9097 unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC) {
9098 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
9100}
9101
9102/// genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate
9103/// instructions with an additional negation of the accumulator
9107 DenseMap<Register, unsigned> &InstrIdxForVirtReg, unsigned IdxMulOpd,
9108 unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC) {
9109 assert(IdxMulOpd == 1);
9110
9111 Register NewVR =
9112 genNeg(MF, MRI, TII, Root, InsInstrs, InstrIdxForVirtReg, MnegOpc, RC);
9113
9114 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
9115 FMAInstKind::Indexed, &NewVR);
9116}
9117
9118/// genMaddR - Generate madd instruction and combine mul and add using
9119/// an extra virtual register
9120/// Example - an ADD intermediate needs to be stored in a register:
9121/// MUL I=A,B,0
9122/// ADD R,I,Imm
9123/// ==> ORR V, ZR, Imm
9124/// ==> MADD R,A,B,V
9125/// \param MF Containing MachineFunction
9126/// \param MRI Register information
9127/// \param TII Target information
9128/// \param Root is the ADD instruction
9129/// \param [out] InsInstrs is a vector of machine instructions and will
9130/// contain the generated madd instruction
9131/// \param IdxMulOpd is index of operand in Root that is the result of
9132/// the MUL. In the example above IdxMulOpd is 1.
9133/// \param MaddOpc the opcode fo the madd instruction
9134/// \param VR is a virtual register that holds the value of an ADD operand
9135/// (V in the example above).
9136/// \param RC Register class of operands
9138 const TargetInstrInfo *TII, MachineInstr &Root,
9140 unsigned IdxMulOpd, unsigned MaddOpc, unsigned VR,
9141 const TargetRegisterClass *RC) {
9142 assert(IdxMulOpd == 1 || IdxMulOpd == 2);
9143
9144 MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(IdxMulOpd).getReg());
9145 Register ResultReg = Root.getOperand(0).getReg();
9146 Register SrcReg0 = MUL->getOperand(1).getReg();
9147 Register SrcReg1 = MUL->getOperand(2).getReg();
9148
9149 if (ResultReg.isVirtual())
9150 MRI.constrainRegClass(ResultReg, RC);
9151 if (SrcReg0.isVirtual())
9152 MRI.constrainRegClass(SrcReg0, RC);
9153 if (SrcReg1.isVirtual())
9154 MRI.constrainRegClass(SrcReg1, RC);
9156 MRI.constrainRegClass(VR, RC);
9157
9159 BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
9160 .addReg(SrcReg0)
9161 .addReg(SrcReg1)
9162 .addReg(VR);
9163 // Insert the MADD
9164 InsInstrs.push_back(MIB);
9165 return MUL;
9166}
9167
9168/// Do the following transformation
9169/// A - (B + C) ==> (A - B) - C
9170/// A - (B + C) ==> (A - C) - B
9172 const TargetInstrInfo *TII, MachineInstr &Root,
9175 unsigned IdxOpd1,
9176 DenseMap<Register, unsigned> &InstrIdxForVirtReg) {
9177 assert(IdxOpd1 == 1 || IdxOpd1 == 2);
9178 unsigned IdxOtherOpd = IdxOpd1 == 1 ? 2 : 1;
9179 MachineInstr *AddMI = MRI.getUniqueVRegDef(Root.getOperand(2).getReg());
9180
9181 Register ResultReg = Root.getOperand(0).getReg();
9182 Register RegA = Root.getOperand(1).getReg();
9183 Register RegB = AddMI->getOperand(IdxOpd1).getReg();
9184 Register RegC = AddMI->getOperand(IdxOtherOpd).getReg();
9185 Register NewVR =
9186 MRI.createVirtualRegister(MRI.getRegClass(Root.getOperand(2).getReg()));
9187
9188 unsigned Opcode = Root.getOpcode();
9189 if (Opcode == AArch64::SUBSWrr)
9190 Opcode = AArch64::SUBWrr;
9191 else if (Opcode == AArch64::SUBSXrr)
9192 Opcode = AArch64::SUBXrr;
9193 else
9194 assert((Opcode == AArch64::SUBWrr || Opcode == AArch64::SUBXrr) &&
9195 "Unexpected instruction opcode.");
9196
9197 uint32_t Flags = Root.mergeFlagsWith(*AddMI);
9198 Flags &= ~MachineInstr::NoSWrap;
9199 Flags &= ~MachineInstr::NoUWrap;
9200
9201 MachineInstrBuilder MIB1 =
9202 BuildMI(MF, MIMetadata(Root), TII->get(Opcode), NewVR)
9203 .addReg(RegA)
9204 .addReg(RegB)
9205 .setMIFlags(Flags);
9206 MachineInstrBuilder MIB2 =
9207 BuildMI(MF, MIMetadata(Root), TII->get(Opcode), ResultReg)
9208 .addReg(NewVR)
9209 .addReg(RegC)
9210 .setMIFlags(Flags);
9211
9212 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9213 InsInstrs.push_back(MIB1);
9214 InsInstrs.push_back(MIB2);
9215 DelInstrs.push_back(AddMI);
9216 DelInstrs.push_back(&Root);
9217}
9218
9219unsigned AArch64InstrInfo::getReduceOpcodeForAccumulator(
9220 unsigned int AccumulatorOpCode) const {
9221 switch (AccumulatorOpCode) {
9222 case AArch64::UABALB_ZZZ_D:
9223 case AArch64::SABALB_ZZZ_D:
9224 case AArch64::UABALT_ZZZ_D:
9225 case AArch64::SABALT_ZZZ_D:
9226 return AArch64::ADD_ZZZ_D;
9227 case AArch64::UABALB_ZZZ_H:
9228 case AArch64::SABALB_ZZZ_H:
9229 case AArch64::UABALT_ZZZ_H:
9230 case AArch64::SABALT_ZZZ_H:
9231 return AArch64::ADD_ZZZ_H;
9232 case AArch64::UABALB_ZZZ_S:
9233 case AArch64::SABALB_ZZZ_S:
9234 case AArch64::UABALT_ZZZ_S:
9235 case AArch64::SABALT_ZZZ_S:
9236 return AArch64::ADD_ZZZ_S;
9237 case AArch64::UABALv16i8_v8i16:
9238 case AArch64::SABALv8i8_v8i16:
9239 case AArch64::SABAv8i16:
9240 case AArch64::UABAv8i16:
9241 return AArch64::ADDv8i16;
9242 case AArch64::SABALv2i32_v2i64:
9243 case AArch64::UABALv2i32_v2i64:
9244 case AArch64::SABALv4i32_v2i64:
9245 return AArch64::ADDv2i64;
9246 case AArch64::UABALv4i16_v4i32:
9247 case AArch64::SABALv4i16_v4i32:
9248 case AArch64::SABALv8i16_v4i32:
9249 case AArch64::SABAv4i32:
9250 case AArch64::UABAv4i32:
9251 return AArch64::ADDv4i32;
9252 case AArch64::UABALv4i32_v2i64:
9253 return AArch64::ADDv2i64;
9254 case AArch64::UABALv8i16_v4i32:
9255 return AArch64::ADDv4i32;
9256 case AArch64::UABALv8i8_v8i16:
9257 case AArch64::SABALv16i8_v8i16:
9258 return AArch64::ADDv8i16;
9259 case AArch64::UABAv16i8:
9260 case AArch64::SABAv16i8:
9261 return AArch64::ADDv16i8;
9262 case AArch64::UABAv4i16:
9263 case AArch64::SABAv4i16:
9264 return AArch64::ADDv4i16;
9265 case AArch64::UABAv2i32:
9266 case AArch64::SABAv2i32:
9267 return AArch64::ADDv2i32;
9268 case AArch64::UABAv8i8:
9269 case AArch64::SABAv8i8:
9270 return AArch64::ADDv8i8;
9271 default:
9272 llvm_unreachable("Unknown accumulator opcode");
9273 }
9274}
9275
9276/// When getMachineCombinerPatterns() finds potential patterns,
9277/// this function generates the instructions that could replace the
9278/// original code sequence
9279void AArch64InstrInfo::genAlternativeCodeSequence(
9280 MachineInstr &Root, unsigned Pattern,
9283 DenseMap<Register, unsigned> &InstrIdxForVirtReg) const {
9284 MachineBasicBlock &MBB = *Root.getParent();
9285 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9286 MachineFunction &MF = *MBB.getParent();
9287 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9288
9289 MachineInstr *MUL = nullptr;
9290 const TargetRegisterClass *RC;
9291 unsigned Opc;
9292 switch (Pattern) {
9293 default:
9294 // Reassociate instructions.
9295 TargetInstrInfo::genAlternativeCodeSequence(Root, Pattern, InsInstrs,
9296 DelInstrs, InstrIdxForVirtReg);
9297 return;
9299 // A - (B + C)
9300 // ==> (A - B) - C
9301 genSubAdd2SubSub(MF, MRI, TII, Root, InsInstrs, DelInstrs, 1,
9302 InstrIdxForVirtReg);
9303 return;
9305 // A - (B + C)
9306 // ==> (A - C) - B
9307 genSubAdd2SubSub(MF, MRI, TII, Root, InsInstrs, DelInstrs, 2,
9308 InstrIdxForVirtReg);
9309 return;
9312 // MUL I=A,B,0
9313 // ADD R,I,C
9314 // ==> MADD R,A,B,C
9315 // --- Create(MADD);
9317 Opc = AArch64::MADDWrrr;
9318 RC = &AArch64::GPR32RegClass;
9319 } else {
9320 Opc = AArch64::MADDXrrr;
9321 RC = &AArch64::GPR64RegClass;
9322 }
9323 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9324 break;
9327 // MUL I=A,B,0
9328 // ADD R,C,I
9329 // ==> MADD R,A,B,C
9330 // --- Create(MADD);
9332 Opc = AArch64::MADDWrrr;
9333 RC = &AArch64::GPR32RegClass;
9334 } else {
9335 Opc = AArch64::MADDXrrr;
9336 RC = &AArch64::GPR64RegClass;
9337 }
9338 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9339 break;
9344 // MUL I=A,B,0
9345 // ADD/SUB R,I,Imm
9346 // ==> MOV V, Imm/-Imm
9347 // ==> MADD R,A,B,V
9348 // --- Create(MADD);
9349 const TargetRegisterClass *RC;
9350 unsigned BitSize, MovImm;
9353 MovImm = AArch64::MOVi32imm;
9354 RC = &AArch64::GPR32spRegClass;
9355 BitSize = 32;
9356 Opc = AArch64::MADDWrrr;
9357 RC = &AArch64::GPR32RegClass;
9358 } else {
9359 MovImm = AArch64::MOVi64imm;
9360 RC = &AArch64::GPR64spRegClass;
9361 BitSize = 64;
9362 Opc = AArch64::MADDXrrr;
9363 RC = &AArch64::GPR64RegClass;
9364 }
9366 uint64_t Imm = Root.getOperand(2).getImm();
9367
9368 if (Root.getOperand(3).isImm()) {
9369 unsigned Val = Root.getOperand(3).getImm();
9370 Imm = Imm << Val;
9371 }
9372 bool IsSub = Pattern == AArch64MachineCombinerPattern::MULSUBWI_OP1 ||
9374 uint64_t UImm = SignExtend64(IsSub ? -Imm : Imm, BitSize);
9375 // Check that the immediate can be composed via a single instruction.
9377 AArch64_IMM::expandMOVImm(UImm, BitSize, Insn);
9378 if (Insn.size() != 1)
9379 return;
9380 MachineInstrBuilder MIB1 =
9381 BuildMI(MF, MIMetadata(Root), TII->get(MovImm), NewVR)
9382 .addImm(IsSub ? -Imm : Imm);
9383 InsInstrs.push_back(MIB1);
9384 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9385 MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC);
9386 break;
9387 }
9390 // MUL I=A,B,0
9391 // SUB R,I, C
9392 // ==> SUB V, 0, C
9393 // ==> MADD R,A,B,V // = -C + A*B
9394 // --- Create(MADD);
9395 const TargetRegisterClass *SubRC;
9396 unsigned SubOpc, ZeroReg;
9398 SubOpc = AArch64::SUBWrr;
9399 SubRC = &AArch64::GPR32spRegClass;
9400 ZeroReg = AArch64::WZR;
9401 Opc = AArch64::MADDWrrr;
9402 RC = &AArch64::GPR32RegClass;
9403 } else {
9404 SubOpc = AArch64::SUBXrr;
9405 SubRC = &AArch64::GPR64spRegClass;
9406 ZeroReg = AArch64::XZR;
9407 Opc = AArch64::MADDXrrr;
9408 RC = &AArch64::GPR64RegClass;
9409 }
9410 Register NewVR = MRI.createVirtualRegister(SubRC);
9411 // SUB NewVR, 0, C
9412 MachineInstrBuilder MIB1 =
9413 BuildMI(MF, MIMetadata(Root), TII->get(SubOpc), NewVR)
9414 .addReg(ZeroReg)
9415 .add(Root.getOperand(2));
9416 InsInstrs.push_back(MIB1);
9417 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9418 MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC);
9419 break;
9420 }
9423 // MUL I=A,B,0
9424 // SUB R,C,I
9425 // ==> MSUB R,A,B,C (computes C - A*B)
9426 // --- Create(MSUB);
9428 Opc = AArch64::MSUBWrrr;
9429 RC = &AArch64::GPR32RegClass;
9430 } else {
9431 Opc = AArch64::MSUBXrrr;
9432 RC = &AArch64::GPR64RegClass;
9433 }
9434 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9435 break;
9437 genMaddShf(MF, MRI, TII, Root, InsInstrs, DelInstrs, AArch64::MADDWrrr,
9438 false, InstrIdxForVirtReg);
9439 return;
9441 genMaddShf(MF, MRI, TII, Root, InsInstrs, DelInstrs, AArch64::MADDXrrr,
9442 true, InstrIdxForVirtReg);
9443 return;
9445 Opc = AArch64::MLAv8i8;
9446 RC = &AArch64::FPR64RegClass;
9447 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9448 break;
9450 Opc = AArch64::MLAv8i8;
9451 RC = &AArch64::FPR64RegClass;
9452 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9453 break;
9455 Opc = AArch64::MLAv16i8;
9456 RC = &AArch64::FPR128RegClass;
9457 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9458 break;
9460 Opc = AArch64::MLAv16i8;
9461 RC = &AArch64::FPR128RegClass;
9462 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9463 break;
9465 Opc = AArch64::MLAv4i16;
9466 RC = &AArch64::FPR64RegClass;
9467 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9468 break;
9470 Opc = AArch64::MLAv4i16;
9471 RC = &AArch64::FPR64RegClass;
9472 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9473 break;
9475 Opc = AArch64::MLAv8i16;
9476 RC = &AArch64::FPR128RegClass;
9477 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9478 break;
9480 Opc = AArch64::MLAv8i16;
9481 RC = &AArch64::FPR128RegClass;
9482 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9483 break;
9485 Opc = AArch64::MLAv2i32;
9486 RC = &AArch64::FPR64RegClass;
9487 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9488 break;
9490 Opc = AArch64::MLAv2i32;
9491 RC = &AArch64::FPR64RegClass;
9492 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9493 break;
9495 Opc = AArch64::MLAv4i32;
9496 RC = &AArch64::FPR128RegClass;
9497 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9498 break;
9500 Opc = AArch64::MLAv4i32;
9501 RC = &AArch64::FPR128RegClass;
9502 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9503 break;
9504
9506 Opc = AArch64::MLAv8i8;
9507 RC = &AArch64::FPR64RegClass;
9508 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9509 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i8,
9510 RC);
9511 break;
9513 Opc = AArch64::MLSv8i8;
9514 RC = &AArch64::FPR64RegClass;
9515 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9516 break;
9518 Opc = AArch64::MLAv16i8;
9519 RC = &AArch64::FPR128RegClass;
9520 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9521 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv16i8,
9522 RC);
9523 break;
9525 Opc = AArch64::MLSv16i8;
9526 RC = &AArch64::FPR128RegClass;
9527 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9528 break;
9530 Opc = AArch64::MLAv4i16;
9531 RC = &AArch64::FPR64RegClass;
9532 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9533 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i16,
9534 RC);
9535 break;
9537 Opc = AArch64::MLSv4i16;
9538 RC = &AArch64::FPR64RegClass;
9539 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9540 break;
9542 Opc = AArch64::MLAv8i16;
9543 RC = &AArch64::FPR128RegClass;
9544 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9545 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i16,
9546 RC);
9547 break;
9549 Opc = AArch64::MLSv8i16;
9550 RC = &AArch64::FPR128RegClass;
9551 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9552 break;
9554 Opc = AArch64::MLAv2i32;
9555 RC = &AArch64::FPR64RegClass;
9556 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9557 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv2i32,
9558 RC);
9559 break;
9561 Opc = AArch64::MLSv2i32;
9562 RC = &AArch64::FPR64RegClass;
9563 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9564 break;
9566 Opc = AArch64::MLAv4i32;
9567 RC = &AArch64::FPR128RegClass;
9568 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9569 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i32,
9570 RC);
9571 break;
9573 Opc = AArch64::MLSv4i32;
9574 RC = &AArch64::FPR128RegClass;
9575 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9576 break;
9577
9579 Opc = AArch64::MLAv4i16_indexed;
9580 RC = &AArch64::FPR64RegClass;
9581 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9582 break;
9584 Opc = AArch64::MLAv4i16_indexed;
9585 RC = &AArch64::FPR64RegClass;
9586 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9587 break;
9589 Opc = AArch64::MLAv8i16_indexed;
9590 RC = &AArch64::FPR128RegClass;
9591 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9592 break;
9594 Opc = AArch64::MLAv8i16_indexed;
9595 RC = &AArch64::FPR128RegClass;
9596 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9597 break;
9599 Opc = AArch64::MLAv2i32_indexed;
9600 RC = &AArch64::FPR64RegClass;
9601 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9602 break;
9604 Opc = AArch64::MLAv2i32_indexed;
9605 RC = &AArch64::FPR64RegClass;
9606 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9607 break;
9609 Opc = AArch64::MLAv4i32_indexed;
9610 RC = &AArch64::FPR128RegClass;
9611 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9612 break;
9614 Opc = AArch64::MLAv4i32_indexed;
9615 RC = &AArch64::FPR128RegClass;
9616 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9617 break;
9618
9620 Opc = AArch64::MLAv4i16_indexed;
9621 RC = &AArch64::FPR64RegClass;
9622 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9623 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i16,
9624 RC);
9625 break;
9627 Opc = AArch64::MLSv4i16_indexed;
9628 RC = &AArch64::FPR64RegClass;
9629 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9630 break;
9632 Opc = AArch64::MLAv8i16_indexed;
9633 RC = &AArch64::FPR128RegClass;
9634 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9635 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i16,
9636 RC);
9637 break;
9639 Opc = AArch64::MLSv8i16_indexed;
9640 RC = &AArch64::FPR128RegClass;
9641 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9642 break;
9644 Opc = AArch64::MLAv2i32_indexed;
9645 RC = &AArch64::FPR64RegClass;
9646 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9647 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv2i32,
9648 RC);
9649 break;
9651 Opc = AArch64::MLSv2i32_indexed;
9652 RC = &AArch64::FPR64RegClass;
9653 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9654 break;
9656 Opc = AArch64::MLAv4i32_indexed;
9657 RC = &AArch64::FPR128RegClass;
9658 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9659 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i32,
9660 RC);
9661 break;
9663 Opc = AArch64::MLSv4i32_indexed;
9664 RC = &AArch64::FPR128RegClass;
9665 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9666 break;
9667
9668 // Floating Point Support
9670 Opc = AArch64::FMADDHrrr;
9671 RC = &AArch64::FPR16RegClass;
9672 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9673 break;
9675 Opc = AArch64::FMADDSrrr;
9676 RC = &AArch64::FPR32RegClass;
9677 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9678 break;
9680 Opc = AArch64::FMADDDrrr;
9681 RC = &AArch64::FPR64RegClass;
9682 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9683 break;
9684
9686 Opc = AArch64::FMADDHrrr;
9687 RC = &AArch64::FPR16RegClass;
9688 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9689 break;
9691 Opc = AArch64::FMADDSrrr;
9692 RC = &AArch64::FPR32RegClass;
9693 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9694 break;
9696 Opc = AArch64::FMADDDrrr;
9697 RC = &AArch64::FPR64RegClass;
9698 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9699 break;
9700
9702 Opc = AArch64::FMLAv1i32_indexed;
9703 RC = &AArch64::FPR32RegClass;
9704 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9706 break;
9708 Opc = AArch64::FMLAv1i32_indexed;
9709 RC = &AArch64::FPR32RegClass;
9710 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9712 break;
9713
9715 Opc = AArch64::FMLAv1i64_indexed;
9716 RC = &AArch64::FPR64RegClass;
9717 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9719 break;
9721 Opc = AArch64::FMLAv1i64_indexed;
9722 RC = &AArch64::FPR64RegClass;
9723 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9725 break;
9726
9728 RC = &AArch64::FPR64RegClass;
9729 Opc = AArch64::FMLAv4i16_indexed;
9730 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9732 break;
9734 RC = &AArch64::FPR64RegClass;
9735 Opc = AArch64::FMLAv4f16;
9736 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9738 break;
9740 RC = &AArch64::FPR64RegClass;
9741 Opc = AArch64::FMLAv4i16_indexed;
9742 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9744 break;
9746 RC = &AArch64::FPR64RegClass;
9747 Opc = AArch64::FMLAv4f16;
9748 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9750 break;
9751
9754 RC = &AArch64::FPR64RegClass;
9756 Opc = AArch64::FMLAv2i32_indexed;
9757 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9759 } else {
9760 Opc = AArch64::FMLAv2f32;
9761 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9763 }
9764 break;
9767 RC = &AArch64::FPR64RegClass;
9769 Opc = AArch64::FMLAv2i32_indexed;
9770 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9772 } else {
9773 Opc = AArch64::FMLAv2f32;
9774 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9776 }
9777 break;
9778
9780 RC = &AArch64::FPR128RegClass;
9781 Opc = AArch64::FMLAv8i16_indexed;
9782 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9784 break;
9786 RC = &AArch64::FPR128RegClass;
9787 Opc = AArch64::FMLAv8f16;
9788 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9790 break;
9792 RC = &AArch64::FPR128RegClass;
9793 Opc = AArch64::FMLAv8i16_indexed;
9794 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9796 break;
9798 RC = &AArch64::FPR128RegClass;
9799 Opc = AArch64::FMLAv8f16;
9800 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9802 break;
9803
9806 RC = &AArch64::FPR128RegClass;
9808 Opc = AArch64::FMLAv2i64_indexed;
9809 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9811 } else {
9812 Opc = AArch64::FMLAv2f64;
9813 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9815 }
9816 break;
9819 RC = &AArch64::FPR128RegClass;
9821 Opc = AArch64::FMLAv2i64_indexed;
9822 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9824 } else {
9825 Opc = AArch64::FMLAv2f64;
9826 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9828 }
9829 break;
9830
9833 RC = &AArch64::FPR128RegClass;
9835 Opc = AArch64::FMLAv4i32_indexed;
9836 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9838 } else {
9839 Opc = AArch64::FMLAv4f32;
9840 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9842 }
9843 break;
9844
9847 RC = &AArch64::FPR128RegClass;
9849 Opc = AArch64::FMLAv4i32_indexed;
9850 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9852 } else {
9853 Opc = AArch64::FMLAv4f32;
9854 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9856 }
9857 break;
9858
9860 Opc = AArch64::FNMSUBHrrr;
9861 RC = &AArch64::FPR16RegClass;
9862 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9863 break;
9865 Opc = AArch64::FNMSUBSrrr;
9866 RC = &AArch64::FPR32RegClass;
9867 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9868 break;
9870 Opc = AArch64::FNMSUBDrrr;
9871 RC = &AArch64::FPR64RegClass;
9872 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9873 break;
9874
9876 Opc = AArch64::FNMADDHrrr;
9877 RC = &AArch64::FPR16RegClass;
9878 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9879 break;
9881 Opc = AArch64::FNMADDSrrr;
9882 RC = &AArch64::FPR32RegClass;
9883 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9884 break;
9886 Opc = AArch64::FNMADDDrrr;
9887 RC = &AArch64::FPR64RegClass;
9888 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9889 break;
9890
9892 Opc = AArch64::FMSUBHrrr;
9893 RC = &AArch64::FPR16RegClass;
9894 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9895 break;
9897 Opc = AArch64::FMSUBSrrr;
9898 RC = &AArch64::FPR32RegClass;
9899 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9900 break;
9902 Opc = AArch64::FMSUBDrrr;
9903 RC = &AArch64::FPR64RegClass;
9904 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9905 break;
9906
9908 Opc = AArch64::FMLSv1i32_indexed;
9909 RC = &AArch64::FPR32RegClass;
9910 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9912 break;
9913
9915 Opc = AArch64::FMLSv1i64_indexed;
9916 RC = &AArch64::FPR64RegClass;
9917 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9919 break;
9920
9923 RC = &AArch64::FPR64RegClass;
9925 MachineInstrBuilder MIB1 =
9926 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv4f16), NewVR)
9927 .add(Root.getOperand(2));
9928 InsInstrs.push_back(MIB1);
9929 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9931 Opc = AArch64::FMLAv4f16;
9932 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9933 FMAInstKind::Accumulator, &NewVR);
9934 } else {
9935 Opc = AArch64::FMLAv4i16_indexed;
9936 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9937 FMAInstKind::Indexed, &NewVR);
9938 }
9939 break;
9940 }
9942 RC = &AArch64::FPR64RegClass;
9943 Opc = AArch64::FMLSv4f16;
9944 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9946 break;
9948 RC = &AArch64::FPR64RegClass;
9949 Opc = AArch64::FMLSv4i16_indexed;
9950 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9952 break;
9953
9956 RC = &AArch64::FPR64RegClass;
9958 Opc = AArch64::FMLSv2i32_indexed;
9959 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9961 } else {
9962 Opc = AArch64::FMLSv2f32;
9963 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9965 }
9966 break;
9967
9970 RC = &AArch64::FPR128RegClass;
9972 MachineInstrBuilder MIB1 =
9973 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv8f16), NewVR)
9974 .add(Root.getOperand(2));
9975 InsInstrs.push_back(MIB1);
9976 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9978 Opc = AArch64::FMLAv8f16;
9979 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9980 FMAInstKind::Accumulator, &NewVR);
9981 } else {
9982 Opc = AArch64::FMLAv8i16_indexed;
9983 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9984 FMAInstKind::Indexed, &NewVR);
9985 }
9986 break;
9987 }
9989 RC = &AArch64::FPR128RegClass;
9990 Opc = AArch64::FMLSv8f16;
9991 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9993 break;
9995 RC = &AArch64::FPR128RegClass;
9996 Opc = AArch64::FMLSv8i16_indexed;
9997 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9999 break;
10000
10003 RC = &AArch64::FPR128RegClass;
10005 Opc = AArch64::FMLSv2i64_indexed;
10006 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
10008 } else {
10009 Opc = AArch64::FMLSv2f64;
10010 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
10012 }
10013 break;
10014
10017 RC = &AArch64::FPR128RegClass;
10019 Opc = AArch64::FMLSv4i32_indexed;
10020 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
10022 } else {
10023 Opc = AArch64::FMLSv4f32;
10024 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
10026 }
10027 break;
10030 RC = &AArch64::FPR64RegClass;
10032 MachineInstrBuilder MIB1 =
10033 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv2f32), NewVR)
10034 .add(Root.getOperand(2));
10035 InsInstrs.push_back(MIB1);
10036 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
10038 Opc = AArch64::FMLAv2i32_indexed;
10039 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
10040 FMAInstKind::Indexed, &NewVR);
10041 } else {
10042 Opc = AArch64::FMLAv2f32;
10043 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
10044 FMAInstKind::Accumulator, &NewVR);
10045 }
10046 break;
10047 }
10050 RC = &AArch64::FPR128RegClass;
10052 MachineInstrBuilder MIB1 =
10053 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv4f32), NewVR)
10054 .add(Root.getOperand(2));
10055 InsInstrs.push_back(MIB1);
10056 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
10058 Opc = AArch64::FMLAv4i32_indexed;
10059 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
10060 FMAInstKind::Indexed, &NewVR);
10061 } else {
10062 Opc = AArch64::FMLAv4f32;
10063 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
10064 FMAInstKind::Accumulator, &NewVR);
10065 }
10066 break;
10067 }
10070 RC = &AArch64::FPR128RegClass;
10072 MachineInstrBuilder MIB1 =
10073 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv2f64), NewVR)
10074 .add(Root.getOperand(2));
10075 InsInstrs.push_back(MIB1);
10076 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
10078 Opc = AArch64::FMLAv2i64_indexed;
10079 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
10080 FMAInstKind::Indexed, &NewVR);
10081 } else {
10082 Opc = AArch64::FMLAv2f64;
10083 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
10084 FMAInstKind::Accumulator, &NewVR);
10085 }
10086 break;
10087 }
10090 unsigned IdxDupOp =
10092 : 2;
10093 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv2i32_indexed,
10094 &AArch64::FPR128RegClass, MRI);
10095 break;
10096 }
10099 unsigned IdxDupOp =
10101 : 2;
10102 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv2i64_indexed,
10103 &AArch64::FPR128RegClass, MRI);
10104 break;
10105 }
10108 unsigned IdxDupOp =
10110 : 2;
10111 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv4i16_indexed,
10112 &AArch64::FPR128_loRegClass, MRI);
10113 break;
10114 }
10117 unsigned IdxDupOp =
10119 : 2;
10120 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv4i32_indexed,
10121 &AArch64::FPR128RegClass, MRI);
10122 break;
10123 }
10126 unsigned IdxDupOp =
10128 : 2;
10129 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv8i16_indexed,
10130 &AArch64::FPR128_loRegClass, MRI);
10131 break;
10132 }
10134 MUL = genFNegatedMAD(MF, MRI, TII, Root, InsInstrs);
10135 break;
10136 }
10138 generateGatherLanePattern(Root, InsInstrs, DelInstrs, InstrIdxForVirtReg,
10139 Pattern, 4);
10140 break;
10141 }
10143 generateGatherLanePattern(Root, InsInstrs, DelInstrs, InstrIdxForVirtReg,
10144 Pattern, 8);
10145 break;
10146 }
10148 generateGatherLanePattern(Root, InsInstrs, DelInstrs, InstrIdxForVirtReg,
10149 Pattern, 16);
10150 break;
10151 }
10152
10153 } // end switch (Pattern)
10154 // Record MUL and ADD/SUB for deletion
10155 if (MUL)
10156 DelInstrs.push_back(MUL);
10157 DelInstrs.push_back(&Root);
10158
10159 // Set the flags on the inserted instructions to be the merged flags of the
10160 // instructions that we have combined.
10161 uint32_t Flags = Root.getFlags();
10162 if (MUL)
10163 Flags = Root.mergeFlagsWith(*MUL);
10164 for (auto *MI : InsInstrs)
10165 MI->setFlags(Flags);
10166}
10167
10168/// Replace csincr-branch sequence by simple conditional branch
10169///
10170/// Examples:
10171/// 1. \code
10172/// csinc w9, wzr, wzr, <condition code>
10173/// tbnz w9, #0, 0x44
10174/// \endcode
10175/// to
10176/// \code
10177/// b.<inverted condition code>
10178/// \endcode
10179///
10180/// 2. \code
10181/// csinc w9, wzr, wzr, <condition code>
10182/// tbz w9, #0, 0x44
10183/// \endcode
10184/// to
10185/// \code
10186/// b.<condition code>
10187/// \endcode
10188///
10189/// Replace compare and branch sequence by TBZ/TBNZ instruction when the
10190/// compare's constant operand is power of 2.
10191///
10192/// Examples:
10193/// \code
10194/// and w8, w8, #0x400
10195/// cbnz w8, L1
10196/// \endcode
10197/// to
10198/// \code
10199/// tbnz w8, #10, L1
10200/// \endcode
10201///
10202/// \param MI Conditional Branch
10203/// \return True when the simple conditional branch is generated
10204///
10206 bool IsNegativeBranch = false;
10207 bool IsTestAndBranch = false;
10208 unsigned TargetBBInMI = 0;
10209 switch (MI.getOpcode()) {
10210 default:
10211 llvm_unreachable("Unknown branch instruction?");
10212 case AArch64::Bcc:
10213 case AArch64::CBWPri:
10214 case AArch64::CBXPri:
10215 case AArch64::CBBAssertExt:
10216 case AArch64::CBHAssertExt:
10217 case AArch64::CBWPrr:
10218 case AArch64::CBXPrr:
10219 return false;
10220 case AArch64::CBZW:
10221 case AArch64::CBZX:
10222 TargetBBInMI = 1;
10223 break;
10224 case AArch64::CBNZW:
10225 case AArch64::CBNZX:
10226 TargetBBInMI = 1;
10227 IsNegativeBranch = true;
10228 break;
10229 case AArch64::TBZW:
10230 case AArch64::TBZX:
10231 TargetBBInMI = 2;
10232 IsTestAndBranch = true;
10233 break;
10234 case AArch64::TBNZW:
10235 case AArch64::TBNZX:
10236 TargetBBInMI = 2;
10237 IsNegativeBranch = true;
10238 IsTestAndBranch = true;
10239 break;
10240 }
10241 // So we increment a zero register and test for bits other
10242 // than bit 0? Conservatively bail out in case the verifier
10243 // missed this case.
10244 if (IsTestAndBranch && MI.getOperand(1).getImm())
10245 return false;
10246
10247 // Find Definition.
10248 assert(MI.getParent() && "Incomplete machine instruction\n");
10249 MachineBasicBlock *MBB = MI.getParent();
10250 MachineFunction *MF = MBB->getParent();
10252 Register VReg = MI.getOperand(0).getReg();
10253 if (!VReg.isVirtual())
10254 return false;
10255
10256 MachineInstr *DefMI = MRI->getVRegDef(VReg);
10257 if (!DefMI)
10258 return false;
10259
10260 // Look through COPY instructions to find definition.
10261 while (DefMI->isCopy()) {
10262 Register CopyVReg = DefMI->getOperand(1).getReg();
10263 if (!CopyVReg.isVirtual())
10264 return false;
10265 if (!MRI->hasOneNonDBGUse(CopyVReg))
10266 return false;
10267 DefMI = MRI->getVRegDef(CopyVReg);
10268 if (!DefMI)
10269 return false;
10270 }
10271
10272 switch (DefMI->getOpcode()) {
10273 default:
10274 return false;
10275 // Fold AND into a TBZ/TBNZ if constant operand is power of 2.
10276 case AArch64::ANDWri:
10277 case AArch64::ANDXri: {
10278 if (IsTestAndBranch)
10279 return false;
10280 if (DefMI->getParent() != MBB)
10281 return false;
10282 if (!MRI->hasOneNonDBGUse(VReg))
10283 return false;
10284
10285 bool Is32Bit = (DefMI->getOpcode() == AArch64::ANDWri);
10286 uint64_t Mask = AArch64_AM::decodeLogicalImmediate(
10287 DefMI->getOperand(2).getImm(), Is32Bit ? 32 : 64);
10288 if (!isPowerOf2_64(Mask))
10289 return false;
10290
10291 MachineOperand &MO = DefMI->getOperand(1);
10292 Register NewReg = MO.getReg();
10293 if (!NewReg.isVirtual())
10294 return false;
10295
10296 if (!MRI->getVRegDef(NewReg))
10297 return false;
10298
10299 MachineBasicBlock &RefToMBB = *MBB;
10300 MachineBasicBlock *TBB = MI.getOperand(1).getMBB();
10301 DebugLoc DL = MI.getDebugLoc();
10302 unsigned Imm = Log2_64(Mask);
10303 unsigned Opc = (Imm < 32)
10304 ? (IsNegativeBranch ? AArch64::TBNZW : AArch64::TBZW)
10305 : (IsNegativeBranch ? AArch64::TBNZX : AArch64::TBZX);
10306 MachineInstr *NewMI = BuildMI(RefToMBB, MI, DL, get(Opc))
10307 .addReg(NewReg)
10308 .addImm(Imm)
10309 .addMBB(TBB);
10310 // Register lives on to the CBZ now.
10311 MO.setIsKill(false);
10312
10313 // For immediate smaller than 32, we need to use the 32-bit
10314 // variant (W) in all cases. Indeed the 64-bit variant does not
10315 // allow to encode them.
10316 // Therefore, if the input register is 64-bit, we need to take the
10317 // 32-bit sub-part.
10318 if (!Is32Bit && Imm < 32)
10319 NewMI->getOperand(0).setSubReg(AArch64::sub_32);
10320 MI.eraseFromParent();
10321 return true;
10322 }
10323 // Look for CSINC
10324 case AArch64::CSINCWr:
10325 case AArch64::CSINCXr: {
10326 if (!(DefMI->getOperand(1).getReg() == AArch64::WZR &&
10327 DefMI->getOperand(2).getReg() == AArch64::WZR) &&
10328 !(DefMI->getOperand(1).getReg() == AArch64::XZR &&
10329 DefMI->getOperand(2).getReg() == AArch64::XZR))
10330 return false;
10331
10332 if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr,
10333 true) != -1)
10334 return false;
10335
10336 AArch64CC::CondCode CC = (AArch64CC::CondCode)DefMI->getOperand(3).getImm();
10337 // Convert only when the condition code is not modified between
10338 // the CSINC and the branch. The CC may be used by other
10339 // instructions in between.
10341 return false;
10342 MachineBasicBlock &RefToMBB = *MBB;
10343 MachineBasicBlock *TBB = MI.getOperand(TargetBBInMI).getMBB();
10344 DebugLoc DL = MI.getDebugLoc();
10345 if (IsNegativeBranch)
10347 BuildMI(RefToMBB, MI, DL, get(AArch64::Bcc)).addImm(CC).addMBB(TBB);
10348 MI.eraseFromParent();
10349 return true;
10350 }
10351 }
10352}
10353
10354std::pair<unsigned, unsigned>
10355AArch64InstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
10356 const unsigned Mask = AArch64II::MO_FRAGMENT;
10357 return std::make_pair(TF & Mask, TF & ~Mask);
10358}
10359
10361AArch64InstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
10362 using namespace AArch64II;
10363
10364 static const std::pair<unsigned, const char *> TargetFlags[] = {
10365 {MO_PAGE, "aarch64-page"}, {MO_PAGEOFF, "aarch64-pageoff"},
10366 {MO_G3, "aarch64-g3"}, {MO_G2, "aarch64-g2"},
10367 {MO_G1, "aarch64-g1"}, {MO_G0, "aarch64-g0"},
10368 {MO_HI12, "aarch64-hi12"}};
10369 return ArrayRef(TargetFlags);
10370}
10371
10373AArch64InstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
10374 using namespace AArch64II;
10375
10376 static const std::pair<unsigned, const char *> TargetFlags[] = {
10377 {MO_COFFSTUB, "aarch64-coffstub"},
10378 {MO_GOT, "aarch64-got"},
10379 {MO_NC, "aarch64-nc"},
10380 {MO_S, "aarch64-s"},
10381 {MO_TLS, "aarch64-tls"},
10382 {MO_DLLIMPORT, "aarch64-dllimport"},
10383 {MO_PREL, "aarch64-prel"},
10384 {MO_TAGGED, "aarch64-tagged"},
10385 {MO_ARM64EC_CALLMANGLE, "aarch64-arm64ec-callmangle"},
10386 };
10387 return ArrayRef(TargetFlags);
10388}
10389
10391AArch64InstrInfo::getSerializableMachineMemOperandTargetFlags() const {
10392 static const std::pair<MachineMemOperand::Flags, const char *> TargetFlags[] =
10393 {{MOSuppressPair, "aarch64-suppress-pair"},
10394 {MOStridedAccess, "aarch64-strided-access"}};
10395 return ArrayRef(TargetFlags);
10396}
10397
10398/// Constants defining how certain sequences should be outlined.
10399/// This encompasses how an outlined function should be called, and what kind of
10400/// frame should be emitted for that outlined function.
10401///
10402/// \p MachineOutlinerDefault implies that the function should be called with
10403/// a save and restore of LR to the stack.
10404///
10405/// That is,
10406///
10407/// I1 Save LR OUTLINED_FUNCTION:
10408/// I2 --> BL OUTLINED_FUNCTION I1
10409/// I3 Restore LR I2
10410/// I3
10411/// RET
10412///
10413/// * Call construction overhead: 3 (save + BL + restore)
10414/// * Frame construction overhead: 1 (ret)
10415/// * Requires stack fixups? Yes
10416///
10417/// \p MachineOutlinerTailCall implies that the function is being created from
10418/// a sequence of instructions ending in a return.
10419///
10420/// That is,
10421///
10422/// I1 OUTLINED_FUNCTION:
10423/// I2 --> B OUTLINED_FUNCTION I1
10424/// RET I2
10425/// RET
10426///
10427/// * Call construction overhead: 1 (B)
10428/// * Frame construction overhead: 0 (Return included in sequence)
10429/// * Requires stack fixups? No
10430///
10431/// \p MachineOutlinerNoLRSave implies that the function should be called using
10432/// a BL instruction, but doesn't require LR to be saved and restored. This
10433/// happens when LR is known to be dead.
10434///
10435/// That is,
10436///
10437/// I1 OUTLINED_FUNCTION:
10438/// I2 --> BL OUTLINED_FUNCTION I1
10439/// I3 I2
10440/// I3
10441/// RET
10442///
10443/// * Call construction overhead: 1 (BL)
10444/// * Frame construction overhead: 1 (RET)
10445/// * Requires stack fixups? No
10446///
10447/// \p MachineOutlinerThunk implies that the function is being created from
10448/// a sequence of instructions ending in a call. The outlined function is
10449/// called with a BL instruction, and the outlined function tail-calls the
10450/// original call destination.
10451///
10452/// That is,
10453///
10454/// I1 OUTLINED_FUNCTION:
10455/// I2 --> BL OUTLINED_FUNCTION I1
10456/// BL f I2
10457/// B f
10458/// * Call construction overhead: 1 (BL)
10459/// * Frame construction overhead: 0
10460/// * Requires stack fixups? No
10461///
10462/// \p MachineOutlinerRegSave implies that the function should be called with a
10463/// save and restore of LR to an available register. This allows us to avoid
10464/// stack fixups. Note that this outlining variant is compatible with the
10465/// NoLRSave case.
10466///
10467/// That is,
10468///
10469/// I1 Save LR OUTLINED_FUNCTION:
10470/// I2 --> BL OUTLINED_FUNCTION I1
10471/// I3 Restore LR I2
10472/// I3
10473/// RET
10474///
10475/// * Call construction overhead: 3 (save + BL + restore)
10476/// * Frame construction overhead: 1 (ret)
10477/// * Requires stack fixups? No
10479 MachineOutlinerDefault, /// Emit a save, restore, call, and return.
10480 MachineOutlinerTailCall, /// Only emit a branch.
10481 MachineOutlinerNoLRSave, /// Emit a call and return.
10482 MachineOutlinerThunk, /// Emit a call and tail-call.
10483 MachineOutlinerRegSave /// Same as default, but save to a register.
10484};
10485
10491
10492/// Return true if the frame-record form of the outlined prologue is enabled for
10493/// the target of \p MF.
10494///
10495/// A non-leaf outlined function must save LR. On MachO, saving LR alone
10496/// (str x30) has no compact unwind encoding, so we get a large DWARF FDE
10497/// instead. Saving FP and LR as a frame record (stp x29, x30 ; mov x29, sp)
10498/// gets the small FRAME encoding, and costs one extra instruction.
10500 return MF.getSubtarget<AArch64Subtarget>()
10501 .getCLOpts()
10502 .outliner_compact_unwind_frame &&
10504}
10505
10506/// Return true if the outlined function in \p MBB should save FP and LR as a
10507/// frame record instead of saving LR alone.
10509 const MachineBasicBlock &MBB) {
10510 const MachineFunction &MF = *MBB.getParent();
10511
10512 // Only worth it if the function has unwind info to shrink.
10515 return false;
10516
10517 // Only safe if the outlined code never touches FP, since we overwrite it.
10519 for (const MachineInstr &MI : MBB.instrs())
10520 LRU.accumulate(MI);
10521 return LRU.available(AArch64::FP);
10522}
10523
10524/// Predict what the above will answer, for use while costing candidates. The
10525/// outlined function does not exist yet, so answer from \p RepeatedSequenceLocs
10526/// instead. This is only an estimate; buildOutlinedFrame() makes the call.
10528 std::vector<outliner::Candidate> &RepeatedSequenceLocs,
10529 const TargetRegisterInfo &TRI) {
10530 if (!isCompactUnwindFrameRecordEnabled(*RepeatedSequenceLocs.front().getMF()))
10531 return false;
10532
10533 // The outlined function is nounwind only if every candidate is, so it has
10534 // unwind info if any candidate does.
10535 if (llvm::none_of(RepeatedSequenceLocs, [](outliner::Candidate &C) {
10536 const MachineFunction &MF = *C.getMF();
10537 return MF.getInfo<AArch64FunctionInfo>()->needsDwarfUnwindInfo(MF);
10538 }))
10539 return false;
10540
10541 // FP is free in the outlined function only if it is free in every candidate.
10542 return llvm::all_of(RepeatedSequenceLocs, [&TRI](outliner::Candidate &C) {
10543 return C.isAvailableInsideSeq(AArch64::FP, TRI);
10544 });
10545}
10546
10548AArch64InstrInfo::findRegisterToSaveLRTo(outliner::Candidate &C) const {
10549 MachineFunction *MF = C.getMF();
10550 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
10551 const AArch64RegisterInfo *ARI =
10552 static_cast<const AArch64RegisterInfo *>(&TRI);
10553 // Check if there is an available register across the sequence that we can
10554 // use.
10555 for (unsigned Reg : AArch64::GPR64RegClass) {
10556 if (!ARI->isReservedReg(*MF, Reg) &&
10557 Reg != AArch64::LR && // LR is not reserved, but don't use it.
10558 Reg != AArch64::X16 && // X16 is not guaranteed to be preserved.
10559 Reg != AArch64::X17 && // Ditto for X17.
10560 C.isAvailableAcrossAndOutOfSeq(Reg, TRI) &&
10561 C.isAvailableInsideSeq(Reg, TRI))
10562 return Reg;
10563 }
10564 return Register();
10565}
10566
10567static bool
10569 const outliner::Candidate &b) {
10570 const auto &MFIa = a.getMF()->getInfo<AArch64FunctionInfo>();
10571 const auto &MFIb = b.getMF()->getInfo<AArch64FunctionInfo>();
10572
10573 return MFIa->getSignReturnAddressCondition() ==
10575}
10576
10577static bool
10579 const outliner::Candidate &b) {
10580 const auto &MFIa = a.getMF()->getInfo<AArch64FunctionInfo>();
10581 const auto &MFIb = b.getMF()->getInfo<AArch64FunctionInfo>();
10582
10583 return MFIa->shouldSignWithBKey() == MFIb->shouldSignWithBKey();
10584}
10585
10587 const outliner::Candidate &b) {
10588 const auto &MFIa = a.getMF()->getInfo<AArch64FunctionInfo>();
10589 const auto &MFIb = b.getMF()->getInfo<AArch64FunctionInfo>();
10590
10591 const AArch64Subtarget &SubtargetA =
10593 const AArch64Subtarget &SubtargetB =
10594 b.getMF()->getSubtarget<AArch64Subtarget>();
10595
10596 // Return true only if branch-protection-pauth-lr attributes match
10597 // and +pauth-lr feature is enabled for both.
10598 if (MFIa->branchProtectionPAuthLR() != MFIb->branchProtectionPAuthLR())
10599 return false;
10600
10601 return !MFIa->branchProtectionPAuthLR() ||
10602 SubtargetA.hasPAuthLR() == SubtargetB.hasPAuthLR();
10603}
10604
10606 const outliner::Candidate &b) {
10607 const AArch64Subtarget &SubtargetA =
10609 const AArch64Subtarget &SubtargetB =
10610 b.getMF()->getSubtarget<AArch64Subtarget>();
10611 return SubtargetA.hasV8_3aOps() == SubtargetB.hasV8_3aOps();
10612}
10613
10614namespace {
10615struct SPAddSubImmEncoding {
10616 unsigned Opcode;
10617 int64_t Imm;
10618 int64_t Shift;
10619};
10620} // namespace
10621
10622/// Returns true if \p MI is an ADD/SUBXri with an immediate offset that reads
10623/// SP but does not write SP (e.g. "add x0, sp, #48").
10624static bool isSPAddSubImm(const MachineInstr &MI) {
10625 if (MI.getOpcode() != AArch64::ADDXri && MI.getOpcode() != AArch64::SUBXri)
10626 return false;
10627
10628 assert(MI.getNumExplicitOperands() == 4 && "Wrong number of operands");
10629 assert(MI.getOperand(0).isReg() && MI.getOperand(1).isReg() &&
10630 MI.getOperand(3).isImm() && "Unexpected add/sub immediate operands");
10631
10632 if (MI.getOperand(0).getReg() == AArch64::SP)
10633 return false;
10634 if (MI.getOperand(1).getReg() != AArch64::SP)
10635 return false;
10636
10637 return MI.getOperand(2).isImm();
10638}
10639
10640/// Adjust the signed byte offset of \p MI, which must satisfy isSPAddSubImm,
10641/// by \p Delta and re-encode the result. Returns std::nullopt if the adjusted
10642/// offset is not encodable.
10643static std::optional<SPAddSubImmEncoding>
10644adjustSPAddSubImm(const MachineInstr &MI, int64_t Delta) {
10645 assert(isSPAddSubImm(MI) && "Expected an SP-based add/sub immediate");
10646 bool IsSub = MI.getOpcode() == AArch64::SUBXri;
10647
10648 // ADD/SUBXri encode a 12-bit unsigned immediate with an optional left shift
10649 // which can only be 12.
10650 int64_t ShiftImm = MI.getOperand(3).getImm();
10652 "Unexpected add/sub immediate shift type");
10653 unsigned Shift = AArch64_AM::getShiftValue(ShiftImm);
10654 assert((Shift == 0 || Shift == 12) && "Unexpected add/sub immediate shift");
10655
10656 int64_t Offset = MI.getOperand(2).getImm() << Shift;
10657 if (IsSub)
10658 Offset = -Offset;
10659
10660 // Apply the adjustment and try to re-encode.
10661 int64_t NewOffset = Offset + Delta;
10662 int64_t AbsOffset = std::abs(NewOffset);
10663
10664 SPAddSubImmEncoding Enc;
10665 Enc.Opcode = NewOffset < 0 ? AArch64::SUBXri : AArch64::ADDXri;
10666
10667 // Try to encode as a 12-bit immediate with shift=0 first.
10668 if (AbsOffset <= 0xfff) {
10669 Enc.Imm = AbsOffset;
10671 } else if ((AbsOffset & 0xfff) == 0 && (AbsOffset >> 12) <= 0xfff) {
10672 Enc.Imm = AbsOffset >> 12;
10674 } else {
10675 return std::nullopt;
10676 }
10677
10678 return Enc;
10679}
10680
10681std::optional<std::unique_ptr<outliner::OutlinedFunction>>
10682AArch64InstrInfo::getOutliningCandidateInfo(
10683 const MachineModuleInfo &MMI,
10684 std::vector<outliner::Candidate> &RepeatedSequenceLocs,
10685 unsigned MinRepeats) const {
10686 unsigned SequenceSize = 0;
10687 for (auto &MI : RepeatedSequenceLocs[0])
10688 SequenceSize += getInstSizeInBytes(MI);
10689
10690 unsigned NumBytesToCreateFrame = 0;
10691
10692 // Avoid splitting ADRP ADD/LDR pair into outlined functions.
10693 // These instructions are fused together by the scheduler.
10694 // Any candidate where ADRP is the last instruction should be rejected
10695 // as that will lead to splitting ADRP pair.
10696 MachineInstr &LastMI = RepeatedSequenceLocs[0].back();
10697 MachineInstr &FirstMI = RepeatedSequenceLocs[0].front();
10698 if (LastMI.getOpcode() == AArch64::ADRP &&
10699 (LastMI.getOperand(1).getTargetFlags() & AArch64II::MO_PAGE) != 0 &&
10700 (LastMI.getOperand(1).getTargetFlags() & AArch64II::MO_GOT) != 0) {
10701 return std::nullopt;
10702 }
10703
10704 // Similarly any candidate where the first instruction is ADD/LDR with a
10705 // page offset should be rejected to avoid ADRP splitting.
10706 if ((FirstMI.getOpcode() == AArch64::ADDXri ||
10707 FirstMI.getOpcode() == AArch64::LDRXui) &&
10708 (FirstMI.getOperand(2).getTargetFlags() & AArch64II::MO_PAGEOFF) != 0 &&
10709 (FirstMI.getOperand(2).getTargetFlags() & AArch64II::MO_GOT) != 0) {
10710 return std::nullopt;
10711 }
10712
10713 // We only allow outlining for functions having exactly matching return
10714 // address signing attributes, i.e., all share the same value for the
10715 // attribute "sign-return-address", all share the same type of key they
10716 // are signed with & all share the same pauth-lr attributes.
10717 // Additionally we require all functions to simultaneously either support
10718 // v8.3a features or not. Otherwise an outlined function could get signed
10719 // using dedicated v8.3 instructions and a call from a function that doesn't
10720 // support v8.3 instructions would therefore be invalid.
10721 if (std::adjacent_find(
10722 RepeatedSequenceLocs.begin(), RepeatedSequenceLocs.end(),
10723 [](const outliner::Candidate &a, const outliner::Candidate &b) {
10724 // Return true if a and b are non-equal w.r.t. return address
10725 // signing, support of v8.3a features or support of pauth-lr
10726 if (outliningCandidatesSigningScopeConsensus(a, b) &&
10727 outliningCandidatesSigningKeyConsensus(a, b) &&
10728 outliningCandidatesV8_3OpsConsensus(a, b) &&
10729 outliningCandidatesPAuthLRConsensus(a, b)) {
10730 return false;
10731 }
10732 return true;
10733 }) != RepeatedSequenceLocs.end()) {
10734 return std::nullopt;
10735 }
10736
10737 // Since at this point all candidates agree on their return address signing
10738 // picking just one is fine. If the candidate functions potentially sign their
10739 // return addresses, the outlined function should do the same. Note that in
10740 // the case of "sign-return-address"="non-leaf" this is an assumption: It is
10741 // not certainly true that the outlined function will have to sign its return
10742 // address but this decision is made later, when the decision to outline
10743 // has already been made.
10744 // The same holds for the number of additional instructions we need: On
10745 // v8.3a RET can be replaced by RETAA/RETAB and no AUT instruction is
10746 // necessary. However, at this point we don't know if the outlined function
10747 // will have a RET instruction so we assume the worst.
10748 const TargetRegisterInfo &TRI = getRegisterInfo();
10749 // Performing a tail call may require extra checks when PAuth is enabled.
10750 // If PAuth is disabled, set it to zero for uniformity.
10751 unsigned NumBytesToCheckLRInTCEpilogue = 0;
10752 const auto RASignCondition = RepeatedSequenceLocs[0]
10753 .getMF()
10754 ->getInfo<AArch64FunctionInfo>()
10755 ->getSignReturnAddressCondition();
10756 if (RASignCondition != SignReturnAddress::None) {
10757 // Candidates that have Return Address Authentication Hardening enabled are
10758 // discarded.
10759 //
10760 // In its current form, the machine outliner does not preserve X16/X17
10761 // across outlined function calls, even though it should as they are
10762 // caller-saved registers. And since the hardening based on load from the
10763 // return address may clobber one of these registers, if they are alive
10764 // across a call their value would be lost due to the hardening mechanism.
10765 llvm::erase_if(RepeatedSequenceLocs, [](outliner::Candidate &C) {
10766 return C.getMF()
10767 ->getInfo<AArch64FunctionInfo>()
10768 ->shouldHardenSignReturnAddress();
10769 });
10770 // If the sequence doesn't have enough candidates left, then we're done.
10771 if (RepeatedSequenceLocs.size() < MinRepeats)
10772 return std::nullopt;
10773
10774 // One PAC and one AUT instructions
10775 NumBytesToCreateFrame += 8;
10776
10777 // PAuth is enabled - set extra tail call cost, if any.
10778 auto LRCheckMethod = Subtarget.getAuthenticatedLRCheckMethod(
10779 *RepeatedSequenceLocs[0].getMF());
10780 NumBytesToCheckLRInTCEpilogue =
10782 // Checking the authenticated LR value may significantly impact
10783 // SequenceSize, so account for it for more precise results.
10784 if (isTailCallReturnInst(RepeatedSequenceLocs[0].back()))
10785 SequenceSize += NumBytesToCheckLRInTCEpilogue;
10786
10787 // We have to check if sp modifying instructions would get outlined.
10788 // If so we only allow outlining if sp is unchanged overall, so matching
10789 // sub and add instructions are okay to outline, all other sp modifications
10790 // are not
10791 auto hasIllegalSPModification = [&TRI](outliner::Candidate &C) {
10792 int SPValue = 0;
10793 for (auto &MI : C) {
10794 if (MI.modifiesRegister(AArch64::SP, &TRI)) {
10795 switch (MI.getOpcode()) {
10796 case AArch64::ADDXri:
10797 case AArch64::ADDWri:
10798 assert(MI.getNumOperands() == 4 && "Wrong number of operands");
10799 assert(MI.getOperand(2).isImm() &&
10800 "Expected operand to be immediate");
10801 assert(MI.getOperand(1).isReg() &&
10802 "Expected operand to be a register");
10803 // Check if the add just increments sp. If so, we search for
10804 // matching sub instructions that decrement sp. If not, the
10805 // modification is illegal
10806 if (MI.getOperand(1).getReg() == AArch64::SP)
10807 SPValue += MI.getOperand(2).getImm();
10808 else
10809 return true;
10810 break;
10811 case AArch64::SUBXri:
10812 case AArch64::SUBWri:
10813 assert(MI.getNumOperands() == 4 && "Wrong number of operands");
10814 assert(MI.getOperand(2).isImm() &&
10815 "Expected operand to be immediate");
10816 assert(MI.getOperand(1).isReg() &&
10817 "Expected operand to be a register");
10818 // Check if the sub just decrements sp. If so, we search for
10819 // matching add instructions that increment sp. If not, the
10820 // modification is illegal
10821 if (MI.getOperand(1).getReg() == AArch64::SP)
10822 SPValue -= MI.getOperand(2).getImm();
10823 else
10824 return true;
10825 break;
10826 default:
10827 return true;
10828 }
10829 }
10830 }
10831 if (SPValue)
10832 return true;
10833 return false;
10834 };
10835 // Remove candidates with illegal stack modifying instructions
10836 llvm::erase_if(RepeatedSequenceLocs, hasIllegalSPModification);
10837
10838 // If the sequence doesn't have enough candidates left, then we're done.
10839 if (RepeatedSequenceLocs.size() < MinRepeats)
10840 return std::nullopt;
10841 }
10842
10843 // Properties about candidate MBBs that hold for all of them.
10844 unsigned FlagsSetInAll = 0xF;
10845
10846 // Compute liveness information for each candidate, and set FlagsSetInAll.
10847 for (outliner::Candidate &C : RepeatedSequenceLocs)
10848 FlagsSetInAll &= C.Flags;
10849
10850 unsigned LastInstrOpcode = RepeatedSequenceLocs[0].back().getOpcode();
10851
10852 // Helper lambda which sets call information for every candidate.
10853 auto SetCandidateCallInfo =
10854 [&RepeatedSequenceLocs](unsigned CallID, unsigned NumBytesForCall) {
10855 for (outliner::Candidate &C : RepeatedSequenceLocs)
10856 C.setCallInfo(CallID, NumBytesForCall);
10857 };
10858
10859 unsigned FrameID = MachineOutlinerDefault;
10860 NumBytesToCreateFrame += 4;
10861
10862 bool HasBTI = any_of(RepeatedSequenceLocs, [](outliner::Candidate &C) {
10863 return C.getMF()->getInfo<AArch64FunctionInfo>()->branchTargetEnforcement();
10864 });
10865
10866 // We check to see if CFI Instructions are present, and if they are
10867 // we find the number of CFI Instructions in the candidates.
10868 unsigned CFICount = 0;
10869 for (auto &I : RepeatedSequenceLocs[0]) {
10870 if (I.isCFIInstruction())
10871 CFICount++;
10872 }
10873
10874 // We compare the number of found CFI Instructions to the number of CFI
10875 // instructions in the parent function for each candidate. We must check this
10876 // since if we outline one of the CFI instructions in a function, we have to
10877 // outline them all for correctness. If we do not, the address offsets will be
10878 // incorrect between the two sections of the program.
10879 for (outliner::Candidate &C : RepeatedSequenceLocs) {
10880 std::vector<MCCFIInstruction> CFIInstructions =
10881 C.getMF()->getFrameInstructions();
10882
10883 if (CFICount > 0 && CFICount != CFIInstructions.size())
10884 return std::nullopt;
10885 }
10886
10887 // Returns true if an instructions is safe to fix up, false otherwise.
10888 auto IsSafeToFixup = [this, &TRI](MachineInstr &MI) {
10889 if (MI.isCall())
10890 return true;
10891
10892 if (!MI.modifiesRegister(AArch64::SP, &TRI) &&
10893 !MI.readsRegister(AArch64::SP, &TRI))
10894 return true;
10895
10896 // Any modification of SP will break our code to save/restore LR.
10897 // FIXME: We could handle some instructions which add a constant
10898 // offset to SP, with a bit more work.
10899 if (MI.modifiesRegister(AArch64::SP, &TRI))
10900 return false;
10901
10902 // At this point, we have a stack instruction that we might need to
10903 // fix up. We'll handle it if it's a load or store.
10904 if (MI.mayLoadOrStore()) {
10905 const MachineOperand *Base; // Filled with the base operand of MI.
10906 int64_t Offset; // Filled with the offset of MI.
10907 bool OffsetIsScalable;
10908
10909 // Does it allow us to offset the base operand and is the base the
10910 // register SP?
10911 if (!getMemOperandWithOffset(MI, Base, Offset, OffsetIsScalable) ||
10912 !Base->isReg() || Base->getReg() != AArch64::SP)
10913 return false;
10914
10915 // Fixe-up code below assumes bytes.
10916 if (OffsetIsScalable)
10917 return false;
10918
10919 // Find the minimum/maximum offset for this instruction and check
10920 // if fixing it up would be in range.
10921 int64_t MinOffset,
10922 MaxOffset; // Unscaled offsets for the instruction.
10923 // The scale to multiply the offsets by.
10924 TypeSize Scale(0U, false), DummyWidth(0U, false);
10925 getMemOpInfo(MI.getOpcode(), Scale, DummyWidth, MinOffset, MaxOffset);
10926
10927 Offset += 16; // Update the offset to what it would be if we outlined.
10928 if (Offset < MinOffset * (int64_t)Scale.getFixedValue() ||
10929 Offset > MaxOffset * (int64_t)Scale.getFixedValue())
10930 return false;
10931
10932 // It's in range, so we can outline it.
10933 return true;
10934 }
10935
10936 if (isSPAddSubImm(MI))
10937 return adjustSPAddSubImm(MI, 16).has_value();
10938
10939 // FIXME: Add handling for other SP-based address calculations that can be
10940 // adjusted after outlining.
10941 return false;
10942 };
10943
10944 // True if it's possible to fix up each stack instruction in this sequence.
10945 // Important for frames/call variants that modify the stack.
10946 bool AllStackInstrsSafe =
10947 llvm::all_of(RepeatedSequenceLocs[0], IsSafeToFixup);
10948
10949 // If the last instruction in any candidate is a terminator, then we should
10950 // tail call all of the candidates.
10951 if (RepeatedSequenceLocs[0].back().isTerminator()) {
10952 FrameID = MachineOutlinerTailCall;
10953 NumBytesToCreateFrame = 0;
10954 unsigned NumBytesForCall = 4 + NumBytesToCheckLRInTCEpilogue;
10955 SetCandidateCallInfo(MachineOutlinerTailCall, NumBytesForCall);
10956 }
10957
10958 else if (LastInstrOpcode == AArch64::BL ||
10959 ((LastInstrOpcode == AArch64::BLR ||
10960 LastInstrOpcode == AArch64::BLRNoIP) &&
10961 !HasBTI)) {
10962 // FIXME: Do we need to check if the code after this uses the value of LR?
10963 FrameID = MachineOutlinerThunk;
10964 NumBytesToCreateFrame = NumBytesToCheckLRInTCEpilogue;
10965 SetCandidateCallInfo(MachineOutlinerThunk, 4);
10966 }
10967
10968 else {
10969 // We need to decide how to emit calls + frames. We can always emit the same
10970 // frame if we don't need to save to the stack. If we have to save to the
10971 // stack, then we need a different frame.
10972 unsigned NumBytesNoStackCalls = 0;
10973 std::vector<outliner::Candidate> CandidatesWithoutStackFixups;
10974
10975 // Check if we have to save LR.
10976 for (outliner::Candidate &C : RepeatedSequenceLocs) {
10977 bool LRAvailable =
10979 ? C.isAvailableAcrossAndOutOfSeq(AArch64::LR, TRI)
10980 : true;
10981 // If we have a noreturn caller, then we're going to be conservative and
10982 // say that we have to save LR. If we don't have a ret at the end of the
10983 // block, then we can't reason about liveness accurately.
10984 //
10985 // FIXME: We can probably do better than always disabling this in
10986 // noreturn functions by fixing up the liveness info.
10987 bool IsNoReturn =
10988 C.getMF()->getFunction().hasFnAttribute(Attribute::NoReturn);
10989
10990 // Is LR available? If so, we don't need a save.
10991 if (LRAvailable && !IsNoReturn) {
10992 NumBytesNoStackCalls += 4;
10993 C.setCallInfo(MachineOutlinerNoLRSave, 4);
10994 CandidatesWithoutStackFixups.push_back(C);
10995 }
10996
10997 // Is an unused register available? If so, we won't modify the stack, so
10998 // we can outline with the same frame type as those that don't save LR.
10999 else if (findRegisterToSaveLRTo(C)) {
11000 NumBytesNoStackCalls += 12;
11001 C.setCallInfo(MachineOutlinerRegSave, 12);
11002 CandidatesWithoutStackFixups.push_back(C);
11003 }
11004
11005 // Is SP used in the sequence at all? If not, we don't have to modify
11006 // the stack, so we are guaranteed to get the same frame.
11007 else if (C.isAvailableInsideSeq(AArch64::SP, TRI)) {
11008 NumBytesNoStackCalls += 12;
11009 C.setCallInfo(MachineOutlinerDefault, 12);
11010 CandidatesWithoutStackFixups.push_back(C);
11011 }
11012
11013 // If we outline this, we need to modify the stack. Pretend we don't
11014 // outline this by saving all of its bytes.
11015 else {
11016 NumBytesNoStackCalls += SequenceSize;
11017 }
11018 }
11019
11020 // If there are no places where we have to save LR, then note that we
11021 // don't have to update the stack. Otherwise, give every candidate the
11022 // default call type, as long as it's safe to do so.
11023 if (!AllStackInstrsSafe ||
11024 NumBytesNoStackCalls <= RepeatedSequenceLocs.size() * 12) {
11025 RepeatedSequenceLocs = CandidatesWithoutStackFixups;
11026 FrameID = MachineOutlinerNoLRSave;
11027 if (RepeatedSequenceLocs.size() < MinRepeats)
11028 return std::nullopt;
11029 } else {
11030 SetCandidateCallInfo(MachineOutlinerDefault, 12);
11031
11032 // Bugzilla ID: 46767
11033 // TODO: Check if fixing up the stack more than once is safe so we can
11034 // outline these.
11035 //
11036 // An outline resulting in a caller that requires stack fixups at the
11037 // callsite to a callee that also requires stack fixups can happen when
11038 // there are no available registers at the candidate callsite for a
11039 // candidate that itself also has calls.
11040 //
11041 // In other words if function_containing_sequence in the following pseudo
11042 // assembly requires that we save LR at the point of the call, but there
11043 // are no available registers: in this case we save using SP and as a
11044 // result the SP offsets requires stack fixups by multiples of 16.
11045 //
11046 // function_containing_sequence:
11047 // ...
11048 // save LR to SP <- Requires stack instr fixups in OUTLINED_FUNCTION_N
11049 // call OUTLINED_FUNCTION_N
11050 // restore LR from SP
11051 // ...
11052 //
11053 // OUTLINED_FUNCTION_N:
11054 // save LR to SP <- Requires stack instr fixups in OUTLINED_FUNCTION_N
11055 // ...
11056 // bl foo
11057 // restore LR from SP
11058 // ret
11059 //
11060 // Because the code to handle more than one stack fixup does not
11061 // currently have the proper checks for legality, these cases will assert
11062 // in the AArch64 MachineOutliner. This is because the code to do this
11063 // needs more hardening, testing, better checks that generated code is
11064 // legal, etc and because it is only verified to handle a single pass of
11065 // stack fixup.
11066 //
11067 // The assert happens in AArch64InstrInfo::buildOutlinedFrame to catch
11068 // these cases until they are known to be handled. Bugzilla 46767 is
11069 // referenced in comments at the assert site.
11070 //
11071 // To avoid asserting (or generating non-legal code on noassert builds)
11072 // we remove all candidates which would need more than one stack fixup by
11073 // pruning the cases where the candidate has calls while also having no
11074 // available LR and having no available general purpose registers to copy
11075 // LR to (ie one extra stack save/restore).
11076 //
11077 if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) {
11078 erase_if(RepeatedSequenceLocs, [this, &TRI](outliner::Candidate &C) {
11079 auto IsCall = [](const MachineInstr &MI) { return MI.isCall(); };
11080 return (llvm::any_of(C, IsCall)) &&
11081 (!C.isAvailableAcrossAndOutOfSeq(AArch64::LR, TRI) ||
11082 !findRegisterToSaveLRTo(C));
11083 });
11084 }
11085 }
11086
11087 // If we dropped all of the candidates, bail out here.
11088 if (RepeatedSequenceLocs.size() < MinRepeats)
11089 return std::nullopt;
11090 }
11091
11092 // Does every candidate's MBB contain a call? If so, then we might have a call
11093 // in the range.
11094 if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) {
11095 // Check if the range contains a call. These require a save + restore of the
11096 // link register.
11097 outliner::Candidate &FirstCand = RepeatedSequenceLocs[0];
11098 bool ModStackToSaveLR = false;
11099 if (any_of(drop_end(FirstCand),
11100 [](const MachineInstr &MI) { return MI.isCall(); }))
11101 ModStackToSaveLR = true;
11102
11103 // Handle the last instruction separately. If this is a tail call, then the
11104 // last instruction is a call. We don't want to save + restore in this case.
11105 // However, it could be possible that the last instruction is a call without
11106 // it being valid to tail call this sequence. We should consider this as
11107 // well.
11108 else if (FrameID != MachineOutlinerThunk &&
11109 FrameID != MachineOutlinerTailCall && FirstCand.back().isCall())
11110 ModStackToSaveLR = true;
11111
11112 if (ModStackToSaveLR) {
11113 // We can't fix up the stack. Bail out.
11114 if (!AllStackInstrsSafe)
11115 return std::nullopt;
11116
11117 // Save + restore LR.
11118 NumBytesToCreateFrame += 8;
11119
11120 // Add the extra mov if we will save a frame record instead of just LR.
11122 RepeatedSequenceLocs, TRI))
11123 NumBytesToCreateFrame += 4;
11124 }
11125 }
11126
11127 // If we have CFI instructions, we can only outline if the outlined section
11128 // can be a tail call
11129 if (FrameID != MachineOutlinerTailCall && CFICount > 0)
11130 return std::nullopt;
11131
11132 return std::make_unique<outliner::OutlinedFunction>(
11133 RepeatedSequenceLocs, SequenceSize, NumBytesToCreateFrame, FrameID);
11134}
11135
11136void AArch64InstrInfo::mergeOutliningCandidateAttributes(
11137 Function &F, std::vector<outliner::Candidate> &Candidates) const {
11138 // If a bunch of candidates reach this point they must agree on their return
11139 // address signing. It is therefore enough to just consider the signing
11140 // behaviour of one of them
11141 const auto &CFn = Candidates.front().getMF()->getFunction();
11142
11143 if (CFn.hasFnAttribute("ptrauth-returns"))
11144 F.addFnAttr(CFn.getFnAttribute("ptrauth-returns"));
11145 if (CFn.hasFnAttribute("ptrauth-auth-traps"))
11146 F.addFnAttr(CFn.getFnAttribute("ptrauth-auth-traps"));
11147 if (CFn.hasFnAttribute("branch-protection-pauth-lr"))
11148 F.addFnAttr(CFn.getFnAttribute("branch-protection-pauth-lr"));
11149 // Since all candidates belong to the same module, just copy the
11150 // function-level attributes of an arbitrary function.
11151 if (CFn.hasFnAttribute("sign-return-address"))
11152 F.addFnAttr(CFn.getFnAttribute("sign-return-address"));
11153 if (CFn.hasFnAttribute("sign-return-address-key"))
11154 F.addFnAttr(CFn.getFnAttribute("sign-return-address-key"));
11155 // The "sign-return-address-harden" attribute is not included because no
11156 // candidate is supposed to have hardening enabled.
11157 assert(llvm::none_of(Candidates, [](const outliner::Candidate &C) {
11158 return C.getMF()
11159 ->getInfo<AArch64FunctionInfo>()
11160 ->shouldHardenSignReturnAddress();
11161 }));
11162
11163 AArch64GenInstrInfo::mergeOutliningCandidateAttributes(F, Candidates);
11164}
11165
11166bool AArch64InstrInfo::isFunctionSafeToOutlineFrom(
11167 MachineFunction &MF, bool OutlineFromLinkOnceODRs) const {
11169 OutlineFromLinkOnceODRs))
11170 return false;
11171
11172 // Outlining from functions with redzones is unsafe since the outliner may
11173 // modify the stack. Check if hasRedZone is true or unknown; if yes, don't
11174 // outline from it.
11175 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
11176 if (!AFI || AFI->hasRedZone().value_or(true))
11177 return false;
11178
11179 // FIXME: Determine whether it is safe to outline from functions which contain
11180 // streaming-mode changes. We may need to ensure any smstart/smstop pairs are
11181 // outlined together and ensure it is safe to outline with async unwind info,
11182 // required for saving & restoring VG around calls.
11183 if (AFI->hasStreamingModeChanges())
11184 return false;
11185
11186 // FIXME: Teach the outliner to generate/handle Windows unwind info.
11187 if (MF.usesWindowsUnwindInfo())
11188 return false;
11189
11190 // It's safe to outline from MF.
11191 return true;
11192}
11193
11195AArch64InstrInfo::getOutlinableRanges(MachineBasicBlock &MBB,
11196 unsigned &Flags) const {
11198 "Must track liveness!");
11200 std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>>
11201 Ranges;
11202 // According to the AArch64 Procedure Call Standard, the following are
11203 // undefined on entry/exit from a function call:
11204 //
11205 // * Registers x16, x17, (and thus w16, w17)
11206 // * Condition codes (and thus the NZCV register)
11207 //
11208 // If any of these registers are used inside or live across an outlined
11209 // function, then they may be modified later, either by the compiler or
11210 // some other tool (like the linker).
11211 //
11212 // To avoid outlining in these situations, partition each block into ranges
11213 // where these registers are dead. We will only outline from those ranges.
11214 LiveRegUnits LRU(getRegisterInfo());
11215 auto AreAllUnsafeRegsDead = [&LRU]() {
11216 return LRU.available(AArch64::W16) && LRU.available(AArch64::W17) &&
11217 LRU.available(AArch64::NZCV);
11218 };
11219
11220 // We need to know if LR is live across an outlining boundary later on in
11221 // order to decide how we'll create the outlined call, frame, etc.
11222 //
11223 // It's pretty expensive to check this for *every candidate* within a block.
11224 // That's some potentially n^2 behaviour, since in the worst case, we'd need
11225 // to compute liveness from the end of the block for O(n) candidates within
11226 // the block.
11227 //
11228 // So, to improve the average case, let's keep track of liveness from the end
11229 // of the block to the beginning of *every outlinable range*. If we know that
11230 // LR is available in every range we could outline from, then we know that
11231 // we don't need to check liveness for any candidate within that range.
11232 bool LRAvailableEverywhere = true;
11233 // Compute liveness bottom-up.
11234 LRU.addLiveOuts(MBB);
11235 // Update flags that require info about the entire MBB.
11236 auto UpdateWholeMBBFlags = [&Flags](const MachineInstr &MI) {
11237 if (MI.isCall() && !MI.isTerminator())
11239 };
11240 // Range: [RangeBegin, RangeEnd)
11241 MachineBasicBlock::instr_iterator RangeBegin, RangeEnd;
11242 unsigned RangeLen;
11243 auto CreateNewRangeStartingAt =
11244 [&RangeBegin, &RangeEnd,
11245 &RangeLen](MachineBasicBlock::instr_iterator NewBegin) {
11246 RangeBegin = NewBegin;
11247 RangeEnd = std::next(RangeBegin);
11248 RangeLen = 0;
11249 };
11250 auto SaveRangeIfNonEmpty = [&RangeLen, &Ranges, &RangeBegin, &RangeEnd]() {
11251 // At least one unsafe register is not dead. We do not want to outline at
11252 // this point. If it is long enough to outline from and does not cross a
11253 // bundle boundary, save the range [RangeBegin, RangeEnd).
11254 if (RangeLen <= 1)
11255 return;
11256 if (!RangeBegin.isEnd() && RangeBegin->isBundledWithPred())
11257 return;
11258 if (!RangeEnd.isEnd() && RangeEnd->isBundledWithPred())
11259 return;
11260 Ranges.emplace_back(RangeBegin, RangeEnd);
11261 };
11262 // Find the first point where all unsafe registers are dead.
11263 // FIND: <safe instr> <-- end of first potential range
11264 // SKIP: <unsafe def>
11265 // SKIP: ... everything between ...
11266 // SKIP: <unsafe use>
11267 auto FirstPossibleEndPt = MBB.instr_rbegin();
11268 for (; FirstPossibleEndPt != MBB.instr_rend(); ++FirstPossibleEndPt) {
11269 if (!FirstPossibleEndPt->isDebugInstr())
11270 LRU.stepBackward(*FirstPossibleEndPt);
11271 // Update flags that impact how we outline across the entire block,
11272 // regardless of safety.
11273 UpdateWholeMBBFlags(*FirstPossibleEndPt);
11274 if (AreAllUnsafeRegsDead())
11275 break;
11276 }
11277 // If we exhausted the entire block, we have no safe ranges to outline.
11278 if (FirstPossibleEndPt == MBB.instr_rend())
11279 return Ranges;
11280 // Current range.
11281 CreateNewRangeStartingAt(FirstPossibleEndPt->getIterator());
11282 // StartPt points to the first place where all unsafe registers
11283 // are dead (if there is any such point). Begin partitioning the MBB into
11284 // ranges.
11285 // Pseudo probes are ordinary instructions to the mapper, so only skip debug
11286 // instructions here.
11287 for (auto &MI : instructionsWithoutDebug(FirstPossibleEndPt, MBB.instr_rend(),
11288 /*SkipPseudoOp=*/false)) {
11289 LRU.stepBackward(MI);
11290 UpdateWholeMBBFlags(MI);
11291 if (!AreAllUnsafeRegsDead()) {
11292 SaveRangeIfNonEmpty();
11293 CreateNewRangeStartingAt(MI.getIterator());
11294 continue;
11295 }
11296 LRAvailableEverywhere &= LRU.available(AArch64::LR);
11297 // Pseudo probes count because the mapper treats them as ordinary
11298 // instructions.
11299 RangeBegin = MI.getIterator();
11300 ++RangeLen;
11301 }
11302 // Above loop misses the last (or only) range. If we are still safe, then
11303 // let's save the range.
11304 if (AreAllUnsafeRegsDead())
11305 SaveRangeIfNonEmpty();
11306 if (Ranges.empty())
11307 return Ranges;
11308 // We found the ranges bottom-up. Mapping expects the top-down. Reverse
11309 // the order.
11310 std::reverse(Ranges.begin(), Ranges.end());
11311 // If there is at least one outlinable range where LR is unavailable
11312 // somewhere, remember that.
11313 if (!LRAvailableEverywhere)
11315 return Ranges;
11316}
11317
11319AArch64InstrInfo::getOutliningTypeImpl(const MachineModuleInfo &MMI,
11321 unsigned Flags) const {
11322 MachineInstr &MI = *MIT;
11323
11324 // Don't outline anything used for return address signing. The outlined
11325 // function will get signed later if needed
11326 switch (MI.getOpcode()) {
11327 case AArch64::PACM:
11328 case AArch64::PACIASP:
11329 case AArch64::PACIBSP:
11330 case AArch64::PACIASPPC:
11331 case AArch64::PACIBSPPC:
11332 case AArch64::PACNBIASPPC:
11333 case AArch64::PACNBIBSPPC:
11334 case AArch64::AUTIASP:
11335 case AArch64::AUTIBSP:
11336 case AArch64::AUTIASPPCi:
11337 case AArch64::AUTIASPPCr:
11338 case AArch64::AUTIBSPPCi:
11339 case AArch64::AUTIBSPPCr:
11340 case AArch64::RETAA:
11341 case AArch64::RETAB:
11342 case AArch64::RETAASPPCi:
11343 case AArch64::RETAASPPCr:
11344 case AArch64::RETABSPPCi:
11345 case AArch64::RETABSPPCr:
11346 case AArch64::EMITBKEY:
11347 case AArch64::PAUTH_PROLOGUE:
11348 case AArch64::PAUTH_EPILOGUE:
11349 case AArch64::PAUTH_EPILOGUE_ENTRY_SP:
11351 }
11352
11353 // We can only outline these if we will tail call the outlined function, or
11354 // fix up the CFI offsets. Currently, CFI instructions are outlined only if
11355 // in a tail call.
11356 //
11357 // FIXME: If the proper fixups for the offset are implemented, this should be
11358 // possible.
11359 if (MI.isCFIInstruction())
11361
11362 // Is this a terminator for a basic block?
11363 if (MI.isTerminator())
11364 // TargetInstrInfo::getOutliningType has already filtered out anything
11365 // that would break this, so we can allow it here.
11367
11368 // Make sure none of the operands are un-outlinable.
11369 for (const MachineOperand &MOP : MI.operands()) {
11370 // A check preventing CFI indices was here before, but only CFI
11371 // instructions should have those.
11372 assert(!MOP.isCFIIndex());
11373
11374 // If it uses LR or W30 explicitly, then don't touch it.
11375 if (MOP.isReg() && !MOP.isImplicit() &&
11376 (MOP.getReg() == AArch64::LR || MOP.getReg() == AArch64::W30))
11378 }
11379
11380 // Special cases for instructions that can always be outlined, but will fail
11381 // the later tests. e.g, ADRPs, which are PC-relative use LR, but can always
11382 // be outlined because they don't require a *specific* value to be in LR.
11383 if (MI.getOpcode() == AArch64::ADRP)
11385
11386 // If MI is a call we might be able to outline it. We don't want to outline
11387 // any calls that rely on the position of items on the stack. When we outline
11388 // something containing a call, we have to emit a save and restore of LR in
11389 // the outlined function. Currently, this always happens by saving LR to the
11390 // stack. Thus, if we outline, say, half the parameters for a function call
11391 // plus the call, then we'll break the callee's expectations for the layout
11392 // of the stack.
11393 //
11394 // FIXME: Allow calls to functions which construct a stack frame, as long
11395 // as they don't access arguments on the stack.
11396 // FIXME: Figure out some way to analyze functions defined in other modules.
11397 // We should be able to compute the memory usage based on the IR calling
11398 // convention, even if we can't see the definition.
11399 if (MI.isCall()) {
11400 // Get the function associated with the call. Look at each operand and find
11401 // the one that represents the callee and get its name.
11402 const Function *Callee = nullptr;
11403 for (const MachineOperand &MOP : MI.operands()) {
11404 if (MOP.isGlobal()) {
11405 Callee = dyn_cast<Function>(MOP.getGlobal());
11406 break;
11407 }
11408 }
11409
11410 // Never outline calls to mcount. There isn't any rule that would require
11411 // this, but the Linux kernel's "ftrace" feature depends on it.
11412 if (Callee && Callee->getName() == "\01_mcount")
11414
11415 // If we don't know anything about the callee, assume it depends on the
11416 // stack layout of the caller. In that case, it's only legal to outline
11417 // as a tail-call. Explicitly list the call instructions we know about so we
11418 // don't get unexpected results with call pseudo-instructions.
11419 auto UnknownCallOutlineType = outliner::InstrType::Illegal;
11420 if (MI.getOpcode() == AArch64::BLR ||
11421 MI.getOpcode() == AArch64::BLRNoIP || MI.getOpcode() == AArch64::BL)
11422 UnknownCallOutlineType = outliner::InstrType::LegalTerminator;
11423
11424 if (!Callee)
11425 return UnknownCallOutlineType;
11426
11427 // We have a function we have information about. Check it if it's something
11428 // can safely outline.
11429 MachineFunction *CalleeMF = MMI.getMachineFunction(*Callee);
11430
11431 // We don't know what's going on with the callee at all. Don't touch it.
11432 if (!CalleeMF)
11433 return UnknownCallOutlineType;
11434
11435 // Check if we know anything about the callee saves on the function. If we
11436 // don't, then don't touch it, since that implies that we haven't
11437 // computed anything about its stack frame yet.
11438 MachineFrameInfo &MFI = CalleeMF->getFrameInfo();
11439 if (!MFI.isCalleeSavedInfoValid() || MFI.getStackSize() > 0 ||
11440 MFI.getNumObjects() > 0)
11441 return UnknownCallOutlineType;
11442
11443 // At this point, we can say that CalleeMF ought to not pass anything on the
11444 // stack. Therefore, we can outline it.
11446 }
11447
11448 // Don't touch the link register or W30.
11449 if (MI.readsRegister(AArch64::W30, &getRegisterInfo()) ||
11450 MI.modifiesRegister(AArch64::W30, &getRegisterInfo()))
11452
11453 // Don't outline BTI instructions, because that will prevent the outlining
11454 // site from being indirectly callable.
11455 if (hasBTISemantics(MI))
11457
11459}
11460
11461void AArch64InstrInfo::fixupPostOutline(MachineBasicBlock &MBB) const {
11462 for (MachineInstr &MI : MBB) {
11463 const MachineOperand *Base;
11464 TypeSize Width(0, false);
11465 int64_t Offset;
11466 bool OffsetIsScalable;
11467
11468 // Is this a load or store with an immediate offset with SP as the base?
11469 if (MI.mayLoadOrStore() &&
11470 getMemOperandWithOffsetWidth(MI, Base, Offset, OffsetIsScalable,
11471 Width) &&
11472 Base->isReg() && Base->getReg() == AArch64::SP) {
11473 TypeSize Scale(0U, false);
11474 int64_t Dummy1, Dummy2;
11475
11476 MachineOperand &StackOffsetOperand =
11478 assert(StackOffsetOperand.isImm() && "Stack offset wasn't immediate!");
11479 getMemOpInfo(MI.getOpcode(), Scale, Width, Dummy1, Dummy2);
11480 assert(Scale != 0 && "Unexpected opcode!");
11481 assert(!OffsetIsScalable && "Expected offset to be a byte offset");
11482
11483 // We've pushed the return address to the stack, so add 16 to the offset.
11484 // This is safe, since we already checked if it would overflow when we
11485 // checked if this instruction was legal to outline.
11486 int64_t NewImm = (Offset + 16) / (int64_t)Scale.getFixedValue();
11487 StackOffsetOperand.setImm(NewImm);
11488 continue;
11489 }
11490
11491 if (isSPAddSubImm(MI)) {
11492 auto Enc = adjustSPAddSubImm(MI, 16);
11493 assert(Enc && "Unencodable SP add/sub should not have been outlined");
11494 MI.setDesc(get(Enc->Opcode));
11495 MI.getOperand(2).setImm(Enc->Imm);
11496 MI.getOperand(3).setImm(Enc->Shift);
11497 }
11498 }
11499}
11500
11502 const AArch64InstrInfo *TII,
11503 bool ShouldSignReturnAddr) {
11504 if (!ShouldSignReturnAddr)
11505 return;
11506
11507 BuildMI(MBB, MBB.begin(), DebugLoc(), TII->get(AArch64::PAUTH_PROLOGUE))
11509 TII->createPauthEpilogueInstr(MBB, DebugLoc());
11510}
11511
11512void AArch64InstrInfo::buildOutlinedFrame(
11514 const outliner::OutlinedFunction &OF) const {
11515
11516 AArch64FunctionInfo *FI = MF.getInfo<AArch64FunctionInfo>();
11517
11518 if (OF.FrameConstructionID == MachineOutlinerTailCall)
11519 FI->setOutliningStyle("Tail Call");
11520 else if (OF.FrameConstructionID == MachineOutlinerThunk) {
11521 // For thunk outlining, rewrite the last instruction from a call to a
11522 // tail-call.
11523 MachineInstr *Call = &*--MBB.instr_end();
11524 unsigned TailOpcode;
11525 if (Call->getOpcode() == AArch64::BL) {
11526 TailOpcode = AArch64::TCRETURNdi;
11527 } else {
11528 assert(Call->getOpcode() == AArch64::BLR ||
11529 Call->getOpcode() == AArch64::BLRNoIP);
11530 TailOpcode = AArch64::TCRETURNriALL;
11531 }
11532 MachineInstr *TC = BuildMI(MF, DebugLoc(), get(TailOpcode))
11533 .add(Call->getOperand(0))
11534 .addImm(0);
11535 MBB.insert(MBB.end(), TC);
11537
11538 FI->setOutliningStyle("Thunk");
11539 }
11540
11541 bool IsLeafFunction = true;
11542
11543 // Is there a call in the outlined range?
11544 auto IsNonTailCall = [](const MachineInstr &MI) {
11545 return MI.isCall() && !MI.isReturn();
11546 };
11547
11548 if (llvm::any_of(MBB.instrs(), IsNonTailCall)) {
11549 // Fix up the instructions in the range, since we're going to modify the
11550 // stack.
11551
11552 // Bugzilla ID: 46767
11553 // TODO: Check if fixing up twice is safe so we can outline these.
11554 assert(OF.FrameConstructionID != MachineOutlinerDefault &&
11555 "Can only fix up stack references once");
11556 fixupPostOutline(MBB);
11557
11558 IsLeafFunction = false;
11559
11560 // LR has to be a live in so that we can save it.
11561 if (!MBB.isLiveIn(AArch64::LR))
11562 MBB.addLiveIn(AArch64::LR);
11563
11566
11567 if (OF.FrameConstructionID == MachineOutlinerTailCall ||
11568 OF.FrameConstructionID == MachineOutlinerThunk)
11569 Et = std::prev(MBB.end());
11570
11571 // There is a call in the range, so we must save LR. Save it as part of a
11572 // frame record when that gives us a smaller compact unwind encoding.
11574 // FP is saved here, so it must be live-in.
11575 if (!MBB.isLiveIn(AArch64::FP))
11576 MBB.addLiveIn(AArch64::FP);
11577
11578 // stp x29, x30, [sp, #-16]! (the pre-index imm is scaled by 8: -2 * 8)
11579 MachineInstr *STPXpre = BuildMI(MF, DebugLoc(), get(AArch64::STPXpre))
11580 .addReg(AArch64::SP, RegState::Define)
11581 .addReg(AArch64::FP)
11582 .addReg(AArch64::LR)
11583 .addReg(AArch64::SP)
11584 .addImm(-2);
11585 It = MBB.insert(It, STPXpre);
11586
11587 // mov x29, sp (add x29, sp, #0), so x29 points at the frame record.
11588 MachineInstr *SetFP = BuildMI(MF, DebugLoc(), get(AArch64::ADDXri))
11589 .addReg(AArch64::FP, RegState::Define)
11590 .addReg(AArch64::SP)
11591 .addImm(0)
11592 .addImm(0);
11593 MBB.insertAfter(It, SetFP);
11594
11595 // Describe the frame record with FP as the CFA. The encoder needs all
11596 // three to pick FRAME. No need to check for unwind info here: we only
11597 // get here if the function has it.
11598 CFIInstBuilder CFIBuilder(MBB, std::next(SetFP->getIterator()),
11600 CFIBuilder.buildDefCFA(AArch64::FP, 16);
11601 CFIBuilder.buildOffset(AArch64::LR, -8);
11602 CFIBuilder.buildOffset(AArch64::FP, -16);
11603
11604 // ldp x29, x30, [sp], #16
11605 MachineInstr *LDPXpost = BuildMI(MF, DebugLoc(), get(AArch64::LDPXpost))
11606 .addReg(AArch64::SP, RegState::Define)
11607 .addReg(AArch64::FP, RegState::Define)
11608 .addReg(AArch64::LR, RegState::Define)
11609 .addReg(AArch64::SP)
11610 .addImm(2);
11611 Et = MBB.insert(Et, LDPXpost);
11612 } else {
11613 // Insert a save before the outlined region
11614 MachineInstr *STRXpre = BuildMI(MF, DebugLoc(), get(AArch64::STRXpre))
11615 .addReg(AArch64::SP, RegState::Define)
11616 .addReg(AArch64::LR)
11617 .addReg(AArch64::SP)
11618 .addImm(-16);
11619 It = MBB.insert(It, STRXpre);
11620
11621 if (MF.getInfo<AArch64FunctionInfo>()->needsDwarfUnwindInfo(MF)) {
11622 CFIInstBuilder CFIBuilder(MBB, It, MachineInstr::FrameSetup);
11623
11624 // Add a CFI saying the stack was moved 16 B down.
11625 CFIBuilder.buildDefCFAOffset(16);
11626
11627 // Add a CFI saying that the LR that we want to find is now 16 B higher
11628 // than before.
11629 CFIBuilder.buildOffset(AArch64::LR, -16);
11630 }
11631
11632 // Insert a restore before the terminator for the function.
11633 MachineInstr *LDRXpost = BuildMI(MF, DebugLoc(), get(AArch64::LDRXpost))
11634 .addReg(AArch64::SP, RegState::Define)
11635 .addReg(AArch64::LR, RegState::Define)
11636 .addReg(AArch64::SP)
11637 .addImm(16);
11638 Et = MBB.insert(Et, LDRXpost);
11639 }
11640 }
11641
11642 auto RASignCondition = FI->getSignReturnAddressCondition();
11643 bool ShouldSignReturnAddr = AArch64FunctionInfo::shouldSignReturnAddress(
11644 RASignCondition, !IsLeafFunction);
11645
11646 // If this is a tail call outlined function, then there's already a return.
11647 if (OF.FrameConstructionID == MachineOutlinerTailCall ||
11648 OF.FrameConstructionID == MachineOutlinerThunk) {
11649 signOutlinedFunction(MF, MBB, this, ShouldSignReturnAddr);
11650 return;
11651 }
11652
11653 // It's not a tail call, so we have to insert the return ourselves.
11654
11655 // LR has to be a live in so that we can return to it.
11656 if (!MBB.isLiveIn(AArch64::LR))
11657 MBB.addLiveIn(AArch64::LR);
11658
11659 MachineInstr *ret = BuildMI(MF, DebugLoc(), get(AArch64::RET))
11660 .addReg(AArch64::LR);
11661 MBB.insert(MBB.end(), ret);
11662
11663 signOutlinedFunction(MF, MBB, this, ShouldSignReturnAddr);
11664
11665 FI->setOutliningStyle("Function");
11666
11667 // Did we have to modify the stack by saving the link register?
11668 if (OF.FrameConstructionID != MachineOutlinerDefault)
11669 return;
11670
11671 // We modified the stack.
11672 // Walk over the basic block and fix up all the stack accesses.
11673 fixupPostOutline(MBB);
11674}
11675
11676MachineBasicBlock::iterator AArch64InstrInfo::insertOutlinedCall(
11679
11680 // Are we tail calling?
11681 if (C.CallConstructionID == MachineOutlinerTailCall) {
11682 // If yes, then we can just branch to the label.
11683 It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::TCRETURNdi))
11684 .addGlobalAddress(M.getNamedValue(MF.getName()))
11685 .addImm(0));
11686 return It;
11687 }
11688
11689 // Are we saving the link register?
11690 if (C.CallConstructionID == MachineOutlinerNoLRSave ||
11691 C.CallConstructionID == MachineOutlinerThunk) {
11692 // No, so just insert the call.
11693 It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::BL))
11694 .addGlobalAddress(M.getNamedValue(MF.getName())));
11695 return It;
11696 }
11697
11698 // We want to return the spot where we inserted the call.
11700
11701 // Instructions for saving and restoring LR around the call instruction we're
11702 // going to insert.
11703 MachineInstr *Save;
11704 MachineInstr *Restore;
11705 // Can we save to a register?
11706 if (C.CallConstructionID == MachineOutlinerRegSave) {
11707 // FIXME: This logic should be sunk into a target-specific interface so that
11708 // we don't have to recompute the register.
11709 Register Reg = findRegisterToSaveLRTo(C);
11710 assert(Reg && "No callee-saved register available?");
11711
11712 // LR has to be a live in so that we can save it.
11713 if (!MBB.isLiveIn(AArch64::LR))
11714 MBB.addLiveIn(AArch64::LR);
11715
11716 // Save and restore LR from Reg.
11717 Save = BuildMI(MF, DebugLoc(), get(AArch64::ORRXrs), Reg)
11718 .addReg(AArch64::XZR)
11719 .addReg(AArch64::LR)
11720 .addImm(0);
11721 Restore = BuildMI(MF, DebugLoc(), get(AArch64::ORRXrs), AArch64::LR)
11722 .addReg(AArch64::XZR)
11723 .addReg(Reg)
11724 .addImm(0);
11725 } else {
11726 // We have the default case. Save and restore from SP.
11727 Save = BuildMI(MF, DebugLoc(), get(AArch64::STRXpre))
11728 .addReg(AArch64::SP, RegState::Define)
11729 .addReg(AArch64::LR)
11730 .addReg(AArch64::SP)
11731 .addImm(-16);
11732 Restore = BuildMI(MF, DebugLoc(), get(AArch64::LDRXpost))
11733 .addReg(AArch64::SP, RegState::Define)
11734 .addReg(AArch64::LR, RegState::Define)
11735 .addReg(AArch64::SP)
11736 .addImm(16);
11737 }
11738
11739 It = MBB.insert(It, Save);
11740 It++;
11741
11742 // Insert the call.
11743 It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::BL))
11744 .addGlobalAddress(M.getNamedValue(MF.getName())));
11745 CallPt = It;
11746 It++;
11747
11748 It = MBB.insert(It, Restore);
11749 return CallPt;
11750}
11751
11752bool AArch64InstrInfo::shouldOutlineFromFunctionByDefault(
11753 MachineFunction &MF) const {
11754 return MF.getFunction().hasMinSize();
11755}
11756
11757void AArch64InstrInfo::buildClearRegister(Register Reg, MachineBasicBlock &MBB,
11759 DebugLoc &DL,
11760 bool AllowSideEffects) const {
11761 const MachineFunction &MF = *MBB.getParent();
11762 const AArch64Subtarget &STI = MF.getSubtarget<AArch64Subtarget>();
11763 const AArch64RegisterInfo &TRI = *STI.getRegisterInfo();
11764
11765 if (TRI.isGeneralPurposeRegister(MF, Reg)) {
11766 BuildMI(MBB, Iter, DL, get(AArch64::MOVZXi), Reg).addImm(0).addImm(0);
11767 } else if (STI.isSVEorStreamingSVEAvailable()) {
11768 BuildMI(MBB, Iter, DL, get(AArch64::DUP_ZI_D), Reg)
11769 .addImm(0)
11770 .addImm(0);
11771 } else if (STI.isNeonAvailable()) {
11772 BuildMI(MBB, Iter, DL, get(AArch64::MOVIv2d_ns), Reg)
11773 .addImm(0);
11774 } else {
11775 // No Advanced SIMD (streaming-compatible without SVE, or +nosimd), so use
11776 // `fmov d...` instead of `movi v...`; writing `d` also clears the upper
11777 // 64 bits.
11778 assert(STI.hasFPARMv8() && "Expected FP to be available.");
11779 Register Reg64 = TRI.getSubReg(Reg, AArch64::dsub);
11780 BuildMI(MBB, Iter, DL, get(AArch64::FMOVD0), Reg64);
11781 }
11782}
11783
11784std::optional<DestSourcePair>
11786
11787 // AArch64::ORRWrs and AArch64::ORRXrs with WZR/XZR reg
11788 // and zero immediate operands used as an alias for mov instruction.
11789 if ((MI.getOpcode() == AArch64::ORRWrs &&
11790 MI.getOperand(1).getReg() == AArch64::WZR &&
11791 MI.getOperand(3).getImm() == 0x0) ||
11792 (MI.getOpcode() == AArch64::ORRWrr &&
11793 MI.getOperand(1).getReg() == AArch64::WZR)) {
11794 // Check that the w->w move is not a zero-extending w->x mov.
11795 if ((MI.getOperand(0).getReg().isPhysical() &&
11796 MI.findRegisterDefOperandIdx(
11797 getXRegFromWReg(MI.getOperand(0).getReg()),
11798 /*TRI=*/nullptr) == -1) ||
11799 (MI.getOperand(0).getReg().isVirtual() &&
11800 !MI.getOperand(0).getSubReg()))
11801 return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
11802 }
11803
11804 if (MI.getOpcode() == AArch64::ORRXrs &&
11805 MI.getOperand(1).getReg() == AArch64::XZR &&
11806 MI.getOperand(3).getImm() == 0x0)
11807 return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
11808
11809 return std::nullopt;
11810}
11811
11812std::optional<DestSourcePair>
11814 if ((MI.getOpcode() == AArch64::ORRWrs &&
11815 MI.getOperand(1).getReg() == AArch64::WZR &&
11816 MI.getOperand(3).getImm() == 0x0) ||
11817 (MI.getOpcode() == AArch64::ORRWrr &&
11818 MI.getOperand(1).getReg() == AArch64::WZR))
11819 return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
11820 return std::nullopt;
11821}
11822
11823std::optional<RegImmPair>
11824AArch64InstrInfo::isAddImmediate(const MachineInstr &MI, Register Reg) const {
11825 int Sign = 1;
11826 int64_t Offset = 0;
11827
11828 // TODO: Handle cases where Reg is a super- or sub-register of the
11829 // destination register.
11830 const MachineOperand &Op0 = MI.getOperand(0);
11831 if (!Op0.isReg() || Reg != Op0.getReg())
11832 return std::nullopt;
11833
11834 switch (MI.getOpcode()) {
11835 default:
11836 return std::nullopt;
11837 case AArch64::SUBWri:
11838 case AArch64::SUBXri:
11839 case AArch64::SUBSWri:
11840 case AArch64::SUBSXri:
11841 Sign *= -1;
11842 [[fallthrough]];
11843 case AArch64::ADDSWri:
11844 case AArch64::ADDSXri:
11845 case AArch64::ADDWri:
11846 case AArch64::ADDXri: {
11847 // TODO: Third operand can be global address (usually some string).
11848 if (!MI.getOperand(0).isReg() || !MI.getOperand(1).isReg() ||
11849 !MI.getOperand(2).isImm())
11850 return std::nullopt;
11851 int Shift = MI.getOperand(3).getImm();
11852 assert((Shift == 0 || Shift == 12) && "Shift can be either 0 or 12");
11853 Offset = Sign * (MI.getOperand(2).getImm() << Shift);
11854 }
11855 }
11856 return RegImmPair{MI.getOperand(1).getReg(), Offset};
11857}
11858
11859/// If the given ORR instruction is a copy, and \p DescribedReg overlaps with
11860/// the destination register then, if possible, describe the value in terms of
11861/// the source register.
11862static std::optional<ParamLoadedValue>
11864 const TargetInstrInfo *TII,
11865 const TargetRegisterInfo *TRI) {
11866 auto DestSrc = TII->isCopyLikeInstr(MI);
11867 if (!DestSrc)
11868 return std::nullopt;
11869
11870 Register DestReg = DestSrc->Destination->getReg();
11871 Register SrcReg = DestSrc->Source->getReg();
11872
11873 if (!DestReg.isValid() || !SrcReg.isValid())
11874 return std::nullopt;
11875
11876 auto Expr = DIExpression::get(MI.getMF()->getFunction().getContext(), {});
11877
11878 // If the described register is the destination, just return the source.
11879 if (DestReg == DescribedReg)
11880 return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
11881
11882 // ORRWrs zero-extends to 64-bits, so we need to consider such cases.
11883 if (MI.getOpcode() == AArch64::ORRWrs &&
11884 TRI->isSuperRegister(DestReg, DescribedReg))
11885 return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
11886
11887 // We may need to describe the lower part of a ORRXrs move.
11888 if (MI.getOpcode() == AArch64::ORRXrs &&
11889 TRI->isSubRegister(DestReg, DescribedReg)) {
11890 Register SrcSubReg = TRI->getSubReg(SrcReg, AArch64::sub_32);
11891 return ParamLoadedValue(MachineOperand::CreateReg(SrcSubReg, false), Expr);
11892 }
11893
11894 assert(!TRI->isSuperOrSubRegisterEq(DestReg, DescribedReg) &&
11895 "Unhandled ORR[XW]rs copy case");
11896
11897 return std::nullopt;
11898}
11899
11900bool AArch64InstrInfo::isFunctionSafeToSplit(const MachineFunction &MF) const {
11901 // Functions cannot be split to different sections on AArch64 if they have
11902 // a red zone. This is because relaxing a cross-section branch may require
11903 // incrementing the stack pointer to spill a register, which would overwrite
11904 // the red zone.
11905 if (MF.getInfo<AArch64FunctionInfo>()->hasRedZone().value_or(true))
11906 return false;
11907
11909}
11910
11911bool AArch64InstrInfo::isMBBSafeToSplitToCold(
11912 const MachineBasicBlock &MBB) const {
11913 // Asm Goto blocks can contain conditional branches to goto labels, which can
11914 // get moved out of range of the branch instruction.
11915 auto isAsmGoto = [](const MachineInstr &MI) {
11916 return MI.getOpcode() == AArch64::INLINEASM_BR;
11917 };
11918 if (llvm::any_of(MBB, isAsmGoto) || MBB.isInlineAsmBrIndirectTarget())
11919 return false;
11920
11921 // Because jump tables are label-relative instead of table-relative, they all
11922 // must be in the same section or relocation fixup handling will fail.
11923
11924 // Check if MBB is a jump table target
11925 const MachineJumpTableInfo *MJTI = MBB.getParent()->getJumpTableInfo();
11926 auto containsMBB = [&MBB](const MachineJumpTableEntry &JTE) {
11927 return llvm::is_contained(JTE.MBBs, &MBB);
11928 };
11929 if (MJTI != nullptr && llvm::any_of(MJTI->getJumpTables(), containsMBB))
11930 return false;
11931
11932 // Check if MBB contains a jump table lookup
11933 for (const MachineInstr &MI : MBB) {
11934 switch (MI.getOpcode()) {
11935 case TargetOpcode::G_BRJT:
11936 case AArch64::JumpTableDest32:
11937 case AArch64::JumpTableDest16:
11938 case AArch64::JumpTableDest8:
11939 return false;
11940 default:
11941 continue;
11942 }
11943 }
11944
11945 // MBB isn't a special case, so it's safe to be split to the cold section.
11946 return true;
11947}
11948
11949std::optional<ParamLoadedValue>
11950AArch64InstrInfo::describeLoadedValue(const MachineInstr &MI,
11951 Register Reg) const {
11952 const MachineFunction *MF = MI.getMF();
11953 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
11954 switch (MI.getOpcode()) {
11955 case AArch64::MOVZWi:
11956 case AArch64::MOVZXi: {
11957 // MOVZWi may be used for producing zero-extended 32-bit immediates in
11958 // 64-bit parameters, so we need to consider super-registers.
11959 if (!TRI->isSuperRegisterEq(MI.getOperand(0).getReg(), Reg))
11960 return std::nullopt;
11961
11962 if (!MI.getOperand(1).isImm())
11963 return std::nullopt;
11964 int64_t Immediate = MI.getOperand(1).getImm();
11965 int Shift = MI.getOperand(2).getImm();
11966 return ParamLoadedValue(MachineOperand::CreateImm(Immediate << Shift),
11967 nullptr);
11968 }
11969 case AArch64::ORRWrs:
11970 case AArch64::ORRXrs:
11971 return describeORRLoadedValue(MI, Reg, this, TRI);
11972 }
11973
11975}
11976
11977bool AArch64InstrInfo::isExtendLikelyToBeFolded(
11978 MachineInstr &ExtMI, MachineRegisterInfo &MRI) const {
11979 assert(ExtMI.getOpcode() == TargetOpcode::G_SEXT ||
11980 ExtMI.getOpcode() == TargetOpcode::G_ZEXT ||
11981 ExtMI.getOpcode() == TargetOpcode::G_ANYEXT);
11982
11983 // Anyexts are nops.
11984 if (ExtMI.getOpcode() == TargetOpcode::G_ANYEXT)
11985 return true;
11986
11987 Register DefReg = ExtMI.getOperand(0).getReg();
11988 if (!MRI.hasOneNonDBGUse(DefReg))
11989 return false;
11990
11991 // It's likely that a sext/zext as a G_PTR_ADD offset will be folded into an
11992 // addressing mode.
11993 auto *UserMI = &*MRI.use_instr_nodbg_begin(DefReg);
11994 return UserMI->getOpcode() == TargetOpcode::G_PTR_ADD;
11995}
11996
11997uint64_t AArch64InstrInfo::getElementSizeForOpcode(unsigned Opc) const {
11998 return get(Opc).TSFlags & AArch64::ElementSizeMask;
11999}
12000
12001bool AArch64InstrInfo::isPTestLikeOpcode(unsigned Opc) const {
12002 return get(Opc).TSFlags & AArch64::InstrFlagIsPTestLike;
12003}
12004
12005bool AArch64InstrInfo::isWhileOpcode(unsigned Opc) const {
12006 return get(Opc).TSFlags & AArch64::InstrFlagIsWhile;
12007}
12008
12009unsigned int
12010AArch64InstrInfo::getTailDuplicateSize(CodeGenOptLevel OptLevel) const {
12011 return OptLevel >= CodeGenOptLevel::Aggressive ? 6 : 2;
12012}
12013
12014bool AArch64InstrInfo::isLegalAddressingMode(unsigned NumBytes, int64_t Offset,
12015 unsigned Scale) const {
12016 if (Offset && Scale)
12017 return false;
12018
12019 // Check Reg + Imm
12020 if (!Scale) {
12021 // 9-bit signed offset
12022 if (isInt<9>(Offset))
12023 return true;
12024
12025 // 12-bit unsigned offset
12026 unsigned Shift = Log2_64(NumBytes);
12027 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
12028 // Must be a multiple of NumBytes (NumBytes is a power of 2)
12029 (Offset >> Shift) << Shift == Offset)
12030 return true;
12031 return false;
12032 }
12033
12034 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
12035 return Scale == 1 || (Scale > 0 && Scale == NumBytes);
12036}
12037
12039 if (MF.getSubtarget<AArch64Subtarget>().hardenSlsBlr())
12040 return AArch64::BLRNoIP;
12041 else
12042 return AArch64::BLR;
12043}
12044
12046 DebugLoc DL) const {
12047 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
12048 auto Builder = BuildMI(MBB, InsertPt, DL, get(AArch64::PAUTH_EPILOGUE))
12050
12051 MachineFunction &MF = *MBB.getParent();
12052 const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
12053 auto &AFL = *static_cast<const AArch64FrameLowering *>(
12054 MF.getSubtarget().getFrameLowering());
12055 if (AFL.getArgumentStackToRestore(MF, MBB)) {
12056 Builder.addReg(AArch64::X17, RegState::ImplicitDefine);
12057 Builder.addReg(AArch64::X16, RegState::ImplicitDefine);
12058 if (AFI->branchProtectionPAuthLR())
12059 Builder.addReg(AArch64::X15, RegState::ImplicitDefine);
12060 return;
12061 }
12062
12063 if (AFI->branchProtectionPAuthLR() && !Subtarget.hasPAuthLR())
12064 Builder.addReg(AArch64::X16, RegState::ImplicitDefine);
12065}
12066
12068AArch64InstrInfo::probedStackAlloc(MachineBasicBlock::iterator MBBI,
12069 Register TargetReg, bool FrameSetup) const {
12070 assert(TargetReg != AArch64::SP && "New top of stack cannot already be in SP");
12071
12072 MachineBasicBlock &MBB = *MBBI->getParent();
12073 MachineFunction &MF = *MBB.getParent();
12074 const AArch64InstrInfo *TII =
12075 MF.getSubtarget<AArch64Subtarget>().getInstrInfo();
12076 int64_t ProbeSize = MF.getInfo<AArch64FunctionInfo>()->getStackProbeSize();
12077 DebugLoc DL = MBB.findDebugLoc(MBBI);
12078
12079 MachineFunction::iterator MBBInsertPoint = std::next(MBB.getIterator());
12080 MachineBasicBlock *LoopTestMBB =
12081 MF.CreateMachineBasicBlock(MBB.getBasicBlock());
12082 MF.insert(MBBInsertPoint, LoopTestMBB);
12083 MachineBasicBlock *LoopBodyMBB =
12084 MF.CreateMachineBasicBlock(MBB.getBasicBlock());
12085 MF.insert(MBBInsertPoint, LoopBodyMBB);
12086 MachineBasicBlock *ExitMBB = MF.CreateMachineBasicBlock(MBB.getBasicBlock());
12087 MF.insert(MBBInsertPoint, ExitMBB);
12088 MachineInstr::MIFlag Flags =
12090
12091 // LoopTest:
12092 // SUB SP, SP, #ProbeSize
12093 emitFrameOffset(*LoopTestMBB, LoopTestMBB->end(), DL, AArch64::SP,
12094 AArch64::SP, StackOffset::getFixed(-ProbeSize), TII, Flags);
12095
12096 // CMP SP, TargetReg
12097 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(AArch64::SUBSXrx64),
12098 AArch64::XZR)
12099 .addReg(AArch64::SP)
12100 .addReg(TargetReg)
12102 .setMIFlags(Flags);
12103
12104 // B.<Cond> LoopExit
12105 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(AArch64::Bcc))
12107 .addMBB(ExitMBB)
12108 .setMIFlags(Flags);
12109
12110 // LDR XZR, [SP]
12111 BuildMI(*LoopBodyMBB, LoopBodyMBB->end(), DL, TII->get(AArch64::LDRXui))
12112 .addDef(AArch64::XZR)
12113 .addReg(AArch64::SP)
12114 .addImm(0)
12118 Align(8)))
12119 .setMIFlags(Flags);
12120
12121 // B loop
12122 BuildMI(*LoopBodyMBB, LoopBodyMBB->end(), DL, TII->get(AArch64::B))
12123 .addMBB(LoopTestMBB)
12124 .setMIFlags(Flags);
12125
12126 // LoopExit:
12127 // MOV SP, TargetReg
12128 BuildMI(*ExitMBB, ExitMBB->end(), DL, TII->get(AArch64::ADDXri), AArch64::SP)
12129 .addReg(TargetReg)
12130 .addImm(0)
12132 .setMIFlags(Flags);
12133
12134 // LDR XZR, [SP]
12135 BuildMI(*ExitMBB, ExitMBB->end(), DL, TII->get(AArch64::LDRXui))
12136 .addReg(AArch64::XZR, RegState::Define)
12137 .addReg(AArch64::SP)
12138 .addImm(0)
12139 .setMIFlags(Flags);
12140
12141 ExitMBB->splice(ExitMBB->end(), &MBB, std::next(MBBI), MBB.end());
12143
12144 LoopTestMBB->addSuccessor(ExitMBB);
12145 LoopTestMBB->addSuccessor(LoopBodyMBB);
12146 LoopBodyMBB->addSuccessor(LoopTestMBB);
12147 MBB.addSuccessor(LoopTestMBB);
12148
12149 // Update liveins.
12150 if (MF.getRegInfo().reservedRegsFrozen())
12151 fullyRecomputeLiveIns({ExitMBB, LoopBodyMBB, LoopTestMBB});
12152
12153 return ExitMBB->begin();
12154}
12155
12156namespace {
12157class AArch64PipelinerLoopInfo : public TargetInstrInfo::PipelinerLoopInfo {
12158 MachineFunction *MF;
12159 const TargetInstrInfo *TII;
12160 const TargetRegisterInfo *TRI;
12161 MachineRegisterInfo &MRI;
12162
12163 /// The block of the loop
12164 MachineBasicBlock *LoopBB;
12165 /// The conditional branch of the loop
12166 MachineInstr *CondBranch;
12167 /// The compare instruction for loop control
12168 MachineInstr *Comp;
12169 /// The number of the operand of the loop counter value in Comp
12170 unsigned CompCounterOprNum;
12171 /// The instruction that updates the loop counter value
12172 MachineInstr *Update;
12173 /// The number of the operand of the loop counter value in Update
12174 unsigned UpdateCounterOprNum;
12175 /// The initial value of the loop counter
12176 Register Init;
12177 /// True iff Update is a predecessor of Comp
12178 bool IsUpdatePriorComp;
12179
12180 /// The normalized condition used by createTripCountGreaterCondition()
12181 SmallVector<MachineOperand, 4> Cond;
12182
12183public:
12184 AArch64PipelinerLoopInfo(MachineBasicBlock *LoopBB, MachineInstr *CondBranch,
12185 MachineInstr *Comp, unsigned CompCounterOprNum,
12186 MachineInstr *Update, unsigned UpdateCounterOprNum,
12187 Register Init, bool IsUpdatePriorComp,
12188 const SmallVectorImpl<MachineOperand> &Cond)
12189 : MF(Comp->getParent()->getParent()),
12190 TII(MF->getSubtarget().getInstrInfo()),
12191 TRI(MF->getSubtarget().getRegisterInfo()), MRI(MF->getRegInfo()),
12192 LoopBB(LoopBB), CondBranch(CondBranch), Comp(Comp),
12193 CompCounterOprNum(CompCounterOprNum), Update(Update),
12194 UpdateCounterOprNum(UpdateCounterOprNum), Init(Init),
12195 IsUpdatePriorComp(IsUpdatePriorComp), Cond(Cond.begin(), Cond.end()) {}
12196
12197 bool shouldIgnoreForPipelining(const MachineInstr *MI) const override {
12198 // Make the instructions for loop control be placed in stage 0.
12199 // The predecessors of Comp are considered by the caller.
12200 return MI == Comp;
12201 }
12202
12203 std::optional<bool> createTripCountGreaterCondition(
12204 int TC, MachineBasicBlock &MBB,
12205 SmallVectorImpl<MachineOperand> &CondParam) override {
12206 // A branch instruction will be inserted as "if (Cond) goto epilogue".
12207 // Cond is normalized for such use.
12208 // The predecessors of the branch are assumed to have already been inserted.
12209 CondParam = Cond;
12210 return {};
12211 }
12212
12213 void createRemainingIterationsGreaterCondition(
12214 int TC, MachineBasicBlock &MBB, SmallVectorImpl<MachineOperand> &Cond,
12215 DenseMap<MachineInstr *, MachineInstr *> &LastStage0Insts) override;
12216
12217 void setPreheader(MachineBasicBlock *NewPreheader) override {}
12218
12219 void adjustTripCount(int TripCountAdjust) override {}
12220
12221 bool isMVEExpanderSupported() override { return true; }
12222};
12223} // namespace
12224
12225/// Clone an instruction from MI. The register of ReplaceOprNum-th operand
12226/// is replaced by ReplaceReg. The output register is newly created.
12227/// The other operands are unchanged from MI.
12228static Register cloneInstr(const MachineInstr *MI, unsigned ReplaceOprNum,
12229 Register ReplaceReg, MachineBasicBlock &MBB,
12230 MachineBasicBlock::iterator InsertTo) {
12231 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
12232 const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
12233 MachineInstr *NewMI = MBB.getParent()->CloneMachineInstr(MI);
12234 Register Result = 0;
12235 for (unsigned I = 0; I < NewMI->getNumOperands(); ++I) {
12236 if (I == 0 && NewMI->getOperand(0).getReg().isVirtual()) {
12237 Result = MRI.createVirtualRegister(
12238 MRI.getRegClass(NewMI->getOperand(0).getReg()));
12239 NewMI->getOperand(I).setReg(Result);
12240 } else if (I == ReplaceOprNum) {
12241 MRI.constrainRegClass(ReplaceReg, TII->getRegClass(NewMI->getDesc(), I));
12242 NewMI->getOperand(I).setReg(ReplaceReg);
12243 }
12244 }
12245 MBB.insert(InsertTo, NewMI);
12246 return Result;
12247}
12248
12249void AArch64PipelinerLoopInfo::createRemainingIterationsGreaterCondition(
12252 // Create and accumulate conditions for next TC iterations.
12253 // Example:
12254 // SUBSXrr N, counter, implicit-def $nzcv # compare instruction for the last
12255 // # iteration of the kernel
12256 //
12257 // # insert the following instructions
12258 // cond = CSINCXr 0, 0, C, implicit $nzcv
12259 // counter = ADDXri counter, 1 # clone from this->Update
12260 // SUBSXrr n, counter, implicit-def $nzcv # clone from this->Comp
12261 // cond = CSINCXr cond, cond, C, implicit $nzcv
12262 // ... (repeat TC times)
12263 // SUBSXri cond, 0, implicit-def $nzcv
12264
12265 assert(CondBranch->getOpcode() == AArch64::Bcc);
12266 // CondCode to exit the loop
12268 (AArch64CC::CondCode)CondBranch->getOperand(0).getImm();
12269 if (CondBranch->getOperand(1).getMBB() == LoopBB)
12271
12272 // Accumulate conditions to exit the loop
12273 Register AccCond = AArch64::XZR;
12274
12275 // If CC holds, CurCond+1 is returned; otherwise CurCond is returned.
12276 auto AccumulateCond = [&](Register CurCond,
12278 Register NewCond = MRI.createVirtualRegister(&AArch64::GPR64commonRegClass);
12279 BuildMI(MBB, MBB.end(), Comp->getDebugLoc(), TII->get(AArch64::CSINCXr))
12280 .addReg(NewCond, RegState::Define)
12281 .addReg(CurCond)
12282 .addReg(CurCond)
12284 return NewCond;
12285 };
12286
12287 if (!LastStage0Insts.empty() && LastStage0Insts[Comp]->getParent() == &MBB) {
12288 // Update and Comp for I==0 are already exists in MBB
12289 // (MBB is an unrolled kernel)
12290 Register Counter;
12291 for (int I = 0; I <= TC; ++I) {
12292 Register NextCounter;
12293 if (I != 0)
12294 NextCounter =
12295 cloneInstr(Comp, CompCounterOprNum, Counter, MBB, MBB.end());
12296
12297 AccCond = AccumulateCond(AccCond, CC);
12298
12299 if (I != TC) {
12300 if (I == 0) {
12301 if (Update != Comp && IsUpdatePriorComp) {
12302 Counter =
12303 LastStage0Insts[Comp]->getOperand(CompCounterOprNum).getReg();
12304 NextCounter = cloneInstr(Update, UpdateCounterOprNum, Counter, MBB,
12305 MBB.end());
12306 } else {
12307 // can use already calculated value
12308 NextCounter = LastStage0Insts[Update]->getOperand(0).getReg();
12309 }
12310 } else if (Update != Comp) {
12311 NextCounter =
12312 cloneInstr(Update, UpdateCounterOprNum, Counter, MBB, MBB.end());
12313 }
12314 }
12315 Counter = NextCounter;
12316 }
12317 } else {
12318 Register Counter;
12319 if (LastStage0Insts.empty()) {
12320 // use initial counter value (testing if the trip count is sufficient to
12321 // be executed by pipelined code)
12322 Counter = Init;
12323 if (IsUpdatePriorComp)
12324 Counter =
12325 cloneInstr(Update, UpdateCounterOprNum, Counter, MBB, MBB.end());
12326 } else {
12327 // MBB is an epilogue block. LastStage0Insts[Comp] is in the kernel block.
12328 Counter = LastStage0Insts[Comp]->getOperand(CompCounterOprNum).getReg();
12329 }
12330
12331 for (int I = 0; I <= TC; ++I) {
12332 Register NextCounter;
12333 NextCounter =
12334 cloneInstr(Comp, CompCounterOprNum, Counter, MBB, MBB.end());
12335 AccCond = AccumulateCond(AccCond, CC);
12336 if (I != TC && Update != Comp)
12337 NextCounter =
12338 cloneInstr(Update, UpdateCounterOprNum, Counter, MBB, MBB.end());
12339 Counter = NextCounter;
12340 }
12341 }
12342
12343 // If AccCond == 0, the remainder is greater than TC.
12344 BuildMI(MBB, MBB.end(), Comp->getDebugLoc(), TII->get(AArch64::SUBSXri))
12345 .addReg(AArch64::XZR, RegState::Define | RegState::Dead)
12346 .addReg(AccCond)
12347 .addImm(0)
12348 .addImm(0);
12349 Cond.clear();
12351}
12352
12353static void extractPhiReg(const MachineInstr &Phi, const MachineBasicBlock *MBB,
12354 Register &RegMBB, Register &RegOther) {
12355 assert(Phi.getNumOperands() == 5);
12356 if (Phi.getOperand(2).getMBB() == MBB) {
12357 RegMBB = Phi.getOperand(1).getReg();
12358 RegOther = Phi.getOperand(3).getReg();
12359 } else {
12360 assert(Phi.getOperand(4).getMBB() == MBB);
12361 RegMBB = Phi.getOperand(3).getReg();
12362 RegOther = Phi.getOperand(1).getReg();
12363 }
12364}
12365
12367 if (!Reg.isVirtual())
12368 return false;
12369 const MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
12370 return MRI.getDefBlock(Reg) != BB;
12371}
12372
12373/// If Reg is an induction variable, return true and set some parameters
12374static bool getIndVarInfo(Register Reg, const MachineBasicBlock *LoopBB,
12375 MachineInstr *&UpdateInst,
12376 unsigned &UpdateCounterOprNum, Register &InitReg,
12377 bool &IsUpdatePriorComp) {
12378 // Example:
12379 //
12380 // Preheader:
12381 // InitReg = ...
12382 // LoopBB:
12383 // Reg0 = PHI (InitReg, Preheader), (Reg1, LoopBB)
12384 // Reg = COPY Reg0 ; COPY is ignored.
12385 // Reg1 = ADD Reg, #1; UpdateInst. Incremented by a loop invariant value.
12386 // ; Reg is the value calculated in the previous
12387 // ; iteration, so IsUpdatePriorComp == false.
12388
12389 if (LoopBB->pred_size() != 2)
12390 return false;
12391 if (!Reg.isVirtual())
12392 return false;
12393 const MachineRegisterInfo &MRI = LoopBB->getParent()->getRegInfo();
12394 UpdateInst = nullptr;
12395 UpdateCounterOprNum = 0;
12396 InitReg = 0;
12397 IsUpdatePriorComp = true;
12398 Register CurReg = Reg;
12399 while (true) {
12400 MachineInstr *Def = MRI.getVRegDef(CurReg);
12401 if (Def->getParent() != LoopBB)
12402 return false;
12403 if (Def->isCopy()) {
12404 // Ignore copy instructions unless they contain subregisters
12405 if (Def->getOperand(0).getSubReg() || Def->getOperand(1).getSubReg())
12406 return false;
12407 CurReg = Def->getOperand(1).getReg();
12408 } else if (Def->isPHI()) {
12409 if (InitReg != 0)
12410 return false;
12411 if (!UpdateInst)
12412 IsUpdatePriorComp = false;
12413 extractPhiReg(*Def, LoopBB, CurReg, InitReg);
12414 } else {
12415 if (UpdateInst)
12416 return false;
12417 switch (Def->getOpcode()) {
12418 case AArch64::ADDSXri:
12419 case AArch64::ADDSWri:
12420 case AArch64::SUBSXri:
12421 case AArch64::SUBSWri:
12422 case AArch64::ADDXri:
12423 case AArch64::ADDWri:
12424 case AArch64::SUBXri:
12425 case AArch64::SUBWri:
12426 UpdateInst = Def;
12427 UpdateCounterOprNum = 1;
12428 break;
12429 case AArch64::ADDSXrr:
12430 case AArch64::ADDSWrr:
12431 case AArch64::SUBSXrr:
12432 case AArch64::SUBSWrr:
12433 case AArch64::ADDXrr:
12434 case AArch64::ADDWrr:
12435 case AArch64::SUBXrr:
12436 case AArch64::SUBWrr:
12437 UpdateInst = Def;
12438 if (isDefinedOutside(Def->getOperand(2).getReg(), LoopBB))
12439 UpdateCounterOprNum = 1;
12440 else if (isDefinedOutside(Def->getOperand(1).getReg(), LoopBB))
12441 UpdateCounterOprNum = 2;
12442 else
12443 return false;
12444 break;
12445 default:
12446 return false;
12447 }
12448 CurReg = Def->getOperand(UpdateCounterOprNum).getReg();
12449 }
12450
12451 if (!CurReg.isVirtual())
12452 return false;
12453 if (Reg == CurReg)
12454 break;
12455 }
12456
12457 if (!UpdateInst)
12458 return false;
12459
12460 return true;
12461}
12462
12463std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo>
12465 // Accept loops that meet the following conditions
12466 // * The conditional branch is BCC
12467 // * The compare instruction is ADDS/SUBS/WHILEXX
12468 // * One operand of the compare is an induction variable and the other is a
12469 // loop invariant value
12470 // * The induction variable is incremented/decremented by a single instruction
12471 // * Does not contain CALL or instructions which have unmodeled side effects
12472
12473 for (MachineInstr &MI : *LoopBB)
12474 if (MI.isCall() || MI.hasUnmodeledSideEffects())
12475 // This instruction may use NZCV, which interferes with the instruction to
12476 // be inserted for loop control.
12477 return nullptr;
12478
12479 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
12481 if (analyzeBranch(*LoopBB, TBB, FBB, Cond))
12482 return nullptr;
12483
12484 // Infinite loops are not supported
12485 if (TBB == LoopBB && FBB == LoopBB)
12486 return nullptr;
12487
12488 // Must be conditional branch
12489 if (TBB != LoopBB && FBB == nullptr)
12490 return nullptr;
12491
12492 assert((TBB == LoopBB || FBB == LoopBB) &&
12493 "The Loop must be a single-basic-block loop");
12494
12495 MachineInstr *CondBranch = &*LoopBB->getFirstTerminator();
12497
12498 if (CondBranch->getOpcode() != AArch64::Bcc)
12499 return nullptr;
12500
12501 // Normalization for createTripCountGreaterCondition()
12502 if (TBB == LoopBB)
12504
12505 MachineInstr *Comp = nullptr;
12506 unsigned CompCounterOprNum = 0;
12507 for (MachineInstr &MI : reverse(*LoopBB)) {
12508 if (MI.modifiesRegister(AArch64::NZCV, &TRI)) {
12509 // Guarantee that the compare is SUBS/ADDS/WHILEXX and that one of the
12510 // operands is a loop invariant value
12511
12512 switch (MI.getOpcode()) {
12513 case AArch64::SUBSXri:
12514 case AArch64::SUBSWri:
12515 case AArch64::ADDSXri:
12516 case AArch64::ADDSWri:
12517 Comp = &MI;
12518 CompCounterOprNum = 1;
12519 break;
12520 case AArch64::ADDSWrr:
12521 case AArch64::ADDSXrr:
12522 case AArch64::SUBSWrr:
12523 case AArch64::SUBSXrr:
12524 Comp = &MI;
12525 break;
12526 default:
12527 if (isWhileOpcode(MI.getOpcode())) {
12528 Comp = &MI;
12529 break;
12530 }
12531 return nullptr;
12532 }
12533
12534 if (CompCounterOprNum == 0) {
12535 if (isDefinedOutside(Comp->getOperand(1).getReg(), LoopBB))
12536 CompCounterOprNum = 2;
12537 else if (isDefinedOutside(Comp->getOperand(2).getReg(), LoopBB))
12538 CompCounterOprNum = 1;
12539 else
12540 return nullptr;
12541 }
12542 break;
12543 }
12544 }
12545 if (!Comp)
12546 return nullptr;
12547
12548 MachineInstr *Update = nullptr;
12549 Register Init;
12550 bool IsUpdatePriorComp;
12551 unsigned UpdateCounterOprNum;
12552 if (!getIndVarInfo(Comp->getOperand(CompCounterOprNum).getReg(), LoopBB,
12553 Update, UpdateCounterOprNum, Init, IsUpdatePriorComp))
12554 return nullptr;
12555
12556 return std::make_unique<AArch64PipelinerLoopInfo>(
12557 LoopBB, CondBranch, Comp, CompCounterOprNum, Update, UpdateCounterOprNum,
12558 Init, IsUpdatePriorComp, Cond);
12559}
12560
12561/// verifyInstruction - Perform target specific instruction verification.
12562bool AArch64InstrInfo::verifyInstruction(const MachineInstr &MI,
12563 StringRef &ErrInfo) const {
12564 // Verify that immediate offsets on load/store instructions are within range.
12565 // Stack objects with an FI operand are excluded as they can be fixed up
12566 // during PEI.
12567 TypeSize Scale(0U, false), Width(0U, false);
12568 int64_t MinOffset, MaxOffset;
12569 if (getMemOpInfo(MI.getOpcode(), Scale, Width, MinOffset, MaxOffset)) {
12570 unsigned ImmIdx = getLoadStoreImmIdx(MI.getOpcode());
12571 if (MI.getOperand(ImmIdx).isImm() && !MI.getOperand(ImmIdx - 1).isFI()) {
12572 int64_t Imm = MI.getOperand(ImmIdx).getImm();
12573 if (Imm < MinOffset || Imm > MaxOffset) {
12574 ErrInfo = "Unexpected immediate on load/store instruction";
12575 return false;
12576 }
12577 }
12578 }
12579
12580 const MCInstrDesc &MCID = MI.getDesc();
12581 for (unsigned Op = 0; Op < MCID.getNumOperands(); Op++) {
12582 const MachineOperand &MO = MI.getOperand(Op);
12583 switch (MCID.operands()[Op].OperandType) {
12585 if (!MO.isImm() || MO.getImm() != 0) {
12586 ErrInfo = "OPERAND_IMPLICIT_IMM_0 should be 0";
12587 return false;
12588 }
12589 break;
12591 if (!MO.isImm() ||
12593 (AArch64_AM::getShiftValue(MO.getImm()) != 8 &&
12594 AArch64_AM::getShiftValue(MO.getImm()) != 16)) {
12595 ErrInfo = "OPERAND_SHIFT_MSL should be msl shift of 8 or 16";
12596 return false;
12597 }
12598 break;
12600 if (!MO.isImm() || (MO.getImm() != 0 && MO.getImm() != 1)) {
12601 ErrInfo = "OPERAND_IMM_UINT1 should be 0 or 1";
12602 return false;
12603 }
12604 break;
12606 if (!MO.isImm() || MO.getImm() <= 0 || MO.getImm() > 16) {
12607 ErrInfo = "OPERAND_IMM_UINT4plus1 should be in the range 1 to 16";
12608 return false;
12609 }
12610 break;
12612 if (!MO.isImm() || !isUInt<5>(MO.getImm())) {
12613 ErrInfo = "OPERAND_IMM_UINT5 should be in the range 0 to 31";
12614 return false;
12615 }
12616 break;
12618 if (!MO.isImm() || !isUInt<8>(MO.getImm())) {
12619 ErrInfo = "OPERAND_IMM_UINT8 should be in the range 0 to 255";
12620 return false;
12621 }
12622 break;
12623 default:
12624 break;
12625 }
12626 }
12627 return true;
12628}
12629
12630#define GET_INSTRINFO_HELPERS
12631#define GET_INSTRMAP_INFO
12632#include "AArch64GenInstrInfo.inc"
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
const AArch64Subtarget & Subtarget
SDValue Pred
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 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 void updateOperandRegClass(MachineInstr &Instr)
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 std::optional< SPAddSubImmEncoding > adjustSPAddSubImm(const MachineInstr &MI, int64_t Delta)
Adjust the signed byte offset of MI, which must satisfy isSPAddSubImm, by Delta and re-encode the res...
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 unsigned getBranchDisplacementBits(const AArch64Options &CLOpts, unsigned Opc)
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 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 genMaddShf(MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, SmallVectorImpl< MachineInstr * > &DelInstrs, unsigned MaddOpc, bool Is64Bit, DenseMap< Register, unsigned > &InstrIdxForVirtReg)
MUL I=A,B,0 ADDrs R,I,C,shift ==> SBFM/UBFM J=C,shift MADD R,A,B,J.
static void appendReadRegExpr(SmallVectorImpl< char > &Expr, unsigned RegNum)
static MachineInstr * genMaddR(MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, unsigned IdxMulOpd, unsigned MaddOpc, unsigned VR, const TargetRegisterClass *RC)
genMaddR - Generate madd instruction and combine mul and add using an extra virtual register Example ...
static Register cloneInstr(const MachineInstr *MI, unsigned ReplaceOprNum, Register ReplaceReg, MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertTo)
Clone an instruction from MI.
static bool scaleOffset(unsigned Opc, int64_t &Offset)
static bool canCombineWithFMUL(MachineBasicBlock &MBB, MachineOperand &MO, unsigned MulOpc)
unsigned scaledOffsetOpcode(unsigned Opcode, unsigned &Scale)
static MachineInstr * genFusedMultiplyIdx(MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC)
genFusedMultiplyIdx - Helper to generate fused multiply accumulate instructions.
static MachineInstr * genIndexedMultiply(MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, unsigned IdxDupOp, unsigned MulOpc, const TargetRegisterClass *RC, MachineRegisterInfo &MRI)
Fold (FMUL x (DUP y lane)) into (FMUL_indexed x y lane)
static bool 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 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 bool outliningCandidatesPAuthLRConsensus(const outliner::Candidate &a, const outliner::Candidate &b)
static bool isValidCBExtend(int64_t Opc, AArch64_AM::ShiftExtendType Ext)
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 isSPAddSubImm(const MachineInstr &MI)
Returns true if MI is an ADD/SUBXri with an immediate offset that reads SP but does not write SP (e....
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 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 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)
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
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[]
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
SmallVector< MachineOperand, 4 > Cond
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
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:479
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
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.
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
Register isLoadFromStackSlot(const MachineInstr &MI, int &FrameIndex) const override
bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
bool getMemOperandsWithOffsetWidth(const MachineInstr &MI, SmallVectorImpl< const MachineOperand * > &BaseOps, int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width) 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.
bool canInsertSelect(const MachineBasicBlock &, ArrayRef< MachineOperand > Cond, Register, Register, Register, SelectExpansion &) const override
MachineOperand & getMemOpBaseRegImmOfsOffsetOperand(MachineInstr &LdSt) const
Return the immediate offset of the base register in a load/store LdSt.
std::optional< ExtAddrMode > getAddrModeFromMemoryOp(const MachineInstr &MemI) const override
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 getMemOperandWithOffsetWidth(const MachineInstr &MI, const MachineOperand *&BaseOp, int64_t &Offset, bool &OffsetIsScalable, TypeSize &Width) const
If OffsetIsScalable is set to 'true', the offset is scaled by vscale.
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,...
AArch64PAuth::AuthCheckMethod getAuthenticatedLRCheckMethod(const MachineFunction &MF) const
Choose a method of checking LR before performing a tail call.
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:44
A debug info location.
Definition DebugLoc.h:126
bool empty() const
Definition DenseMap.h:716
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition Function.h:708
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:705
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
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.
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:1579
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.
bool usesWindowsUnwindInfo() const
True if this function describes its unwind information with Windows SEH unwind opcodes (....
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.
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 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.
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.
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
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition Module.h:328
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
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
unsigned getNumOperands() const
Return the number of values used by this operation.
const SDValue & getOperand(unsigned Num) const
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:28
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:70
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:31
int64_t getFixed() const
Returns the fixed component of the stack.
Definition TypeSize.h:47
int64_t getScalable() const
Returns the scalable component of the stack.
Definition TypeSize.h:50
static StackOffset get(int64_t Fixed, int64_t Scalable)
Definition TypeSize.h:42
static StackOffset getScalable(int64_t Scalable)
Definition TypeSize.h:41
static StackOffset getFixed(int64_t Fixed)
Definition TypeSize.h:40
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 isFunctionSafeToOutlineFrom(MachineFunction &MF, bool OutlineFromLinkOnceODRs) const
Return true if the function can safely be outlined from.
virtual bool isSchedulingBoundary(const MachineInstr &MI, const MachineBasicBlock *MBB, const MachineFunction &MF) const
Test if the given instruction should be considered a scheduling boundary.
virtual CombinerObjective getCombinerObjective(unsigned Pattern) const
Return the objective of a combiner pattern.
virtual bool isFunctionSafeToSplit(const MachineFunction &MF) const
Return true if the function is a viable candidate for machine function splitting.
const MCAsmInfo & getMCAsmInfo() const
Return target specific asm information.
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:877
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
static constexpr TypeSize getScalable(ScalarTy MinimumSize)
Definition TypeSize.h:355
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:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
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.
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.
IterT next_nodbg(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It, then continue incrementing it while it points to a debug instruction.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
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:1755
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.
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:2570
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:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
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:1769
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:280
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:323
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:2208
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:1963
static const MachineMemOperand::Flags MOSuppressPair
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:572
void appendLEB128(SmallVectorImpl< U > &Buffer, T Value)
Definition LEB128.h:280
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
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
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.