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 "AArch64Subtarget.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/CodeGen/Analysis.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
24 #include "llvm/CodeGen/GlobalISel/Utils.h"
25 #include "llvm/CodeGen/LowLevelType.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineMemOperand.h"
31 #include "llvm/CodeGen/MachineOperand.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/TargetRegisterInfo.h"
34 #include "llvm/CodeGen/TargetSubtargetInfo.h"
35 #include "llvm/CodeGen/ValueTypes.h"
36 #include "llvm/IR/Argument.h"
37 #include "llvm/IR/Attributes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/IR/Value.h"
41 #include "llvm/Support/MachineValueType.h"
42 #include <algorithm>
43 #include <cassert>
44 #include <cstdint>
45 #include <iterator>
46 
47 #define DEBUG_TYPE "aarch64-call-lowering"
48 
49 using namespace llvm;
50 
51 AArch64CallLowering::AArch64CallLowering(const AArch64TargetLowering &TLI)
52   : CallLowering(&TLI) {}
53 
54 namespace {
55 struct IncomingArgHandler : public CallLowering::IncomingValueHandler {
56   IncomingArgHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
57                      CCAssignFn *AssignFn)
58       : IncomingValueHandler(MIRBuilder, MRI, AssignFn), StackUsed(0) {}
59 
60   Register getStackAddress(uint64_t Size, int64_t Offset,
61                            MachinePointerInfo &MPO,
62                            ISD::ArgFlagsTy Flags) override {
63     auto &MFI = MIRBuilder.getMF().getFrameInfo();
64 
65     // Byval is assumed to be writable memory, but other stack passed arguments
66     // are not.
67     const bool IsImmutable = !Flags.isByVal();
68 
69     int FI = MFI.CreateFixedObject(Size, Offset, IsImmutable);
70     MPO = MachinePointerInfo::getFixedStack(MIRBuilder.getMF(), FI);
71     auto AddrReg = MIRBuilder.buildFrameIndex(LLT::pointer(0, 64), FI);
72     StackUsed = std::max(StackUsed, Size + Offset);
73     return AddrReg.getReg(0);
74   }
75 
76   void assignValueToReg(Register ValVReg, Register PhysReg,
77                         CCValAssign &VA) override {
78     markPhysRegUsed(PhysReg);
79     IncomingValueHandler::assignValueToReg(ValVReg, PhysReg, VA);
80   }
81 
82   void assignValueToAddress(Register ValVReg, Register Addr, uint64_t MemSize,
83                             MachinePointerInfo &MPO, CCValAssign &VA) override {
84     MachineFunction &MF = MIRBuilder.getMF();
85 
86     // The reported memory location may be wider than the value.
87     const LLT RegTy = MRI.getType(ValVReg);
88     MemSize = std::min(static_cast<uint64_t>(RegTy.getSizeInBytes()), MemSize);
89 
90     auto MMO = MF.getMachineMemOperand(
91         MPO, MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
92         MemSize, inferAlignFromPtrInfo(MF, MPO));
93     const LLT LocVT = LLT{VA.getLocVT()};
94 
95     if (RegTy.getScalarSizeInBits() < LocVT.getScalarSizeInBits()) {
96       auto LocInfo = VA.getLocInfo();
97       if (LocInfo == CCValAssign::LocInfo::ZExt) {
98         // We know the parameter is zero-extended. Perform a load into LocVT,
99         // and use G_ASSERT_ZEXT to communicate that this was zero-extended from
100         // the parameter type. Move down to the parameter type using G_TRUNC.
101         MIRBuilder.buildTrunc(
102             ValVReg, MIRBuilder.buildAssertZExt(
103                          LocVT, MIRBuilder.buildLoad(LocVT, Addr, *MMO),
104                          RegTy.getScalarSizeInBits()));
105         return;
106       }
107 
108       if (LocInfo == CCValAssign::LocInfo::SExt) {
109         // Same as the ZExt case, but use G_ASSERT_SEXT instead.
110         MIRBuilder.buildTrunc(
111             ValVReg, MIRBuilder.buildAssertSExt(
112                          LocVT, MIRBuilder.buildLoad(LocVT, Addr, *MMO),
113                          RegTy.getScalarSizeInBits()));
114         return;
115       }
116     }
117 
118     // No extension information, or no extension necessary. Load into the
119     // incoming parameter type directly.
120     MIRBuilder.buildLoad(ValVReg, Addr, *MMO);
121   }
122 
123   /// How the physical register gets marked varies between formal
124   /// parameters (it's a basic-block live-in), and a call instruction
125   /// (it's an implicit-def of the BL).
126   virtual void markPhysRegUsed(MCRegister PhysReg) = 0;
127 
128   uint64_t StackUsed;
129 };
130 
131 struct FormalArgHandler : public IncomingArgHandler {
132   FormalArgHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
133                    CCAssignFn *AssignFn)
134     : IncomingArgHandler(MIRBuilder, MRI, AssignFn) {}
135 
136   void markPhysRegUsed(MCRegister PhysReg) override {
137     MIRBuilder.getMRI()->addLiveIn(PhysReg);
138     MIRBuilder.getMBB().addLiveIn(PhysReg);
139   }
140 };
141 
142 struct CallReturnHandler : public IncomingArgHandler {
143   CallReturnHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
144                     MachineInstrBuilder MIB, CCAssignFn *AssignFn)
145     : IncomingArgHandler(MIRBuilder, MRI, AssignFn), MIB(MIB) {}
146 
147   void markPhysRegUsed(MCRegister PhysReg) override {
148     MIB.addDef(PhysReg, RegState::Implicit);
149   }
150 
151   MachineInstrBuilder MIB;
152 };
153 
154 /// A special return arg handler for "returned" attribute arg calls.
155 struct ReturnedArgCallReturnHandler : public CallReturnHandler {
156   ReturnedArgCallReturnHandler(MachineIRBuilder &MIRBuilder,
157                                MachineRegisterInfo &MRI,
158                                MachineInstrBuilder MIB, CCAssignFn *AssignFn)
159       : CallReturnHandler(MIRBuilder, MRI, MIB, AssignFn) {}
160 
161   void markPhysRegUsed(MCRegister PhysReg) override {}
162 };
163 
164 struct OutgoingArgHandler : public CallLowering::OutgoingValueHandler {
165   OutgoingArgHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
166                      MachineInstrBuilder MIB, CCAssignFn *AssignFn,
167                      CCAssignFn *AssignFnVarArg, bool IsTailCall = false,
168                      int FPDiff = 0)
169       : OutgoingValueHandler(MIRBuilder, MRI, AssignFn), MIB(MIB),
170         AssignFnVarArg(AssignFnVarArg), IsTailCall(IsTailCall), FPDiff(FPDiff),
171         StackSize(0), SPReg(0) {}
172 
173   Register getStackAddress(uint64_t Size, int64_t Offset,
174                            MachinePointerInfo &MPO,
175                            ISD::ArgFlagsTy Flags) override {
176     MachineFunction &MF = MIRBuilder.getMF();
177     LLT p0 = LLT::pointer(0, 64);
178     LLT s64 = LLT::scalar(64);
179 
180     if (IsTailCall) {
181       assert(!Flags.isByVal() && "byval unhandled with tail calls");
182 
183       Offset += FPDiff;
184       int FI = MF.getFrameInfo().CreateFixedObject(Size, Offset, true);
185       auto FIReg = MIRBuilder.buildFrameIndex(p0, FI);
186       MPO = MachinePointerInfo::getFixedStack(MF, FI);
187       return FIReg.getReg(0);
188     }
189 
190     if (!SPReg)
191       SPReg = MIRBuilder.buildCopy(p0, Register(AArch64::SP)).getReg(0);
192 
193     auto OffsetReg = MIRBuilder.buildConstant(s64, Offset);
194 
195     auto AddrReg = MIRBuilder.buildPtrAdd(p0, SPReg, OffsetReg);
196 
197     MPO = MachinePointerInfo::getStack(MF, Offset);
198     return AddrReg.getReg(0);
199   }
200 
201   void assignValueToReg(Register ValVReg, Register PhysReg,
202                         CCValAssign &VA) override {
203     MIB.addUse(PhysReg, RegState::Implicit);
204     Register ExtReg = extendRegister(ValVReg, VA);
205     MIRBuilder.buildCopy(PhysReg, ExtReg);
206   }
207 
208   void assignValueToAddress(Register ValVReg, Register Addr, uint64_t Size,
209                             MachinePointerInfo &MPO, CCValAssign &VA) override {
210     MachineFunction &MF = MIRBuilder.getMF();
211     auto MMO = MF.getMachineMemOperand(MPO, MachineMemOperand::MOStore, Size,
212                                        inferAlignFromPtrInfo(MF, MPO));
213     MIRBuilder.buildStore(ValVReg, Addr, *MMO);
214   }
215 
216   void assignValueToAddress(const CallLowering::ArgInfo &Arg, unsigned RegIndex,
217                             Register Addr, uint64_t Size,
218                             MachinePointerInfo &MPO, CCValAssign &VA) override {
219     unsigned MaxSize = Size * 8;
220     // For varargs, we always want to extend them to 8 bytes, in which case
221     // we disable setting a max.
222     if (!Arg.IsFixed)
223       MaxSize = 0;
224 
225     Register ValVReg = VA.getLocInfo() != CCValAssign::LocInfo::FPExt
226                            ? extendRegister(Arg.Regs[RegIndex], VA, MaxSize)
227                            : Arg.Regs[0];
228 
229     // If we extended we might need to adjust the MMO's Size.
230     const LLT RegTy = MRI.getType(ValVReg);
231     if (RegTy.getSizeInBytes() > Size)
232       Size = RegTy.getSizeInBytes();
233 
234     assignValueToAddress(ValVReg, Addr, Size, MPO, VA);
235   }
236 
237   bool assignArg(unsigned ValNo, MVT ValVT, MVT LocVT,
238                  CCValAssign::LocInfo LocInfo,
239                  const CallLowering::ArgInfo &Info,
240                  ISD::ArgFlagsTy Flags,
241                  CCState &State) override {
242     bool Res;
243     if (Info.IsFixed)
244       Res = AssignFn(ValNo, ValVT, LocVT, LocInfo, Flags, State);
245     else
246       Res = AssignFnVarArg(ValNo, ValVT, LocVT, LocInfo, Flags, State);
247 
248     StackSize = State.getNextStackOffset();
249     return Res;
250   }
251 
252   MachineInstrBuilder MIB;
253   CCAssignFn *AssignFnVarArg;
254   bool IsTailCall;
255 
256   /// For tail calls, the byte offset of the call's argument area from the
257   /// callee's. Unused elsewhere.
258   int FPDiff;
259   uint64_t StackSize;
260 
261   // Cache the SP register vreg if we need it more than once in this call site.
262   Register SPReg;
263 };
264 } // namespace
265 
266 static bool doesCalleeRestoreStack(CallingConv::ID CallConv, bool TailCallOpt) {
267   return CallConv == CallingConv::Fast && TailCallOpt;
268 }
269 
270 bool AArch64CallLowering::lowerReturn(MachineIRBuilder &MIRBuilder,
271                                       const Value *Val,
272                                       ArrayRef<Register> VRegs,
273                                       FunctionLoweringInfo &FLI,
274                                       Register SwiftErrorVReg) const {
275   auto MIB = MIRBuilder.buildInstrNoInsert(AArch64::RET_ReallyLR);
276   assert(((Val && !VRegs.empty()) || (!Val && VRegs.empty())) &&
277          "Return value without a vreg");
278 
279   bool Success = true;
280   if (!VRegs.empty()) {
281     MachineFunction &MF = MIRBuilder.getMF();
282     const Function &F = MF.getFunction();
283 
284     MachineRegisterInfo &MRI = MF.getRegInfo();
285     const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
286     CCAssignFn *AssignFn = TLI.CCAssignFnForReturn(F.getCallingConv());
287     auto &DL = F.getParent()->getDataLayout();
288     LLVMContext &Ctx = Val->getType()->getContext();
289 
290     SmallVector<EVT, 4> SplitEVTs;
291     ComputeValueVTs(TLI, DL, Val->getType(), SplitEVTs);
292     assert(VRegs.size() == SplitEVTs.size() &&
293            "For each split Type there should be exactly one VReg.");
294 
295     SmallVector<ArgInfo, 8> SplitArgs;
296     CallingConv::ID CC = F.getCallingConv();
297 
298     for (unsigned i = 0; i < SplitEVTs.size(); ++i) {
299       if (TLI.getNumRegistersForCallingConv(Ctx, CC, SplitEVTs[i]) > 1) {
300         LLVM_DEBUG(dbgs() << "Can't handle extended arg types which need split");
301         return false;
302       }
303 
304       Register CurVReg = VRegs[i];
305       ArgInfo CurArgInfo = ArgInfo{CurVReg, SplitEVTs[i].getTypeForEVT(Ctx)};
306       setArgFlags(CurArgInfo, AttributeList::ReturnIndex, DL, F);
307 
308       // i1 is a special case because SDAG i1 true is naturally zero extended
309       // when widened using ANYEXT. We need to do it explicitly here.
310       if (MRI.getType(CurVReg).getSizeInBits() == 1) {
311         CurVReg = MIRBuilder.buildZExt(LLT::scalar(8), CurVReg).getReg(0);
312       } else {
313         // Some types will need extending as specified by the CC.
314         MVT NewVT = TLI.getRegisterTypeForCallingConv(Ctx, CC, SplitEVTs[i]);
315         if (EVT(NewVT) != SplitEVTs[i]) {
316           unsigned ExtendOp = TargetOpcode::G_ANYEXT;
317           if (F.getAttributes().hasAttribute(AttributeList::ReturnIndex,
318                                              Attribute::SExt))
319             ExtendOp = TargetOpcode::G_SEXT;
320           else if (F.getAttributes().hasAttribute(AttributeList::ReturnIndex,
321                                                   Attribute::ZExt))
322             ExtendOp = TargetOpcode::G_ZEXT;
323 
324           LLT NewLLT(NewVT);
325           LLT OldLLT(MVT::getVT(CurArgInfo.Ty));
326           CurArgInfo.Ty = EVT(NewVT).getTypeForEVT(Ctx);
327           // Instead of an extend, we might have a vector type which needs
328           // padding with more elements, e.g. <2 x half> -> <4 x half>.
329           if (NewVT.isVector()) {
330             if (OldLLT.isVector()) {
331               if (NewLLT.getNumElements() > OldLLT.getNumElements()) {
332                 // We don't handle VA types which are not exactly twice the
333                 // size, but can easily be done in future.
334                 if (NewLLT.getNumElements() != OldLLT.getNumElements() * 2) {
335                   LLVM_DEBUG(dbgs() << "Outgoing vector ret has too many elts");
336                   return false;
337                 }
338                 auto Undef = MIRBuilder.buildUndef({OldLLT});
339                 CurVReg =
340                     MIRBuilder.buildMerge({NewLLT}, {CurVReg, Undef}).getReg(0);
341               } else {
342                 // Just do a vector extend.
343                 CurVReg = MIRBuilder.buildInstr(ExtendOp, {NewLLT}, {CurVReg})
344                               .getReg(0);
345               }
346             } else if (NewLLT.getNumElements() == 2) {
347               // We need to pad a <1 x S> type to <2 x S>. Since we don't have
348               // <1 x S> vector types in GISel we use a build_vector instead
349               // of a vector merge/concat.
350               auto Undef = MIRBuilder.buildUndef({OldLLT});
351               CurVReg =
352                   MIRBuilder
353                       .buildBuildVector({NewLLT}, {CurVReg, Undef.getReg(0)})
354                       .getReg(0);
355             } else {
356               LLVM_DEBUG(dbgs() << "Could not handle ret ty");
357               return false;
358             }
359           } else {
360             // If the split EVT was a <1 x T> vector, and NewVT is T, then we
361             // don't have to do anything since we don't distinguish between the
362             // two.
363             if (NewLLT != MRI.getType(CurVReg)) {
364               // A scalar extend.
365               CurVReg = MIRBuilder.buildInstr(ExtendOp, {NewLLT}, {CurVReg})
366                             .getReg(0);
367             }
368           }
369         }
370       }
371       if (CurVReg != CurArgInfo.Regs[0]) {
372         CurArgInfo.Regs[0] = CurVReg;
373         // Reset the arg flags after modifying CurVReg.
374         setArgFlags(CurArgInfo, AttributeList::ReturnIndex, DL, F);
375       }
376       splitToValueTypes(CurArgInfo, SplitArgs, DL, CC);
377     }
378 
379     OutgoingArgHandler Handler(MIRBuilder, MRI, MIB, AssignFn, AssignFn);
380     Success =
381         handleAssignments(MIRBuilder, SplitArgs, Handler, CC, F.isVarArg());
382   }
383 
384   if (SwiftErrorVReg) {
385     MIB.addUse(AArch64::X21, RegState::Implicit);
386     MIRBuilder.buildCopy(AArch64::X21, SwiftErrorVReg);
387   }
388 
389   MIRBuilder.insertInstr(MIB);
390   return Success;
391 }
392 
393 /// Helper function to compute forwarded registers for musttail calls. Computes
394 /// the forwarded registers, sets MBB liveness, and emits COPY instructions that
395 /// can be used to save + restore registers later.
396 static void handleMustTailForwardedRegisters(MachineIRBuilder &MIRBuilder,
397                                              CCAssignFn *AssignFn) {
398   MachineBasicBlock &MBB = MIRBuilder.getMBB();
399   MachineFunction &MF = MIRBuilder.getMF();
400   MachineFrameInfo &MFI = MF.getFrameInfo();
401 
402   if (!MFI.hasMustTailInVarArgFunc())
403     return;
404 
405   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
406   const Function &F = MF.getFunction();
407   assert(F.isVarArg() && "Expected F to be vararg?");
408 
409   // Compute the set of forwarded registers. The rest are scratch.
410   SmallVector<CCValAssign, 16> ArgLocs;
411   CCState CCInfo(F.getCallingConv(), /*IsVarArg=*/true, MF, ArgLocs,
412                  F.getContext());
413   SmallVector<MVT, 2> RegParmTypes;
414   RegParmTypes.push_back(MVT::i64);
415   RegParmTypes.push_back(MVT::f128);
416 
417   // Later on, we can use this vector to restore the registers if necessary.
418   SmallVectorImpl<ForwardedRegister> &Forwards =
419       FuncInfo->getForwardedMustTailRegParms();
420   CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, AssignFn);
421 
422   // Conservatively forward X8, since it might be used for an aggregate
423   // return.
424   if (!CCInfo.isAllocated(AArch64::X8)) {
425     Register X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
426     Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
427   }
428 
429   // Add the forwards to the MachineBasicBlock and MachineFunction.
430   for (const auto &F : Forwards) {
431     MBB.addLiveIn(F.PReg);
432     MIRBuilder.buildCopy(Register(F.VReg), Register(F.PReg));
433   }
434 }
435 
436 bool AArch64CallLowering::fallBackToDAGISel(const MachineFunction &MF) const {
437   auto &F = MF.getFunction();
438   if (isa<ScalableVectorType>(F.getReturnType()))
439     return true;
440   if (llvm::any_of(F.args(), [](const Argument &A) {
441         return isa<ScalableVectorType>(A.getType());
442       }))
443     return true;
444   const auto &ST = MF.getSubtarget<AArch64Subtarget>();
445   LLVM_DEBUG(dbgs() << "Falling back to SDAG because we don't support no-NEON");
446   if (!ST.hasNEON() || !ST.hasFPARMv8())
447     return true;
448   return false;
449 }
450 
451 bool AArch64CallLowering::lowerFormalArguments(
452     MachineIRBuilder &MIRBuilder, const Function &F,
453     ArrayRef<ArrayRef<Register>> VRegs, FunctionLoweringInfo &FLI) const {
454   MachineFunction &MF = MIRBuilder.getMF();
455   MachineBasicBlock &MBB = MIRBuilder.getMBB();
456   MachineRegisterInfo &MRI = MF.getRegInfo();
457   auto &DL = F.getParent()->getDataLayout();
458 
459   SmallVector<ArgInfo, 8> SplitArgs;
460   unsigned i = 0;
461   for (auto &Arg : F.args()) {
462     if (DL.getTypeStoreSize(Arg.getType()).isZero())
463       continue;
464 
465     ArgInfo OrigArg{VRegs[i], Arg};
466     setArgFlags(OrigArg, i + AttributeList::FirstArgIndex, DL, F);
467 
468     splitToValueTypes(OrigArg, SplitArgs, DL, F.getCallingConv());
469     ++i;
470   }
471 
472   if (!MBB.empty())
473     MIRBuilder.setInstr(*MBB.begin());
474 
475   const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
476   CCAssignFn *AssignFn =
477       TLI.CCAssignFnForCall(F.getCallingConv(), /*IsVarArg=*/false);
478 
479   FormalArgHandler Handler(MIRBuilder, MRI, AssignFn);
480   if (!handleAssignments(MIRBuilder, SplitArgs, Handler, F.getCallingConv(),
481                          F.isVarArg()))
482     return false;
483 
484   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
485   uint64_t StackOffset = Handler.StackUsed;
486   if (F.isVarArg()) {
487     auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
488     if (!Subtarget.isTargetDarwin()) {
489         // FIXME: we need to reimplement saveVarArgsRegisters from
490       // AArch64ISelLowering.
491       return false;
492     }
493 
494     // We currently pass all varargs at 8-byte alignment, or 4 in ILP32.
495     StackOffset = alignTo(Handler.StackUsed, Subtarget.isTargetILP32() ? 4 : 8);
496 
497     auto &MFI = MIRBuilder.getMF().getFrameInfo();
498     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
499   }
500 
501   if (doesCalleeRestoreStack(F.getCallingConv(),
502                              MF.getTarget().Options.GuaranteedTailCallOpt)) {
503     // We have a non-standard ABI, so why not make full use of the stack that
504     // we're going to pop? It must be aligned to 16 B in any case.
505     StackOffset = alignTo(StackOffset, 16);
506 
507     // If we're expected to restore the stack (e.g. fastcc), then we'll be
508     // adding a multiple of 16.
509     FuncInfo->setArgumentStackToRestore(StackOffset);
510 
511     // Our own callers will guarantee that the space is free by giving an
512     // aligned value to CALLSEQ_START.
513   }
514 
515   // When we tail call, we need to check if the callee's arguments
516   // will fit on the caller's stack. So, whenever we lower formal arguments,
517   // we should keep track of this information, since we might lower a tail call
518   // in this function later.
519   FuncInfo->setBytesInStackArgArea(StackOffset);
520 
521   auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
522   if (Subtarget.hasCustomCallingConv())
523     Subtarget.getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
524 
525   handleMustTailForwardedRegisters(MIRBuilder, AssignFn);
526 
527   // Move back to the end of the basic block.
528   MIRBuilder.setMBB(MBB);
529 
530   return true;
531 }
532 
533 /// Return true if the calling convention is one that we can guarantee TCO for.
534 static bool canGuaranteeTCO(CallingConv::ID CC) {
535   return CC == CallingConv::Fast;
536 }
537 
538 /// Return true if we might ever do TCO for calls with this calling convention.
539 static bool mayTailCallThisCC(CallingConv::ID CC) {
540   switch (CC) {
541   case CallingConv::C:
542   case CallingConv::PreserveMost:
543   case CallingConv::Swift:
544     return true;
545   default:
546     return canGuaranteeTCO(CC);
547   }
548 }
549 
550 /// Returns a pair containing the fixed CCAssignFn and the vararg CCAssignFn for
551 /// CC.
552 static std::pair<CCAssignFn *, CCAssignFn *>
553 getAssignFnsForCC(CallingConv::ID CC, const AArch64TargetLowering &TLI) {
554   return {TLI.CCAssignFnForCall(CC, false), TLI.CCAssignFnForCall(CC, true)};
555 }
556 
557 bool AArch64CallLowering::doCallerAndCalleePassArgsTheSameWay(
558     CallLoweringInfo &Info, MachineFunction &MF,
559     SmallVectorImpl<ArgInfo> &InArgs) const {
560   const Function &CallerF = MF.getFunction();
561   CallingConv::ID CalleeCC = Info.CallConv;
562   CallingConv::ID CallerCC = CallerF.getCallingConv();
563 
564   // If the calling conventions match, then everything must be the same.
565   if (CalleeCC == CallerCC)
566     return true;
567 
568   // Check if the caller and callee will handle arguments in the same way.
569   const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
570   CCAssignFn *CalleeAssignFnFixed;
571   CCAssignFn *CalleeAssignFnVarArg;
572   std::tie(CalleeAssignFnFixed, CalleeAssignFnVarArg) =
573       getAssignFnsForCC(CalleeCC, TLI);
574 
575   CCAssignFn *CallerAssignFnFixed;
576   CCAssignFn *CallerAssignFnVarArg;
577   std::tie(CallerAssignFnFixed, CallerAssignFnVarArg) =
578       getAssignFnsForCC(CallerCC, TLI);
579 
580   if (!resultsCompatible(Info, MF, InArgs, *CalleeAssignFnFixed,
581                          *CalleeAssignFnVarArg, *CallerAssignFnFixed,
582                          *CallerAssignFnVarArg))
583     return false;
584 
585   // Make sure that the caller and callee preserve all of the same registers.
586   auto TRI = MF.getSubtarget<AArch64Subtarget>().getRegisterInfo();
587   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
588   const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
589   if (MF.getSubtarget<AArch64Subtarget>().hasCustomCallingConv()) {
590     TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
591     TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
592   }
593 
594   return TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved);
595 }
596 
597 bool AArch64CallLowering::areCalleeOutgoingArgsTailCallable(
598     CallLoweringInfo &Info, MachineFunction &MF,
599     SmallVectorImpl<ArgInfo> &OutArgs) const {
600   // If there are no outgoing arguments, then we are done.
601   if (OutArgs.empty())
602     return true;
603 
604   const Function &CallerF = MF.getFunction();
605   CallingConv::ID CalleeCC = Info.CallConv;
606   CallingConv::ID CallerCC = CallerF.getCallingConv();
607   const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
608 
609   CCAssignFn *AssignFnFixed;
610   CCAssignFn *AssignFnVarArg;
611   std::tie(AssignFnFixed, AssignFnVarArg) = getAssignFnsForCC(CalleeCC, TLI);
612 
613   // We have outgoing arguments. Make sure that we can tail call with them.
614   SmallVector<CCValAssign, 16> OutLocs;
615   CCState OutInfo(CalleeCC, false, MF, OutLocs, CallerF.getContext());
616 
617   if (!analyzeArgInfo(OutInfo, OutArgs, *AssignFnFixed, *AssignFnVarArg)) {
618     LLVM_DEBUG(dbgs() << "... Could not analyze call operands.\n");
619     return false;
620   }
621 
622   // Make sure that they can fit on the caller's stack.
623   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
624   if (OutInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) {
625     LLVM_DEBUG(dbgs() << "... Cannot fit call operands on caller's stack.\n");
626     return false;
627   }
628 
629   // Verify that the parameters in callee-saved registers match.
630   // TODO: Port this over to CallLowering as general code once swiftself is
631   // supported.
632   auto TRI = MF.getSubtarget<AArch64Subtarget>().getRegisterInfo();
633   const uint32_t *CallerPreservedMask = TRI->getCallPreservedMask(MF, CallerCC);
634   MachineRegisterInfo &MRI = MF.getRegInfo();
635 
636   if (Info.IsVarArg) {
637     // Be conservative and disallow variadic memory operands to match SDAG's
638     // behaviour.
639     // FIXME: If the caller's calling convention is C, then we can
640     // potentially use its argument area. However, for cases like fastcc,
641     // we can't do anything.
642     for (unsigned i = 0; i < OutLocs.size(); ++i) {
643       auto &ArgLoc = OutLocs[i];
644       if (ArgLoc.isRegLoc())
645         continue;
646 
647       LLVM_DEBUG(
648           dbgs()
649           << "... Cannot tail call vararg function with stack arguments\n");
650       return false;
651     }
652   }
653 
654   return parametersInCSRMatch(MRI, CallerPreservedMask, OutLocs, OutArgs);
655 }
656 
657 bool AArch64CallLowering::isEligibleForTailCallOptimization(
658     MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info,
659     SmallVectorImpl<ArgInfo> &InArgs,
660     SmallVectorImpl<ArgInfo> &OutArgs) const {
661 
662   // Must pass all target-independent checks in order to tail call optimize.
663   if (!Info.IsTailCall)
664     return false;
665 
666   CallingConv::ID CalleeCC = Info.CallConv;
667   MachineFunction &MF = MIRBuilder.getMF();
668   const Function &CallerF = MF.getFunction();
669 
670   LLVM_DEBUG(dbgs() << "Attempting to lower call as tail call\n");
671 
672   if (Info.SwiftErrorVReg) {
673     // TODO: We should handle this.
674     // Note that this is also handled by the check for no outgoing arguments.
675     // Proactively disabling this though, because the swifterror handling in
676     // lowerCall inserts a COPY *after* the location of the call.
677     LLVM_DEBUG(dbgs() << "... Cannot handle tail calls with swifterror yet.\n");
678     return false;
679   }
680 
681   if (!mayTailCallThisCC(CalleeCC)) {
682     LLVM_DEBUG(dbgs() << "... Calling convention cannot be tail called.\n");
683     return false;
684   }
685 
686   // Byval parameters hand the function a pointer directly into the stack area
687   // we want to reuse during a tail call. Working around this *is* possible (see
688   // X86).
689   //
690   // FIXME: In AArch64ISelLowering, this isn't worked around. Can/should we try
691   // it?
692   //
693   // On Windows, "inreg" attributes signify non-aggregate indirect returns.
694   // In this case, it is necessary to save/restore X0 in the callee. Tail
695   // call opt interferes with this. So we disable tail call opt when the
696   // caller has an argument with "inreg" attribute.
697   //
698   // FIXME: Check whether the callee also has an "inreg" argument.
699   //
700   // When the caller has a swifterror argument, we don't want to tail call
701   // because would have to move into the swifterror register before the
702   // tail call.
703   if (any_of(CallerF.args(), [](const Argument &A) {
704         return A.hasByValAttr() || A.hasInRegAttr() || A.hasSwiftErrorAttr();
705       })) {
706     LLVM_DEBUG(dbgs() << "... Cannot tail call from callers with byval, "
707                          "inreg, or swifterror arguments\n");
708     return false;
709   }
710 
711   // Externally-defined functions with weak linkage should not be
712   // tail-called on AArch64 when the OS does not support dynamic
713   // pre-emption of symbols, as the AAELF spec requires normal calls
714   // to undefined weak functions to be replaced with a NOP or jump to the
715   // next instruction. The behaviour of branch instructions in this
716   // situation (as used for tail calls) is implementation-defined, so we
717   // cannot rely on the linker replacing the tail call with a return.
718   if (Info.Callee.isGlobal()) {
719     const GlobalValue *GV = Info.Callee.getGlobal();
720     const Triple &TT = MF.getTarget().getTargetTriple();
721     if (GV->hasExternalWeakLinkage() &&
722         (!TT.isOSWindows() || TT.isOSBinFormatELF() ||
723          TT.isOSBinFormatMachO())) {
724       LLVM_DEBUG(dbgs() << "... Cannot tail call externally-defined function "
725                            "with weak linkage for this OS.\n");
726       return false;
727     }
728   }
729 
730   // If we have -tailcallopt, then we're done.
731   if (MF.getTarget().Options.GuaranteedTailCallOpt)
732     return canGuaranteeTCO(CalleeCC) && CalleeCC == CallerF.getCallingConv();
733 
734   // We don't have -tailcallopt, so we're allowed to change the ABI (sibcall).
735   // Try to find cases where we can do that.
736 
737   // I want anyone implementing a new calling convention to think long and hard
738   // about this assert.
739   assert((!Info.IsVarArg || CalleeCC == CallingConv::C) &&
740          "Unexpected variadic calling convention");
741 
742   // Verify that the incoming and outgoing arguments from the callee are
743   // safe to tail call.
744   if (!doCallerAndCalleePassArgsTheSameWay(Info, MF, InArgs)) {
745     LLVM_DEBUG(
746         dbgs()
747         << "... Caller and callee have incompatible calling conventions.\n");
748     return false;
749   }
750 
751   if (!areCalleeOutgoingArgsTailCallable(Info, MF, OutArgs))
752     return false;
753 
754   LLVM_DEBUG(
755       dbgs() << "... Call is eligible for tail call optimization.\n");
756   return true;
757 }
758 
759 static unsigned getCallOpcode(const MachineFunction &CallerF, bool IsIndirect,
760                               bool IsTailCall) {
761   if (!IsTailCall)
762     return IsIndirect ? getBLRCallOpcode(CallerF) : (unsigned)AArch64::BL;
763 
764   if (!IsIndirect)
765     return AArch64::TCRETURNdi;
766 
767   // When BTI is enabled, we need to use TCRETURNriBTI to make sure that we use
768   // x16 or x17.
769   if (CallerF.getInfo<AArch64FunctionInfo>()->branchTargetEnforcement())
770     return AArch64::TCRETURNriBTI;
771 
772   return AArch64::TCRETURNri;
773 }
774 
775 static const uint32_t *
776 getMaskForArgs(SmallVectorImpl<AArch64CallLowering::ArgInfo> &OutArgs,
777                AArch64CallLowering::CallLoweringInfo &Info,
778                const AArch64RegisterInfo &TRI, MachineFunction &MF) {
779   const uint32_t *Mask;
780   if (!OutArgs.empty() && OutArgs[0].Flags[0].isReturned()) {
781     // For 'this' returns, use the X0-preserving mask if applicable
782     Mask = TRI.getThisReturnPreservedMask(MF, Info.CallConv);
783     if (!Mask) {
784       OutArgs[0].Flags[0].setReturned(false);
785       Mask = TRI.getCallPreservedMask(MF, Info.CallConv);
786     }
787   } else {
788     Mask = TRI.getCallPreservedMask(MF, Info.CallConv);
789   }
790   return Mask;
791 }
792 
793 bool AArch64CallLowering::lowerTailCall(
794     MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info,
795     SmallVectorImpl<ArgInfo> &OutArgs) const {
796   MachineFunction &MF = MIRBuilder.getMF();
797   const Function &F = MF.getFunction();
798   MachineRegisterInfo &MRI = MF.getRegInfo();
799   const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
800   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
801 
802   // True when we're tail calling, but without -tailcallopt.
803   bool IsSibCall = !MF.getTarget().Options.GuaranteedTailCallOpt;
804 
805   // TODO: Right now, regbankselect doesn't know how to handle the rtcGPR64
806   // register class. Until we can do that, we should fall back here.
807   if (MF.getInfo<AArch64FunctionInfo>()->branchTargetEnforcement()) {
808     LLVM_DEBUG(
809         dbgs() << "Cannot lower indirect tail calls with BTI enabled yet.\n");
810     return false;
811   }
812 
813   // Find out which ABI gets to decide where things go.
814   CallingConv::ID CalleeCC = Info.CallConv;
815   CCAssignFn *AssignFnFixed;
816   CCAssignFn *AssignFnVarArg;
817   std::tie(AssignFnFixed, AssignFnVarArg) = getAssignFnsForCC(CalleeCC, TLI);
818 
819   MachineInstrBuilder CallSeqStart;
820   if (!IsSibCall)
821     CallSeqStart = MIRBuilder.buildInstr(AArch64::ADJCALLSTACKDOWN);
822 
823   unsigned Opc = getCallOpcode(MF, Info.Callee.isReg(), true);
824   auto MIB = MIRBuilder.buildInstrNoInsert(Opc);
825   MIB.add(Info.Callee);
826 
827   // Byte offset for the tail call. When we are sibcalling, this will always
828   // be 0.
829   MIB.addImm(0);
830 
831   // Tell the call which registers are clobbered.
832   auto TRI = MF.getSubtarget<AArch64Subtarget>().getRegisterInfo();
833   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CalleeCC);
834   if (MF.getSubtarget<AArch64Subtarget>().hasCustomCallingConv())
835     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
836   MIB.addRegMask(Mask);
837 
838   if (TRI->isAnyArgRegReserved(MF))
839     TRI->emitReservedArgRegCallError(MF);
840 
841   // FPDiff is the byte offset of the call's argument area from the callee's.
842   // Stores to callee stack arguments will be placed in FixedStackSlots offset
843   // by this amount for a tail call. In a sibling call it must be 0 because the
844   // caller will deallocate the entire stack and the callee still expects its
845   // arguments to begin at SP+0.
846   int FPDiff = 0;
847 
848   // This will be 0 for sibcalls, potentially nonzero for tail calls produced
849   // by -tailcallopt. For sibcalls, the memory operands for the call are
850   // already available in the caller's incoming argument space.
851   unsigned NumBytes = 0;
852   if (!IsSibCall) {
853     // We aren't sibcalling, so we need to compute FPDiff. We need to do this
854     // before handling assignments, because FPDiff must be known for memory
855     // arguments.
856     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
857     SmallVector<CCValAssign, 16> OutLocs;
858     CCState OutInfo(CalleeCC, false, MF, OutLocs, F.getContext());
859     analyzeArgInfo(OutInfo, OutArgs, *AssignFnFixed, *AssignFnVarArg);
860 
861     // The callee will pop the argument stack as a tail call. Thus, we must
862     // keep it 16-byte aligned.
863     NumBytes = alignTo(OutInfo.getNextStackOffset(), 16);
864 
865     // FPDiff will be negative if this tail call requires more space than we
866     // would automatically have in our incoming argument space. Positive if we
867     // actually shrink the stack.
868     FPDiff = NumReusableBytes - NumBytes;
869 
870     // The stack pointer must be 16-byte aligned at all times it's used for a
871     // memory operation, which in practice means at *all* times and in
872     // particular across call boundaries. Therefore our own arguments started at
873     // a 16-byte aligned SP and the delta applied for the tail call should
874     // satisfy the same constraint.
875     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
876   }
877 
878   const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
879 
880   // Do the actual argument marshalling.
881   OutgoingArgHandler Handler(MIRBuilder, MRI, MIB, AssignFnFixed,
882                              AssignFnVarArg, true, FPDiff);
883   if (!handleAssignments(MIRBuilder, OutArgs, Handler, CalleeCC, Info.IsVarArg))
884     return false;
885 
886   Mask = getMaskForArgs(OutArgs, Info, *TRI, MF);
887 
888   if (Info.IsVarArg && Info.IsMustTailCall) {
889     // Now we know what's being passed to the function. Add uses to the call for
890     // the forwarded registers that we *aren't* passing as parameters. This will
891     // preserve the copies we build earlier.
892     for (const auto &F : Forwards) {
893       Register ForwardedReg = F.PReg;
894       // If the register is already passed, or aliases a register which is
895       // already being passed, then skip it.
896       if (any_of(MIB->uses(), [&ForwardedReg, &TRI](const MachineOperand &Use) {
897             if (!Use.isReg())
898               return false;
899             return TRI->regsOverlap(Use.getReg(), ForwardedReg);
900           }))
901         continue;
902 
903       // We aren't passing it already, so we should add it to the call.
904       MIRBuilder.buildCopy(ForwardedReg, Register(F.VReg));
905       MIB.addReg(ForwardedReg, RegState::Implicit);
906     }
907   }
908 
909   // If we have -tailcallopt, we need to adjust the stack. We'll do the call
910   // sequence start and end here.
911   if (!IsSibCall) {
912     MIB->getOperand(1).setImm(FPDiff);
913     CallSeqStart.addImm(NumBytes).addImm(0);
914     // End the call sequence *before* emitting the call. Normally, we would
915     // tidy the frame up after the call. However, here, we've laid out the
916     // parameters so that when SP is reset, they will be in the correct
917     // location.
918     MIRBuilder.buildInstr(AArch64::ADJCALLSTACKUP).addImm(NumBytes).addImm(0);
919   }
920 
921   // Now we can add the actual call instruction to the correct basic block.
922   MIRBuilder.insertInstr(MIB);
923 
924   // If Callee is a reg, since it is used by a target specific instruction,
925   // it must have a register class matching the constraint of that instruction.
926   if (Info.Callee.isReg())
927     constrainOperandRegClass(MF, *TRI, MRI, *MF.getSubtarget().getInstrInfo(),
928                              *MF.getSubtarget().getRegBankInfo(), *MIB,
929                              MIB->getDesc(), Info.Callee, 0);
930 
931   MF.getFrameInfo().setHasTailCall();
932   Info.LoweredTailCall = true;
933   return true;
934 }
935 
936 bool AArch64CallLowering::lowerCall(MachineIRBuilder &MIRBuilder,
937                                     CallLoweringInfo &Info) const {
938   MachineFunction &MF = MIRBuilder.getMF();
939   const Function &F = MF.getFunction();
940   MachineRegisterInfo &MRI = MF.getRegInfo();
941   auto &DL = F.getParent()->getDataLayout();
942   const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
943 
944   SmallVector<ArgInfo, 8> OutArgs;
945   for (auto &OrigArg : Info.OrigArgs) {
946     splitToValueTypes(OrigArg, OutArgs, DL, Info.CallConv);
947     // AAPCS requires that we zero-extend i1 to 8 bits by the caller.
948     if (OrigArg.Ty->isIntegerTy(1))
949       OutArgs.back().Flags[0].setZExt();
950   }
951 
952   SmallVector<ArgInfo, 8> InArgs;
953   if (!Info.OrigRet.Ty->isVoidTy())
954     splitToValueTypes(Info.OrigRet, InArgs, DL, Info.CallConv);
955 
956   // If we can lower as a tail call, do that instead.
957   bool CanTailCallOpt =
958       isEligibleForTailCallOptimization(MIRBuilder, Info, InArgs, OutArgs);
959 
960   // We must emit a tail call if we have musttail.
961   if (Info.IsMustTailCall && !CanTailCallOpt) {
962     // There are types of incoming/outgoing arguments we can't handle yet, so
963     // it doesn't make sense to actually die here like in ISelLowering. Instead,
964     // fall back to SelectionDAG and let it try to handle this.
965     LLVM_DEBUG(dbgs() << "Failed to lower musttail call as tail call\n");
966     return false;
967   }
968 
969   if (CanTailCallOpt)
970     return lowerTailCall(MIRBuilder, Info, OutArgs);
971 
972   // Find out which ABI gets to decide where things go.
973   CCAssignFn *AssignFnFixed;
974   CCAssignFn *AssignFnVarArg;
975   std::tie(AssignFnFixed, AssignFnVarArg) =
976       getAssignFnsForCC(Info.CallConv, TLI);
977 
978   MachineInstrBuilder CallSeqStart;
979   CallSeqStart = MIRBuilder.buildInstr(AArch64::ADJCALLSTACKDOWN);
980 
981   // Create a temporarily-floating call instruction so we can add the implicit
982   // uses of arg registers.
983   unsigned Opc = getCallOpcode(MF, Info.Callee.isReg(), false);
984 
985   auto MIB = MIRBuilder.buildInstrNoInsert(Opc);
986   MIB.add(Info.Callee);
987 
988   // Tell the call which registers are clobbered.
989   const uint32_t *Mask;
990   const auto *TRI = MF.getSubtarget<AArch64Subtarget>().getRegisterInfo();
991 
992   // Do the actual argument marshalling.
993   OutgoingArgHandler Handler(MIRBuilder, MRI, MIB, AssignFnFixed,
994                              AssignFnVarArg, false);
995   if (!handleAssignments(MIRBuilder, OutArgs, Handler, Info.CallConv,
996                          Info.IsVarArg))
997     return false;
998 
999   Mask = getMaskForArgs(OutArgs, Info, *TRI, MF);
1000 
1001   if (MF.getSubtarget<AArch64Subtarget>().hasCustomCallingConv())
1002     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
1003   MIB.addRegMask(Mask);
1004 
1005   if (TRI->isAnyArgRegReserved(MF))
1006     TRI->emitReservedArgRegCallError(MF);
1007 
1008   // Now we can add the actual call instruction to the correct basic block.
1009   MIRBuilder.insertInstr(MIB);
1010 
1011   // If Callee is a reg, since it is used by a target specific
1012   // instruction, it must have a register class matching the
1013   // constraint of that instruction.
1014   if (Info.Callee.isReg())
1015     constrainOperandRegClass(MF, *TRI, MRI, *MF.getSubtarget().getInstrInfo(),
1016                              *MF.getSubtarget().getRegBankInfo(), *MIB,
1017                              MIB->getDesc(), Info.Callee, 0);
1018 
1019   // Finally we can copy the returned value back into its virtual-register. In
1020   // symmetry with the arguments, the physical register must be an
1021   // implicit-define of the call instruction.
1022   if (!Info.OrigRet.Ty->isVoidTy()) {
1023     CCAssignFn *RetAssignFn = TLI.CCAssignFnForReturn(Info.CallConv);
1024     CallReturnHandler Handler(MIRBuilder, MRI, MIB, RetAssignFn);
1025     bool UsingReturnedArg =
1026         !OutArgs.empty() && OutArgs[0].Flags[0].isReturned();
1027     ReturnedArgCallReturnHandler ReturnedArgHandler(MIRBuilder, MRI, MIB,
1028                                                     RetAssignFn);
1029     if (!handleAssignments(MIRBuilder, InArgs,
1030                            UsingReturnedArg ? ReturnedArgHandler : Handler,
1031                            Info.CallConv, Info.IsVarArg,
1032                            UsingReturnedArg ? OutArgs[0].Regs[0] : Register()))
1033       return false;
1034   }
1035 
1036   if (Info.SwiftErrorVReg) {
1037     MIB.addDef(AArch64::X21, RegState::Implicit);
1038     MIRBuilder.buildCopy(Info.SwiftErrorVReg, Register(AArch64::X21));
1039   }
1040 
1041   uint64_t CalleePopBytes =
1042       doesCalleeRestoreStack(Info.CallConv,
1043                              MF.getTarget().Options.GuaranteedTailCallOpt)
1044           ? alignTo(Handler.StackSize, 16)
1045           : 0;
1046 
1047   CallSeqStart.addImm(Handler.StackSize).addImm(0);
1048   MIRBuilder.buildInstr(AArch64::ADJCALLSTACKUP)
1049       .addImm(Handler.StackSize)
1050       .addImm(CalleePopBytes);
1051 
1052   return true;
1053 }
1054 
1055 bool AArch64CallLowering::isTypeIsValidForThisReturn(EVT Ty) const {
1056   return Ty.getSizeInBits() == 64;
1057 }
1058