xref: /freebsd/contrib/llvm-project/clang/lib/CodeGen/CGCall.cpp (revision 22d7dd834bc5cd189810e414701e3ad1e98102e4)
1 //===--- CGCall.cpp - Encapsulate calling convention details --------------===//
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 // These classes wrap the information about a call or function
10 // definition used to handle ABI compliancy.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CGCall.h"
15 #include "ABIInfo.h"
16 #include "CGBlocks.h"
17 #include "CGCXXABI.h"
18 #include "CGCleanup.h"
19 #include "CGRecordLayout.h"
20 #include "CodeGenFunction.h"
21 #include "CodeGenModule.h"
22 #include "TargetInfo.h"
23 #include "clang/AST/Attr.h"
24 #include "clang/AST/Decl.h"
25 #include "clang/AST/DeclCXX.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/Basic/CodeGenOptions.h"
28 #include "clang/Basic/TargetBuiltins.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/CodeGen/CGFunctionInfo.h"
31 #include "clang/CodeGen/SwiftCallingConv.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/IR/Assumptions.h"
35 #include "llvm/IR/Attributes.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/DataLayout.h"
38 #include "llvm/IR/InlineAsm.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/Transforms/Utils/Local.h"
43 #include <optional>
44 using namespace clang;
45 using namespace CodeGen;
46 
47 /***/
48 
49 unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC) {
50   switch (CC) {
51   default: return llvm::CallingConv::C;
52   case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
53   case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
54   case CC_X86RegCall: return llvm::CallingConv::X86_RegCall;
55   case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
56   case CC_Win64: return llvm::CallingConv::Win64;
57   case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
58   case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
59   case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
60   case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
61   // TODO: Add support for __pascal to LLVM.
62   case CC_X86Pascal: return llvm::CallingConv::C;
63   // TODO: Add support for __vectorcall to LLVM.
64   case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
65   case CC_AArch64VectorCall: return llvm::CallingConv::AArch64_VectorCall;
66   case CC_AArch64SVEPCS: return llvm::CallingConv::AArch64_SVE_VectorCall;
67   case CC_AMDGPUKernelCall: return llvm::CallingConv::AMDGPU_KERNEL;
68   case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
69   case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv();
70   case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
71   case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
72   case CC_Swift: return llvm::CallingConv::Swift;
73   case CC_SwiftAsync: return llvm::CallingConv::SwiftTail;
74   }
75 }
76 
77 /// Derives the 'this' type for codegen purposes, i.e. ignoring method CVR
78 /// qualification. Either or both of RD and MD may be null. A null RD indicates
79 /// that there is no meaningful 'this' type, and a null MD can occur when
80 /// calling a method pointer.
81 CanQualType CodeGenTypes::DeriveThisType(const CXXRecordDecl *RD,
82                                          const CXXMethodDecl *MD) {
83   QualType RecTy;
84   if (RD)
85     RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
86   else
87     RecTy = Context.VoidTy;
88 
89   if (MD)
90     RecTy = Context.getAddrSpaceQualType(RecTy, MD->getMethodQualifiers().getAddressSpace());
91   return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
92 }
93 
94 /// Returns the canonical formal type of the given C++ method.
95 static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
96   return MD->getType()->getCanonicalTypeUnqualified()
97            .getAs<FunctionProtoType>();
98 }
99 
100 /// Returns the "extra-canonicalized" return type, which discards
101 /// qualifiers on the return type.  Codegen doesn't care about them,
102 /// and it makes ABI code a little easier to be able to assume that
103 /// all parameter and return types are top-level unqualified.
104 static CanQualType GetReturnType(QualType RetTy) {
105   return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
106 }
107 
108 /// Arrange the argument and result information for a value of the given
109 /// unprototyped freestanding function type.
110 const CGFunctionInfo &
111 CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
112   // When translating an unprototyped function type, always use a
113   // variadic type.
114   return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
115                                  /*instanceMethod=*/false,
116                                  /*chainCall=*/false, std::nullopt,
117                                  FTNP->getExtInfo(), {}, RequiredArgs(0));
118 }
119 
120 static void addExtParameterInfosForCall(
121          llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
122                                         const FunctionProtoType *proto,
123                                         unsigned prefixArgs,
124                                         unsigned totalArgs) {
125   assert(proto->hasExtParameterInfos());
126   assert(paramInfos.size() <= prefixArgs);
127   assert(proto->getNumParams() + prefixArgs <= totalArgs);
128 
129   paramInfos.reserve(totalArgs);
130 
131   // Add default infos for any prefix args that don't already have infos.
132   paramInfos.resize(prefixArgs);
133 
134   // Add infos for the prototype.
135   for (const auto &ParamInfo : proto->getExtParameterInfos()) {
136     paramInfos.push_back(ParamInfo);
137     // pass_object_size params have no parameter info.
138     if (ParamInfo.hasPassObjectSize())
139       paramInfos.emplace_back();
140   }
141 
142   assert(paramInfos.size() <= totalArgs &&
143          "Did we forget to insert pass_object_size args?");
144   // Add default infos for the variadic and/or suffix arguments.
145   paramInfos.resize(totalArgs);
146 }
147 
148 /// Adds the formal parameters in FPT to the given prefix. If any parameter in
149 /// FPT has pass_object_size attrs, then we'll add parameters for those, too.
150 static void appendParameterTypes(const CodeGenTypes &CGT,
151                                  SmallVectorImpl<CanQualType> &prefix,
152               SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
153                                  CanQual<FunctionProtoType> FPT) {
154   // Fast path: don't touch param info if we don't need to.
155   if (!FPT->hasExtParameterInfos()) {
156     assert(paramInfos.empty() &&
157            "We have paramInfos, but the prototype doesn't?");
158     prefix.append(FPT->param_type_begin(), FPT->param_type_end());
159     return;
160   }
161 
162   unsigned PrefixSize = prefix.size();
163   // In the vast majority of cases, we'll have precisely FPT->getNumParams()
164   // parameters; the only thing that can change this is the presence of
165   // pass_object_size. So, we preallocate for the common case.
166   prefix.reserve(prefix.size() + FPT->getNumParams());
167 
168   auto ExtInfos = FPT->getExtParameterInfos();
169   assert(ExtInfos.size() == FPT->getNumParams());
170   for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
171     prefix.push_back(FPT->getParamType(I));
172     if (ExtInfos[I].hasPassObjectSize())
173       prefix.push_back(CGT.getContext().getSizeType());
174   }
175 
176   addExtParameterInfosForCall(paramInfos, FPT.getTypePtr(), PrefixSize,
177                               prefix.size());
178 }
179 
180 /// Arrange the LLVM function layout for a value of the given function
181 /// type, on top of any implicit parameters already stored.
182 static const CGFunctionInfo &
183 arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
184                         SmallVectorImpl<CanQualType> &prefix,
185                         CanQual<FunctionProtoType> FTP) {
186   SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
187   RequiredArgs Required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
188   // FIXME: Kill copy.
189   appendParameterTypes(CGT, prefix, paramInfos, FTP);
190   CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
191 
192   return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
193                                      /*chainCall=*/false, prefix,
194                                      FTP->getExtInfo(), paramInfos,
195                                      Required);
196 }
197 
198 /// Arrange the argument and result information for a value of the
199 /// given freestanding function type.
200 const CGFunctionInfo &
201 CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
202   SmallVector<CanQualType, 16> argTypes;
203   return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
204                                    FTP);
205 }
206 
207 static CallingConv getCallingConventionForDecl(const ObjCMethodDecl *D,
208                                                bool IsWindows) {
209   // Set the appropriate calling convention for the Function.
210   if (D->hasAttr<StdCallAttr>())
211     return CC_X86StdCall;
212 
213   if (D->hasAttr<FastCallAttr>())
214     return CC_X86FastCall;
215 
216   if (D->hasAttr<RegCallAttr>())
217     return CC_X86RegCall;
218 
219   if (D->hasAttr<ThisCallAttr>())
220     return CC_X86ThisCall;
221 
222   if (D->hasAttr<VectorCallAttr>())
223     return CC_X86VectorCall;
224 
225   if (D->hasAttr<PascalAttr>())
226     return CC_X86Pascal;
227 
228   if (PcsAttr *PCS = D->getAttr<PcsAttr>())
229     return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
230 
231   if (D->hasAttr<AArch64VectorPcsAttr>())
232     return CC_AArch64VectorCall;
233 
234   if (D->hasAttr<AArch64SVEPcsAttr>())
235     return CC_AArch64SVEPCS;
236 
237   if (D->hasAttr<AMDGPUKernelCallAttr>())
238     return CC_AMDGPUKernelCall;
239 
240   if (D->hasAttr<IntelOclBiccAttr>())
241     return CC_IntelOclBicc;
242 
243   if (D->hasAttr<MSABIAttr>())
244     return IsWindows ? CC_C : CC_Win64;
245 
246   if (D->hasAttr<SysVABIAttr>())
247     return IsWindows ? CC_X86_64SysV : CC_C;
248 
249   if (D->hasAttr<PreserveMostAttr>())
250     return CC_PreserveMost;
251 
252   if (D->hasAttr<PreserveAllAttr>())
253     return CC_PreserveAll;
254 
255   return CC_C;
256 }
257 
258 /// Arrange the argument and result information for a call to an
259 /// unknown C++ non-static member function of the given abstract type.
260 /// (A null RD means we don't have any meaningful "this" argument type,
261 ///  so fall back to a generic pointer type).
262 /// The member function must be an ordinary function, i.e. not a
263 /// constructor or destructor.
264 const CGFunctionInfo &
265 CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
266                                    const FunctionProtoType *FTP,
267                                    const CXXMethodDecl *MD) {
268   SmallVector<CanQualType, 16> argTypes;
269 
270   // Add the 'this' pointer.
271   argTypes.push_back(DeriveThisType(RD, MD));
272 
273   return ::arrangeLLVMFunctionInfo(
274       *this, true, argTypes,
275       FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
276 }
277 
278 /// Set calling convention for CUDA/HIP kernel.
279 static void setCUDAKernelCallingConvention(CanQualType &FTy, CodeGenModule &CGM,
280                                            const FunctionDecl *FD) {
281   if (FD->hasAttr<CUDAGlobalAttr>()) {
282     const FunctionType *FT = FTy->getAs<FunctionType>();
283     CGM.getTargetCodeGenInfo().setCUDAKernelCallingConvention(FT);
284     FTy = FT->getCanonicalTypeUnqualified();
285   }
286 }
287 
288 /// Arrange the argument and result information for a declaration or
289 /// definition of the given C++ non-static member function.  The
290 /// member function must be an ordinary function, i.e. not a
291 /// constructor or destructor.
292 const CGFunctionInfo &
293 CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
294   assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
295   assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
296 
297   CanQualType FT = GetFormalType(MD).getAs<Type>();
298   setCUDAKernelCallingConvention(FT, CGM, MD);
299   auto prototype = FT.getAs<FunctionProtoType>();
300 
301   if (MD->isInstance()) {
302     // The abstract case is perfectly fine.
303     const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
304     return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
305   }
306 
307   return arrangeFreeFunctionType(prototype);
308 }
309 
310 bool CodeGenTypes::inheritingCtorHasParams(
311     const InheritedConstructor &Inherited, CXXCtorType Type) {
312   // Parameters are unnecessary if we're constructing a base class subobject
313   // and the inherited constructor lives in a virtual base.
314   return Type == Ctor_Complete ||
315          !Inherited.getShadowDecl()->constructsVirtualBase() ||
316          !Target.getCXXABI().hasConstructorVariants();
317 }
318 
319 const CGFunctionInfo &
320 CodeGenTypes::arrangeCXXStructorDeclaration(GlobalDecl GD) {
321   auto *MD = cast<CXXMethodDecl>(GD.getDecl());
322 
323   SmallVector<CanQualType, 16> argTypes;
324   SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
325 
326   const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(GD);
327   argTypes.push_back(DeriveThisType(ThisType, MD));
328 
329   bool PassParams = true;
330 
331   if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
332     // A base class inheriting constructor doesn't get forwarded arguments
333     // needed to construct a virtual base (or base class thereof).
334     if (auto Inherited = CD->getInheritedConstructor())
335       PassParams = inheritingCtorHasParams(Inherited, GD.getCtorType());
336   }
337 
338   CanQual<FunctionProtoType> FTP = GetFormalType(MD);
339 
340   // Add the formal parameters.
341   if (PassParams)
342     appendParameterTypes(*this, argTypes, paramInfos, FTP);
343 
344   CGCXXABI::AddedStructorArgCounts AddedArgs =
345       TheCXXABI.buildStructorSignature(GD, argTypes);
346   if (!paramInfos.empty()) {
347     // Note: prefix implies after the first param.
348     if (AddedArgs.Prefix)
349       paramInfos.insert(paramInfos.begin() + 1, AddedArgs.Prefix,
350                         FunctionProtoType::ExtParameterInfo{});
351     if (AddedArgs.Suffix)
352       paramInfos.append(AddedArgs.Suffix,
353                         FunctionProtoType::ExtParameterInfo{});
354   }
355 
356   RequiredArgs required =
357       (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
358                                       : RequiredArgs::All);
359 
360   FunctionType::ExtInfo extInfo = FTP->getExtInfo();
361   CanQualType resultType = TheCXXABI.HasThisReturn(GD)
362                                ? argTypes.front()
363                                : TheCXXABI.hasMostDerivedReturn(GD)
364                                      ? CGM.getContext().VoidPtrTy
365                                      : Context.VoidTy;
366   return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
367                                  /*chainCall=*/false, argTypes, extInfo,
368                                  paramInfos, required);
369 }
370 
371 static SmallVector<CanQualType, 16>
372 getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
373   SmallVector<CanQualType, 16> argTypes;
374   for (auto &arg : args)
375     argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
376   return argTypes;
377 }
378 
379 static SmallVector<CanQualType, 16>
380 getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
381   SmallVector<CanQualType, 16> argTypes;
382   for (auto &arg : args)
383     argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
384   return argTypes;
385 }
386 
387 static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
388 getExtParameterInfosForCall(const FunctionProtoType *proto,
389                             unsigned prefixArgs, unsigned totalArgs) {
390   llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
391   if (proto->hasExtParameterInfos()) {
392     addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
393   }
394   return result;
395 }
396 
397 /// Arrange a call to a C++ method, passing the given arguments.
398 ///
399 /// ExtraPrefixArgs is the number of ABI-specific args passed after the `this`
400 /// parameter.
401 /// ExtraSuffixArgs is the number of ABI-specific args passed at the end of
402 /// args.
403 /// PassProtoArgs indicates whether `args` has args for the parameters in the
404 /// given CXXConstructorDecl.
405 const CGFunctionInfo &
406 CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
407                                         const CXXConstructorDecl *D,
408                                         CXXCtorType CtorKind,
409                                         unsigned ExtraPrefixArgs,
410                                         unsigned ExtraSuffixArgs,
411                                         bool PassProtoArgs) {
412   // FIXME: Kill copy.
413   SmallVector<CanQualType, 16> ArgTypes;
414   for (const auto &Arg : args)
415     ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
416 
417   // +1 for implicit this, which should always be args[0].
418   unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs;
419 
420   CanQual<FunctionProtoType> FPT = GetFormalType(D);
421   RequiredArgs Required = PassProtoArgs
422                               ? RequiredArgs::forPrototypePlus(
423                                     FPT, TotalPrefixArgs + ExtraSuffixArgs)
424                               : RequiredArgs::All;
425 
426   GlobalDecl GD(D, CtorKind);
427   CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
428                                ? ArgTypes.front()
429                                : TheCXXABI.hasMostDerivedReturn(GD)
430                                      ? CGM.getContext().VoidPtrTy
431                                      : Context.VoidTy;
432 
433   FunctionType::ExtInfo Info = FPT->getExtInfo();
434   llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> ParamInfos;
435   // If the prototype args are elided, we should only have ABI-specific args,
436   // which never have param info.
437   if (PassProtoArgs && FPT->hasExtParameterInfos()) {
438     // ABI-specific suffix arguments are treated the same as variadic arguments.
439     addExtParameterInfosForCall(ParamInfos, FPT.getTypePtr(), TotalPrefixArgs,
440                                 ArgTypes.size());
441   }
442   return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
443                                  /*chainCall=*/false, ArgTypes, Info,
444                                  ParamInfos, Required);
445 }
446 
447 /// Arrange the argument and result information for the declaration or
448 /// definition of the given function.
449 const CGFunctionInfo &
450 CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
451   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
452     if (MD->isInstance())
453       return arrangeCXXMethodDeclaration(MD);
454 
455   CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
456 
457   assert(isa<FunctionType>(FTy));
458   setCUDAKernelCallingConvention(FTy, CGM, FD);
459 
460   // When declaring a function without a prototype, always use a
461   // non-variadic type.
462   if (CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>()) {
463     return arrangeLLVMFunctionInfo(
464         noProto->getReturnType(), /*instanceMethod=*/false,
465         /*chainCall=*/false, std::nullopt, noProto->getExtInfo(), {},
466         RequiredArgs::All);
467   }
468 
469   return arrangeFreeFunctionType(FTy.castAs<FunctionProtoType>());
470 }
471 
472 /// Arrange the argument and result information for the declaration or
473 /// definition of an Objective-C method.
474 const CGFunctionInfo &
475 CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
476   // It happens that this is the same as a call with no optional
477   // arguments, except also using the formal 'self' type.
478   return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
479 }
480 
481 /// Arrange the argument and result information for the function type
482 /// through which to perform a send to the given Objective-C method,
483 /// using the given receiver type.  The receiver type is not always
484 /// the 'self' type of the method or even an Objective-C pointer type.
485 /// This is *not* the right method for actually performing such a
486 /// message send, due to the possibility of optional arguments.
487 const CGFunctionInfo &
488 CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
489                                               QualType receiverType) {
490   SmallVector<CanQualType, 16> argTys;
491   SmallVector<FunctionProtoType::ExtParameterInfo, 4> extParamInfos(
492       MD->isDirectMethod() ? 1 : 2);
493   argTys.push_back(Context.getCanonicalParamType(receiverType));
494   if (!MD->isDirectMethod())
495     argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
496   // FIXME: Kill copy?
497   for (const auto *I : MD->parameters()) {
498     argTys.push_back(Context.getCanonicalParamType(I->getType()));
499     auto extParamInfo = FunctionProtoType::ExtParameterInfo().withIsNoEscape(
500         I->hasAttr<NoEscapeAttr>());
501     extParamInfos.push_back(extParamInfo);
502   }
503 
504   FunctionType::ExtInfo einfo;
505   bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
506   einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
507 
508   if (getContext().getLangOpts().ObjCAutoRefCount &&
509       MD->hasAttr<NSReturnsRetainedAttr>())
510     einfo = einfo.withProducesResult(true);
511 
512   RequiredArgs required =
513     (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
514 
515   return arrangeLLVMFunctionInfo(
516       GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
517       /*chainCall=*/false, argTys, einfo, extParamInfos, required);
518 }
519 
520 const CGFunctionInfo &
521 CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
522                                                  const CallArgList &args) {
523   auto argTypes = getArgTypesForCall(Context, args);
524   FunctionType::ExtInfo einfo;
525 
526   return arrangeLLVMFunctionInfo(
527       GetReturnType(returnType), /*instanceMethod=*/false,
528       /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
529 }
530 
531 const CGFunctionInfo &
532 CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
533   // FIXME: Do we need to handle ObjCMethodDecl?
534   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
535 
536   if (isa<CXXConstructorDecl>(GD.getDecl()) ||
537       isa<CXXDestructorDecl>(GD.getDecl()))
538     return arrangeCXXStructorDeclaration(GD);
539 
540   return arrangeFunctionDeclaration(FD);
541 }
542 
543 /// Arrange a thunk that takes 'this' as the first parameter followed by
544 /// varargs.  Return a void pointer, regardless of the actual return type.
545 /// The body of the thunk will end in a musttail call to a function of the
546 /// correct type, and the caller will bitcast the function to the correct
547 /// prototype.
548 const CGFunctionInfo &
549 CodeGenTypes::arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD) {
550   assert(MD->isVirtual() && "only methods have thunks");
551   CanQual<FunctionProtoType> FTP = GetFormalType(MD);
552   CanQualType ArgTys[] = {DeriveThisType(MD->getParent(), MD)};
553   return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
554                                  /*chainCall=*/false, ArgTys,
555                                  FTP->getExtInfo(), {}, RequiredArgs(1));
556 }
557 
558 const CGFunctionInfo &
559 CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
560                                    CXXCtorType CT) {
561   assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
562 
563   CanQual<FunctionProtoType> FTP = GetFormalType(CD);
564   SmallVector<CanQualType, 2> ArgTys;
565   const CXXRecordDecl *RD = CD->getParent();
566   ArgTys.push_back(DeriveThisType(RD, CD));
567   if (CT == Ctor_CopyingClosure)
568     ArgTys.push_back(*FTP->param_type_begin());
569   if (RD->getNumVBases() > 0)
570     ArgTys.push_back(Context.IntTy);
571   CallingConv CC = Context.getDefaultCallingConvention(
572       /*IsVariadic=*/false, /*IsCXXMethod=*/true);
573   return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
574                                  /*chainCall=*/false, ArgTys,
575                                  FunctionType::ExtInfo(CC), {},
576                                  RequiredArgs::All);
577 }
578 
579 /// Arrange a call as unto a free function, except possibly with an
580 /// additional number of formal parameters considered required.
581 static const CGFunctionInfo &
582 arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
583                             CodeGenModule &CGM,
584                             const CallArgList &args,
585                             const FunctionType *fnType,
586                             unsigned numExtraRequiredArgs,
587                             bool chainCall) {
588   assert(args.size() >= numExtraRequiredArgs);
589 
590   llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
591 
592   // In most cases, there are no optional arguments.
593   RequiredArgs required = RequiredArgs::All;
594 
595   // If we have a variadic prototype, the required arguments are the
596   // extra prefix plus the arguments in the prototype.
597   if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
598     if (proto->isVariadic())
599       required = RequiredArgs::forPrototypePlus(proto, numExtraRequiredArgs);
600 
601     if (proto->hasExtParameterInfos())
602       addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
603                                   args.size());
604 
605   // If we don't have a prototype at all, but we're supposed to
606   // explicitly use the variadic convention for unprototyped calls,
607   // treat all of the arguments as required but preserve the nominal
608   // possibility of variadics.
609   } else if (CGM.getTargetCodeGenInfo()
610                 .isNoProtoCallVariadic(args,
611                                        cast<FunctionNoProtoType>(fnType))) {
612     required = RequiredArgs(args.size());
613   }
614 
615   // FIXME: Kill copy.
616   SmallVector<CanQualType, 16> argTypes;
617   for (const auto &arg : args)
618     argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
619   return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
620                                      /*instanceMethod=*/false, chainCall,
621                                      argTypes, fnType->getExtInfo(), paramInfos,
622                                      required);
623 }
624 
625 /// Figure out the rules for calling a function with the given formal
626 /// type using the given arguments.  The arguments are necessary
627 /// because the function might be unprototyped, in which case it's
628 /// target-dependent in crazy ways.
629 const CGFunctionInfo &
630 CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
631                                       const FunctionType *fnType,
632                                       bool chainCall) {
633   return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
634                                      chainCall ? 1 : 0, chainCall);
635 }
636 
637 /// A block function is essentially a free function with an
638 /// extra implicit argument.
639 const CGFunctionInfo &
640 CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
641                                        const FunctionType *fnType) {
642   return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
643                                      /*chainCall=*/false);
644 }
645 
646 const CGFunctionInfo &
647 CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
648                                               const FunctionArgList &params) {
649   auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
650   auto argTypes = getArgTypesForDeclaration(Context, params);
651 
652   return arrangeLLVMFunctionInfo(GetReturnType(proto->getReturnType()),
653                                  /*instanceMethod*/ false, /*chainCall*/ false,
654                                  argTypes, proto->getExtInfo(), paramInfos,
655                                  RequiredArgs::forPrototypePlus(proto, 1));
656 }
657 
658 const CGFunctionInfo &
659 CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
660                                          const CallArgList &args) {
661   // FIXME: Kill copy.
662   SmallVector<CanQualType, 16> argTypes;
663   for (const auto &Arg : args)
664     argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
665   return arrangeLLVMFunctionInfo(
666       GetReturnType(resultType), /*instanceMethod=*/false,
667       /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
668       /*paramInfos=*/ {}, RequiredArgs::All);
669 }
670 
671 const CGFunctionInfo &
672 CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
673                                                 const FunctionArgList &args) {
674   auto argTypes = getArgTypesForDeclaration(Context, args);
675 
676   return arrangeLLVMFunctionInfo(
677       GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
678       argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
679 }
680 
681 const CGFunctionInfo &
682 CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
683                                               ArrayRef<CanQualType> argTypes) {
684   return arrangeLLVMFunctionInfo(
685       resultType, /*instanceMethod=*/false, /*chainCall=*/false,
686       argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
687 }
688 
689 /// Arrange a call to a C++ method, passing the given arguments.
690 ///
691 /// numPrefixArgs is the number of ABI-specific prefix arguments we have. It
692 /// does not count `this`.
693 const CGFunctionInfo &
694 CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
695                                    const FunctionProtoType *proto,
696                                    RequiredArgs required,
697                                    unsigned numPrefixArgs) {
698   assert(numPrefixArgs + 1 <= args.size() &&
699          "Emitting a call with less args than the required prefix?");
700   // Add one to account for `this`. It's a bit awkward here, but we don't count
701   // `this` in similar places elsewhere.
702   auto paramInfos =
703     getExtParameterInfosForCall(proto, numPrefixArgs + 1, args.size());
704 
705   // FIXME: Kill copy.
706   auto argTypes = getArgTypesForCall(Context, args);
707 
708   FunctionType::ExtInfo info = proto->getExtInfo();
709   return arrangeLLVMFunctionInfo(
710       GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
711       /*chainCall=*/false, argTypes, info, paramInfos, required);
712 }
713 
714 const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
715   return arrangeLLVMFunctionInfo(
716       getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
717       std::nullopt, FunctionType::ExtInfo(), {}, RequiredArgs::All);
718 }
719 
720 const CGFunctionInfo &
721 CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
722                           const CallArgList &args) {
723   assert(signature.arg_size() <= args.size());
724   if (signature.arg_size() == args.size())
725     return signature;
726 
727   SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
728   auto sigParamInfos = signature.getExtParameterInfos();
729   if (!sigParamInfos.empty()) {
730     paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
731     paramInfos.resize(args.size());
732   }
733 
734   auto argTypes = getArgTypesForCall(Context, args);
735 
736   assert(signature.getRequiredArgs().allowsOptionalArgs());
737   return arrangeLLVMFunctionInfo(signature.getReturnType(),
738                                  signature.isInstanceMethod(),
739                                  signature.isChainCall(),
740                                  argTypes,
741                                  signature.getExtInfo(),
742                                  paramInfos,
743                                  signature.getRequiredArgs());
744 }
745 
746 namespace clang {
747 namespace CodeGen {
748 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI);
749 }
750 }
751 
752 /// Arrange the argument and result information for an abstract value
753 /// of a given function type.  This is the method which all of the
754 /// above functions ultimately defer to.
755 const CGFunctionInfo &
756 CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
757                                       bool instanceMethod,
758                                       bool chainCall,
759                                       ArrayRef<CanQualType> argTypes,
760                                       FunctionType::ExtInfo info,
761                      ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
762                                       RequiredArgs required) {
763   assert(llvm::all_of(argTypes,
764                       [](CanQualType T) { return T.isCanonicalAsParam(); }));
765 
766   // Lookup or create unique function info.
767   llvm::FoldingSetNodeID ID;
768   CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
769                           required, resultType, argTypes);
770 
771   void *insertPos = nullptr;
772   CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
773   if (FI)
774     return *FI;
775 
776   unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
777 
778   // Construct the function info.  We co-allocate the ArgInfos.
779   FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
780                               paramInfos, resultType, argTypes, required);
781   FunctionInfos.InsertNode(FI, insertPos);
782 
783   bool inserted = FunctionsBeingProcessed.insert(FI).second;
784   (void)inserted;
785   assert(inserted && "Recursively being processed?");
786 
787   // Compute ABI information.
788   if (CC == llvm::CallingConv::SPIR_KERNEL) {
789     // Force target independent argument handling for the host visible
790     // kernel functions.
791     computeSPIRKernelABIInfo(CGM, *FI);
792   } else if (info.getCC() == CC_Swift || info.getCC() == CC_SwiftAsync) {
793     swiftcall::computeABIInfo(CGM, *FI);
794   } else {
795     getABIInfo().computeInfo(*FI);
796   }
797 
798   // Loop over all of the computed argument and return value info.  If any of
799   // them are direct or extend without a specified coerce type, specify the
800   // default now.
801   ABIArgInfo &retInfo = FI->getReturnInfo();
802   if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
803     retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
804 
805   for (auto &I : FI->arguments())
806     if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
807       I.info.setCoerceToType(ConvertType(I.type));
808 
809   bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
810   assert(erased && "Not in set?");
811 
812   return *FI;
813 }
814 
815 CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
816                                        bool instanceMethod,
817                                        bool chainCall,
818                                        const FunctionType::ExtInfo &info,
819                                        ArrayRef<ExtParameterInfo> paramInfos,
820                                        CanQualType resultType,
821                                        ArrayRef<CanQualType> argTypes,
822                                        RequiredArgs required) {
823   assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
824   assert(!required.allowsOptionalArgs() ||
825          required.getNumRequiredArgs() <= argTypes.size());
826 
827   void *buffer =
828     operator new(totalSizeToAlloc<ArgInfo,             ExtParameterInfo>(
829                                   argTypes.size() + 1, paramInfos.size()));
830 
831   CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
832   FI->CallingConvention = llvmCC;
833   FI->EffectiveCallingConvention = llvmCC;
834   FI->ASTCallingConvention = info.getCC();
835   FI->InstanceMethod = instanceMethod;
836   FI->ChainCall = chainCall;
837   FI->CmseNSCall = info.getCmseNSCall();
838   FI->NoReturn = info.getNoReturn();
839   FI->ReturnsRetained = info.getProducesResult();
840   FI->NoCallerSavedRegs = info.getNoCallerSavedRegs();
841   FI->NoCfCheck = info.getNoCfCheck();
842   FI->Required = required;
843   FI->HasRegParm = info.getHasRegParm();
844   FI->RegParm = info.getRegParm();
845   FI->ArgStruct = nullptr;
846   FI->ArgStructAlign = 0;
847   FI->NumArgs = argTypes.size();
848   FI->HasExtParameterInfos = !paramInfos.empty();
849   FI->getArgsBuffer()[0].type = resultType;
850   FI->MaxVectorWidth = 0;
851   for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
852     FI->getArgsBuffer()[i + 1].type = argTypes[i];
853   for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
854     FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
855   return FI;
856 }
857 
858 /***/
859 
860 namespace {
861 // ABIArgInfo::Expand implementation.
862 
863 // Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
864 struct TypeExpansion {
865   enum TypeExpansionKind {
866     // Elements of constant arrays are expanded recursively.
867     TEK_ConstantArray,
868     // Record fields are expanded recursively (but if record is a union, only
869     // the field with the largest size is expanded).
870     TEK_Record,
871     // For complex types, real and imaginary parts are expanded recursively.
872     TEK_Complex,
873     // All other types are not expandable.
874     TEK_None
875   };
876 
877   const TypeExpansionKind Kind;
878 
879   TypeExpansion(TypeExpansionKind K) : Kind(K) {}
880   virtual ~TypeExpansion() {}
881 };
882 
883 struct ConstantArrayExpansion : TypeExpansion {
884   QualType EltTy;
885   uint64_t NumElts;
886 
887   ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
888       : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
889   static bool classof(const TypeExpansion *TE) {
890     return TE->Kind == TEK_ConstantArray;
891   }
892 };
893 
894 struct RecordExpansion : TypeExpansion {
895   SmallVector<const CXXBaseSpecifier *, 1> Bases;
896 
897   SmallVector<const FieldDecl *, 1> Fields;
898 
899   RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
900                   SmallVector<const FieldDecl *, 1> &&Fields)
901       : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
902         Fields(std::move(Fields)) {}
903   static bool classof(const TypeExpansion *TE) {
904     return TE->Kind == TEK_Record;
905   }
906 };
907 
908 struct ComplexExpansion : TypeExpansion {
909   QualType EltTy;
910 
911   ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
912   static bool classof(const TypeExpansion *TE) {
913     return TE->Kind == TEK_Complex;
914   }
915 };
916 
917 struct NoExpansion : TypeExpansion {
918   NoExpansion() : TypeExpansion(TEK_None) {}
919   static bool classof(const TypeExpansion *TE) {
920     return TE->Kind == TEK_None;
921   }
922 };
923 }  // namespace
924 
925 static std::unique_ptr<TypeExpansion>
926 getTypeExpansion(QualType Ty, const ASTContext &Context) {
927   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
928     return std::make_unique<ConstantArrayExpansion>(
929         AT->getElementType(), AT->getSize().getZExtValue());
930   }
931   if (const RecordType *RT = Ty->getAs<RecordType>()) {
932     SmallVector<const CXXBaseSpecifier *, 1> Bases;
933     SmallVector<const FieldDecl *, 1> Fields;
934     const RecordDecl *RD = RT->getDecl();
935     assert(!RD->hasFlexibleArrayMember() &&
936            "Cannot expand structure with flexible array.");
937     if (RD->isUnion()) {
938       // Unions can be here only in degenerative cases - all the fields are same
939       // after flattening. Thus we have to use the "largest" field.
940       const FieldDecl *LargestFD = nullptr;
941       CharUnits UnionSize = CharUnits::Zero();
942 
943       for (const auto *FD : RD->fields()) {
944         if (FD->isZeroLengthBitField(Context))
945           continue;
946         assert(!FD->isBitField() &&
947                "Cannot expand structure with bit-field members.");
948         CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
949         if (UnionSize < FieldSize) {
950           UnionSize = FieldSize;
951           LargestFD = FD;
952         }
953       }
954       if (LargestFD)
955         Fields.push_back(LargestFD);
956     } else {
957       if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
958         assert(!CXXRD->isDynamicClass() &&
959                "cannot expand vtable pointers in dynamic classes");
960         llvm::append_range(Bases, llvm::make_pointer_range(CXXRD->bases()));
961       }
962 
963       for (const auto *FD : RD->fields()) {
964         if (FD->isZeroLengthBitField(Context))
965           continue;
966         assert(!FD->isBitField() &&
967                "Cannot expand structure with bit-field members.");
968         Fields.push_back(FD);
969       }
970     }
971     return std::make_unique<RecordExpansion>(std::move(Bases),
972                                               std::move(Fields));
973   }
974   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
975     return std::make_unique<ComplexExpansion>(CT->getElementType());
976   }
977   return std::make_unique<NoExpansion>();
978 }
979 
980 static int getExpansionSize(QualType Ty, const ASTContext &Context) {
981   auto Exp = getTypeExpansion(Ty, Context);
982   if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
983     return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
984   }
985   if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
986     int Res = 0;
987     for (auto BS : RExp->Bases)
988       Res += getExpansionSize(BS->getType(), Context);
989     for (auto FD : RExp->Fields)
990       Res += getExpansionSize(FD->getType(), Context);
991     return Res;
992   }
993   if (isa<ComplexExpansion>(Exp.get()))
994     return 2;
995   assert(isa<NoExpansion>(Exp.get()));
996   return 1;
997 }
998 
999 void
1000 CodeGenTypes::getExpandedTypes(QualType Ty,
1001                                SmallVectorImpl<llvm::Type *>::iterator &TI) {
1002   auto Exp = getTypeExpansion(Ty, Context);
1003   if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1004     for (int i = 0, n = CAExp->NumElts; i < n; i++) {
1005       getExpandedTypes(CAExp->EltTy, TI);
1006     }
1007   } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1008     for (auto BS : RExp->Bases)
1009       getExpandedTypes(BS->getType(), TI);
1010     for (auto FD : RExp->Fields)
1011       getExpandedTypes(FD->getType(), TI);
1012   } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
1013     llvm::Type *EltTy = ConvertType(CExp->EltTy);
1014     *TI++ = EltTy;
1015     *TI++ = EltTy;
1016   } else {
1017     assert(isa<NoExpansion>(Exp.get()));
1018     *TI++ = ConvertType(Ty);
1019   }
1020 }
1021 
1022 static void forConstantArrayExpansion(CodeGenFunction &CGF,
1023                                       ConstantArrayExpansion *CAE,
1024                                       Address BaseAddr,
1025                                       llvm::function_ref<void(Address)> Fn) {
1026   CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
1027   CharUnits EltAlign =
1028     BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
1029   llvm::Type *EltTy = CGF.ConvertTypeForMem(CAE->EltTy);
1030 
1031   for (int i = 0, n = CAE->NumElts; i < n; i++) {
1032     llvm::Value *EltAddr = CGF.Builder.CreateConstGEP2_32(
1033         BaseAddr.getElementType(), BaseAddr.getPointer(), 0, i);
1034     Fn(Address(EltAddr, EltTy, EltAlign));
1035   }
1036 }
1037 
1038 void CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
1039                                          llvm::Function::arg_iterator &AI) {
1040   assert(LV.isSimple() &&
1041          "Unexpected non-simple lvalue during struct expansion.");
1042 
1043   auto Exp = getTypeExpansion(Ty, getContext());
1044   if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1045     forConstantArrayExpansion(
1046         *this, CAExp, LV.getAddress(*this), [&](Address EltAddr) {
1047           LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
1048           ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
1049         });
1050   } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1051     Address This = LV.getAddress(*this);
1052     for (const CXXBaseSpecifier *BS : RExp->Bases) {
1053       // Perform a single step derived-to-base conversion.
1054       Address Base =
1055           GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1056                                 /*NullCheckValue=*/false, SourceLocation());
1057       LValue SubLV = MakeAddrLValue(Base, BS->getType());
1058 
1059       // Recurse onto bases.
1060       ExpandTypeFromArgs(BS->getType(), SubLV, AI);
1061     }
1062     for (auto FD : RExp->Fields) {
1063       // FIXME: What are the right qualifiers here?
1064       LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
1065       ExpandTypeFromArgs(FD->getType(), SubLV, AI);
1066     }
1067   } else if (isa<ComplexExpansion>(Exp.get())) {
1068     auto realValue = &*AI++;
1069     auto imagValue = &*AI++;
1070     EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
1071   } else {
1072     // Call EmitStoreOfScalar except when the lvalue is a bitfield to emit a
1073     // primitive store.
1074     assert(isa<NoExpansion>(Exp.get()));
1075     llvm::Value *Arg = &*AI++;
1076     if (LV.isBitField()) {
1077       EmitStoreThroughLValue(RValue::get(Arg), LV);
1078     } else {
1079       // TODO: currently there are some places are inconsistent in what LLVM
1080       // pointer type they use (see D118744). Once clang uses opaque pointers
1081       // all LLVM pointer types will be the same and we can remove this check.
1082       if (Arg->getType()->isPointerTy()) {
1083         Address Addr = LV.getAddress(*this);
1084         Arg = Builder.CreateBitCast(Arg, Addr.getElementType());
1085       }
1086       EmitStoreOfScalar(Arg, LV);
1087     }
1088   }
1089 }
1090 
1091 void CodeGenFunction::ExpandTypeToArgs(
1092     QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
1093     SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
1094   auto Exp = getTypeExpansion(Ty, getContext());
1095   if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1096     Address Addr = Arg.hasLValue() ? Arg.getKnownLValue().getAddress(*this)
1097                                    : Arg.getKnownRValue().getAggregateAddress();
1098     forConstantArrayExpansion(
1099         *this, CAExp, Addr, [&](Address EltAddr) {
1100           CallArg EltArg = CallArg(
1101               convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation()),
1102               CAExp->EltTy);
1103           ExpandTypeToArgs(CAExp->EltTy, EltArg, IRFuncTy, IRCallArgs,
1104                            IRCallArgPos);
1105         });
1106   } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1107     Address This = Arg.hasLValue() ? Arg.getKnownLValue().getAddress(*this)
1108                                    : Arg.getKnownRValue().getAggregateAddress();
1109     for (const CXXBaseSpecifier *BS : RExp->Bases) {
1110       // Perform a single step derived-to-base conversion.
1111       Address Base =
1112           GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1113                                 /*NullCheckValue=*/false, SourceLocation());
1114       CallArg BaseArg = CallArg(RValue::getAggregate(Base), BS->getType());
1115 
1116       // Recurse onto bases.
1117       ExpandTypeToArgs(BS->getType(), BaseArg, IRFuncTy, IRCallArgs,
1118                        IRCallArgPos);
1119     }
1120 
1121     LValue LV = MakeAddrLValue(This, Ty);
1122     for (auto FD : RExp->Fields) {
1123       CallArg FldArg =
1124           CallArg(EmitRValueForField(LV, FD, SourceLocation()), FD->getType());
1125       ExpandTypeToArgs(FD->getType(), FldArg, IRFuncTy, IRCallArgs,
1126                        IRCallArgPos);
1127     }
1128   } else if (isa<ComplexExpansion>(Exp.get())) {
1129     ComplexPairTy CV = Arg.getKnownRValue().getComplexVal();
1130     IRCallArgs[IRCallArgPos++] = CV.first;
1131     IRCallArgs[IRCallArgPos++] = CV.second;
1132   } else {
1133     assert(isa<NoExpansion>(Exp.get()));
1134     auto RV = Arg.getKnownRValue();
1135     assert(RV.isScalar() &&
1136            "Unexpected non-scalar rvalue during struct expansion.");
1137 
1138     // Insert a bitcast as needed.
1139     llvm::Value *V = RV.getScalarVal();
1140     if (IRCallArgPos < IRFuncTy->getNumParams() &&
1141         V->getType() != IRFuncTy->getParamType(IRCallArgPos))
1142       V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
1143 
1144     IRCallArgs[IRCallArgPos++] = V;
1145   }
1146 }
1147 
1148 /// Create a temporary allocation for the purposes of coercion.
1149 static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
1150                                            CharUnits MinAlign,
1151                                            const Twine &Name = "tmp") {
1152   // Don't use an alignment that's worse than what LLVM would prefer.
1153   auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(Ty);
1154   CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
1155 
1156   return CGF.CreateTempAlloca(Ty, Align, Name + ".coerce");
1157 }
1158 
1159 /// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
1160 /// accessing some number of bytes out of it, try to gep into the struct to get
1161 /// at its inner goodness.  Dive as deep as possible without entering an element
1162 /// with an in-memory size smaller than DstSize.
1163 static Address
1164 EnterStructPointerForCoercedAccess(Address SrcPtr,
1165                                    llvm::StructType *SrcSTy,
1166                                    uint64_t DstSize, CodeGenFunction &CGF) {
1167   // We can't dive into a zero-element struct.
1168   if (SrcSTy->getNumElements() == 0) return SrcPtr;
1169 
1170   llvm::Type *FirstElt = SrcSTy->getElementType(0);
1171 
1172   // If the first elt is at least as large as what we're looking for, or if the
1173   // first element is the same size as the whole struct, we can enter it. The
1174   // comparison must be made on the store size and not the alloca size. Using
1175   // the alloca size may overstate the size of the load.
1176   uint64_t FirstEltSize =
1177     CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
1178   if (FirstEltSize < DstSize &&
1179       FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
1180     return SrcPtr;
1181 
1182   // GEP into the first element.
1183   SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, "coerce.dive");
1184 
1185   // If the first element is a struct, recurse.
1186   llvm::Type *SrcTy = SrcPtr.getElementType();
1187   if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
1188     return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
1189 
1190   return SrcPtr;
1191 }
1192 
1193 /// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1194 /// are either integers or pointers.  This does a truncation of the value if it
1195 /// is too large or a zero extension if it is too small.
1196 ///
1197 /// This behaves as if the value were coerced through memory, so on big-endian
1198 /// targets the high bits are preserved in a truncation, while little-endian
1199 /// targets preserve the low bits.
1200 static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
1201                                              llvm::Type *Ty,
1202                                              CodeGenFunction &CGF) {
1203   if (Val->getType() == Ty)
1204     return Val;
1205 
1206   if (isa<llvm::PointerType>(Val->getType())) {
1207     // If this is Pointer->Pointer avoid conversion to and from int.
1208     if (isa<llvm::PointerType>(Ty))
1209       return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
1210 
1211     // Convert the pointer to an integer so we can play with its width.
1212     Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
1213   }
1214 
1215   llvm::Type *DestIntTy = Ty;
1216   if (isa<llvm::PointerType>(DestIntTy))
1217     DestIntTy = CGF.IntPtrTy;
1218 
1219   if (Val->getType() != DestIntTy) {
1220     const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
1221     if (DL.isBigEndian()) {
1222       // Preserve the high bits on big-endian targets.
1223       // That is what memory coercion does.
1224       uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1225       uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1226 
1227       if (SrcSize > DstSize) {
1228         Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
1229         Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
1230       } else {
1231         Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
1232         Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
1233       }
1234     } else {
1235       // Little-endian targets preserve the low bits. No shifts required.
1236       Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
1237     }
1238   }
1239 
1240   if (isa<llvm::PointerType>(Ty))
1241     Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
1242   return Val;
1243 }
1244 
1245 
1246 
1247 /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
1248 /// a pointer to an object of type \arg Ty, known to be aligned to
1249 /// \arg SrcAlign bytes.
1250 ///
1251 /// This safely handles the case when the src type is smaller than the
1252 /// destination type; in this situation the values of bits which not
1253 /// present in the src are undefined.
1254 static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
1255                                       CodeGenFunction &CGF) {
1256   llvm::Type *SrcTy = Src.getElementType();
1257 
1258   // If SrcTy and Ty are the same, just do a load.
1259   if (SrcTy == Ty)
1260     return CGF.Builder.CreateLoad(Src);
1261 
1262   llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
1263 
1264   if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
1265     Src = EnterStructPointerForCoercedAccess(Src, SrcSTy,
1266                                              DstSize.getFixedValue(), CGF);
1267     SrcTy = Src.getElementType();
1268   }
1269 
1270   llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
1271 
1272   // If the source and destination are integer or pointer types, just do an
1273   // extension or truncation to the desired type.
1274   if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
1275       (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
1276     llvm::Value *Load = CGF.Builder.CreateLoad(Src);
1277     return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
1278   }
1279 
1280   // If load is legal, just bitcast the src pointer.
1281   if (!SrcSize.isScalable() && !DstSize.isScalable() &&
1282       SrcSize.getFixedValue() >= DstSize.getFixedValue()) {
1283     // Generally SrcSize is never greater than DstSize, since this means we are
1284     // losing bits. However, this can happen in cases where the structure has
1285     // additional padding, for example due to a user specified alignment.
1286     //
1287     // FIXME: Assert that we aren't truncating non-padding bits when have access
1288     // to that information.
1289     Src = CGF.Builder.CreateElementBitCast(Src, Ty);
1290     return CGF.Builder.CreateLoad(Src);
1291   }
1292 
1293   // If coercing a fixed vector to a scalable vector for ABI compatibility, and
1294   // the types match, use the llvm.vector.insert intrinsic to perform the
1295   // conversion.
1296   if (auto *ScalableDst = dyn_cast<llvm::ScalableVectorType>(Ty)) {
1297     if (auto *FixedSrc = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
1298       // If we are casting a fixed i8 vector to a scalable 16 x i1 predicate
1299       // vector, use a vector insert and bitcast the result.
1300       bool NeedsBitcast = false;
1301       auto PredType =
1302           llvm::ScalableVectorType::get(CGF.Builder.getInt1Ty(), 16);
1303       llvm::Type *OrigType = Ty;
1304       if (ScalableDst == PredType &&
1305           FixedSrc->getElementType() == CGF.Builder.getInt8Ty()) {
1306         ScalableDst = llvm::ScalableVectorType::get(CGF.Builder.getInt8Ty(), 2);
1307         NeedsBitcast = true;
1308       }
1309       if (ScalableDst->getElementType() == FixedSrc->getElementType()) {
1310         auto *Load = CGF.Builder.CreateLoad(Src);
1311         auto *UndefVec = llvm::UndefValue::get(ScalableDst);
1312         auto *Zero = llvm::Constant::getNullValue(CGF.CGM.Int64Ty);
1313         llvm::Value *Result = CGF.Builder.CreateInsertVector(
1314             ScalableDst, UndefVec, Load, Zero, "castScalableSve");
1315         if (NeedsBitcast)
1316           Result = CGF.Builder.CreateBitCast(Result, OrigType);
1317         return Result;
1318       }
1319     }
1320   }
1321 
1322   // Otherwise do coercion through memory. This is stupid, but simple.
1323   Address Tmp =
1324       CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment(), Src.getName());
1325   CGF.Builder.CreateMemCpy(
1326       Tmp.getPointer(), Tmp.getAlignment().getAsAlign(), Src.getPointer(),
1327       Src.getAlignment().getAsAlign(),
1328       llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize.getKnownMinValue()));
1329   return CGF.Builder.CreateLoad(Tmp);
1330 }
1331 
1332 // Function to store a first-class aggregate into memory.  We prefer to
1333 // store the elements rather than the aggregate to be more friendly to
1334 // fast-isel.
1335 // FIXME: Do we need to recurse here?
1336 void CodeGenFunction::EmitAggregateStore(llvm::Value *Val, Address Dest,
1337                                          bool DestIsVolatile) {
1338   // Prefer scalar stores to first-class aggregate stores.
1339   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(Val->getType())) {
1340     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1341       Address EltPtr = Builder.CreateStructGEP(Dest, i);
1342       llvm::Value *Elt = Builder.CreateExtractValue(Val, i);
1343       Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
1344     }
1345   } else {
1346     Builder.CreateStore(Val, Dest, DestIsVolatile);
1347   }
1348 }
1349 
1350 /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
1351 /// where the source and destination may have different types.  The
1352 /// destination is known to be aligned to \arg DstAlign bytes.
1353 ///
1354 /// This safely handles the case when the src type is larger than the
1355 /// destination type; the upper bits of the src will be lost.
1356 static void CreateCoercedStore(llvm::Value *Src,
1357                                Address Dst,
1358                                bool DstIsVolatile,
1359                                CodeGenFunction &CGF) {
1360   llvm::Type *SrcTy = Src->getType();
1361   llvm::Type *DstTy = Dst.getElementType();
1362   if (SrcTy == DstTy) {
1363     CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1364     return;
1365   }
1366 
1367   llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
1368 
1369   if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
1370     Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy,
1371                                              SrcSize.getFixedValue(), CGF);
1372     DstTy = Dst.getElementType();
1373   }
1374 
1375   llvm::PointerType *SrcPtrTy = llvm::dyn_cast<llvm::PointerType>(SrcTy);
1376   llvm::PointerType *DstPtrTy = llvm::dyn_cast<llvm::PointerType>(DstTy);
1377   if (SrcPtrTy && DstPtrTy &&
1378       SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace()) {
1379     Src = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy);
1380     CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1381     return;
1382   }
1383 
1384   // If the source and destination are integer or pointer types, just do an
1385   // extension or truncation to the desired type.
1386   if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1387       (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1388     Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
1389     CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1390     return;
1391   }
1392 
1393   llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
1394 
1395   // If store is legal, just bitcast the src pointer.
1396   if (isa<llvm::ScalableVectorType>(SrcTy) ||
1397       isa<llvm::ScalableVectorType>(DstTy) ||
1398       SrcSize.getFixedValue() <= DstSize.getFixedValue()) {
1399     Dst = CGF.Builder.CreateElementBitCast(Dst, SrcTy);
1400     CGF.EmitAggregateStore(Src, Dst, DstIsVolatile);
1401   } else {
1402     // Otherwise do coercion through memory. This is stupid, but
1403     // simple.
1404 
1405     // Generally SrcSize is never greater than DstSize, since this means we are
1406     // losing bits. However, this can happen in cases where the structure has
1407     // additional padding, for example due to a user specified alignment.
1408     //
1409     // FIXME: Assert that we aren't truncating non-padding bits when have access
1410     // to that information.
1411     Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1412     CGF.Builder.CreateStore(Src, Tmp);
1413     CGF.Builder.CreateMemCpy(
1414         Dst.getPointer(), Dst.getAlignment().getAsAlign(), Tmp.getPointer(),
1415         Tmp.getAlignment().getAsAlign(),
1416         llvm::ConstantInt::get(CGF.IntPtrTy, DstSize.getFixedValue()));
1417   }
1418 }
1419 
1420 static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
1421                                    const ABIArgInfo &info) {
1422   if (unsigned offset = info.getDirectOffset()) {
1423     addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
1424     addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1425                                              CharUnits::fromQuantity(offset));
1426     addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
1427   }
1428   return addr;
1429 }
1430 
1431 namespace {
1432 
1433 /// Encapsulates information about the way function arguments from
1434 /// CGFunctionInfo should be passed to actual LLVM IR function.
1435 class ClangToLLVMArgMapping {
1436   static const unsigned InvalidIndex = ~0U;
1437   unsigned InallocaArgNo;
1438   unsigned SRetArgNo;
1439   unsigned TotalIRArgs;
1440 
1441   /// Arguments of LLVM IR function corresponding to single Clang argument.
1442   struct IRArgs {
1443     unsigned PaddingArgIndex;
1444     // Argument is expanded to IR arguments at positions
1445     // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1446     unsigned FirstArgIndex;
1447     unsigned NumberOfArgs;
1448 
1449     IRArgs()
1450         : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1451           NumberOfArgs(0) {}
1452   };
1453 
1454   SmallVector<IRArgs, 8> ArgInfo;
1455 
1456 public:
1457   ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1458                         bool OnlyRequiredArgs = false)
1459       : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1460         ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1461     construct(Context, FI, OnlyRequiredArgs);
1462   }
1463 
1464   bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1465   unsigned getInallocaArgNo() const {
1466     assert(hasInallocaArg());
1467     return InallocaArgNo;
1468   }
1469 
1470   bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1471   unsigned getSRetArgNo() const {
1472     assert(hasSRetArg());
1473     return SRetArgNo;
1474   }
1475 
1476   unsigned totalIRArgs() const { return TotalIRArgs; }
1477 
1478   bool hasPaddingArg(unsigned ArgNo) const {
1479     assert(ArgNo < ArgInfo.size());
1480     return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1481   }
1482   unsigned getPaddingArgNo(unsigned ArgNo) const {
1483     assert(hasPaddingArg(ArgNo));
1484     return ArgInfo[ArgNo].PaddingArgIndex;
1485   }
1486 
1487   /// Returns index of first IR argument corresponding to ArgNo, and their
1488   /// quantity.
1489   std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1490     assert(ArgNo < ArgInfo.size());
1491     return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1492                           ArgInfo[ArgNo].NumberOfArgs);
1493   }
1494 
1495 private:
1496   void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1497                  bool OnlyRequiredArgs);
1498 };
1499 
1500 void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1501                                       const CGFunctionInfo &FI,
1502                                       bool OnlyRequiredArgs) {
1503   unsigned IRArgNo = 0;
1504   bool SwapThisWithSRet = false;
1505   const ABIArgInfo &RetAI = FI.getReturnInfo();
1506 
1507   if (RetAI.getKind() == ABIArgInfo::Indirect) {
1508     SwapThisWithSRet = RetAI.isSRetAfterThis();
1509     SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1510   }
1511 
1512   unsigned ArgNo = 0;
1513   unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1514   for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1515        ++I, ++ArgNo) {
1516     assert(I != FI.arg_end());
1517     QualType ArgType = I->type;
1518     const ABIArgInfo &AI = I->info;
1519     // Collect data about IR arguments corresponding to Clang argument ArgNo.
1520     auto &IRArgs = ArgInfo[ArgNo];
1521 
1522     if (AI.getPaddingType())
1523       IRArgs.PaddingArgIndex = IRArgNo++;
1524 
1525     switch (AI.getKind()) {
1526     case ABIArgInfo::Extend:
1527     case ABIArgInfo::Direct: {
1528       // FIXME: handle sseregparm someday...
1529       llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1530       if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1531         IRArgs.NumberOfArgs = STy->getNumElements();
1532       } else {
1533         IRArgs.NumberOfArgs = 1;
1534       }
1535       break;
1536     }
1537     case ABIArgInfo::Indirect:
1538     case ABIArgInfo::IndirectAliased:
1539       IRArgs.NumberOfArgs = 1;
1540       break;
1541     case ABIArgInfo::Ignore:
1542     case ABIArgInfo::InAlloca:
1543       // ignore and inalloca doesn't have matching LLVM parameters.
1544       IRArgs.NumberOfArgs = 0;
1545       break;
1546     case ABIArgInfo::CoerceAndExpand:
1547       IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1548       break;
1549     case ABIArgInfo::Expand:
1550       IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1551       break;
1552     }
1553 
1554     if (IRArgs.NumberOfArgs > 0) {
1555       IRArgs.FirstArgIndex = IRArgNo;
1556       IRArgNo += IRArgs.NumberOfArgs;
1557     }
1558 
1559     // Skip over the sret parameter when it comes second.  We already handled it
1560     // above.
1561     if (IRArgNo == 1 && SwapThisWithSRet)
1562       IRArgNo++;
1563   }
1564   assert(ArgNo == ArgInfo.size());
1565 
1566   if (FI.usesInAlloca())
1567     InallocaArgNo = IRArgNo++;
1568 
1569   TotalIRArgs = IRArgNo;
1570 }
1571 }  // namespace
1572 
1573 /***/
1574 
1575 bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
1576   const auto &RI = FI.getReturnInfo();
1577   return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet());
1578 }
1579 
1580 bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1581   return ReturnTypeUsesSRet(FI) &&
1582          getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1583 }
1584 
1585 bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1586   if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1587     switch (BT->getKind()) {
1588     default:
1589       return false;
1590     case BuiltinType::Float:
1591       return getTarget().useObjCFPRetForRealType(FloatModeKind::Float);
1592     case BuiltinType::Double:
1593       return getTarget().useObjCFPRetForRealType(FloatModeKind::Double);
1594     case BuiltinType::LongDouble:
1595       return getTarget().useObjCFPRetForRealType(FloatModeKind::LongDouble);
1596     }
1597   }
1598 
1599   return false;
1600 }
1601 
1602 bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1603   if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1604     if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1605       if (BT->getKind() == BuiltinType::LongDouble)
1606         return getTarget().useObjCFP2RetForComplexLongDouble();
1607     }
1608   }
1609 
1610   return false;
1611 }
1612 
1613 llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
1614   const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1615   return GetFunctionType(FI);
1616 }
1617 
1618 llvm::FunctionType *
1619 CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
1620 
1621   bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1622   (void)Inserted;
1623   assert(Inserted && "Recursively being processed?");
1624 
1625   llvm::Type *resultType = nullptr;
1626   const ABIArgInfo &retAI = FI.getReturnInfo();
1627   switch (retAI.getKind()) {
1628   case ABIArgInfo::Expand:
1629   case ABIArgInfo::IndirectAliased:
1630     llvm_unreachable("Invalid ABI kind for return argument");
1631 
1632   case ABIArgInfo::Extend:
1633   case ABIArgInfo::Direct:
1634     resultType = retAI.getCoerceToType();
1635     break;
1636 
1637   case ABIArgInfo::InAlloca:
1638     if (retAI.getInAllocaSRet()) {
1639       // sret things on win32 aren't void, they return the sret pointer.
1640       QualType ret = FI.getReturnType();
1641       llvm::Type *ty = ConvertType(ret);
1642       unsigned addressSpace = CGM.getTypes().getTargetAddressSpace(ret);
1643       resultType = llvm::PointerType::get(ty, addressSpace);
1644     } else {
1645       resultType = llvm::Type::getVoidTy(getLLVMContext());
1646     }
1647     break;
1648 
1649   case ABIArgInfo::Indirect:
1650   case ABIArgInfo::Ignore:
1651     resultType = llvm::Type::getVoidTy(getLLVMContext());
1652     break;
1653 
1654   case ABIArgInfo::CoerceAndExpand:
1655     resultType = retAI.getUnpaddedCoerceAndExpandType();
1656     break;
1657   }
1658 
1659   ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1660   SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1661 
1662   // Add type for sret argument.
1663   if (IRFunctionArgs.hasSRetArg()) {
1664     QualType Ret = FI.getReturnType();
1665     llvm::Type *Ty = ConvertType(Ret);
1666     unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(Ret);
1667     ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1668         llvm::PointerType::get(Ty, AddressSpace);
1669   }
1670 
1671   // Add type for inalloca argument.
1672   if (IRFunctionArgs.hasInallocaArg()) {
1673     auto ArgStruct = FI.getArgStruct();
1674     assert(ArgStruct);
1675     ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1676   }
1677 
1678   // Add in all of the required arguments.
1679   unsigned ArgNo = 0;
1680   CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1681                                      ie = it + FI.getNumRequiredArgs();
1682   for (; it != ie; ++it, ++ArgNo) {
1683     const ABIArgInfo &ArgInfo = it->info;
1684 
1685     // Insert a padding type to ensure proper alignment.
1686     if (IRFunctionArgs.hasPaddingArg(ArgNo))
1687       ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1688           ArgInfo.getPaddingType();
1689 
1690     unsigned FirstIRArg, NumIRArgs;
1691     std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1692 
1693     switch (ArgInfo.getKind()) {
1694     case ABIArgInfo::Ignore:
1695     case ABIArgInfo::InAlloca:
1696       assert(NumIRArgs == 0);
1697       break;
1698 
1699     case ABIArgInfo::Indirect: {
1700       assert(NumIRArgs == 1);
1701       // indirect arguments are always on the stack, which is alloca addr space.
1702       llvm::Type *LTy = ConvertTypeForMem(it->type);
1703       ArgTypes[FirstIRArg] = LTy->getPointerTo(
1704           CGM.getDataLayout().getAllocaAddrSpace());
1705       break;
1706     }
1707     case ABIArgInfo::IndirectAliased: {
1708       assert(NumIRArgs == 1);
1709       llvm::Type *LTy = ConvertTypeForMem(it->type);
1710       ArgTypes[FirstIRArg] = LTy->getPointerTo(ArgInfo.getIndirectAddrSpace());
1711       break;
1712     }
1713     case ABIArgInfo::Extend:
1714     case ABIArgInfo::Direct: {
1715       // Fast-isel and the optimizer generally like scalar values better than
1716       // FCAs, so we flatten them if this is safe to do for this argument.
1717       llvm::Type *argType = ArgInfo.getCoerceToType();
1718       llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
1719       if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1720         assert(NumIRArgs == st->getNumElements());
1721         for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
1722           ArgTypes[FirstIRArg + i] = st->getElementType(i);
1723       } else {
1724         assert(NumIRArgs == 1);
1725         ArgTypes[FirstIRArg] = argType;
1726       }
1727       break;
1728     }
1729 
1730     case ABIArgInfo::CoerceAndExpand: {
1731       auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1732       for (auto *EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1733         *ArgTypesIter++ = EltTy;
1734       }
1735       assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1736       break;
1737     }
1738 
1739     case ABIArgInfo::Expand:
1740       auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1741       getExpandedTypes(it->type, ArgTypesIter);
1742       assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1743       break;
1744     }
1745   }
1746 
1747   bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1748   assert(Erased && "Not in set?");
1749 
1750   return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
1751 }
1752 
1753 llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
1754   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1755   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
1756 
1757   if (!isFuncTypeConvertible(FPT))
1758     return llvm::StructType::get(getLLVMContext());
1759 
1760   return GetFunctionType(GD);
1761 }
1762 
1763 static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
1764                                                llvm::AttrBuilder &FuncAttrs,
1765                                                const FunctionProtoType *FPT) {
1766   if (!FPT)
1767     return;
1768 
1769   if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
1770       FPT->isNothrow())
1771     FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1772 }
1773 
1774 static void AddAttributesFromAssumes(llvm::AttrBuilder &FuncAttrs,
1775                                      const Decl *Callee) {
1776   if (!Callee)
1777     return;
1778 
1779   SmallVector<StringRef, 4> Attrs;
1780 
1781   for (const AssumptionAttr *AA : Callee->specific_attrs<AssumptionAttr>())
1782     AA->getAssumption().split(Attrs, ",");
1783 
1784   if (!Attrs.empty())
1785     FuncAttrs.addAttribute(llvm::AssumptionAttrKey,
1786                            llvm::join(Attrs.begin(), Attrs.end(), ","));
1787 }
1788 
1789 bool CodeGenModule::MayDropFunctionReturn(const ASTContext &Context,
1790                                           QualType ReturnType) const {
1791   // We can't just discard the return value for a record type with a
1792   // complex destructor or a non-trivially copyable type.
1793   if (const RecordType *RT =
1794           ReturnType.getCanonicalType()->getAs<RecordType>()) {
1795     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1796       return ClassDecl->hasTrivialDestructor();
1797   }
1798   return ReturnType.isTriviallyCopyableType(Context);
1799 }
1800 
1801 static bool HasStrictReturn(const CodeGenModule &Module, QualType RetTy,
1802                             const Decl *TargetDecl) {
1803   // As-is msan can not tolerate noundef mismatch between caller and
1804   // implementation. Mismatch is possible for e.g. indirect calls from C-caller
1805   // into C++. Such mismatches lead to confusing false reports. To avoid
1806   // expensive workaround on msan we enforce initialization event in uncommon
1807   // cases where it's allowed.
1808   if (Module.getLangOpts().Sanitize.has(SanitizerKind::Memory))
1809     return true;
1810   // C++ explicitly makes returning undefined values UB. C's rule only applies
1811   // to used values, so we never mark them noundef for now.
1812   if (!Module.getLangOpts().CPlusPlus)
1813     return false;
1814   if (TargetDecl) {
1815     if (const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(TargetDecl)) {
1816       if (FDecl->isExternC())
1817         return false;
1818     } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(TargetDecl)) {
1819       // Function pointer.
1820       if (VDecl->isExternC())
1821         return false;
1822     }
1823   }
1824 
1825   // We don't want to be too aggressive with the return checking, unless
1826   // it's explicit in the code opts or we're using an appropriate sanitizer.
1827   // Try to respect what the programmer intended.
1828   return Module.getCodeGenOpts().StrictReturn ||
1829          !Module.MayDropFunctionReturn(Module.getContext(), RetTy) ||
1830          Module.getLangOpts().Sanitize.has(SanitizerKind::Return);
1831 }
1832 
1833 void CodeGenModule::getDefaultFunctionAttributes(StringRef Name,
1834                                                  bool HasOptnone,
1835                                                  bool AttrOnCallSite,
1836                                                llvm::AttrBuilder &FuncAttrs) {
1837   // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1838   if (!HasOptnone) {
1839     if (CodeGenOpts.OptimizeSize)
1840       FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1841     if (CodeGenOpts.OptimizeSize == 2)
1842       FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1843   }
1844 
1845   if (CodeGenOpts.DisableRedZone)
1846     FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
1847   if (CodeGenOpts.IndirectTlsSegRefs)
1848     FuncAttrs.addAttribute("indirect-tls-seg-refs");
1849   if (CodeGenOpts.NoImplicitFloat)
1850     FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
1851 
1852   if (AttrOnCallSite) {
1853     // Attributes that should go on the call site only.
1854     // FIXME: Look for 'BuiltinAttr' on the function rather than re-checking
1855     // the -fno-builtin-foo list.
1856     if (!CodeGenOpts.SimplifyLibCalls || LangOpts.isNoBuiltinFunc(Name))
1857       FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
1858     if (!CodeGenOpts.TrapFuncName.empty())
1859       FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
1860   } else {
1861     switch (CodeGenOpts.getFramePointer()) {
1862     case CodeGenOptions::FramePointerKind::None:
1863       // This is the default behavior.
1864       break;
1865     case CodeGenOptions::FramePointerKind::NonLeaf:
1866     case CodeGenOptions::FramePointerKind::All:
1867       FuncAttrs.addAttribute("frame-pointer",
1868                              CodeGenOptions::getFramePointerKindName(
1869                                  CodeGenOpts.getFramePointer()));
1870     }
1871 
1872     if (CodeGenOpts.LessPreciseFPMAD)
1873       FuncAttrs.addAttribute("less-precise-fpmad", "true");
1874 
1875     if (CodeGenOpts.NullPointerIsValid)
1876       FuncAttrs.addAttribute(llvm::Attribute::NullPointerIsValid);
1877 
1878     if (CodeGenOpts.FPDenormalMode != llvm::DenormalMode::getIEEE())
1879       FuncAttrs.addAttribute("denormal-fp-math",
1880                              CodeGenOpts.FPDenormalMode.str());
1881     if (CodeGenOpts.FP32DenormalMode != CodeGenOpts.FPDenormalMode) {
1882       FuncAttrs.addAttribute(
1883           "denormal-fp-math-f32",
1884           CodeGenOpts.FP32DenormalMode.str());
1885     }
1886 
1887     if (LangOpts.getDefaultExceptionMode() == LangOptions::FPE_Ignore)
1888       FuncAttrs.addAttribute("no-trapping-math", "true");
1889 
1890     // TODO: Are these all needed?
1891     // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
1892     if (LangOpts.NoHonorInfs)
1893       FuncAttrs.addAttribute("no-infs-fp-math", "true");
1894     if (LangOpts.NoHonorNaNs)
1895       FuncAttrs.addAttribute("no-nans-fp-math", "true");
1896     if (LangOpts.ApproxFunc)
1897       FuncAttrs.addAttribute("approx-func-fp-math", "true");
1898     if (LangOpts.AllowFPReassoc && LangOpts.AllowRecip &&
1899         LangOpts.NoSignedZero && LangOpts.ApproxFunc &&
1900         (LangOpts.getDefaultFPContractMode() ==
1901              LangOptions::FPModeKind::FPM_Fast ||
1902          LangOpts.getDefaultFPContractMode() ==
1903              LangOptions::FPModeKind::FPM_FastHonorPragmas))
1904       FuncAttrs.addAttribute("unsafe-fp-math", "true");
1905     if (CodeGenOpts.SoftFloat)
1906       FuncAttrs.addAttribute("use-soft-float", "true");
1907     FuncAttrs.addAttribute("stack-protector-buffer-size",
1908                            llvm::utostr(CodeGenOpts.SSPBufferSize));
1909     if (LangOpts.NoSignedZero)
1910       FuncAttrs.addAttribute("no-signed-zeros-fp-math", "true");
1911 
1912     // TODO: Reciprocal estimate codegen options should apply to instructions?
1913     const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals;
1914     if (!Recips.empty())
1915       FuncAttrs.addAttribute("reciprocal-estimates",
1916                              llvm::join(Recips, ","));
1917 
1918     if (!CodeGenOpts.PreferVectorWidth.empty() &&
1919         CodeGenOpts.PreferVectorWidth != "none")
1920       FuncAttrs.addAttribute("prefer-vector-width",
1921                              CodeGenOpts.PreferVectorWidth);
1922 
1923     if (CodeGenOpts.StackRealignment)
1924       FuncAttrs.addAttribute("stackrealign");
1925     if (CodeGenOpts.Backchain)
1926       FuncAttrs.addAttribute("backchain");
1927     if (CodeGenOpts.EnableSegmentedStacks)
1928       FuncAttrs.addAttribute("split-stack");
1929 
1930     if (CodeGenOpts.SpeculativeLoadHardening)
1931       FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
1932 
1933     // Add zero-call-used-regs attribute.
1934     switch (CodeGenOpts.getZeroCallUsedRegs()) {
1935     case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Skip:
1936       FuncAttrs.removeAttribute("zero-call-used-regs");
1937       break;
1938     case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPRArg:
1939       FuncAttrs.addAttribute("zero-call-used-regs", "used-gpr-arg");
1940       break;
1941     case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPR:
1942       FuncAttrs.addAttribute("zero-call-used-regs", "used-gpr");
1943       break;
1944     case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedArg:
1945       FuncAttrs.addAttribute("zero-call-used-regs", "used-arg");
1946       break;
1947     case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Used:
1948       FuncAttrs.addAttribute("zero-call-used-regs", "used");
1949       break;
1950     case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPRArg:
1951       FuncAttrs.addAttribute("zero-call-used-regs", "all-gpr-arg");
1952       break;
1953     case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPR:
1954       FuncAttrs.addAttribute("zero-call-used-regs", "all-gpr");
1955       break;
1956     case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllArg:
1957       FuncAttrs.addAttribute("zero-call-used-regs", "all-arg");
1958       break;
1959     case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::All:
1960       FuncAttrs.addAttribute("zero-call-used-regs", "all");
1961       break;
1962     }
1963   }
1964 
1965   if (getLangOpts().assumeFunctionsAreConvergent()) {
1966     // Conservatively, mark all functions and calls in CUDA and OpenCL as
1967     // convergent (meaning, they may call an intrinsically convergent op, such
1968     // as __syncthreads() / barrier(), and so can't have certain optimizations
1969     // applied around them).  LLVM will remove this attribute where it safely
1970     // can.
1971     FuncAttrs.addAttribute(llvm::Attribute::Convergent);
1972   }
1973 
1974   // TODO: NoUnwind attribute should be added for other GPU modes HIP,
1975   // SYCL, OpenMP offload. AFAIK, none of them support exceptions in device
1976   // code.
1977   if ((getLangOpts().CUDA && getLangOpts().CUDAIsDevice) ||
1978       getLangOpts().OpenCL) {
1979     FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1980   }
1981 
1982   for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) {
1983     StringRef Var, Value;
1984     std::tie(Var, Value) = Attr.split('=');
1985     FuncAttrs.addAttribute(Var, Value);
1986   }
1987 }
1988 
1989 void CodeGenModule::addDefaultFunctionDefinitionAttributes(llvm::Function &F) {
1990   llvm::AttrBuilder FuncAttrs(F.getContext());
1991   getDefaultFunctionAttributes(F.getName(), F.hasOptNone(),
1992                                /* AttrOnCallSite = */ false, FuncAttrs);
1993   // TODO: call GetCPUAndFeaturesAttributes?
1994   F.addFnAttrs(FuncAttrs);
1995 }
1996 
1997 void CodeGenModule::addDefaultFunctionDefinitionAttributes(
1998                                                    llvm::AttrBuilder &attrs) {
1999   getDefaultFunctionAttributes(/*function name*/ "", /*optnone*/ false,
2000                                /*for call*/ false, attrs);
2001   GetCPUAndFeaturesAttributes(GlobalDecl(), attrs);
2002 }
2003 
2004 static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs,
2005                                    const LangOptions &LangOpts,
2006                                    const NoBuiltinAttr *NBA = nullptr) {
2007   auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) {
2008     SmallString<32> AttributeName;
2009     AttributeName += "no-builtin-";
2010     AttributeName += BuiltinName;
2011     FuncAttrs.addAttribute(AttributeName);
2012   };
2013 
2014   // First, handle the language options passed through -fno-builtin.
2015   if (LangOpts.NoBuiltin) {
2016     // -fno-builtin disables them all.
2017     FuncAttrs.addAttribute("no-builtins");
2018     return;
2019   }
2020 
2021   // Then, add attributes for builtins specified through -fno-builtin-<name>.
2022   llvm::for_each(LangOpts.NoBuiltinFuncs, AddNoBuiltinAttr);
2023 
2024   // Now, let's check the __attribute__((no_builtin("...")) attribute added to
2025   // the source.
2026   if (!NBA)
2027     return;
2028 
2029   // If there is a wildcard in the builtin names specified through the
2030   // attribute, disable them all.
2031   if (llvm::is_contained(NBA->builtinNames(), "*")) {
2032     FuncAttrs.addAttribute("no-builtins");
2033     return;
2034   }
2035 
2036   // And last, add the rest of the builtin names.
2037   llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr);
2038 }
2039 
2040 static bool DetermineNoUndef(QualType QTy, CodeGenTypes &Types,
2041                              const llvm::DataLayout &DL, const ABIArgInfo &AI,
2042                              bool CheckCoerce = true) {
2043   llvm::Type *Ty = Types.ConvertTypeForMem(QTy);
2044   if (AI.getKind() == ABIArgInfo::Indirect)
2045     return true;
2046   if (AI.getKind() == ABIArgInfo::Extend)
2047     return true;
2048   if (!DL.typeSizeEqualsStoreSize(Ty))
2049     // TODO: This will result in a modest amount of values not marked noundef
2050     // when they could be. We care about values that *invisibly* contain undef
2051     // bits from the perspective of LLVM IR.
2052     return false;
2053   if (CheckCoerce && AI.canHaveCoerceToType()) {
2054     llvm::Type *CoerceTy = AI.getCoerceToType();
2055     if (llvm::TypeSize::isKnownGT(DL.getTypeSizeInBits(CoerceTy),
2056                                   DL.getTypeSizeInBits(Ty)))
2057       // If we're coercing to a type with a greater size than the canonical one,
2058       // we're introducing new undef bits.
2059       // Coercing to a type of smaller or equal size is ok, as we know that
2060       // there's no internal padding (typeSizeEqualsStoreSize).
2061       return false;
2062   }
2063   if (QTy->isBitIntType())
2064     return true;
2065   if (QTy->isReferenceType())
2066     return true;
2067   if (QTy->isNullPtrType())
2068     return false;
2069   if (QTy->isMemberPointerType())
2070     // TODO: Some member pointers are `noundef`, but it depends on the ABI. For
2071     // now, never mark them.
2072     return false;
2073   if (QTy->isScalarType()) {
2074     if (const ComplexType *Complex = dyn_cast<ComplexType>(QTy))
2075       return DetermineNoUndef(Complex->getElementType(), Types, DL, AI, false);
2076     return true;
2077   }
2078   if (const VectorType *Vector = dyn_cast<VectorType>(QTy))
2079     return DetermineNoUndef(Vector->getElementType(), Types, DL, AI, false);
2080   if (const MatrixType *Matrix = dyn_cast<MatrixType>(QTy))
2081     return DetermineNoUndef(Matrix->getElementType(), Types, DL, AI, false);
2082   if (const ArrayType *Array = dyn_cast<ArrayType>(QTy))
2083     return DetermineNoUndef(Array->getElementType(), Types, DL, AI, false);
2084 
2085   // TODO: Some structs may be `noundef`, in specific situations.
2086   return false;
2087 }
2088 
2089 /// Check if the argument of a function has maybe_undef attribute.
2090 static bool IsArgumentMaybeUndef(const Decl *TargetDecl,
2091                                  unsigned NumRequiredArgs, unsigned ArgNo) {
2092   const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
2093   if (!FD)
2094     return false;
2095 
2096   // Assume variadic arguments do not have maybe_undef attribute.
2097   if (ArgNo >= NumRequiredArgs)
2098     return false;
2099 
2100   // Check if argument has maybe_undef attribute.
2101   if (ArgNo < FD->getNumParams()) {
2102     const ParmVarDecl *Param = FD->getParamDecl(ArgNo);
2103     if (Param && Param->hasAttr<MaybeUndefAttr>())
2104       return true;
2105   }
2106 
2107   return false;
2108 }
2109 
2110 /// Construct the IR attribute list of a function or call.
2111 ///
2112 /// When adding an attribute, please consider where it should be handled:
2113 ///
2114 ///   - getDefaultFunctionAttributes is for attributes that are essentially
2115 ///     part of the global target configuration (but perhaps can be
2116 ///     overridden on a per-function basis).  Adding attributes there
2117 ///     will cause them to also be set in frontends that build on Clang's
2118 ///     target-configuration logic, as well as for code defined in library
2119 ///     modules such as CUDA's libdevice.
2120 ///
2121 ///   - ConstructAttributeList builds on top of getDefaultFunctionAttributes
2122 ///     and adds declaration-specific, convention-specific, and
2123 ///     frontend-specific logic.  The last is of particular importance:
2124 ///     attributes that restrict how the frontend generates code must be
2125 ///     added here rather than getDefaultFunctionAttributes.
2126 ///
2127 void CodeGenModule::ConstructAttributeList(StringRef Name,
2128                                            const CGFunctionInfo &FI,
2129                                            CGCalleeInfo CalleeInfo,
2130                                            llvm::AttributeList &AttrList,
2131                                            unsigned &CallingConv,
2132                                            bool AttrOnCallSite, bool IsThunk) {
2133   llvm::AttrBuilder FuncAttrs(getLLVMContext());
2134   llvm::AttrBuilder RetAttrs(getLLVMContext());
2135 
2136   // Collect function IR attributes from the CC lowering.
2137   // We'll collect the paramete and result attributes later.
2138   CallingConv = FI.getEffectiveCallingConvention();
2139   if (FI.isNoReturn())
2140     FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2141   if (FI.isCmseNSCall())
2142     FuncAttrs.addAttribute("cmse_nonsecure_call");
2143 
2144   // Collect function IR attributes from the callee prototype if we have one.
2145   AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
2146                                      CalleeInfo.getCalleeFunctionProtoType());
2147 
2148   const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl();
2149 
2150   // Attach assumption attributes to the declaration. If this is a call
2151   // site, attach assumptions from the caller to the call as well.
2152   AddAttributesFromAssumes(FuncAttrs, TargetDecl);
2153 
2154   bool HasOptnone = false;
2155   // The NoBuiltinAttr attached to the target FunctionDecl.
2156   const NoBuiltinAttr *NBA = nullptr;
2157 
2158   // Some ABIs may result in additional accesses to arguments that may
2159   // otherwise not be present.
2160   auto AddPotentialArgAccess = [&]() {
2161     llvm::Attribute A = FuncAttrs.getAttribute(llvm::Attribute::Memory);
2162     if (A.isValid())
2163       FuncAttrs.addMemoryAttr(A.getMemoryEffects() |
2164                               llvm::MemoryEffects::argMemOnly());
2165   };
2166 
2167   // Collect function IR attributes based on declaration-specific
2168   // information.
2169   // FIXME: handle sseregparm someday...
2170   if (TargetDecl) {
2171     if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
2172       FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
2173     if (TargetDecl->hasAttr<NoThrowAttr>())
2174       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2175     if (TargetDecl->hasAttr<NoReturnAttr>())
2176       FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2177     if (TargetDecl->hasAttr<ColdAttr>())
2178       FuncAttrs.addAttribute(llvm::Attribute::Cold);
2179     if (TargetDecl->hasAttr<HotAttr>())
2180       FuncAttrs.addAttribute(llvm::Attribute::Hot);
2181     if (TargetDecl->hasAttr<NoDuplicateAttr>())
2182       FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
2183     if (TargetDecl->hasAttr<ConvergentAttr>())
2184       FuncAttrs.addAttribute(llvm::Attribute::Convergent);
2185 
2186     if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2187       AddAttributesFromFunctionProtoType(
2188           getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
2189       if (AttrOnCallSite && Fn->isReplaceableGlobalAllocationFunction()) {
2190         // A sane operator new returns a non-aliasing pointer.
2191         auto Kind = Fn->getDeclName().getCXXOverloadedOperator();
2192         if (getCodeGenOpts().AssumeSaneOperatorNew &&
2193             (Kind == OO_New || Kind == OO_Array_New))
2194           RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2195       }
2196       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
2197       const bool IsVirtualCall = MD && MD->isVirtual();
2198       // Don't use [[noreturn]], _Noreturn or [[no_builtin]] for a call to a
2199       // virtual function. These attributes are not inherited by overloads.
2200       if (!(AttrOnCallSite && IsVirtualCall)) {
2201         if (Fn->isNoReturn())
2202           FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2203         NBA = Fn->getAttr<NoBuiltinAttr>();
2204       }
2205       // Only place nomerge attribute on call sites, never functions. This
2206       // allows it to work on indirect virtual function calls.
2207       if (AttrOnCallSite && TargetDecl->hasAttr<NoMergeAttr>())
2208         FuncAttrs.addAttribute(llvm::Attribute::NoMerge);
2209     }
2210 
2211     // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
2212     if (TargetDecl->hasAttr<ConstAttr>()) {
2213       FuncAttrs.addMemoryAttr(llvm::MemoryEffects::none());
2214       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2215       // gcc specifies that 'const' functions have greater restrictions than
2216       // 'pure' functions, so they also cannot have infinite loops.
2217       FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
2218     } else if (TargetDecl->hasAttr<PureAttr>()) {
2219       FuncAttrs.addMemoryAttr(llvm::MemoryEffects::readOnly());
2220       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2221       // gcc specifies that 'pure' functions cannot have infinite loops.
2222       FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
2223     } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
2224       FuncAttrs.addMemoryAttr(llvm::MemoryEffects::argMemOnly());
2225       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2226     }
2227     if (TargetDecl->hasAttr<RestrictAttr>())
2228       RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2229     if (TargetDecl->hasAttr<ReturnsNonNullAttr>() &&
2230         !CodeGenOpts.NullPointerIsValid)
2231       RetAttrs.addAttribute(llvm::Attribute::NonNull);
2232     if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
2233       FuncAttrs.addAttribute("no_caller_saved_registers");
2234     if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>())
2235       FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck);
2236     if (TargetDecl->hasAttr<LeafAttr>())
2237       FuncAttrs.addAttribute(llvm::Attribute::NoCallback);
2238 
2239     HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
2240     if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
2241       std::optional<unsigned> NumElemsParam;
2242       if (AllocSize->getNumElemsParam().isValid())
2243         NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
2244       FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(),
2245                                  NumElemsParam);
2246     }
2247 
2248     if (TargetDecl->hasAttr<OpenCLKernelAttr>()) {
2249       if (getLangOpts().OpenCLVersion <= 120) {
2250         // OpenCL v1.2 Work groups are always uniform
2251         FuncAttrs.addAttribute("uniform-work-group-size", "true");
2252       } else {
2253         // OpenCL v2.0 Work groups may be whether uniform or not.
2254         // '-cl-uniform-work-group-size' compile option gets a hint
2255         // to the compiler that the global work-size be a multiple of
2256         // the work-group size specified to clEnqueueNDRangeKernel
2257         // (i.e. work groups are uniform).
2258         FuncAttrs.addAttribute("uniform-work-group-size",
2259                                llvm::toStringRef(CodeGenOpts.UniformWGSize));
2260       }
2261     }
2262   }
2263 
2264   // Attach "no-builtins" attributes to:
2265   // * call sites: both `nobuiltin` and "no-builtins" or "no-builtin-<name>".
2266   // * definitions: "no-builtins" or "no-builtin-<name>" only.
2267   // The attributes can come from:
2268   // * LangOpts: -ffreestanding, -fno-builtin, -fno-builtin-<name>
2269   // * FunctionDecl attributes: __attribute__((no_builtin(...)))
2270   addNoBuiltinAttributes(FuncAttrs, getLangOpts(), NBA);
2271 
2272   // Collect function IR attributes based on global settiings.
2273   getDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
2274 
2275   // Override some default IR attributes based on declaration-specific
2276   // information.
2277   if (TargetDecl) {
2278     if (TargetDecl->hasAttr<NoSpeculativeLoadHardeningAttr>())
2279       FuncAttrs.removeAttribute(llvm::Attribute::SpeculativeLoadHardening);
2280     if (TargetDecl->hasAttr<SpeculativeLoadHardeningAttr>())
2281       FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
2282     if (TargetDecl->hasAttr<NoSplitStackAttr>())
2283       FuncAttrs.removeAttribute("split-stack");
2284     if (TargetDecl->hasAttr<ZeroCallUsedRegsAttr>()) {
2285       // A function "__attribute__((...))" overrides the command-line flag.
2286       auto Kind =
2287           TargetDecl->getAttr<ZeroCallUsedRegsAttr>()->getZeroCallUsedRegs();
2288       FuncAttrs.removeAttribute("zero-call-used-regs");
2289       FuncAttrs.addAttribute(
2290           "zero-call-used-regs",
2291           ZeroCallUsedRegsAttr::ConvertZeroCallUsedRegsKindToStr(Kind));
2292     }
2293 
2294     // Add NonLazyBind attribute to function declarations when -fno-plt
2295     // is used.
2296     // FIXME: what if we just haven't processed the function definition
2297     // yet, or if it's an external definition like C99 inline?
2298     if (CodeGenOpts.NoPLT) {
2299       if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2300         if (!Fn->isDefined() && !AttrOnCallSite) {
2301           FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind);
2302         }
2303       }
2304     }
2305   }
2306 
2307   // Add "sample-profile-suffix-elision-policy" attribute for internal linkage
2308   // functions with -funique-internal-linkage-names.
2309   if (TargetDecl && CodeGenOpts.UniqueInternalLinkageNames) {
2310     if (const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
2311       if (!FD->isExternallyVisible())
2312         FuncAttrs.addAttribute("sample-profile-suffix-elision-policy",
2313                                "selected");
2314     }
2315   }
2316 
2317   // Collect non-call-site function IR attributes from declaration-specific
2318   // information.
2319   if (!AttrOnCallSite) {
2320     if (TargetDecl && TargetDecl->hasAttr<CmseNSEntryAttr>())
2321       FuncAttrs.addAttribute("cmse_nonsecure_entry");
2322 
2323     // Whether tail calls are enabled.
2324     auto shouldDisableTailCalls = [&] {
2325       // Should this be honored in getDefaultFunctionAttributes?
2326       if (CodeGenOpts.DisableTailCalls)
2327         return true;
2328 
2329       if (!TargetDecl)
2330         return false;
2331 
2332       if (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
2333           TargetDecl->hasAttr<AnyX86InterruptAttr>())
2334         return true;
2335 
2336       if (CodeGenOpts.NoEscapingBlockTailCalls) {
2337         if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl))
2338           if (!BD->doesNotEscape())
2339             return true;
2340       }
2341 
2342       return false;
2343     };
2344     if (shouldDisableTailCalls())
2345       FuncAttrs.addAttribute("disable-tail-calls", "true");
2346 
2347     // CPU/feature overrides.  addDefaultFunctionDefinitionAttributes
2348     // handles these separately to set them based on the global defaults.
2349     GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs);
2350   }
2351 
2352   // Collect attributes from arguments and return values.
2353   ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
2354 
2355   QualType RetTy = FI.getReturnType();
2356   const ABIArgInfo &RetAI = FI.getReturnInfo();
2357   const llvm::DataLayout &DL = getDataLayout();
2358 
2359   // Determine if the return type could be partially undef
2360   if (CodeGenOpts.EnableNoundefAttrs &&
2361       HasStrictReturn(*this, RetTy, TargetDecl)) {
2362     if (!RetTy->isVoidType() && RetAI.getKind() != ABIArgInfo::Indirect &&
2363         DetermineNoUndef(RetTy, getTypes(), DL, RetAI))
2364       RetAttrs.addAttribute(llvm::Attribute::NoUndef);
2365   }
2366 
2367   switch (RetAI.getKind()) {
2368   case ABIArgInfo::Extend:
2369     if (RetAI.isSignExt())
2370       RetAttrs.addAttribute(llvm::Attribute::SExt);
2371     else
2372       RetAttrs.addAttribute(llvm::Attribute::ZExt);
2373     [[fallthrough]];
2374   case ABIArgInfo::Direct:
2375     if (RetAI.getInReg())
2376       RetAttrs.addAttribute(llvm::Attribute::InReg);
2377     break;
2378   case ABIArgInfo::Ignore:
2379     break;
2380 
2381   case ABIArgInfo::InAlloca:
2382   case ABIArgInfo::Indirect: {
2383     // inalloca and sret disable readnone and readonly
2384     AddPotentialArgAccess();
2385     break;
2386   }
2387 
2388   case ABIArgInfo::CoerceAndExpand:
2389     break;
2390 
2391   case ABIArgInfo::Expand:
2392   case ABIArgInfo::IndirectAliased:
2393     llvm_unreachable("Invalid ABI kind for return argument");
2394   }
2395 
2396   if (!IsThunk) {
2397     // FIXME: fix this properly, https://reviews.llvm.org/D100388
2398     if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
2399       QualType PTy = RefTy->getPointeeType();
2400       if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2401         RetAttrs.addDereferenceableAttr(
2402             getMinimumObjectSize(PTy).getQuantity());
2403       if (getTypes().getTargetAddressSpace(PTy) == 0 &&
2404           !CodeGenOpts.NullPointerIsValid)
2405         RetAttrs.addAttribute(llvm::Attribute::NonNull);
2406       if (PTy->isObjectType()) {
2407         llvm::Align Alignment =
2408             getNaturalPointeeTypeAlignment(RetTy).getAsAlign();
2409         RetAttrs.addAlignmentAttr(Alignment);
2410       }
2411     }
2412   }
2413 
2414   bool hasUsedSRet = false;
2415   SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs());
2416 
2417   // Attach attributes to sret.
2418   if (IRFunctionArgs.hasSRetArg()) {
2419     llvm::AttrBuilder SRETAttrs(getLLVMContext());
2420     SRETAttrs.addStructRetAttr(getTypes().ConvertTypeForMem(RetTy));
2421     hasUsedSRet = true;
2422     if (RetAI.getInReg())
2423       SRETAttrs.addAttribute(llvm::Attribute::InReg);
2424     SRETAttrs.addAlignmentAttr(RetAI.getIndirectAlign().getQuantity());
2425     ArgAttrs[IRFunctionArgs.getSRetArgNo()] =
2426         llvm::AttributeSet::get(getLLVMContext(), SRETAttrs);
2427   }
2428 
2429   // Attach attributes to inalloca argument.
2430   if (IRFunctionArgs.hasInallocaArg()) {
2431     llvm::AttrBuilder Attrs(getLLVMContext());
2432     Attrs.addInAllocaAttr(FI.getArgStruct());
2433     ArgAttrs[IRFunctionArgs.getInallocaArgNo()] =
2434         llvm::AttributeSet::get(getLLVMContext(), Attrs);
2435   }
2436 
2437   // Apply `nonnull`, `dereferencable(N)` and `align N` to the `this` argument,
2438   // unless this is a thunk function.
2439   // FIXME: fix this properly, https://reviews.llvm.org/D100388
2440   if (FI.isInstanceMethod() && !IRFunctionArgs.hasInallocaArg() &&
2441       !FI.arg_begin()->type->isVoidPointerType() && !IsThunk) {
2442     auto IRArgs = IRFunctionArgs.getIRArgs(0);
2443 
2444     assert(IRArgs.second == 1 && "Expected only a single `this` pointer.");
2445 
2446     llvm::AttrBuilder Attrs(getLLVMContext());
2447 
2448     QualType ThisTy =
2449         FI.arg_begin()->type.castAs<PointerType>()->getPointeeType();
2450 
2451     if (!CodeGenOpts.NullPointerIsValid &&
2452         getTypes().getTargetAddressSpace(FI.arg_begin()->type) == 0) {
2453       Attrs.addAttribute(llvm::Attribute::NonNull);
2454       Attrs.addDereferenceableAttr(getMinimumObjectSize(ThisTy).getQuantity());
2455     } else {
2456       // FIXME dereferenceable should be correct here, regardless of
2457       // NullPointerIsValid. However, dereferenceable currently does not always
2458       // respect NullPointerIsValid and may imply nonnull and break the program.
2459       // See https://reviews.llvm.org/D66618 for discussions.
2460       Attrs.addDereferenceableOrNullAttr(
2461           getMinimumObjectSize(
2462               FI.arg_begin()->type.castAs<PointerType>()->getPointeeType())
2463               .getQuantity());
2464     }
2465 
2466     llvm::Align Alignment =
2467         getNaturalTypeAlignment(ThisTy, /*BaseInfo=*/nullptr,
2468                                 /*TBAAInfo=*/nullptr, /*forPointeeType=*/true)
2469             .getAsAlign();
2470     Attrs.addAlignmentAttr(Alignment);
2471 
2472     ArgAttrs[IRArgs.first] = llvm::AttributeSet::get(getLLVMContext(), Attrs);
2473   }
2474 
2475   unsigned ArgNo = 0;
2476   for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
2477                                           E = FI.arg_end();
2478        I != E; ++I, ++ArgNo) {
2479     QualType ParamType = I->type;
2480     const ABIArgInfo &AI = I->info;
2481     llvm::AttrBuilder Attrs(getLLVMContext());
2482 
2483     // Add attribute for padding argument, if necessary.
2484     if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
2485       if (AI.getPaddingInReg()) {
2486         ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2487             llvm::AttributeSet::get(
2488                 getLLVMContext(),
2489                 llvm::AttrBuilder(getLLVMContext()).addAttribute(llvm::Attribute::InReg));
2490       }
2491     }
2492 
2493     // Decide whether the argument we're handling could be partially undef
2494     if (CodeGenOpts.EnableNoundefAttrs &&
2495         DetermineNoUndef(ParamType, getTypes(), DL, AI)) {
2496       Attrs.addAttribute(llvm::Attribute::NoUndef);
2497     }
2498 
2499     // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
2500     // have the corresponding parameter variable.  It doesn't make
2501     // sense to do it here because parameters are so messed up.
2502     switch (AI.getKind()) {
2503     case ABIArgInfo::Extend:
2504       if (AI.isSignExt())
2505         Attrs.addAttribute(llvm::Attribute::SExt);
2506       else
2507         Attrs.addAttribute(llvm::Attribute::ZExt);
2508       [[fallthrough]];
2509     case ABIArgInfo::Direct:
2510       if (ArgNo == 0 && FI.isChainCall())
2511         Attrs.addAttribute(llvm::Attribute::Nest);
2512       else if (AI.getInReg())
2513         Attrs.addAttribute(llvm::Attribute::InReg);
2514       Attrs.addStackAlignmentAttr(llvm::MaybeAlign(AI.getDirectAlign()));
2515       break;
2516 
2517     case ABIArgInfo::Indirect: {
2518       if (AI.getInReg())
2519         Attrs.addAttribute(llvm::Attribute::InReg);
2520 
2521       if (AI.getIndirectByVal())
2522         Attrs.addByValAttr(getTypes().ConvertTypeForMem(ParamType));
2523 
2524       auto *Decl = ParamType->getAsRecordDecl();
2525       if (CodeGenOpts.PassByValueIsNoAlias && Decl &&
2526           Decl->getArgPassingRestrictions() == RecordDecl::APK_CanPassInRegs)
2527         // When calling the function, the pointer passed in will be the only
2528         // reference to the underlying object. Mark it accordingly.
2529         Attrs.addAttribute(llvm::Attribute::NoAlias);
2530 
2531       // TODO: We could add the byref attribute if not byval, but it would
2532       // require updating many testcases.
2533 
2534       CharUnits Align = AI.getIndirectAlign();
2535 
2536       // In a byval argument, it is important that the required
2537       // alignment of the type is honored, as LLVM might be creating a
2538       // *new* stack object, and needs to know what alignment to give
2539       // it. (Sometimes it can deduce a sensible alignment on its own,
2540       // but not if clang decides it must emit a packed struct, or the
2541       // user specifies increased alignment requirements.)
2542       //
2543       // This is different from indirect *not* byval, where the object
2544       // exists already, and the align attribute is purely
2545       // informative.
2546       assert(!Align.isZero());
2547 
2548       // For now, only add this when we have a byval argument.
2549       // TODO: be less lazy about updating test cases.
2550       if (AI.getIndirectByVal())
2551         Attrs.addAlignmentAttr(Align.getQuantity());
2552 
2553       // byval disables readnone and readonly.
2554       AddPotentialArgAccess();
2555       break;
2556     }
2557     case ABIArgInfo::IndirectAliased: {
2558       CharUnits Align = AI.getIndirectAlign();
2559       Attrs.addByRefAttr(getTypes().ConvertTypeForMem(ParamType));
2560       Attrs.addAlignmentAttr(Align.getQuantity());
2561       break;
2562     }
2563     case ABIArgInfo::Ignore:
2564     case ABIArgInfo::Expand:
2565     case ABIArgInfo::CoerceAndExpand:
2566       break;
2567 
2568     case ABIArgInfo::InAlloca:
2569       // inalloca disables readnone and readonly.
2570       AddPotentialArgAccess();
2571       continue;
2572     }
2573 
2574     if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
2575       QualType PTy = RefTy->getPointeeType();
2576       if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2577         Attrs.addDereferenceableAttr(
2578             getMinimumObjectSize(PTy).getQuantity());
2579       if (getTypes().getTargetAddressSpace(PTy) == 0 &&
2580           !CodeGenOpts.NullPointerIsValid)
2581         Attrs.addAttribute(llvm::Attribute::NonNull);
2582       if (PTy->isObjectType()) {
2583         llvm::Align Alignment =
2584             getNaturalPointeeTypeAlignment(ParamType).getAsAlign();
2585         Attrs.addAlignmentAttr(Alignment);
2586       }
2587     }
2588 
2589     // From OpenCL spec v3.0.10 section 6.3.5 Alignment of Types:
2590     // > For arguments to a __kernel function declared to be a pointer to a
2591     // > data type, the OpenCL compiler can assume that the pointee is always
2592     // > appropriately aligned as required by the data type.
2593     if (TargetDecl && TargetDecl->hasAttr<OpenCLKernelAttr>() &&
2594         ParamType->isPointerType()) {
2595       QualType PTy = ParamType->getPointeeType();
2596       if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2597         llvm::Align Alignment =
2598             getNaturalPointeeTypeAlignment(ParamType).getAsAlign();
2599         Attrs.addAlignmentAttr(Alignment);
2600       }
2601     }
2602 
2603     switch (FI.getExtParameterInfo(ArgNo).getABI()) {
2604     case ParameterABI::Ordinary:
2605       break;
2606 
2607     case ParameterABI::SwiftIndirectResult: {
2608       // Add 'sret' if we haven't already used it for something, but
2609       // only if the result is void.
2610       if (!hasUsedSRet && RetTy->isVoidType()) {
2611         Attrs.addStructRetAttr(getTypes().ConvertTypeForMem(ParamType));
2612         hasUsedSRet = true;
2613       }
2614 
2615       // Add 'noalias' in either case.
2616       Attrs.addAttribute(llvm::Attribute::NoAlias);
2617 
2618       // Add 'dereferenceable' and 'alignment'.
2619       auto PTy = ParamType->getPointeeType();
2620       if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2621         auto info = getContext().getTypeInfoInChars(PTy);
2622         Attrs.addDereferenceableAttr(info.Width.getQuantity());
2623         Attrs.addAlignmentAttr(info.Align.getAsAlign());
2624       }
2625       break;
2626     }
2627 
2628     case ParameterABI::SwiftErrorResult:
2629       Attrs.addAttribute(llvm::Attribute::SwiftError);
2630       break;
2631 
2632     case ParameterABI::SwiftContext:
2633       Attrs.addAttribute(llvm::Attribute::SwiftSelf);
2634       break;
2635 
2636     case ParameterABI::SwiftAsyncContext:
2637       Attrs.addAttribute(llvm::Attribute::SwiftAsync);
2638       break;
2639     }
2640 
2641     if (FI.getExtParameterInfo(ArgNo).isNoEscape())
2642       Attrs.addAttribute(llvm::Attribute::NoCapture);
2643 
2644     if (Attrs.hasAttributes()) {
2645       unsigned FirstIRArg, NumIRArgs;
2646       std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2647       for (unsigned i = 0; i < NumIRArgs; i++)
2648         ArgAttrs[FirstIRArg + i] = ArgAttrs[FirstIRArg + i].addAttributes(
2649             getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), Attrs));
2650     }
2651   }
2652   assert(ArgNo == FI.arg_size());
2653 
2654   AttrList = llvm::AttributeList::get(
2655       getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs),
2656       llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs);
2657 }
2658 
2659 /// An argument came in as a promoted argument; demote it back to its
2660 /// declared type.
2661 static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
2662                                          const VarDecl *var,
2663                                          llvm::Value *value) {
2664   llvm::Type *varType = CGF.ConvertType(var->getType());
2665 
2666   // This can happen with promotions that actually don't change the
2667   // underlying type, like the enum promotions.
2668   if (value->getType() == varType) return value;
2669 
2670   assert((varType->isIntegerTy() || varType->isFloatingPointTy())
2671          && "unexpected promotion type");
2672 
2673   if (isa<llvm::IntegerType>(varType))
2674     return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2675 
2676   return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2677 }
2678 
2679 /// Returns the attribute (either parameter attribute, or function
2680 /// attribute), which declares argument ArgNo to be non-null.
2681 static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2682                                          QualType ArgType, unsigned ArgNo) {
2683   // FIXME: __attribute__((nonnull)) can also be applied to:
2684   //   - references to pointers, where the pointee is known to be
2685   //     nonnull (apparently a Clang extension)
2686   //   - transparent unions containing pointers
2687   // In the former case, LLVM IR cannot represent the constraint. In
2688   // the latter case, we have no guarantee that the transparent union
2689   // is in fact passed as a pointer.
2690   if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2691     return nullptr;
2692   // First, check attribute on parameter itself.
2693   if (PVD) {
2694     if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2695       return ParmNNAttr;
2696   }
2697   // Check function attributes.
2698   if (!FD)
2699     return nullptr;
2700   for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
2701     if (NNAttr->isNonNull(ArgNo))
2702       return NNAttr;
2703   }
2704   return nullptr;
2705 }
2706 
2707 namespace {
2708   struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2709     Address Temp;
2710     Address Arg;
2711     CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
2712     void Emit(CodeGenFunction &CGF, Flags flags) override {
2713       llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2714       CGF.Builder.CreateStore(errorValue, Arg);
2715     }
2716   };
2717 }
2718 
2719 void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
2720                                          llvm::Function *Fn,
2721                                          const FunctionArgList &Args) {
2722   if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
2723     // Naked functions don't have prologues.
2724     return;
2725 
2726   // If this is an implicit-return-zero function, go ahead and
2727   // initialize the return value.  TODO: it might be nice to have
2728   // a more general mechanism for this that didn't require synthesized
2729   // return statements.
2730   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
2731     if (FD->hasImplicitReturnZero()) {
2732       QualType RetTy = FD->getReturnType().getUnqualifiedType();
2733       llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
2734       llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
2735       Builder.CreateStore(Zero, ReturnValue);
2736     }
2737   }
2738 
2739   // FIXME: We no longer need the types from FunctionArgList; lift up and
2740   // simplify.
2741 
2742   ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
2743   assert(Fn->arg_size() == IRFunctionArgs.totalIRArgs());
2744 
2745   // If we're using inalloca, all the memory arguments are GEPs off of the last
2746   // parameter, which is a pointer to the complete memory area.
2747   Address ArgStruct = Address::invalid();
2748   if (IRFunctionArgs.hasInallocaArg()) {
2749     ArgStruct = Address(Fn->getArg(IRFunctionArgs.getInallocaArgNo()),
2750                         FI.getArgStruct(), FI.getArgStructAlignment());
2751 
2752     assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
2753   }
2754 
2755   // Name the struct return parameter.
2756   if (IRFunctionArgs.hasSRetArg()) {
2757     auto AI = Fn->getArg(IRFunctionArgs.getSRetArgNo());
2758     AI->setName("agg.result");
2759     AI->addAttr(llvm::Attribute::NoAlias);
2760   }
2761 
2762   // Track if we received the parameter as a pointer (indirect, byval, or
2763   // inalloca).  If already have a pointer, EmitParmDecl doesn't need to copy it
2764   // into a local alloca for us.
2765   SmallVector<ParamValue, 16> ArgVals;
2766   ArgVals.reserve(Args.size());
2767 
2768   // Create a pointer value for every parameter declaration.  This usually
2769   // entails copying one or more LLVM IR arguments into an alloca.  Don't push
2770   // any cleanups or do anything that might unwind.  We do that separately, so
2771   // we can push the cleanups in the correct order for the ABI.
2772   assert(FI.arg_size() == Args.size() &&
2773          "Mismatch between function signature & arguments.");
2774   unsigned ArgNo = 0;
2775   CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
2776   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
2777        i != e; ++i, ++info_it, ++ArgNo) {
2778     const VarDecl *Arg = *i;
2779     const ABIArgInfo &ArgI = info_it->info;
2780 
2781     bool isPromoted =
2782       isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
2783     // We are converting from ABIArgInfo type to VarDecl type directly, unless
2784     // the parameter is promoted. In this case we convert to
2785     // CGFunctionInfo::ArgInfo type with subsequent argument demotion.
2786     QualType Ty = isPromoted ? info_it->type : Arg->getType();
2787     assert(hasScalarEvaluationKind(Ty) ==
2788            hasScalarEvaluationKind(Arg->getType()));
2789 
2790     unsigned FirstIRArg, NumIRArgs;
2791     std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2792 
2793     switch (ArgI.getKind()) {
2794     case ABIArgInfo::InAlloca: {
2795       assert(NumIRArgs == 0);
2796       auto FieldIndex = ArgI.getInAllocaFieldIndex();
2797       Address V =
2798           Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName());
2799       if (ArgI.getInAllocaIndirect())
2800         V = Address(Builder.CreateLoad(V), ConvertTypeForMem(Ty),
2801                     getContext().getTypeAlignInChars(Ty));
2802       ArgVals.push_back(ParamValue::forIndirect(V));
2803       break;
2804     }
2805 
2806     case ABIArgInfo::Indirect:
2807     case ABIArgInfo::IndirectAliased: {
2808       assert(NumIRArgs == 1);
2809       Address ParamAddr = Address(Fn->getArg(FirstIRArg), ConvertTypeForMem(Ty),
2810                                   ArgI.getIndirectAlign());
2811 
2812       if (!hasScalarEvaluationKind(Ty)) {
2813         // Aggregates and complex variables are accessed by reference. All we
2814         // need to do is realign the value, if requested. Also, if the address
2815         // may be aliased, copy it to ensure that the parameter variable is
2816         // mutable and has a unique adress, as C requires.
2817         Address V = ParamAddr;
2818         if (ArgI.getIndirectRealign() || ArgI.isIndirectAliased()) {
2819           Address AlignedTemp = CreateMemTemp(Ty, "coerce");
2820 
2821           // Copy from the incoming argument pointer to the temporary with the
2822           // appropriate alignment.
2823           //
2824           // FIXME: We should have a common utility for generating an aggregate
2825           // copy.
2826           CharUnits Size = getContext().getTypeSizeInChars(Ty);
2827           Builder.CreateMemCpy(
2828               AlignedTemp.getPointer(), AlignedTemp.getAlignment().getAsAlign(),
2829               ParamAddr.getPointer(), ParamAddr.getAlignment().getAsAlign(),
2830               llvm::ConstantInt::get(IntPtrTy, Size.getQuantity()));
2831           V = AlignedTemp;
2832         }
2833         ArgVals.push_back(ParamValue::forIndirect(V));
2834       } else {
2835         // Load scalar value from indirect argument.
2836         llvm::Value *V =
2837             EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc());
2838 
2839         if (isPromoted)
2840           V = emitArgumentDemotion(*this, Arg, V);
2841         ArgVals.push_back(ParamValue::forDirect(V));
2842       }
2843       break;
2844     }
2845 
2846     case ABIArgInfo::Extend:
2847     case ABIArgInfo::Direct: {
2848       auto AI = Fn->getArg(FirstIRArg);
2849       llvm::Type *LTy = ConvertType(Arg->getType());
2850 
2851       // Prepare parameter attributes. So far, only attributes for pointer
2852       // parameters are prepared. See
2853       // http://llvm.org/docs/LangRef.html#paramattrs.
2854       if (ArgI.getDirectOffset() == 0 && LTy->isPointerTy() &&
2855           ArgI.getCoerceToType()->isPointerTy()) {
2856         assert(NumIRArgs == 1);
2857 
2858         if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
2859           // Set `nonnull` attribute if any.
2860           if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
2861                              PVD->getFunctionScopeIndex()) &&
2862               !CGM.getCodeGenOpts().NullPointerIsValid)
2863             AI->addAttr(llvm::Attribute::NonNull);
2864 
2865           QualType OTy = PVD->getOriginalType();
2866           if (const auto *ArrTy =
2867               getContext().getAsConstantArrayType(OTy)) {
2868             // A C99 array parameter declaration with the static keyword also
2869             // indicates dereferenceability, and if the size is constant we can
2870             // use the dereferenceable attribute (which requires the size in
2871             // bytes).
2872             if (ArrTy->getSizeModifier() == ArrayType::Static) {
2873               QualType ETy = ArrTy->getElementType();
2874               llvm::Align Alignment =
2875                   CGM.getNaturalTypeAlignment(ETy).getAsAlign();
2876               AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(Alignment));
2877               uint64_t ArrSize = ArrTy->getSize().getZExtValue();
2878               if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
2879                   ArrSize) {
2880                 llvm::AttrBuilder Attrs(getLLVMContext());
2881                 Attrs.addDereferenceableAttr(
2882                     getContext().getTypeSizeInChars(ETy).getQuantity() *
2883                     ArrSize);
2884                 AI->addAttrs(Attrs);
2885               } else if (getContext().getTargetInfo().getNullPointerValue(
2886                              ETy.getAddressSpace()) == 0 &&
2887                          !CGM.getCodeGenOpts().NullPointerIsValid) {
2888                 AI->addAttr(llvm::Attribute::NonNull);
2889               }
2890             }
2891           } else if (const auto *ArrTy =
2892                      getContext().getAsVariableArrayType(OTy)) {
2893             // For C99 VLAs with the static keyword, we don't know the size so
2894             // we can't use the dereferenceable attribute, but in addrspace(0)
2895             // we know that it must be nonnull.
2896             if (ArrTy->getSizeModifier() == VariableArrayType::Static) {
2897               QualType ETy = ArrTy->getElementType();
2898               llvm::Align Alignment =
2899                   CGM.getNaturalTypeAlignment(ETy).getAsAlign();
2900               AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(Alignment));
2901               if (!getTypes().getTargetAddressSpace(ETy) &&
2902                   !CGM.getCodeGenOpts().NullPointerIsValid)
2903                 AI->addAttr(llvm::Attribute::NonNull);
2904             }
2905           }
2906 
2907           // Set `align` attribute if any.
2908           const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
2909           if (!AVAttr)
2910             if (const auto *TOTy = OTy->getAs<TypedefType>())
2911               AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
2912           if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) {
2913             // If alignment-assumption sanitizer is enabled, we do *not* add
2914             // alignment attribute here, but emit normal alignment assumption,
2915             // so the UBSAN check could function.
2916             llvm::ConstantInt *AlignmentCI =
2917                 cast<llvm::ConstantInt>(EmitScalarExpr(AVAttr->getAlignment()));
2918             uint64_t AlignmentInt =
2919                 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment);
2920             if (AI->getParamAlign().valueOrOne() < AlignmentInt) {
2921               AI->removeAttr(llvm::Attribute::AttrKind::Alignment);
2922               AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(
2923                   llvm::Align(AlignmentInt)));
2924             }
2925           }
2926         }
2927 
2928         // Set 'noalias' if an argument type has the `restrict` qualifier.
2929         if (Arg->getType().isRestrictQualified())
2930           AI->addAttr(llvm::Attribute::NoAlias);
2931       }
2932 
2933       // Prepare the argument value. If we have the trivial case, handle it
2934       // with no muss and fuss.
2935       if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
2936           ArgI.getCoerceToType() == ConvertType(Ty) &&
2937           ArgI.getDirectOffset() == 0) {
2938         assert(NumIRArgs == 1);
2939 
2940         // LLVM expects swifterror parameters to be used in very restricted
2941         // ways.  Copy the value into a less-restricted temporary.
2942         llvm::Value *V = AI;
2943         if (FI.getExtParameterInfo(ArgNo).getABI()
2944               == ParameterABI::SwiftErrorResult) {
2945           QualType pointeeTy = Ty->getPointeeType();
2946           assert(pointeeTy->isPointerType());
2947           Address temp =
2948             CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
2949           Address arg(V, ConvertTypeForMem(pointeeTy),
2950                       getContext().getTypeAlignInChars(pointeeTy));
2951           llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
2952           Builder.CreateStore(incomingErrorValue, temp);
2953           V = temp.getPointer();
2954 
2955           // Push a cleanup to copy the value back at the end of the function.
2956           // The convention does not guarantee that the value will be written
2957           // back if the function exits with an unwind exception.
2958           EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
2959         }
2960 
2961         // Ensure the argument is the correct type.
2962         if (V->getType() != ArgI.getCoerceToType())
2963           V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
2964 
2965         if (isPromoted)
2966           V = emitArgumentDemotion(*this, Arg, V);
2967 
2968         // Because of merging of function types from multiple decls it is
2969         // possible for the type of an argument to not match the corresponding
2970         // type in the function type. Since we are codegening the callee
2971         // in here, add a cast to the argument type.
2972         llvm::Type *LTy = ConvertType(Arg->getType());
2973         if (V->getType() != LTy)
2974           V = Builder.CreateBitCast(V, LTy);
2975 
2976         ArgVals.push_back(ParamValue::forDirect(V));
2977         break;
2978       }
2979 
2980       // VLST arguments are coerced to VLATs at the function boundary for
2981       // ABI consistency. If this is a VLST that was coerced to
2982       // a VLAT at the function boundary and the types match up, use
2983       // llvm.vector.extract to convert back to the original VLST.
2984       if (auto *VecTyTo = dyn_cast<llvm::FixedVectorType>(ConvertType(Ty))) {
2985         llvm::Value *Coerced = Fn->getArg(FirstIRArg);
2986         if (auto *VecTyFrom =
2987                 dyn_cast<llvm::ScalableVectorType>(Coerced->getType())) {
2988           // If we are casting a scalable 16 x i1 predicate vector to a fixed i8
2989           // vector, bitcast the source and use a vector extract.
2990           auto PredType =
2991               llvm::ScalableVectorType::get(Builder.getInt1Ty(), 16);
2992           if (VecTyFrom == PredType &&
2993               VecTyTo->getElementType() == Builder.getInt8Ty()) {
2994             VecTyFrom = llvm::ScalableVectorType::get(Builder.getInt8Ty(), 2);
2995             Coerced = Builder.CreateBitCast(Coerced, VecTyFrom);
2996           }
2997           if (VecTyFrom->getElementType() == VecTyTo->getElementType()) {
2998             llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty);
2999 
3000             assert(NumIRArgs == 1);
3001             Coerced->setName(Arg->getName() + ".coerce");
3002             ArgVals.push_back(ParamValue::forDirect(Builder.CreateExtractVector(
3003                 VecTyTo, Coerced, Zero, "castFixedSve")));
3004             break;
3005           }
3006         }
3007       }
3008 
3009       Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
3010                                      Arg->getName());
3011 
3012       // Pointer to store into.
3013       Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
3014 
3015       // Fast-isel and the optimizer generally like scalar values better than
3016       // FCAs, so we flatten them if this is safe to do for this argument.
3017       llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
3018       if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
3019           STy->getNumElements() > 1) {
3020         uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
3021         llvm::Type *DstTy = Ptr.getElementType();
3022         uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
3023 
3024         Address AddrToStoreInto = Address::invalid();
3025         if (SrcSize <= DstSize) {
3026           AddrToStoreInto = Builder.CreateElementBitCast(Ptr, STy);
3027         } else {
3028           AddrToStoreInto =
3029             CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
3030         }
3031 
3032         assert(STy->getNumElements() == NumIRArgs);
3033         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3034           auto AI = Fn->getArg(FirstIRArg + i);
3035           AI->setName(Arg->getName() + ".coerce" + Twine(i));
3036           Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i);
3037           Builder.CreateStore(AI, EltPtr);
3038         }
3039 
3040         if (SrcSize > DstSize) {
3041           Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
3042         }
3043 
3044       } else {
3045         // Simple case, just do a coerced store of the argument into the alloca.
3046         assert(NumIRArgs == 1);
3047         auto AI = Fn->getArg(FirstIRArg);
3048         AI->setName(Arg->getName() + ".coerce");
3049         CreateCoercedStore(AI, Ptr, /*DstIsVolatile=*/false, *this);
3050       }
3051 
3052       // Match to what EmitParmDecl is expecting for this type.
3053       if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
3054         llvm::Value *V =
3055             EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc());
3056         if (isPromoted)
3057           V = emitArgumentDemotion(*this, Arg, V);
3058         ArgVals.push_back(ParamValue::forDirect(V));
3059       } else {
3060         ArgVals.push_back(ParamValue::forIndirect(Alloca));
3061       }
3062       break;
3063     }
3064 
3065     case ABIArgInfo::CoerceAndExpand: {
3066       // Reconstruct into a temporary.
3067       Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
3068       ArgVals.push_back(ParamValue::forIndirect(alloca));
3069 
3070       auto coercionType = ArgI.getCoerceAndExpandType();
3071       alloca = Builder.CreateElementBitCast(alloca, coercionType);
3072 
3073       unsigned argIndex = FirstIRArg;
3074       for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3075         llvm::Type *eltType = coercionType->getElementType(i);
3076         if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
3077           continue;
3078 
3079         auto eltAddr = Builder.CreateStructGEP(alloca, i);
3080         auto elt = Fn->getArg(argIndex++);
3081         Builder.CreateStore(elt, eltAddr);
3082       }
3083       assert(argIndex == FirstIRArg + NumIRArgs);
3084       break;
3085     }
3086 
3087     case ABIArgInfo::Expand: {
3088       // If this structure was expanded into multiple arguments then
3089       // we need to create a temporary and reconstruct it from the
3090       // arguments.
3091       Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
3092       LValue LV = MakeAddrLValue(Alloca, Ty);
3093       ArgVals.push_back(ParamValue::forIndirect(Alloca));
3094 
3095       auto FnArgIter = Fn->arg_begin() + FirstIRArg;
3096       ExpandTypeFromArgs(Ty, LV, FnArgIter);
3097       assert(FnArgIter == Fn->arg_begin() + FirstIRArg + NumIRArgs);
3098       for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
3099         auto AI = Fn->getArg(FirstIRArg + i);
3100         AI->setName(Arg->getName() + "." + Twine(i));
3101       }
3102       break;
3103     }
3104 
3105     case ABIArgInfo::Ignore:
3106       assert(NumIRArgs == 0);
3107       // Initialize the local variable appropriately.
3108       if (!hasScalarEvaluationKind(Ty)) {
3109         ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
3110       } else {
3111         llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
3112         ArgVals.push_back(ParamValue::forDirect(U));
3113       }
3114       break;
3115     }
3116   }
3117 
3118   if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3119     for (int I = Args.size() - 1; I >= 0; --I)
3120       EmitParmDecl(*Args[I], ArgVals[I], I + 1);
3121   } else {
3122     for (unsigned I = 0, E = Args.size(); I != E; ++I)
3123       EmitParmDecl(*Args[I], ArgVals[I], I + 1);
3124   }
3125 }
3126 
3127 static void eraseUnusedBitCasts(llvm::Instruction *insn) {
3128   while (insn->use_empty()) {
3129     llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
3130     if (!bitcast) return;
3131 
3132     // This is "safe" because we would have used a ConstantExpr otherwise.
3133     insn = cast<llvm::Instruction>(bitcast->getOperand(0));
3134     bitcast->eraseFromParent();
3135   }
3136 }
3137 
3138 /// Try to emit a fused autorelease of a return result.
3139 static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
3140                                                     llvm::Value *result) {
3141   // We must be immediately followed the cast.
3142   llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
3143   if (BB->empty()) return nullptr;
3144   if (&BB->back() != result) return nullptr;
3145 
3146   llvm::Type *resultType = result->getType();
3147 
3148   // result is in a BasicBlock and is therefore an Instruction.
3149   llvm::Instruction *generator = cast<llvm::Instruction>(result);
3150 
3151   SmallVector<llvm::Instruction *, 4> InstsToKill;
3152 
3153   // Look for:
3154   //  %generator = bitcast %type1* %generator2 to %type2*
3155   while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
3156     // We would have emitted this as a constant if the operand weren't
3157     // an Instruction.
3158     generator = cast<llvm::Instruction>(bitcast->getOperand(0));
3159 
3160     // Require the generator to be immediately followed by the cast.
3161     if (generator->getNextNode() != bitcast)
3162       return nullptr;
3163 
3164     InstsToKill.push_back(bitcast);
3165   }
3166 
3167   // Look for:
3168   //   %generator = call i8* @objc_retain(i8* %originalResult)
3169   // or
3170   //   %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
3171   llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
3172   if (!call) return nullptr;
3173 
3174   bool doRetainAutorelease;
3175 
3176   if (call->getCalledOperand() == CGF.CGM.getObjCEntrypoints().objc_retain) {
3177     doRetainAutorelease = true;
3178   } else if (call->getCalledOperand() ==
3179              CGF.CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue) {
3180     doRetainAutorelease = false;
3181 
3182     // If we emitted an assembly marker for this call (and the
3183     // ARCEntrypoints field should have been set if so), go looking
3184     // for that call.  If we can't find it, we can't do this
3185     // optimization.  But it should always be the immediately previous
3186     // instruction, unless we needed bitcasts around the call.
3187     if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
3188       llvm::Instruction *prev = call->getPrevNode();
3189       assert(prev);
3190       if (isa<llvm::BitCastInst>(prev)) {
3191         prev = prev->getPrevNode();
3192         assert(prev);
3193       }
3194       assert(isa<llvm::CallInst>(prev));
3195       assert(cast<llvm::CallInst>(prev)->getCalledOperand() ==
3196              CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
3197       InstsToKill.push_back(prev);
3198     }
3199   } else {
3200     return nullptr;
3201   }
3202 
3203   result = call->getArgOperand(0);
3204   InstsToKill.push_back(call);
3205 
3206   // Keep killing bitcasts, for sanity.  Note that we no longer care
3207   // about precise ordering as long as there's exactly one use.
3208   while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
3209     if (!bitcast->hasOneUse()) break;
3210     InstsToKill.push_back(bitcast);
3211     result = bitcast->getOperand(0);
3212   }
3213 
3214   // Delete all the unnecessary instructions, from latest to earliest.
3215   for (auto *I : InstsToKill)
3216     I->eraseFromParent();
3217 
3218   // Do the fused retain/autorelease if we were asked to.
3219   if (doRetainAutorelease)
3220     result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
3221 
3222   // Cast back to the result type.
3223   return CGF.Builder.CreateBitCast(result, resultType);
3224 }
3225 
3226 /// If this is a +1 of the value of an immutable 'self', remove it.
3227 static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
3228                                           llvm::Value *result) {
3229   // This is only applicable to a method with an immutable 'self'.
3230   const ObjCMethodDecl *method =
3231     dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
3232   if (!method) return nullptr;
3233   const VarDecl *self = method->getSelfDecl();
3234   if (!self->getType().isConstQualified()) return nullptr;
3235 
3236   // Look for a retain call.
3237   llvm::CallInst *retainCall =
3238     dyn_cast<llvm::CallInst>(result->stripPointerCasts());
3239   if (!retainCall || retainCall->getCalledOperand() !=
3240                          CGF.CGM.getObjCEntrypoints().objc_retain)
3241     return nullptr;
3242 
3243   // Look for an ordinary load of 'self'.
3244   llvm::Value *retainedValue = retainCall->getArgOperand(0);
3245   llvm::LoadInst *load =
3246     dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
3247   if (!load || load->isAtomic() || load->isVolatile() ||
3248       load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
3249     return nullptr;
3250 
3251   // Okay!  Burn it all down.  This relies for correctness on the
3252   // assumption that the retain is emitted as part of the return and
3253   // that thereafter everything is used "linearly".
3254   llvm::Type *resultType = result->getType();
3255   eraseUnusedBitCasts(cast<llvm::Instruction>(result));
3256   assert(retainCall->use_empty());
3257   retainCall->eraseFromParent();
3258   eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
3259 
3260   return CGF.Builder.CreateBitCast(load, resultType);
3261 }
3262 
3263 /// Emit an ARC autorelease of the result of a function.
3264 ///
3265 /// \return the value to actually return from the function
3266 static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
3267                                             llvm::Value *result) {
3268   // If we're returning 'self', kill the initial retain.  This is a
3269   // heuristic attempt to "encourage correctness" in the really unfortunate
3270   // case where we have a return of self during a dealloc and we desperately
3271   // need to avoid the possible autorelease.
3272   if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
3273     return self;
3274 
3275   // At -O0, try to emit a fused retain/autorelease.
3276   if (CGF.shouldUseFusedARCCalls())
3277     if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
3278       return fused;
3279 
3280   return CGF.EmitARCAutoreleaseReturnValue(result);
3281 }
3282 
3283 /// Heuristically search for a dominating store to the return-value slot.
3284 static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
3285   // Check if a User is a store which pointerOperand is the ReturnValue.
3286   // We are looking for stores to the ReturnValue, not for stores of the
3287   // ReturnValue to some other location.
3288   auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
3289     auto *SI = dyn_cast<llvm::StoreInst>(U);
3290     if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer() ||
3291         SI->getValueOperand()->getType() != CGF.ReturnValue.getElementType())
3292       return nullptr;
3293     // These aren't actually possible for non-coerced returns, and we
3294     // only care about non-coerced returns on this code path.
3295     assert(!SI->isAtomic() && !SI->isVolatile());
3296     return SI;
3297   };
3298   // If there are multiple uses of the return-value slot, just check
3299   // for something immediately preceding the IP.  Sometimes this can
3300   // happen with how we generate implicit-returns; it can also happen
3301   // with noreturn cleanups.
3302   if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
3303     llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
3304     if (IP->empty()) return nullptr;
3305 
3306     // Look at directly preceding instruction, skipping bitcasts and lifetime
3307     // markers.
3308     for (llvm::Instruction &I : make_range(IP->rbegin(), IP->rend())) {
3309       if (isa<llvm::BitCastInst>(&I))
3310         continue;
3311       if (auto *II = dyn_cast<llvm::IntrinsicInst>(&I))
3312         if (II->getIntrinsicID() == llvm::Intrinsic::lifetime_end)
3313           continue;
3314 
3315       return GetStoreIfValid(&I);
3316     }
3317     return nullptr;
3318   }
3319 
3320   llvm::StoreInst *store =
3321       GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
3322   if (!store) return nullptr;
3323 
3324   // Now do a first-and-dirty dominance check: just walk up the
3325   // single-predecessors chain from the current insertion point.
3326   llvm::BasicBlock *StoreBB = store->getParent();
3327   llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
3328   while (IP != StoreBB) {
3329     if (!(IP = IP->getSinglePredecessor()))
3330       return nullptr;
3331   }
3332 
3333   // Okay, the store's basic block dominates the insertion point; we
3334   // can do our thing.
3335   return store;
3336 }
3337 
3338 // Helper functions for EmitCMSEClearRecord
3339 
3340 // Set the bits corresponding to a field having width `BitWidth` and located at
3341 // offset `BitOffset` (from the least significant bit) within a storage unit of
3342 // `Bits.size()` bytes. Each element of `Bits` corresponds to one target byte.
3343 // Use little-endian layout, i.e.`Bits[0]` is the LSB.
3344 static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int BitOffset,
3345                         int BitWidth, int CharWidth) {
3346   assert(CharWidth <= 64);
3347   assert(static_cast<unsigned>(BitWidth) <= Bits.size() * CharWidth);
3348 
3349   int Pos = 0;
3350   if (BitOffset >= CharWidth) {
3351     Pos += BitOffset / CharWidth;
3352     BitOffset = BitOffset % CharWidth;
3353   }
3354 
3355   const uint64_t Used = (uint64_t(1) << CharWidth) - 1;
3356   if (BitOffset + BitWidth >= CharWidth) {
3357     Bits[Pos++] |= (Used << BitOffset) & Used;
3358     BitWidth -= CharWidth - BitOffset;
3359     BitOffset = 0;
3360   }
3361 
3362   while (BitWidth >= CharWidth) {
3363     Bits[Pos++] = Used;
3364     BitWidth -= CharWidth;
3365   }
3366 
3367   if (BitWidth > 0)
3368     Bits[Pos++] |= (Used >> (CharWidth - BitWidth)) << BitOffset;
3369 }
3370 
3371 // Set the bits corresponding to a field having width `BitWidth` and located at
3372 // offset `BitOffset` (from the least significant bit) within a storage unit of
3373 // `StorageSize` bytes, located at `StorageOffset` in `Bits`. Each element of
3374 // `Bits` corresponds to one target byte. Use target endian layout.
3375 static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int StorageOffset,
3376                         int StorageSize, int BitOffset, int BitWidth,
3377                         int CharWidth, bool BigEndian) {
3378 
3379   SmallVector<uint64_t, 8> TmpBits(StorageSize);
3380   setBitRange(TmpBits, BitOffset, BitWidth, CharWidth);
3381 
3382   if (BigEndian)
3383     std::reverse(TmpBits.begin(), TmpBits.end());
3384 
3385   for (uint64_t V : TmpBits)
3386     Bits[StorageOffset++] |= V;
3387 }
3388 
3389 static void setUsedBits(CodeGenModule &, QualType, int,
3390                         SmallVectorImpl<uint64_t> &);
3391 
3392 // Set the bits in `Bits`, which correspond to the value representations of
3393 // the actual members of the record type `RTy`. Note that this function does
3394 // not handle base classes, virtual tables, etc, since they cannot happen in
3395 // CMSE function arguments or return. The bit mask corresponds to the target
3396 // memory layout, i.e. it's endian dependent.
3397 static void setUsedBits(CodeGenModule &CGM, const RecordType *RTy, int Offset,
3398                         SmallVectorImpl<uint64_t> &Bits) {
3399   ASTContext &Context = CGM.getContext();
3400   int CharWidth = Context.getCharWidth();
3401   const RecordDecl *RD = RTy->getDecl()->getDefinition();
3402   const ASTRecordLayout &ASTLayout = Context.getASTRecordLayout(RD);
3403   const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(RD);
3404 
3405   int Idx = 0;
3406   for (auto I = RD->field_begin(), E = RD->field_end(); I != E; ++I, ++Idx) {
3407     const FieldDecl *F = *I;
3408 
3409     if (F->isUnnamedBitfield() || F->isZeroLengthBitField(Context) ||
3410         F->getType()->isIncompleteArrayType())
3411       continue;
3412 
3413     if (F->isBitField()) {
3414       const CGBitFieldInfo &BFI = Layout.getBitFieldInfo(F);
3415       setBitRange(Bits, Offset + BFI.StorageOffset.getQuantity(),
3416                   BFI.StorageSize / CharWidth, BFI.Offset,
3417                   BFI.Size, CharWidth,
3418                   CGM.getDataLayout().isBigEndian());
3419       continue;
3420     }
3421 
3422     setUsedBits(CGM, F->getType(),
3423                 Offset + ASTLayout.getFieldOffset(Idx) / CharWidth, Bits);
3424   }
3425 }
3426 
3427 // Set the bits in `Bits`, which correspond to the value representations of
3428 // the elements of an array type `ATy`.
3429 static void setUsedBits(CodeGenModule &CGM, const ConstantArrayType *ATy,
3430                         int Offset, SmallVectorImpl<uint64_t> &Bits) {
3431   const ASTContext &Context = CGM.getContext();
3432 
3433   QualType ETy = Context.getBaseElementType(ATy);
3434   int Size = Context.getTypeSizeInChars(ETy).getQuantity();
3435   SmallVector<uint64_t, 4> TmpBits(Size);
3436   setUsedBits(CGM, ETy, 0, TmpBits);
3437 
3438   for (int I = 0, N = Context.getConstantArrayElementCount(ATy); I < N; ++I) {
3439     auto Src = TmpBits.begin();
3440     auto Dst = Bits.begin() + Offset + I * Size;
3441     for (int J = 0; J < Size; ++J)
3442       *Dst++ |= *Src++;
3443   }
3444 }
3445 
3446 // Set the bits in `Bits`, which correspond to the value representations of
3447 // the type `QTy`.
3448 static void setUsedBits(CodeGenModule &CGM, QualType QTy, int Offset,
3449                         SmallVectorImpl<uint64_t> &Bits) {
3450   if (const auto *RTy = QTy->getAs<RecordType>())
3451     return setUsedBits(CGM, RTy, Offset, Bits);
3452 
3453   ASTContext &Context = CGM.getContext();
3454   if (const auto *ATy = Context.getAsConstantArrayType(QTy))
3455     return setUsedBits(CGM, ATy, Offset, Bits);
3456 
3457   int Size = Context.getTypeSizeInChars(QTy).getQuantity();
3458   if (Size <= 0)
3459     return;
3460 
3461   std::fill_n(Bits.begin() + Offset, Size,
3462               (uint64_t(1) << Context.getCharWidth()) - 1);
3463 }
3464 
3465 static uint64_t buildMultiCharMask(const SmallVectorImpl<uint64_t> &Bits,
3466                                    int Pos, int Size, int CharWidth,
3467                                    bool BigEndian) {
3468   assert(Size > 0);
3469   uint64_t Mask = 0;
3470   if (BigEndian) {
3471     for (auto P = Bits.begin() + Pos, E = Bits.begin() + Pos + Size; P != E;
3472          ++P)
3473       Mask = (Mask << CharWidth) | *P;
3474   } else {
3475     auto P = Bits.begin() + Pos + Size, End = Bits.begin() + Pos;
3476     do
3477       Mask = (Mask << CharWidth) | *--P;
3478     while (P != End);
3479   }
3480   return Mask;
3481 }
3482 
3483 // Emit code to clear the bits in a record, which aren't a part of any user
3484 // declared member, when the record is a function return.
3485 llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3486                                                   llvm::IntegerType *ITy,
3487                                                   QualType QTy) {
3488   assert(Src->getType() == ITy);
3489   assert(ITy->getScalarSizeInBits() <= 64);
3490 
3491   const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3492   int Size = DataLayout.getTypeStoreSize(ITy);
3493   SmallVector<uint64_t, 4> Bits(Size);
3494   setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
3495 
3496   int CharWidth = CGM.getContext().getCharWidth();
3497   uint64_t Mask =
3498       buildMultiCharMask(Bits, 0, Size, CharWidth, DataLayout.isBigEndian());
3499 
3500   return Builder.CreateAnd(Src, Mask, "cmse.clear");
3501 }
3502 
3503 // Emit code to clear the bits in a record, which aren't a part of any user
3504 // declared member, when the record is a function argument.
3505 llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3506                                                   llvm::ArrayType *ATy,
3507                                                   QualType QTy) {
3508   const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3509   int Size = DataLayout.getTypeStoreSize(ATy);
3510   SmallVector<uint64_t, 16> Bits(Size);
3511   setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
3512 
3513   // Clear each element of the LLVM array.
3514   int CharWidth = CGM.getContext().getCharWidth();
3515   int CharsPerElt =
3516       ATy->getArrayElementType()->getScalarSizeInBits() / CharWidth;
3517   int MaskIndex = 0;
3518   llvm::Value *R = llvm::PoisonValue::get(ATy);
3519   for (int I = 0, N = ATy->getArrayNumElements(); I != N; ++I) {
3520     uint64_t Mask = buildMultiCharMask(Bits, MaskIndex, CharsPerElt, CharWidth,
3521                                        DataLayout.isBigEndian());
3522     MaskIndex += CharsPerElt;
3523     llvm::Value *T0 = Builder.CreateExtractValue(Src, I);
3524     llvm::Value *T1 = Builder.CreateAnd(T0, Mask, "cmse.clear");
3525     R = Builder.CreateInsertValue(R, T1, I);
3526   }
3527 
3528   return R;
3529 }
3530 
3531 void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
3532                                          bool EmitRetDbgLoc,
3533                                          SourceLocation EndLoc) {
3534   if (FI.isNoReturn()) {
3535     // Noreturn functions don't return.
3536     EmitUnreachable(EndLoc);
3537     return;
3538   }
3539 
3540   if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
3541     // Naked functions don't have epilogues.
3542     Builder.CreateUnreachable();
3543     return;
3544   }
3545 
3546   // Functions with no result always return void.
3547   if (!ReturnValue.isValid()) {
3548     Builder.CreateRetVoid();
3549     return;
3550   }
3551 
3552   llvm::DebugLoc RetDbgLoc;
3553   llvm::Value *RV = nullptr;
3554   QualType RetTy = FI.getReturnType();
3555   const ABIArgInfo &RetAI = FI.getReturnInfo();
3556 
3557   switch (RetAI.getKind()) {
3558   case ABIArgInfo::InAlloca:
3559     // Aggregates get evaluated directly into the destination.  Sometimes we
3560     // need to return the sret value in a register, though.
3561     assert(hasAggregateEvaluationKind(RetTy));
3562     if (RetAI.getInAllocaSRet()) {
3563       llvm::Function::arg_iterator EI = CurFn->arg_end();
3564       --EI;
3565       llvm::Value *ArgStruct = &*EI;
3566       llvm::Value *SRet = Builder.CreateStructGEP(
3567           FI.getArgStruct(), ArgStruct, RetAI.getInAllocaFieldIndex());
3568       llvm::Type *Ty =
3569           cast<llvm::GetElementPtrInst>(SRet)->getResultElementType();
3570       RV = Builder.CreateAlignedLoad(Ty, SRet, getPointerAlign(), "sret");
3571     }
3572     break;
3573 
3574   case ABIArgInfo::Indirect: {
3575     auto AI = CurFn->arg_begin();
3576     if (RetAI.isSRetAfterThis())
3577       ++AI;
3578     switch (getEvaluationKind(RetTy)) {
3579     case TEK_Complex: {
3580       ComplexPairTy RT =
3581         EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
3582       EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
3583                          /*isInit*/ true);
3584       break;
3585     }
3586     case TEK_Aggregate:
3587       // Do nothing; aggregates get evaluated directly into the destination.
3588       break;
3589     case TEK_Scalar: {
3590       LValueBaseInfo BaseInfo;
3591       TBAAAccessInfo TBAAInfo;
3592       CharUnits Alignment =
3593           CGM.getNaturalTypeAlignment(RetTy, &BaseInfo, &TBAAInfo);
3594       Address ArgAddr(&*AI, ConvertType(RetTy), Alignment);
3595       LValue ArgVal =
3596           LValue::MakeAddr(ArgAddr, RetTy, getContext(), BaseInfo, TBAAInfo);
3597       EmitStoreOfScalar(
3598           Builder.CreateLoad(ReturnValue), ArgVal, /*isInit*/ true);
3599       break;
3600     }
3601     }
3602     break;
3603   }
3604 
3605   case ABIArgInfo::Extend:
3606   case ABIArgInfo::Direct:
3607     if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
3608         RetAI.getDirectOffset() == 0) {
3609       // The internal return value temp always will have pointer-to-return-type
3610       // type, just do a load.
3611 
3612       // If there is a dominating store to ReturnValue, we can elide
3613       // the load, zap the store, and usually zap the alloca.
3614       if (llvm::StoreInst *SI =
3615               findDominatingStoreToReturnValue(*this)) {
3616         // Reuse the debug location from the store unless there is
3617         // cleanup code to be emitted between the store and return
3618         // instruction.
3619         if (EmitRetDbgLoc && !AutoreleaseResult)
3620           RetDbgLoc = SI->getDebugLoc();
3621         // Get the stored value and nuke the now-dead store.
3622         RV = SI->getValueOperand();
3623         SI->eraseFromParent();
3624 
3625       // Otherwise, we have to do a simple load.
3626       } else {
3627         RV = Builder.CreateLoad(ReturnValue);
3628       }
3629     } else {
3630       // If the value is offset in memory, apply the offset now.
3631       Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
3632 
3633       RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
3634     }
3635 
3636     // In ARC, end functions that return a retainable type with a call
3637     // to objc_autoreleaseReturnValue.
3638     if (AutoreleaseResult) {
3639 #ifndef NDEBUG
3640       // Type::isObjCRetainabletype has to be called on a QualType that hasn't
3641       // been stripped of the typedefs, so we cannot use RetTy here. Get the
3642       // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
3643       // CurCodeDecl or BlockInfo.
3644       QualType RT;
3645 
3646       if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
3647         RT = FD->getReturnType();
3648       else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
3649         RT = MD->getReturnType();
3650       else if (isa<BlockDecl>(CurCodeDecl))
3651         RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
3652       else
3653         llvm_unreachable("Unexpected function/method type");
3654 
3655       assert(getLangOpts().ObjCAutoRefCount &&
3656              !FI.isReturnsRetained() &&
3657              RT->isObjCRetainableType());
3658 #endif
3659       RV = emitAutoreleaseOfResult(*this, RV);
3660     }
3661 
3662     break;
3663 
3664   case ABIArgInfo::Ignore:
3665     break;
3666 
3667   case ABIArgInfo::CoerceAndExpand: {
3668     auto coercionType = RetAI.getCoerceAndExpandType();
3669 
3670     // Load all of the coerced elements out into results.
3671     llvm::SmallVector<llvm::Value*, 4> results;
3672     Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
3673     for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3674       auto coercedEltType = coercionType->getElementType(i);
3675       if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
3676         continue;
3677 
3678       auto eltAddr = Builder.CreateStructGEP(addr, i);
3679       auto elt = Builder.CreateLoad(eltAddr);
3680       results.push_back(elt);
3681     }
3682 
3683     // If we have one result, it's the single direct result type.
3684     if (results.size() == 1) {
3685       RV = results[0];
3686 
3687     // Otherwise, we need to make a first-class aggregate.
3688     } else {
3689       // Construct a return type that lacks padding elements.
3690       llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
3691 
3692       RV = llvm::PoisonValue::get(returnType);
3693       for (unsigned i = 0, e = results.size(); i != e; ++i) {
3694         RV = Builder.CreateInsertValue(RV, results[i], i);
3695       }
3696     }
3697     break;
3698   }
3699   case ABIArgInfo::Expand:
3700   case ABIArgInfo::IndirectAliased:
3701     llvm_unreachable("Invalid ABI kind for return argument");
3702   }
3703 
3704   llvm::Instruction *Ret;
3705   if (RV) {
3706     if (CurFuncDecl && CurFuncDecl->hasAttr<CmseNSEntryAttr>()) {
3707       // For certain return types, clear padding bits, as they may reveal
3708       // sensitive information.
3709       // Small struct/union types are passed as integers.
3710       auto *ITy = dyn_cast<llvm::IntegerType>(RV->getType());
3711       if (ITy != nullptr && isa<RecordType>(RetTy.getCanonicalType()))
3712         RV = EmitCMSEClearRecord(RV, ITy, RetTy);
3713     }
3714     EmitReturnValueCheck(RV);
3715     Ret = Builder.CreateRet(RV);
3716   } else {
3717     Ret = Builder.CreateRetVoid();
3718   }
3719 
3720   if (RetDbgLoc)
3721     Ret->setDebugLoc(std::move(RetDbgLoc));
3722 }
3723 
3724 void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) {
3725   // A current decl may not be available when emitting vtable thunks.
3726   if (!CurCodeDecl)
3727     return;
3728 
3729   // If the return block isn't reachable, neither is this check, so don't emit
3730   // it.
3731   if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty())
3732     return;
3733 
3734   ReturnsNonNullAttr *RetNNAttr = nullptr;
3735   if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
3736     RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
3737 
3738   if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
3739     return;
3740 
3741   // Prefer the returns_nonnull attribute if it's present.
3742   SourceLocation AttrLoc;
3743   SanitizerMask CheckKind;
3744   SanitizerHandler Handler;
3745   if (RetNNAttr) {
3746     assert(!requiresReturnValueNullabilityCheck() &&
3747            "Cannot check nullability and the nonnull attribute");
3748     AttrLoc = RetNNAttr->getLocation();
3749     CheckKind = SanitizerKind::ReturnsNonnullAttribute;
3750     Handler = SanitizerHandler::NonnullReturn;
3751   } else {
3752     if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl))
3753       if (auto *TSI = DD->getTypeSourceInfo())
3754         if (auto FTL = TSI->getTypeLoc().getAsAdjusted<FunctionTypeLoc>())
3755           AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
3756     CheckKind = SanitizerKind::NullabilityReturn;
3757     Handler = SanitizerHandler::NullabilityReturn;
3758   }
3759 
3760   SanitizerScope SanScope(this);
3761 
3762   // Make sure the "return" source location is valid. If we're checking a
3763   // nullability annotation, make sure the preconditions for the check are met.
3764   llvm::BasicBlock *Check = createBasicBlock("nullcheck");
3765   llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck");
3766   llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load");
3767   llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr);
3768   if (requiresReturnValueNullabilityCheck())
3769     CanNullCheck =
3770         Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition);
3771   Builder.CreateCondBr(CanNullCheck, Check, NoCheck);
3772   EmitBlock(Check);
3773 
3774   // Now do the null check.
3775   llvm::Value *Cond = Builder.CreateIsNotNull(RV);
3776   llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)};
3777   llvm::Value *DynamicData[] = {SLocPtr};
3778   EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData);
3779 
3780   EmitBlock(NoCheck);
3781 
3782 #ifndef NDEBUG
3783   // The return location should not be used after the check has been emitted.
3784   ReturnLocation = Address::invalid();
3785 #endif
3786 }
3787 
3788 static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
3789   const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
3790   return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
3791 }
3792 
3793 static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
3794                                           QualType Ty) {
3795   // FIXME: Generate IR in one pass, rather than going back and fixing up these
3796   // placeholders.
3797   llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
3798   llvm::Type *IRPtrTy = IRTy->getPointerTo();
3799   llvm::Value *Placeholder = llvm::PoisonValue::get(IRPtrTy->getPointerTo());
3800 
3801   // FIXME: When we generate this IR in one pass, we shouldn't need
3802   // this win32-specific alignment hack.
3803   CharUnits Align = CharUnits::fromQuantity(4);
3804   Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
3805 
3806   return AggValueSlot::forAddr(Address(Placeholder, IRTy, Align),
3807                                Ty.getQualifiers(),
3808                                AggValueSlot::IsNotDestructed,
3809                                AggValueSlot::DoesNotNeedGCBarriers,
3810                                AggValueSlot::IsNotAliased,
3811                                AggValueSlot::DoesNotOverlap);
3812 }
3813 
3814 void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
3815                                           const VarDecl *param,
3816                                           SourceLocation loc) {
3817   // StartFunction converted the ABI-lowered parameter(s) into a
3818   // local alloca.  We need to turn that into an r-value suitable
3819   // for EmitCall.
3820   Address local = GetAddrOfLocalVar(param);
3821 
3822   QualType type = param->getType();
3823 
3824   if (isInAllocaArgument(CGM.getCXXABI(), type)) {
3825     CGM.ErrorUnsupported(param, "forwarded non-trivially copyable parameter");
3826   }
3827 
3828   // GetAddrOfLocalVar returns a pointer-to-pointer for references,
3829   // but the argument needs to be the original pointer.
3830   if (type->isReferenceType()) {
3831     args.add(RValue::get(Builder.CreateLoad(local)), type);
3832 
3833   // In ARC, move out of consumed arguments so that the release cleanup
3834   // entered by StartFunction doesn't cause an over-release.  This isn't
3835   // optimal -O0 code generation, but it should get cleaned up when
3836   // optimization is enabled.  This also assumes that delegate calls are
3837   // performed exactly once for a set of arguments, but that should be safe.
3838   } else if (getLangOpts().ObjCAutoRefCount &&
3839              param->hasAttr<NSConsumedAttr>() &&
3840              type->isObjCRetainableType()) {
3841     llvm::Value *ptr = Builder.CreateLoad(local);
3842     auto null =
3843       llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
3844     Builder.CreateStore(null, local);
3845     args.add(RValue::get(ptr), type);
3846 
3847   // For the most part, we just need to load the alloca, except that
3848   // aggregate r-values are actually pointers to temporaries.
3849   } else {
3850     args.add(convertTempToRValue(local, type, loc), type);
3851   }
3852 
3853   // Deactivate the cleanup for the callee-destructed param that was pushed.
3854   if (type->isRecordType() && !CurFuncIsThunk &&
3855       type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee() &&
3856       param->needsDestruction(getContext())) {
3857     EHScopeStack::stable_iterator cleanup =
3858         CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param));
3859     assert(cleanup.isValid() &&
3860            "cleanup for callee-destructed param not recorded");
3861     // This unreachable is a temporary marker which will be removed later.
3862     llvm::Instruction *isActive = Builder.CreateUnreachable();
3863     args.addArgCleanupDeactivation(cleanup, isActive);
3864   }
3865 }
3866 
3867 static bool isProvablyNull(llvm::Value *addr) {
3868   return isa<llvm::ConstantPointerNull>(addr);
3869 }
3870 
3871 /// Emit the actual writing-back of a writeback.
3872 static void emitWriteback(CodeGenFunction &CGF,
3873                           const CallArgList::Writeback &writeback) {
3874   const LValue &srcLV = writeback.Source;
3875   Address srcAddr = srcLV.getAddress(CGF);
3876   assert(!isProvablyNull(srcAddr.getPointer()) &&
3877          "shouldn't have writeback for provably null argument");
3878 
3879   llvm::BasicBlock *contBB = nullptr;
3880 
3881   // If the argument wasn't provably non-null, we need to null check
3882   // before doing the store.
3883   bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
3884                                               CGF.CGM.getDataLayout());
3885   if (!provablyNonNull) {
3886     llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
3887     contBB = CGF.createBasicBlock("icr.done");
3888 
3889     llvm::Value *isNull =
3890       CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
3891     CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
3892     CGF.EmitBlock(writebackBB);
3893   }
3894 
3895   // Load the value to writeback.
3896   llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
3897 
3898   // Cast it back, in case we're writing an id to a Foo* or something.
3899   value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
3900                                     "icr.writeback-cast");
3901 
3902   // Perform the writeback.
3903 
3904   // If we have a "to use" value, it's something we need to emit a use
3905   // of.  This has to be carefully threaded in: if it's done after the
3906   // release it's potentially undefined behavior (and the optimizer
3907   // will ignore it), and if it happens before the retain then the
3908   // optimizer could move the release there.
3909   if (writeback.ToUse) {
3910     assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
3911 
3912     // Retain the new value.  No need to block-copy here:  the block's
3913     // being passed up the stack.
3914     value = CGF.EmitARCRetainNonBlock(value);
3915 
3916     // Emit the intrinsic use here.
3917     CGF.EmitARCIntrinsicUse(writeback.ToUse);
3918 
3919     // Load the old value (primitively).
3920     llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
3921 
3922     // Put the new value in place (primitively).
3923     CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
3924 
3925     // Release the old value.
3926     CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
3927 
3928   // Otherwise, we can just do a normal lvalue store.
3929   } else {
3930     CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
3931   }
3932 
3933   // Jump to the continuation block.
3934   if (!provablyNonNull)
3935     CGF.EmitBlock(contBB);
3936 }
3937 
3938 static void emitWritebacks(CodeGenFunction &CGF,
3939                            const CallArgList &args) {
3940   for (const auto &I : args.writebacks())
3941     emitWriteback(CGF, I);
3942 }
3943 
3944 static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
3945                                             const CallArgList &CallArgs) {
3946   ArrayRef<CallArgList::CallArgCleanup> Cleanups =
3947     CallArgs.getCleanupsToDeactivate();
3948   // Iterate in reverse to increase the likelihood of popping the cleanup.
3949   for (const auto &I : llvm::reverse(Cleanups)) {
3950     CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
3951     I.IsActiveIP->eraseFromParent();
3952   }
3953 }
3954 
3955 static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
3956   if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
3957     if (uop->getOpcode() == UO_AddrOf)
3958       return uop->getSubExpr();
3959   return nullptr;
3960 }
3961 
3962 /// Emit an argument that's being passed call-by-writeback.  That is,
3963 /// we are passing the address of an __autoreleased temporary; it
3964 /// might be copy-initialized with the current value of the given
3965 /// address, but it will definitely be copied out of after the call.
3966 static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
3967                              const ObjCIndirectCopyRestoreExpr *CRE) {
3968   LValue srcLV;
3969 
3970   // Make an optimistic effort to emit the address as an l-value.
3971   // This can fail if the argument expression is more complicated.
3972   if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
3973     srcLV = CGF.EmitLValue(lvExpr);
3974 
3975   // Otherwise, just emit it as a scalar.
3976   } else {
3977     Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
3978 
3979     QualType srcAddrType =
3980       CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
3981     srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
3982   }
3983   Address srcAddr = srcLV.getAddress(CGF);
3984 
3985   // The dest and src types don't necessarily match in LLVM terms
3986   // because of the crazy ObjC compatibility rules.
3987 
3988   llvm::PointerType *destType =
3989       cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
3990   llvm::Type *destElemType =
3991       CGF.ConvertTypeForMem(CRE->getType()->getPointeeType());
3992 
3993   // If the address is a constant null, just pass the appropriate null.
3994   if (isProvablyNull(srcAddr.getPointer())) {
3995     args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
3996              CRE->getType());
3997     return;
3998   }
3999 
4000   // Create the temporary.
4001   Address temp =
4002       CGF.CreateTempAlloca(destElemType, CGF.getPointerAlign(), "icr.temp");
4003   // Loading an l-value can introduce a cleanup if the l-value is __weak,
4004   // and that cleanup will be conditional if we can't prove that the l-value
4005   // isn't null, so we need to register a dominating point so that the cleanups
4006   // system will make valid IR.
4007   CodeGenFunction::ConditionalEvaluation condEval(CGF);
4008 
4009   // Zero-initialize it if we're not doing a copy-initialization.
4010   bool shouldCopy = CRE->shouldCopy();
4011   if (!shouldCopy) {
4012     llvm::Value *null =
4013         llvm::ConstantPointerNull::get(cast<llvm::PointerType>(destElemType));
4014     CGF.Builder.CreateStore(null, temp);
4015   }
4016 
4017   llvm::BasicBlock *contBB = nullptr;
4018   llvm::BasicBlock *originBB = nullptr;
4019 
4020   // If the address is *not* known to be non-null, we need to switch.
4021   llvm::Value *finalArgument;
4022 
4023   bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
4024                                               CGF.CGM.getDataLayout());
4025   if (provablyNonNull) {
4026     finalArgument = temp.getPointer();
4027   } else {
4028     llvm::Value *isNull =
4029       CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
4030 
4031     finalArgument = CGF.Builder.CreateSelect(isNull,
4032                                    llvm::ConstantPointerNull::get(destType),
4033                                              temp.getPointer(), "icr.argument");
4034 
4035     // If we need to copy, then the load has to be conditional, which
4036     // means we need control flow.
4037     if (shouldCopy) {
4038       originBB = CGF.Builder.GetInsertBlock();
4039       contBB = CGF.createBasicBlock("icr.cont");
4040       llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
4041       CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
4042       CGF.EmitBlock(copyBB);
4043       condEval.begin(CGF);
4044     }
4045   }
4046 
4047   llvm::Value *valueToUse = nullptr;
4048 
4049   // Perform a copy if necessary.
4050   if (shouldCopy) {
4051     RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
4052     assert(srcRV.isScalar());
4053 
4054     llvm::Value *src = srcRV.getScalarVal();
4055     src = CGF.Builder.CreateBitCast(src, destElemType, "icr.cast");
4056 
4057     // Use an ordinary store, not a store-to-lvalue.
4058     CGF.Builder.CreateStore(src, temp);
4059 
4060     // If optimization is enabled, and the value was held in a
4061     // __strong variable, we need to tell the optimizer that this
4062     // value has to stay alive until we're doing the store back.
4063     // This is because the temporary is effectively unretained,
4064     // and so otherwise we can violate the high-level semantics.
4065     if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
4066         srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
4067       valueToUse = src;
4068     }
4069   }
4070 
4071   // Finish the control flow if we needed it.
4072   if (shouldCopy && !provablyNonNull) {
4073     llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
4074     CGF.EmitBlock(contBB);
4075 
4076     // Make a phi for the value to intrinsically use.
4077     if (valueToUse) {
4078       llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
4079                                                       "icr.to-use");
4080       phiToUse->addIncoming(valueToUse, copyBB);
4081       phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
4082                             originBB);
4083       valueToUse = phiToUse;
4084     }
4085 
4086     condEval.end(CGF);
4087   }
4088 
4089   args.addWriteback(srcLV, temp, valueToUse);
4090   args.add(RValue::get(finalArgument), CRE->getType());
4091 }
4092 
4093 void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
4094   assert(!StackBase);
4095 
4096   // Save the stack.
4097   llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
4098   StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
4099 }
4100 
4101 void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
4102   if (StackBase) {
4103     // Restore the stack after the call.
4104     llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
4105     CGF.Builder.CreateCall(F, StackBase);
4106   }
4107 }
4108 
4109 void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
4110                                           SourceLocation ArgLoc,
4111                                           AbstractCallee AC,
4112                                           unsigned ParmNum) {
4113   if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
4114                          SanOpts.has(SanitizerKind::NullabilityArg)))
4115     return;
4116 
4117   // The param decl may be missing in a variadic function.
4118   auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr;
4119   unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
4120 
4121   // Prefer the nonnull attribute if it's present.
4122   const NonNullAttr *NNAttr = nullptr;
4123   if (SanOpts.has(SanitizerKind::NonnullAttribute))
4124     NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
4125 
4126   bool CanCheckNullability = false;
4127   if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD) {
4128     auto Nullability = PVD->getType()->getNullability();
4129     CanCheckNullability = Nullability &&
4130                           *Nullability == NullabilityKind::NonNull &&
4131                           PVD->getTypeSourceInfo();
4132   }
4133 
4134   if (!NNAttr && !CanCheckNullability)
4135     return;
4136 
4137   SourceLocation AttrLoc;
4138   SanitizerMask CheckKind;
4139   SanitizerHandler Handler;
4140   if (NNAttr) {
4141     AttrLoc = NNAttr->getLocation();
4142     CheckKind = SanitizerKind::NonnullAttribute;
4143     Handler = SanitizerHandler::NonnullArg;
4144   } else {
4145     AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
4146     CheckKind = SanitizerKind::NullabilityArg;
4147     Handler = SanitizerHandler::NullabilityArg;
4148   }
4149 
4150   SanitizerScope SanScope(this);
4151   llvm::Value *Cond = EmitNonNullRValueCheck(RV, ArgType);
4152   llvm::Constant *StaticData[] = {
4153       EmitCheckSourceLocation(ArgLoc), EmitCheckSourceLocation(AttrLoc),
4154       llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
4155   };
4156   EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, std::nullopt);
4157 }
4158 
4159 // Check if the call is going to use the inalloca convention. This needs to
4160 // agree with CGFunctionInfo::usesInAlloca. The CGFunctionInfo is arranged
4161 // later, so we can't check it directly.
4162 static bool hasInAllocaArgs(CodeGenModule &CGM, CallingConv ExplicitCC,
4163                             ArrayRef<QualType> ArgTypes) {
4164   // The Swift calling conventions don't go through the target-specific
4165   // argument classification, they never use inalloca.
4166   // TODO: Consider limiting inalloca use to only calling conventions supported
4167   // by MSVC.
4168   if (ExplicitCC == CC_Swift || ExplicitCC == CC_SwiftAsync)
4169     return false;
4170   if (!CGM.getTarget().getCXXABI().isMicrosoft())
4171     return false;
4172   return llvm::any_of(ArgTypes, [&](QualType Ty) {
4173     return isInAllocaArgument(CGM.getCXXABI(), Ty);
4174   });
4175 }
4176 
4177 #ifndef NDEBUG
4178 // Determine whether the given argument is an Objective-C method
4179 // that may have type parameters in its signature.
4180 static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
4181   const DeclContext *dc = method->getDeclContext();
4182   if (const ObjCInterfaceDecl *classDecl = dyn_cast<ObjCInterfaceDecl>(dc)) {
4183     return classDecl->getTypeParamListAsWritten();
4184   }
4185 
4186   if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
4187     return catDecl->getTypeParamList();
4188   }
4189 
4190   return false;
4191 }
4192 #endif
4193 
4194 /// EmitCallArgs - Emit call arguments for a function.
4195 void CodeGenFunction::EmitCallArgs(
4196     CallArgList &Args, PrototypeWrapper Prototype,
4197     llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
4198     AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
4199   SmallVector<QualType, 16> ArgTypes;
4200 
4201   assert((ParamsToSkip == 0 || Prototype.P) &&
4202          "Can't skip parameters if type info is not provided");
4203 
4204   // This variable only captures *explicitly* written conventions, not those
4205   // applied by default via command line flags or target defaults, such as
4206   // thiscall, aapcs, stdcall via -mrtd, etc. Computing that correctly would
4207   // require knowing if this is a C++ instance method or being able to see
4208   // unprototyped FunctionTypes.
4209   CallingConv ExplicitCC = CC_C;
4210 
4211   // First, if a prototype was provided, use those argument types.
4212   bool IsVariadic = false;
4213   if (Prototype.P) {
4214     const auto *MD = Prototype.P.dyn_cast<const ObjCMethodDecl *>();
4215     if (MD) {
4216       IsVariadic = MD->isVariadic();
4217       ExplicitCC = getCallingConventionForDecl(
4218           MD, CGM.getTarget().getTriple().isOSWindows());
4219       ArgTypes.assign(MD->param_type_begin() + ParamsToSkip,
4220                       MD->param_type_end());
4221     } else {
4222       const auto *FPT = Prototype.P.get<const FunctionProtoType *>();
4223       IsVariadic = FPT->isVariadic();
4224       ExplicitCC = FPT->getExtInfo().getCC();
4225       ArgTypes.assign(FPT->param_type_begin() + ParamsToSkip,
4226                       FPT->param_type_end());
4227     }
4228 
4229 #ifndef NDEBUG
4230     // Check that the prototyped types match the argument expression types.
4231     bool isGenericMethod = MD && isObjCMethodWithTypeParams(MD);
4232     CallExpr::const_arg_iterator Arg = ArgRange.begin();
4233     for (QualType Ty : ArgTypes) {
4234       assert(Arg != ArgRange.end() && "Running over edge of argument list!");
4235       assert(
4236           (isGenericMethod || Ty->isVariablyModifiedType() ||
4237            Ty.getNonReferenceType()->isObjCRetainableType() ||
4238            getContext()
4239                    .getCanonicalType(Ty.getNonReferenceType())
4240                    .getTypePtr() ==
4241                getContext().getCanonicalType((*Arg)->getType()).getTypePtr()) &&
4242           "type mismatch in call argument!");
4243       ++Arg;
4244     }
4245 
4246     // Either we've emitted all the call args, or we have a call to variadic
4247     // function.
4248     assert((Arg == ArgRange.end() || IsVariadic) &&
4249            "Extra arguments in non-variadic function!");
4250 #endif
4251   }
4252 
4253   // If we still have any arguments, emit them using the type of the argument.
4254   for (auto *A : llvm::drop_begin(ArgRange, ArgTypes.size()))
4255     ArgTypes.push_back(IsVariadic ? getVarArgType(A) : A->getType());
4256   assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
4257 
4258   // We must evaluate arguments from right to left in the MS C++ ABI,
4259   // because arguments are destroyed left to right in the callee. As a special
4260   // case, there are certain language constructs that require left-to-right
4261   // evaluation, and in those cases we consider the evaluation order requirement
4262   // to trump the "destruction order is reverse construction order" guarantee.
4263   bool LeftToRight =
4264       CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
4265           ? Order == EvaluationOrder::ForceLeftToRight
4266           : Order != EvaluationOrder::ForceRightToLeft;
4267 
4268   auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
4269                                          RValue EmittedArg) {
4270     if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
4271       return;
4272     auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
4273     if (PS == nullptr)
4274       return;
4275 
4276     const auto &Context = getContext();
4277     auto SizeTy = Context.getSizeType();
4278     auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
4279     assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?");
4280     llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
4281                                                      EmittedArg.getScalarVal(),
4282                                                      PS->isDynamic());
4283     Args.add(RValue::get(V), SizeTy);
4284     // If we're emitting args in reverse, be sure to do so with
4285     // pass_object_size, as well.
4286     if (!LeftToRight)
4287       std::swap(Args.back(), *(&Args.back() - 1));
4288   };
4289 
4290   // Insert a stack save if we're going to need any inalloca args.
4291   if (hasInAllocaArgs(CGM, ExplicitCC, ArgTypes)) {
4292     assert(getTarget().getTriple().getArch() == llvm::Triple::x86 &&
4293            "inalloca only supported on x86");
4294     Args.allocateArgumentMemory(*this);
4295   }
4296 
4297   // Evaluate each argument in the appropriate order.
4298   size_t CallArgsStart = Args.size();
4299   for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
4300     unsigned Idx = LeftToRight ? I : E - I - 1;
4301     CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
4302     unsigned InitialArgSize = Args.size();
4303     // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of
4304     // the argument and parameter match or the objc method is parameterized.
4305     assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) ||
4306             getContext().hasSameUnqualifiedType((*Arg)->getType(),
4307                                                 ArgTypes[Idx]) ||
4308             (isa<ObjCMethodDecl>(AC.getDecl()) &&
4309              isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) &&
4310            "Argument and parameter types don't match");
4311     EmitCallArg(Args, *Arg, ArgTypes[Idx]);
4312     // In particular, we depend on it being the last arg in Args, and the
4313     // objectsize bits depend on there only being one arg if !LeftToRight.
4314     assert(InitialArgSize + 1 == Args.size() &&
4315            "The code below depends on only adding one arg per EmitCallArg");
4316     (void)InitialArgSize;
4317     // Since pointer argument are never emitted as LValue, it is safe to emit
4318     // non-null argument check for r-value only.
4319     if (!Args.back().hasLValue()) {
4320       RValue RVArg = Args.back().getKnownRValue();
4321       EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
4322                           ParamsToSkip + Idx);
4323       // @llvm.objectsize should never have side-effects and shouldn't need
4324       // destruction/cleanups, so we can safely "emit" it after its arg,
4325       // regardless of right-to-leftness
4326       MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
4327     }
4328   }
4329 
4330   if (!LeftToRight) {
4331     // Un-reverse the arguments we just evaluated so they match up with the LLVM
4332     // IR function.
4333     std::reverse(Args.begin() + CallArgsStart, Args.end());
4334   }
4335 }
4336 
4337 namespace {
4338 
4339 struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
4340   DestroyUnpassedArg(Address Addr, QualType Ty)
4341       : Addr(Addr), Ty(Ty) {}
4342 
4343   Address Addr;
4344   QualType Ty;
4345 
4346   void Emit(CodeGenFunction &CGF, Flags flags) override {
4347     QualType::DestructionKind DtorKind = Ty.isDestructedType();
4348     if (DtorKind == QualType::DK_cxx_destructor) {
4349       const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
4350       assert(!Dtor->isTrivial());
4351       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
4352                                 /*Delegating=*/false, Addr, Ty);
4353     } else {
4354       CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty));
4355     }
4356   }
4357 };
4358 
4359 struct DisableDebugLocationUpdates {
4360   CodeGenFunction &CGF;
4361   bool disabledDebugInfo;
4362   DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
4363     if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
4364       CGF.disableDebugInfo();
4365   }
4366   ~DisableDebugLocationUpdates() {
4367     if (disabledDebugInfo)
4368       CGF.enableDebugInfo();
4369   }
4370 };
4371 
4372 } // end anonymous namespace
4373 
4374 RValue CallArg::getRValue(CodeGenFunction &CGF) const {
4375   if (!HasLV)
4376     return RV;
4377   LValue Copy = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty), Ty);
4378   CGF.EmitAggregateCopy(Copy, LV, Ty, AggValueSlot::DoesNotOverlap,
4379                         LV.isVolatile());
4380   IsUsed = true;
4381   return RValue::getAggregate(Copy.getAddress(CGF));
4382 }
4383 
4384 void CallArg::copyInto(CodeGenFunction &CGF, Address Addr) const {
4385   LValue Dst = CGF.MakeAddrLValue(Addr, Ty);
4386   if (!HasLV && RV.isScalar())
4387     CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*isInit=*/true);
4388   else if (!HasLV && RV.isComplex())
4389     CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true);
4390   else {
4391     auto Addr = HasLV ? LV.getAddress(CGF) : RV.getAggregateAddress();
4392     LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty);
4393     // We assume that call args are never copied into subobjects.
4394     CGF.EmitAggregateCopy(Dst, SrcLV, Ty, AggValueSlot::DoesNotOverlap,
4395                           HasLV ? LV.isVolatileQualified()
4396                                 : RV.isVolatileQualified());
4397   }
4398   IsUsed = true;
4399 }
4400 
4401 void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
4402                                   QualType type) {
4403   DisableDebugLocationUpdates Dis(*this, E);
4404   if (const ObjCIndirectCopyRestoreExpr *CRE
4405         = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
4406     assert(getLangOpts().ObjCAutoRefCount);
4407     return emitWritebackArg(*this, args, CRE);
4408   }
4409 
4410   assert(type->isReferenceType() == E->isGLValue() &&
4411          "reference binding to unmaterialized r-value!");
4412 
4413   if (E->isGLValue()) {
4414     assert(E->getObjectKind() == OK_Ordinary);
4415     return args.add(EmitReferenceBindingToExpr(E), type);
4416   }
4417 
4418   bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
4419 
4420   // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
4421   // However, we still have to push an EH-only cleanup in case we unwind before
4422   // we make it to the call.
4423   if (type->isRecordType() &&
4424       type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
4425     // If we're using inalloca, use the argument memory.  Otherwise, use a
4426     // temporary.
4427     AggValueSlot Slot = args.isUsingInAlloca()
4428         ? createPlaceholderSlot(*this, type) : CreateAggTemp(type, "agg.tmp");
4429 
4430     bool DestroyedInCallee = true, NeedsEHCleanup = true;
4431     if (const auto *RD = type->getAsCXXRecordDecl())
4432       DestroyedInCallee = RD->hasNonTrivialDestructor();
4433     else
4434       NeedsEHCleanup = needsEHCleanup(type.isDestructedType());
4435 
4436     if (DestroyedInCallee)
4437       Slot.setExternallyDestructed();
4438 
4439     EmitAggExpr(E, Slot);
4440     RValue RV = Slot.asRValue();
4441     args.add(RV, type);
4442 
4443     if (DestroyedInCallee && NeedsEHCleanup) {
4444       // Create a no-op GEP between the placeholder and the cleanup so we can
4445       // RAUW it successfully.  It also serves as a marker of the first
4446       // instruction where the cleanup is active.
4447       pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
4448                                               type);
4449       // This unreachable is a temporary marker which will be removed later.
4450       llvm::Instruction *IsActive = Builder.CreateUnreachable();
4451       args.addArgCleanupDeactivation(EHStack.stable_begin(), IsActive);
4452     }
4453     return;
4454   }
4455 
4456   if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
4457       cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
4458     LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
4459     assert(L.isSimple());
4460     args.addUncopiedAggregate(L, type);
4461     return;
4462   }
4463 
4464   args.add(EmitAnyExprToTemp(E), type);
4465 }
4466 
4467 QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
4468   // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
4469   // implicitly widens null pointer constants that are arguments to varargs
4470   // functions to pointer-sized ints.
4471   if (!getTarget().getTriple().isOSWindows())
4472     return Arg->getType();
4473 
4474   if (Arg->getType()->isIntegerType() &&
4475       getContext().getTypeSize(Arg->getType()) <
4476           getContext().getTargetInfo().getPointerWidth(LangAS::Default) &&
4477       Arg->isNullPointerConstant(getContext(),
4478                                  Expr::NPC_ValueDependentIsNotNull)) {
4479     return getContext().getIntPtrType();
4480   }
4481 
4482   return Arg->getType();
4483 }
4484 
4485 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4486 // optimizer it can aggressively ignore unwind edges.
4487 void
4488 CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
4489   if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
4490       !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
4491     Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
4492                       CGM.getNoObjCARCExceptionsMetadata());
4493 }
4494 
4495 /// Emits a call to the given no-arguments nounwind runtime function.
4496 llvm::CallInst *
4497 CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4498                                          const llvm::Twine &name) {
4499   return EmitNounwindRuntimeCall(callee, std::nullopt, name);
4500 }
4501 
4502 /// Emits a call to the given nounwind runtime function.
4503 llvm::CallInst *
4504 CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4505                                          ArrayRef<llvm::Value *> args,
4506                                          const llvm::Twine &name) {
4507   llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
4508   call->setDoesNotThrow();
4509   return call;
4510 }
4511 
4512 /// Emits a simple call (never an invoke) to the given no-arguments
4513 /// runtime function.
4514 llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
4515                                                  const llvm::Twine &name) {
4516   return EmitRuntimeCall(callee, std::nullopt, name);
4517 }
4518 
4519 // Calls which may throw must have operand bundles indicating which funclet
4520 // they are nested within.
4521 SmallVector<llvm::OperandBundleDef, 1>
4522 CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) {
4523   // There is no need for a funclet operand bundle if we aren't inside a
4524   // funclet.
4525   if (!CurrentFuncletPad)
4526     return (SmallVector<llvm::OperandBundleDef, 1>());
4527 
4528   // Skip intrinsics which cannot throw (as long as they don't lower into
4529   // regular function calls in the course of IR transformations).
4530   if (auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts())) {
4531     if (CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow()) {
4532       auto IID = CalleeFn->getIntrinsicID();
4533       if (!llvm::IntrinsicInst::mayLowerToFunctionCall(IID))
4534         return (SmallVector<llvm::OperandBundleDef, 1>());
4535     }
4536   }
4537 
4538   SmallVector<llvm::OperandBundleDef, 1> BundleList;
4539   BundleList.emplace_back("funclet", CurrentFuncletPad);
4540   return BundleList;
4541 }
4542 
4543 /// Emits a simple call (never an invoke) to the given runtime function.
4544 llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
4545                                                  ArrayRef<llvm::Value *> args,
4546                                                  const llvm::Twine &name) {
4547   llvm::CallInst *call = Builder.CreateCall(
4548       callee, args, getBundlesForFunclet(callee.getCallee()), name);
4549   call->setCallingConv(getRuntimeCC());
4550   return call;
4551 }
4552 
4553 /// Emits a call or invoke to the given noreturn runtime function.
4554 void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(
4555     llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) {
4556   SmallVector<llvm::OperandBundleDef, 1> BundleList =
4557       getBundlesForFunclet(callee.getCallee());
4558 
4559   if (getInvokeDest()) {
4560     llvm::InvokeInst *invoke =
4561       Builder.CreateInvoke(callee,
4562                            getUnreachableBlock(),
4563                            getInvokeDest(),
4564                            args,
4565                            BundleList);
4566     invoke->setDoesNotReturn();
4567     invoke->setCallingConv(getRuntimeCC());
4568   } else {
4569     llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
4570     call->setDoesNotReturn();
4571     call->setCallingConv(getRuntimeCC());
4572     Builder.CreateUnreachable();
4573   }
4574 }
4575 
4576 /// Emits a call or invoke instruction to the given nullary runtime function.
4577 llvm::CallBase *
4578 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4579                                          const Twine &name) {
4580   return EmitRuntimeCallOrInvoke(callee, std::nullopt, name);
4581 }
4582 
4583 /// Emits a call or invoke instruction to the given runtime function.
4584 llvm::CallBase *
4585 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4586                                          ArrayRef<llvm::Value *> args,
4587                                          const Twine &name) {
4588   llvm::CallBase *call = EmitCallOrInvoke(callee, args, name);
4589   call->setCallingConv(getRuntimeCC());
4590   return call;
4591 }
4592 
4593 /// Emits a call or invoke instruction to the given function, depending
4594 /// on the current state of the EH stack.
4595 llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee,
4596                                                   ArrayRef<llvm::Value *> Args,
4597                                                   const Twine &Name) {
4598   llvm::BasicBlock *InvokeDest = getInvokeDest();
4599   SmallVector<llvm::OperandBundleDef, 1> BundleList =
4600       getBundlesForFunclet(Callee.getCallee());
4601 
4602   llvm::CallBase *Inst;
4603   if (!InvokeDest)
4604     Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
4605   else {
4606     llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
4607     Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
4608                                 Name);
4609     EmitBlock(ContBB);
4610   }
4611 
4612   // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4613   // optimizer it can aggressively ignore unwind edges.
4614   if (CGM.getLangOpts().ObjCAutoRefCount)
4615     AddObjCARCExceptionMetadata(Inst);
4616 
4617   return Inst;
4618 }
4619 
4620 void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
4621                                                   llvm::Value *New) {
4622   DeferredReplacements.push_back(
4623       std::make_pair(llvm::WeakTrackingVH(Old), New));
4624 }
4625 
4626 namespace {
4627 
4628 /// Specify given \p NewAlign as the alignment of return value attribute. If
4629 /// such attribute already exists, re-set it to the maximal one of two options.
4630 [[nodiscard]] llvm::AttributeList
4631 maybeRaiseRetAlignmentAttribute(llvm::LLVMContext &Ctx,
4632                                 const llvm::AttributeList &Attrs,
4633                                 llvm::Align NewAlign) {
4634   llvm::Align CurAlign = Attrs.getRetAlignment().valueOrOne();
4635   if (CurAlign >= NewAlign)
4636     return Attrs;
4637   llvm::Attribute AlignAttr = llvm::Attribute::getWithAlignment(Ctx, NewAlign);
4638   return Attrs.removeRetAttribute(Ctx, llvm::Attribute::AttrKind::Alignment)
4639       .addRetAttribute(Ctx, AlignAttr);
4640 }
4641 
4642 template <typename AlignedAttrTy> class AbstractAssumeAlignedAttrEmitter {
4643 protected:
4644   CodeGenFunction &CGF;
4645 
4646   /// We do nothing if this is, or becomes, nullptr.
4647   const AlignedAttrTy *AA = nullptr;
4648 
4649   llvm::Value *Alignment = nullptr;      // May or may not be a constant.
4650   llvm::ConstantInt *OffsetCI = nullptr; // Constant, hopefully zero.
4651 
4652   AbstractAssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
4653       : CGF(CGF_) {
4654     if (!FuncDecl)
4655       return;
4656     AA = FuncDecl->getAttr<AlignedAttrTy>();
4657   }
4658 
4659 public:
4660   /// If we can, materialize the alignment as an attribute on return value.
4661   [[nodiscard]] llvm::AttributeList
4662   TryEmitAsCallSiteAttribute(const llvm::AttributeList &Attrs) {
4663     if (!AA || OffsetCI || CGF.SanOpts.has(SanitizerKind::Alignment))
4664       return Attrs;
4665     const auto *AlignmentCI = dyn_cast<llvm::ConstantInt>(Alignment);
4666     if (!AlignmentCI)
4667       return Attrs;
4668     // We may legitimately have non-power-of-2 alignment here.
4669     // If so, this is UB land, emit it via `@llvm.assume` instead.
4670     if (!AlignmentCI->getValue().isPowerOf2())
4671       return Attrs;
4672     llvm::AttributeList NewAttrs = maybeRaiseRetAlignmentAttribute(
4673         CGF.getLLVMContext(), Attrs,
4674         llvm::Align(
4675             AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment)));
4676     AA = nullptr; // We're done. Disallow doing anything else.
4677     return NewAttrs;
4678   }
4679 
4680   /// Emit alignment assumption.
4681   /// This is a general fallback that we take if either there is an offset,
4682   /// or the alignment is variable or we are sanitizing for alignment.
4683   void EmitAsAnAssumption(SourceLocation Loc, QualType RetTy, RValue &Ret) {
4684     if (!AA)
4685       return;
4686     CGF.emitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc,
4687                                 AA->getLocation(), Alignment, OffsetCI);
4688     AA = nullptr; // We're done. Disallow doing anything else.
4689   }
4690 };
4691 
4692 /// Helper data structure to emit `AssumeAlignedAttr`.
4693 class AssumeAlignedAttrEmitter final
4694     : public AbstractAssumeAlignedAttrEmitter<AssumeAlignedAttr> {
4695 public:
4696   AssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
4697       : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
4698     if (!AA)
4699       return;
4700     // It is guaranteed that the alignment/offset are constants.
4701     Alignment = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AA->getAlignment()));
4702     if (Expr *Offset = AA->getOffset()) {
4703       OffsetCI = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(Offset));
4704       if (OffsetCI->isNullValue()) // Canonicalize zero offset to no offset.
4705         OffsetCI = nullptr;
4706     }
4707   }
4708 };
4709 
4710 /// Helper data structure to emit `AllocAlignAttr`.
4711 class AllocAlignAttrEmitter final
4712     : public AbstractAssumeAlignedAttrEmitter<AllocAlignAttr> {
4713 public:
4714   AllocAlignAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl,
4715                         const CallArgList &CallArgs)
4716       : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
4717     if (!AA)
4718       return;
4719     // Alignment may or may not be a constant, and that is okay.
4720     Alignment = CallArgs[AA->getParamIndex().getLLVMIndex()]
4721                     .getRValue(CGF)
4722                     .getScalarVal();
4723   }
4724 };
4725 
4726 } // namespace
4727 
4728 static unsigned getMaxVectorWidth(const llvm::Type *Ty) {
4729   if (auto *VT = dyn_cast<llvm::VectorType>(Ty))
4730     return VT->getPrimitiveSizeInBits().getKnownMinValue();
4731   if (auto *AT = dyn_cast<llvm::ArrayType>(Ty))
4732     return getMaxVectorWidth(AT->getElementType());
4733 
4734   unsigned MaxVectorWidth = 0;
4735   if (auto *ST = dyn_cast<llvm::StructType>(Ty))
4736     for (auto *I : ST->elements())
4737       MaxVectorWidth = std::max(MaxVectorWidth, getMaxVectorWidth(I));
4738   return MaxVectorWidth;
4739 }
4740 
4741 RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
4742                                  const CGCallee &Callee,
4743                                  ReturnValueSlot ReturnValue,
4744                                  const CallArgList &CallArgs,
4745                                  llvm::CallBase **callOrInvoke, bool IsMustTail,
4746                                  SourceLocation Loc) {
4747   // FIXME: We no longer need the types from CallArgs; lift up and simplify.
4748 
4749   assert(Callee.isOrdinary() || Callee.isVirtual());
4750 
4751   // Handle struct-return functions by passing a pointer to the
4752   // location that we would like to return into.
4753   QualType RetTy = CallInfo.getReturnType();
4754   const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
4755 
4756   llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
4757 
4758   const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
4759   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
4760     // We can only guarantee that a function is called from the correct
4761     // context/function based on the appropriate target attributes,
4762     // so only check in the case where we have both always_inline and target
4763     // since otherwise we could be making a conditional call after a check for
4764     // the proper cpu features (and it won't cause code generation issues due to
4765     // function based code generation).
4766     if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4767         TargetDecl->hasAttr<TargetAttr>())
4768       checkTargetFeatures(Loc, FD);
4769 
4770     // Some architectures (such as x86-64) have the ABI changed based on
4771     // attribute-target/features. Give them a chance to diagnose.
4772     CGM.getTargetCodeGenInfo().checkFunctionCallABI(
4773         CGM, Loc, dyn_cast_or_null<FunctionDecl>(CurCodeDecl), FD, CallArgs);
4774   }
4775 
4776 #ifndef NDEBUG
4777   if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) {
4778     // For an inalloca varargs function, we don't expect CallInfo to match the
4779     // function pointer's type, because the inalloca struct a will have extra
4780     // fields in it for the varargs parameters.  Code later in this function
4781     // bitcasts the function pointer to the type derived from CallInfo.
4782     //
4783     // In other cases, we assert that the types match up (until pointers stop
4784     // having pointee types).
4785     if (Callee.isVirtual())
4786       assert(IRFuncTy == Callee.getVirtualFunctionType());
4787     else {
4788       llvm::PointerType *PtrTy =
4789           llvm::cast<llvm::PointerType>(Callee.getFunctionPointer()->getType());
4790       assert(PtrTy->isOpaqueOrPointeeTypeMatches(IRFuncTy));
4791     }
4792   }
4793 #endif
4794 
4795   // 1. Set up the arguments.
4796 
4797   // If we're using inalloca, insert the allocation after the stack save.
4798   // FIXME: Do this earlier rather than hacking it in here!
4799   Address ArgMemory = Address::invalid();
4800   if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
4801     const llvm::DataLayout &DL = CGM.getDataLayout();
4802     llvm::Instruction *IP = CallArgs.getStackBase();
4803     llvm::AllocaInst *AI;
4804     if (IP) {
4805       IP = IP->getNextNode();
4806       AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(),
4807                                 "argmem", IP);
4808     } else {
4809       AI = CreateTempAlloca(ArgStruct, "argmem");
4810     }
4811     auto Align = CallInfo.getArgStructAlignment();
4812     AI->setAlignment(Align.getAsAlign());
4813     AI->setUsedWithInAlloca(true);
4814     assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
4815     ArgMemory = Address(AI, ArgStruct, Align);
4816   }
4817 
4818   ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
4819   SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
4820 
4821   // If the call returns a temporary with struct return, create a temporary
4822   // alloca to hold the result, unless one is given to us.
4823   Address SRetPtr = Address::invalid();
4824   Address SRetAlloca = Address::invalid();
4825   llvm::Value *UnusedReturnSizePtr = nullptr;
4826   if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
4827     if (!ReturnValue.isNull()) {
4828       SRetPtr = ReturnValue.getValue();
4829     } else {
4830       SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca);
4831       if (HaveInsertPoint() && ReturnValue.isUnused()) {
4832         llvm::TypeSize size =
4833             CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
4834         UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer());
4835       }
4836     }
4837     if (IRFunctionArgs.hasSRetArg()) {
4838       IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
4839     } else if (RetAI.isInAlloca()) {
4840       Address Addr =
4841           Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
4842       Builder.CreateStore(SRetPtr.getPointer(), Addr);
4843     }
4844   }
4845 
4846   Address swiftErrorTemp = Address::invalid();
4847   Address swiftErrorArg = Address::invalid();
4848 
4849   // When passing arguments using temporary allocas, we need to add the
4850   // appropriate lifetime markers. This vector keeps track of all the lifetime
4851   // markers that need to be ended right after the call.
4852   SmallVector<CallLifetimeEnd, 2> CallLifetimeEndAfterCall;
4853 
4854   // Translate all of the arguments as necessary to match the IR lowering.
4855   assert(CallInfo.arg_size() == CallArgs.size() &&
4856          "Mismatch between function signature & arguments.");
4857   unsigned ArgNo = 0;
4858   CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
4859   for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
4860        I != E; ++I, ++info_it, ++ArgNo) {
4861     const ABIArgInfo &ArgInfo = info_it->info;
4862 
4863     // Insert a padding argument to ensure proper alignment.
4864     if (IRFunctionArgs.hasPaddingArg(ArgNo))
4865       IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
4866           llvm::UndefValue::get(ArgInfo.getPaddingType());
4867 
4868     unsigned FirstIRArg, NumIRArgs;
4869     std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
4870 
4871     bool ArgHasMaybeUndefAttr =
4872         IsArgumentMaybeUndef(TargetDecl, CallInfo.getNumRequiredArgs(), ArgNo);
4873 
4874     switch (ArgInfo.getKind()) {
4875     case ABIArgInfo::InAlloca: {
4876       assert(NumIRArgs == 0);
4877       assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
4878       if (I->isAggregate()) {
4879         Address Addr = I->hasLValue()
4880                            ? I->getKnownLValue().getAddress(*this)
4881                            : I->getKnownRValue().getAggregateAddress();
4882         llvm::Instruction *Placeholder =
4883             cast<llvm::Instruction>(Addr.getPointer());
4884 
4885         if (!ArgInfo.getInAllocaIndirect()) {
4886           // Replace the placeholder with the appropriate argument slot GEP.
4887           CGBuilderTy::InsertPoint IP = Builder.saveIP();
4888           Builder.SetInsertPoint(Placeholder);
4889           Addr = Builder.CreateStructGEP(ArgMemory,
4890                                          ArgInfo.getInAllocaFieldIndex());
4891           Builder.restoreIP(IP);
4892         } else {
4893           // For indirect things such as overaligned structs, replace the
4894           // placeholder with a regular aggregate temporary alloca. Store the
4895           // address of this alloca into the struct.
4896           Addr = CreateMemTemp(info_it->type, "inalloca.indirect.tmp");
4897           Address ArgSlot = Builder.CreateStructGEP(
4898               ArgMemory, ArgInfo.getInAllocaFieldIndex());
4899           Builder.CreateStore(Addr.getPointer(), ArgSlot);
4900         }
4901         deferPlaceholderReplacement(Placeholder, Addr.getPointer());
4902       } else if (ArgInfo.getInAllocaIndirect()) {
4903         // Make a temporary alloca and store the address of it into the argument
4904         // struct.
4905         Address Addr = CreateMemTempWithoutCast(
4906             I->Ty, getContext().getTypeAlignInChars(I->Ty),
4907             "indirect-arg-temp");
4908         I->copyInto(*this, Addr);
4909         Address ArgSlot =
4910             Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
4911         Builder.CreateStore(Addr.getPointer(), ArgSlot);
4912       } else {
4913         // Store the RValue into the argument struct.
4914         Address Addr =
4915             Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
4916         // There are some cases where a trivial bitcast is not avoidable.  The
4917         // definition of a type later in a translation unit may change it's type
4918         // from {}* to (%struct.foo*)*.
4919         Addr = Builder.CreateElementBitCast(Addr, ConvertTypeForMem(I->Ty));
4920         I->copyInto(*this, Addr);
4921       }
4922       break;
4923     }
4924 
4925     case ABIArgInfo::Indirect:
4926     case ABIArgInfo::IndirectAliased: {
4927       assert(NumIRArgs == 1);
4928       if (!I->isAggregate()) {
4929         // Make a temporary alloca to pass the argument.
4930         Address Addr = CreateMemTempWithoutCast(
4931             I->Ty, ArgInfo.getIndirectAlign(), "indirect-arg-temp");
4932 
4933         llvm::Value *Val = Addr.getPointer();
4934         if (ArgHasMaybeUndefAttr)
4935           Val = Builder.CreateFreeze(Addr.getPointer());
4936         IRCallArgs[FirstIRArg] = Val;
4937 
4938         I->copyInto(*this, Addr);
4939       } else {
4940         // We want to avoid creating an unnecessary temporary+copy here;
4941         // however, we need one in three cases:
4942         // 1. If the argument is not byval, and we are required to copy the
4943         //    source.  (This case doesn't occur on any common architecture.)
4944         // 2. If the argument is byval, RV is not sufficiently aligned, and
4945         //    we cannot force it to be sufficiently aligned.
4946         // 3. If the argument is byval, but RV is not located in default
4947         //    or alloca address space.
4948         Address Addr = I->hasLValue()
4949                            ? I->getKnownLValue().getAddress(*this)
4950                            : I->getKnownRValue().getAggregateAddress();
4951         llvm::Value *V = Addr.getPointer();
4952         CharUnits Align = ArgInfo.getIndirectAlign();
4953         const llvm::DataLayout *TD = &CGM.getDataLayout();
4954 
4955         assert((FirstIRArg >= IRFuncTy->getNumParams() ||
4956                 IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() ==
4957                     TD->getAllocaAddrSpace()) &&
4958                "indirect argument must be in alloca address space");
4959 
4960         bool NeedCopy = false;
4961 
4962         if (Addr.getAlignment() < Align &&
4963             llvm::getOrEnforceKnownAlignment(V, Align.getAsAlign(), *TD) <
4964                 Align.getAsAlign()) {
4965           NeedCopy = true;
4966         } else if (I->hasLValue()) {
4967           auto LV = I->getKnownLValue();
4968           auto AS = LV.getAddressSpace();
4969 
4970           if (!ArgInfo.getIndirectByVal() ||
4971               (LV.getAlignment() < getContext().getTypeAlignInChars(I->Ty))) {
4972             NeedCopy = true;
4973           }
4974           if (!getLangOpts().OpenCL) {
4975             if ((ArgInfo.getIndirectByVal() &&
4976                 (AS != LangAS::Default &&
4977                  AS != CGM.getASTAllocaAddressSpace()))) {
4978               NeedCopy = true;
4979             }
4980           }
4981           // For OpenCL even if RV is located in default or alloca address space
4982           // we don't want to perform address space cast for it.
4983           else if ((ArgInfo.getIndirectByVal() &&
4984                     Addr.getType()->getAddressSpace() != IRFuncTy->
4985                       getParamType(FirstIRArg)->getPointerAddressSpace())) {
4986             NeedCopy = true;
4987           }
4988         }
4989 
4990         if (NeedCopy) {
4991           // Create an aligned temporary, and copy to it.
4992           Address AI = CreateMemTempWithoutCast(
4993               I->Ty, ArgInfo.getIndirectAlign(), "byval-temp");
4994           llvm::Value *Val = AI.getPointer();
4995           if (ArgHasMaybeUndefAttr)
4996             Val = Builder.CreateFreeze(AI.getPointer());
4997           IRCallArgs[FirstIRArg] = Val;
4998 
4999           // Emit lifetime markers for the temporary alloca.
5000           llvm::TypeSize ByvalTempElementSize =
5001               CGM.getDataLayout().getTypeAllocSize(AI.getElementType());
5002           llvm::Value *LifetimeSize =
5003               EmitLifetimeStart(ByvalTempElementSize, AI.getPointer());
5004 
5005           // Add cleanup code to emit the end lifetime marker after the call.
5006           if (LifetimeSize) // In case we disabled lifetime markers.
5007             CallLifetimeEndAfterCall.emplace_back(AI, LifetimeSize);
5008 
5009           // Generate the copy.
5010           I->copyInto(*this, AI);
5011         } else {
5012           // Skip the extra memcpy call.
5013           auto *T = llvm::PointerType::getWithSamePointeeType(
5014               cast<llvm::PointerType>(V->getType()),
5015               CGM.getDataLayout().getAllocaAddrSpace());
5016 
5017           llvm::Value *Val = getTargetHooks().performAddrSpaceCast(
5018               *this, V, LangAS::Default, CGM.getASTAllocaAddressSpace(), T,
5019               true);
5020           if (ArgHasMaybeUndefAttr)
5021             Val = Builder.CreateFreeze(Val);
5022           IRCallArgs[FirstIRArg] = Val;
5023         }
5024       }
5025       break;
5026     }
5027 
5028     case ABIArgInfo::Ignore:
5029       assert(NumIRArgs == 0);
5030       break;
5031 
5032     case ABIArgInfo::Extend:
5033     case ABIArgInfo::Direct: {
5034       if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
5035           ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
5036           ArgInfo.getDirectOffset() == 0) {
5037         assert(NumIRArgs == 1);
5038         llvm::Value *V;
5039         if (!I->isAggregate())
5040           V = I->getKnownRValue().getScalarVal();
5041         else
5042           V = Builder.CreateLoad(
5043               I->hasLValue() ? I->getKnownLValue().getAddress(*this)
5044                              : I->getKnownRValue().getAggregateAddress());
5045 
5046         // Implement swifterror by copying into a new swifterror argument.
5047         // We'll write back in the normal path out of the call.
5048         if (CallInfo.getExtParameterInfo(ArgNo).getABI()
5049               == ParameterABI::SwiftErrorResult) {
5050           assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
5051 
5052           QualType pointeeTy = I->Ty->getPointeeType();
5053           swiftErrorArg = Address(V, ConvertTypeForMem(pointeeTy),
5054                                   getContext().getTypeAlignInChars(pointeeTy));
5055 
5056           swiftErrorTemp =
5057             CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
5058           V = swiftErrorTemp.getPointer();
5059           cast<llvm::AllocaInst>(V)->setSwiftError(true);
5060 
5061           llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
5062           Builder.CreateStore(errorValue, swiftErrorTemp);
5063         }
5064 
5065         // We might have to widen integers, but we should never truncate.
5066         if (ArgInfo.getCoerceToType() != V->getType() &&
5067             V->getType()->isIntegerTy())
5068           V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
5069 
5070         // If the argument doesn't match, perform a bitcast to coerce it.  This
5071         // can happen due to trivial type mismatches.
5072         if (FirstIRArg < IRFuncTy->getNumParams() &&
5073             V->getType() != IRFuncTy->getParamType(FirstIRArg))
5074           V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
5075 
5076         if (ArgHasMaybeUndefAttr)
5077           V = Builder.CreateFreeze(V);
5078         IRCallArgs[FirstIRArg] = V;
5079         break;
5080       }
5081 
5082       // FIXME: Avoid the conversion through memory if possible.
5083       Address Src = Address::invalid();
5084       if (!I->isAggregate()) {
5085         Src = CreateMemTemp(I->Ty, "coerce");
5086         I->copyInto(*this, Src);
5087       } else {
5088         Src = I->hasLValue() ? I->getKnownLValue().getAddress(*this)
5089                              : I->getKnownRValue().getAggregateAddress();
5090       }
5091 
5092       // If the value is offset in memory, apply the offset now.
5093       Src = emitAddressAtOffset(*this, Src, ArgInfo);
5094 
5095       // Fast-isel and the optimizer generally like scalar values better than
5096       // FCAs, so we flatten them if this is safe to do for this argument.
5097       llvm::StructType *STy =
5098             dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
5099       if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
5100         llvm::Type *SrcTy = Src.getElementType();
5101         uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
5102         uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
5103 
5104         // If the source type is smaller than the destination type of the
5105         // coerce-to logic, copy the source value into a temp alloca the size
5106         // of the destination type to allow loading all of it. The bits past
5107         // the source value are left undef.
5108         if (SrcSize < DstSize) {
5109           Address TempAlloca
5110             = CreateTempAlloca(STy, Src.getAlignment(),
5111                                Src.getName() + ".coerce");
5112           Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
5113           Src = TempAlloca;
5114         } else {
5115           Src = Builder.CreateElementBitCast(Src, STy);
5116         }
5117 
5118         assert(NumIRArgs == STy->getNumElements());
5119         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
5120           Address EltPtr = Builder.CreateStructGEP(Src, i);
5121           llvm::Value *LI = Builder.CreateLoad(EltPtr);
5122           if (ArgHasMaybeUndefAttr)
5123             LI = Builder.CreateFreeze(LI);
5124           IRCallArgs[FirstIRArg + i] = LI;
5125         }
5126       } else {
5127         // In the simple case, just pass the coerced loaded value.
5128         assert(NumIRArgs == 1);
5129         llvm::Value *Load =
5130             CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
5131 
5132         if (CallInfo.isCmseNSCall()) {
5133           // For certain parameter types, clear padding bits, as they may reveal
5134           // sensitive information.
5135           // Small struct/union types are passed as integer arrays.
5136           auto *ATy = dyn_cast<llvm::ArrayType>(Load->getType());
5137           if (ATy != nullptr && isa<RecordType>(I->Ty.getCanonicalType()))
5138             Load = EmitCMSEClearRecord(Load, ATy, I->Ty);
5139         }
5140 
5141         if (ArgHasMaybeUndefAttr)
5142           Load = Builder.CreateFreeze(Load);
5143         IRCallArgs[FirstIRArg] = Load;
5144       }
5145 
5146       break;
5147     }
5148 
5149     case ABIArgInfo::CoerceAndExpand: {
5150       auto coercionType = ArgInfo.getCoerceAndExpandType();
5151       auto layout = CGM.getDataLayout().getStructLayout(coercionType);
5152 
5153       llvm::Value *tempSize = nullptr;
5154       Address addr = Address::invalid();
5155       Address AllocaAddr = Address::invalid();
5156       if (I->isAggregate()) {
5157         addr = I->hasLValue() ? I->getKnownLValue().getAddress(*this)
5158                               : I->getKnownRValue().getAggregateAddress();
5159 
5160       } else {
5161         RValue RV = I->getKnownRValue();
5162         assert(RV.isScalar()); // complex should always just be direct
5163 
5164         llvm::Type *scalarType = RV.getScalarVal()->getType();
5165         auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
5166         auto scalarAlign = CGM.getDataLayout().getPrefTypeAlign(scalarType);
5167 
5168         // Materialize to a temporary.
5169         addr = CreateTempAlloca(
5170             RV.getScalarVal()->getType(),
5171             CharUnits::fromQuantity(std::max(layout->getAlignment(), scalarAlign)),
5172             "tmp",
5173             /*ArraySize=*/nullptr, &AllocaAddr);
5174         tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer());
5175 
5176         Builder.CreateStore(RV.getScalarVal(), addr);
5177       }
5178 
5179       addr = Builder.CreateElementBitCast(addr, coercionType);
5180 
5181       unsigned IRArgPos = FirstIRArg;
5182       for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
5183         llvm::Type *eltType = coercionType->getElementType(i);
5184         if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
5185         Address eltAddr = Builder.CreateStructGEP(addr, i);
5186         llvm::Value *elt = Builder.CreateLoad(eltAddr);
5187         if (ArgHasMaybeUndefAttr)
5188           elt = Builder.CreateFreeze(elt);
5189         IRCallArgs[IRArgPos++] = elt;
5190       }
5191       assert(IRArgPos == FirstIRArg + NumIRArgs);
5192 
5193       if (tempSize) {
5194         EmitLifetimeEnd(tempSize, AllocaAddr.getPointer());
5195       }
5196 
5197       break;
5198     }
5199 
5200     case ABIArgInfo::Expand: {
5201       unsigned IRArgPos = FirstIRArg;
5202       ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos);
5203       assert(IRArgPos == FirstIRArg + NumIRArgs);
5204       break;
5205     }
5206     }
5207   }
5208 
5209   const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this);
5210   llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer();
5211 
5212   // If we're using inalloca, set up that argument.
5213   if (ArgMemory.isValid()) {
5214     llvm::Value *Arg = ArgMemory.getPointer();
5215     if (CallInfo.isVariadic()) {
5216       // When passing non-POD arguments by value to variadic functions, we will
5217       // end up with a variadic prototype and an inalloca call site.  In such
5218       // cases, we can't do any parameter mismatch checks.  Give up and bitcast
5219       // the callee.
5220       unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace();
5221       CalleePtr =
5222           Builder.CreateBitCast(CalleePtr, IRFuncTy->getPointerTo(CalleeAS));
5223     } else {
5224       llvm::Type *LastParamTy =
5225           IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
5226       if (Arg->getType() != LastParamTy) {
5227 #ifndef NDEBUG
5228         // Assert that these structs have equivalent element types.
5229         llvm::StructType *FullTy = CallInfo.getArgStruct();
5230         if (!LastParamTy->isOpaquePointerTy()) {
5231           llvm::StructType *DeclaredTy = cast<llvm::StructType>(
5232               LastParamTy->getNonOpaquePointerElementType());
5233           assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
5234           for (auto DI = DeclaredTy->element_begin(),
5235                     DE = DeclaredTy->element_end(),
5236                     FI = FullTy->element_begin();
5237                DI != DE; ++DI, ++FI)
5238             assert(*DI == *FI);
5239         }
5240 #endif
5241         Arg = Builder.CreateBitCast(Arg, LastParamTy);
5242       }
5243     }
5244     assert(IRFunctionArgs.hasInallocaArg());
5245     IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
5246   }
5247 
5248   // 2. Prepare the function pointer.
5249 
5250   // If the callee is a bitcast of a non-variadic function to have a
5251   // variadic function pointer type, check to see if we can remove the
5252   // bitcast.  This comes up with unprototyped functions.
5253   //
5254   // This makes the IR nicer, but more importantly it ensures that we
5255   // can inline the function at -O0 if it is marked always_inline.
5256   auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT,
5257                                    llvm::Value *Ptr) -> llvm::Function * {
5258     if (!CalleeFT->isVarArg())
5259       return nullptr;
5260 
5261     // Get underlying value if it's a bitcast
5262     if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) {
5263       if (CE->getOpcode() == llvm::Instruction::BitCast)
5264         Ptr = CE->getOperand(0);
5265     }
5266 
5267     llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr);
5268     if (!OrigFn)
5269       return nullptr;
5270 
5271     llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
5272 
5273     // If the original type is variadic, or if any of the component types
5274     // disagree, we cannot remove the cast.
5275     if (OrigFT->isVarArg() ||
5276         OrigFT->getNumParams() != CalleeFT->getNumParams() ||
5277         OrigFT->getReturnType() != CalleeFT->getReturnType())
5278       return nullptr;
5279 
5280     for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
5281       if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
5282         return nullptr;
5283 
5284     return OrigFn;
5285   };
5286 
5287   if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) {
5288     CalleePtr = OrigFn;
5289     IRFuncTy = OrigFn->getFunctionType();
5290   }
5291 
5292   // 3. Perform the actual call.
5293 
5294   // Deactivate any cleanups that we're supposed to do immediately before
5295   // the call.
5296   if (!CallArgs.getCleanupsToDeactivate().empty())
5297     deactivateArgCleanupsBeforeCall(*this, CallArgs);
5298 
5299   // Assert that the arguments we computed match up.  The IR verifier
5300   // will catch this, but this is a common enough source of problems
5301   // during IRGen changes that it's way better for debugging to catch
5302   // it ourselves here.
5303 #ifndef NDEBUG
5304   assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
5305   for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
5306     // Inalloca argument can have different type.
5307     if (IRFunctionArgs.hasInallocaArg() &&
5308         i == IRFunctionArgs.getInallocaArgNo())
5309       continue;
5310     if (i < IRFuncTy->getNumParams())
5311       assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
5312   }
5313 #endif
5314 
5315   // Update the largest vector width if any arguments have vector types.
5316   for (unsigned i = 0; i < IRCallArgs.size(); ++i)
5317     LargestVectorWidth = std::max(LargestVectorWidth,
5318                                   getMaxVectorWidth(IRCallArgs[i]->getType()));
5319 
5320   // Compute the calling convention and attributes.
5321   unsigned CallingConv;
5322   llvm::AttributeList Attrs;
5323   CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
5324                              Callee.getAbstractInfo(), Attrs, CallingConv,
5325                              /*AttrOnCallSite=*/true,
5326                              /*IsThunk=*/false);
5327 
5328   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
5329     if (FD->hasAttr<StrictFPAttr>())
5330       // All calls within a strictfp function are marked strictfp
5331       Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::StrictFP);
5332 
5333   // Add call-site nomerge attribute if exists.
5334   if (InNoMergeAttributedStmt)
5335     Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoMerge);
5336 
5337   // Add call-site noinline attribute if exists.
5338   if (InNoInlineAttributedStmt)
5339     Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoInline);
5340 
5341   // Add call-site always_inline attribute if exists.
5342   if (InAlwaysInlineAttributedStmt)
5343     Attrs =
5344         Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::AlwaysInline);
5345 
5346   // Apply some call-site-specific attributes.
5347   // TODO: work this into building the attribute set.
5348 
5349   // Apply always_inline to all calls within flatten functions.
5350   // FIXME: should this really take priority over __try, below?
5351   if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
5352       !InNoInlineAttributedStmt &&
5353       !(TargetDecl && TargetDecl->hasAttr<NoInlineAttr>())) {
5354     Attrs =
5355         Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::AlwaysInline);
5356   }
5357 
5358   // Disable inlining inside SEH __try blocks.
5359   if (isSEHTryScope()) {
5360     Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoInline);
5361   }
5362 
5363   // Decide whether to use a call or an invoke.
5364   bool CannotThrow;
5365   if (currentFunctionUsesSEHTry()) {
5366     // SEH cares about asynchronous exceptions, so everything can "throw."
5367     CannotThrow = false;
5368   } else if (isCleanupPadScope() &&
5369              EHPersonality::get(*this).isMSVCXXPersonality()) {
5370     // The MSVC++ personality will implicitly terminate the program if an
5371     // exception is thrown during a cleanup outside of a try/catch.
5372     // We don't need to model anything in IR to get this behavior.
5373     CannotThrow = true;
5374   } else {
5375     // Otherwise, nounwind call sites will never throw.
5376     CannotThrow = Attrs.hasFnAttr(llvm::Attribute::NoUnwind);
5377 
5378     if (auto *FPtr = dyn_cast<llvm::Function>(CalleePtr))
5379       if (FPtr->hasFnAttribute(llvm::Attribute::NoUnwind))
5380         CannotThrow = true;
5381   }
5382 
5383   // If we made a temporary, be sure to clean up after ourselves. Note that we
5384   // can't depend on being inside of an ExprWithCleanups, so we need to manually
5385   // pop this cleanup later on. Being eager about this is OK, since this
5386   // temporary is 'invisible' outside of the callee.
5387   if (UnusedReturnSizePtr)
5388     pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca,
5389                                          UnusedReturnSizePtr);
5390 
5391   llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
5392 
5393   SmallVector<llvm::OperandBundleDef, 1> BundleList =
5394       getBundlesForFunclet(CalleePtr);
5395 
5396   if (SanOpts.has(SanitizerKind::KCFI) &&
5397       !isa_and_nonnull<FunctionDecl>(TargetDecl))
5398     EmitKCFIOperandBundle(ConcreteCallee, BundleList);
5399 
5400   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
5401     if (FD->hasAttr<StrictFPAttr>())
5402       // All calls within a strictfp function are marked strictfp
5403       Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::StrictFP);
5404 
5405   AssumeAlignedAttrEmitter AssumeAlignedAttrEmitter(*this, TargetDecl);
5406   Attrs = AssumeAlignedAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
5407 
5408   AllocAlignAttrEmitter AllocAlignAttrEmitter(*this, TargetDecl, CallArgs);
5409   Attrs = AllocAlignAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
5410 
5411   // Emit the actual call/invoke instruction.
5412   llvm::CallBase *CI;
5413   if (!InvokeDest) {
5414     CI = Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList);
5415   } else {
5416     llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
5417     CI = Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs,
5418                               BundleList);
5419     EmitBlock(Cont);
5420   }
5421   if (callOrInvoke)
5422     *callOrInvoke = CI;
5423 
5424   // If this is within a function that has the guard(nocf) attribute and is an
5425   // indirect call, add the "guard_nocf" attribute to this call to indicate that
5426   // Control Flow Guard checks should not be added, even if the call is inlined.
5427   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
5428     if (const auto *A = FD->getAttr<CFGuardAttr>()) {
5429       if (A->getGuard() == CFGuardAttr::GuardArg::nocf && !CI->getCalledFunction())
5430         Attrs = Attrs.addFnAttribute(getLLVMContext(), "guard_nocf");
5431     }
5432   }
5433 
5434   // Apply the attributes and calling convention.
5435   CI->setAttributes(Attrs);
5436   CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
5437 
5438   // Apply various metadata.
5439 
5440   if (!CI->getType()->isVoidTy())
5441     CI->setName("call");
5442 
5443   // Update largest vector width from the return type.
5444   LargestVectorWidth =
5445       std::max(LargestVectorWidth, getMaxVectorWidth(CI->getType()));
5446 
5447   // Insert instrumentation or attach profile metadata at indirect call sites.
5448   // For more details, see the comment before the definition of
5449   // IPVK_IndirectCallTarget in InstrProfData.inc.
5450   if (!CI->getCalledFunction())
5451     PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
5452                      CI, CalleePtr);
5453 
5454   // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
5455   // optimizer it can aggressively ignore unwind edges.
5456   if (CGM.getLangOpts().ObjCAutoRefCount)
5457     AddObjCARCExceptionMetadata(CI);
5458 
5459   // Set tail call kind if necessary.
5460   if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
5461     if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
5462       Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
5463     else if (IsMustTail)
5464       Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
5465   }
5466 
5467   // Add metadata for calls to MSAllocator functions
5468   if (getDebugInfo() && TargetDecl &&
5469       TargetDecl->hasAttr<MSAllocatorAttr>())
5470     getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy->getPointeeType(), Loc);
5471 
5472   // Add metadata if calling an __attribute__((error(""))) or warning fn.
5473   if (TargetDecl && TargetDecl->hasAttr<ErrorAttr>()) {
5474     llvm::ConstantInt *Line =
5475         llvm::ConstantInt::get(Int32Ty, Loc.getRawEncoding());
5476     llvm::ConstantAsMetadata *MD = llvm::ConstantAsMetadata::get(Line);
5477     llvm::MDTuple *MDT = llvm::MDNode::get(getLLVMContext(), {MD});
5478     CI->setMetadata("srcloc", MDT);
5479   }
5480 
5481   // 4. Finish the call.
5482 
5483   // If the call doesn't return, finish the basic block and clear the
5484   // insertion point; this allows the rest of IRGen to discard
5485   // unreachable code.
5486   if (CI->doesNotReturn()) {
5487     if (UnusedReturnSizePtr)
5488       PopCleanupBlock();
5489 
5490     // Strip away the noreturn attribute to better diagnose unreachable UB.
5491     if (SanOpts.has(SanitizerKind::Unreachable)) {
5492       // Also remove from function since CallBase::hasFnAttr additionally checks
5493       // attributes of the called function.
5494       if (auto *F = CI->getCalledFunction())
5495         F->removeFnAttr(llvm::Attribute::NoReturn);
5496       CI->removeFnAttr(llvm::Attribute::NoReturn);
5497 
5498       // Avoid incompatibility with ASan which relies on the `noreturn`
5499       // attribute to insert handler calls.
5500       if (SanOpts.hasOneOf(SanitizerKind::Address |
5501                            SanitizerKind::KernelAddress)) {
5502         SanitizerScope SanScope(this);
5503         llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder);
5504         Builder.SetInsertPoint(CI);
5505         auto *FnType = llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
5506         llvm::FunctionCallee Fn =
5507             CGM.CreateRuntimeFunction(FnType, "__asan_handle_no_return");
5508         EmitNounwindRuntimeCall(Fn);
5509       }
5510     }
5511 
5512     EmitUnreachable(Loc);
5513     Builder.ClearInsertionPoint();
5514 
5515     // FIXME: For now, emit a dummy basic block because expr emitters in
5516     // generally are not ready to handle emitting expressions at unreachable
5517     // points.
5518     EnsureInsertPoint();
5519 
5520     // Return a reasonable RValue.
5521     return GetUndefRValue(RetTy);
5522   }
5523 
5524   // If this is a musttail call, return immediately. We do not branch to the
5525   // epilogue in this case.
5526   if (IsMustTail) {
5527     for (auto it = EHStack.find(CurrentCleanupScopeDepth); it != EHStack.end();
5528          ++it) {
5529       EHCleanupScope *Cleanup = dyn_cast<EHCleanupScope>(&*it);
5530       if (!(Cleanup && Cleanup->getCleanup()->isRedundantBeforeReturn()))
5531         CGM.ErrorUnsupported(MustTailCall, "tail call skipping over cleanups");
5532     }
5533     if (CI->getType()->isVoidTy())
5534       Builder.CreateRetVoid();
5535     else
5536       Builder.CreateRet(CI);
5537     Builder.ClearInsertionPoint();
5538     EnsureInsertPoint();
5539     return GetUndefRValue(RetTy);
5540   }
5541 
5542   // Perform the swifterror writeback.
5543   if (swiftErrorTemp.isValid()) {
5544     llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
5545     Builder.CreateStore(errorResult, swiftErrorArg);
5546   }
5547 
5548   // Emit any call-associated writebacks immediately.  Arguably this
5549   // should happen after any return-value munging.
5550   if (CallArgs.hasWritebacks())
5551     emitWritebacks(*this, CallArgs);
5552 
5553   // The stack cleanup for inalloca arguments has to run out of the normal
5554   // lexical order, so deactivate it and run it manually here.
5555   CallArgs.freeArgumentMemory(*this);
5556 
5557   // Extract the return value.
5558   RValue Ret = [&] {
5559     switch (RetAI.getKind()) {
5560     case ABIArgInfo::CoerceAndExpand: {
5561       auto coercionType = RetAI.getCoerceAndExpandType();
5562 
5563       Address addr = SRetPtr;
5564       addr = Builder.CreateElementBitCast(addr, coercionType);
5565 
5566       assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
5567       bool requiresExtract = isa<llvm::StructType>(CI->getType());
5568 
5569       unsigned unpaddedIndex = 0;
5570       for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
5571         llvm::Type *eltType = coercionType->getElementType(i);
5572         if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
5573         Address eltAddr = Builder.CreateStructGEP(addr, i);
5574         llvm::Value *elt = CI;
5575         if (requiresExtract)
5576           elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
5577         else
5578           assert(unpaddedIndex == 0);
5579         Builder.CreateStore(elt, eltAddr);
5580       }
5581       // FALLTHROUGH
5582       [[fallthrough]];
5583     }
5584 
5585     case ABIArgInfo::InAlloca:
5586     case ABIArgInfo::Indirect: {
5587       RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
5588       if (UnusedReturnSizePtr)
5589         PopCleanupBlock();
5590       return ret;
5591     }
5592 
5593     case ABIArgInfo::Ignore:
5594       // If we are ignoring an argument that had a result, make sure to
5595       // construct the appropriate return value for our caller.
5596       return GetUndefRValue(RetTy);
5597 
5598     case ABIArgInfo::Extend:
5599     case ABIArgInfo::Direct: {
5600       llvm::Type *RetIRTy = ConvertType(RetTy);
5601       if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
5602         switch (getEvaluationKind(RetTy)) {
5603         case TEK_Complex: {
5604           llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
5605           llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
5606           return RValue::getComplex(std::make_pair(Real, Imag));
5607         }
5608         case TEK_Aggregate: {
5609           Address DestPtr = ReturnValue.getValue();
5610           bool DestIsVolatile = ReturnValue.isVolatile();
5611 
5612           if (!DestPtr.isValid()) {
5613             DestPtr = CreateMemTemp(RetTy, "agg.tmp");
5614             DestIsVolatile = false;
5615           }
5616           EmitAggregateStore(CI, DestPtr, DestIsVolatile);
5617           return RValue::getAggregate(DestPtr);
5618         }
5619         case TEK_Scalar: {
5620           // If the argument doesn't match, perform a bitcast to coerce it.  This
5621           // can happen due to trivial type mismatches.
5622           llvm::Value *V = CI;
5623           if (V->getType() != RetIRTy)
5624             V = Builder.CreateBitCast(V, RetIRTy);
5625           return RValue::get(V);
5626         }
5627         }
5628         llvm_unreachable("bad evaluation kind");
5629       }
5630 
5631       Address DestPtr = ReturnValue.getValue();
5632       bool DestIsVolatile = ReturnValue.isVolatile();
5633 
5634       if (!DestPtr.isValid()) {
5635         DestPtr = CreateMemTemp(RetTy, "coerce");
5636         DestIsVolatile = false;
5637       }
5638 
5639       // If the value is offset in memory, apply the offset now.
5640       Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
5641       CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
5642 
5643       return convertTempToRValue(DestPtr, RetTy, SourceLocation());
5644     }
5645 
5646     case ABIArgInfo::Expand:
5647     case ABIArgInfo::IndirectAliased:
5648       llvm_unreachable("Invalid ABI kind for return argument");
5649     }
5650 
5651     llvm_unreachable("Unhandled ABIArgInfo::Kind");
5652   } ();
5653 
5654   // Emit the assume_aligned check on the return value.
5655   if (Ret.isScalar() && TargetDecl) {
5656     AssumeAlignedAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
5657     AllocAlignAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
5658   }
5659 
5660   // Explicitly call CallLifetimeEnd::Emit just to re-use the code even though
5661   // we can't use the full cleanup mechanism.
5662   for (CallLifetimeEnd &LifetimeEnd : CallLifetimeEndAfterCall)
5663     LifetimeEnd.Emit(*this, /*Flags=*/{});
5664 
5665   if (!ReturnValue.isExternallyDestructed() &&
5666       RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct)
5667     pushDestroy(QualType::DK_nontrivial_c_struct, Ret.getAggregateAddress(),
5668                 RetTy);
5669 
5670   return Ret;
5671 }
5672 
5673 CGCallee CGCallee::prepareConcreteCallee(CodeGenFunction &CGF) const {
5674   if (isVirtual()) {
5675     const CallExpr *CE = getVirtualCallExpr();
5676     return CGF.CGM.getCXXABI().getVirtualFunctionPointer(
5677         CGF, getVirtualMethodDecl(), getThisAddress(), getVirtualFunctionType(),
5678         CE ? CE->getBeginLoc() : SourceLocation());
5679   }
5680 
5681   return *this;
5682 }
5683 
5684 /* VarArg handling */
5685 
5686 Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
5687   VAListAddr = VE->isMicrosoftABI()
5688                  ? EmitMSVAListRef(VE->getSubExpr())
5689                  : EmitVAListRef(VE->getSubExpr());
5690   QualType Ty = VE->getType();
5691   if (VE->isMicrosoftABI())
5692     return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
5693   return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
5694 }
5695