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