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