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