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