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