xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64CallLowering.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
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"
16 #include "AArch64ISelLowering.h"
17 #include "AArch64MachineFunctionInfo.h"
18 #include "AArch64RegisterInfo.h"
19 #include "AArch64Subtarget.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/Analysis/ObjCARCUtil.h"
23 #include "llvm/CodeGen/Analysis.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/FunctionLoweringInfo.h"
26 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
27 #include "llvm/CodeGen/GlobalISel/Utils.h"
28 #include "llvm/CodeGen/LowLevelTypeUtils.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineMemOperand.h"
34 #include "llvm/CodeGen/MachineOperand.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/MachineValueType.h"
37 #include "llvm/CodeGen/TargetRegisterInfo.h"
38 #include "llvm/CodeGen/TargetSubtargetInfo.h"
39 #include "llvm/CodeGen/ValueTypes.h"
40 #include "llvm/IR/Argument.h"
41 #include "llvm/IR/Attributes.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/IR/Value.h"
45 #include <algorithm>
46 #include <cassert>
47 #include <cstdint>
48 #include <iterator>
49 
50 #define DEBUG_TYPE "aarch64-call-lowering"
51 
52 using namespace llvm;
53 
54 AArch64CallLowering::AArch64CallLowering(const AArch64TargetLowering &TLI)
55   : CallLowering(&TLI) {}
56 
57 static void applyStackPassedSmallTypeDAGHack(EVT OrigVT, MVT &ValVT,
58                                              MVT &LocVT) {
59   // If ValVT is i1/i8/i16, we should set LocVT to i8/i8/i16. This is a legacy
60   // hack because the DAG calls the assignment function with pre-legalized
61   // register typed values, not the raw type.
62   //
63   // This hack is not applied to return values which are not passed on the
64   // stack.
65   if (OrigVT == MVT::i1 || OrigVT == MVT::i8)
66     ValVT = LocVT = MVT::i8;
67   else if (OrigVT == MVT::i16)
68     ValVT = LocVT = MVT::i16;
69 }
70 
71 // Account for i1/i8/i16 stack passed value hack
72 static LLT getStackValueStoreTypeHack(const CCValAssign &VA) {
73   const MVT ValVT = VA.getValVT();
74   return (ValVT == MVT::i8 || ValVT == MVT::i16) ? LLT(ValVT)
75                                                  : LLT(VA.getLocVT());
76 }
77 
78 namespace {
79 
80 struct AArch64IncomingValueAssigner
81     : public CallLowering::IncomingValueAssigner {
82   AArch64IncomingValueAssigner(CCAssignFn *AssignFn_,
83                                CCAssignFn *AssignFnVarArg_)
84       : IncomingValueAssigner(AssignFn_, AssignFnVarArg_) {}
85 
86   bool assignArg(unsigned ValNo, EVT OrigVT, MVT ValVT, MVT LocVT,
87                  CCValAssign::LocInfo LocInfo,
88                  const CallLowering::ArgInfo &Info, ISD::ArgFlagsTy Flags,
89                  CCState &State) override {
90     applyStackPassedSmallTypeDAGHack(OrigVT, ValVT, LocVT);
91     return IncomingValueAssigner::assignArg(ValNo, OrigVT, ValVT, LocVT,
92                                             LocInfo, Info, Flags, State);
93   }
94 };
95 
96 struct AArch64OutgoingValueAssigner
97     : public CallLowering::OutgoingValueAssigner {
98   const AArch64Subtarget &Subtarget;
99 
100   /// Track if this is used for a return instead of function argument
101   /// passing. We apply a hack to i1/i8/i16 stack passed values, but do not use
102   /// stack passed returns for them and cannot apply the type adjustment.
103   bool IsReturn;
104 
105   AArch64OutgoingValueAssigner(CCAssignFn *AssignFn_,
106                                CCAssignFn *AssignFnVarArg_,
107                                const AArch64Subtarget &Subtarget_,
108                                bool IsReturn)
109       : OutgoingValueAssigner(AssignFn_, AssignFnVarArg_),
110         Subtarget(Subtarget_), IsReturn(IsReturn) {}
111 
112   bool assignArg(unsigned ValNo, EVT OrigVT, MVT ValVT, MVT LocVT,
113                  CCValAssign::LocInfo LocInfo,
114                  const CallLowering::ArgInfo &Info, ISD::ArgFlagsTy Flags,
115                  CCState &State) override {
116     bool IsCalleeWin = Subtarget.isCallingConvWin64(State.getCallingConv());
117     bool UseVarArgsCCForFixed = IsCalleeWin && State.isVarArg();
118 
119     bool Res;
120     if (Info.IsFixed && !UseVarArgsCCForFixed) {
121       if (!IsReturn)
122         applyStackPassedSmallTypeDAGHack(OrigVT, ValVT, LocVT);
123       Res = AssignFn(ValNo, ValVT, LocVT, LocInfo, Flags, State);
124     } else
125       Res = AssignFnVarArg(ValNo, ValVT, LocVT, LocInfo, Flags, State);
126 
127     StackSize = State.getStackSize();
128     return Res;
129   }
130 };
131 
132 struct IncomingArgHandler : public CallLowering::IncomingValueHandler {
133   IncomingArgHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI)
134       : IncomingValueHandler(MIRBuilder, MRI) {}
135 
136   Register getStackAddress(uint64_t Size, int64_t Offset,
137                            MachinePointerInfo &MPO,
138                            ISD::ArgFlagsTy Flags) override {
139     auto &MFI = MIRBuilder.getMF().getFrameInfo();
140 
141     // Byval is assumed to be writable memory, but other stack passed arguments
142     // are not.
143     const bool IsImmutable = !Flags.isByVal();
144 
145     int FI = MFI.CreateFixedObject(Size, Offset, IsImmutable);
146     MPO = MachinePointerInfo::getFixedStack(MIRBuilder.getMF(), FI);
147     auto AddrReg = MIRBuilder.buildFrameIndex(LLT::pointer(0, 64), FI);
148     return AddrReg.getReg(0);
149   }
150 
151   LLT getStackValueStoreType(const DataLayout &DL, const CCValAssign &VA,
152                              ISD::ArgFlagsTy Flags) const override {
153     // For pointers, we just need to fixup the integer types reported in the
154     // CCValAssign.
155     if (Flags.isPointer())
156       return CallLowering::ValueHandler::getStackValueStoreType(DL, VA, Flags);
157     return getStackValueStoreTypeHack(VA);
158   }
159 
160   void assignValueToReg(Register ValVReg, Register PhysReg,
161                         CCValAssign VA) override {
162     markPhysRegUsed(PhysReg);
163     IncomingValueHandler::assignValueToReg(ValVReg, PhysReg, VA);
164   }
165 
166   void assignValueToAddress(Register ValVReg, Register Addr, LLT MemTy,
167                             MachinePointerInfo &MPO, CCValAssign &VA) override {
168     MachineFunction &MF = MIRBuilder.getMF();
169 
170     LLT ValTy(VA.getValVT());
171     LLT LocTy(VA.getLocVT());
172 
173     // Fixup the types for the DAG compatibility hack.
174     if (VA.getValVT() == MVT::i8 || VA.getValVT() == MVT::i16)
175       std::swap(ValTy, LocTy);
176     else {
177       // The calling code knows if this is a pointer or not, we're only touching
178       // the LocTy for the i8/i16 hack.
179       assert(LocTy.getSizeInBits() == MemTy.getSizeInBits());
180       LocTy = MemTy;
181     }
182 
183     auto MMO = MF.getMachineMemOperand(
184         MPO, MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant, LocTy,
185         inferAlignFromPtrInfo(MF, MPO));
186 
187     switch (VA.getLocInfo()) {
188     case CCValAssign::LocInfo::ZExt:
189       MIRBuilder.buildLoadInstr(TargetOpcode::G_ZEXTLOAD, ValVReg, Addr, *MMO);
190       return;
191     case CCValAssign::LocInfo::SExt:
192       MIRBuilder.buildLoadInstr(TargetOpcode::G_SEXTLOAD, ValVReg, Addr, *MMO);
193       return;
194     default:
195       MIRBuilder.buildLoad(ValVReg, Addr, *MMO);
196       return;
197     }
198   }
199 
200   /// How the physical register gets marked varies between formal
201   /// parameters (it's a basic-block live-in), and a call instruction
202   /// (it's an implicit-def of the BL).
203   virtual void markPhysRegUsed(MCRegister PhysReg) = 0;
204 };
205 
206 struct FormalArgHandler : public IncomingArgHandler {
207   FormalArgHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI)
208       : IncomingArgHandler(MIRBuilder, MRI) {}
209 
210   void markPhysRegUsed(MCRegister PhysReg) override {
211     MIRBuilder.getMRI()->addLiveIn(PhysReg);
212     MIRBuilder.getMBB().addLiveIn(PhysReg);
213   }
214 };
215 
216 struct CallReturnHandler : public IncomingArgHandler {
217   CallReturnHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
218                     MachineInstrBuilder MIB)
219       : IncomingArgHandler(MIRBuilder, MRI), MIB(MIB) {}
220 
221   void markPhysRegUsed(MCRegister PhysReg) override {
222     MIB.addDef(PhysReg, RegState::Implicit);
223   }
224 
225   MachineInstrBuilder MIB;
226 };
227 
228 /// A special return arg handler for "returned" attribute arg calls.
229 struct ReturnedArgCallReturnHandler : public CallReturnHandler {
230   ReturnedArgCallReturnHandler(MachineIRBuilder &MIRBuilder,
231                                MachineRegisterInfo &MRI,
232                                MachineInstrBuilder MIB)
233       : CallReturnHandler(MIRBuilder, MRI, MIB) {}
234 
235   void markPhysRegUsed(MCRegister PhysReg) override {}
236 };
237 
238 struct OutgoingArgHandler : public CallLowering::OutgoingValueHandler {
239   OutgoingArgHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
240                      MachineInstrBuilder MIB, bool IsTailCall = false,
241                      int FPDiff = 0)
242       : OutgoingValueHandler(MIRBuilder, MRI), MIB(MIB), IsTailCall(IsTailCall),
243         FPDiff(FPDiff),
244         Subtarget(MIRBuilder.getMF().getSubtarget<AArch64Subtarget>()) {}
245 
246   Register getStackAddress(uint64_t Size, int64_t Offset,
247                            MachinePointerInfo &MPO,
248                            ISD::ArgFlagsTy Flags) override {
249     MachineFunction &MF = MIRBuilder.getMF();
250     LLT p0 = LLT::pointer(0, 64);
251     LLT s64 = LLT::scalar(64);
252 
253     if (IsTailCall) {
254       assert(!Flags.isByVal() && "byval unhandled with tail calls");
255 
256       Offset += FPDiff;
257       int FI = MF.getFrameInfo().CreateFixedObject(Size, Offset, true);
258       auto FIReg = MIRBuilder.buildFrameIndex(p0, FI);
259       MPO = MachinePointerInfo::getFixedStack(MF, FI);
260       return FIReg.getReg(0);
261     }
262 
263     if (!SPReg)
264       SPReg = MIRBuilder.buildCopy(p0, Register(AArch64::SP)).getReg(0);
265 
266     auto OffsetReg = MIRBuilder.buildConstant(s64, Offset);
267 
268     auto AddrReg = MIRBuilder.buildPtrAdd(p0, SPReg, OffsetReg);
269 
270     MPO = MachinePointerInfo::getStack(MF, Offset);
271     return AddrReg.getReg(0);
272   }
273 
274   /// We need to fixup the reported store size for certain value types because
275   /// we invert the interpretation of ValVT and LocVT in certain cases. This is
276   /// for compatability with the DAG call lowering implementation, which we're
277   /// currently building on top of.
278   LLT getStackValueStoreType(const DataLayout &DL, const CCValAssign &VA,
279                              ISD::ArgFlagsTy Flags) const override {
280     if (Flags.isPointer())
281       return CallLowering::ValueHandler::getStackValueStoreType(DL, VA, Flags);
282     return getStackValueStoreTypeHack(VA);
283   }
284 
285   void assignValueToReg(Register ValVReg, Register PhysReg,
286                         CCValAssign VA) override {
287     MIB.addUse(PhysReg, RegState::Implicit);
288     Register ExtReg = extendRegister(ValVReg, VA);
289     MIRBuilder.buildCopy(PhysReg, ExtReg);
290   }
291 
292   void assignValueToAddress(Register ValVReg, Register Addr, LLT MemTy,
293                             MachinePointerInfo &MPO, CCValAssign &VA) override {
294     MachineFunction &MF = MIRBuilder.getMF();
295     auto MMO = MF.getMachineMemOperand(MPO, MachineMemOperand::MOStore, MemTy,
296                                        inferAlignFromPtrInfo(MF, MPO));
297     MIRBuilder.buildStore(ValVReg, Addr, *MMO);
298   }
299 
300   void assignValueToAddress(const CallLowering::ArgInfo &Arg, unsigned RegIndex,
301                             Register Addr, LLT MemTy, MachinePointerInfo &MPO,
302                             CCValAssign &VA) override {
303     unsigned MaxSize = MemTy.getSizeInBytes() * 8;
304     // For varargs, we always want to extend them to 8 bytes, in which case
305     // we disable setting a max.
306     if (!Arg.IsFixed)
307       MaxSize = 0;
308 
309     Register ValVReg = Arg.Regs[RegIndex];
310     if (VA.getLocInfo() != CCValAssign::LocInfo::FPExt) {
311       MVT LocVT = VA.getLocVT();
312       MVT ValVT = VA.getValVT();
313 
314       if (VA.getValVT() == MVT::i8 || VA.getValVT() == MVT::i16) {
315         std::swap(ValVT, LocVT);
316         MemTy = LLT(VA.getValVT());
317       }
318 
319       ValVReg = extendRegister(ValVReg, VA, MaxSize);
320     } else {
321       // The store does not cover the full allocated stack slot.
322       MemTy = LLT(VA.getValVT());
323     }
324 
325     assignValueToAddress(ValVReg, Addr, MemTy, MPO, VA);
326   }
327 
328   MachineInstrBuilder MIB;
329 
330   bool IsTailCall;
331 
332   /// For tail calls, the byte offset of the call's argument area from the
333   /// callee's. Unused elsewhere.
334   int FPDiff;
335 
336   // Cache the SP register vreg if we need it more than once in this call site.
337   Register SPReg;
338 
339   const AArch64Subtarget &Subtarget;
340 };
341 } // namespace
342 
343 static bool doesCalleeRestoreStack(CallingConv::ID CallConv, bool TailCallOpt) {
344   return (CallConv == CallingConv::Fast && TailCallOpt) ||
345          CallConv == CallingConv::Tail || CallConv == CallingConv::SwiftTail;
346 }
347 
348 bool AArch64CallLowering::lowerReturn(MachineIRBuilder &MIRBuilder,
349                                       const Value *Val,
350                                       ArrayRef<Register> VRegs,
351                                       FunctionLoweringInfo &FLI,
352                                       Register SwiftErrorVReg) const {
353   auto MIB = MIRBuilder.buildInstrNoInsert(AArch64::RET_ReallyLR);
354   assert(((Val && !VRegs.empty()) || (!Val && VRegs.empty())) &&
355          "Return value without a vreg");
356 
357   bool Success = true;
358   if (!FLI.CanLowerReturn) {
359     insertSRetStores(MIRBuilder, Val->getType(), VRegs, FLI.DemoteRegister);
360   } else if (!VRegs.empty()) {
361     MachineFunction &MF = MIRBuilder.getMF();
362     const Function &F = MF.getFunction();
363     const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
364 
365     MachineRegisterInfo &MRI = MF.getRegInfo();
366     const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
367     CCAssignFn *AssignFn = TLI.CCAssignFnForReturn(F.getCallingConv());
368     auto &DL = F.getParent()->getDataLayout();
369     LLVMContext &Ctx = Val->getType()->getContext();
370 
371     SmallVector<EVT, 4> SplitEVTs;
372     ComputeValueVTs(TLI, DL, Val->getType(), SplitEVTs);
373     assert(VRegs.size() == SplitEVTs.size() &&
374            "For each split Type there should be exactly one VReg.");
375 
376     SmallVector<ArgInfo, 8> SplitArgs;
377     CallingConv::ID CC = F.getCallingConv();
378 
379     for (unsigned i = 0; i < SplitEVTs.size(); ++i) {
380       Register CurVReg = VRegs[i];
381       ArgInfo CurArgInfo = ArgInfo{CurVReg, SplitEVTs[i].getTypeForEVT(Ctx), 0};
382       setArgFlags(CurArgInfo, AttributeList::ReturnIndex, DL, F);
383 
384       // i1 is a special case because SDAG i1 true is naturally zero extended
385       // when widened using ANYEXT. We need to do it explicitly here.
386       auto &Flags = CurArgInfo.Flags[0];
387       if (MRI.getType(CurVReg).getSizeInBits() == 1 && !Flags.isSExt() &&
388           !Flags.isZExt()) {
389         CurVReg = MIRBuilder.buildZExt(LLT::scalar(8), CurVReg).getReg(0);
390       } else if (TLI.getNumRegistersForCallingConv(Ctx, CC, SplitEVTs[i]) ==
391                  1) {
392         // Some types will need extending as specified by the CC.
393         MVT NewVT = TLI.getRegisterTypeForCallingConv(Ctx, CC, SplitEVTs[i]);
394         if (EVT(NewVT) != SplitEVTs[i]) {
395           unsigned ExtendOp = TargetOpcode::G_ANYEXT;
396           if (F.getAttributes().hasRetAttr(Attribute::SExt))
397             ExtendOp = TargetOpcode::G_SEXT;
398           else if (F.getAttributes().hasRetAttr(Attribute::ZExt))
399             ExtendOp = TargetOpcode::G_ZEXT;
400 
401           LLT NewLLT(NewVT);
402           LLT OldLLT(MVT::getVT(CurArgInfo.Ty));
403           CurArgInfo.Ty = EVT(NewVT).getTypeForEVT(Ctx);
404           // Instead of an extend, we might have a vector type which needs
405           // padding with more elements, e.g. <2 x half> -> <4 x half>.
406           if (NewVT.isVector()) {
407             if (OldLLT.isVector()) {
408               if (NewLLT.getNumElements() > OldLLT.getNumElements()) {
409 
410                 CurVReg =
411                     MIRBuilder.buildPadVectorWithUndefElements(NewLLT, CurVReg)
412                         .getReg(0);
413               } else {
414                 // Just do a vector extend.
415                 CurVReg = MIRBuilder.buildInstr(ExtendOp, {NewLLT}, {CurVReg})
416                               .getReg(0);
417               }
418             } else if (NewLLT.getNumElements() >= 2 &&
419                        NewLLT.getNumElements() <= 8) {
420               // We need to pad a <1 x S> type to <2/4/8 x S>. Since we don't
421               // have <1 x S> vector types in GISel we use a build_vector
422               // instead of a vector merge/concat.
423               CurVReg =
424                   MIRBuilder.buildPadVectorWithUndefElements(NewLLT, CurVReg)
425                       .getReg(0);
426             } else {
427               LLVM_DEBUG(dbgs() << "Could not handle ret ty\n");
428               return false;
429             }
430           } else {
431             // If the split EVT was a <1 x T> vector, and NewVT is T, then we
432             // don't have to do anything since we don't distinguish between the
433             // two.
434             if (NewLLT != MRI.getType(CurVReg)) {
435               // A scalar extend.
436               CurVReg = MIRBuilder.buildInstr(ExtendOp, {NewLLT}, {CurVReg})
437                             .getReg(0);
438             }
439           }
440         }
441       }
442       if (CurVReg != CurArgInfo.Regs[0]) {
443         CurArgInfo.Regs[0] = CurVReg;
444         // Reset the arg flags after modifying CurVReg.
445         setArgFlags(CurArgInfo, AttributeList::ReturnIndex, DL, F);
446       }
447       splitToValueTypes(CurArgInfo, SplitArgs, DL, CC);
448     }
449 
450     AArch64OutgoingValueAssigner Assigner(AssignFn, AssignFn, Subtarget,
451                                           /*IsReturn*/ true);
452     OutgoingArgHandler Handler(MIRBuilder, MRI, MIB);
453     Success = determineAndHandleAssignments(Handler, Assigner, SplitArgs,
454                                             MIRBuilder, CC, F.isVarArg());
455   }
456 
457   if (SwiftErrorVReg) {
458     MIB.addUse(AArch64::X21, RegState::Implicit);
459     MIRBuilder.buildCopy(AArch64::X21, SwiftErrorVReg);
460   }
461 
462   MIRBuilder.insertInstr(MIB);
463   return Success;
464 }
465 
466 bool AArch64CallLowering::canLowerReturn(MachineFunction &MF,
467                                          CallingConv::ID CallConv,
468                                          SmallVectorImpl<BaseArgInfo> &Outs,
469                                          bool IsVarArg) const {
470   SmallVector<CCValAssign, 16> ArgLocs;
471   const auto &TLI = *getTLI<AArch64TargetLowering>();
472   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs,
473                  MF.getFunction().getContext());
474 
475   return checkReturn(CCInfo, Outs, TLI.CCAssignFnForReturn(CallConv));
476 }
477 
478 /// Helper function to compute forwarded registers for musttail calls. Computes
479 /// the forwarded registers, sets MBB liveness, and emits COPY instructions that
480 /// can be used to save + restore registers later.
481 static void handleMustTailForwardedRegisters(MachineIRBuilder &MIRBuilder,
482                                              CCAssignFn *AssignFn) {
483   MachineBasicBlock &MBB = MIRBuilder.getMBB();
484   MachineFunction &MF = MIRBuilder.getMF();
485   MachineFrameInfo &MFI = MF.getFrameInfo();
486 
487   if (!MFI.hasMustTailInVarArgFunc())
488     return;
489 
490   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
491   const Function &F = MF.getFunction();
492   assert(F.isVarArg() && "Expected F to be vararg?");
493 
494   // Compute the set of forwarded registers. The rest are scratch.
495   SmallVector<CCValAssign, 16> ArgLocs;
496   CCState CCInfo(F.getCallingConv(), /*IsVarArg=*/true, MF, ArgLocs,
497                  F.getContext());
498   SmallVector<MVT, 2> RegParmTypes;
499   RegParmTypes.push_back(MVT::i64);
500   RegParmTypes.push_back(MVT::f128);
501 
502   // Later on, we can use this vector to restore the registers if necessary.
503   SmallVectorImpl<ForwardedRegister> &Forwards =
504       FuncInfo->getForwardedMustTailRegParms();
505   CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, AssignFn);
506 
507   // Conservatively forward X8, since it might be used for an aggregate
508   // return.
509   if (!CCInfo.isAllocated(AArch64::X8)) {
510     Register X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
511     Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
512   }
513 
514   // Add the forwards to the MachineBasicBlock and MachineFunction.
515   for (const auto &F : Forwards) {
516     MBB.addLiveIn(F.PReg);
517     MIRBuilder.buildCopy(Register(F.VReg), Register(F.PReg));
518   }
519 }
520 
521 bool AArch64CallLowering::fallBackToDAGISel(const MachineFunction &MF) const {
522   auto &F = MF.getFunction();
523   if (F.getReturnType()->isScalableTy() ||
524       llvm::any_of(F.args(), [](const Argument &A) {
525         return A.getType()->isScalableTy();
526       }))
527     return true;
528   const auto &ST = MF.getSubtarget<AArch64Subtarget>();
529   if (!ST.hasNEON() || !ST.hasFPARMv8()) {
530     LLVM_DEBUG(dbgs() << "Falling back to SDAG because we don't support no-NEON\n");
531     return true;
532   }
533 
534   SMEAttrs Attrs(F);
535   if (Attrs.hasNewZAInterface() ||
536       (!Attrs.hasStreamingInterface() && Attrs.hasStreamingBody()))
537     return true;
538 
539   return false;
540 }
541 
542 void AArch64CallLowering::saveVarArgRegisters(
543     MachineIRBuilder &MIRBuilder, CallLowering::IncomingValueHandler &Handler,
544     CCState &CCInfo) const {
545   auto GPRArgRegs = AArch64::getGPRArgRegs();
546   auto FPRArgRegs = AArch64::getFPRArgRegs();
547 
548   MachineFunction &MF = MIRBuilder.getMF();
549   MachineRegisterInfo &MRI = MF.getRegInfo();
550   MachineFrameInfo &MFI = MF.getFrameInfo();
551   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
552   auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
553   bool IsWin64CC =
554       Subtarget.isCallingConvWin64(CCInfo.getCallingConv());
555   const LLT p0 = LLT::pointer(0, 64);
556   const LLT s64 = LLT::scalar(64);
557 
558   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
559   unsigned NumVariadicGPRArgRegs = GPRArgRegs.size() - FirstVariadicGPR + 1;
560 
561   unsigned GPRSaveSize = 8 * (GPRArgRegs.size() - FirstVariadicGPR);
562   int GPRIdx = 0;
563   if (GPRSaveSize != 0) {
564     if (IsWin64CC) {
565       GPRIdx = MFI.CreateFixedObject(GPRSaveSize,
566                                      -static_cast<int>(GPRSaveSize), false);
567     } else
568       GPRIdx = MFI.CreateStackObject(GPRSaveSize, Align(8), false);
569 
570     auto FIN = MIRBuilder.buildFrameIndex(p0, GPRIdx);
571     auto Offset =
572         MIRBuilder.buildConstant(MRI.createGenericVirtualRegister(s64), 8);
573 
574     for (unsigned i = FirstVariadicGPR; i < GPRArgRegs.size(); ++i) {
575       Register Val = MRI.createGenericVirtualRegister(s64);
576       Handler.assignValueToReg(
577           Val, GPRArgRegs[i],
578           CCValAssign::getReg(i + MF.getFunction().getNumOperands(), MVT::i64,
579                               GPRArgRegs[i], MVT::i64, CCValAssign::Full));
580       auto MPO = IsWin64CC ? MachinePointerInfo::getFixedStack(
581                                MF, GPRIdx, (i - FirstVariadicGPR) * 8)
582                          : MachinePointerInfo::getStack(MF, i * 8);
583       MIRBuilder.buildStore(Val, FIN, MPO, inferAlignFromPtrInfo(MF, MPO));
584 
585       FIN = MIRBuilder.buildPtrAdd(MRI.createGenericVirtualRegister(p0),
586                                    FIN.getReg(0), Offset);
587     }
588   }
589   FuncInfo->setVarArgsGPRIndex(GPRIdx);
590   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
591 
592   if (Subtarget.hasFPARMv8() && !IsWin64CC) {
593     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
594 
595     unsigned FPRSaveSize = 16 * (FPRArgRegs.size() - FirstVariadicFPR);
596     int FPRIdx = 0;
597     if (FPRSaveSize != 0) {
598       FPRIdx = MFI.CreateStackObject(FPRSaveSize, Align(16), false);
599 
600       auto FIN = MIRBuilder.buildFrameIndex(p0, FPRIdx);
601       auto Offset =
602           MIRBuilder.buildConstant(MRI.createGenericVirtualRegister(s64), 16);
603 
604       for (unsigned i = FirstVariadicFPR; i < FPRArgRegs.size(); ++i) {
605         Register Val = MRI.createGenericVirtualRegister(LLT::scalar(128));
606         Handler.assignValueToReg(
607             Val, FPRArgRegs[i],
608             CCValAssign::getReg(
609                 i + MF.getFunction().getNumOperands() + NumVariadicGPRArgRegs,
610                 MVT::f128, FPRArgRegs[i], MVT::f128, CCValAssign::Full));
611 
612         auto MPO = MachinePointerInfo::getStack(MF, i * 16);
613         MIRBuilder.buildStore(Val, FIN, MPO, inferAlignFromPtrInfo(MF, MPO));
614 
615         FIN = MIRBuilder.buildPtrAdd(MRI.createGenericVirtualRegister(p0),
616                                      FIN.getReg(0), Offset);
617       }
618     }
619     FuncInfo->setVarArgsFPRIndex(FPRIdx);
620     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
621   }
622 }
623 
624 bool AArch64CallLowering::lowerFormalArguments(
625     MachineIRBuilder &MIRBuilder, const Function &F,
626     ArrayRef<ArrayRef<Register>> VRegs, FunctionLoweringInfo &FLI) const {
627   MachineFunction &MF = MIRBuilder.getMF();
628   MachineBasicBlock &MBB = MIRBuilder.getMBB();
629   MachineRegisterInfo &MRI = MF.getRegInfo();
630   auto &DL = F.getParent()->getDataLayout();
631   auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
632   // TODO: Support Arm64EC
633   bool IsWin64 = Subtarget.isCallingConvWin64(F.getCallingConv()) && !Subtarget.isWindowsArm64EC();
634 
635   SmallVector<ArgInfo, 8> SplitArgs;
636   SmallVector<std::pair<Register, Register>> BoolArgs;
637 
638   // Insert the hidden sret parameter if the return value won't fit in the
639   // return registers.
640   if (!FLI.CanLowerReturn)
641     insertSRetIncomingArgument(F, SplitArgs, FLI.DemoteRegister, MRI, DL);
642 
643   unsigned i = 0;
644   for (auto &Arg : F.args()) {
645     if (DL.getTypeStoreSize(Arg.getType()).isZero())
646       continue;
647 
648     ArgInfo OrigArg{VRegs[i], Arg, i};
649     setArgFlags(OrigArg, i + AttributeList::FirstArgIndex, DL, F);
650 
651     // i1 arguments are zero-extended to i8 by the caller. Emit a
652     // hint to reflect this.
653     if (OrigArg.Ty->isIntegerTy(1)) {
654       assert(OrigArg.Regs.size() == 1 &&
655              MRI.getType(OrigArg.Regs[0]).getSizeInBits() == 1 &&
656              "Unexpected registers used for i1 arg");
657 
658       auto &Flags = OrigArg.Flags[0];
659       if (!Flags.isZExt() && !Flags.isSExt()) {
660         // Lower i1 argument as i8, and insert AssertZExt + Trunc later.
661         Register OrigReg = OrigArg.Regs[0];
662         Register WideReg = MRI.createGenericVirtualRegister(LLT::scalar(8));
663         OrigArg.Regs[0] = WideReg;
664         BoolArgs.push_back({OrigReg, WideReg});
665       }
666     }
667 
668     if (Arg.hasAttribute(Attribute::SwiftAsync))
669       MF.getInfo<AArch64FunctionInfo>()->setHasSwiftAsyncContext(true);
670 
671     splitToValueTypes(OrigArg, SplitArgs, DL, F.getCallingConv());
672     ++i;
673   }
674 
675   if (!MBB.empty())
676     MIRBuilder.setInstr(*MBB.begin());
677 
678   const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
679   CCAssignFn *AssignFn = TLI.CCAssignFnForCall(F.getCallingConv(), IsWin64 && F.isVarArg());
680 
681   AArch64IncomingValueAssigner Assigner(AssignFn, AssignFn);
682   FormalArgHandler Handler(MIRBuilder, MRI);
683   SmallVector<CCValAssign, 16> ArgLocs;
684   CCState CCInfo(F.getCallingConv(), F.isVarArg(), MF, ArgLocs, F.getContext());
685   if (!determineAssignments(Assigner, SplitArgs, CCInfo) ||
686       !handleAssignments(Handler, SplitArgs, CCInfo, ArgLocs, MIRBuilder))
687     return false;
688 
689   if (!BoolArgs.empty()) {
690     for (auto &KV : BoolArgs) {
691       Register OrigReg = KV.first;
692       Register WideReg = KV.second;
693       LLT WideTy = MRI.getType(WideReg);
694       assert(MRI.getType(OrigReg).getScalarSizeInBits() == 1 &&
695              "Unexpected bit size of a bool arg");
696       MIRBuilder.buildTrunc(
697           OrigReg, MIRBuilder.buildAssertZExt(WideTy, WideReg, 1).getReg(0));
698     }
699   }
700 
701   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
702   uint64_t StackSize = Assigner.StackSize;
703   if (F.isVarArg()) {
704     if ((!Subtarget.isTargetDarwin() && !Subtarget.isWindowsArm64EC()) || IsWin64) {
705       // The AAPCS variadic function ABI is identical to the non-variadic
706       // one. As a result there may be more arguments in registers and we should
707       // save them for future reference.
708       // Win64 variadic functions also pass arguments in registers, but all
709       // float arguments are passed in integer registers.
710       saveVarArgRegisters(MIRBuilder, Handler, CCInfo);
711     } else if (Subtarget.isWindowsArm64EC()) {
712       return false;
713     }
714 
715     // We currently pass all varargs at 8-byte alignment, or 4 in ILP32.
716     StackSize = alignTo(Assigner.StackSize, Subtarget.isTargetILP32() ? 4 : 8);
717 
718     auto &MFI = MIRBuilder.getMF().getFrameInfo();
719     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackSize, true));
720   }
721 
722   if (doesCalleeRestoreStack(F.getCallingConv(),
723                              MF.getTarget().Options.GuaranteedTailCallOpt)) {
724     // We have a non-standard ABI, so why not make full use of the stack that
725     // we're going to pop? It must be aligned to 16 B in any case.
726     StackSize = alignTo(StackSize, 16);
727 
728     // If we're expected to restore the stack (e.g. fastcc), then we'll be
729     // adding a multiple of 16.
730     FuncInfo->setArgumentStackToRestore(StackSize);
731 
732     // Our own callers will guarantee that the space is free by giving an
733     // aligned value to CALLSEQ_START.
734   }
735 
736   // When we tail call, we need to check if the callee's arguments
737   // will fit on the caller's stack. So, whenever we lower formal arguments,
738   // we should keep track of this information, since we might lower a tail call
739   // in this function later.
740   FuncInfo->setBytesInStackArgArea(StackSize);
741 
742   if (Subtarget.hasCustomCallingConv())
743     Subtarget.getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
744 
745   handleMustTailForwardedRegisters(MIRBuilder, AssignFn);
746 
747   // Move back to the end of the basic block.
748   MIRBuilder.setMBB(MBB);
749 
750   return true;
751 }
752 
753 /// Return true if the calling convention is one that we can guarantee TCO for.
754 static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls) {
755   return (CC == CallingConv::Fast && GuaranteeTailCalls) ||
756          CC == CallingConv::Tail || CC == CallingConv::SwiftTail;
757 }
758 
759 /// Return true if we might ever do TCO for calls with this calling convention.
760 static bool mayTailCallThisCC(CallingConv::ID CC) {
761   switch (CC) {
762   case CallingConv::C:
763   case CallingConv::PreserveMost:
764   case CallingConv::PreserveAll:
765   case CallingConv::Swift:
766   case CallingConv::SwiftTail:
767   case CallingConv::Tail:
768   case CallingConv::Fast:
769     return true;
770   default:
771     return false;
772   }
773 }
774 
775 /// Returns a pair containing the fixed CCAssignFn and the vararg CCAssignFn for
776 /// CC.
777 static std::pair<CCAssignFn *, CCAssignFn *>
778 getAssignFnsForCC(CallingConv::ID CC, const AArch64TargetLowering &TLI) {
779   return {TLI.CCAssignFnForCall(CC, false), TLI.CCAssignFnForCall(CC, true)};
780 }
781 
782 bool AArch64CallLowering::doCallerAndCalleePassArgsTheSameWay(
783     CallLoweringInfo &Info, MachineFunction &MF,
784     SmallVectorImpl<ArgInfo> &InArgs) const {
785   const Function &CallerF = MF.getFunction();
786   CallingConv::ID CalleeCC = Info.CallConv;
787   CallingConv::ID CallerCC = CallerF.getCallingConv();
788 
789   // If the calling conventions match, then everything must be the same.
790   if (CalleeCC == CallerCC)
791     return true;
792 
793   // Check if the caller and callee will handle arguments in the same way.
794   const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
795   CCAssignFn *CalleeAssignFnFixed;
796   CCAssignFn *CalleeAssignFnVarArg;
797   std::tie(CalleeAssignFnFixed, CalleeAssignFnVarArg) =
798       getAssignFnsForCC(CalleeCC, TLI);
799 
800   CCAssignFn *CallerAssignFnFixed;
801   CCAssignFn *CallerAssignFnVarArg;
802   std::tie(CallerAssignFnFixed, CallerAssignFnVarArg) =
803       getAssignFnsForCC(CallerCC, TLI);
804 
805   AArch64IncomingValueAssigner CalleeAssigner(CalleeAssignFnFixed,
806                                               CalleeAssignFnVarArg);
807   AArch64IncomingValueAssigner CallerAssigner(CallerAssignFnFixed,
808                                               CallerAssignFnVarArg);
809 
810   if (!resultsCompatible(Info, MF, InArgs, CalleeAssigner, CallerAssigner))
811     return false;
812 
813   // Make sure that the caller and callee preserve all of the same registers.
814   auto TRI = MF.getSubtarget<AArch64Subtarget>().getRegisterInfo();
815   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
816   const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
817   if (MF.getSubtarget<AArch64Subtarget>().hasCustomCallingConv()) {
818     TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
819     TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
820   }
821 
822   return TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved);
823 }
824 
825 bool AArch64CallLowering::areCalleeOutgoingArgsTailCallable(
826     CallLoweringInfo &Info, MachineFunction &MF,
827     SmallVectorImpl<ArgInfo> &OutArgs) const {
828   // If there are no outgoing arguments, then we are done.
829   if (OutArgs.empty())
830     return true;
831 
832   const Function &CallerF = MF.getFunction();
833   LLVMContext &Ctx = CallerF.getContext();
834   CallingConv::ID CalleeCC = Info.CallConv;
835   CallingConv::ID CallerCC = CallerF.getCallingConv();
836   const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
837   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
838 
839   CCAssignFn *AssignFnFixed;
840   CCAssignFn *AssignFnVarArg;
841   std::tie(AssignFnFixed, AssignFnVarArg) = getAssignFnsForCC(CalleeCC, TLI);
842 
843   // We have outgoing arguments. Make sure that we can tail call with them.
844   SmallVector<CCValAssign, 16> OutLocs;
845   CCState OutInfo(CalleeCC, false, MF, OutLocs, Ctx);
846 
847   AArch64OutgoingValueAssigner CalleeAssigner(AssignFnFixed, AssignFnVarArg,
848                                               Subtarget, /*IsReturn*/ false);
849   if (!determineAssignments(CalleeAssigner, OutArgs, OutInfo)) {
850     LLVM_DEBUG(dbgs() << "... Could not analyze call operands.\n");
851     return false;
852   }
853 
854   // Make sure that they can fit on the caller's stack.
855   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
856   if (OutInfo.getStackSize() > FuncInfo->getBytesInStackArgArea()) {
857     LLVM_DEBUG(dbgs() << "... Cannot fit call operands on caller's stack.\n");
858     return false;
859   }
860 
861   // Verify that the parameters in callee-saved registers match.
862   // TODO: Port this over to CallLowering as general code once swiftself is
863   // supported.
864   auto TRI = MF.getSubtarget<AArch64Subtarget>().getRegisterInfo();
865   const uint32_t *CallerPreservedMask = TRI->getCallPreservedMask(MF, CallerCC);
866   MachineRegisterInfo &MRI = MF.getRegInfo();
867 
868   if (Info.IsVarArg) {
869     // Be conservative and disallow variadic memory operands to match SDAG's
870     // behaviour.
871     // FIXME: If the caller's calling convention is C, then we can
872     // potentially use its argument area. However, for cases like fastcc,
873     // we can't do anything.
874     for (unsigned i = 0; i < OutLocs.size(); ++i) {
875       auto &ArgLoc = OutLocs[i];
876       if (ArgLoc.isRegLoc())
877         continue;
878 
879       LLVM_DEBUG(
880           dbgs()
881           << "... Cannot tail call vararg function with stack arguments\n");
882       return false;
883     }
884   }
885 
886   return parametersInCSRMatch(MRI, CallerPreservedMask, OutLocs, OutArgs);
887 }
888 
889 bool AArch64CallLowering::isEligibleForTailCallOptimization(
890     MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info,
891     SmallVectorImpl<ArgInfo> &InArgs,
892     SmallVectorImpl<ArgInfo> &OutArgs) const {
893 
894   // Must pass all target-independent checks in order to tail call optimize.
895   if (!Info.IsTailCall)
896     return false;
897 
898   CallingConv::ID CalleeCC = Info.CallConv;
899   MachineFunction &MF = MIRBuilder.getMF();
900   const Function &CallerF = MF.getFunction();
901 
902   LLVM_DEBUG(dbgs() << "Attempting to lower call as tail call\n");
903 
904   if (Info.SwiftErrorVReg) {
905     // TODO: We should handle this.
906     // Note that this is also handled by the check for no outgoing arguments.
907     // Proactively disabling this though, because the swifterror handling in
908     // lowerCall inserts a COPY *after* the location of the call.
909     LLVM_DEBUG(dbgs() << "... Cannot handle tail calls with swifterror yet.\n");
910     return false;
911   }
912 
913   if (!mayTailCallThisCC(CalleeCC)) {
914     LLVM_DEBUG(dbgs() << "... Calling convention cannot be tail called.\n");
915     return false;
916   }
917 
918   // Byval parameters hand the function a pointer directly into the stack area
919   // we want to reuse during a tail call. Working around this *is* possible (see
920   // X86).
921   //
922   // FIXME: In AArch64ISelLowering, this isn't worked around. Can/should we try
923   // it?
924   //
925   // On Windows, "inreg" attributes signify non-aggregate indirect returns.
926   // In this case, it is necessary to save/restore X0 in the callee. Tail
927   // call opt interferes with this. So we disable tail call opt when the
928   // caller has an argument with "inreg" attribute.
929   //
930   // FIXME: Check whether the callee also has an "inreg" argument.
931   //
932   // When the caller has a swifterror argument, we don't want to tail call
933   // because would have to move into the swifterror register before the
934   // tail call.
935   if (any_of(CallerF.args(), [](const Argument &A) {
936         return A.hasByValAttr() || A.hasInRegAttr() || A.hasSwiftErrorAttr();
937       })) {
938     LLVM_DEBUG(dbgs() << "... Cannot tail call from callers with byval, "
939                          "inreg, or swifterror arguments\n");
940     return false;
941   }
942 
943   // Externally-defined functions with weak linkage should not be
944   // tail-called on AArch64 when the OS does not support dynamic
945   // pre-emption of symbols, as the AAELF spec requires normal calls
946   // to undefined weak functions to be replaced with a NOP or jump to the
947   // next instruction. The behaviour of branch instructions in this
948   // situation (as used for tail calls) is implementation-defined, so we
949   // cannot rely on the linker replacing the tail call with a return.
950   if (Info.Callee.isGlobal()) {
951     const GlobalValue *GV = Info.Callee.getGlobal();
952     const Triple &TT = MF.getTarget().getTargetTriple();
953     if (GV->hasExternalWeakLinkage() &&
954         (!TT.isOSWindows() || TT.isOSBinFormatELF() ||
955          TT.isOSBinFormatMachO())) {
956       LLVM_DEBUG(dbgs() << "... Cannot tail call externally-defined function "
957                            "with weak linkage for this OS.\n");
958       return false;
959     }
960   }
961 
962   // If we have -tailcallopt, then we're done.
963   if (canGuaranteeTCO(CalleeCC, MF.getTarget().Options.GuaranteedTailCallOpt))
964     return CalleeCC == CallerF.getCallingConv();
965 
966   // We don't have -tailcallopt, so we're allowed to change the ABI (sibcall).
967   // Try to find cases where we can do that.
968 
969   // I want anyone implementing a new calling convention to think long and hard
970   // about this assert.
971   assert((!Info.IsVarArg || CalleeCC == CallingConv::C) &&
972          "Unexpected variadic calling convention");
973 
974   // Verify that the incoming and outgoing arguments from the callee are
975   // safe to tail call.
976   if (!doCallerAndCalleePassArgsTheSameWay(Info, MF, InArgs)) {
977     LLVM_DEBUG(
978         dbgs()
979         << "... Caller and callee have incompatible calling conventions.\n");
980     return false;
981   }
982 
983   if (!areCalleeOutgoingArgsTailCallable(Info, MF, OutArgs))
984     return false;
985 
986   LLVM_DEBUG(
987       dbgs() << "... Call is eligible for tail call optimization.\n");
988   return true;
989 }
990 
991 static unsigned getCallOpcode(const MachineFunction &CallerF, bool IsIndirect,
992                               bool IsTailCall) {
993   if (!IsTailCall)
994     return IsIndirect ? getBLRCallOpcode(CallerF) : (unsigned)AArch64::BL;
995 
996   if (!IsIndirect)
997     return AArch64::TCRETURNdi;
998 
999   // When BTI is enabled, we need to use TCRETURNriBTI to make sure that we use
1000   // x16 or x17.
1001   if (CallerF.getInfo<AArch64FunctionInfo>()->branchTargetEnforcement())
1002     return AArch64::TCRETURNriBTI;
1003 
1004   return AArch64::TCRETURNri;
1005 }
1006 
1007 static const uint32_t *
1008 getMaskForArgs(SmallVectorImpl<AArch64CallLowering::ArgInfo> &OutArgs,
1009                AArch64CallLowering::CallLoweringInfo &Info,
1010                const AArch64RegisterInfo &TRI, MachineFunction &MF) {
1011   const uint32_t *Mask;
1012   if (!OutArgs.empty() && OutArgs[0].Flags[0].isReturned()) {
1013     // For 'this' returns, use the X0-preserving mask if applicable
1014     Mask = TRI.getThisReturnPreservedMask(MF, Info.CallConv);
1015     if (!Mask) {
1016       OutArgs[0].Flags[0].setReturned(false);
1017       Mask = TRI.getCallPreservedMask(MF, Info.CallConv);
1018     }
1019   } else {
1020     Mask = TRI.getCallPreservedMask(MF, Info.CallConv);
1021   }
1022   return Mask;
1023 }
1024 
1025 bool AArch64CallLowering::lowerTailCall(
1026     MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info,
1027     SmallVectorImpl<ArgInfo> &OutArgs) const {
1028   MachineFunction &MF = MIRBuilder.getMF();
1029   const Function &F = MF.getFunction();
1030   MachineRegisterInfo &MRI = MF.getRegInfo();
1031   const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
1032   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
1033 
1034   // True when we're tail calling, but without -tailcallopt.
1035   bool IsSibCall = !MF.getTarget().Options.GuaranteedTailCallOpt &&
1036                    Info.CallConv != CallingConv::Tail &&
1037                    Info.CallConv != CallingConv::SwiftTail;
1038 
1039   // TODO: Right now, regbankselect doesn't know how to handle the rtcGPR64
1040   // register class. Until we can do that, we should fall back here.
1041   if (MF.getInfo<AArch64FunctionInfo>()->branchTargetEnforcement()) {
1042     LLVM_DEBUG(
1043         dbgs() << "Cannot lower indirect tail calls with BTI enabled yet.\n");
1044     return false;
1045   }
1046 
1047   // Find out which ABI gets to decide where things go.
1048   CallingConv::ID CalleeCC = Info.CallConv;
1049   CCAssignFn *AssignFnFixed;
1050   CCAssignFn *AssignFnVarArg;
1051   std::tie(AssignFnFixed, AssignFnVarArg) = getAssignFnsForCC(CalleeCC, TLI);
1052 
1053   MachineInstrBuilder CallSeqStart;
1054   if (!IsSibCall)
1055     CallSeqStart = MIRBuilder.buildInstr(AArch64::ADJCALLSTACKDOWN);
1056 
1057   unsigned Opc = getCallOpcode(MF, Info.Callee.isReg(), true);
1058   auto MIB = MIRBuilder.buildInstrNoInsert(Opc);
1059   MIB.add(Info.Callee);
1060 
1061   // Byte offset for the tail call. When we are sibcalling, this will always
1062   // be 0.
1063   MIB.addImm(0);
1064 
1065   // Tell the call which registers are clobbered.
1066   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1067   auto TRI = Subtarget.getRegisterInfo();
1068   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CalleeCC);
1069   if (Subtarget.hasCustomCallingConv())
1070     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
1071   MIB.addRegMask(Mask);
1072 
1073   if (Info.CFIType)
1074     MIB->setCFIType(MF, Info.CFIType->getZExtValue());
1075 
1076   if (TRI->isAnyArgRegReserved(MF))
1077     TRI->emitReservedArgRegCallError(MF);
1078 
1079   // FPDiff is the byte offset of the call's argument area from the callee's.
1080   // Stores to callee stack arguments will be placed in FixedStackSlots offset
1081   // by this amount for a tail call. In a sibling call it must be 0 because the
1082   // caller will deallocate the entire stack and the callee still expects its
1083   // arguments to begin at SP+0.
1084   int FPDiff = 0;
1085 
1086   // This will be 0 for sibcalls, potentially nonzero for tail calls produced
1087   // by -tailcallopt. For sibcalls, the memory operands for the call are
1088   // already available in the caller's incoming argument space.
1089   unsigned NumBytes = 0;
1090   if (!IsSibCall) {
1091     // We aren't sibcalling, so we need to compute FPDiff. We need to do this
1092     // before handling assignments, because FPDiff must be known for memory
1093     // arguments.
1094     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
1095     SmallVector<CCValAssign, 16> OutLocs;
1096     CCState OutInfo(CalleeCC, false, MF, OutLocs, F.getContext());
1097 
1098     AArch64OutgoingValueAssigner CalleeAssigner(AssignFnFixed, AssignFnVarArg,
1099                                                 Subtarget, /*IsReturn*/ false);
1100     if (!determineAssignments(CalleeAssigner, OutArgs, OutInfo))
1101       return false;
1102 
1103     // The callee will pop the argument stack as a tail call. Thus, we must
1104     // keep it 16-byte aligned.
1105     NumBytes = alignTo(OutInfo.getStackSize(), 16);
1106 
1107     // FPDiff will be negative if this tail call requires more space than we
1108     // would automatically have in our incoming argument space. Positive if we
1109     // actually shrink the stack.
1110     FPDiff = NumReusableBytes - NumBytes;
1111 
1112     // Update the required reserved area if this is the tail call requiring the
1113     // most argument stack space.
1114     if (FPDiff < 0 && FuncInfo->getTailCallReservedStack() < (unsigned)-FPDiff)
1115       FuncInfo->setTailCallReservedStack(-FPDiff);
1116 
1117     // The stack pointer must be 16-byte aligned at all times it's used for a
1118     // memory operation, which in practice means at *all* times and in
1119     // particular across call boundaries. Therefore our own arguments started at
1120     // a 16-byte aligned SP and the delta applied for the tail call should
1121     // satisfy the same constraint.
1122     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
1123   }
1124 
1125   const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
1126 
1127   AArch64OutgoingValueAssigner Assigner(AssignFnFixed, AssignFnVarArg,
1128                                         Subtarget, /*IsReturn*/ false);
1129 
1130   // Do the actual argument marshalling.
1131   OutgoingArgHandler Handler(MIRBuilder, MRI, MIB,
1132                              /*IsTailCall*/ true, FPDiff);
1133   if (!determineAndHandleAssignments(Handler, Assigner, OutArgs, MIRBuilder,
1134                                      CalleeCC, Info.IsVarArg))
1135     return false;
1136 
1137   Mask = getMaskForArgs(OutArgs, Info, *TRI, MF);
1138 
1139   if (Info.IsVarArg && Info.IsMustTailCall) {
1140     // Now we know what's being passed to the function. Add uses to the call for
1141     // the forwarded registers that we *aren't* passing as parameters. This will
1142     // preserve the copies we build earlier.
1143     for (const auto &F : Forwards) {
1144       Register ForwardedReg = F.PReg;
1145       // If the register is already passed, or aliases a register which is
1146       // already being passed, then skip it.
1147       if (any_of(MIB->uses(), [&ForwardedReg, &TRI](const MachineOperand &Use) {
1148             if (!Use.isReg())
1149               return false;
1150             return TRI->regsOverlap(Use.getReg(), ForwardedReg);
1151           }))
1152         continue;
1153 
1154       // We aren't passing it already, so we should add it to the call.
1155       MIRBuilder.buildCopy(ForwardedReg, Register(F.VReg));
1156       MIB.addReg(ForwardedReg, RegState::Implicit);
1157     }
1158   }
1159 
1160   // If we have -tailcallopt, we need to adjust the stack. We'll do the call
1161   // sequence start and end here.
1162   if (!IsSibCall) {
1163     MIB->getOperand(1).setImm(FPDiff);
1164     CallSeqStart.addImm(0).addImm(0);
1165     // End the call sequence *before* emitting the call. Normally, we would
1166     // tidy the frame up after the call. However, here, we've laid out the
1167     // parameters so that when SP is reset, they will be in the correct
1168     // location.
1169     MIRBuilder.buildInstr(AArch64::ADJCALLSTACKUP).addImm(0).addImm(0);
1170   }
1171 
1172   // Now we can add the actual call instruction to the correct basic block.
1173   MIRBuilder.insertInstr(MIB);
1174 
1175   // If Callee is a reg, since it is used by a target specific instruction,
1176   // it must have a register class matching the constraint of that instruction.
1177   if (MIB->getOperand(0).isReg())
1178     constrainOperandRegClass(MF, *TRI, MRI, *MF.getSubtarget().getInstrInfo(),
1179                              *MF.getSubtarget().getRegBankInfo(), *MIB,
1180                              MIB->getDesc(), MIB->getOperand(0), 0);
1181 
1182   MF.getFrameInfo().setHasTailCall();
1183   Info.LoweredTailCall = true;
1184   return true;
1185 }
1186 
1187 bool AArch64CallLowering::lowerCall(MachineIRBuilder &MIRBuilder,
1188                                     CallLoweringInfo &Info) const {
1189   MachineFunction &MF = MIRBuilder.getMF();
1190   const Function &F = MF.getFunction();
1191   MachineRegisterInfo &MRI = MF.getRegInfo();
1192   auto &DL = F.getParent()->getDataLayout();
1193   const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
1194   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1195 
1196   // Arm64EC has extra requirements for varargs calls; bail out for now.
1197   if (Info.IsVarArg && Subtarget.isWindowsArm64EC())
1198     return false;
1199 
1200   SmallVector<ArgInfo, 8> OutArgs;
1201   for (auto &OrigArg : Info.OrigArgs) {
1202     splitToValueTypes(OrigArg, OutArgs, DL, Info.CallConv);
1203     // AAPCS requires that we zero-extend i1 to 8 bits by the caller.
1204     auto &Flags = OrigArg.Flags[0];
1205     if (OrigArg.Ty->isIntegerTy(1) && !Flags.isSExt() && !Flags.isZExt()) {
1206       ArgInfo &OutArg = OutArgs.back();
1207       assert(OutArg.Regs.size() == 1 &&
1208              MRI.getType(OutArg.Regs[0]).getSizeInBits() == 1 &&
1209              "Unexpected registers used for i1 arg");
1210 
1211       // We cannot use a ZExt ArgInfo flag here, because it will
1212       // zero-extend the argument to i32 instead of just i8.
1213       OutArg.Regs[0] =
1214           MIRBuilder.buildZExt(LLT::scalar(8), OutArg.Regs[0]).getReg(0);
1215       LLVMContext &Ctx = MF.getFunction().getContext();
1216       OutArg.Ty = Type::getInt8Ty(Ctx);
1217     }
1218   }
1219 
1220   SmallVector<ArgInfo, 8> InArgs;
1221   if (!Info.OrigRet.Ty->isVoidTy())
1222     splitToValueTypes(Info.OrigRet, InArgs, DL, Info.CallConv);
1223 
1224   // If we can lower as a tail call, do that instead.
1225   bool CanTailCallOpt =
1226       isEligibleForTailCallOptimization(MIRBuilder, Info, InArgs, OutArgs);
1227 
1228   // We must emit a tail call if we have musttail.
1229   if (Info.IsMustTailCall && !CanTailCallOpt) {
1230     // There are types of incoming/outgoing arguments we can't handle yet, so
1231     // it doesn't make sense to actually die here like in ISelLowering. Instead,
1232     // fall back to SelectionDAG and let it try to handle this.
1233     LLVM_DEBUG(dbgs() << "Failed to lower musttail call as tail call\n");
1234     return false;
1235   }
1236 
1237   Info.IsTailCall = CanTailCallOpt;
1238   if (CanTailCallOpt)
1239     return lowerTailCall(MIRBuilder, Info, OutArgs);
1240 
1241   // Find out which ABI gets to decide where things go.
1242   CCAssignFn *AssignFnFixed;
1243   CCAssignFn *AssignFnVarArg;
1244   std::tie(AssignFnFixed, AssignFnVarArg) =
1245       getAssignFnsForCC(Info.CallConv, TLI);
1246 
1247   MachineInstrBuilder CallSeqStart;
1248   CallSeqStart = MIRBuilder.buildInstr(AArch64::ADJCALLSTACKDOWN);
1249 
1250   // Create a temporarily-floating call instruction so we can add the implicit
1251   // uses of arg registers.
1252 
1253   unsigned Opc = 0;
1254   // Calls with operand bundle "clang.arc.attachedcall" are special. They should
1255   // be expanded to the call, directly followed by a special marker sequence and
1256   // a call to an ObjC library function.
1257   if (Info.CB && objcarc::hasAttachedCallOpBundle(Info.CB))
1258     Opc = AArch64::BLR_RVMARKER;
1259   // A call to a returns twice function like setjmp must be followed by a bti
1260   // instruction.
1261   else if (Info.CB && Info.CB->hasFnAttr(Attribute::ReturnsTwice) &&
1262            !Subtarget.noBTIAtReturnTwice() &&
1263            MF.getInfo<AArch64FunctionInfo>()->branchTargetEnforcement())
1264     Opc = AArch64::BLR_BTI;
1265   else
1266     Opc = getCallOpcode(MF, Info.Callee.isReg(), false);
1267 
1268   auto MIB = MIRBuilder.buildInstrNoInsert(Opc);
1269   unsigned CalleeOpNo = 0;
1270 
1271   if (Opc == AArch64::BLR_RVMARKER) {
1272     // Add a target global address for the retainRV/claimRV runtime function
1273     // just before the call target.
1274     Function *ARCFn = *objcarc::getAttachedARCFunction(Info.CB);
1275     MIB.addGlobalAddress(ARCFn);
1276     ++CalleeOpNo;
1277   } else if (Info.CFIType) {
1278     MIB->setCFIType(MF, Info.CFIType->getZExtValue());
1279   }
1280 
1281   MIB.add(Info.Callee);
1282 
1283   // Tell the call which registers are clobbered.
1284   const uint32_t *Mask;
1285   const auto *TRI = Subtarget.getRegisterInfo();
1286 
1287   AArch64OutgoingValueAssigner Assigner(AssignFnFixed, AssignFnVarArg,
1288                                         Subtarget, /*IsReturn*/ false);
1289   // Do the actual argument marshalling.
1290   OutgoingArgHandler Handler(MIRBuilder, MRI, MIB, /*IsReturn*/ false);
1291   if (!determineAndHandleAssignments(Handler, Assigner, OutArgs, MIRBuilder,
1292                                      Info.CallConv, Info.IsVarArg))
1293     return false;
1294 
1295   Mask = getMaskForArgs(OutArgs, Info, *TRI, MF);
1296 
1297   if (MF.getSubtarget<AArch64Subtarget>().hasCustomCallingConv())
1298     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
1299   MIB.addRegMask(Mask);
1300 
1301   if (TRI->isAnyArgRegReserved(MF))
1302     TRI->emitReservedArgRegCallError(MF);
1303 
1304   // Now we can add the actual call instruction to the correct basic block.
1305   MIRBuilder.insertInstr(MIB);
1306 
1307   uint64_t CalleePopBytes =
1308       doesCalleeRestoreStack(Info.CallConv,
1309                              MF.getTarget().Options.GuaranteedTailCallOpt)
1310           ? alignTo(Assigner.StackSize, 16)
1311           : 0;
1312 
1313   CallSeqStart.addImm(Assigner.StackSize).addImm(0);
1314   MIRBuilder.buildInstr(AArch64::ADJCALLSTACKUP)
1315       .addImm(Assigner.StackSize)
1316       .addImm(CalleePopBytes);
1317 
1318   // If Callee is a reg, since it is used by a target specific
1319   // instruction, it must have a register class matching the
1320   // constraint of that instruction.
1321   if (MIB->getOperand(CalleeOpNo).isReg())
1322     constrainOperandRegClass(MF, *TRI, MRI, *Subtarget.getInstrInfo(),
1323                              *Subtarget.getRegBankInfo(), *MIB, MIB->getDesc(),
1324                              MIB->getOperand(CalleeOpNo), CalleeOpNo);
1325 
1326   // Finally we can copy the returned value back into its virtual-register. In
1327   // symmetry with the arguments, the physical register must be an
1328   // implicit-define of the call instruction.
1329   if (Info.CanLowerReturn  && !Info.OrigRet.Ty->isVoidTy()) {
1330     CCAssignFn *RetAssignFn = TLI.CCAssignFnForReturn(Info.CallConv);
1331     CallReturnHandler Handler(MIRBuilder, MRI, MIB);
1332     bool UsingReturnedArg =
1333         !OutArgs.empty() && OutArgs[0].Flags[0].isReturned();
1334 
1335     AArch64OutgoingValueAssigner Assigner(RetAssignFn, RetAssignFn, Subtarget,
1336                                           /*IsReturn*/ false);
1337     ReturnedArgCallReturnHandler ReturnedArgHandler(MIRBuilder, MRI, MIB);
1338     if (!determineAndHandleAssignments(
1339             UsingReturnedArg ? ReturnedArgHandler : Handler, Assigner, InArgs,
1340             MIRBuilder, Info.CallConv, Info.IsVarArg,
1341             UsingReturnedArg ? ArrayRef(OutArgs[0].Regs) : std::nullopt))
1342       return false;
1343   }
1344 
1345   if (Info.SwiftErrorVReg) {
1346     MIB.addDef(AArch64::X21, RegState::Implicit);
1347     MIRBuilder.buildCopy(Info.SwiftErrorVReg, Register(AArch64::X21));
1348   }
1349 
1350   if (!Info.CanLowerReturn) {
1351     insertSRetLoads(MIRBuilder, Info.OrigRet.Ty, Info.OrigRet.Regs,
1352                     Info.DemoteRegister, Info.DemoteStackIndex);
1353   }
1354   return true;
1355 }
1356 
1357 bool AArch64CallLowering::isTypeIsValidForThisReturn(EVT Ty) const {
1358   return Ty.getSizeInBits() == 64;
1359 }
1360