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