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