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