LLVM 19.0.0git
AArch64CallLowering.cpp
Go to the documentation of this file.
1//===--- AArch64CallLowering.cpp - Call lowering --------------------------===//
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/// \file
10/// This file implements the lowering of LLVM calls to machine code calls for
11/// GlobalISel.
12///
13//===----------------------------------------------------------------------===//
14
15#include "AArch64CallLowering.h"
17#include "AArch64ISelLowering.h"
19#include "AArch64RegisterInfo.h"
20#include "AArch64Subtarget.h"
21#include "llvm/ADT/ArrayRef.h"
41#include "llvm/IR/Argument.h"
42#include "llvm/IR/Attributes.h"
43#include "llvm/IR/Function.h"
44#include "llvm/IR/Type.h"
45#include "llvm/IR/Value.h"
46#include <algorithm>
47#include <cassert>
48#include <cstdint>
49#include <iterator>
50
51#define DEBUG_TYPE "aarch64-call-lowering"
52
53using namespace llvm;
54using namespace AArch64GISelUtils;
55
57 : CallLowering(&TLI) {}
58
59static void applyStackPassedSmallTypeDAGHack(EVT OrigVT, MVT &ValVT,
60 MVT &LocVT) {
61 // If ValVT is i1/i8/i16, we should set LocVT to i8/i8/i16. This is a legacy
62 // hack because the DAG calls the assignment function with pre-legalized
63 // register typed values, not the raw type.
64 //
65 // This hack is not applied to return values which are not passed on the
66 // stack.
67 if (OrigVT == MVT::i1 || OrigVT == MVT::i8)
68 ValVT = LocVT = MVT::i8;
69 else if (OrigVT == MVT::i16)
70 ValVT = LocVT = MVT::i16;
71}
72
73// Account for i1/i8/i16 stack passed value hack
75 const MVT ValVT = VA.getValVT();
76 return (ValVT == MVT::i8 || ValVT == MVT::i16) ? LLT(ValVT)
77 : LLT(VA.getLocVT());
78}
79
80namespace {
81
82struct AArch64IncomingValueAssigner
84 AArch64IncomingValueAssigner(CCAssignFn *AssignFn_,
85 CCAssignFn *AssignFnVarArg_)
86 : IncomingValueAssigner(AssignFn_, AssignFnVarArg_) {}
87
88 bool assignArg(unsigned ValNo, EVT OrigVT, MVT ValVT, MVT LocVT,
91 CCState &State) override {
92 applyStackPassedSmallTypeDAGHack(OrigVT, ValVT, LocVT);
93 return IncomingValueAssigner::assignArg(ValNo, OrigVT, ValVT, LocVT,
94 LocInfo, Info, Flags, State);
95 }
96};
97
98struct AArch64OutgoingValueAssigner
100 const AArch64Subtarget &Subtarget;
101
102 /// Track if this is used for a return instead of function argument
103 /// passing. We apply a hack to i1/i8/i16 stack passed values, but do not use
104 /// stack passed returns for them and cannot apply the type adjustment.
105 bool IsReturn;
106
107 AArch64OutgoingValueAssigner(CCAssignFn *AssignFn_,
108 CCAssignFn *AssignFnVarArg_,
109 const AArch64Subtarget &Subtarget_,
110 bool IsReturn)
111 : OutgoingValueAssigner(AssignFn_, AssignFnVarArg_),
112 Subtarget(Subtarget_), IsReturn(IsReturn) {}
113
114 bool assignArg(unsigned ValNo, EVT OrigVT, MVT ValVT, MVT LocVT,
115 CCValAssign::LocInfo LocInfo,
117 CCState &State) override {
118 bool IsCalleeWin = Subtarget.isCallingConvWin64(State.getCallingConv());
119 bool UseVarArgsCCForFixed = IsCalleeWin && State.isVarArg();
120
121 bool Res;
122 if (Info.IsFixed && !UseVarArgsCCForFixed) {
123 if (!IsReturn)
124 applyStackPassedSmallTypeDAGHack(OrigVT, ValVT, LocVT);
125 Res = AssignFn(ValNo, ValVT, LocVT, LocInfo, Flags, State);
126 } else
127 Res = AssignFnVarArg(ValNo, ValVT, LocVT, LocInfo, Flags, State);
128
129 StackSize = State.getStackSize();
130 return Res;
131 }
132};
133
134struct IncomingArgHandler : public CallLowering::IncomingValueHandler {
135 IncomingArgHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI)
136 : IncomingValueHandler(MIRBuilder, MRI) {}
137
138 Register getStackAddress(uint64_t Size, int64_t Offset,
140 ISD::ArgFlagsTy Flags) override {
141 auto &MFI = MIRBuilder.getMF().getFrameInfo();
142
143 // Byval is assumed to be writable memory, but other stack passed arguments
144 // are not.
145 const bool IsImmutable = !Flags.isByVal();
146
147 int FI = MFI.CreateFixedObject(Size, Offset, IsImmutable);
148 MPO = MachinePointerInfo::getFixedStack(MIRBuilder.getMF(), FI);
149 auto AddrReg = MIRBuilder.buildFrameIndex(LLT::pointer(0, 64), FI);
150 return AddrReg.getReg(0);
151 }
152
153 LLT getStackValueStoreType(const DataLayout &DL, const CCValAssign &VA,
154 ISD::ArgFlagsTy Flags) const override {
155 // For pointers, we just need to fixup the integer types reported in the
156 // CCValAssign.
157 if (Flags.isPointer())
160 }
161
162 void assignValueToReg(Register ValVReg, Register PhysReg,
163 const CCValAssign &VA) override {
164 markPhysRegUsed(PhysReg);
165 IncomingValueHandler::assignValueToReg(ValVReg, PhysReg, VA);
166 }
167
168 void assignValueToAddress(Register ValVReg, Register Addr, LLT MemTy,
169 const MachinePointerInfo &MPO,
170 const CCValAssign &VA) override {
171 MachineFunction &MF = MIRBuilder.getMF();
172
173 LLT ValTy(VA.getValVT());
174 LLT LocTy(VA.getLocVT());
175
176 // Fixup the types for the DAG compatibility hack.
177 if (VA.getValVT() == MVT::i8 || VA.getValVT() == MVT::i16)
178 std::swap(ValTy, LocTy);
179 else {
180 // The calling code knows if this is a pointer or not, we're only touching
181 // the LocTy for the i8/i16 hack.
182 assert(LocTy.getSizeInBits() == MemTy.getSizeInBits());
183 LocTy = MemTy;
184 }
185
186 auto MMO = MF.getMachineMemOperand(
188 inferAlignFromPtrInfo(MF, MPO));
189
190 switch (VA.getLocInfo()) {
191 case CCValAssign::LocInfo::ZExt:
192 MIRBuilder.buildLoadInstr(TargetOpcode::G_ZEXTLOAD, ValVReg, Addr, *MMO);
193 return;
194 case CCValAssign::LocInfo::SExt:
195 MIRBuilder.buildLoadInstr(TargetOpcode::G_SEXTLOAD, ValVReg, Addr, *MMO);
196 return;
197 default:
198 MIRBuilder.buildLoad(ValVReg, Addr, *MMO);
199 return;
200 }
201 }
202
203 /// How the physical register gets marked varies between formal
204 /// parameters (it's a basic-block live-in), and a call instruction
205 /// (it's an implicit-def of the BL).
206 virtual void markPhysRegUsed(MCRegister PhysReg) = 0;
207};
208
209struct FormalArgHandler : public IncomingArgHandler {
211 : IncomingArgHandler(MIRBuilder, MRI) {}
212
213 void markPhysRegUsed(MCRegister PhysReg) override {
214 MIRBuilder.getMRI()->addLiveIn(PhysReg);
215 MIRBuilder.getMBB().addLiveIn(PhysReg);
216 }
217};
218
219struct CallReturnHandler : public IncomingArgHandler {
220 CallReturnHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
222 : IncomingArgHandler(MIRBuilder, MRI), MIB(MIB) {}
223
224 void markPhysRegUsed(MCRegister PhysReg) override {
225 MIB.addDef(PhysReg, RegState::Implicit);
226 }
227
229};
230
231/// A special return arg handler for "returned" attribute arg calls.
232struct ReturnedArgCallReturnHandler : public CallReturnHandler {
233 ReturnedArgCallReturnHandler(MachineIRBuilder &MIRBuilder,
236 : CallReturnHandler(MIRBuilder, MRI, MIB) {}
237
238 void markPhysRegUsed(MCRegister PhysReg) override {}
239};
240
241struct OutgoingArgHandler : public CallLowering::OutgoingValueHandler {
242 OutgoingArgHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
243 MachineInstrBuilder MIB, bool IsTailCall = false,
244 int FPDiff = 0)
245 : OutgoingValueHandler(MIRBuilder, MRI), MIB(MIB), IsTailCall(IsTailCall),
246 FPDiff(FPDiff),
247 Subtarget(MIRBuilder.getMF().getSubtarget<AArch64Subtarget>()) {}
248
249 Register getStackAddress(uint64_t Size, int64_t Offset,
251 ISD::ArgFlagsTy Flags) override {
252 MachineFunction &MF = MIRBuilder.getMF();
253 LLT p0 = LLT::pointer(0, 64);
254 LLT s64 = LLT::scalar(64);
255
256 if (IsTailCall) {
257 assert(!Flags.isByVal() && "byval unhandled with tail calls");
258
259 Offset += FPDiff;
260 int FI = MF.getFrameInfo().CreateFixedObject(Size, Offset, true);
261 auto FIReg = MIRBuilder.buildFrameIndex(p0, FI);
263 return FIReg.getReg(0);
264 }
265
266 if (!SPReg)
267 SPReg = MIRBuilder.buildCopy(p0, Register(AArch64::SP)).getReg(0);
268
269 auto OffsetReg = MIRBuilder.buildConstant(s64, Offset);
270
271 auto AddrReg = MIRBuilder.buildPtrAdd(p0, SPReg, OffsetReg);
272
274 return AddrReg.getReg(0);
275 }
276
277 /// We need to fixup the reported store size for certain value types because
278 /// we invert the interpretation of ValVT and LocVT in certain cases. This is
279 /// for compatability with the DAG call lowering implementation, which we're
280 /// currently building on top of.
281 LLT getStackValueStoreType(const DataLayout &DL, const CCValAssign &VA,
282 ISD::ArgFlagsTy Flags) const override {
283 if (Flags.isPointer())
286 }
287
288 void assignValueToReg(Register ValVReg, Register PhysReg,
289 const CCValAssign &VA) override {
290 MIB.addUse(PhysReg, RegState::Implicit);
291 Register ExtReg = extendRegister(ValVReg, VA);
292 MIRBuilder.buildCopy(PhysReg, ExtReg);
293 }
294
295 void assignValueToAddress(Register ValVReg, Register Addr, LLT MemTy,
296 const MachinePointerInfo &MPO,
297 const CCValAssign &VA) override {
298 MachineFunction &MF = MIRBuilder.getMF();
299 auto MMO = MF.getMachineMemOperand(MPO, MachineMemOperand::MOStore, MemTy,
300 inferAlignFromPtrInfo(MF, MPO));
301 MIRBuilder.buildStore(ValVReg, Addr, *MMO);
302 }
303
304 void assignValueToAddress(const CallLowering::ArgInfo &Arg, unsigned RegIndex,
305 Register Addr, LLT MemTy,
306 const MachinePointerInfo &MPO,
307 const CCValAssign &VA) override {
308 unsigned MaxSize = MemTy.getSizeInBytes() * 8;
309 // For varargs, we always want to extend them to 8 bytes, in which case
310 // we disable setting a max.
311 if (!Arg.IsFixed)
312 MaxSize = 0;
313
314 Register ValVReg = Arg.Regs[RegIndex];
315 if (VA.getLocInfo() != CCValAssign::LocInfo::FPExt) {
316 MVT LocVT = VA.getLocVT();
317 MVT ValVT = VA.getValVT();
318
319 if (VA.getValVT() == MVT::i8 || VA.getValVT() == MVT::i16) {
320 std::swap(ValVT, LocVT);
321 MemTy = LLT(VA.getValVT());
322 }
323
324 ValVReg = extendRegister(ValVReg, VA, MaxSize);
325 } else {
326 // The store does not cover the full allocated stack slot.
327 MemTy = LLT(VA.getValVT());
328 }
329
330 assignValueToAddress(ValVReg, Addr, MemTy, MPO, VA);
331 }
332
334
335 bool IsTailCall;
336
337 /// For tail calls, the byte offset of the call's argument area from the
338 /// callee's. Unused elsewhere.
339 int FPDiff;
340
341 // Cache the SP register vreg if we need it more than once in this call site.
342 Register SPReg;
343
344 const AArch64Subtarget &Subtarget;
345};
346} // namespace
347
348static bool doesCalleeRestoreStack(CallingConv::ID CallConv, bool TailCallOpt) {
349 return (CallConv == CallingConv::Fast && TailCallOpt) ||
350 CallConv == CallingConv::Tail || CallConv == CallingConv::SwiftTail;
351}
352
354 const Value *Val,
355 ArrayRef<Register> VRegs,
357 Register SwiftErrorVReg) const {
358 auto MIB = MIRBuilder.buildInstrNoInsert(AArch64::RET_ReallyLR);
359 assert(((Val && !VRegs.empty()) || (!Val && VRegs.empty())) &&
360 "Return value without a vreg");
361
362 bool Success = true;
363 if (!FLI.CanLowerReturn) {
364 insertSRetStores(MIRBuilder, Val->getType(), VRegs, FLI.DemoteRegister);
365 } else if (!VRegs.empty()) {
366 MachineFunction &MF = MIRBuilder.getMF();
367 const Function &F = MF.getFunction();
368 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
369
371 const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
372 CCAssignFn *AssignFn = TLI.CCAssignFnForReturn(F.getCallingConv());
373 auto &DL = F.getParent()->getDataLayout();
374 LLVMContext &Ctx = Val->getType()->getContext();
375
376 SmallVector<EVT, 4> SplitEVTs;
377 ComputeValueVTs(TLI, DL, Val->getType(), SplitEVTs);
378 assert(VRegs.size() == SplitEVTs.size() &&
379 "For each split Type there should be exactly one VReg.");
380
381 SmallVector<ArgInfo, 8> SplitArgs;
382 CallingConv::ID CC = F.getCallingConv();
383
384 for (unsigned i = 0; i < SplitEVTs.size(); ++i) {
385 Register CurVReg = VRegs[i];
386 ArgInfo CurArgInfo = ArgInfo{CurVReg, SplitEVTs[i].getTypeForEVT(Ctx), 0};
388
389 // i1 is a special case because SDAG i1 true is naturally zero extended
390 // when widened using ANYEXT. We need to do it explicitly here.
391 auto &Flags = CurArgInfo.Flags[0];
392 if (MRI.getType(CurVReg).getSizeInBits() == 1 && !Flags.isSExt() &&
393 !Flags.isZExt()) {
394 CurVReg = MIRBuilder.buildZExt(LLT::scalar(8), CurVReg).getReg(0);
395 } else if (TLI.getNumRegistersForCallingConv(Ctx, CC, SplitEVTs[i]) ==
396 1) {
397 // Some types will need extending as specified by the CC.
398 MVT NewVT = TLI.getRegisterTypeForCallingConv(Ctx, CC, SplitEVTs[i]);
399 if (EVT(NewVT) != SplitEVTs[i]) {
400 unsigned ExtendOp = TargetOpcode::G_ANYEXT;
401 if (F.getAttributes().hasRetAttr(Attribute::SExt))
402 ExtendOp = TargetOpcode::G_SEXT;
403 else if (F.getAttributes().hasRetAttr(Attribute::ZExt))
404 ExtendOp = TargetOpcode::G_ZEXT;
405
406 LLT NewLLT(NewVT);
407 LLT OldLLT(MVT::getVT(CurArgInfo.Ty));
408 CurArgInfo.Ty = EVT(NewVT).getTypeForEVT(Ctx);
409 // Instead of an extend, we might have a vector type which needs
410 // padding with more elements, e.g. <2 x half> -> <4 x half>.
411 if (NewVT.isVector()) {
412 if (OldLLT.isVector()) {
413 if (NewLLT.getNumElements() > OldLLT.getNumElements()) {
414
415 CurVReg =
416 MIRBuilder.buildPadVectorWithUndefElements(NewLLT, CurVReg)
417 .getReg(0);
418 } else {
419 // Just do a vector extend.
420 CurVReg = MIRBuilder.buildInstr(ExtendOp, {NewLLT}, {CurVReg})
421 .getReg(0);
422 }
423 } else if (NewLLT.getNumElements() >= 2 &&
424 NewLLT.getNumElements() <= 8) {
425 // We need to pad a <1 x S> type to <2/4/8 x S>. Since we don't
426 // have <1 x S> vector types in GISel we use a build_vector
427 // instead of a vector merge/concat.
428 CurVReg =
429 MIRBuilder.buildPadVectorWithUndefElements(NewLLT, CurVReg)
430 .getReg(0);
431 } else {
432 LLVM_DEBUG(dbgs() << "Could not handle ret ty\n");
433 return false;
434 }
435 } else {
436 // If the split EVT was a <1 x T> vector, and NewVT is T, then we
437 // don't have to do anything since we don't distinguish between the
438 // two.
439 if (NewLLT != MRI.getType(CurVReg)) {
440 // A scalar extend.
441 CurVReg = MIRBuilder.buildInstr(ExtendOp, {NewLLT}, {CurVReg})
442 .getReg(0);
443 }
444 }
445 }
446 }
447 if (CurVReg != CurArgInfo.Regs[0]) {
448 CurArgInfo.Regs[0] = CurVReg;
449 // Reset the arg flags after modifying CurVReg.
451 }
452 splitToValueTypes(CurArgInfo, SplitArgs, DL, CC);
453 }
454
455 AArch64OutgoingValueAssigner Assigner(AssignFn, AssignFn, Subtarget,
456 /*IsReturn*/ true);
457 OutgoingArgHandler Handler(MIRBuilder, MRI, MIB);
458 Success = determineAndHandleAssignments(Handler, Assigner, SplitArgs,
459 MIRBuilder, CC, F.isVarArg());
460 }
461
462 if (SwiftErrorVReg) {
463 MIB.addUse(AArch64::X21, RegState::Implicit);
464 MIRBuilder.buildCopy(AArch64::X21, SwiftErrorVReg);
465 }
466
467 MIRBuilder.insertInstr(MIB);
468 return Success;
469}
470
472 CallingConv::ID CallConv,
474 bool IsVarArg) const {
476 const auto &TLI = *getTLI<AArch64TargetLowering>();
477 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs,
478 MF.getFunction().getContext());
479
480 return checkReturn(CCInfo, Outs, TLI.CCAssignFnForReturn(CallConv));
481}
482
483/// Helper function to compute forwarded registers for musttail calls. Computes
484/// the forwarded registers, sets MBB liveness, and emits COPY instructions that
485/// can be used to save + restore registers later.
487 CCAssignFn *AssignFn) {
488 MachineBasicBlock &MBB = MIRBuilder.getMBB();
489 MachineFunction &MF = MIRBuilder.getMF();
490 MachineFrameInfo &MFI = MF.getFrameInfo();
491
492 if (!MFI.hasMustTailInVarArgFunc())
493 return;
494
496 const Function &F = MF.getFunction();
497 assert(F.isVarArg() && "Expected F to be vararg?");
498
499 // Compute the set of forwarded registers. The rest are scratch.
501 CCState CCInfo(F.getCallingConv(), /*IsVarArg=*/true, MF, ArgLocs,
502 F.getContext());
503 SmallVector<MVT, 2> RegParmTypes;
504 RegParmTypes.push_back(MVT::i64);
505 RegParmTypes.push_back(MVT::f128);
506
507 // Later on, we can use this vector to restore the registers if necessary.
510 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, AssignFn);
511
512 // Conservatively forward X8, since it might be used for an aggregate
513 // return.
514 if (!CCInfo.isAllocated(AArch64::X8)) {
515 Register X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
516 Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
517 }
518
519 // Add the forwards to the MachineBasicBlock and MachineFunction.
520 for (const auto &F : Forwards) {
521 MBB.addLiveIn(F.PReg);
522 MIRBuilder.buildCopy(Register(F.VReg), Register(F.PReg));
523 }
524}
525
527 auto &F = MF.getFunction();
528 if (F.getReturnType()->isScalableTy() ||
529 llvm::any_of(F.args(), [](const Argument &A) {
530 return A.getType()->isScalableTy();
531 }))
532 return true;
533 const auto &ST = MF.getSubtarget<AArch64Subtarget>();
534 if (!ST.hasNEON() || !ST.hasFPARMv8()) {
535 LLVM_DEBUG(dbgs() << "Falling back to SDAG because we don't support no-NEON\n");
536 return true;
537 }
538
539 SMEAttrs Attrs(F);
540 if (Attrs.hasZAState() || Attrs.hasZT0State() ||
541 Attrs.hasStreamingInterfaceOrBody() ||
542 Attrs.hasStreamingCompatibleInterface())
543 return true;
544
545 return false;
546}
547
548void AArch64CallLowering::saveVarArgRegisters(
550 CCState &CCInfo) const {
553
554 MachineFunction &MF = MIRBuilder.getMF();
556 MachineFrameInfo &MFI = MF.getFrameInfo();
558 auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
559 bool IsWin64CC =
560 Subtarget.isCallingConvWin64(CCInfo.getCallingConv());
561 const LLT p0 = LLT::pointer(0, 64);
562 const LLT s64 = LLT::scalar(64);
563
564 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
565 unsigned NumVariadicGPRArgRegs = GPRArgRegs.size() - FirstVariadicGPR + 1;
566
567 unsigned GPRSaveSize = 8 * (GPRArgRegs.size() - FirstVariadicGPR);
568 int GPRIdx = 0;
569 if (GPRSaveSize != 0) {
570 if (IsWin64CC) {
571 GPRIdx = MFI.CreateFixedObject(GPRSaveSize,
572 -static_cast<int>(GPRSaveSize), false);
573 if (GPRSaveSize & 15)
574 // The extra size here, if triggered, will always be 8.
575 MFI.CreateFixedObject(16 - (GPRSaveSize & 15),
576 -static_cast<int>(alignTo(GPRSaveSize, 16)),
577 false);
578 } else
579 GPRIdx = MFI.CreateStackObject(GPRSaveSize, Align(8), false);
580
581 auto FIN = MIRBuilder.buildFrameIndex(p0, GPRIdx);
582 auto Offset =
583 MIRBuilder.buildConstant(MRI.createGenericVirtualRegister(s64), 8);
584
585 for (unsigned i = FirstVariadicGPR; i < GPRArgRegs.size(); ++i) {
586 Register Val = MRI.createGenericVirtualRegister(s64);
587 Handler.assignValueToReg(
588 Val, GPRArgRegs[i],
590 GPRArgRegs[i], MVT::i64, CCValAssign::Full));
591 auto MPO = IsWin64CC ? MachinePointerInfo::getFixedStack(
592 MF, GPRIdx, (i - FirstVariadicGPR) * 8)
593 : MachinePointerInfo::getStack(MF, i * 8);
594 MIRBuilder.buildStore(Val, FIN, MPO, inferAlignFromPtrInfo(MF, MPO));
595
596 FIN = MIRBuilder.buildPtrAdd(MRI.createGenericVirtualRegister(p0),
597 FIN.getReg(0), Offset);
598 }
599 }
600 FuncInfo->setVarArgsGPRIndex(GPRIdx);
601 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
602
603 if (Subtarget.hasFPARMv8() && !IsWin64CC) {
604 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
605
606 unsigned FPRSaveSize = 16 * (FPRArgRegs.size() - FirstVariadicFPR);
607 int FPRIdx = 0;
608 if (FPRSaveSize != 0) {
609 FPRIdx = MFI.CreateStackObject(FPRSaveSize, Align(16), false);
610
611 auto FIN = MIRBuilder.buildFrameIndex(p0, FPRIdx);
612 auto Offset =
613 MIRBuilder.buildConstant(MRI.createGenericVirtualRegister(s64), 16);
614
615 for (unsigned i = FirstVariadicFPR; i < FPRArgRegs.size(); ++i) {
616 Register Val = MRI.createGenericVirtualRegister(LLT::scalar(128));
617 Handler.assignValueToReg(
618 Val, FPRArgRegs[i],
620 i + MF.getFunction().getNumOperands() + NumVariadicGPRArgRegs,
621 MVT::f128, FPRArgRegs[i], MVT::f128, CCValAssign::Full));
622
623 auto MPO = MachinePointerInfo::getStack(MF, i * 16);
624 MIRBuilder.buildStore(Val, FIN, MPO, inferAlignFromPtrInfo(MF, MPO));
625
626 FIN = MIRBuilder.buildPtrAdd(MRI.createGenericVirtualRegister(p0),
627 FIN.getReg(0), Offset);
628 }
629 }
630 FuncInfo->setVarArgsFPRIndex(FPRIdx);
631 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
632 }
633}
634
636 MachineIRBuilder &MIRBuilder, const Function &F,
638 MachineFunction &MF = MIRBuilder.getMF();
639 MachineBasicBlock &MBB = MIRBuilder.getMBB();
641 auto &DL = F.getParent()->getDataLayout();
642 auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
643
644 // Arm64EC has extra requirements for varargs calls which are only implemented
645 // in SelectionDAG; bail out for now.
646 if (F.isVarArg() && Subtarget.isWindowsArm64EC())
647 return false;
648
649 // Arm64EC thunks have a special calling convention which is only implemented
650 // in SelectionDAG; bail out for now.
651 if (F.getCallingConv() == CallingConv::ARM64EC_Thunk_Native ||
652 F.getCallingConv() == CallingConv::ARM64EC_Thunk_X64)
653 return false;
654
655 bool IsWin64 = Subtarget.isCallingConvWin64(F.getCallingConv()) && !Subtarget.isWindowsArm64EC();
656
657 SmallVector<ArgInfo, 8> SplitArgs;
659
660 // Insert the hidden sret parameter if the return value won't fit in the
661 // return registers.
662 if (!FLI.CanLowerReturn)
664
665 unsigned i = 0;
666 for (auto &Arg : F.args()) {
667 if (DL.getTypeStoreSize(Arg.getType()).isZero())
668 continue;
669
670 ArgInfo OrigArg{VRegs[i], Arg, i};
672
673 // i1 arguments are zero-extended to i8 by the caller. Emit a
674 // hint to reflect this.
675 if (OrigArg.Ty->isIntegerTy(1)) {
676 assert(OrigArg.Regs.size() == 1 &&
677 MRI.getType(OrigArg.Regs[0]).getSizeInBits() == 1 &&
678 "Unexpected registers used for i1 arg");
679
680 auto &Flags = OrigArg.Flags[0];
681 if (!Flags.isZExt() && !Flags.isSExt()) {
682 // Lower i1 argument as i8, and insert AssertZExt + Trunc later.
683 Register OrigReg = OrigArg.Regs[0];
684 Register WideReg = MRI.createGenericVirtualRegister(LLT::scalar(8));
685 OrigArg.Regs[0] = WideReg;
686 BoolArgs.push_back({OrigReg, WideReg});
687 }
688 }
689
690 if (Arg.hasAttribute(Attribute::SwiftAsync))
691 MF.getInfo<AArch64FunctionInfo>()->setHasSwiftAsyncContext(true);
692
693 splitToValueTypes(OrigArg, SplitArgs, DL, F.getCallingConv());
694 ++i;
695 }
696
697 if (!MBB.empty())
698 MIRBuilder.setInstr(*MBB.begin());
699
700 const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
701 CCAssignFn *AssignFn = TLI.CCAssignFnForCall(F.getCallingConv(), IsWin64 && F.isVarArg());
702
703 AArch64IncomingValueAssigner Assigner(AssignFn, AssignFn);
704 FormalArgHandler Handler(MIRBuilder, MRI);
706 CCState CCInfo(F.getCallingConv(), F.isVarArg(), MF, ArgLocs, F.getContext());
707 if (!determineAssignments(Assigner, SplitArgs, CCInfo) ||
708 !handleAssignments(Handler, SplitArgs, CCInfo, ArgLocs, MIRBuilder))
709 return false;
710
711 if (!BoolArgs.empty()) {
712 for (auto &KV : BoolArgs) {
713 Register OrigReg = KV.first;
714 Register WideReg = KV.second;
715 LLT WideTy = MRI.getType(WideReg);
716 assert(MRI.getType(OrigReg).getScalarSizeInBits() == 1 &&
717 "Unexpected bit size of a bool arg");
718 MIRBuilder.buildTrunc(
719 OrigReg, MIRBuilder.buildAssertZExt(WideTy, WideReg, 1).getReg(0));
720 }
721 }
722
724 uint64_t StackSize = Assigner.StackSize;
725 if (F.isVarArg()) {
726 if ((!Subtarget.isTargetDarwin() && !Subtarget.isWindowsArm64EC()) || IsWin64) {
727 // The AAPCS variadic function ABI is identical to the non-variadic
728 // one. As a result there may be more arguments in registers and we should
729 // save them for future reference.
730 // Win64 variadic functions also pass arguments in registers, but all
731 // float arguments are passed in integer registers.
732 saveVarArgRegisters(MIRBuilder, Handler, CCInfo);
733 } else if (Subtarget.isWindowsArm64EC()) {
734 return false;
735 }
736
737 // We currently pass all varargs at 8-byte alignment, or 4 in ILP32.
738 StackSize = alignTo(Assigner.StackSize, Subtarget.isTargetILP32() ? 4 : 8);
739
740 auto &MFI = MIRBuilder.getMF().getFrameInfo();
741 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackSize, true));
742 }
743
744 if (doesCalleeRestoreStack(F.getCallingConv(),
746 // We have a non-standard ABI, so why not make full use of the stack that
747 // we're going to pop? It must be aligned to 16 B in any case.
748 StackSize = alignTo(StackSize, 16);
749
750 // If we're expected to restore the stack (e.g. fastcc), then we'll be
751 // adding a multiple of 16.
752 FuncInfo->setArgumentStackToRestore(StackSize);
753
754 // Our own callers will guarantee that the space is free by giving an
755 // aligned value to CALLSEQ_START.
756 }
757
758 // When we tail call, we need to check if the callee's arguments
759 // will fit on the caller's stack. So, whenever we lower formal arguments,
760 // we should keep track of this information, since we might lower a tail call
761 // in this function later.
762 FuncInfo->setBytesInStackArgArea(StackSize);
763
764 if (Subtarget.hasCustomCallingConv())
765 Subtarget.getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
766
767 handleMustTailForwardedRegisters(MIRBuilder, AssignFn);
768
769 // Move back to the end of the basic block.
770 MIRBuilder.setMBB(MBB);
771
772 return true;
773}
774
775/// Return true if the calling convention is one that we can guarantee TCO for.
776static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls) {
777 return (CC == CallingConv::Fast && GuaranteeTailCalls) ||
779}
780
781/// Return true if we might ever do TCO for calls with this calling convention.
783 switch (CC) {
784 case CallingConv::C:
792 return true;
793 default:
794 return false;
795 }
796}
797
798/// Returns a pair containing the fixed CCAssignFn and the vararg CCAssignFn for
799/// CC.
800static std::pair<CCAssignFn *, CCAssignFn *>
802 return {TLI.CCAssignFnForCall(CC, false), TLI.CCAssignFnForCall(CC, true)};
803}
804
805bool AArch64CallLowering::doCallerAndCalleePassArgsTheSameWay(
806 CallLoweringInfo &Info, MachineFunction &MF,
807 SmallVectorImpl<ArgInfo> &InArgs) const {
808 const Function &CallerF = MF.getFunction();
809 CallingConv::ID CalleeCC = Info.CallConv;
810 CallingConv::ID CallerCC = CallerF.getCallingConv();
811
812 // If the calling conventions match, then everything must be the same.
813 if (CalleeCC == CallerCC)
814 return true;
815
816 // Check if the caller and callee will handle arguments in the same way.
817 const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
818 CCAssignFn *CalleeAssignFnFixed;
819 CCAssignFn *CalleeAssignFnVarArg;
820 std::tie(CalleeAssignFnFixed, CalleeAssignFnVarArg) =
821 getAssignFnsForCC(CalleeCC, TLI);
822
823 CCAssignFn *CallerAssignFnFixed;
824 CCAssignFn *CallerAssignFnVarArg;
825 std::tie(CallerAssignFnFixed, CallerAssignFnVarArg) =
826 getAssignFnsForCC(CallerCC, TLI);
827
828 AArch64IncomingValueAssigner CalleeAssigner(CalleeAssignFnFixed,
829 CalleeAssignFnVarArg);
830 AArch64IncomingValueAssigner CallerAssigner(CallerAssignFnFixed,
831 CallerAssignFnVarArg);
832
833 if (!resultsCompatible(Info, MF, InArgs, CalleeAssigner, CallerAssigner))
834 return false;
835
836 // Make sure that the caller and callee preserve all of the same registers.
837 auto TRI = MF.getSubtarget<AArch64Subtarget>().getRegisterInfo();
838 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
839 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
841 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
842 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
843 }
844
845 return TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved);
846}
847
848bool AArch64CallLowering::areCalleeOutgoingArgsTailCallable(
849 CallLoweringInfo &Info, MachineFunction &MF,
850 SmallVectorImpl<ArgInfo> &OrigOutArgs) const {
851 // If there are no outgoing arguments, then we are done.
852 if (OrigOutArgs.empty())
853 return true;
854
855 const Function &CallerF = MF.getFunction();
856 LLVMContext &Ctx = CallerF.getContext();
857 CallingConv::ID CalleeCC = Info.CallConv;
858 CallingConv::ID CallerCC = CallerF.getCallingConv();
859 const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
860 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
861
862 CCAssignFn *AssignFnFixed;
863 CCAssignFn *AssignFnVarArg;
864 std::tie(AssignFnFixed, AssignFnVarArg) = getAssignFnsForCC(CalleeCC, TLI);
865
866 // We have outgoing arguments. Make sure that we can tail call with them.
868 CCState OutInfo(CalleeCC, false, MF, OutLocs, Ctx);
869
870 AArch64OutgoingValueAssigner CalleeAssigner(AssignFnFixed, AssignFnVarArg,
871 Subtarget, /*IsReturn*/ false);
872 // determineAssignments() may modify argument flags, so make a copy.
874 append_range(OutArgs, OrigOutArgs);
875 if (!determineAssignments(CalleeAssigner, OutArgs, OutInfo)) {
876 LLVM_DEBUG(dbgs() << "... Could not analyze call operands.\n");
877 return false;
878 }
879
880 // Make sure that they can fit on the caller's stack.
881 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
882 if (OutInfo.getStackSize() > FuncInfo->getBytesInStackArgArea()) {
883 LLVM_DEBUG(dbgs() << "... Cannot fit call operands on caller's stack.\n");
884 return false;
885 }
886
887 // Verify that the parameters in callee-saved registers match.
888 // TODO: Port this over to CallLowering as general code once swiftself is
889 // supported.
890 auto TRI = MF.getSubtarget<AArch64Subtarget>().getRegisterInfo();
891 const uint32_t *CallerPreservedMask = TRI->getCallPreservedMask(MF, CallerCC);
893
894 if (Info.IsVarArg) {
895 // Be conservative and disallow variadic memory operands to match SDAG's
896 // behaviour.
897 // FIXME: If the caller's calling convention is C, then we can
898 // potentially use its argument area. However, for cases like fastcc,
899 // we can't do anything.
900 for (unsigned i = 0; i < OutLocs.size(); ++i) {
901 auto &ArgLoc = OutLocs[i];
902 if (ArgLoc.isRegLoc())
903 continue;
904
906 dbgs()
907 << "... Cannot tail call vararg function with stack arguments\n");
908 return false;
909 }
910 }
911
912 return parametersInCSRMatch(MRI, CallerPreservedMask, OutLocs, OutArgs);
913}
914
916 MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info,
918 SmallVectorImpl<ArgInfo> &OutArgs) const {
919
920 // Must pass all target-independent checks in order to tail call optimize.
921 if (!Info.IsTailCall)
922 return false;
923
924 CallingConv::ID CalleeCC = Info.CallConv;
925 MachineFunction &MF = MIRBuilder.getMF();
926 const Function &CallerF = MF.getFunction();
927
928 LLVM_DEBUG(dbgs() << "Attempting to lower call as tail call\n");
929
930 if (Info.SwiftErrorVReg) {
931 // TODO: We should handle this.
932 // Note that this is also handled by the check for no outgoing arguments.
933 // Proactively disabling this though, because the swifterror handling in
934 // lowerCall inserts a COPY *after* the location of the call.
935 LLVM_DEBUG(dbgs() << "... Cannot handle tail calls with swifterror yet.\n");
936 return false;
937 }
938
939 if (!mayTailCallThisCC(CalleeCC)) {
940 LLVM_DEBUG(dbgs() << "... Calling convention cannot be tail called.\n");
941 return false;
942 }
943
944 // Byval parameters hand the function a pointer directly into the stack area
945 // we want to reuse during a tail call. Working around this *is* possible (see
946 // X86).
947 //
948 // FIXME: In AArch64ISelLowering, this isn't worked around. Can/should we try
949 // it?
950 //
951 // On Windows, "inreg" attributes signify non-aggregate indirect returns.
952 // In this case, it is necessary to save/restore X0 in the callee. Tail
953 // call opt interferes with this. So we disable tail call opt when the
954 // caller has an argument with "inreg" attribute.
955 //
956 // FIXME: Check whether the callee also has an "inreg" argument.
957 //
958 // When the caller has a swifterror argument, we don't want to tail call
959 // because would have to move into the swifterror register before the
960 // tail call.
961 if (any_of(CallerF.args(), [](const Argument &A) {
962 return A.hasByValAttr() || A.hasInRegAttr() || A.hasSwiftErrorAttr();
963 })) {
964 LLVM_DEBUG(dbgs() << "... Cannot tail call from callers with byval, "
965 "inreg, or swifterror arguments\n");
966 return false;
967 }
968
969 // Externally-defined functions with weak linkage should not be
970 // tail-called on AArch64 when the OS does not support dynamic
971 // pre-emption of symbols, as the AAELF spec requires normal calls
972 // to undefined weak functions to be replaced with a NOP or jump to the
973 // next instruction. The behaviour of branch instructions in this
974 // situation (as used for tail calls) is implementation-defined, so we
975 // cannot rely on the linker replacing the tail call with a return.
976 if (Info.Callee.isGlobal()) {
977 const GlobalValue *GV = Info.Callee.getGlobal();
978 const Triple &TT = MF.getTarget().getTargetTriple();
979 if (GV->hasExternalWeakLinkage() &&
980 (!TT.isOSWindows() || TT.isOSBinFormatELF() ||
981 TT.isOSBinFormatMachO())) {
982 LLVM_DEBUG(dbgs() << "... Cannot tail call externally-defined function "
983 "with weak linkage for this OS.\n");
984 return false;
985 }
986 }
987
988 // If we have -tailcallopt, then we're done.
990 return CalleeCC == CallerF.getCallingConv();
991
992 // We don't have -tailcallopt, so we're allowed to change the ABI (sibcall).
993 // Try to find cases where we can do that.
994
995 // I want anyone implementing a new calling convention to think long and hard
996 // about this assert.
997 assert((!Info.IsVarArg || CalleeCC == CallingConv::C) &&
998 "Unexpected variadic calling convention");
999
1000 // Verify that the incoming and outgoing arguments from the callee are
1001 // safe to tail call.
1002 if (!doCallerAndCalleePassArgsTheSameWay(Info, MF, InArgs)) {
1003 LLVM_DEBUG(
1004 dbgs()
1005 << "... Caller and callee have incompatible calling conventions.\n");
1006 return false;
1007 }
1008
1009 if (!areCalleeOutgoingArgsTailCallable(Info, MF, OutArgs))
1010 return false;
1011
1012 LLVM_DEBUG(
1013 dbgs() << "... Call is eligible for tail call optimization.\n");
1014 return true;
1015}
1016
1017static unsigned getCallOpcode(const MachineFunction &CallerF, bool IsIndirect,
1018 bool IsTailCall,
1019 std::optional<CallLowering::PtrAuthInfo> &PAI,
1021 const AArch64FunctionInfo *FuncInfo = CallerF.getInfo<AArch64FunctionInfo>();
1022
1023 if (!IsTailCall) {
1024 if (!PAI)
1025 return IsIndirect ? getBLRCallOpcode(CallerF) : (unsigned)AArch64::BL;
1026
1027 assert(IsIndirect && "Direct call should not be authenticated");
1028 assert((PAI->Key == AArch64PACKey::IA || PAI->Key == AArch64PACKey::IB) &&
1029 "Invalid auth call key");
1030 return AArch64::BLRA;
1031 }
1032
1033 if (!IsIndirect)
1034 return AArch64::TCRETURNdi;
1035
1036 // When BTI or PAuthLR are enabled, there are restrictions on using x16 and
1037 // x17 to hold the function pointer.
1038 if (FuncInfo->branchTargetEnforcement()) {
1039 if (FuncInfo->branchProtectionPAuthLR()) {
1040 assert(!PAI && "ptrauth tail-calls not yet supported with PAuthLR");
1041 return AArch64::TCRETURNrix17;
1042 }
1043 if (PAI)
1044 return AArch64::AUTH_TCRETURN_BTI;
1045 return AArch64::TCRETURNrix16x17;
1046 }
1047
1048 if (FuncInfo->branchProtectionPAuthLR()) {
1049 assert(!PAI && "ptrauth tail-calls not yet supported with PAuthLR");
1050 return AArch64::TCRETURNrinotx16;
1051 }
1052
1053 if (PAI)
1054 return AArch64::AUTH_TCRETURN;
1055 return AArch64::TCRETURNri;
1056}
1057
1058static const uint32_t *
1062 const uint32_t *Mask;
1063 if (!OutArgs.empty() && OutArgs[0].Flags[0].isReturned()) {
1064 // For 'this' returns, use the X0-preserving mask if applicable
1065 Mask = TRI.getThisReturnPreservedMask(MF, Info.CallConv);
1066 if (!Mask) {
1067 OutArgs[0].Flags[0].setReturned(false);
1068 Mask = TRI.getCallPreservedMask(MF, Info.CallConv);
1069 }
1070 } else {
1071 Mask = TRI.getCallPreservedMask(MF, Info.CallConv);
1072 }
1073 return Mask;
1074}
1075
1076bool AArch64CallLowering::lowerTailCall(
1077 MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info,
1078 SmallVectorImpl<ArgInfo> &OutArgs) const {
1079 MachineFunction &MF = MIRBuilder.getMF();
1080 const Function &F = MF.getFunction();
1082 const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
1084
1085 // True when we're tail calling, but without -tailcallopt.
1086 bool IsSibCall = !MF.getTarget().Options.GuaranteedTailCallOpt &&
1087 Info.CallConv != CallingConv::Tail &&
1088 Info.CallConv != CallingConv::SwiftTail;
1089
1090 // Find out which ABI gets to decide where things go.
1091 CallingConv::ID CalleeCC = Info.CallConv;
1092 CCAssignFn *AssignFnFixed;
1093 CCAssignFn *AssignFnVarArg;
1094 std::tie(AssignFnFixed, AssignFnVarArg) = getAssignFnsForCC(CalleeCC, TLI);
1095
1096 MachineInstrBuilder CallSeqStart;
1097 if (!IsSibCall)
1098 CallSeqStart = MIRBuilder.buildInstr(AArch64::ADJCALLSTACKDOWN);
1099
1100 unsigned Opc = getCallOpcode(MF, Info.Callee.isReg(), true, Info.PAI, MRI);
1101 auto MIB = MIRBuilder.buildInstrNoInsert(Opc);
1102 MIB.add(Info.Callee);
1103
1104 // Tell the call which registers are clobbered.
1105 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1106 auto TRI = Subtarget.getRegisterInfo();
1107
1108 // Byte offset for the tail call. When we are sibcalling, this will always
1109 // be 0.
1110 MIB.addImm(0);
1111
1112 // Authenticated tail calls always take key/discriminator arguments.
1113 if (Opc == AArch64::AUTH_TCRETURN || Opc == AArch64::AUTH_TCRETURN_BTI) {
1114 assert((Info.PAI->Key == AArch64PACKey::IA ||
1115 Info.PAI->Key == AArch64PACKey::IB) &&
1116 "Invalid auth call key");
1117 MIB.addImm(Info.PAI->Key);
1118
1119 Register AddrDisc = 0;
1120 uint16_t IntDisc = 0;
1121 std::tie(IntDisc, AddrDisc) =
1122 extractPtrauthBlendDiscriminators(Info.PAI->Discriminator, MRI);
1123
1124 MIB.addImm(IntDisc);
1125 MIB.addUse(AddrDisc);
1126 if (AddrDisc != AArch64::NoRegister) {
1127 MIB->getOperand(4).setReg(constrainOperandRegClass(
1128 MF, *TRI, MRI, *MF.getSubtarget().getInstrInfo(),
1129 *MF.getSubtarget().getRegBankInfo(), *MIB, MIB->getDesc(),
1130 MIB->getOperand(4), 4));
1131 }
1132 }
1133
1134 // Tell the call which registers are clobbered.
1135 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CalleeCC);
1136 if (Subtarget.hasCustomCallingConv())
1137 TRI->UpdateCustomCallPreservedMask(MF, &Mask);
1138 MIB.addRegMask(Mask);
1139
1140 if (Info.CFIType)
1141 MIB->setCFIType(MF, Info.CFIType->getZExtValue());
1142
1143 if (TRI->isAnyArgRegReserved(MF))
1144 TRI->emitReservedArgRegCallError(MF);
1145
1146 // FPDiff is the byte offset of the call's argument area from the callee's.
1147 // Stores to callee stack arguments will be placed in FixedStackSlots offset
1148 // by this amount for a tail call. In a sibling call it must be 0 because the
1149 // caller will deallocate the entire stack and the callee still expects its
1150 // arguments to begin at SP+0.
1151 int FPDiff = 0;
1152
1153 // This will be 0 for sibcalls, potentially nonzero for tail calls produced
1154 // by -tailcallopt. For sibcalls, the memory operands for the call are
1155 // already available in the caller's incoming argument space.
1156 unsigned NumBytes = 0;
1157 if (!IsSibCall) {
1158 // We aren't sibcalling, so we need to compute FPDiff. We need to do this
1159 // before handling assignments, because FPDiff must be known for memory
1160 // arguments.
1161 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
1163 CCState OutInfo(CalleeCC, false, MF, OutLocs, F.getContext());
1164
1165 AArch64OutgoingValueAssigner CalleeAssigner(AssignFnFixed, AssignFnVarArg,
1166 Subtarget, /*IsReturn*/ false);
1167 if (!determineAssignments(CalleeAssigner, OutArgs, OutInfo))
1168 return false;
1169
1170 // The callee will pop the argument stack as a tail call. Thus, we must
1171 // keep it 16-byte aligned.
1172 NumBytes = alignTo(OutInfo.getStackSize(), 16);
1173
1174 // FPDiff will be negative if this tail call requires more space than we
1175 // would automatically have in our incoming argument space. Positive if we
1176 // actually shrink the stack.
1177 FPDiff = NumReusableBytes - NumBytes;
1178
1179 // Update the required reserved area if this is the tail call requiring the
1180 // most argument stack space.
1181 if (FPDiff < 0 && FuncInfo->getTailCallReservedStack() < (unsigned)-FPDiff)
1182 FuncInfo->setTailCallReservedStack(-FPDiff);
1183
1184 // The stack pointer must be 16-byte aligned at all times it's used for a
1185 // memory operation, which in practice means at *all* times and in
1186 // particular across call boundaries. Therefore our own arguments started at
1187 // a 16-byte aligned SP and the delta applied for the tail call should
1188 // satisfy the same constraint.
1189 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
1190 }
1191
1192 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
1193
1194 AArch64OutgoingValueAssigner Assigner(AssignFnFixed, AssignFnVarArg,
1195 Subtarget, /*IsReturn*/ false);
1196
1197 // Do the actual argument marshalling.
1198 OutgoingArgHandler Handler(MIRBuilder, MRI, MIB,
1199 /*IsTailCall*/ true, FPDiff);
1200 if (!determineAndHandleAssignments(Handler, Assigner, OutArgs, MIRBuilder,
1201 CalleeCC, Info.IsVarArg))
1202 return false;
1203
1204 Mask = getMaskForArgs(OutArgs, Info, *TRI, MF);
1205
1206 if (Info.IsVarArg && Info.IsMustTailCall) {
1207 // Now we know what's being passed to the function. Add uses to the call for
1208 // the forwarded registers that we *aren't* passing as parameters. This will
1209 // preserve the copies we build earlier.
1210 for (const auto &F : Forwards) {
1211 Register ForwardedReg = F.PReg;
1212 // If the register is already passed, or aliases a register which is
1213 // already being passed, then skip it.
1214 if (any_of(MIB->uses(), [&ForwardedReg, &TRI](const MachineOperand &Use) {
1215 if (!Use.isReg())
1216 return false;
1217 return TRI->regsOverlap(Use.getReg(), ForwardedReg);
1218 }))
1219 continue;
1220
1221 // We aren't passing it already, so we should add it to the call.
1222 MIRBuilder.buildCopy(ForwardedReg, Register(F.VReg));
1223 MIB.addReg(ForwardedReg, RegState::Implicit);
1224 }
1225 }
1226
1227 // If we have -tailcallopt, we need to adjust the stack. We'll do the call
1228 // sequence start and end here.
1229 if (!IsSibCall) {
1230 MIB->getOperand(1).setImm(FPDiff);
1231 CallSeqStart.addImm(0).addImm(0);
1232 // End the call sequence *before* emitting the call. Normally, we would
1233 // tidy the frame up after the call. However, here, we've laid out the
1234 // parameters so that when SP is reset, they will be in the correct
1235 // location.
1236 MIRBuilder.buildInstr(AArch64::ADJCALLSTACKUP).addImm(0).addImm(0);
1237 }
1238
1239 // Now we can add the actual call instruction to the correct basic block.
1240 MIRBuilder.insertInstr(MIB);
1241
1242 // If Callee is a reg, since it is used by a target specific instruction,
1243 // it must have a register class matching the constraint of that instruction.
1244 if (MIB->getOperand(0).isReg())
1246 *MF.getSubtarget().getRegBankInfo(), *MIB,
1247 MIB->getDesc(), MIB->getOperand(0), 0);
1248
1250 Info.LoweredTailCall = true;
1251 return true;
1252}
1253
1255 CallLoweringInfo &Info) const {
1256 MachineFunction &MF = MIRBuilder.getMF();
1257 const Function &F = MF.getFunction();
1259 auto &DL = F.getParent()->getDataLayout();
1260 const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
1261 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1262
1263 // Arm64EC has extra requirements for varargs calls; bail out for now.
1264 //
1265 // Arm64EC has special mangling rules for calls; bail out on all calls for
1266 // now.
1267 if (Subtarget.isWindowsArm64EC())
1268 return false;
1269
1270 // Arm64EC thunks have a special calling convention which is only implemented
1271 // in SelectionDAG; bail out for now.
1272 if (Info.CallConv == CallingConv::ARM64EC_Thunk_Native ||
1274 return false;
1275
1277 for (auto &OrigArg : Info.OrigArgs) {
1278 splitToValueTypes(OrigArg, OutArgs, DL, Info.CallConv);
1279 // AAPCS requires that we zero-extend i1 to 8 bits by the caller.
1280 auto &Flags = OrigArg.Flags[0];
1281 if (OrigArg.Ty->isIntegerTy(1) && !Flags.isSExt() && !Flags.isZExt()) {
1282 ArgInfo &OutArg = OutArgs.back();
1283 assert(OutArg.Regs.size() == 1 &&
1284 MRI.getType(OutArg.Regs[0]).getSizeInBits() == 1 &&
1285 "Unexpected registers used for i1 arg");
1286
1287 // We cannot use a ZExt ArgInfo flag here, because it will
1288 // zero-extend the argument to i32 instead of just i8.
1289 OutArg.Regs[0] =
1290 MIRBuilder.buildZExt(LLT::scalar(8), OutArg.Regs[0]).getReg(0);
1291 LLVMContext &Ctx = MF.getFunction().getContext();
1292 OutArg.Ty = Type::getInt8Ty(Ctx);
1293 }
1294 }
1295
1297 if (!Info.OrigRet.Ty->isVoidTy())
1298 splitToValueTypes(Info.OrigRet, InArgs, DL, Info.CallConv);
1299
1300 // If we can lower as a tail call, do that instead.
1301 bool CanTailCallOpt =
1302 isEligibleForTailCallOptimization(MIRBuilder, Info, InArgs, OutArgs);
1303
1304 // We must emit a tail call if we have musttail.
1305 if (Info.IsMustTailCall && !CanTailCallOpt) {
1306 // There are types of incoming/outgoing arguments we can't handle yet, so
1307 // it doesn't make sense to actually die here like in ISelLowering. Instead,
1308 // fall back to SelectionDAG and let it try to handle this.
1309 LLVM_DEBUG(dbgs() << "Failed to lower musttail call as tail call\n");
1310 return false;
1311 }
1312
1313 Info.IsTailCall = CanTailCallOpt;
1314 if (CanTailCallOpt)
1315 return lowerTailCall(MIRBuilder, Info, OutArgs);
1316
1317 // Find out which ABI gets to decide where things go.
1318 CCAssignFn *AssignFnFixed;
1319 CCAssignFn *AssignFnVarArg;
1320 std::tie(AssignFnFixed, AssignFnVarArg) =
1321 getAssignFnsForCC(Info.CallConv, TLI);
1322
1323 MachineInstrBuilder CallSeqStart;
1324 CallSeqStart = MIRBuilder.buildInstr(AArch64::ADJCALLSTACKDOWN);
1325
1326 // Create a temporarily-floating call instruction so we can add the implicit
1327 // uses of arg registers.
1328
1329 unsigned Opc = 0;
1330 // Calls with operand bundle "clang.arc.attachedcall" are special. They should
1331 // be expanded to the call, directly followed by a special marker sequence and
1332 // a call to an ObjC library function.
1334 Opc = Info.PAI ? AArch64::BLRA_RVMARKER : AArch64::BLR_RVMARKER;
1335 // A call to a returns twice function like setjmp must be followed by a bti
1336 // instruction.
1337 else if (Info.CB && Info.CB->hasFnAttr(Attribute::ReturnsTwice) &&
1338 !Subtarget.noBTIAtReturnTwice() &&
1340 Opc = AArch64::BLR_BTI;
1341 else {
1342 // For an intrinsic call (e.g. memset), use GOT if "RtLibUseGOT" (-fno-plt)
1343 // is set.
1344 if (Info.Callee.isSymbol() && F.getParent()->getRtLibUseGOT()) {
1345 auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_GLOBAL_VALUE);
1346 DstOp(getLLTForType(*F.getType(), DL)).addDefToMIB(MRI, MIB);
1347 MIB.addExternalSymbol(Info.Callee.getSymbolName(), AArch64II::MO_GOT);
1348 Info.Callee = MachineOperand::CreateReg(MIB.getReg(0), false);
1349 }
1350 Opc = getCallOpcode(MF, Info.Callee.isReg(), false, Info.PAI, MRI);
1351 }
1352
1353 auto MIB = MIRBuilder.buildInstrNoInsert(Opc);
1354 unsigned CalleeOpNo = 0;
1355
1356 if (Opc == AArch64::BLR_RVMARKER || Opc == AArch64::BLRA_RVMARKER) {
1357 // Add a target global address for the retainRV/claimRV runtime function
1358 // just before the call target.
1360 MIB.addGlobalAddress(ARCFn);
1361 ++CalleeOpNo;
1362 } else if (Info.CFIType) {
1363 MIB->setCFIType(MF, Info.CFIType->getZExtValue());
1364 }
1365
1366 MIB.add(Info.Callee);
1367
1368 // Tell the call which registers are clobbered.
1369 const uint32_t *Mask;
1370 const auto *TRI = Subtarget.getRegisterInfo();
1371
1372 AArch64OutgoingValueAssigner Assigner(AssignFnFixed, AssignFnVarArg,
1373 Subtarget, /*IsReturn*/ false);
1374 // Do the actual argument marshalling.
1375 OutgoingArgHandler Handler(MIRBuilder, MRI, MIB, /*IsReturn*/ false);
1376 if (!determineAndHandleAssignments(Handler, Assigner, OutArgs, MIRBuilder,
1377 Info.CallConv, Info.IsVarArg))
1378 return false;
1379
1380 Mask = getMaskForArgs(OutArgs, Info, *TRI, MF);
1381
1382 if (Opc == AArch64::BLRA || Opc == AArch64::BLRA_RVMARKER) {
1383 assert((Info.PAI->Key == AArch64PACKey::IA ||
1384 Info.PAI->Key == AArch64PACKey::IB) &&
1385 "Invalid auth call key");
1386 MIB.addImm(Info.PAI->Key);
1387
1388 Register AddrDisc = 0;
1389 uint16_t IntDisc = 0;
1390 std::tie(IntDisc, AddrDisc) =
1391 extractPtrauthBlendDiscriminators(Info.PAI->Discriminator, MRI);
1392
1393 MIB.addImm(IntDisc);
1394 MIB.addUse(AddrDisc);
1395 if (AddrDisc != AArch64::NoRegister) {
1397 *MF.getSubtarget().getRegBankInfo(), *MIB,
1398 MIB->getDesc(), MIB->getOperand(CalleeOpNo + 3),
1399 CalleeOpNo + 3);
1400 }
1401 }
1402
1403 // Tell the call which registers are clobbered.
1405 TRI->UpdateCustomCallPreservedMask(MF, &Mask);
1406 MIB.addRegMask(Mask);
1407
1408 if (TRI->isAnyArgRegReserved(MF))
1409 TRI->emitReservedArgRegCallError(MF);
1410
1411 // Now we can add the actual call instruction to the correct basic block.
1412 MIRBuilder.insertInstr(MIB);
1413
1414 uint64_t CalleePopBytes =
1417 ? alignTo(Assigner.StackSize, 16)
1418 : 0;
1419
1420 CallSeqStart.addImm(Assigner.StackSize).addImm(0);
1421 MIRBuilder.buildInstr(AArch64::ADJCALLSTACKUP)
1422 .addImm(Assigner.StackSize)
1423 .addImm(CalleePopBytes);
1424
1425 // If Callee is a reg, since it is used by a target specific
1426 // instruction, it must have a register class matching the
1427 // constraint of that instruction.
1428 if (MIB->getOperand(CalleeOpNo).isReg())
1429 constrainOperandRegClass(MF, *TRI, MRI, *Subtarget.getInstrInfo(),
1430 *Subtarget.getRegBankInfo(), *MIB, MIB->getDesc(),
1431 MIB->getOperand(CalleeOpNo), CalleeOpNo);
1432
1433 // Finally we can copy the returned value back into its virtual-register. In
1434 // symmetry with the arguments, the physical register must be an
1435 // implicit-define of the call instruction.
1436 if (Info.CanLowerReturn && !Info.OrigRet.Ty->isVoidTy()) {
1437 CCAssignFn *RetAssignFn = TLI.CCAssignFnForReturn(Info.CallConv);
1438 CallReturnHandler Handler(MIRBuilder, MRI, MIB);
1439 bool UsingReturnedArg =
1440 !OutArgs.empty() && OutArgs[0].Flags[0].isReturned();
1441
1442 AArch64OutgoingValueAssigner Assigner(RetAssignFn, RetAssignFn, Subtarget,
1443 /*IsReturn*/ false);
1444 ReturnedArgCallReturnHandler ReturnedArgHandler(MIRBuilder, MRI, MIB);
1446 UsingReturnedArg ? ReturnedArgHandler : Handler, Assigner, InArgs,
1447 MIRBuilder, Info.CallConv, Info.IsVarArg,
1448 UsingReturnedArg ? ArrayRef(OutArgs[0].Regs) : std::nullopt))
1449 return false;
1450 }
1451
1452 if (Info.SwiftErrorVReg) {
1453 MIB.addDef(AArch64::X21, RegState::Implicit);
1454 MIRBuilder.buildCopy(Info.SwiftErrorVReg, Register(AArch64::X21));
1455 }
1456
1457 if (!Info.CanLowerReturn) {
1458 insertSRetLoads(MIRBuilder, Info.OrigRet.Ty, Info.OrigRet.Regs,
1459 Info.DemoteRegister, Info.DemoteStackIndex);
1460 }
1461 return true;
1462}
1463
1465 return Ty.getSizeInBits() == 64;
1466}
unsigned const MachineRegisterInfo * MRI
static void handleMustTailForwardedRegisters(MachineIRBuilder &MIRBuilder, CCAssignFn *AssignFn)
Helper function to compute forwarded registers for musttail calls.
static unsigned getCallOpcode(const MachineFunction &CallerF, bool IsIndirect, bool IsTailCall, std::optional< CallLowering::PtrAuthInfo > &PAI, MachineRegisterInfo &MRI)
static LLT getStackValueStoreTypeHack(const CCValAssign &VA)
static const uint32_t * getMaskForArgs(SmallVectorImpl< AArch64CallLowering::ArgInfo > &OutArgs, AArch64CallLowering::CallLoweringInfo &Info, const AArch64RegisterInfo &TRI, MachineFunction &MF)
static void applyStackPassedSmallTypeDAGHack(EVT OrigVT, MVT &ValVT, MVT &LocVT)
static std::pair< CCAssignFn *, CCAssignFn * > getAssignFnsForCC(CallingConv::ID CC, const AArch64TargetLowering &TLI)
Returns a pair containing the fixed CCAssignFn and the vararg CCAssignFn for CC.
static bool doesCalleeRestoreStack(CallingConv::ID CallConv, bool TailCallOpt)
This file describes how to lower LLVM calls to machine code calls.
#define Success
static std::tuple< SDValue, SDValue > extractPtrauthBlendDiscriminators(SDValue Disc, SelectionDAG *DAG)
static const MCPhysReg GPRArgRegs[]
static const MCPhysReg FPRArgRegs[]
static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls)
Return true if the calling convention is one that we can guarantee TCO for.
static bool mayTailCallThisCC(CallingConv::ID CC)
Return true if we might ever do TCO for calls with this calling convention.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
#define LLVM_DEBUG(X)
Definition: Debug.h:101
uint64_t Addr
uint64_t Size
Implement a low-level type suitable for MachineInstr level instruction selection.
#define F(x, y, z)
Definition: MD5.cpp:55
This file declares the MachineIRBuilder class.
unsigned const TargetRegisterInfo * TRI
static unsigned getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
This file defines ARC utility functions which are used by various parts of the compiler.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
bool lowerReturn(MachineIRBuilder &MIRBuilder, const Value *Val, ArrayRef< Register > VRegs, FunctionLoweringInfo &FLI, Register SwiftErrorVReg) const override
This hook must be implemented to lower outgoing return values, described by Val, into the specified v...
bool canLowerReturn(MachineFunction &MF, CallingConv::ID CallConv, SmallVectorImpl< BaseArgInfo > &Outs, bool IsVarArg) const override
This hook must be implemented to check whether the return values described by Outs can fit into the r...
bool fallBackToDAGISel(const MachineFunction &MF) const override
bool isTypeIsValidForThisReturn(EVT Ty) const override
For targets which support the "returned" parameter attribute, returns true if the given type is a val...
bool isEligibleForTailCallOptimization(MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info, SmallVectorImpl< ArgInfo > &InArgs, SmallVectorImpl< ArgInfo > &OutArgs) const
Returns true if the call can be lowered as a tail call.
AArch64CallLowering(const AArch64TargetLowering &TLI)
bool lowerCall(MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info) const override
This hook must be implemented to lower the given call instruction, including argument and return valu...
bool lowerFormalArguments(MachineIRBuilder &MIRBuilder, const Function &F, ArrayRef< ArrayRef< Register > > VRegs, FunctionLoweringInfo &FLI) const override
This hook must be implemented to lower the incoming (formal) arguments, described by VRegs,...
AArch64FunctionInfo - This class is derived from MachineFunctionInfo and contains private AArch64-spe...
void setTailCallReservedStack(unsigned bytes)
SmallVectorImpl< ForwardedRegister > & getForwardedMustTailRegParms()
void setBytesInStackArgArea(unsigned bytes)
void setArgumentStackToRestore(unsigned bytes)
const AArch64RegisterInfo * getRegisterInfo() const override
const AArch64InstrInfo * getInstrInfo() const override
bool isCallingConvWin64(CallingConv::ID CC) const
const RegisterBankInfo * getRegBankInfo() const override
bool hasCustomCallingConv() const
MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const override
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const override
Certain targets require unusual breakdowns of certain types.
CCAssignFn * CCAssignFnForReturn(CallingConv::ID CC) const
Selects the correct CCAssignFn for a given CallingConvention value.
CCAssignFn * CCAssignFnForCall(CallingConv::ID CC, bool IsVarArg) const
Selects the correct CCAssignFn for a given CallingConvention value.
This class represents an incoming formal argument to a Function.
Definition: Argument.h:31
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:160
CCState - This class holds information needed while lowering arguments and return values.
unsigned getFirstUnallocated(ArrayRef< MCPhysReg > Regs) const
getFirstUnallocated - Return the index of the first unallocated register in the set,...
void analyzeMustTailForwardedRegisters(SmallVectorImpl< ForwardedRegister > &Forwards, ArrayRef< MVT > RegParmTypes, CCAssignFn Fn)
Compute the set of registers that need to be preserved and forwarded to any musttail calls.
CallingConv::ID getCallingConv() const
uint64_t getStackSize() const
Returns the size of the currently allocated portion of the stack.
bool isVarArg() const
bool isAllocated(MCRegister Reg) const
isAllocated - Return true if the specified register (or an alias) is allocated.
CCValAssign - Represent assignment of one arg/retval to a location.
LocInfo getLocInfo() const
static CCValAssign getReg(unsigned ValNo, MVT ValVT, unsigned RegNo, MVT LocVT, LocInfo HTP, bool IsCustom=false)
bool handleAssignments(ValueHandler &Handler, SmallVectorImpl< ArgInfo > &Args, CCState &CCState, SmallVectorImpl< CCValAssign > &ArgLocs, MachineIRBuilder &MIRBuilder, ArrayRef< Register > ThisReturnRegs=std::nullopt) const
Use Handler to insert code to handle the argument/return values represented by Args.
void insertSRetLoads(MachineIRBuilder &MIRBuilder, Type *RetTy, ArrayRef< Register > VRegs, Register DemoteReg, int FI) const
Load the returned value from the stack into virtual registers in VRegs.
bool determineAndHandleAssignments(ValueHandler &Handler, ValueAssigner &Assigner, SmallVectorImpl< ArgInfo > &Args, MachineIRBuilder &MIRBuilder, CallingConv::ID CallConv, bool IsVarArg, ArrayRef< Register > ThisReturnRegs=std::nullopt) const
Invoke ValueAssigner::assignArg on each of the given Args and then use Handler to move them to the as...
bool resultsCompatible(CallLoweringInfo &Info, MachineFunction &MF, SmallVectorImpl< ArgInfo > &InArgs, ValueAssigner &CalleeAssigner, ValueAssigner &CallerAssigner) const
void splitToValueTypes(const ArgInfo &OrigArgInfo, SmallVectorImpl< ArgInfo > &SplitArgs, const DataLayout &DL, CallingConv::ID CallConv, SmallVectorImpl< uint64_t > *Offsets=nullptr) const
Break OrigArgInfo into one or more pieces the calling convention can process, returned in SplitArgs.
void insertSRetIncomingArgument(const Function &F, SmallVectorImpl< ArgInfo > &SplitArgs, Register &DemoteReg, MachineRegisterInfo &MRI, const DataLayout &DL) const
Insert the hidden sret ArgInfo to the beginning of SplitArgs.
void insertSRetStores(MachineIRBuilder &MIRBuilder, Type *RetTy, ArrayRef< Register > VRegs, Register DemoteReg) const
Store the return value given by VRegs into stack starting at the offset specified in DemoteReg.
bool parametersInCSRMatch(const MachineRegisterInfo &MRI, const uint32_t *CallerPreservedMask, const SmallVectorImpl< CCValAssign > &ArgLocs, const SmallVectorImpl< ArgInfo > &OutVals) const
Check whether parameters to a call that are passed in callee saved registers are the same as from the...
bool determineAssignments(ValueAssigner &Assigner, SmallVectorImpl< ArgInfo > &Args, CCState &CCInfo) const
Analyze the argument list in Args, using Assigner to populate CCInfo.
bool checkReturn(CCState &CCInfo, SmallVectorImpl< BaseArgInfo > &Outs, CCAssignFn *Fn) const
void setArgFlags(ArgInfo &Arg, unsigned OpIdx, const DataLayout &DL, const FuncInfoTy &FuncInfo) const
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
void addDefToMIB(MachineRegisterInfo &MRI, MachineInstrBuilder &MIB) const
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
Register DemoteRegister
DemoteRegister - if CanLowerReturn is false, DemoteRegister is a vreg allocated to hold a pointer to ...
bool CanLowerReturn
CanLowerReturn - true iff the function's return value can be lowered to registers.
iterator_range< arg_iterator > args()
Definition: Function.h:845
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:264
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:356
bool hasExternalWeakLinkage() const
Definition: GlobalValue.h:528
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
Definition: LowLevelType.h:42
constexpr uint16_t getNumElements() const
Returns the number of elements in a vector LLT.
Definition: LowLevelType.h:159
constexpr bool isVector() const
Definition: LowLevelType.h:148
static constexpr LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
Definition: LowLevelType.h:57
constexpr TypeSize getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
Definition: LowLevelType.h:193
constexpr TypeSize getSizeInBytes() const
Returns the total size of the type in bytes, i.e.
Definition: LowLevelType.h:203
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:33
Machine Value Type.
bool isVector() const
Return true if this is a vector value type.
static MVT getVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
Definition: ValueTypes.cpp:588
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
void setHasTailCall(bool V=true)
bool hasMustTailInVarArgFunc() const
Returns true if the function is variadic and contains a musttail call.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy, Align base_alignment, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr, SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
Helper class to build MachineInstr.
MachineInstrBuilder insertInstr(MachineInstrBuilder MIB)
Insert an existing instruction at the insertion point.
MachineInstrBuilder buildZExt(const DstOp &Res, const SrcOp &Op, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_ZEXT Op.
void setInstr(MachineInstr &MI)
Set the insertion point to before MI.
MachineInstrBuilder buildAssertZExt(const DstOp &Res, const SrcOp &Op, unsigned Size)
Build and insert Res = G_ASSERT_ZEXT Op, Size.
MachineInstrBuilder buildPtrAdd(const DstOp &Res, const SrcOp &Op0, const SrcOp &Op1, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_PTR_ADD Op0, Op1.
MachineInstrBuilder buildStore(const SrcOp &Val, const SrcOp &Addr, MachineMemOperand &MMO)
Build and insert G_STORE Val, Addr, MMO.
MachineInstrBuilder buildInstr(unsigned Opcode)
Build and insert <empty> = Opcode <empty>.
MachineInstrBuilder buildPadVectorWithUndefElements(const DstOp &Res, const SrcOp &Op0)
Build and insert a, b, ..., x = G_UNMERGE_VALUES Op0 Res = G_BUILD_VECTOR a, b, .....
MachineInstrBuilder buildFrameIndex(const DstOp &Res, int Idx)
Build and insert Res = G_FRAME_INDEX Idx.
MachineFunction & getMF()
Getter for the function we currently build.
MachineInstrBuilder buildTrunc(const DstOp &Res, const SrcOp &Op, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_TRUNC Op.
const MachineBasicBlock & getMBB() const
Getter for the basic block we currently build.
void setMBB(MachineBasicBlock &MBB)
Set the insertion point to the end of MBB.
MachineRegisterInfo * getMRI()
Getter for MRI.
MachineInstrBuilder buildInstrNoInsert(unsigned Opcode)
Build but don't insert <empty> = Opcode <empty>.
MachineInstrBuilder buildCopy(const DstOp &Res, const SrcOp &Op)
Build and insert Res = COPY Op.
virtual MachineInstrBuilder buildConstant(const DstOp &Res, const ConstantInt &Val)
Build and insert Res = G_CONSTANT Val.
Register getReg(unsigned Idx) const
Get the register for the operand index.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addDef(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register definition operand.
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:574
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
MachineOperand class - Representation of each machine instruction operand.
void setImm(int64_t immVal)
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,...
void addLiveIn(MCRegister Reg, Register vreg=Register())
addLiveIn - Add the specified register as a live-in.
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
SMEAttrs is a utility class to parse the SME ACLE attributes on functions.
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
const Triple & getTargetTriple() const
TargetOptions Options
unsigned GuaranteedTailCallOpt
GuaranteedTailCallOpt - This flag is enabled when -tailcallopt is specified on the commandline.
virtual const RegisterBankInfo * getRegBankInfo() const
If the information for the register banks is available, return it.
virtual const TargetInstrInfo * getInstrInfo() const
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:129
static IntegerType * getInt8Ty(LLVMContext &C)
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
unsigned getNumOperands() const
Definition: User.h:191
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
@ MO_GOT
MO_GOT - This flag indicates that a symbol operand represents the address of the GOT entry for the sy...
ArrayRef< MCPhysReg > getFPRArgRegs()
ArrayRef< MCPhysReg > getGPRArgRegs()
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.
Definition: BitmaskEnum.h:121
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ ARM64EC_Thunk_Native
Calling convention used in the ARM64EC ABI to implement calls between ARM64 code and thunks.
Definition: CallingConv.h:265
@ Swift
Calling convention for Swift.
Definition: CallingConv.h:69
@ PreserveMost
Used for runtime calls that preserves most registers.
Definition: CallingConv.h:63
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
Definition: CallingConv.h:66
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition: CallingConv.h:41
@ PreserveNone
Used for runtime calls that preserves none general registers.
Definition: CallingConv.h:90
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition: CallingConv.h:76
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
Definition: CallingConv.h:87
@ ARM64EC_Thunk_X64
Calling convention used in the ARM64EC ABI to implement calls between x64 code and thunks.
Definition: CallingConv.h:260
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ Implicit
Not emitted register (e.g. carry, or temporary result).
std::optional< Function * > getAttachedARCFunction(const CallBase *CB)
This function returns operand bundle clang_arc_attachedcall's argument, which is the address of the A...
Definition: ObjCARCUtil.h:43
bool hasAttachedCallOpBundle(const CallBase *CB)
Definition: ObjCARCUtil.h:29
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:456
Register constrainOperandRegClass(const MachineFunction &MF, const TargetRegisterInfo &TRI, MachineRegisterInfo &MRI, const TargetInstrInfo &TII, const RegisterBankInfo &RBI, MachineInstr &InsertPt, const TargetRegisterClass &RegClass, MachineOperand &RegMO)
Constrain the Register operand OpIdx, so that it is now constrained to the TargetRegisterClass passed...
Definition: Utils.cpp:56
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2067
unsigned getBLRCallOpcode(const MachineFunction &MF)
Return opcode to be used for indirect calls.
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:1729
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
bool CCAssignFn(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, CCState &State)
CCAssignFn - This function assigns a location for Val, updating State to reflect the change.
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
void ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL, Type *Ty, SmallVectorImpl< EVT > &ValueVTs, SmallVectorImpl< EVT > *MemVTs, SmallVectorImpl< TypeSize > *Offsets=nullptr, TypeSize StartingOffset=TypeSize::getZero())
ComputeValueVTs - Given an LLVM IR type, compute a sequence of EVTs that represent all the individual...
Definition: Analysis.cpp:79
LLT getLLTForType(Type &Ty, const DataLayout &DL)
Construct a low-level type based on an LLVM type.
Align inferAlignFromPtrInfo(MachineFunction &MF, const MachinePointerInfo &MPO)
Definition: Utils.cpp:880
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
SmallVector< Register, 4 > Regs
Definition: CallLowering.h:63
SmallVector< ISD::ArgFlagsTy, 4 > Flags
Definition: CallLowering.h:51
Base class for ValueHandlers used for arguments coming into the current function, or for return value...
Definition: CallLowering.h:331
void assignValueToReg(Register ValVReg, Register PhysReg, const CCValAssign &VA) override
Provides a default implementation for argument handling.
Base class for ValueHandlers used for arguments passed to a function call, or for return values.
Definition: CallLowering.h:347
MachineRegisterInfo & MRI
Definition: CallLowering.h:244
virtual LLT getStackValueStoreType(const DataLayout &DL, const CCValAssign &VA, ISD::ArgFlagsTy Flags) const
Return the in-memory size to write for the argument at VA.
Extended Value Type.
Definition: ValueTypes.h:34
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition: ValueTypes.h:358
Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
Definition: ValueTypes.cpp:203
Describes a register that needs to be forwarded from the prologue to a musttail call.
This class contains a discriminated union of information about pointers in memory operands,...
static MachinePointerInfo getStack(MachineFunction &MF, int64_t Offset, uint8_t ID=0)
Stack pointer relative access.
static MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.