xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/CodeGen/CGCall.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //===--- CGCall.cpp - Encapsulate calling convention details --------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // These classes wrap the information about a call or function
107330f729Sjoerg // definition used to handle ABI compliancy.
117330f729Sjoerg //
127330f729Sjoerg //===----------------------------------------------------------------------===//
137330f729Sjoerg 
147330f729Sjoerg #include "CGCall.h"
157330f729Sjoerg #include "ABIInfo.h"
167330f729Sjoerg #include "CGBlocks.h"
177330f729Sjoerg #include "CGCXXABI.h"
187330f729Sjoerg #include "CGCleanup.h"
19*e038c9c4Sjoerg #include "CGRecordLayout.h"
207330f729Sjoerg #include "CodeGenFunction.h"
217330f729Sjoerg #include "CodeGenModule.h"
227330f729Sjoerg #include "TargetInfo.h"
23*e038c9c4Sjoerg #include "clang/AST/Attr.h"
247330f729Sjoerg #include "clang/AST/Decl.h"
257330f729Sjoerg #include "clang/AST/DeclCXX.h"
267330f729Sjoerg #include "clang/AST/DeclObjC.h"
277330f729Sjoerg #include "clang/Basic/CodeGenOptions.h"
287330f729Sjoerg #include "clang/Basic/TargetBuiltins.h"
297330f729Sjoerg #include "clang/Basic/TargetInfo.h"
307330f729Sjoerg #include "clang/CodeGen/CGFunctionInfo.h"
317330f729Sjoerg #include "clang/CodeGen/SwiftCallingConv.h"
327330f729Sjoerg #include "llvm/ADT/StringExtras.h"
337330f729Sjoerg #include "llvm/Analysis/ValueTracking.h"
34*e038c9c4Sjoerg #include "llvm/IR/Assumptions.h"
357330f729Sjoerg #include "llvm/IR/Attributes.h"
367330f729Sjoerg #include "llvm/IR/CallingConv.h"
377330f729Sjoerg #include "llvm/IR/DataLayout.h"
387330f729Sjoerg #include "llvm/IR/InlineAsm.h"
397330f729Sjoerg #include "llvm/IR/IntrinsicInst.h"
407330f729Sjoerg #include "llvm/IR/Intrinsics.h"
41*e038c9c4Sjoerg #include "llvm/Transforms/Utils/Local.h"
427330f729Sjoerg using namespace clang;
437330f729Sjoerg using namespace CodeGen;
447330f729Sjoerg 
457330f729Sjoerg /***/
467330f729Sjoerg 
ClangCallConvToLLVMCallConv(CallingConv CC)477330f729Sjoerg unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC) {
487330f729Sjoerg   switch (CC) {
497330f729Sjoerg   default: return llvm::CallingConv::C;
507330f729Sjoerg   case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
517330f729Sjoerg   case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
527330f729Sjoerg   case CC_X86RegCall: return llvm::CallingConv::X86_RegCall;
537330f729Sjoerg   case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
547330f729Sjoerg   case CC_Win64: return llvm::CallingConv::Win64;
557330f729Sjoerg   case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
567330f729Sjoerg   case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
577330f729Sjoerg   case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
587330f729Sjoerg   case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
597330f729Sjoerg   // TODO: Add support for __pascal to LLVM.
607330f729Sjoerg   case CC_X86Pascal: return llvm::CallingConv::C;
617330f729Sjoerg   // TODO: Add support for __vectorcall to LLVM.
627330f729Sjoerg   case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
637330f729Sjoerg   case CC_AArch64VectorCall: return llvm::CallingConv::AArch64_VectorCall;
647330f729Sjoerg   case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
657330f729Sjoerg   case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv();
667330f729Sjoerg   case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
677330f729Sjoerg   case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
687330f729Sjoerg   case CC_Swift: return llvm::CallingConv::Swift;
697330f729Sjoerg   }
707330f729Sjoerg }
717330f729Sjoerg 
727330f729Sjoerg /// Derives the 'this' type for codegen purposes, i.e. ignoring method CVR
737330f729Sjoerg /// qualification. Either or both of RD and MD may be null. A null RD indicates
747330f729Sjoerg /// that there is no meaningful 'this' type, and a null MD can occur when
757330f729Sjoerg /// calling a method pointer.
DeriveThisType(const CXXRecordDecl * RD,const CXXMethodDecl * MD)767330f729Sjoerg CanQualType CodeGenTypes::DeriveThisType(const CXXRecordDecl *RD,
777330f729Sjoerg                                          const CXXMethodDecl *MD) {
787330f729Sjoerg   QualType RecTy;
797330f729Sjoerg   if (RD)
807330f729Sjoerg     RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
817330f729Sjoerg   else
827330f729Sjoerg     RecTy = Context.VoidTy;
837330f729Sjoerg 
847330f729Sjoerg   if (MD)
857330f729Sjoerg     RecTy = Context.getAddrSpaceQualType(RecTy, MD->getMethodQualifiers().getAddressSpace());
867330f729Sjoerg   return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
877330f729Sjoerg }
887330f729Sjoerg 
897330f729Sjoerg /// Returns the canonical formal type of the given C++ method.
GetFormalType(const CXXMethodDecl * MD)907330f729Sjoerg static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
917330f729Sjoerg   return MD->getType()->getCanonicalTypeUnqualified()
927330f729Sjoerg            .getAs<FunctionProtoType>();
937330f729Sjoerg }
947330f729Sjoerg 
957330f729Sjoerg /// Returns the "extra-canonicalized" return type, which discards
967330f729Sjoerg /// qualifiers on the return type.  Codegen doesn't care about them,
977330f729Sjoerg /// and it makes ABI code a little easier to be able to assume that
987330f729Sjoerg /// all parameter and return types are top-level unqualified.
GetReturnType(QualType RetTy)997330f729Sjoerg static CanQualType GetReturnType(QualType RetTy) {
1007330f729Sjoerg   return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
1017330f729Sjoerg }
1027330f729Sjoerg 
1037330f729Sjoerg /// Arrange the argument and result information for a value of the given
1047330f729Sjoerg /// unprototyped freestanding function type.
1057330f729Sjoerg const CGFunctionInfo &
arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP)1067330f729Sjoerg CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
1077330f729Sjoerg   // When translating an unprototyped function type, always use a
1087330f729Sjoerg   // variadic type.
1097330f729Sjoerg   return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
1107330f729Sjoerg                                  /*instanceMethod=*/false,
1117330f729Sjoerg                                  /*chainCall=*/false, None,
1127330f729Sjoerg                                  FTNP->getExtInfo(), {}, RequiredArgs(0));
1137330f729Sjoerg }
1147330f729Sjoerg 
addExtParameterInfosForCall(llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> & paramInfos,const FunctionProtoType * proto,unsigned prefixArgs,unsigned totalArgs)1157330f729Sjoerg static void addExtParameterInfosForCall(
1167330f729Sjoerg          llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
1177330f729Sjoerg                                         const FunctionProtoType *proto,
1187330f729Sjoerg                                         unsigned prefixArgs,
1197330f729Sjoerg                                         unsigned totalArgs) {
1207330f729Sjoerg   assert(proto->hasExtParameterInfos());
1217330f729Sjoerg   assert(paramInfos.size() <= prefixArgs);
1227330f729Sjoerg   assert(proto->getNumParams() + prefixArgs <= totalArgs);
1237330f729Sjoerg 
1247330f729Sjoerg   paramInfos.reserve(totalArgs);
1257330f729Sjoerg 
1267330f729Sjoerg   // Add default infos for any prefix args that don't already have infos.
1277330f729Sjoerg   paramInfos.resize(prefixArgs);
1287330f729Sjoerg 
1297330f729Sjoerg   // Add infos for the prototype.
1307330f729Sjoerg   for (const auto &ParamInfo : proto->getExtParameterInfos()) {
1317330f729Sjoerg     paramInfos.push_back(ParamInfo);
1327330f729Sjoerg     // pass_object_size params have no parameter info.
1337330f729Sjoerg     if (ParamInfo.hasPassObjectSize())
1347330f729Sjoerg       paramInfos.emplace_back();
1357330f729Sjoerg   }
1367330f729Sjoerg 
1377330f729Sjoerg   assert(paramInfos.size() <= totalArgs &&
1387330f729Sjoerg          "Did we forget to insert pass_object_size args?");
1397330f729Sjoerg   // Add default infos for the variadic and/or suffix arguments.
1407330f729Sjoerg   paramInfos.resize(totalArgs);
1417330f729Sjoerg }
1427330f729Sjoerg 
1437330f729Sjoerg /// Adds the formal parameters in FPT to the given prefix. If any parameter in
1447330f729Sjoerg /// FPT has pass_object_size attrs, then we'll add parameters for those, too.
appendParameterTypes(const CodeGenTypes & CGT,SmallVectorImpl<CanQualType> & prefix,SmallVectorImpl<FunctionProtoType::ExtParameterInfo> & paramInfos,CanQual<FunctionProtoType> FPT)1457330f729Sjoerg static void appendParameterTypes(const CodeGenTypes &CGT,
1467330f729Sjoerg                                  SmallVectorImpl<CanQualType> &prefix,
1477330f729Sjoerg               SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
1487330f729Sjoerg                                  CanQual<FunctionProtoType> FPT) {
1497330f729Sjoerg   // Fast path: don't touch param info if we don't need to.
1507330f729Sjoerg   if (!FPT->hasExtParameterInfos()) {
1517330f729Sjoerg     assert(paramInfos.empty() &&
1527330f729Sjoerg            "We have paramInfos, but the prototype doesn't?");
1537330f729Sjoerg     prefix.append(FPT->param_type_begin(), FPT->param_type_end());
1547330f729Sjoerg     return;
1557330f729Sjoerg   }
1567330f729Sjoerg 
1577330f729Sjoerg   unsigned PrefixSize = prefix.size();
1587330f729Sjoerg   // In the vast majority of cases, we'll have precisely FPT->getNumParams()
1597330f729Sjoerg   // parameters; the only thing that can change this is the presence of
1607330f729Sjoerg   // pass_object_size. So, we preallocate for the common case.
1617330f729Sjoerg   prefix.reserve(prefix.size() + FPT->getNumParams());
1627330f729Sjoerg 
1637330f729Sjoerg   auto ExtInfos = FPT->getExtParameterInfos();
1647330f729Sjoerg   assert(ExtInfos.size() == FPT->getNumParams());
1657330f729Sjoerg   for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
1667330f729Sjoerg     prefix.push_back(FPT->getParamType(I));
1677330f729Sjoerg     if (ExtInfos[I].hasPassObjectSize())
1687330f729Sjoerg       prefix.push_back(CGT.getContext().getSizeType());
1697330f729Sjoerg   }
1707330f729Sjoerg 
1717330f729Sjoerg   addExtParameterInfosForCall(paramInfos, FPT.getTypePtr(), PrefixSize,
1727330f729Sjoerg                               prefix.size());
1737330f729Sjoerg }
1747330f729Sjoerg 
1757330f729Sjoerg /// Arrange the LLVM function layout for a value of the given function
1767330f729Sjoerg /// type, on top of any implicit parameters already stored.
1777330f729Sjoerg static const CGFunctionInfo &
arrangeLLVMFunctionInfo(CodeGenTypes & CGT,bool instanceMethod,SmallVectorImpl<CanQualType> & prefix,CanQual<FunctionProtoType> FTP)1787330f729Sjoerg arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
1797330f729Sjoerg                         SmallVectorImpl<CanQualType> &prefix,
1807330f729Sjoerg                         CanQual<FunctionProtoType> FTP) {
1817330f729Sjoerg   SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
1827330f729Sjoerg   RequiredArgs Required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
1837330f729Sjoerg   // FIXME: Kill copy.
1847330f729Sjoerg   appendParameterTypes(CGT, prefix, paramInfos, FTP);
1857330f729Sjoerg   CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
1867330f729Sjoerg 
1877330f729Sjoerg   return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
1887330f729Sjoerg                                      /*chainCall=*/false, prefix,
1897330f729Sjoerg                                      FTP->getExtInfo(), paramInfos,
1907330f729Sjoerg                                      Required);
1917330f729Sjoerg }
1927330f729Sjoerg 
1937330f729Sjoerg /// Arrange the argument and result information for a value of the
1947330f729Sjoerg /// given freestanding function type.
1957330f729Sjoerg const CGFunctionInfo &
arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP)1967330f729Sjoerg CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
1977330f729Sjoerg   SmallVector<CanQualType, 16> argTypes;
1987330f729Sjoerg   return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
1997330f729Sjoerg                                    FTP);
2007330f729Sjoerg }
2017330f729Sjoerg 
getCallingConventionForDecl(const ObjCMethodDecl * D,bool IsWindows)202*e038c9c4Sjoerg static CallingConv getCallingConventionForDecl(const ObjCMethodDecl *D,
203*e038c9c4Sjoerg                                                bool IsWindows) {
2047330f729Sjoerg   // Set the appropriate calling convention for the Function.
2057330f729Sjoerg   if (D->hasAttr<StdCallAttr>())
2067330f729Sjoerg     return CC_X86StdCall;
2077330f729Sjoerg 
2087330f729Sjoerg   if (D->hasAttr<FastCallAttr>())
2097330f729Sjoerg     return CC_X86FastCall;
2107330f729Sjoerg 
2117330f729Sjoerg   if (D->hasAttr<RegCallAttr>())
2127330f729Sjoerg     return CC_X86RegCall;
2137330f729Sjoerg 
2147330f729Sjoerg   if (D->hasAttr<ThisCallAttr>())
2157330f729Sjoerg     return CC_X86ThisCall;
2167330f729Sjoerg 
2177330f729Sjoerg   if (D->hasAttr<VectorCallAttr>())
2187330f729Sjoerg     return CC_X86VectorCall;
2197330f729Sjoerg 
2207330f729Sjoerg   if (D->hasAttr<PascalAttr>())
2217330f729Sjoerg     return CC_X86Pascal;
2227330f729Sjoerg 
2237330f729Sjoerg   if (PcsAttr *PCS = D->getAttr<PcsAttr>())
2247330f729Sjoerg     return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
2257330f729Sjoerg 
2267330f729Sjoerg   if (D->hasAttr<AArch64VectorPcsAttr>())
2277330f729Sjoerg     return CC_AArch64VectorCall;
2287330f729Sjoerg 
2297330f729Sjoerg   if (D->hasAttr<IntelOclBiccAttr>())
2307330f729Sjoerg     return CC_IntelOclBicc;
2317330f729Sjoerg 
2327330f729Sjoerg   if (D->hasAttr<MSABIAttr>())
2337330f729Sjoerg     return IsWindows ? CC_C : CC_Win64;
2347330f729Sjoerg 
2357330f729Sjoerg   if (D->hasAttr<SysVABIAttr>())
2367330f729Sjoerg     return IsWindows ? CC_X86_64SysV : CC_C;
2377330f729Sjoerg 
2387330f729Sjoerg   if (D->hasAttr<PreserveMostAttr>())
2397330f729Sjoerg     return CC_PreserveMost;
2407330f729Sjoerg 
2417330f729Sjoerg   if (D->hasAttr<PreserveAllAttr>())
2427330f729Sjoerg     return CC_PreserveAll;
2437330f729Sjoerg 
2447330f729Sjoerg   return CC_C;
2457330f729Sjoerg }
2467330f729Sjoerg 
2477330f729Sjoerg /// Arrange the argument and result information for a call to an
2487330f729Sjoerg /// unknown C++ non-static member function of the given abstract type.
2497330f729Sjoerg /// (A null RD means we don't have any meaningful "this" argument type,
2507330f729Sjoerg ///  so fall back to a generic pointer type).
2517330f729Sjoerg /// The member function must be an ordinary function, i.e. not a
2527330f729Sjoerg /// constructor or destructor.
2537330f729Sjoerg const CGFunctionInfo &
arrangeCXXMethodType(const CXXRecordDecl * RD,const FunctionProtoType * FTP,const CXXMethodDecl * MD)2547330f729Sjoerg CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
2557330f729Sjoerg                                    const FunctionProtoType *FTP,
2567330f729Sjoerg                                    const CXXMethodDecl *MD) {
2577330f729Sjoerg   SmallVector<CanQualType, 16> argTypes;
2587330f729Sjoerg 
2597330f729Sjoerg   // Add the 'this' pointer.
2607330f729Sjoerg   argTypes.push_back(DeriveThisType(RD, MD));
2617330f729Sjoerg 
2627330f729Sjoerg   return ::arrangeLLVMFunctionInfo(
2637330f729Sjoerg       *this, true, argTypes,
2647330f729Sjoerg       FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
2657330f729Sjoerg }
2667330f729Sjoerg 
2677330f729Sjoerg /// Set calling convention for CUDA/HIP kernel.
setCUDAKernelCallingConvention(CanQualType & FTy,CodeGenModule & CGM,const FunctionDecl * FD)2687330f729Sjoerg static void setCUDAKernelCallingConvention(CanQualType &FTy, CodeGenModule &CGM,
2697330f729Sjoerg                                            const FunctionDecl *FD) {
2707330f729Sjoerg   if (FD->hasAttr<CUDAGlobalAttr>()) {
2717330f729Sjoerg     const FunctionType *FT = FTy->getAs<FunctionType>();
2727330f729Sjoerg     CGM.getTargetCodeGenInfo().setCUDAKernelCallingConvention(FT);
2737330f729Sjoerg     FTy = FT->getCanonicalTypeUnqualified();
2747330f729Sjoerg   }
2757330f729Sjoerg }
2767330f729Sjoerg 
2777330f729Sjoerg /// Arrange the argument and result information for a declaration or
2787330f729Sjoerg /// definition of the given C++ non-static member function.  The
2797330f729Sjoerg /// member function must be an ordinary function, i.e. not a
2807330f729Sjoerg /// constructor or destructor.
2817330f729Sjoerg const CGFunctionInfo &
arrangeCXXMethodDeclaration(const CXXMethodDecl * MD)2827330f729Sjoerg CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
2837330f729Sjoerg   assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
2847330f729Sjoerg   assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
2857330f729Sjoerg 
2867330f729Sjoerg   CanQualType FT = GetFormalType(MD).getAs<Type>();
2877330f729Sjoerg   setCUDAKernelCallingConvention(FT, CGM, MD);
2887330f729Sjoerg   auto prototype = FT.getAs<FunctionProtoType>();
2897330f729Sjoerg 
2907330f729Sjoerg   if (MD->isInstance()) {
2917330f729Sjoerg     // The abstract case is perfectly fine.
2927330f729Sjoerg     const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
2937330f729Sjoerg     return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
2947330f729Sjoerg   }
2957330f729Sjoerg 
2967330f729Sjoerg   return arrangeFreeFunctionType(prototype);
2977330f729Sjoerg }
2987330f729Sjoerg 
inheritingCtorHasParams(const InheritedConstructor & Inherited,CXXCtorType Type)2997330f729Sjoerg bool CodeGenTypes::inheritingCtorHasParams(
3007330f729Sjoerg     const InheritedConstructor &Inherited, CXXCtorType Type) {
3017330f729Sjoerg   // Parameters are unnecessary if we're constructing a base class subobject
3027330f729Sjoerg   // and the inherited constructor lives in a virtual base.
3037330f729Sjoerg   return Type == Ctor_Complete ||
3047330f729Sjoerg          !Inherited.getShadowDecl()->constructsVirtualBase() ||
3057330f729Sjoerg          !Target.getCXXABI().hasConstructorVariants();
3067330f729Sjoerg }
3077330f729Sjoerg 
3087330f729Sjoerg const CGFunctionInfo &
arrangeCXXStructorDeclaration(GlobalDecl GD)3097330f729Sjoerg CodeGenTypes::arrangeCXXStructorDeclaration(GlobalDecl GD) {
3107330f729Sjoerg   auto *MD = cast<CXXMethodDecl>(GD.getDecl());
3117330f729Sjoerg 
3127330f729Sjoerg   SmallVector<CanQualType, 16> argTypes;
3137330f729Sjoerg   SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
3147330f729Sjoerg   argTypes.push_back(DeriveThisType(MD->getParent(), MD));
3157330f729Sjoerg 
3167330f729Sjoerg   bool PassParams = true;
3177330f729Sjoerg 
3187330f729Sjoerg   if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
3197330f729Sjoerg     // A base class inheriting constructor doesn't get forwarded arguments
3207330f729Sjoerg     // needed to construct a virtual base (or base class thereof).
3217330f729Sjoerg     if (auto Inherited = CD->getInheritedConstructor())
3227330f729Sjoerg       PassParams = inheritingCtorHasParams(Inherited, GD.getCtorType());
3237330f729Sjoerg   }
3247330f729Sjoerg 
3257330f729Sjoerg   CanQual<FunctionProtoType> FTP = GetFormalType(MD);
3267330f729Sjoerg 
3277330f729Sjoerg   // Add the formal parameters.
3287330f729Sjoerg   if (PassParams)
3297330f729Sjoerg     appendParameterTypes(*this, argTypes, paramInfos, FTP);
3307330f729Sjoerg 
331*e038c9c4Sjoerg   CGCXXABI::AddedStructorArgCounts AddedArgs =
3327330f729Sjoerg       TheCXXABI.buildStructorSignature(GD, argTypes);
3337330f729Sjoerg   if (!paramInfos.empty()) {
3347330f729Sjoerg     // Note: prefix implies after the first param.
3357330f729Sjoerg     if (AddedArgs.Prefix)
3367330f729Sjoerg       paramInfos.insert(paramInfos.begin() + 1, AddedArgs.Prefix,
3377330f729Sjoerg                         FunctionProtoType::ExtParameterInfo{});
3387330f729Sjoerg     if (AddedArgs.Suffix)
3397330f729Sjoerg       paramInfos.append(AddedArgs.Suffix,
3407330f729Sjoerg                         FunctionProtoType::ExtParameterInfo{});
3417330f729Sjoerg   }
3427330f729Sjoerg 
3437330f729Sjoerg   RequiredArgs required =
3447330f729Sjoerg       (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
3457330f729Sjoerg                                       : RequiredArgs::All);
3467330f729Sjoerg 
3477330f729Sjoerg   FunctionType::ExtInfo extInfo = FTP->getExtInfo();
3487330f729Sjoerg   CanQualType resultType = TheCXXABI.HasThisReturn(GD)
3497330f729Sjoerg                                ? argTypes.front()
3507330f729Sjoerg                                : TheCXXABI.hasMostDerivedReturn(GD)
3517330f729Sjoerg                                      ? CGM.getContext().VoidPtrTy
3527330f729Sjoerg                                      : Context.VoidTy;
3537330f729Sjoerg   return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
3547330f729Sjoerg                                  /*chainCall=*/false, argTypes, extInfo,
3557330f729Sjoerg                                  paramInfos, required);
3567330f729Sjoerg }
3577330f729Sjoerg 
3587330f729Sjoerg static SmallVector<CanQualType, 16>
getArgTypesForCall(ASTContext & ctx,const CallArgList & args)3597330f729Sjoerg getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
3607330f729Sjoerg   SmallVector<CanQualType, 16> argTypes;
3617330f729Sjoerg   for (auto &arg : args)
3627330f729Sjoerg     argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
3637330f729Sjoerg   return argTypes;
3647330f729Sjoerg }
3657330f729Sjoerg 
3667330f729Sjoerg static SmallVector<CanQualType, 16>
getArgTypesForDeclaration(ASTContext & ctx,const FunctionArgList & args)3677330f729Sjoerg getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
3687330f729Sjoerg   SmallVector<CanQualType, 16> argTypes;
3697330f729Sjoerg   for (auto &arg : args)
3707330f729Sjoerg     argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
3717330f729Sjoerg   return argTypes;
3727330f729Sjoerg }
3737330f729Sjoerg 
3747330f729Sjoerg static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
getExtParameterInfosForCall(const FunctionProtoType * proto,unsigned prefixArgs,unsigned totalArgs)3757330f729Sjoerg getExtParameterInfosForCall(const FunctionProtoType *proto,
3767330f729Sjoerg                             unsigned prefixArgs, unsigned totalArgs) {
3777330f729Sjoerg   llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
3787330f729Sjoerg   if (proto->hasExtParameterInfos()) {
3797330f729Sjoerg     addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
3807330f729Sjoerg   }
3817330f729Sjoerg   return result;
3827330f729Sjoerg }
3837330f729Sjoerg 
3847330f729Sjoerg /// Arrange a call to a C++ method, passing the given arguments.
3857330f729Sjoerg ///
3867330f729Sjoerg /// ExtraPrefixArgs is the number of ABI-specific args passed after the `this`
3877330f729Sjoerg /// parameter.
3887330f729Sjoerg /// ExtraSuffixArgs is the number of ABI-specific args passed at the end of
3897330f729Sjoerg /// args.
3907330f729Sjoerg /// PassProtoArgs indicates whether `args` has args for the parameters in the
3917330f729Sjoerg /// given CXXConstructorDecl.
3927330f729Sjoerg const CGFunctionInfo &
arrangeCXXConstructorCall(const CallArgList & args,const CXXConstructorDecl * D,CXXCtorType CtorKind,unsigned ExtraPrefixArgs,unsigned ExtraSuffixArgs,bool PassProtoArgs)3937330f729Sjoerg CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
3947330f729Sjoerg                                         const CXXConstructorDecl *D,
3957330f729Sjoerg                                         CXXCtorType CtorKind,
3967330f729Sjoerg                                         unsigned ExtraPrefixArgs,
3977330f729Sjoerg                                         unsigned ExtraSuffixArgs,
3987330f729Sjoerg                                         bool PassProtoArgs) {
3997330f729Sjoerg   // FIXME: Kill copy.
4007330f729Sjoerg   SmallVector<CanQualType, 16> ArgTypes;
4017330f729Sjoerg   for (const auto &Arg : args)
4027330f729Sjoerg     ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
4037330f729Sjoerg 
4047330f729Sjoerg   // +1 for implicit this, which should always be args[0].
4057330f729Sjoerg   unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs;
4067330f729Sjoerg 
4077330f729Sjoerg   CanQual<FunctionProtoType> FPT = GetFormalType(D);
4087330f729Sjoerg   RequiredArgs Required = PassProtoArgs
4097330f729Sjoerg                               ? RequiredArgs::forPrototypePlus(
4107330f729Sjoerg                                     FPT, TotalPrefixArgs + ExtraSuffixArgs)
4117330f729Sjoerg                               : RequiredArgs::All;
4127330f729Sjoerg 
4137330f729Sjoerg   GlobalDecl GD(D, CtorKind);
4147330f729Sjoerg   CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
4157330f729Sjoerg                                ? ArgTypes.front()
4167330f729Sjoerg                                : TheCXXABI.hasMostDerivedReturn(GD)
4177330f729Sjoerg                                      ? CGM.getContext().VoidPtrTy
4187330f729Sjoerg                                      : Context.VoidTy;
4197330f729Sjoerg 
4207330f729Sjoerg   FunctionType::ExtInfo Info = FPT->getExtInfo();
4217330f729Sjoerg   llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> ParamInfos;
4227330f729Sjoerg   // If the prototype args are elided, we should only have ABI-specific args,
4237330f729Sjoerg   // which never have param info.
4247330f729Sjoerg   if (PassProtoArgs && FPT->hasExtParameterInfos()) {
4257330f729Sjoerg     // ABI-specific suffix arguments are treated the same as variadic arguments.
4267330f729Sjoerg     addExtParameterInfosForCall(ParamInfos, FPT.getTypePtr(), TotalPrefixArgs,
4277330f729Sjoerg                                 ArgTypes.size());
4287330f729Sjoerg   }
4297330f729Sjoerg   return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
4307330f729Sjoerg                                  /*chainCall=*/false, ArgTypes, Info,
4317330f729Sjoerg                                  ParamInfos, Required);
4327330f729Sjoerg }
4337330f729Sjoerg 
4347330f729Sjoerg /// Arrange the argument and result information for the declaration or
4357330f729Sjoerg /// definition of the given function.
4367330f729Sjoerg const CGFunctionInfo &
arrangeFunctionDeclaration(const FunctionDecl * FD)4377330f729Sjoerg CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
4387330f729Sjoerg   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
4397330f729Sjoerg     if (MD->isInstance())
4407330f729Sjoerg       return arrangeCXXMethodDeclaration(MD);
4417330f729Sjoerg 
4427330f729Sjoerg   CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
4437330f729Sjoerg 
4447330f729Sjoerg   assert(isa<FunctionType>(FTy));
4457330f729Sjoerg   setCUDAKernelCallingConvention(FTy, CGM, FD);
4467330f729Sjoerg 
4477330f729Sjoerg   // When declaring a function without a prototype, always use a
4487330f729Sjoerg   // non-variadic type.
4497330f729Sjoerg   if (CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>()) {
4507330f729Sjoerg     return arrangeLLVMFunctionInfo(
4517330f729Sjoerg         noProto->getReturnType(), /*instanceMethod=*/false,
4527330f729Sjoerg         /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All);
4537330f729Sjoerg   }
4547330f729Sjoerg 
4557330f729Sjoerg   return arrangeFreeFunctionType(FTy.castAs<FunctionProtoType>());
4567330f729Sjoerg }
4577330f729Sjoerg 
4587330f729Sjoerg /// Arrange the argument and result information for the declaration or
4597330f729Sjoerg /// definition of an Objective-C method.
4607330f729Sjoerg const CGFunctionInfo &
arrangeObjCMethodDeclaration(const ObjCMethodDecl * MD)4617330f729Sjoerg CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
4627330f729Sjoerg   // It happens that this is the same as a call with no optional
4637330f729Sjoerg   // arguments, except also using the formal 'self' type.
4647330f729Sjoerg   return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
4657330f729Sjoerg }
4667330f729Sjoerg 
4677330f729Sjoerg /// Arrange the argument and result information for the function type
4687330f729Sjoerg /// through which to perform a send to the given Objective-C method,
4697330f729Sjoerg /// using the given receiver type.  The receiver type is not always
4707330f729Sjoerg /// the 'self' type of the method or even an Objective-C pointer type.
4717330f729Sjoerg /// This is *not* the right method for actually performing such a
4727330f729Sjoerg /// message send, due to the possibility of optional arguments.
4737330f729Sjoerg const CGFunctionInfo &
arrangeObjCMessageSendSignature(const ObjCMethodDecl * MD,QualType receiverType)4747330f729Sjoerg CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
4757330f729Sjoerg                                               QualType receiverType) {
4767330f729Sjoerg   SmallVector<CanQualType, 16> argTys;
4777330f729Sjoerg   SmallVector<FunctionProtoType::ExtParameterInfo, 4> extParamInfos(2);
4787330f729Sjoerg   argTys.push_back(Context.getCanonicalParamType(receiverType));
4797330f729Sjoerg   argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
4807330f729Sjoerg   // FIXME: Kill copy?
4817330f729Sjoerg   for (const auto *I : MD->parameters()) {
4827330f729Sjoerg     argTys.push_back(Context.getCanonicalParamType(I->getType()));
4837330f729Sjoerg     auto extParamInfo = FunctionProtoType::ExtParameterInfo().withIsNoEscape(
4847330f729Sjoerg         I->hasAttr<NoEscapeAttr>());
4857330f729Sjoerg     extParamInfos.push_back(extParamInfo);
4867330f729Sjoerg   }
4877330f729Sjoerg 
4887330f729Sjoerg   FunctionType::ExtInfo einfo;
4897330f729Sjoerg   bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
4907330f729Sjoerg   einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
4917330f729Sjoerg 
4927330f729Sjoerg   if (getContext().getLangOpts().ObjCAutoRefCount &&
4937330f729Sjoerg       MD->hasAttr<NSReturnsRetainedAttr>())
4947330f729Sjoerg     einfo = einfo.withProducesResult(true);
4957330f729Sjoerg 
4967330f729Sjoerg   RequiredArgs required =
4977330f729Sjoerg     (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
4987330f729Sjoerg 
4997330f729Sjoerg   return arrangeLLVMFunctionInfo(
5007330f729Sjoerg       GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
5017330f729Sjoerg       /*chainCall=*/false, argTys, einfo, extParamInfos, required);
5027330f729Sjoerg }
5037330f729Sjoerg 
5047330f729Sjoerg const CGFunctionInfo &
arrangeUnprototypedObjCMessageSend(QualType returnType,const CallArgList & args)5057330f729Sjoerg CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
5067330f729Sjoerg                                                  const CallArgList &args) {
5077330f729Sjoerg   auto argTypes = getArgTypesForCall(Context, args);
5087330f729Sjoerg   FunctionType::ExtInfo einfo;
5097330f729Sjoerg 
5107330f729Sjoerg   return arrangeLLVMFunctionInfo(
5117330f729Sjoerg       GetReturnType(returnType), /*instanceMethod=*/false,
5127330f729Sjoerg       /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
5137330f729Sjoerg }
5147330f729Sjoerg 
5157330f729Sjoerg const CGFunctionInfo &
arrangeGlobalDeclaration(GlobalDecl GD)5167330f729Sjoerg CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
5177330f729Sjoerg   // FIXME: Do we need to handle ObjCMethodDecl?
5187330f729Sjoerg   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
5197330f729Sjoerg 
5207330f729Sjoerg   if (isa<CXXConstructorDecl>(GD.getDecl()) ||
5217330f729Sjoerg       isa<CXXDestructorDecl>(GD.getDecl()))
5227330f729Sjoerg     return arrangeCXXStructorDeclaration(GD);
5237330f729Sjoerg 
5247330f729Sjoerg   return arrangeFunctionDeclaration(FD);
5257330f729Sjoerg }
5267330f729Sjoerg 
5277330f729Sjoerg /// Arrange a thunk that takes 'this' as the first parameter followed by
5287330f729Sjoerg /// varargs.  Return a void pointer, regardless of the actual return type.
5297330f729Sjoerg /// The body of the thunk will end in a musttail call to a function of the
5307330f729Sjoerg /// correct type, and the caller will bitcast the function to the correct
5317330f729Sjoerg /// prototype.
5327330f729Sjoerg const CGFunctionInfo &
arrangeUnprototypedMustTailThunk(const CXXMethodDecl * MD)5337330f729Sjoerg CodeGenTypes::arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD) {
5347330f729Sjoerg   assert(MD->isVirtual() && "only methods have thunks");
5357330f729Sjoerg   CanQual<FunctionProtoType> FTP = GetFormalType(MD);
5367330f729Sjoerg   CanQualType ArgTys[] = {DeriveThisType(MD->getParent(), MD)};
5377330f729Sjoerg   return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
5387330f729Sjoerg                                  /*chainCall=*/false, ArgTys,
5397330f729Sjoerg                                  FTP->getExtInfo(), {}, RequiredArgs(1));
5407330f729Sjoerg }
5417330f729Sjoerg 
5427330f729Sjoerg const CGFunctionInfo &
arrangeMSCtorClosure(const CXXConstructorDecl * CD,CXXCtorType CT)5437330f729Sjoerg CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
5447330f729Sjoerg                                    CXXCtorType CT) {
5457330f729Sjoerg   assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
5467330f729Sjoerg 
5477330f729Sjoerg   CanQual<FunctionProtoType> FTP = GetFormalType(CD);
5487330f729Sjoerg   SmallVector<CanQualType, 2> ArgTys;
5497330f729Sjoerg   const CXXRecordDecl *RD = CD->getParent();
5507330f729Sjoerg   ArgTys.push_back(DeriveThisType(RD, CD));
5517330f729Sjoerg   if (CT == Ctor_CopyingClosure)
5527330f729Sjoerg     ArgTys.push_back(*FTP->param_type_begin());
5537330f729Sjoerg   if (RD->getNumVBases() > 0)
5547330f729Sjoerg     ArgTys.push_back(Context.IntTy);
5557330f729Sjoerg   CallingConv CC = Context.getDefaultCallingConvention(
5567330f729Sjoerg       /*IsVariadic=*/false, /*IsCXXMethod=*/true);
5577330f729Sjoerg   return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
5587330f729Sjoerg                                  /*chainCall=*/false, ArgTys,
5597330f729Sjoerg                                  FunctionType::ExtInfo(CC), {},
5607330f729Sjoerg                                  RequiredArgs::All);
5617330f729Sjoerg }
5627330f729Sjoerg 
5637330f729Sjoerg /// Arrange a call as unto a free function, except possibly with an
5647330f729Sjoerg /// additional number of formal parameters considered required.
5657330f729Sjoerg static const CGFunctionInfo &
arrangeFreeFunctionLikeCall(CodeGenTypes & CGT,CodeGenModule & CGM,const CallArgList & args,const FunctionType * fnType,unsigned numExtraRequiredArgs,bool chainCall)5667330f729Sjoerg arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
5677330f729Sjoerg                             CodeGenModule &CGM,
5687330f729Sjoerg                             const CallArgList &args,
5697330f729Sjoerg                             const FunctionType *fnType,
5707330f729Sjoerg                             unsigned numExtraRequiredArgs,
5717330f729Sjoerg                             bool chainCall) {
5727330f729Sjoerg   assert(args.size() >= numExtraRequiredArgs);
5737330f729Sjoerg 
5747330f729Sjoerg   llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
5757330f729Sjoerg 
5767330f729Sjoerg   // In most cases, there are no optional arguments.
5777330f729Sjoerg   RequiredArgs required = RequiredArgs::All;
5787330f729Sjoerg 
5797330f729Sjoerg   // If we have a variadic prototype, the required arguments are the
5807330f729Sjoerg   // extra prefix plus the arguments in the prototype.
5817330f729Sjoerg   if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
5827330f729Sjoerg     if (proto->isVariadic())
5837330f729Sjoerg       required = RequiredArgs::forPrototypePlus(proto, numExtraRequiredArgs);
5847330f729Sjoerg 
5857330f729Sjoerg     if (proto->hasExtParameterInfos())
5867330f729Sjoerg       addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
5877330f729Sjoerg                                   args.size());
5887330f729Sjoerg 
5897330f729Sjoerg   // If we don't have a prototype at all, but we're supposed to
5907330f729Sjoerg   // explicitly use the variadic convention for unprototyped calls,
5917330f729Sjoerg   // treat all of the arguments as required but preserve the nominal
5927330f729Sjoerg   // possibility of variadics.
5937330f729Sjoerg   } else if (CGM.getTargetCodeGenInfo()
5947330f729Sjoerg                 .isNoProtoCallVariadic(args,
5957330f729Sjoerg                                        cast<FunctionNoProtoType>(fnType))) {
5967330f729Sjoerg     required = RequiredArgs(args.size());
5977330f729Sjoerg   }
5987330f729Sjoerg 
5997330f729Sjoerg   // FIXME: Kill copy.
6007330f729Sjoerg   SmallVector<CanQualType, 16> argTypes;
6017330f729Sjoerg   for (const auto &arg : args)
6027330f729Sjoerg     argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
6037330f729Sjoerg   return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
6047330f729Sjoerg                                      /*instanceMethod=*/false, chainCall,
6057330f729Sjoerg                                      argTypes, fnType->getExtInfo(), paramInfos,
6067330f729Sjoerg                                      required);
6077330f729Sjoerg }
6087330f729Sjoerg 
6097330f729Sjoerg /// Figure out the rules for calling a function with the given formal
6107330f729Sjoerg /// type using the given arguments.  The arguments are necessary
6117330f729Sjoerg /// because the function might be unprototyped, in which case it's
6127330f729Sjoerg /// target-dependent in crazy ways.
6137330f729Sjoerg const CGFunctionInfo &
arrangeFreeFunctionCall(const CallArgList & args,const FunctionType * fnType,bool chainCall)6147330f729Sjoerg CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
6157330f729Sjoerg                                       const FunctionType *fnType,
6167330f729Sjoerg                                       bool chainCall) {
6177330f729Sjoerg   return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
6187330f729Sjoerg                                      chainCall ? 1 : 0, chainCall);
6197330f729Sjoerg }
6207330f729Sjoerg 
6217330f729Sjoerg /// A block function is essentially a free function with an
6227330f729Sjoerg /// extra implicit argument.
6237330f729Sjoerg const CGFunctionInfo &
arrangeBlockFunctionCall(const CallArgList & args,const FunctionType * fnType)6247330f729Sjoerg CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
6257330f729Sjoerg                                        const FunctionType *fnType) {
6267330f729Sjoerg   return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
6277330f729Sjoerg                                      /*chainCall=*/false);
6287330f729Sjoerg }
6297330f729Sjoerg 
6307330f729Sjoerg const CGFunctionInfo &
arrangeBlockFunctionDeclaration(const FunctionProtoType * proto,const FunctionArgList & params)6317330f729Sjoerg CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
6327330f729Sjoerg                                               const FunctionArgList &params) {
6337330f729Sjoerg   auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
6347330f729Sjoerg   auto argTypes = getArgTypesForDeclaration(Context, params);
6357330f729Sjoerg 
6367330f729Sjoerg   return arrangeLLVMFunctionInfo(GetReturnType(proto->getReturnType()),
6377330f729Sjoerg                                  /*instanceMethod*/ false, /*chainCall*/ false,
6387330f729Sjoerg                                  argTypes, proto->getExtInfo(), paramInfos,
6397330f729Sjoerg                                  RequiredArgs::forPrototypePlus(proto, 1));
6407330f729Sjoerg }
6417330f729Sjoerg 
6427330f729Sjoerg const CGFunctionInfo &
arrangeBuiltinFunctionCall(QualType resultType,const CallArgList & args)6437330f729Sjoerg CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
6447330f729Sjoerg                                          const CallArgList &args) {
6457330f729Sjoerg   // FIXME: Kill copy.
6467330f729Sjoerg   SmallVector<CanQualType, 16> argTypes;
6477330f729Sjoerg   for (const auto &Arg : args)
6487330f729Sjoerg     argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
6497330f729Sjoerg   return arrangeLLVMFunctionInfo(
6507330f729Sjoerg       GetReturnType(resultType), /*instanceMethod=*/false,
6517330f729Sjoerg       /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
6527330f729Sjoerg       /*paramInfos=*/ {}, RequiredArgs::All);
6537330f729Sjoerg }
6547330f729Sjoerg 
6557330f729Sjoerg const CGFunctionInfo &
arrangeBuiltinFunctionDeclaration(QualType resultType,const FunctionArgList & args)6567330f729Sjoerg CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
6577330f729Sjoerg                                                 const FunctionArgList &args) {
6587330f729Sjoerg   auto argTypes = getArgTypesForDeclaration(Context, args);
6597330f729Sjoerg 
6607330f729Sjoerg   return arrangeLLVMFunctionInfo(
6617330f729Sjoerg       GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
6627330f729Sjoerg       argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
6637330f729Sjoerg }
6647330f729Sjoerg 
6657330f729Sjoerg const CGFunctionInfo &
arrangeBuiltinFunctionDeclaration(CanQualType resultType,ArrayRef<CanQualType> argTypes)6667330f729Sjoerg CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
6677330f729Sjoerg                                               ArrayRef<CanQualType> argTypes) {
6687330f729Sjoerg   return arrangeLLVMFunctionInfo(
6697330f729Sjoerg       resultType, /*instanceMethod=*/false, /*chainCall=*/false,
6707330f729Sjoerg       argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
6717330f729Sjoerg }
6727330f729Sjoerg 
6737330f729Sjoerg /// Arrange a call to a C++ method, passing the given arguments.
6747330f729Sjoerg ///
6757330f729Sjoerg /// numPrefixArgs is the number of ABI-specific prefix arguments we have. It
6767330f729Sjoerg /// does not count `this`.
6777330f729Sjoerg const CGFunctionInfo &
arrangeCXXMethodCall(const CallArgList & args,const FunctionProtoType * proto,RequiredArgs required,unsigned numPrefixArgs)6787330f729Sjoerg CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
6797330f729Sjoerg                                    const FunctionProtoType *proto,
6807330f729Sjoerg                                    RequiredArgs required,
6817330f729Sjoerg                                    unsigned numPrefixArgs) {
6827330f729Sjoerg   assert(numPrefixArgs + 1 <= args.size() &&
6837330f729Sjoerg          "Emitting a call with less args than the required prefix?");
6847330f729Sjoerg   // Add one to account for `this`. It's a bit awkward here, but we don't count
6857330f729Sjoerg   // `this` in similar places elsewhere.
6867330f729Sjoerg   auto paramInfos =
6877330f729Sjoerg     getExtParameterInfosForCall(proto, numPrefixArgs + 1, args.size());
6887330f729Sjoerg 
6897330f729Sjoerg   // FIXME: Kill copy.
6907330f729Sjoerg   auto argTypes = getArgTypesForCall(Context, args);
6917330f729Sjoerg 
6927330f729Sjoerg   FunctionType::ExtInfo info = proto->getExtInfo();
6937330f729Sjoerg   return arrangeLLVMFunctionInfo(
6947330f729Sjoerg       GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
6957330f729Sjoerg       /*chainCall=*/false, argTypes, info, paramInfos, required);
6967330f729Sjoerg }
6977330f729Sjoerg 
arrangeNullaryFunction()6987330f729Sjoerg const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
6997330f729Sjoerg   return arrangeLLVMFunctionInfo(
7007330f729Sjoerg       getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
7017330f729Sjoerg       None, FunctionType::ExtInfo(), {}, RequiredArgs::All);
7027330f729Sjoerg }
7037330f729Sjoerg 
7047330f729Sjoerg const CGFunctionInfo &
arrangeCall(const CGFunctionInfo & signature,const CallArgList & args)7057330f729Sjoerg CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
7067330f729Sjoerg                           const CallArgList &args) {
7077330f729Sjoerg   assert(signature.arg_size() <= args.size());
7087330f729Sjoerg   if (signature.arg_size() == args.size())
7097330f729Sjoerg     return signature;
7107330f729Sjoerg 
7117330f729Sjoerg   SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
7127330f729Sjoerg   auto sigParamInfos = signature.getExtParameterInfos();
7137330f729Sjoerg   if (!sigParamInfos.empty()) {
7147330f729Sjoerg     paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
7157330f729Sjoerg     paramInfos.resize(args.size());
7167330f729Sjoerg   }
7177330f729Sjoerg 
7187330f729Sjoerg   auto argTypes = getArgTypesForCall(Context, args);
7197330f729Sjoerg 
7207330f729Sjoerg   assert(signature.getRequiredArgs().allowsOptionalArgs());
7217330f729Sjoerg   return arrangeLLVMFunctionInfo(signature.getReturnType(),
7227330f729Sjoerg                                  signature.isInstanceMethod(),
7237330f729Sjoerg                                  signature.isChainCall(),
7247330f729Sjoerg                                  argTypes,
7257330f729Sjoerg                                  signature.getExtInfo(),
7267330f729Sjoerg                                  paramInfos,
7277330f729Sjoerg                                  signature.getRequiredArgs());
7287330f729Sjoerg }
7297330f729Sjoerg 
7307330f729Sjoerg namespace clang {
7317330f729Sjoerg namespace CodeGen {
7327330f729Sjoerg void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI);
7337330f729Sjoerg }
7347330f729Sjoerg }
7357330f729Sjoerg 
7367330f729Sjoerg /// Arrange the argument and result information for an abstract value
7377330f729Sjoerg /// of a given function type.  This is the method which all of the
7387330f729Sjoerg /// above functions ultimately defer to.
7397330f729Sjoerg const CGFunctionInfo &
arrangeLLVMFunctionInfo(CanQualType resultType,bool instanceMethod,bool chainCall,ArrayRef<CanQualType> argTypes,FunctionType::ExtInfo info,ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,RequiredArgs required)7407330f729Sjoerg CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
7417330f729Sjoerg                                       bool instanceMethod,
7427330f729Sjoerg                                       bool chainCall,
7437330f729Sjoerg                                       ArrayRef<CanQualType> argTypes,
7447330f729Sjoerg                                       FunctionType::ExtInfo info,
7457330f729Sjoerg                      ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
7467330f729Sjoerg                                       RequiredArgs required) {
7477330f729Sjoerg   assert(llvm::all_of(argTypes,
7487330f729Sjoerg                       [](CanQualType T) { return T.isCanonicalAsParam(); }));
7497330f729Sjoerg 
7507330f729Sjoerg   // Lookup or create unique function info.
7517330f729Sjoerg   llvm::FoldingSetNodeID ID;
7527330f729Sjoerg   CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
7537330f729Sjoerg                           required, resultType, argTypes);
7547330f729Sjoerg 
7557330f729Sjoerg   void *insertPos = nullptr;
7567330f729Sjoerg   CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
7577330f729Sjoerg   if (FI)
7587330f729Sjoerg     return *FI;
7597330f729Sjoerg 
7607330f729Sjoerg   unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
7617330f729Sjoerg 
7627330f729Sjoerg   // Construct the function info.  We co-allocate the ArgInfos.
7637330f729Sjoerg   FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
7647330f729Sjoerg                               paramInfos, resultType, argTypes, required);
7657330f729Sjoerg   FunctionInfos.InsertNode(FI, insertPos);
7667330f729Sjoerg 
7677330f729Sjoerg   bool inserted = FunctionsBeingProcessed.insert(FI).second;
7687330f729Sjoerg   (void)inserted;
7697330f729Sjoerg   assert(inserted && "Recursively being processed?");
7707330f729Sjoerg 
7717330f729Sjoerg   // Compute ABI information.
7727330f729Sjoerg   if (CC == llvm::CallingConv::SPIR_KERNEL) {
7737330f729Sjoerg     // Force target independent argument handling for the host visible
7747330f729Sjoerg     // kernel functions.
7757330f729Sjoerg     computeSPIRKernelABIInfo(CGM, *FI);
7767330f729Sjoerg   } else if (info.getCC() == CC_Swift) {
7777330f729Sjoerg     swiftcall::computeABIInfo(CGM, *FI);
7787330f729Sjoerg   } else {
7797330f729Sjoerg     getABIInfo().computeInfo(*FI);
7807330f729Sjoerg   }
7817330f729Sjoerg 
7827330f729Sjoerg   // Loop over all of the computed argument and return value info.  If any of
7837330f729Sjoerg   // them are direct or extend without a specified coerce type, specify the
7847330f729Sjoerg   // default now.
7857330f729Sjoerg   ABIArgInfo &retInfo = FI->getReturnInfo();
7867330f729Sjoerg   if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
7877330f729Sjoerg     retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
7887330f729Sjoerg 
7897330f729Sjoerg   for (auto &I : FI->arguments())
7907330f729Sjoerg     if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
7917330f729Sjoerg       I.info.setCoerceToType(ConvertType(I.type));
7927330f729Sjoerg 
7937330f729Sjoerg   bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
7947330f729Sjoerg   assert(erased && "Not in set?");
7957330f729Sjoerg 
7967330f729Sjoerg   return *FI;
7977330f729Sjoerg }
7987330f729Sjoerg 
create(unsigned llvmCC,bool instanceMethod,bool chainCall,const FunctionType::ExtInfo & info,ArrayRef<ExtParameterInfo> paramInfos,CanQualType resultType,ArrayRef<CanQualType> argTypes,RequiredArgs required)7997330f729Sjoerg CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
8007330f729Sjoerg                                        bool instanceMethod,
8017330f729Sjoerg                                        bool chainCall,
8027330f729Sjoerg                                        const FunctionType::ExtInfo &info,
8037330f729Sjoerg                                        ArrayRef<ExtParameterInfo> paramInfos,
8047330f729Sjoerg                                        CanQualType resultType,
8057330f729Sjoerg                                        ArrayRef<CanQualType> argTypes,
8067330f729Sjoerg                                        RequiredArgs required) {
8077330f729Sjoerg   assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
8087330f729Sjoerg   assert(!required.allowsOptionalArgs() ||
8097330f729Sjoerg          required.getNumRequiredArgs() <= argTypes.size());
8107330f729Sjoerg 
8117330f729Sjoerg   void *buffer =
8127330f729Sjoerg     operator new(totalSizeToAlloc<ArgInfo,             ExtParameterInfo>(
8137330f729Sjoerg                                   argTypes.size() + 1, paramInfos.size()));
8147330f729Sjoerg 
8157330f729Sjoerg   CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
8167330f729Sjoerg   FI->CallingConvention = llvmCC;
8177330f729Sjoerg   FI->EffectiveCallingConvention = llvmCC;
8187330f729Sjoerg   FI->ASTCallingConvention = info.getCC();
8197330f729Sjoerg   FI->InstanceMethod = instanceMethod;
8207330f729Sjoerg   FI->ChainCall = chainCall;
821*e038c9c4Sjoerg   FI->CmseNSCall = info.getCmseNSCall();
8227330f729Sjoerg   FI->NoReturn = info.getNoReturn();
8237330f729Sjoerg   FI->ReturnsRetained = info.getProducesResult();
8247330f729Sjoerg   FI->NoCallerSavedRegs = info.getNoCallerSavedRegs();
8257330f729Sjoerg   FI->NoCfCheck = info.getNoCfCheck();
8267330f729Sjoerg   FI->Required = required;
8277330f729Sjoerg   FI->HasRegParm = info.getHasRegParm();
8287330f729Sjoerg   FI->RegParm = info.getRegParm();
8297330f729Sjoerg   FI->ArgStruct = nullptr;
8307330f729Sjoerg   FI->ArgStructAlign = 0;
8317330f729Sjoerg   FI->NumArgs = argTypes.size();
8327330f729Sjoerg   FI->HasExtParameterInfos = !paramInfos.empty();
8337330f729Sjoerg   FI->getArgsBuffer()[0].type = resultType;
8347330f729Sjoerg   for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
8357330f729Sjoerg     FI->getArgsBuffer()[i + 1].type = argTypes[i];
8367330f729Sjoerg   for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
8377330f729Sjoerg     FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
8387330f729Sjoerg   return FI;
8397330f729Sjoerg }
8407330f729Sjoerg 
8417330f729Sjoerg /***/
8427330f729Sjoerg 
8437330f729Sjoerg namespace {
8447330f729Sjoerg // ABIArgInfo::Expand implementation.
8457330f729Sjoerg 
8467330f729Sjoerg // Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
8477330f729Sjoerg struct TypeExpansion {
8487330f729Sjoerg   enum TypeExpansionKind {
8497330f729Sjoerg     // Elements of constant arrays are expanded recursively.
8507330f729Sjoerg     TEK_ConstantArray,
8517330f729Sjoerg     // Record fields are expanded recursively (but if record is a union, only
8527330f729Sjoerg     // the field with the largest size is expanded).
8537330f729Sjoerg     TEK_Record,
8547330f729Sjoerg     // For complex types, real and imaginary parts are expanded recursively.
8557330f729Sjoerg     TEK_Complex,
8567330f729Sjoerg     // All other types are not expandable.
8577330f729Sjoerg     TEK_None
8587330f729Sjoerg   };
8597330f729Sjoerg 
8607330f729Sjoerg   const TypeExpansionKind Kind;
8617330f729Sjoerg 
TypeExpansion__anon6af8234f0211::TypeExpansion8627330f729Sjoerg   TypeExpansion(TypeExpansionKind K) : Kind(K) {}
~TypeExpansion__anon6af8234f0211::TypeExpansion8637330f729Sjoerg   virtual ~TypeExpansion() {}
8647330f729Sjoerg };
8657330f729Sjoerg 
8667330f729Sjoerg struct ConstantArrayExpansion : TypeExpansion {
8677330f729Sjoerg   QualType EltTy;
8687330f729Sjoerg   uint64_t NumElts;
8697330f729Sjoerg 
ConstantArrayExpansion__anon6af8234f0211::ConstantArrayExpansion8707330f729Sjoerg   ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
8717330f729Sjoerg       : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
classof__anon6af8234f0211::ConstantArrayExpansion8727330f729Sjoerg   static bool classof(const TypeExpansion *TE) {
8737330f729Sjoerg     return TE->Kind == TEK_ConstantArray;
8747330f729Sjoerg   }
8757330f729Sjoerg };
8767330f729Sjoerg 
8777330f729Sjoerg struct RecordExpansion : TypeExpansion {
8787330f729Sjoerg   SmallVector<const CXXBaseSpecifier *, 1> Bases;
8797330f729Sjoerg 
8807330f729Sjoerg   SmallVector<const FieldDecl *, 1> Fields;
8817330f729Sjoerg 
RecordExpansion__anon6af8234f0211::RecordExpansion8827330f729Sjoerg   RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
8837330f729Sjoerg                   SmallVector<const FieldDecl *, 1> &&Fields)
8847330f729Sjoerg       : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
8857330f729Sjoerg         Fields(std::move(Fields)) {}
classof__anon6af8234f0211::RecordExpansion8867330f729Sjoerg   static bool classof(const TypeExpansion *TE) {
8877330f729Sjoerg     return TE->Kind == TEK_Record;
8887330f729Sjoerg   }
8897330f729Sjoerg };
8907330f729Sjoerg 
8917330f729Sjoerg struct ComplexExpansion : TypeExpansion {
8927330f729Sjoerg   QualType EltTy;
8937330f729Sjoerg 
ComplexExpansion__anon6af8234f0211::ComplexExpansion8947330f729Sjoerg   ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
classof__anon6af8234f0211::ComplexExpansion8957330f729Sjoerg   static bool classof(const TypeExpansion *TE) {
8967330f729Sjoerg     return TE->Kind == TEK_Complex;
8977330f729Sjoerg   }
8987330f729Sjoerg };
8997330f729Sjoerg 
9007330f729Sjoerg struct NoExpansion : TypeExpansion {
NoExpansion__anon6af8234f0211::NoExpansion9017330f729Sjoerg   NoExpansion() : TypeExpansion(TEK_None) {}
classof__anon6af8234f0211::NoExpansion9027330f729Sjoerg   static bool classof(const TypeExpansion *TE) {
9037330f729Sjoerg     return TE->Kind == TEK_None;
9047330f729Sjoerg   }
9057330f729Sjoerg };
9067330f729Sjoerg }  // namespace
9077330f729Sjoerg 
9087330f729Sjoerg static std::unique_ptr<TypeExpansion>
getTypeExpansion(QualType Ty,const ASTContext & Context)9097330f729Sjoerg getTypeExpansion(QualType Ty, const ASTContext &Context) {
9107330f729Sjoerg   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
9117330f729Sjoerg     return std::make_unique<ConstantArrayExpansion>(
9127330f729Sjoerg         AT->getElementType(), AT->getSize().getZExtValue());
9137330f729Sjoerg   }
9147330f729Sjoerg   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9157330f729Sjoerg     SmallVector<const CXXBaseSpecifier *, 1> Bases;
9167330f729Sjoerg     SmallVector<const FieldDecl *, 1> Fields;
9177330f729Sjoerg     const RecordDecl *RD = RT->getDecl();
9187330f729Sjoerg     assert(!RD->hasFlexibleArrayMember() &&
9197330f729Sjoerg            "Cannot expand structure with flexible array.");
9207330f729Sjoerg     if (RD->isUnion()) {
9217330f729Sjoerg       // Unions can be here only in degenerative cases - all the fields are same
9227330f729Sjoerg       // after flattening. Thus we have to use the "largest" field.
9237330f729Sjoerg       const FieldDecl *LargestFD = nullptr;
9247330f729Sjoerg       CharUnits UnionSize = CharUnits::Zero();
9257330f729Sjoerg 
9267330f729Sjoerg       for (const auto *FD : RD->fields()) {
9277330f729Sjoerg         if (FD->isZeroLengthBitField(Context))
9287330f729Sjoerg           continue;
9297330f729Sjoerg         assert(!FD->isBitField() &&
9307330f729Sjoerg                "Cannot expand structure with bit-field members.");
9317330f729Sjoerg         CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
9327330f729Sjoerg         if (UnionSize < FieldSize) {
9337330f729Sjoerg           UnionSize = FieldSize;
9347330f729Sjoerg           LargestFD = FD;
9357330f729Sjoerg         }
9367330f729Sjoerg       }
9377330f729Sjoerg       if (LargestFD)
9387330f729Sjoerg         Fields.push_back(LargestFD);
9397330f729Sjoerg     } else {
9407330f729Sjoerg       if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
9417330f729Sjoerg         assert(!CXXRD->isDynamicClass() &&
9427330f729Sjoerg                "cannot expand vtable pointers in dynamic classes");
9437330f729Sjoerg         for (const CXXBaseSpecifier &BS : CXXRD->bases())
9447330f729Sjoerg           Bases.push_back(&BS);
9457330f729Sjoerg       }
9467330f729Sjoerg 
9477330f729Sjoerg       for (const auto *FD : RD->fields()) {
9487330f729Sjoerg         if (FD->isZeroLengthBitField(Context))
9497330f729Sjoerg           continue;
9507330f729Sjoerg         assert(!FD->isBitField() &&
9517330f729Sjoerg                "Cannot expand structure with bit-field members.");
9527330f729Sjoerg         Fields.push_back(FD);
9537330f729Sjoerg       }
9547330f729Sjoerg     }
9557330f729Sjoerg     return std::make_unique<RecordExpansion>(std::move(Bases),
9567330f729Sjoerg                                               std::move(Fields));
9577330f729Sjoerg   }
9587330f729Sjoerg   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
9597330f729Sjoerg     return std::make_unique<ComplexExpansion>(CT->getElementType());
9607330f729Sjoerg   }
9617330f729Sjoerg   return std::make_unique<NoExpansion>();
9627330f729Sjoerg }
9637330f729Sjoerg 
getExpansionSize(QualType Ty,const ASTContext & Context)9647330f729Sjoerg static int getExpansionSize(QualType Ty, const ASTContext &Context) {
9657330f729Sjoerg   auto Exp = getTypeExpansion(Ty, Context);
9667330f729Sjoerg   if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
9677330f729Sjoerg     return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
9687330f729Sjoerg   }
9697330f729Sjoerg   if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
9707330f729Sjoerg     int Res = 0;
9717330f729Sjoerg     for (auto BS : RExp->Bases)
9727330f729Sjoerg       Res += getExpansionSize(BS->getType(), Context);
9737330f729Sjoerg     for (auto FD : RExp->Fields)
9747330f729Sjoerg       Res += getExpansionSize(FD->getType(), Context);
9757330f729Sjoerg     return Res;
9767330f729Sjoerg   }
9777330f729Sjoerg   if (isa<ComplexExpansion>(Exp.get()))
9787330f729Sjoerg     return 2;
9797330f729Sjoerg   assert(isa<NoExpansion>(Exp.get()));
9807330f729Sjoerg   return 1;
9817330f729Sjoerg }
9827330f729Sjoerg 
9837330f729Sjoerg void
getExpandedTypes(QualType Ty,SmallVectorImpl<llvm::Type * >::iterator & TI)9847330f729Sjoerg CodeGenTypes::getExpandedTypes(QualType Ty,
9857330f729Sjoerg                                SmallVectorImpl<llvm::Type *>::iterator &TI) {
9867330f729Sjoerg   auto Exp = getTypeExpansion(Ty, Context);
9877330f729Sjoerg   if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
9887330f729Sjoerg     for (int i = 0, n = CAExp->NumElts; i < n; i++) {
9897330f729Sjoerg       getExpandedTypes(CAExp->EltTy, TI);
9907330f729Sjoerg     }
9917330f729Sjoerg   } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
9927330f729Sjoerg     for (auto BS : RExp->Bases)
9937330f729Sjoerg       getExpandedTypes(BS->getType(), TI);
9947330f729Sjoerg     for (auto FD : RExp->Fields)
9957330f729Sjoerg       getExpandedTypes(FD->getType(), TI);
9967330f729Sjoerg   } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
9977330f729Sjoerg     llvm::Type *EltTy = ConvertType(CExp->EltTy);
9987330f729Sjoerg     *TI++ = EltTy;
9997330f729Sjoerg     *TI++ = EltTy;
10007330f729Sjoerg   } else {
10017330f729Sjoerg     assert(isa<NoExpansion>(Exp.get()));
10027330f729Sjoerg     *TI++ = ConvertType(Ty);
10037330f729Sjoerg   }
10047330f729Sjoerg }
10057330f729Sjoerg 
forConstantArrayExpansion(CodeGenFunction & CGF,ConstantArrayExpansion * CAE,Address BaseAddr,llvm::function_ref<void (Address)> Fn)10067330f729Sjoerg static void forConstantArrayExpansion(CodeGenFunction &CGF,
10077330f729Sjoerg                                       ConstantArrayExpansion *CAE,
10087330f729Sjoerg                                       Address BaseAddr,
10097330f729Sjoerg                                       llvm::function_ref<void(Address)> Fn) {
10107330f729Sjoerg   CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
10117330f729Sjoerg   CharUnits EltAlign =
10127330f729Sjoerg     BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
10137330f729Sjoerg 
10147330f729Sjoerg   for (int i = 0, n = CAE->NumElts; i < n; i++) {
10157330f729Sjoerg     llvm::Value *EltAddr =
10167330f729Sjoerg       CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
10177330f729Sjoerg     Fn(Address(EltAddr, EltAlign));
10187330f729Sjoerg   }
10197330f729Sjoerg }
10207330f729Sjoerg 
ExpandTypeFromArgs(QualType Ty,LValue LV,llvm::Function::arg_iterator & AI)1021*e038c9c4Sjoerg void CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
1022*e038c9c4Sjoerg                                          llvm::Function::arg_iterator &AI) {
10237330f729Sjoerg   assert(LV.isSimple() &&
10247330f729Sjoerg          "Unexpected non-simple lvalue during struct expansion.");
10257330f729Sjoerg 
10267330f729Sjoerg   auto Exp = getTypeExpansion(Ty, getContext());
10277330f729Sjoerg   if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1028*e038c9c4Sjoerg     forConstantArrayExpansion(
1029*e038c9c4Sjoerg         *this, CAExp, LV.getAddress(*this), [&](Address EltAddr) {
10307330f729Sjoerg           LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
10317330f729Sjoerg           ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
10327330f729Sjoerg         });
10337330f729Sjoerg   } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1034*e038c9c4Sjoerg     Address This = LV.getAddress(*this);
10357330f729Sjoerg     for (const CXXBaseSpecifier *BS : RExp->Bases) {
10367330f729Sjoerg       // Perform a single step derived-to-base conversion.
10377330f729Sjoerg       Address Base =
10387330f729Sjoerg           GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
10397330f729Sjoerg                                 /*NullCheckValue=*/false, SourceLocation());
10407330f729Sjoerg       LValue SubLV = MakeAddrLValue(Base, BS->getType());
10417330f729Sjoerg 
10427330f729Sjoerg       // Recurse onto bases.
10437330f729Sjoerg       ExpandTypeFromArgs(BS->getType(), SubLV, AI);
10447330f729Sjoerg     }
10457330f729Sjoerg     for (auto FD : RExp->Fields) {
10467330f729Sjoerg       // FIXME: What are the right qualifiers here?
10477330f729Sjoerg       LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
10487330f729Sjoerg       ExpandTypeFromArgs(FD->getType(), SubLV, AI);
10497330f729Sjoerg     }
10507330f729Sjoerg   } else if (isa<ComplexExpansion>(Exp.get())) {
1051*e038c9c4Sjoerg     auto realValue = &*AI++;
1052*e038c9c4Sjoerg     auto imagValue = &*AI++;
10537330f729Sjoerg     EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
10547330f729Sjoerg   } else {
1055*e038c9c4Sjoerg     // Call EmitStoreOfScalar except when the lvalue is a bitfield to emit a
1056*e038c9c4Sjoerg     // primitive store.
10577330f729Sjoerg     assert(isa<NoExpansion>(Exp.get()));
1058*e038c9c4Sjoerg     if (LV.isBitField())
1059*e038c9c4Sjoerg       EmitStoreThroughLValue(RValue::get(&*AI++), LV);
1060*e038c9c4Sjoerg     else
1061*e038c9c4Sjoerg       EmitStoreOfScalar(&*AI++, LV);
10627330f729Sjoerg   }
10637330f729Sjoerg }
10647330f729Sjoerg 
ExpandTypeToArgs(QualType Ty,CallArg Arg,llvm::FunctionType * IRFuncTy,SmallVectorImpl<llvm::Value * > & IRCallArgs,unsigned & IRCallArgPos)10657330f729Sjoerg void CodeGenFunction::ExpandTypeToArgs(
10667330f729Sjoerg     QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
10677330f729Sjoerg     SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
10687330f729Sjoerg   auto Exp = getTypeExpansion(Ty, getContext());
10697330f729Sjoerg   if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1070*e038c9c4Sjoerg     Address Addr = Arg.hasLValue() ? Arg.getKnownLValue().getAddress(*this)
10717330f729Sjoerg                                    : Arg.getKnownRValue().getAggregateAddress();
10727330f729Sjoerg     forConstantArrayExpansion(
10737330f729Sjoerg         *this, CAExp, Addr, [&](Address EltAddr) {
10747330f729Sjoerg           CallArg EltArg = CallArg(
10757330f729Sjoerg               convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation()),
10767330f729Sjoerg               CAExp->EltTy);
10777330f729Sjoerg           ExpandTypeToArgs(CAExp->EltTy, EltArg, IRFuncTy, IRCallArgs,
10787330f729Sjoerg                            IRCallArgPos);
10797330f729Sjoerg         });
10807330f729Sjoerg   } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1081*e038c9c4Sjoerg     Address This = Arg.hasLValue() ? Arg.getKnownLValue().getAddress(*this)
10827330f729Sjoerg                                    : Arg.getKnownRValue().getAggregateAddress();
10837330f729Sjoerg     for (const CXXBaseSpecifier *BS : RExp->Bases) {
10847330f729Sjoerg       // Perform a single step derived-to-base conversion.
10857330f729Sjoerg       Address Base =
10867330f729Sjoerg           GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
10877330f729Sjoerg                                 /*NullCheckValue=*/false, SourceLocation());
10887330f729Sjoerg       CallArg BaseArg = CallArg(RValue::getAggregate(Base), BS->getType());
10897330f729Sjoerg 
10907330f729Sjoerg       // Recurse onto bases.
10917330f729Sjoerg       ExpandTypeToArgs(BS->getType(), BaseArg, IRFuncTy, IRCallArgs,
10927330f729Sjoerg                        IRCallArgPos);
10937330f729Sjoerg     }
10947330f729Sjoerg 
10957330f729Sjoerg     LValue LV = MakeAddrLValue(This, Ty);
10967330f729Sjoerg     for (auto FD : RExp->Fields) {
10977330f729Sjoerg       CallArg FldArg =
10987330f729Sjoerg           CallArg(EmitRValueForField(LV, FD, SourceLocation()), FD->getType());
10997330f729Sjoerg       ExpandTypeToArgs(FD->getType(), FldArg, IRFuncTy, IRCallArgs,
11007330f729Sjoerg                        IRCallArgPos);
11017330f729Sjoerg     }
11027330f729Sjoerg   } else if (isa<ComplexExpansion>(Exp.get())) {
11037330f729Sjoerg     ComplexPairTy CV = Arg.getKnownRValue().getComplexVal();
11047330f729Sjoerg     IRCallArgs[IRCallArgPos++] = CV.first;
11057330f729Sjoerg     IRCallArgs[IRCallArgPos++] = CV.second;
11067330f729Sjoerg   } else {
11077330f729Sjoerg     assert(isa<NoExpansion>(Exp.get()));
11087330f729Sjoerg     auto RV = Arg.getKnownRValue();
11097330f729Sjoerg     assert(RV.isScalar() &&
11107330f729Sjoerg            "Unexpected non-scalar rvalue during struct expansion.");
11117330f729Sjoerg 
11127330f729Sjoerg     // Insert a bitcast as needed.
11137330f729Sjoerg     llvm::Value *V = RV.getScalarVal();
11147330f729Sjoerg     if (IRCallArgPos < IRFuncTy->getNumParams() &&
11157330f729Sjoerg         V->getType() != IRFuncTy->getParamType(IRCallArgPos))
11167330f729Sjoerg       V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
11177330f729Sjoerg 
11187330f729Sjoerg     IRCallArgs[IRCallArgPos++] = V;
11197330f729Sjoerg   }
11207330f729Sjoerg }
11217330f729Sjoerg 
11227330f729Sjoerg /// Create a temporary allocation for the purposes of coercion.
CreateTempAllocaForCoercion(CodeGenFunction & CGF,llvm::Type * Ty,CharUnits MinAlign,const Twine & Name="tmp")11237330f729Sjoerg static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
1124*e038c9c4Sjoerg                                            CharUnits MinAlign,
1125*e038c9c4Sjoerg                                            const Twine &Name = "tmp") {
11267330f729Sjoerg   // Don't use an alignment that's worse than what LLVM would prefer.
11277330f729Sjoerg   auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
11287330f729Sjoerg   CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
11297330f729Sjoerg 
1130*e038c9c4Sjoerg   return CGF.CreateTempAlloca(Ty, Align, Name + ".coerce");
11317330f729Sjoerg }
11327330f729Sjoerg 
11337330f729Sjoerg /// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
11347330f729Sjoerg /// accessing some number of bytes out of it, try to gep into the struct to get
11357330f729Sjoerg /// at its inner goodness.  Dive as deep as possible without entering an element
11367330f729Sjoerg /// with an in-memory size smaller than DstSize.
11377330f729Sjoerg static Address
EnterStructPointerForCoercedAccess(Address SrcPtr,llvm::StructType * SrcSTy,uint64_t DstSize,CodeGenFunction & CGF)11387330f729Sjoerg EnterStructPointerForCoercedAccess(Address SrcPtr,
11397330f729Sjoerg                                    llvm::StructType *SrcSTy,
11407330f729Sjoerg                                    uint64_t DstSize, CodeGenFunction &CGF) {
11417330f729Sjoerg   // We can't dive into a zero-element struct.
11427330f729Sjoerg   if (SrcSTy->getNumElements() == 0) return SrcPtr;
11437330f729Sjoerg 
11447330f729Sjoerg   llvm::Type *FirstElt = SrcSTy->getElementType(0);
11457330f729Sjoerg 
11467330f729Sjoerg   // If the first elt is at least as large as what we're looking for, or if the
11477330f729Sjoerg   // first element is the same size as the whole struct, we can enter it. The
11487330f729Sjoerg   // comparison must be made on the store size and not the alloca size. Using
11497330f729Sjoerg   // the alloca size may overstate the size of the load.
11507330f729Sjoerg   uint64_t FirstEltSize =
11517330f729Sjoerg     CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
11527330f729Sjoerg   if (FirstEltSize < DstSize &&
11537330f729Sjoerg       FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
11547330f729Sjoerg     return SrcPtr;
11557330f729Sjoerg 
11567330f729Sjoerg   // GEP into the first element.
11577330f729Sjoerg   SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, "coerce.dive");
11587330f729Sjoerg 
11597330f729Sjoerg   // If the first element is a struct, recurse.
11607330f729Sjoerg   llvm::Type *SrcTy = SrcPtr.getElementType();
11617330f729Sjoerg   if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
11627330f729Sjoerg     return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
11637330f729Sjoerg 
11647330f729Sjoerg   return SrcPtr;
11657330f729Sjoerg }
11667330f729Sjoerg 
11677330f729Sjoerg /// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
11687330f729Sjoerg /// are either integers or pointers.  This does a truncation of the value if it
11697330f729Sjoerg /// is too large or a zero extension if it is too small.
11707330f729Sjoerg ///
11717330f729Sjoerg /// This behaves as if the value were coerced through memory, so on big-endian
11727330f729Sjoerg /// targets the high bits are preserved in a truncation, while little-endian
11737330f729Sjoerg /// targets preserve the low bits.
CoerceIntOrPtrToIntOrPtr(llvm::Value * Val,llvm::Type * Ty,CodeGenFunction & CGF)11747330f729Sjoerg static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
11757330f729Sjoerg                                              llvm::Type *Ty,
11767330f729Sjoerg                                              CodeGenFunction &CGF) {
11777330f729Sjoerg   if (Val->getType() == Ty)
11787330f729Sjoerg     return Val;
11797330f729Sjoerg 
11807330f729Sjoerg   if (isa<llvm::PointerType>(Val->getType())) {
11817330f729Sjoerg     // If this is Pointer->Pointer avoid conversion to and from int.
11827330f729Sjoerg     if (isa<llvm::PointerType>(Ty))
11837330f729Sjoerg       return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
11847330f729Sjoerg 
11857330f729Sjoerg     // Convert the pointer to an integer so we can play with its width.
11867330f729Sjoerg     Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
11877330f729Sjoerg   }
11887330f729Sjoerg 
11897330f729Sjoerg   llvm::Type *DestIntTy = Ty;
11907330f729Sjoerg   if (isa<llvm::PointerType>(DestIntTy))
11917330f729Sjoerg     DestIntTy = CGF.IntPtrTy;
11927330f729Sjoerg 
11937330f729Sjoerg   if (Val->getType() != DestIntTy) {
11947330f729Sjoerg     const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
11957330f729Sjoerg     if (DL.isBigEndian()) {
11967330f729Sjoerg       // Preserve the high bits on big-endian targets.
11977330f729Sjoerg       // That is what memory coercion does.
11987330f729Sjoerg       uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
11997330f729Sjoerg       uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
12007330f729Sjoerg 
12017330f729Sjoerg       if (SrcSize > DstSize) {
12027330f729Sjoerg         Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
12037330f729Sjoerg         Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
12047330f729Sjoerg       } else {
12057330f729Sjoerg         Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
12067330f729Sjoerg         Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
12077330f729Sjoerg       }
12087330f729Sjoerg     } else {
12097330f729Sjoerg       // Little-endian targets preserve the low bits. No shifts required.
12107330f729Sjoerg       Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
12117330f729Sjoerg     }
12127330f729Sjoerg   }
12137330f729Sjoerg 
12147330f729Sjoerg   if (isa<llvm::PointerType>(Ty))
12157330f729Sjoerg     Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
12167330f729Sjoerg   return Val;
12177330f729Sjoerg }
12187330f729Sjoerg 
12197330f729Sjoerg 
12207330f729Sjoerg 
12217330f729Sjoerg /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
12227330f729Sjoerg /// a pointer to an object of type \arg Ty, known to be aligned to
12237330f729Sjoerg /// \arg SrcAlign bytes.
12247330f729Sjoerg ///
12257330f729Sjoerg /// This safely handles the case when the src type is smaller than the
12267330f729Sjoerg /// destination type; in this situation the values of bits which not
12277330f729Sjoerg /// present in the src are undefined.
CreateCoercedLoad(Address Src,llvm::Type * Ty,CodeGenFunction & CGF)12287330f729Sjoerg static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
12297330f729Sjoerg                                       CodeGenFunction &CGF) {
12307330f729Sjoerg   llvm::Type *SrcTy = Src.getElementType();
12317330f729Sjoerg 
12327330f729Sjoerg   // If SrcTy and Ty are the same, just do a load.
12337330f729Sjoerg   if (SrcTy == Ty)
12347330f729Sjoerg     return CGF.Builder.CreateLoad(Src);
12357330f729Sjoerg 
1236*e038c9c4Sjoerg   llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
12377330f729Sjoerg 
12387330f729Sjoerg   if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
1239*e038c9c4Sjoerg     Src = EnterStructPointerForCoercedAccess(Src, SrcSTy,
1240*e038c9c4Sjoerg                                              DstSize.getFixedSize(), CGF);
1241*e038c9c4Sjoerg     SrcTy = Src.getElementType();
12427330f729Sjoerg   }
12437330f729Sjoerg 
1244*e038c9c4Sjoerg   llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
12457330f729Sjoerg 
12467330f729Sjoerg   // If the source and destination are integer or pointer types, just do an
12477330f729Sjoerg   // extension or truncation to the desired type.
12487330f729Sjoerg   if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
12497330f729Sjoerg       (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
12507330f729Sjoerg     llvm::Value *Load = CGF.Builder.CreateLoad(Src);
12517330f729Sjoerg     return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
12527330f729Sjoerg   }
12537330f729Sjoerg 
12547330f729Sjoerg   // If load is legal, just bitcast the src pointer.
1255*e038c9c4Sjoerg   if (!SrcSize.isScalable() && !DstSize.isScalable() &&
1256*e038c9c4Sjoerg       SrcSize.getFixedSize() >= DstSize.getFixedSize()) {
12577330f729Sjoerg     // Generally SrcSize is never greater than DstSize, since this means we are
12587330f729Sjoerg     // losing bits. However, this can happen in cases where the structure has
12597330f729Sjoerg     // additional padding, for example due to a user specified alignment.
12607330f729Sjoerg     //
12617330f729Sjoerg     // FIXME: Assert that we aren't truncating non-padding bits when have access
12627330f729Sjoerg     // to that information.
12637330f729Sjoerg     Src = CGF.Builder.CreateBitCast(Src,
12647330f729Sjoerg                                     Ty->getPointerTo(Src.getAddressSpace()));
12657330f729Sjoerg     return CGF.Builder.CreateLoad(Src);
12667330f729Sjoerg   }
12677330f729Sjoerg 
1268*e038c9c4Sjoerg   // If coercing a fixed vector to a scalable vector for ABI compatibility, and
1269*e038c9c4Sjoerg   // the types match, use the llvm.experimental.vector.insert intrinsic to
1270*e038c9c4Sjoerg   // perform the conversion.
1271*e038c9c4Sjoerg   if (auto *ScalableDst = dyn_cast<llvm::ScalableVectorType>(Ty)) {
1272*e038c9c4Sjoerg     if (auto *FixedSrc = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
1273*e038c9c4Sjoerg       if (ScalableDst->getElementType() == FixedSrc->getElementType()) {
1274*e038c9c4Sjoerg         auto *Load = CGF.Builder.CreateLoad(Src);
1275*e038c9c4Sjoerg         auto *UndefVec = llvm::UndefValue::get(ScalableDst);
1276*e038c9c4Sjoerg         auto *Zero = llvm::Constant::getNullValue(CGF.CGM.Int64Ty);
1277*e038c9c4Sjoerg         return CGF.Builder.CreateInsertVector(ScalableDst, UndefVec, Load, Zero,
1278*e038c9c4Sjoerg                                               "castScalableSve");
1279*e038c9c4Sjoerg       }
1280*e038c9c4Sjoerg     }
1281*e038c9c4Sjoerg   }
1282*e038c9c4Sjoerg 
12837330f729Sjoerg   // Otherwise do coercion through memory. This is stupid, but simple.
1284*e038c9c4Sjoerg   Address Tmp =
1285*e038c9c4Sjoerg       CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment(), Src.getName());
1286*e038c9c4Sjoerg   CGF.Builder.CreateMemCpy(
1287*e038c9c4Sjoerg       Tmp.getPointer(), Tmp.getAlignment().getAsAlign(), Src.getPointer(),
1288*e038c9c4Sjoerg       Src.getAlignment().getAsAlign(),
1289*e038c9c4Sjoerg       llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize.getKnownMinSize()));
12907330f729Sjoerg   return CGF.Builder.CreateLoad(Tmp);
12917330f729Sjoerg }
12927330f729Sjoerg 
12937330f729Sjoerg // Function to store a first-class aggregate into memory.  We prefer to
12947330f729Sjoerg // store the elements rather than the aggregate to be more friendly to
12957330f729Sjoerg // fast-isel.
12967330f729Sjoerg // FIXME: Do we need to recurse here?
EmitAggregateStore(llvm::Value * Val,Address Dest,bool DestIsVolatile)1297*e038c9c4Sjoerg void CodeGenFunction::EmitAggregateStore(llvm::Value *Val, Address Dest,
1298*e038c9c4Sjoerg                                          bool DestIsVolatile) {
12997330f729Sjoerg   // Prefer scalar stores to first-class aggregate stores.
1300*e038c9c4Sjoerg   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(Val->getType())) {
13017330f729Sjoerg     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1302*e038c9c4Sjoerg       Address EltPtr = Builder.CreateStructGEP(Dest, i);
1303*e038c9c4Sjoerg       llvm::Value *Elt = Builder.CreateExtractValue(Val, i);
1304*e038c9c4Sjoerg       Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
13057330f729Sjoerg     }
13067330f729Sjoerg   } else {
1307*e038c9c4Sjoerg     Builder.CreateStore(Val, Dest, DestIsVolatile);
13087330f729Sjoerg   }
13097330f729Sjoerg }
13107330f729Sjoerg 
13117330f729Sjoerg /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
13127330f729Sjoerg /// where the source and destination may have different types.  The
13137330f729Sjoerg /// destination is known to be aligned to \arg DstAlign bytes.
13147330f729Sjoerg ///
13157330f729Sjoerg /// This safely handles the case when the src type is larger than the
13167330f729Sjoerg /// destination type; the upper bits of the src will be lost.
CreateCoercedStore(llvm::Value * Src,Address Dst,bool DstIsVolatile,CodeGenFunction & CGF)13177330f729Sjoerg static void CreateCoercedStore(llvm::Value *Src,
13187330f729Sjoerg                                Address Dst,
13197330f729Sjoerg                                bool DstIsVolatile,
13207330f729Sjoerg                                CodeGenFunction &CGF) {
13217330f729Sjoerg   llvm::Type *SrcTy = Src->getType();
1322*e038c9c4Sjoerg   llvm::Type *DstTy = Dst.getElementType();
13237330f729Sjoerg   if (SrcTy == DstTy) {
13247330f729Sjoerg     CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
13257330f729Sjoerg     return;
13267330f729Sjoerg   }
13277330f729Sjoerg 
1328*e038c9c4Sjoerg   llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
13297330f729Sjoerg 
13307330f729Sjoerg   if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
1331*e038c9c4Sjoerg     Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy,
1332*e038c9c4Sjoerg                                              SrcSize.getFixedSize(), CGF);
1333*e038c9c4Sjoerg     DstTy = Dst.getElementType();
1334*e038c9c4Sjoerg   }
1335*e038c9c4Sjoerg 
1336*e038c9c4Sjoerg   llvm::PointerType *SrcPtrTy = llvm::dyn_cast<llvm::PointerType>(SrcTy);
1337*e038c9c4Sjoerg   llvm::PointerType *DstPtrTy = llvm::dyn_cast<llvm::PointerType>(DstTy);
1338*e038c9c4Sjoerg   if (SrcPtrTy && DstPtrTy &&
1339*e038c9c4Sjoerg       SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace()) {
1340*e038c9c4Sjoerg     Src = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy);
1341*e038c9c4Sjoerg     CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1342*e038c9c4Sjoerg     return;
13437330f729Sjoerg   }
13447330f729Sjoerg 
13457330f729Sjoerg   // If the source and destination are integer or pointer types, just do an
13467330f729Sjoerg   // extension or truncation to the desired type.
13477330f729Sjoerg   if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
13487330f729Sjoerg       (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
13497330f729Sjoerg     Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
13507330f729Sjoerg     CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
13517330f729Sjoerg     return;
13527330f729Sjoerg   }
13537330f729Sjoerg 
1354*e038c9c4Sjoerg   llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
13557330f729Sjoerg 
13567330f729Sjoerg   // If store is legal, just bitcast the src pointer.
1357*e038c9c4Sjoerg   if (isa<llvm::ScalableVectorType>(SrcTy) ||
1358*e038c9c4Sjoerg       isa<llvm::ScalableVectorType>(DstTy) ||
1359*e038c9c4Sjoerg       SrcSize.getFixedSize() <= DstSize.getFixedSize()) {
13607330f729Sjoerg     Dst = CGF.Builder.CreateElementBitCast(Dst, SrcTy);
1361*e038c9c4Sjoerg     CGF.EmitAggregateStore(Src, Dst, DstIsVolatile);
13627330f729Sjoerg   } else {
13637330f729Sjoerg     // Otherwise do coercion through memory. This is stupid, but
13647330f729Sjoerg     // simple.
13657330f729Sjoerg 
13667330f729Sjoerg     // Generally SrcSize is never greater than DstSize, since this means we are
13677330f729Sjoerg     // losing bits. However, this can happen in cases where the structure has
13687330f729Sjoerg     // additional padding, for example due to a user specified alignment.
13697330f729Sjoerg     //
13707330f729Sjoerg     // FIXME: Assert that we aren't truncating non-padding bits when have access
13717330f729Sjoerg     // to that information.
13727330f729Sjoerg     Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
13737330f729Sjoerg     CGF.Builder.CreateStore(Src, Tmp);
1374*e038c9c4Sjoerg     CGF.Builder.CreateMemCpy(
1375*e038c9c4Sjoerg         Dst.getPointer(), Dst.getAlignment().getAsAlign(), Tmp.getPointer(),
1376*e038c9c4Sjoerg         Tmp.getAlignment().getAsAlign(),
1377*e038c9c4Sjoerg         llvm::ConstantInt::get(CGF.IntPtrTy, DstSize.getFixedSize()));
13787330f729Sjoerg   }
13797330f729Sjoerg }
13807330f729Sjoerg 
emitAddressAtOffset(CodeGenFunction & CGF,Address addr,const ABIArgInfo & info)13817330f729Sjoerg static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
13827330f729Sjoerg                                    const ABIArgInfo &info) {
13837330f729Sjoerg   if (unsigned offset = info.getDirectOffset()) {
13847330f729Sjoerg     addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
13857330f729Sjoerg     addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
13867330f729Sjoerg                                              CharUnits::fromQuantity(offset));
13877330f729Sjoerg     addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
13887330f729Sjoerg   }
13897330f729Sjoerg   return addr;
13907330f729Sjoerg }
13917330f729Sjoerg 
13927330f729Sjoerg namespace {
13937330f729Sjoerg 
13947330f729Sjoerg /// Encapsulates information about the way function arguments from
13957330f729Sjoerg /// CGFunctionInfo should be passed to actual LLVM IR function.
13967330f729Sjoerg class ClangToLLVMArgMapping {
13977330f729Sjoerg   static const unsigned InvalidIndex = ~0U;
13987330f729Sjoerg   unsigned InallocaArgNo;
13997330f729Sjoerg   unsigned SRetArgNo;
14007330f729Sjoerg   unsigned TotalIRArgs;
14017330f729Sjoerg 
14027330f729Sjoerg   /// Arguments of LLVM IR function corresponding to single Clang argument.
14037330f729Sjoerg   struct IRArgs {
14047330f729Sjoerg     unsigned PaddingArgIndex;
14057330f729Sjoerg     // Argument is expanded to IR arguments at positions
14067330f729Sjoerg     // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
14077330f729Sjoerg     unsigned FirstArgIndex;
14087330f729Sjoerg     unsigned NumberOfArgs;
14097330f729Sjoerg 
IRArgs__anon6af8234f0511::ClangToLLVMArgMapping::IRArgs14107330f729Sjoerg     IRArgs()
14117330f729Sjoerg         : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
14127330f729Sjoerg           NumberOfArgs(0) {}
14137330f729Sjoerg   };
14147330f729Sjoerg 
14157330f729Sjoerg   SmallVector<IRArgs, 8> ArgInfo;
14167330f729Sjoerg 
14177330f729Sjoerg public:
ClangToLLVMArgMapping(const ASTContext & Context,const CGFunctionInfo & FI,bool OnlyRequiredArgs=false)14187330f729Sjoerg   ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
14197330f729Sjoerg                         bool OnlyRequiredArgs = false)
14207330f729Sjoerg       : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
14217330f729Sjoerg         ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
14227330f729Sjoerg     construct(Context, FI, OnlyRequiredArgs);
14237330f729Sjoerg   }
14247330f729Sjoerg 
hasInallocaArg() const14257330f729Sjoerg   bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
getInallocaArgNo() const14267330f729Sjoerg   unsigned getInallocaArgNo() const {
14277330f729Sjoerg     assert(hasInallocaArg());
14287330f729Sjoerg     return InallocaArgNo;
14297330f729Sjoerg   }
14307330f729Sjoerg 
hasSRetArg() const14317330f729Sjoerg   bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
getSRetArgNo() const14327330f729Sjoerg   unsigned getSRetArgNo() const {
14337330f729Sjoerg     assert(hasSRetArg());
14347330f729Sjoerg     return SRetArgNo;
14357330f729Sjoerg   }
14367330f729Sjoerg 
totalIRArgs() const14377330f729Sjoerg   unsigned totalIRArgs() const { return TotalIRArgs; }
14387330f729Sjoerg 
hasPaddingArg(unsigned ArgNo) const14397330f729Sjoerg   bool hasPaddingArg(unsigned ArgNo) const {
14407330f729Sjoerg     assert(ArgNo < ArgInfo.size());
14417330f729Sjoerg     return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
14427330f729Sjoerg   }
getPaddingArgNo(unsigned ArgNo) const14437330f729Sjoerg   unsigned getPaddingArgNo(unsigned ArgNo) const {
14447330f729Sjoerg     assert(hasPaddingArg(ArgNo));
14457330f729Sjoerg     return ArgInfo[ArgNo].PaddingArgIndex;
14467330f729Sjoerg   }
14477330f729Sjoerg 
14487330f729Sjoerg   /// Returns index of first IR argument corresponding to ArgNo, and their
14497330f729Sjoerg   /// quantity.
getIRArgs(unsigned ArgNo) const14507330f729Sjoerg   std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
14517330f729Sjoerg     assert(ArgNo < ArgInfo.size());
14527330f729Sjoerg     return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
14537330f729Sjoerg                           ArgInfo[ArgNo].NumberOfArgs);
14547330f729Sjoerg   }
14557330f729Sjoerg 
14567330f729Sjoerg private:
14577330f729Sjoerg   void construct(const ASTContext &Context, const CGFunctionInfo &FI,
14587330f729Sjoerg                  bool OnlyRequiredArgs);
14597330f729Sjoerg };
14607330f729Sjoerg 
construct(const ASTContext & Context,const CGFunctionInfo & FI,bool OnlyRequiredArgs)14617330f729Sjoerg void ClangToLLVMArgMapping::construct(const ASTContext &Context,
14627330f729Sjoerg                                       const CGFunctionInfo &FI,
14637330f729Sjoerg                                       bool OnlyRequiredArgs) {
14647330f729Sjoerg   unsigned IRArgNo = 0;
14657330f729Sjoerg   bool SwapThisWithSRet = false;
14667330f729Sjoerg   const ABIArgInfo &RetAI = FI.getReturnInfo();
14677330f729Sjoerg 
14687330f729Sjoerg   if (RetAI.getKind() == ABIArgInfo::Indirect) {
14697330f729Sjoerg     SwapThisWithSRet = RetAI.isSRetAfterThis();
14707330f729Sjoerg     SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
14717330f729Sjoerg   }
14727330f729Sjoerg 
14737330f729Sjoerg   unsigned ArgNo = 0;
14747330f729Sjoerg   unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
14757330f729Sjoerg   for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
14767330f729Sjoerg        ++I, ++ArgNo) {
14777330f729Sjoerg     assert(I != FI.arg_end());
14787330f729Sjoerg     QualType ArgType = I->type;
14797330f729Sjoerg     const ABIArgInfo &AI = I->info;
14807330f729Sjoerg     // Collect data about IR arguments corresponding to Clang argument ArgNo.
14817330f729Sjoerg     auto &IRArgs = ArgInfo[ArgNo];
14827330f729Sjoerg 
14837330f729Sjoerg     if (AI.getPaddingType())
14847330f729Sjoerg       IRArgs.PaddingArgIndex = IRArgNo++;
14857330f729Sjoerg 
14867330f729Sjoerg     switch (AI.getKind()) {
14877330f729Sjoerg     case ABIArgInfo::Extend:
14887330f729Sjoerg     case ABIArgInfo::Direct: {
14897330f729Sjoerg       // FIXME: handle sseregparm someday...
14907330f729Sjoerg       llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
14917330f729Sjoerg       if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
14927330f729Sjoerg         IRArgs.NumberOfArgs = STy->getNumElements();
14937330f729Sjoerg       } else {
14947330f729Sjoerg         IRArgs.NumberOfArgs = 1;
14957330f729Sjoerg       }
14967330f729Sjoerg       break;
14977330f729Sjoerg     }
14987330f729Sjoerg     case ABIArgInfo::Indirect:
1499*e038c9c4Sjoerg     case ABIArgInfo::IndirectAliased:
15007330f729Sjoerg       IRArgs.NumberOfArgs = 1;
15017330f729Sjoerg       break;
15027330f729Sjoerg     case ABIArgInfo::Ignore:
15037330f729Sjoerg     case ABIArgInfo::InAlloca:
15047330f729Sjoerg       // ignore and inalloca doesn't have matching LLVM parameters.
15057330f729Sjoerg       IRArgs.NumberOfArgs = 0;
15067330f729Sjoerg       break;
15077330f729Sjoerg     case ABIArgInfo::CoerceAndExpand:
15087330f729Sjoerg       IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
15097330f729Sjoerg       break;
15107330f729Sjoerg     case ABIArgInfo::Expand:
15117330f729Sjoerg       IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
15127330f729Sjoerg       break;
15137330f729Sjoerg     }
15147330f729Sjoerg 
15157330f729Sjoerg     if (IRArgs.NumberOfArgs > 0) {
15167330f729Sjoerg       IRArgs.FirstArgIndex = IRArgNo;
15177330f729Sjoerg       IRArgNo += IRArgs.NumberOfArgs;
15187330f729Sjoerg     }
15197330f729Sjoerg 
15207330f729Sjoerg     // Skip over the sret parameter when it comes second.  We already handled it
15217330f729Sjoerg     // above.
15227330f729Sjoerg     if (IRArgNo == 1 && SwapThisWithSRet)
15237330f729Sjoerg       IRArgNo++;
15247330f729Sjoerg   }
15257330f729Sjoerg   assert(ArgNo == ArgInfo.size());
15267330f729Sjoerg 
15277330f729Sjoerg   if (FI.usesInAlloca())
15287330f729Sjoerg     InallocaArgNo = IRArgNo++;
15297330f729Sjoerg 
15307330f729Sjoerg   TotalIRArgs = IRArgNo;
15317330f729Sjoerg }
15327330f729Sjoerg }  // namespace
15337330f729Sjoerg 
15347330f729Sjoerg /***/
15357330f729Sjoerg 
ReturnTypeUsesSRet(const CGFunctionInfo & FI)15367330f729Sjoerg bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
15377330f729Sjoerg   const auto &RI = FI.getReturnInfo();
15387330f729Sjoerg   return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet());
15397330f729Sjoerg }
15407330f729Sjoerg 
ReturnSlotInterferesWithArgs(const CGFunctionInfo & FI)15417330f729Sjoerg bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
15427330f729Sjoerg   return ReturnTypeUsesSRet(FI) &&
15437330f729Sjoerg          getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
15447330f729Sjoerg }
15457330f729Sjoerg 
ReturnTypeUsesFPRet(QualType ResultType)15467330f729Sjoerg bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
15477330f729Sjoerg   if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
15487330f729Sjoerg     switch (BT->getKind()) {
15497330f729Sjoerg     default:
15507330f729Sjoerg       return false;
15517330f729Sjoerg     case BuiltinType::Float:
15527330f729Sjoerg       return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
15537330f729Sjoerg     case BuiltinType::Double:
15547330f729Sjoerg       return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
15557330f729Sjoerg     case BuiltinType::LongDouble:
15567330f729Sjoerg       return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
15577330f729Sjoerg     }
15587330f729Sjoerg   }
15597330f729Sjoerg 
15607330f729Sjoerg   return false;
15617330f729Sjoerg }
15627330f729Sjoerg 
ReturnTypeUsesFP2Ret(QualType ResultType)15637330f729Sjoerg bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
15647330f729Sjoerg   if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
15657330f729Sjoerg     if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
15667330f729Sjoerg       if (BT->getKind() == BuiltinType::LongDouble)
15677330f729Sjoerg         return getTarget().useObjCFP2RetForComplexLongDouble();
15687330f729Sjoerg     }
15697330f729Sjoerg   }
15707330f729Sjoerg 
15717330f729Sjoerg   return false;
15727330f729Sjoerg }
15737330f729Sjoerg 
GetFunctionType(GlobalDecl GD)15747330f729Sjoerg llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
15757330f729Sjoerg   const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
15767330f729Sjoerg   return GetFunctionType(FI);
15777330f729Sjoerg }
15787330f729Sjoerg 
15797330f729Sjoerg llvm::FunctionType *
GetFunctionType(const CGFunctionInfo & FI)15807330f729Sjoerg CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
15817330f729Sjoerg 
15827330f729Sjoerg   bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
15837330f729Sjoerg   (void)Inserted;
15847330f729Sjoerg   assert(Inserted && "Recursively being processed?");
15857330f729Sjoerg 
15867330f729Sjoerg   llvm::Type *resultType = nullptr;
15877330f729Sjoerg   const ABIArgInfo &retAI = FI.getReturnInfo();
15887330f729Sjoerg   switch (retAI.getKind()) {
15897330f729Sjoerg   case ABIArgInfo::Expand:
1590*e038c9c4Sjoerg   case ABIArgInfo::IndirectAliased:
15917330f729Sjoerg     llvm_unreachable("Invalid ABI kind for return argument");
15927330f729Sjoerg 
15937330f729Sjoerg   case ABIArgInfo::Extend:
15947330f729Sjoerg   case ABIArgInfo::Direct:
15957330f729Sjoerg     resultType = retAI.getCoerceToType();
15967330f729Sjoerg     break;
15977330f729Sjoerg 
15987330f729Sjoerg   case ABIArgInfo::InAlloca:
15997330f729Sjoerg     if (retAI.getInAllocaSRet()) {
16007330f729Sjoerg       // sret things on win32 aren't void, they return the sret pointer.
16017330f729Sjoerg       QualType ret = FI.getReturnType();
16027330f729Sjoerg       llvm::Type *ty = ConvertType(ret);
16037330f729Sjoerg       unsigned addressSpace = Context.getTargetAddressSpace(ret);
16047330f729Sjoerg       resultType = llvm::PointerType::get(ty, addressSpace);
16057330f729Sjoerg     } else {
16067330f729Sjoerg       resultType = llvm::Type::getVoidTy(getLLVMContext());
16077330f729Sjoerg     }
16087330f729Sjoerg     break;
16097330f729Sjoerg 
16107330f729Sjoerg   case ABIArgInfo::Indirect:
16117330f729Sjoerg   case ABIArgInfo::Ignore:
16127330f729Sjoerg     resultType = llvm::Type::getVoidTy(getLLVMContext());
16137330f729Sjoerg     break;
16147330f729Sjoerg 
16157330f729Sjoerg   case ABIArgInfo::CoerceAndExpand:
16167330f729Sjoerg     resultType = retAI.getUnpaddedCoerceAndExpandType();
16177330f729Sjoerg     break;
16187330f729Sjoerg   }
16197330f729Sjoerg 
16207330f729Sjoerg   ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
16217330f729Sjoerg   SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
16227330f729Sjoerg 
16237330f729Sjoerg   // Add type for sret argument.
16247330f729Sjoerg   if (IRFunctionArgs.hasSRetArg()) {
16257330f729Sjoerg     QualType Ret = FI.getReturnType();
16267330f729Sjoerg     llvm::Type *Ty = ConvertType(Ret);
16277330f729Sjoerg     unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
16287330f729Sjoerg     ArgTypes[IRFunctionArgs.getSRetArgNo()] =
16297330f729Sjoerg         llvm::PointerType::get(Ty, AddressSpace);
16307330f729Sjoerg   }
16317330f729Sjoerg 
16327330f729Sjoerg   // Add type for inalloca argument.
16337330f729Sjoerg   if (IRFunctionArgs.hasInallocaArg()) {
16347330f729Sjoerg     auto ArgStruct = FI.getArgStruct();
16357330f729Sjoerg     assert(ArgStruct);
16367330f729Sjoerg     ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
16377330f729Sjoerg   }
16387330f729Sjoerg 
16397330f729Sjoerg   // Add in all of the required arguments.
16407330f729Sjoerg   unsigned ArgNo = 0;
16417330f729Sjoerg   CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
16427330f729Sjoerg                                      ie = it + FI.getNumRequiredArgs();
16437330f729Sjoerg   for (; it != ie; ++it, ++ArgNo) {
16447330f729Sjoerg     const ABIArgInfo &ArgInfo = it->info;
16457330f729Sjoerg 
16467330f729Sjoerg     // Insert a padding type to ensure proper alignment.
16477330f729Sjoerg     if (IRFunctionArgs.hasPaddingArg(ArgNo))
16487330f729Sjoerg       ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
16497330f729Sjoerg           ArgInfo.getPaddingType();
16507330f729Sjoerg 
16517330f729Sjoerg     unsigned FirstIRArg, NumIRArgs;
16527330f729Sjoerg     std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
16537330f729Sjoerg 
16547330f729Sjoerg     switch (ArgInfo.getKind()) {
16557330f729Sjoerg     case ABIArgInfo::Ignore:
16567330f729Sjoerg     case ABIArgInfo::InAlloca:
16577330f729Sjoerg       assert(NumIRArgs == 0);
16587330f729Sjoerg       break;
16597330f729Sjoerg 
16607330f729Sjoerg     case ABIArgInfo::Indirect: {
16617330f729Sjoerg       assert(NumIRArgs == 1);
16627330f729Sjoerg       // indirect arguments are always on the stack, which is alloca addr space.
16637330f729Sjoerg       llvm::Type *LTy = ConvertTypeForMem(it->type);
16647330f729Sjoerg       ArgTypes[FirstIRArg] = LTy->getPointerTo(
16657330f729Sjoerg           CGM.getDataLayout().getAllocaAddrSpace());
16667330f729Sjoerg       break;
16677330f729Sjoerg     }
1668*e038c9c4Sjoerg     case ABIArgInfo::IndirectAliased: {
1669*e038c9c4Sjoerg       assert(NumIRArgs == 1);
1670*e038c9c4Sjoerg       llvm::Type *LTy = ConvertTypeForMem(it->type);
1671*e038c9c4Sjoerg       ArgTypes[FirstIRArg] = LTy->getPointerTo(ArgInfo.getIndirectAddrSpace());
1672*e038c9c4Sjoerg       break;
1673*e038c9c4Sjoerg     }
16747330f729Sjoerg     case ABIArgInfo::Extend:
16757330f729Sjoerg     case ABIArgInfo::Direct: {
16767330f729Sjoerg       // Fast-isel and the optimizer generally like scalar values better than
16777330f729Sjoerg       // FCAs, so we flatten them if this is safe to do for this argument.
16787330f729Sjoerg       llvm::Type *argType = ArgInfo.getCoerceToType();
16797330f729Sjoerg       llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
16807330f729Sjoerg       if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
16817330f729Sjoerg         assert(NumIRArgs == st->getNumElements());
16827330f729Sjoerg         for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
16837330f729Sjoerg           ArgTypes[FirstIRArg + i] = st->getElementType(i);
16847330f729Sjoerg       } else {
16857330f729Sjoerg         assert(NumIRArgs == 1);
16867330f729Sjoerg         ArgTypes[FirstIRArg] = argType;
16877330f729Sjoerg       }
16887330f729Sjoerg       break;
16897330f729Sjoerg     }
16907330f729Sjoerg 
16917330f729Sjoerg     case ABIArgInfo::CoerceAndExpand: {
16927330f729Sjoerg       auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
16937330f729Sjoerg       for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
16947330f729Sjoerg         *ArgTypesIter++ = EltTy;
16957330f729Sjoerg       }
16967330f729Sjoerg       assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
16977330f729Sjoerg       break;
16987330f729Sjoerg     }
16997330f729Sjoerg 
17007330f729Sjoerg     case ABIArgInfo::Expand:
17017330f729Sjoerg       auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
17027330f729Sjoerg       getExpandedTypes(it->type, ArgTypesIter);
17037330f729Sjoerg       assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
17047330f729Sjoerg       break;
17057330f729Sjoerg     }
17067330f729Sjoerg   }
17077330f729Sjoerg 
17087330f729Sjoerg   bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
17097330f729Sjoerg   assert(Erased && "Not in set?");
17107330f729Sjoerg 
17117330f729Sjoerg   return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
17127330f729Sjoerg }
17137330f729Sjoerg 
GetFunctionTypeForVTable(GlobalDecl GD)17147330f729Sjoerg llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
17157330f729Sjoerg   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
17167330f729Sjoerg   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
17177330f729Sjoerg 
17187330f729Sjoerg   if (!isFuncTypeConvertible(FPT))
17197330f729Sjoerg     return llvm::StructType::get(getLLVMContext());
17207330f729Sjoerg 
17217330f729Sjoerg   return GetFunctionType(GD);
17227330f729Sjoerg }
17237330f729Sjoerg 
AddAttributesFromFunctionProtoType(ASTContext & Ctx,llvm::AttrBuilder & FuncAttrs,const FunctionProtoType * FPT)17247330f729Sjoerg static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
17257330f729Sjoerg                                                llvm::AttrBuilder &FuncAttrs,
17267330f729Sjoerg                                                const FunctionProtoType *FPT) {
17277330f729Sjoerg   if (!FPT)
17287330f729Sjoerg     return;
17297330f729Sjoerg 
17307330f729Sjoerg   if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
17317330f729Sjoerg       FPT->isNothrow())
17327330f729Sjoerg     FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
17337330f729Sjoerg }
17347330f729Sjoerg 
MayDropFunctionReturn(const ASTContext & Context,QualType ReturnType)1735*e038c9c4Sjoerg bool CodeGenModule::MayDropFunctionReturn(const ASTContext &Context,
1736*e038c9c4Sjoerg                                           QualType ReturnType) {
1737*e038c9c4Sjoerg   // We can't just discard the return value for a record type with a
1738*e038c9c4Sjoerg   // complex destructor or a non-trivially copyable type.
1739*e038c9c4Sjoerg   if (const RecordType *RT =
1740*e038c9c4Sjoerg           ReturnType.getCanonicalType()->getAs<RecordType>()) {
1741*e038c9c4Sjoerg     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1742*e038c9c4Sjoerg       return ClassDecl->hasTrivialDestructor();
1743*e038c9c4Sjoerg   }
1744*e038c9c4Sjoerg   return ReturnType.isTriviallyCopyableType(Context);
1745*e038c9c4Sjoerg }
1746*e038c9c4Sjoerg 
getDefaultFunctionAttributes(StringRef Name,bool HasOptnone,bool AttrOnCallSite,llvm::AttrBuilder & FuncAttrs)1747*e038c9c4Sjoerg void CodeGenModule::getDefaultFunctionAttributes(StringRef Name,
1748*e038c9c4Sjoerg                                                  bool HasOptnone,
17497330f729Sjoerg                                                  bool AttrOnCallSite,
17507330f729Sjoerg                                                llvm::AttrBuilder &FuncAttrs) {
17517330f729Sjoerg   // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
17527330f729Sjoerg   if (!HasOptnone) {
17537330f729Sjoerg     if (CodeGenOpts.OptimizeSize)
17547330f729Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
17557330f729Sjoerg     if (CodeGenOpts.OptimizeSize == 2)
17567330f729Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::MinSize);
17577330f729Sjoerg   }
17587330f729Sjoerg 
17597330f729Sjoerg   if (CodeGenOpts.DisableRedZone)
17607330f729Sjoerg     FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
17617330f729Sjoerg   if (CodeGenOpts.IndirectTlsSegRefs)
17627330f729Sjoerg     FuncAttrs.addAttribute("indirect-tls-seg-refs");
17637330f729Sjoerg   if (CodeGenOpts.NoImplicitFloat)
17647330f729Sjoerg     FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
17657330f729Sjoerg 
17667330f729Sjoerg   if (AttrOnCallSite) {
17677330f729Sjoerg     // Attributes that should go on the call site only.
1768*e038c9c4Sjoerg     if (!CodeGenOpts.SimplifyLibCalls || LangOpts.isNoBuiltinFunc(Name))
17697330f729Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
17707330f729Sjoerg     if (!CodeGenOpts.TrapFuncName.empty())
17717330f729Sjoerg       FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
17727330f729Sjoerg   } else {
17737330f729Sjoerg     StringRef FpKind;
17747330f729Sjoerg     switch (CodeGenOpts.getFramePointer()) {
17757330f729Sjoerg     case CodeGenOptions::FramePointerKind::None:
17767330f729Sjoerg       FpKind = "none";
17777330f729Sjoerg       break;
17787330f729Sjoerg     case CodeGenOptions::FramePointerKind::NonLeaf:
17797330f729Sjoerg       FpKind = "non-leaf";
17807330f729Sjoerg       break;
17817330f729Sjoerg     case CodeGenOptions::FramePointerKind::All:
17827330f729Sjoerg       FpKind = "all";
17837330f729Sjoerg       break;
17847330f729Sjoerg     }
17857330f729Sjoerg     FuncAttrs.addAttribute("frame-pointer", FpKind);
17867330f729Sjoerg 
1787*e038c9c4Sjoerg     if (CodeGenOpts.LessPreciseFPMAD)
1788*e038c9c4Sjoerg       FuncAttrs.addAttribute("less-precise-fpmad", "true");
17897330f729Sjoerg 
17907330f729Sjoerg     if (CodeGenOpts.NullPointerIsValid)
1791*e038c9c4Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::NullPointerIsValid);
17927330f729Sjoerg 
1793*e038c9c4Sjoerg     if (CodeGenOpts.FPDenormalMode != llvm::DenormalMode::getIEEE())
1794*e038c9c4Sjoerg       FuncAttrs.addAttribute("denormal-fp-math",
1795*e038c9c4Sjoerg                              CodeGenOpts.FPDenormalMode.str());
1796*e038c9c4Sjoerg     if (CodeGenOpts.FP32DenormalMode != CodeGenOpts.FPDenormalMode) {
1797*e038c9c4Sjoerg       FuncAttrs.addAttribute(
1798*e038c9c4Sjoerg           "denormal-fp-math-f32",
1799*e038c9c4Sjoerg           CodeGenOpts.FP32DenormalMode.str());
1800*e038c9c4Sjoerg     }
1801*e038c9c4Sjoerg 
1802*e038c9c4Sjoerg     if (LangOpts.getFPExceptionMode() == LangOptions::FPE_Ignore)
1803*e038c9c4Sjoerg       FuncAttrs.addAttribute("no-trapping-math", "true");
18047330f729Sjoerg 
18057330f729Sjoerg     // Strict (compliant) code is the default, so only add this attribute to
18067330f729Sjoerg     // indicate that we are trying to workaround a problem case.
18077330f729Sjoerg     if (!CodeGenOpts.StrictFloatCastOverflow)
18087330f729Sjoerg       FuncAttrs.addAttribute("strict-float-cast-overflow", "false");
18097330f729Sjoerg 
18107330f729Sjoerg     // TODO: Are these all needed?
18117330f729Sjoerg     // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
1812*e038c9c4Sjoerg     if (LangOpts.NoHonorInfs)
1813*e038c9c4Sjoerg       FuncAttrs.addAttribute("no-infs-fp-math", "true");
1814*e038c9c4Sjoerg     if (LangOpts.NoHonorNaNs)
1815*e038c9c4Sjoerg       FuncAttrs.addAttribute("no-nans-fp-math", "true");
1816*e038c9c4Sjoerg     if (LangOpts.UnsafeFPMath)
1817*e038c9c4Sjoerg       FuncAttrs.addAttribute("unsafe-fp-math", "true");
1818*e038c9c4Sjoerg     if (CodeGenOpts.SoftFloat)
1819*e038c9c4Sjoerg       FuncAttrs.addAttribute("use-soft-float", "true");
18207330f729Sjoerg     FuncAttrs.addAttribute("stack-protector-buffer-size",
18217330f729Sjoerg                            llvm::utostr(CodeGenOpts.SSPBufferSize));
1822*e038c9c4Sjoerg     if (LangOpts.NoSignedZero)
1823*e038c9c4Sjoerg       FuncAttrs.addAttribute("no-signed-zeros-fp-math", "true");
18247330f729Sjoerg 
18257330f729Sjoerg     // TODO: Reciprocal estimate codegen options should apply to instructions?
18267330f729Sjoerg     const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals;
18277330f729Sjoerg     if (!Recips.empty())
18287330f729Sjoerg       FuncAttrs.addAttribute("reciprocal-estimates",
18297330f729Sjoerg                              llvm::join(Recips, ","));
18307330f729Sjoerg 
18317330f729Sjoerg     if (!CodeGenOpts.PreferVectorWidth.empty() &&
18327330f729Sjoerg         CodeGenOpts.PreferVectorWidth != "none")
18337330f729Sjoerg       FuncAttrs.addAttribute("prefer-vector-width",
18347330f729Sjoerg                              CodeGenOpts.PreferVectorWidth);
18357330f729Sjoerg 
18367330f729Sjoerg     if (CodeGenOpts.StackRealignment)
18377330f729Sjoerg       FuncAttrs.addAttribute("stackrealign");
18387330f729Sjoerg     if (CodeGenOpts.Backchain)
18397330f729Sjoerg       FuncAttrs.addAttribute("backchain");
1840*e038c9c4Sjoerg     if (CodeGenOpts.EnableSegmentedStacks)
1841*e038c9c4Sjoerg       FuncAttrs.addAttribute("split-stack");
18427330f729Sjoerg 
18437330f729Sjoerg     if (CodeGenOpts.SpeculativeLoadHardening)
18447330f729Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
18457330f729Sjoerg   }
18467330f729Sjoerg 
18477330f729Sjoerg   if (getLangOpts().assumeFunctionsAreConvergent()) {
18487330f729Sjoerg     // Conservatively, mark all functions and calls in CUDA and OpenCL as
18497330f729Sjoerg     // convergent (meaning, they may call an intrinsically convergent op, such
18507330f729Sjoerg     // as __syncthreads() / barrier(), and so can't have certain optimizations
18517330f729Sjoerg     // applied around them).  LLVM will remove this attribute where it safely
18527330f729Sjoerg     // can.
18537330f729Sjoerg     FuncAttrs.addAttribute(llvm::Attribute::Convergent);
18547330f729Sjoerg   }
18557330f729Sjoerg 
18567330f729Sjoerg   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
18577330f729Sjoerg     // Exceptions aren't supported in CUDA device code.
18587330f729Sjoerg     FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
18597330f729Sjoerg   }
18607330f729Sjoerg 
18617330f729Sjoerg   for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) {
18627330f729Sjoerg     StringRef Var, Value;
18637330f729Sjoerg     std::tie(Var, Value) = Attr.split('=');
18647330f729Sjoerg     FuncAttrs.addAttribute(Var, Value);
18657330f729Sjoerg   }
18667330f729Sjoerg }
18677330f729Sjoerg 
addDefaultFunctionDefinitionAttributes(llvm::Function & F)1868*e038c9c4Sjoerg void CodeGenModule::addDefaultFunctionDefinitionAttributes(llvm::Function &F) {
18697330f729Sjoerg   llvm::AttrBuilder FuncAttrs;
1870*e038c9c4Sjoerg   getDefaultFunctionAttributes(F.getName(), F.hasOptNone(),
18717330f729Sjoerg                                /* AttrOnCallSite = */ false, FuncAttrs);
1872*e038c9c4Sjoerg   // TODO: call GetCPUAndFeaturesAttributes?
18737330f729Sjoerg   F.addAttributes(llvm::AttributeList::FunctionIndex, FuncAttrs);
18747330f729Sjoerg }
18757330f729Sjoerg 
addDefaultFunctionDefinitionAttributes(llvm::AttrBuilder & attrs)1876*e038c9c4Sjoerg void CodeGenModule::addDefaultFunctionDefinitionAttributes(
1877*e038c9c4Sjoerg                                                    llvm::AttrBuilder &attrs) {
1878*e038c9c4Sjoerg   getDefaultFunctionAttributes(/*function name*/ "", /*optnone*/ false,
1879*e038c9c4Sjoerg                                /*for call*/ false, attrs);
1880*e038c9c4Sjoerg   GetCPUAndFeaturesAttributes(GlobalDecl(), attrs);
1881*e038c9c4Sjoerg }
1882*e038c9c4Sjoerg 
addNoBuiltinAttributes(llvm::AttrBuilder & FuncAttrs,const LangOptions & LangOpts,const NoBuiltinAttr * NBA=nullptr)1883*e038c9c4Sjoerg static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs,
1884*e038c9c4Sjoerg                                    const LangOptions &LangOpts,
1885*e038c9c4Sjoerg                                    const NoBuiltinAttr *NBA = nullptr) {
1886*e038c9c4Sjoerg   auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) {
1887*e038c9c4Sjoerg     SmallString<32> AttributeName;
1888*e038c9c4Sjoerg     AttributeName += "no-builtin-";
1889*e038c9c4Sjoerg     AttributeName += BuiltinName;
1890*e038c9c4Sjoerg     FuncAttrs.addAttribute(AttributeName);
1891*e038c9c4Sjoerg   };
1892*e038c9c4Sjoerg 
1893*e038c9c4Sjoerg   // First, handle the language options passed through -fno-builtin.
1894*e038c9c4Sjoerg   if (LangOpts.NoBuiltin) {
1895*e038c9c4Sjoerg     // -fno-builtin disables them all.
1896*e038c9c4Sjoerg     FuncAttrs.addAttribute("no-builtins");
1897*e038c9c4Sjoerg     return;
1898*e038c9c4Sjoerg   }
1899*e038c9c4Sjoerg 
1900*e038c9c4Sjoerg   // Then, add attributes for builtins specified through -fno-builtin-<name>.
1901*e038c9c4Sjoerg   llvm::for_each(LangOpts.NoBuiltinFuncs, AddNoBuiltinAttr);
1902*e038c9c4Sjoerg 
1903*e038c9c4Sjoerg   // Now, let's check the __attribute__((no_builtin("...")) attribute added to
1904*e038c9c4Sjoerg   // the source.
1905*e038c9c4Sjoerg   if (!NBA)
1906*e038c9c4Sjoerg     return;
1907*e038c9c4Sjoerg 
1908*e038c9c4Sjoerg   // If there is a wildcard in the builtin names specified through the
1909*e038c9c4Sjoerg   // attribute, disable them all.
1910*e038c9c4Sjoerg   if (llvm::is_contained(NBA->builtinNames(), "*")) {
1911*e038c9c4Sjoerg     FuncAttrs.addAttribute("no-builtins");
1912*e038c9c4Sjoerg     return;
1913*e038c9c4Sjoerg   }
1914*e038c9c4Sjoerg 
1915*e038c9c4Sjoerg   // And last, add the rest of the builtin names.
1916*e038c9c4Sjoerg   llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr);
1917*e038c9c4Sjoerg }
1918*e038c9c4Sjoerg 
DetermineNoUndef(QualType QTy,CodeGenTypes & Types,const llvm::DataLayout & DL,const ABIArgInfo & AI,bool CheckCoerce=true)1919*e038c9c4Sjoerg static bool DetermineNoUndef(QualType QTy, CodeGenTypes &Types,
1920*e038c9c4Sjoerg                              const llvm::DataLayout &DL, const ABIArgInfo &AI,
1921*e038c9c4Sjoerg                              bool CheckCoerce = true) {
1922*e038c9c4Sjoerg   llvm::Type *Ty = Types.ConvertTypeForMem(QTy);
1923*e038c9c4Sjoerg   if (AI.getKind() == ABIArgInfo::Indirect)
1924*e038c9c4Sjoerg     return true;
1925*e038c9c4Sjoerg   if (AI.getKind() == ABIArgInfo::Extend)
1926*e038c9c4Sjoerg     return true;
1927*e038c9c4Sjoerg   if (!DL.typeSizeEqualsStoreSize(Ty))
1928*e038c9c4Sjoerg     // TODO: This will result in a modest amount of values not marked noundef
1929*e038c9c4Sjoerg     // when they could be. We care about values that *invisibly* contain undef
1930*e038c9c4Sjoerg     // bits from the perspective of LLVM IR.
1931*e038c9c4Sjoerg     return false;
1932*e038c9c4Sjoerg   if (CheckCoerce && AI.canHaveCoerceToType()) {
1933*e038c9c4Sjoerg     llvm::Type *CoerceTy = AI.getCoerceToType();
1934*e038c9c4Sjoerg     if (llvm::TypeSize::isKnownGT(DL.getTypeSizeInBits(CoerceTy),
1935*e038c9c4Sjoerg                                   DL.getTypeSizeInBits(Ty)))
1936*e038c9c4Sjoerg       // If we're coercing to a type with a greater size than the canonical one,
1937*e038c9c4Sjoerg       // we're introducing new undef bits.
1938*e038c9c4Sjoerg       // Coercing to a type of smaller or equal size is ok, as we know that
1939*e038c9c4Sjoerg       // there's no internal padding (typeSizeEqualsStoreSize).
1940*e038c9c4Sjoerg       return false;
1941*e038c9c4Sjoerg   }
1942*e038c9c4Sjoerg   if (QTy->isExtIntType())
1943*e038c9c4Sjoerg     return true;
1944*e038c9c4Sjoerg   if (QTy->isReferenceType())
1945*e038c9c4Sjoerg     return true;
1946*e038c9c4Sjoerg   if (QTy->isNullPtrType())
1947*e038c9c4Sjoerg     return false;
1948*e038c9c4Sjoerg   if (QTy->isMemberPointerType())
1949*e038c9c4Sjoerg     // TODO: Some member pointers are `noundef`, but it depends on the ABI. For
1950*e038c9c4Sjoerg     // now, never mark them.
1951*e038c9c4Sjoerg     return false;
1952*e038c9c4Sjoerg   if (QTy->isScalarType()) {
1953*e038c9c4Sjoerg     if (const ComplexType *Complex = dyn_cast<ComplexType>(QTy))
1954*e038c9c4Sjoerg       return DetermineNoUndef(Complex->getElementType(), Types, DL, AI, false);
1955*e038c9c4Sjoerg     return true;
1956*e038c9c4Sjoerg   }
1957*e038c9c4Sjoerg   if (const VectorType *Vector = dyn_cast<VectorType>(QTy))
1958*e038c9c4Sjoerg     return DetermineNoUndef(Vector->getElementType(), Types, DL, AI, false);
1959*e038c9c4Sjoerg   if (const MatrixType *Matrix = dyn_cast<MatrixType>(QTy))
1960*e038c9c4Sjoerg     return DetermineNoUndef(Matrix->getElementType(), Types, DL, AI, false);
1961*e038c9c4Sjoerg   if (const ArrayType *Array = dyn_cast<ArrayType>(QTy))
1962*e038c9c4Sjoerg     return DetermineNoUndef(Array->getElementType(), Types, DL, AI, false);
1963*e038c9c4Sjoerg 
1964*e038c9c4Sjoerg   // TODO: Some structs may be `noundef`, in specific situations.
1965*e038c9c4Sjoerg   return false;
1966*e038c9c4Sjoerg }
1967*e038c9c4Sjoerg 
1968*e038c9c4Sjoerg /// Construct the IR attribute list of a function or call.
1969*e038c9c4Sjoerg ///
1970*e038c9c4Sjoerg /// When adding an attribute, please consider where it should be handled:
1971*e038c9c4Sjoerg ///
1972*e038c9c4Sjoerg ///   - getDefaultFunctionAttributes is for attributes that are essentially
1973*e038c9c4Sjoerg ///     part of the global target configuration (but perhaps can be
1974*e038c9c4Sjoerg ///     overridden on a per-function basis).  Adding attributes there
1975*e038c9c4Sjoerg ///     will cause them to also be set in frontends that build on Clang's
1976*e038c9c4Sjoerg ///     target-configuration logic, as well as for code defined in library
1977*e038c9c4Sjoerg ///     modules such as CUDA's libdevice.
1978*e038c9c4Sjoerg ///
1979*e038c9c4Sjoerg ///   - ConstructAttributeList builds on top of getDefaultFunctionAttributes
1980*e038c9c4Sjoerg ///     and adds declaration-specific, convention-specific, and
1981*e038c9c4Sjoerg ///     frontend-specific logic.  The last is of particular importance:
1982*e038c9c4Sjoerg ///     attributes that restrict how the frontend generates code must be
1983*e038c9c4Sjoerg ///     added here rather than getDefaultFunctionAttributes.
1984*e038c9c4Sjoerg ///
ConstructAttributeList(StringRef Name,const CGFunctionInfo & FI,CGCalleeInfo CalleeInfo,llvm::AttributeList & AttrList,unsigned & CallingConv,bool AttrOnCallSite,bool IsThunk)1985*e038c9c4Sjoerg void CodeGenModule::ConstructAttributeList(StringRef Name,
1986*e038c9c4Sjoerg                                            const CGFunctionInfo &FI,
1987*e038c9c4Sjoerg                                            CGCalleeInfo CalleeInfo,
1988*e038c9c4Sjoerg                                            llvm::AttributeList &AttrList,
1989*e038c9c4Sjoerg                                            unsigned &CallingConv,
1990*e038c9c4Sjoerg                                            bool AttrOnCallSite, bool IsThunk) {
19917330f729Sjoerg   llvm::AttrBuilder FuncAttrs;
19927330f729Sjoerg   llvm::AttrBuilder RetAttrs;
19937330f729Sjoerg 
1994*e038c9c4Sjoerg   // Collect function IR attributes from the CC lowering.
1995*e038c9c4Sjoerg   // We'll collect the paramete and result attributes later.
19967330f729Sjoerg   CallingConv = FI.getEffectiveCallingConvention();
19977330f729Sjoerg   if (FI.isNoReturn())
19987330f729Sjoerg     FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1999*e038c9c4Sjoerg   if (FI.isCmseNSCall())
2000*e038c9c4Sjoerg     FuncAttrs.addAttribute("cmse_nonsecure_call");
20017330f729Sjoerg 
2002*e038c9c4Sjoerg   // Collect function IR attributes from the callee prototype if we have one.
20037330f729Sjoerg   AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
20047330f729Sjoerg                                      CalleeInfo.getCalleeFunctionProtoType());
20057330f729Sjoerg 
20067330f729Sjoerg   const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl();
20077330f729Sjoerg 
20087330f729Sjoerg   bool HasOptnone = false;
2009*e038c9c4Sjoerg   // The NoBuiltinAttr attached to the target FunctionDecl.
2010*e038c9c4Sjoerg   const NoBuiltinAttr *NBA = nullptr;
2011*e038c9c4Sjoerg 
2012*e038c9c4Sjoerg   // Collect function IR attributes based on declaration-specific
2013*e038c9c4Sjoerg   // information.
20147330f729Sjoerg   // FIXME: handle sseregparm someday...
20157330f729Sjoerg   if (TargetDecl) {
20167330f729Sjoerg     if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
20177330f729Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
20187330f729Sjoerg     if (TargetDecl->hasAttr<NoThrowAttr>())
20197330f729Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
20207330f729Sjoerg     if (TargetDecl->hasAttr<NoReturnAttr>())
20217330f729Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
20227330f729Sjoerg     if (TargetDecl->hasAttr<ColdAttr>())
20237330f729Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::Cold);
2024*e038c9c4Sjoerg     if (TargetDecl->hasAttr<HotAttr>())
2025*e038c9c4Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::Hot);
20267330f729Sjoerg     if (TargetDecl->hasAttr<NoDuplicateAttr>())
20277330f729Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
20287330f729Sjoerg     if (TargetDecl->hasAttr<ConvergentAttr>())
20297330f729Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::Convergent);
20307330f729Sjoerg 
20317330f729Sjoerg     if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
20327330f729Sjoerg       AddAttributesFromFunctionProtoType(
20337330f729Sjoerg           getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
2034*e038c9c4Sjoerg       if (AttrOnCallSite && Fn->isReplaceableGlobalAllocationFunction()) {
2035*e038c9c4Sjoerg         // A sane operator new returns a non-aliasing pointer.
2036*e038c9c4Sjoerg         auto Kind = Fn->getDeclName().getCXXOverloadedOperator();
2037*e038c9c4Sjoerg         if (getCodeGenOpts().AssumeSaneOperatorNew &&
2038*e038c9c4Sjoerg             (Kind == OO_New || Kind == OO_Array_New))
2039*e038c9c4Sjoerg           RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2040*e038c9c4Sjoerg       }
20417330f729Sjoerg       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
2042*e038c9c4Sjoerg       const bool IsVirtualCall = MD && MD->isVirtual();
2043*e038c9c4Sjoerg       // Don't use [[noreturn]], _Noreturn or [[no_builtin]] for a call to a
2044*e038c9c4Sjoerg       // virtual function. These attributes are not inherited by overloads.
2045*e038c9c4Sjoerg       if (!(AttrOnCallSite && IsVirtualCall)) {
2046*e038c9c4Sjoerg         if (Fn->isNoReturn())
20477330f729Sjoerg           FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2048*e038c9c4Sjoerg         NBA = Fn->getAttr<NoBuiltinAttr>();
2049*e038c9c4Sjoerg       }
2050*e038c9c4Sjoerg       // Only place nomerge attribute on call sites, never functions. This
2051*e038c9c4Sjoerg       // allows it to work on indirect virtual function calls.
2052*e038c9c4Sjoerg       if (AttrOnCallSite && TargetDecl->hasAttr<NoMergeAttr>())
2053*e038c9c4Sjoerg         FuncAttrs.addAttribute(llvm::Attribute::NoMerge);
2054*e038c9c4Sjoerg 
2055*e038c9c4Sjoerg       // Add known guaranteed alignment for allocation functions.
2056*e038c9c4Sjoerg       if (unsigned BuiltinID = Fn->getBuiltinID()) {
2057*e038c9c4Sjoerg         switch (BuiltinID) {
2058*e038c9c4Sjoerg         case Builtin::BIaligned_alloc:
2059*e038c9c4Sjoerg         case Builtin::BIcalloc:
2060*e038c9c4Sjoerg         case Builtin::BImalloc:
2061*e038c9c4Sjoerg         case Builtin::BImemalign:
2062*e038c9c4Sjoerg         case Builtin::BIrealloc:
2063*e038c9c4Sjoerg         case Builtin::BIstrdup:
2064*e038c9c4Sjoerg         case Builtin::BIstrndup:
2065*e038c9c4Sjoerg           RetAttrs.addAlignmentAttr(Context.getTargetInfo().getNewAlign() /
2066*e038c9c4Sjoerg                                     Context.getTargetInfo().getCharWidth());
2067*e038c9c4Sjoerg           break;
2068*e038c9c4Sjoerg         default:
2069*e038c9c4Sjoerg           break;
2070*e038c9c4Sjoerg         }
2071*e038c9c4Sjoerg       }
20727330f729Sjoerg     }
20737330f729Sjoerg 
20747330f729Sjoerg     // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
20757330f729Sjoerg     if (TargetDecl->hasAttr<ConstAttr>()) {
20767330f729Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
20777330f729Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2078*e038c9c4Sjoerg       // gcc specifies that 'const' functions have greater restrictions than
2079*e038c9c4Sjoerg       // 'pure' functions, so they also cannot have infinite loops.
2080*e038c9c4Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
20817330f729Sjoerg     } else if (TargetDecl->hasAttr<PureAttr>()) {
20827330f729Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
20837330f729Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2084*e038c9c4Sjoerg       // gcc specifies that 'pure' functions cannot have infinite loops.
2085*e038c9c4Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
20867330f729Sjoerg     } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
20877330f729Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
20887330f729Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
20897330f729Sjoerg     }
20907330f729Sjoerg     if (TargetDecl->hasAttr<RestrictAttr>())
20917330f729Sjoerg       RetAttrs.addAttribute(llvm::Attribute::NoAlias);
20927330f729Sjoerg     if (TargetDecl->hasAttr<ReturnsNonNullAttr>() &&
20937330f729Sjoerg         !CodeGenOpts.NullPointerIsValid)
20947330f729Sjoerg       RetAttrs.addAttribute(llvm::Attribute::NonNull);
20957330f729Sjoerg     if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
20967330f729Sjoerg       FuncAttrs.addAttribute("no_caller_saved_registers");
20977330f729Sjoerg     if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>())
20987330f729Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck);
2099*e038c9c4Sjoerg     if (TargetDecl->hasAttr<LeafAttr>())
2100*e038c9c4Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::NoCallback);
21017330f729Sjoerg 
21027330f729Sjoerg     HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
21037330f729Sjoerg     if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
21047330f729Sjoerg       Optional<unsigned> NumElemsParam;
21057330f729Sjoerg       if (AllocSize->getNumElemsParam().isValid())
21067330f729Sjoerg         NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
21077330f729Sjoerg       FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(),
21087330f729Sjoerg                                  NumElemsParam);
21097330f729Sjoerg     }
21107330f729Sjoerg 
2111*e038c9c4Sjoerg     if (TargetDecl->hasAttr<OpenCLKernelAttr>()) {
21127330f729Sjoerg       if (getLangOpts().OpenCLVersion <= 120) {
21137330f729Sjoerg         // OpenCL v1.2 Work groups are always uniform
21147330f729Sjoerg         FuncAttrs.addAttribute("uniform-work-group-size", "true");
21157330f729Sjoerg       } else {
21167330f729Sjoerg         // OpenCL v2.0 Work groups may be whether uniform or not.
21177330f729Sjoerg         // '-cl-uniform-work-group-size' compile option gets a hint
21187330f729Sjoerg         // to the compiler that the global work-size be a multiple of
21197330f729Sjoerg         // the work-group size specified to clEnqueueNDRangeKernel
21207330f729Sjoerg         // (i.e. work groups are uniform).
21217330f729Sjoerg         FuncAttrs.addAttribute("uniform-work-group-size",
21227330f729Sjoerg                                llvm::toStringRef(CodeGenOpts.UniformWGSize));
21237330f729Sjoerg       }
21247330f729Sjoerg     }
21257330f729Sjoerg 
2126*e038c9c4Sjoerg     std::string AssumptionValueStr;
2127*e038c9c4Sjoerg     for (AssumptionAttr *AssumptionA :
2128*e038c9c4Sjoerg          TargetDecl->specific_attrs<AssumptionAttr>()) {
2129*e038c9c4Sjoerg       std::string AS = AssumptionA->getAssumption().str();
2130*e038c9c4Sjoerg       if (!AS.empty() && !AssumptionValueStr.empty())
2131*e038c9c4Sjoerg         AssumptionValueStr += ",";
2132*e038c9c4Sjoerg       AssumptionValueStr += AS;
2133*e038c9c4Sjoerg     }
21347330f729Sjoerg 
2135*e038c9c4Sjoerg     if (!AssumptionValueStr.empty())
2136*e038c9c4Sjoerg       FuncAttrs.addAttribute(llvm::AssumptionAttrKey, AssumptionValueStr);
2137*e038c9c4Sjoerg   }
2138*e038c9c4Sjoerg 
2139*e038c9c4Sjoerg   // Attach "no-builtins" attributes to:
2140*e038c9c4Sjoerg   // * call sites: both `nobuiltin` and "no-builtins" or "no-builtin-<name>".
2141*e038c9c4Sjoerg   // * definitions: "no-builtins" or "no-builtin-<name>" only.
2142*e038c9c4Sjoerg   // The attributes can come from:
2143*e038c9c4Sjoerg   // * LangOpts: -ffreestanding, -fno-builtin, -fno-builtin-<name>
2144*e038c9c4Sjoerg   // * FunctionDecl attributes: __attribute__((no_builtin(...)))
2145*e038c9c4Sjoerg   addNoBuiltinAttributes(FuncAttrs, getLangOpts(), NBA);
2146*e038c9c4Sjoerg 
2147*e038c9c4Sjoerg   // Collect function IR attributes based on global settiings.
2148*e038c9c4Sjoerg   getDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
2149*e038c9c4Sjoerg 
2150*e038c9c4Sjoerg   // Override some default IR attributes based on declaration-specific
2151*e038c9c4Sjoerg   // information.
2152*e038c9c4Sjoerg   if (TargetDecl) {
2153*e038c9c4Sjoerg     if (TargetDecl->hasAttr<NoSpeculativeLoadHardeningAttr>())
2154*e038c9c4Sjoerg       FuncAttrs.removeAttribute(llvm::Attribute::SpeculativeLoadHardening);
2155*e038c9c4Sjoerg     if (TargetDecl->hasAttr<SpeculativeLoadHardeningAttr>())
2156*e038c9c4Sjoerg       FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
2157*e038c9c4Sjoerg     if (TargetDecl->hasAttr<NoSplitStackAttr>())
2158*e038c9c4Sjoerg       FuncAttrs.removeAttribute("split-stack");
2159*e038c9c4Sjoerg 
2160*e038c9c4Sjoerg     // Add NonLazyBind attribute to function declarations when -fno-plt
2161*e038c9c4Sjoerg     // is used.
2162*e038c9c4Sjoerg     // FIXME: what if we just haven't processed the function definition
2163*e038c9c4Sjoerg     // yet, or if it's an external definition like C99 inline?
2164*e038c9c4Sjoerg     if (CodeGenOpts.NoPLT) {
2165*e038c9c4Sjoerg       if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2166*e038c9c4Sjoerg         if (!Fn->isDefined() && !AttrOnCallSite) {
2167*e038c9c4Sjoerg           FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind);
2168*e038c9c4Sjoerg         }
2169*e038c9c4Sjoerg       }
2170*e038c9c4Sjoerg     }
2171*e038c9c4Sjoerg   }
2172*e038c9c4Sjoerg 
2173*e038c9c4Sjoerg   // Add "sample-profile-suffix-elision-policy" attribute for internal linkage
2174*e038c9c4Sjoerg   // functions with -funique-internal-linkage-names.
2175*e038c9c4Sjoerg   if (TargetDecl && CodeGenOpts.UniqueInternalLinkageNames) {
2176*e038c9c4Sjoerg     if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2177*e038c9c4Sjoerg       if (this->getFunctionLinkage(Fn) == llvm::GlobalValue::InternalLinkage)
2178*e038c9c4Sjoerg         FuncAttrs.addAttribute("sample-profile-suffix-elision-policy",
2179*e038c9c4Sjoerg                                "selected");
2180*e038c9c4Sjoerg     }
2181*e038c9c4Sjoerg   }
2182*e038c9c4Sjoerg 
2183*e038c9c4Sjoerg   // Collect non-call-site function IR attributes from declaration-specific
2184*e038c9c4Sjoerg   // information.
2185*e038c9c4Sjoerg   if (!AttrOnCallSite) {
2186*e038c9c4Sjoerg     if (TargetDecl && TargetDecl->hasAttr<CmseNSEntryAttr>())
2187*e038c9c4Sjoerg       FuncAttrs.addAttribute("cmse_nonsecure_entry");
2188*e038c9c4Sjoerg 
2189*e038c9c4Sjoerg     // Whether tail calls are enabled.
2190*e038c9c4Sjoerg     auto shouldDisableTailCalls = [&] {
2191*e038c9c4Sjoerg       // Should this be honored in getDefaultFunctionAttributes?
21927330f729Sjoerg       if (CodeGenOpts.DisableTailCalls)
2193*e038c9c4Sjoerg         return true;
2194*e038c9c4Sjoerg 
2195*e038c9c4Sjoerg       if (!TargetDecl)
2196*e038c9c4Sjoerg         return false;
2197*e038c9c4Sjoerg 
21987330f729Sjoerg       if (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
21997330f729Sjoerg           TargetDecl->hasAttr<AnyX86InterruptAttr>())
2200*e038c9c4Sjoerg         return true;
2201*e038c9c4Sjoerg 
2202*e038c9c4Sjoerg       if (CodeGenOpts.NoEscapingBlockTailCalls) {
22037330f729Sjoerg         if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl))
22047330f729Sjoerg           if (!BD->doesNotEscape())
2205*e038c9c4Sjoerg             return true;
22067330f729Sjoerg       }
22077330f729Sjoerg 
2208*e038c9c4Sjoerg       return false;
2209*e038c9c4Sjoerg     };
2210*e038c9c4Sjoerg     if (shouldDisableTailCalls())
2211*e038c9c4Sjoerg       FuncAttrs.addAttribute("disable-tail-calls", "true");
2212*e038c9c4Sjoerg 
2213*e038c9c4Sjoerg     // CPU/feature overrides.  addDefaultFunctionDefinitionAttributes
2214*e038c9c4Sjoerg     // handles these separately to set them based on the global defaults.
22157330f729Sjoerg     GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs);
22167330f729Sjoerg   }
22177330f729Sjoerg 
2218*e038c9c4Sjoerg   // Collect attributes from arguments and return values.
22197330f729Sjoerg   ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
22207330f729Sjoerg 
22217330f729Sjoerg   QualType RetTy = FI.getReturnType();
22227330f729Sjoerg   const ABIArgInfo &RetAI = FI.getReturnInfo();
2223*e038c9c4Sjoerg   const llvm::DataLayout &DL = getDataLayout();
2224*e038c9c4Sjoerg 
2225*e038c9c4Sjoerg   // C++ explicitly makes returning undefined values UB. C's rule only applies
2226*e038c9c4Sjoerg   // to used values, so we never mark them noundef for now.
2227*e038c9c4Sjoerg   bool HasStrictReturn = getLangOpts().CPlusPlus;
2228*e038c9c4Sjoerg   if (TargetDecl) {
2229*e038c9c4Sjoerg     if (const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(TargetDecl))
2230*e038c9c4Sjoerg       HasStrictReturn &= !FDecl->isExternC();
2231*e038c9c4Sjoerg     else if (const VarDecl *VDecl = dyn_cast<VarDecl>(TargetDecl))
2232*e038c9c4Sjoerg       // Function pointer
2233*e038c9c4Sjoerg       HasStrictReturn &= !VDecl->isExternC();
2234*e038c9c4Sjoerg   }
2235*e038c9c4Sjoerg 
2236*e038c9c4Sjoerg   // We don't want to be too aggressive with the return checking, unless
2237*e038c9c4Sjoerg   // it's explicit in the code opts or we're using an appropriate sanitizer.
2238*e038c9c4Sjoerg   // Try to respect what the programmer intended.
2239*e038c9c4Sjoerg   HasStrictReturn &= getCodeGenOpts().StrictReturn ||
2240*e038c9c4Sjoerg                      !MayDropFunctionReturn(getContext(), RetTy) ||
2241*e038c9c4Sjoerg                      getLangOpts().Sanitize.has(SanitizerKind::Memory) ||
2242*e038c9c4Sjoerg                      getLangOpts().Sanitize.has(SanitizerKind::Return);
2243*e038c9c4Sjoerg 
2244*e038c9c4Sjoerg   // Determine if the return type could be partially undef
2245*e038c9c4Sjoerg   if (CodeGenOpts.EnableNoundefAttrs && HasStrictReturn) {
2246*e038c9c4Sjoerg     if (!RetTy->isVoidType() && RetAI.getKind() != ABIArgInfo::Indirect &&
2247*e038c9c4Sjoerg         DetermineNoUndef(RetTy, getTypes(), DL, RetAI))
2248*e038c9c4Sjoerg       RetAttrs.addAttribute(llvm::Attribute::NoUndef);
2249*e038c9c4Sjoerg   }
2250*e038c9c4Sjoerg 
22517330f729Sjoerg   switch (RetAI.getKind()) {
22527330f729Sjoerg   case ABIArgInfo::Extend:
22537330f729Sjoerg     if (RetAI.isSignExt())
22547330f729Sjoerg       RetAttrs.addAttribute(llvm::Attribute::SExt);
22557330f729Sjoerg     else
22567330f729Sjoerg       RetAttrs.addAttribute(llvm::Attribute::ZExt);
22577330f729Sjoerg     LLVM_FALLTHROUGH;
22587330f729Sjoerg   case ABIArgInfo::Direct:
22597330f729Sjoerg     if (RetAI.getInReg())
22607330f729Sjoerg       RetAttrs.addAttribute(llvm::Attribute::InReg);
22617330f729Sjoerg     break;
22627330f729Sjoerg   case ABIArgInfo::Ignore:
22637330f729Sjoerg     break;
22647330f729Sjoerg 
22657330f729Sjoerg   case ABIArgInfo::InAlloca:
22667330f729Sjoerg   case ABIArgInfo::Indirect: {
22677330f729Sjoerg     // inalloca and sret disable readnone and readonly
22687330f729Sjoerg     FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
22697330f729Sjoerg       .removeAttribute(llvm::Attribute::ReadNone);
22707330f729Sjoerg     break;
22717330f729Sjoerg   }
22727330f729Sjoerg 
22737330f729Sjoerg   case ABIArgInfo::CoerceAndExpand:
22747330f729Sjoerg     break;
22757330f729Sjoerg 
22767330f729Sjoerg   case ABIArgInfo::Expand:
2277*e038c9c4Sjoerg   case ABIArgInfo::IndirectAliased:
22787330f729Sjoerg     llvm_unreachable("Invalid ABI kind for return argument");
22797330f729Sjoerg   }
22807330f729Sjoerg 
2281*e038c9c4Sjoerg   if (!IsThunk) {
2282*e038c9c4Sjoerg     // FIXME: fix this properly, https://reviews.llvm.org/D100388
22837330f729Sjoerg     if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
22847330f729Sjoerg       QualType PTy = RefTy->getPointeeType();
22857330f729Sjoerg       if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2286*e038c9c4Sjoerg         RetAttrs.addDereferenceableAttr(
2287*e038c9c4Sjoerg             getMinimumObjectSize(PTy).getQuantity());
2288*e038c9c4Sjoerg       if (getContext().getTargetAddressSpace(PTy) == 0 &&
22897330f729Sjoerg           !CodeGenOpts.NullPointerIsValid)
22907330f729Sjoerg         RetAttrs.addAttribute(llvm::Attribute::NonNull);
2291*e038c9c4Sjoerg       if (PTy->isObjectType()) {
2292*e038c9c4Sjoerg         llvm::Align Alignment =
2293*e038c9c4Sjoerg             getNaturalPointeeTypeAlignment(RetTy).getAsAlign();
2294*e038c9c4Sjoerg         RetAttrs.addAlignmentAttr(Alignment);
2295*e038c9c4Sjoerg       }
2296*e038c9c4Sjoerg     }
22977330f729Sjoerg   }
22987330f729Sjoerg 
22997330f729Sjoerg   bool hasUsedSRet = false;
23007330f729Sjoerg   SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs());
23017330f729Sjoerg 
23027330f729Sjoerg   // Attach attributes to sret.
23037330f729Sjoerg   if (IRFunctionArgs.hasSRetArg()) {
23047330f729Sjoerg     llvm::AttrBuilder SRETAttrs;
2305*e038c9c4Sjoerg     SRETAttrs.addStructRetAttr(getTypes().ConvertTypeForMem(RetTy));
23067330f729Sjoerg     hasUsedSRet = true;
23077330f729Sjoerg     if (RetAI.getInReg())
23087330f729Sjoerg       SRETAttrs.addAttribute(llvm::Attribute::InReg);
2309*e038c9c4Sjoerg     SRETAttrs.addAlignmentAttr(RetAI.getIndirectAlign().getQuantity());
23107330f729Sjoerg     ArgAttrs[IRFunctionArgs.getSRetArgNo()] =
23117330f729Sjoerg         llvm::AttributeSet::get(getLLVMContext(), SRETAttrs);
23127330f729Sjoerg   }
23137330f729Sjoerg 
23147330f729Sjoerg   // Attach attributes to inalloca argument.
23157330f729Sjoerg   if (IRFunctionArgs.hasInallocaArg()) {
23167330f729Sjoerg     llvm::AttrBuilder Attrs;
2317*e038c9c4Sjoerg     Attrs.addInAllocaAttr(FI.getArgStruct());
23187330f729Sjoerg     ArgAttrs[IRFunctionArgs.getInallocaArgNo()] =
23197330f729Sjoerg         llvm::AttributeSet::get(getLLVMContext(), Attrs);
23207330f729Sjoerg   }
23217330f729Sjoerg 
2322*e038c9c4Sjoerg   // Apply `nonnull`, `dereferencable(N)` and `align N` to the `this` argument,
2323*e038c9c4Sjoerg   // unless this is a thunk function.
2324*e038c9c4Sjoerg   // FIXME: fix this properly, https://reviews.llvm.org/D100388
2325*e038c9c4Sjoerg   if (FI.isInstanceMethod() && !IRFunctionArgs.hasInallocaArg() &&
2326*e038c9c4Sjoerg       !FI.arg_begin()->type->isVoidPointerType() && !IsThunk) {
2327*e038c9c4Sjoerg     auto IRArgs = IRFunctionArgs.getIRArgs(0);
2328*e038c9c4Sjoerg 
2329*e038c9c4Sjoerg     assert(IRArgs.second == 1 && "Expected only a single `this` pointer.");
2330*e038c9c4Sjoerg 
2331*e038c9c4Sjoerg     llvm::AttrBuilder Attrs;
2332*e038c9c4Sjoerg 
2333*e038c9c4Sjoerg     QualType ThisTy =
2334*e038c9c4Sjoerg         FI.arg_begin()->type.castAs<PointerType>()->getPointeeType();
2335*e038c9c4Sjoerg 
2336*e038c9c4Sjoerg     if (!CodeGenOpts.NullPointerIsValid &&
2337*e038c9c4Sjoerg         getContext().getTargetAddressSpace(FI.arg_begin()->type) == 0) {
2338*e038c9c4Sjoerg       Attrs.addAttribute(llvm::Attribute::NonNull);
2339*e038c9c4Sjoerg       Attrs.addDereferenceableAttr(getMinimumObjectSize(ThisTy).getQuantity());
2340*e038c9c4Sjoerg     } else {
2341*e038c9c4Sjoerg       // FIXME dereferenceable should be correct here, regardless of
2342*e038c9c4Sjoerg       // NullPointerIsValid. However, dereferenceable currently does not always
2343*e038c9c4Sjoerg       // respect NullPointerIsValid and may imply nonnull and break the program.
2344*e038c9c4Sjoerg       // See https://reviews.llvm.org/D66618 for discussions.
2345*e038c9c4Sjoerg       Attrs.addDereferenceableOrNullAttr(
2346*e038c9c4Sjoerg           getMinimumObjectSize(
2347*e038c9c4Sjoerg               FI.arg_begin()->type.castAs<PointerType>()->getPointeeType())
2348*e038c9c4Sjoerg               .getQuantity());
2349*e038c9c4Sjoerg     }
2350*e038c9c4Sjoerg 
2351*e038c9c4Sjoerg     llvm::Align Alignment =
2352*e038c9c4Sjoerg         getNaturalTypeAlignment(ThisTy, /*BaseInfo=*/nullptr,
2353*e038c9c4Sjoerg                                 /*TBAAInfo=*/nullptr, /*forPointeeType=*/true)
2354*e038c9c4Sjoerg             .getAsAlign();
2355*e038c9c4Sjoerg     Attrs.addAlignmentAttr(Alignment);
2356*e038c9c4Sjoerg 
2357*e038c9c4Sjoerg     ArgAttrs[IRArgs.first] = llvm::AttributeSet::get(getLLVMContext(), Attrs);
2358*e038c9c4Sjoerg   }
2359*e038c9c4Sjoerg 
23607330f729Sjoerg   unsigned ArgNo = 0;
23617330f729Sjoerg   for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
23627330f729Sjoerg                                           E = FI.arg_end();
23637330f729Sjoerg        I != E; ++I, ++ArgNo) {
23647330f729Sjoerg     QualType ParamType = I->type;
23657330f729Sjoerg     const ABIArgInfo &AI = I->info;
23667330f729Sjoerg     llvm::AttrBuilder Attrs;
23677330f729Sjoerg 
23687330f729Sjoerg     // Add attribute for padding argument, if necessary.
23697330f729Sjoerg     if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
23707330f729Sjoerg       if (AI.getPaddingInReg()) {
23717330f729Sjoerg         ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
23727330f729Sjoerg             llvm::AttributeSet::get(
23737330f729Sjoerg                 getLLVMContext(),
23747330f729Sjoerg                 llvm::AttrBuilder().addAttribute(llvm::Attribute::InReg));
23757330f729Sjoerg       }
23767330f729Sjoerg     }
23777330f729Sjoerg 
2378*e038c9c4Sjoerg     // Decide whether the argument we're handling could be partially undef
2379*e038c9c4Sjoerg     bool ArgNoUndef = DetermineNoUndef(ParamType, getTypes(), DL, AI);
2380*e038c9c4Sjoerg     if (CodeGenOpts.EnableNoundefAttrs && ArgNoUndef)
2381*e038c9c4Sjoerg       Attrs.addAttribute(llvm::Attribute::NoUndef);
2382*e038c9c4Sjoerg 
23837330f729Sjoerg     // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
23847330f729Sjoerg     // have the corresponding parameter variable.  It doesn't make
23857330f729Sjoerg     // sense to do it here because parameters are so messed up.
23867330f729Sjoerg     switch (AI.getKind()) {
23877330f729Sjoerg     case ABIArgInfo::Extend:
23887330f729Sjoerg       if (AI.isSignExt())
23897330f729Sjoerg         Attrs.addAttribute(llvm::Attribute::SExt);
23907330f729Sjoerg       else
23917330f729Sjoerg         Attrs.addAttribute(llvm::Attribute::ZExt);
23927330f729Sjoerg       LLVM_FALLTHROUGH;
23937330f729Sjoerg     case ABIArgInfo::Direct:
23947330f729Sjoerg       if (ArgNo == 0 && FI.isChainCall())
23957330f729Sjoerg         Attrs.addAttribute(llvm::Attribute::Nest);
23967330f729Sjoerg       else if (AI.getInReg())
23977330f729Sjoerg         Attrs.addAttribute(llvm::Attribute::InReg);
2398*e038c9c4Sjoerg       Attrs.addStackAlignmentAttr(llvm::MaybeAlign(AI.getDirectAlign()));
23997330f729Sjoerg       break;
24007330f729Sjoerg 
24017330f729Sjoerg     case ABIArgInfo::Indirect: {
24027330f729Sjoerg       if (AI.getInReg())
24037330f729Sjoerg         Attrs.addAttribute(llvm::Attribute::InReg);
24047330f729Sjoerg 
24057330f729Sjoerg       if (AI.getIndirectByVal())
24067330f729Sjoerg         Attrs.addByValAttr(getTypes().ConvertTypeForMem(ParamType));
24077330f729Sjoerg 
2408*e038c9c4Sjoerg       auto *Decl = ParamType->getAsRecordDecl();
2409*e038c9c4Sjoerg       if (CodeGenOpts.PassByValueIsNoAlias && Decl &&
2410*e038c9c4Sjoerg           Decl->getArgPassingRestrictions() == RecordDecl::APK_CanPassInRegs)
2411*e038c9c4Sjoerg         // When calling the function, the pointer passed in will be the only
2412*e038c9c4Sjoerg         // reference to the underlying object. Mark it accordingly.
2413*e038c9c4Sjoerg         Attrs.addAttribute(llvm::Attribute::NoAlias);
2414*e038c9c4Sjoerg 
2415*e038c9c4Sjoerg       // TODO: We could add the byref attribute if not byval, but it would
2416*e038c9c4Sjoerg       // require updating many testcases.
2417*e038c9c4Sjoerg 
24187330f729Sjoerg       CharUnits Align = AI.getIndirectAlign();
24197330f729Sjoerg 
24207330f729Sjoerg       // In a byval argument, it is important that the required
24217330f729Sjoerg       // alignment of the type is honored, as LLVM might be creating a
24227330f729Sjoerg       // *new* stack object, and needs to know what alignment to give
24237330f729Sjoerg       // it. (Sometimes it can deduce a sensible alignment on its own,
24247330f729Sjoerg       // but not if clang decides it must emit a packed struct, or the
24257330f729Sjoerg       // user specifies increased alignment requirements.)
24267330f729Sjoerg       //
24277330f729Sjoerg       // This is different from indirect *not* byval, where the object
24287330f729Sjoerg       // exists already, and the align attribute is purely
24297330f729Sjoerg       // informative.
24307330f729Sjoerg       assert(!Align.isZero());
24317330f729Sjoerg 
24327330f729Sjoerg       // For now, only add this when we have a byval argument.
24337330f729Sjoerg       // TODO: be less lazy about updating test cases.
24347330f729Sjoerg       if (AI.getIndirectByVal())
24357330f729Sjoerg         Attrs.addAlignmentAttr(Align.getQuantity());
24367330f729Sjoerg 
24377330f729Sjoerg       // byval disables readnone and readonly.
24387330f729Sjoerg       FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
24397330f729Sjoerg         .removeAttribute(llvm::Attribute::ReadNone);
2440*e038c9c4Sjoerg 
2441*e038c9c4Sjoerg       break;
2442*e038c9c4Sjoerg     }
2443*e038c9c4Sjoerg     case ABIArgInfo::IndirectAliased: {
2444*e038c9c4Sjoerg       CharUnits Align = AI.getIndirectAlign();
2445*e038c9c4Sjoerg       Attrs.addByRefAttr(getTypes().ConvertTypeForMem(ParamType));
2446*e038c9c4Sjoerg       Attrs.addAlignmentAttr(Align.getQuantity());
24477330f729Sjoerg       break;
24487330f729Sjoerg     }
24497330f729Sjoerg     case ABIArgInfo::Ignore:
24507330f729Sjoerg     case ABIArgInfo::Expand:
24517330f729Sjoerg     case ABIArgInfo::CoerceAndExpand:
24527330f729Sjoerg       break;
24537330f729Sjoerg 
24547330f729Sjoerg     case ABIArgInfo::InAlloca:
24557330f729Sjoerg       // inalloca disables readnone and readonly.
24567330f729Sjoerg       FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
24577330f729Sjoerg           .removeAttribute(llvm::Attribute::ReadNone);
24587330f729Sjoerg       continue;
24597330f729Sjoerg     }
24607330f729Sjoerg 
24617330f729Sjoerg     if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
24627330f729Sjoerg       QualType PTy = RefTy->getPointeeType();
24637330f729Sjoerg       if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2464*e038c9c4Sjoerg         Attrs.addDereferenceableAttr(
2465*e038c9c4Sjoerg             getMinimumObjectSize(PTy).getQuantity());
2466*e038c9c4Sjoerg       if (getContext().getTargetAddressSpace(PTy) == 0 &&
24677330f729Sjoerg           !CodeGenOpts.NullPointerIsValid)
24687330f729Sjoerg         Attrs.addAttribute(llvm::Attribute::NonNull);
2469*e038c9c4Sjoerg       if (PTy->isObjectType()) {
2470*e038c9c4Sjoerg         llvm::Align Alignment =
2471*e038c9c4Sjoerg             getNaturalPointeeTypeAlignment(ParamType).getAsAlign();
2472*e038c9c4Sjoerg         Attrs.addAlignmentAttr(Alignment);
2473*e038c9c4Sjoerg       }
24747330f729Sjoerg     }
24757330f729Sjoerg 
24767330f729Sjoerg     switch (FI.getExtParameterInfo(ArgNo).getABI()) {
24777330f729Sjoerg     case ParameterABI::Ordinary:
24787330f729Sjoerg       break;
24797330f729Sjoerg 
24807330f729Sjoerg     case ParameterABI::SwiftIndirectResult: {
24817330f729Sjoerg       // Add 'sret' if we haven't already used it for something, but
24827330f729Sjoerg       // only if the result is void.
24837330f729Sjoerg       if (!hasUsedSRet && RetTy->isVoidType()) {
2484*e038c9c4Sjoerg         Attrs.addStructRetAttr(getTypes().ConvertTypeForMem(ParamType));
24857330f729Sjoerg         hasUsedSRet = true;
24867330f729Sjoerg       }
24877330f729Sjoerg 
24887330f729Sjoerg       // Add 'noalias' in either case.
24897330f729Sjoerg       Attrs.addAttribute(llvm::Attribute::NoAlias);
24907330f729Sjoerg 
24917330f729Sjoerg       // Add 'dereferenceable' and 'alignment'.
24927330f729Sjoerg       auto PTy = ParamType->getPointeeType();
24937330f729Sjoerg       if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
24947330f729Sjoerg         auto info = getContext().getTypeInfoInChars(PTy);
2495*e038c9c4Sjoerg         Attrs.addDereferenceableAttr(info.Width.getQuantity());
2496*e038c9c4Sjoerg         Attrs.addAlignmentAttr(info.Align.getAsAlign());
24977330f729Sjoerg       }
24987330f729Sjoerg       break;
24997330f729Sjoerg     }
25007330f729Sjoerg 
25017330f729Sjoerg     case ParameterABI::SwiftErrorResult:
25027330f729Sjoerg       Attrs.addAttribute(llvm::Attribute::SwiftError);
25037330f729Sjoerg       break;
25047330f729Sjoerg 
25057330f729Sjoerg     case ParameterABI::SwiftContext:
25067330f729Sjoerg       Attrs.addAttribute(llvm::Attribute::SwiftSelf);
25077330f729Sjoerg       break;
25087330f729Sjoerg     }
25097330f729Sjoerg 
25107330f729Sjoerg     if (FI.getExtParameterInfo(ArgNo).isNoEscape())
25117330f729Sjoerg       Attrs.addAttribute(llvm::Attribute::NoCapture);
25127330f729Sjoerg 
25137330f729Sjoerg     if (Attrs.hasAttributes()) {
25147330f729Sjoerg       unsigned FirstIRArg, NumIRArgs;
25157330f729Sjoerg       std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
25167330f729Sjoerg       for (unsigned i = 0; i < NumIRArgs; i++)
25177330f729Sjoerg         ArgAttrs[FirstIRArg + i] =
25187330f729Sjoerg             llvm::AttributeSet::get(getLLVMContext(), Attrs);
25197330f729Sjoerg     }
25207330f729Sjoerg   }
25217330f729Sjoerg   assert(ArgNo == FI.arg_size());
25227330f729Sjoerg 
25237330f729Sjoerg   AttrList = llvm::AttributeList::get(
25247330f729Sjoerg       getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs),
25257330f729Sjoerg       llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs);
25267330f729Sjoerg }
25277330f729Sjoerg 
25287330f729Sjoerg /// An argument came in as a promoted argument; demote it back to its
25297330f729Sjoerg /// declared type.
emitArgumentDemotion(CodeGenFunction & CGF,const VarDecl * var,llvm::Value * value)25307330f729Sjoerg static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
25317330f729Sjoerg                                          const VarDecl *var,
25327330f729Sjoerg                                          llvm::Value *value) {
25337330f729Sjoerg   llvm::Type *varType = CGF.ConvertType(var->getType());
25347330f729Sjoerg 
25357330f729Sjoerg   // This can happen with promotions that actually don't change the
25367330f729Sjoerg   // underlying type, like the enum promotions.
25377330f729Sjoerg   if (value->getType() == varType) return value;
25387330f729Sjoerg 
25397330f729Sjoerg   assert((varType->isIntegerTy() || varType->isFloatingPointTy())
25407330f729Sjoerg          && "unexpected promotion type");
25417330f729Sjoerg 
25427330f729Sjoerg   if (isa<llvm::IntegerType>(varType))
25437330f729Sjoerg     return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
25447330f729Sjoerg 
25457330f729Sjoerg   return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
25467330f729Sjoerg }
25477330f729Sjoerg 
25487330f729Sjoerg /// Returns the attribute (either parameter attribute, or function
25497330f729Sjoerg /// attribute), which declares argument ArgNo to be non-null.
getNonNullAttr(const Decl * FD,const ParmVarDecl * PVD,QualType ArgType,unsigned ArgNo)25507330f729Sjoerg static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
25517330f729Sjoerg                                          QualType ArgType, unsigned ArgNo) {
25527330f729Sjoerg   // FIXME: __attribute__((nonnull)) can also be applied to:
25537330f729Sjoerg   //   - references to pointers, where the pointee is known to be
25547330f729Sjoerg   //     nonnull (apparently a Clang extension)
25557330f729Sjoerg   //   - transparent unions containing pointers
25567330f729Sjoerg   // In the former case, LLVM IR cannot represent the constraint. In
25577330f729Sjoerg   // the latter case, we have no guarantee that the transparent union
25587330f729Sjoerg   // is in fact passed as a pointer.
25597330f729Sjoerg   if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
25607330f729Sjoerg     return nullptr;
25617330f729Sjoerg   // First, check attribute on parameter itself.
25627330f729Sjoerg   if (PVD) {
25637330f729Sjoerg     if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
25647330f729Sjoerg       return ParmNNAttr;
25657330f729Sjoerg   }
25667330f729Sjoerg   // Check function attributes.
25677330f729Sjoerg   if (!FD)
25687330f729Sjoerg     return nullptr;
25697330f729Sjoerg   for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
25707330f729Sjoerg     if (NNAttr->isNonNull(ArgNo))
25717330f729Sjoerg       return NNAttr;
25727330f729Sjoerg   }
25737330f729Sjoerg   return nullptr;
25747330f729Sjoerg }
25757330f729Sjoerg 
25767330f729Sjoerg namespace {
25777330f729Sjoerg   struct CopyBackSwiftError final : EHScopeStack::Cleanup {
25787330f729Sjoerg     Address Temp;
25797330f729Sjoerg     Address Arg;
CopyBackSwiftError__anon6af8234f0811::CopyBackSwiftError25807330f729Sjoerg     CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
Emit__anon6af8234f0811::CopyBackSwiftError25817330f729Sjoerg     void Emit(CodeGenFunction &CGF, Flags flags) override {
25827330f729Sjoerg       llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
25837330f729Sjoerg       CGF.Builder.CreateStore(errorValue, Arg);
25847330f729Sjoerg     }
25857330f729Sjoerg   };
25867330f729Sjoerg }
25877330f729Sjoerg 
EmitFunctionProlog(const CGFunctionInfo & FI,llvm::Function * Fn,const FunctionArgList & Args)25887330f729Sjoerg void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
25897330f729Sjoerg                                          llvm::Function *Fn,
25907330f729Sjoerg                                          const FunctionArgList &Args) {
25917330f729Sjoerg   if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
25927330f729Sjoerg     // Naked functions don't have prologues.
25937330f729Sjoerg     return;
25947330f729Sjoerg 
25957330f729Sjoerg   // If this is an implicit-return-zero function, go ahead and
25967330f729Sjoerg   // initialize the return value.  TODO: it might be nice to have
25977330f729Sjoerg   // a more general mechanism for this that didn't require synthesized
25987330f729Sjoerg   // return statements.
25997330f729Sjoerg   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
26007330f729Sjoerg     if (FD->hasImplicitReturnZero()) {
26017330f729Sjoerg       QualType RetTy = FD->getReturnType().getUnqualifiedType();
26027330f729Sjoerg       llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
26037330f729Sjoerg       llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
26047330f729Sjoerg       Builder.CreateStore(Zero, ReturnValue);
26057330f729Sjoerg     }
26067330f729Sjoerg   }
26077330f729Sjoerg 
26087330f729Sjoerg   // FIXME: We no longer need the types from FunctionArgList; lift up and
26097330f729Sjoerg   // simplify.
26107330f729Sjoerg 
26117330f729Sjoerg   ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
2612*e038c9c4Sjoerg   assert(Fn->arg_size() == IRFunctionArgs.totalIRArgs());
26137330f729Sjoerg 
26147330f729Sjoerg   // If we're using inalloca, all the memory arguments are GEPs off of the last
26157330f729Sjoerg   // parameter, which is a pointer to the complete memory area.
26167330f729Sjoerg   Address ArgStruct = Address::invalid();
26177330f729Sjoerg   if (IRFunctionArgs.hasInallocaArg()) {
2618*e038c9c4Sjoerg     ArgStruct = Address(Fn->getArg(IRFunctionArgs.getInallocaArgNo()),
26197330f729Sjoerg                         FI.getArgStructAlignment());
26207330f729Sjoerg 
26217330f729Sjoerg     assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
26227330f729Sjoerg   }
26237330f729Sjoerg 
26247330f729Sjoerg   // Name the struct return parameter.
26257330f729Sjoerg   if (IRFunctionArgs.hasSRetArg()) {
2626*e038c9c4Sjoerg     auto AI = Fn->getArg(IRFunctionArgs.getSRetArgNo());
26277330f729Sjoerg     AI->setName("agg.result");
26287330f729Sjoerg     AI->addAttr(llvm::Attribute::NoAlias);
26297330f729Sjoerg   }
26307330f729Sjoerg 
26317330f729Sjoerg   // Track if we received the parameter as a pointer (indirect, byval, or
26327330f729Sjoerg   // inalloca).  If already have a pointer, EmitParmDecl doesn't need to copy it
26337330f729Sjoerg   // into a local alloca for us.
26347330f729Sjoerg   SmallVector<ParamValue, 16> ArgVals;
26357330f729Sjoerg   ArgVals.reserve(Args.size());
26367330f729Sjoerg 
26377330f729Sjoerg   // Create a pointer value for every parameter declaration.  This usually
26387330f729Sjoerg   // entails copying one or more LLVM IR arguments into an alloca.  Don't push
26397330f729Sjoerg   // any cleanups or do anything that might unwind.  We do that separately, so
26407330f729Sjoerg   // we can push the cleanups in the correct order for the ABI.
26417330f729Sjoerg   assert(FI.arg_size() == Args.size() &&
26427330f729Sjoerg          "Mismatch between function signature & arguments.");
26437330f729Sjoerg   unsigned ArgNo = 0;
26447330f729Sjoerg   CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
26457330f729Sjoerg   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
26467330f729Sjoerg        i != e; ++i, ++info_it, ++ArgNo) {
26477330f729Sjoerg     const VarDecl *Arg = *i;
26487330f729Sjoerg     const ABIArgInfo &ArgI = info_it->info;
26497330f729Sjoerg 
26507330f729Sjoerg     bool isPromoted =
26517330f729Sjoerg       isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
26527330f729Sjoerg     // We are converting from ABIArgInfo type to VarDecl type directly, unless
26537330f729Sjoerg     // the parameter is promoted. In this case we convert to
26547330f729Sjoerg     // CGFunctionInfo::ArgInfo type with subsequent argument demotion.
26557330f729Sjoerg     QualType Ty = isPromoted ? info_it->type : Arg->getType();
26567330f729Sjoerg     assert(hasScalarEvaluationKind(Ty) ==
26577330f729Sjoerg            hasScalarEvaluationKind(Arg->getType()));
26587330f729Sjoerg 
26597330f729Sjoerg     unsigned FirstIRArg, NumIRArgs;
26607330f729Sjoerg     std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
26617330f729Sjoerg 
26627330f729Sjoerg     switch (ArgI.getKind()) {
26637330f729Sjoerg     case ABIArgInfo::InAlloca: {
26647330f729Sjoerg       assert(NumIRArgs == 0);
26657330f729Sjoerg       auto FieldIndex = ArgI.getInAllocaFieldIndex();
26667330f729Sjoerg       Address V =
26677330f729Sjoerg           Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName());
2668*e038c9c4Sjoerg       if (ArgI.getInAllocaIndirect())
2669*e038c9c4Sjoerg         V = Address(Builder.CreateLoad(V),
2670*e038c9c4Sjoerg                     getContext().getTypeAlignInChars(Ty));
26717330f729Sjoerg       ArgVals.push_back(ParamValue::forIndirect(V));
26727330f729Sjoerg       break;
26737330f729Sjoerg     }
26747330f729Sjoerg 
2675*e038c9c4Sjoerg     case ABIArgInfo::Indirect:
2676*e038c9c4Sjoerg     case ABIArgInfo::IndirectAliased: {
26777330f729Sjoerg       assert(NumIRArgs == 1);
2678*e038c9c4Sjoerg       Address ParamAddr =
2679*e038c9c4Sjoerg           Address(Fn->getArg(FirstIRArg), ArgI.getIndirectAlign());
26807330f729Sjoerg 
26817330f729Sjoerg       if (!hasScalarEvaluationKind(Ty)) {
26827330f729Sjoerg         // Aggregates and complex variables are accessed by reference. All we
2683*e038c9c4Sjoerg         // need to do is realign the value, if requested. Also, if the address
2684*e038c9c4Sjoerg         // may be aliased, copy it to ensure that the parameter variable is
2685*e038c9c4Sjoerg         // mutable and has a unique adress, as C requires.
26867330f729Sjoerg         Address V = ParamAddr;
2687*e038c9c4Sjoerg         if (ArgI.getIndirectRealign() || ArgI.isIndirectAliased()) {
26887330f729Sjoerg           Address AlignedTemp = CreateMemTemp(Ty, "coerce");
26897330f729Sjoerg 
26907330f729Sjoerg           // Copy from the incoming argument pointer to the temporary with the
26917330f729Sjoerg           // appropriate alignment.
26927330f729Sjoerg           //
26937330f729Sjoerg           // FIXME: We should have a common utility for generating an aggregate
26947330f729Sjoerg           // copy.
26957330f729Sjoerg           CharUnits Size = getContext().getTypeSizeInChars(Ty);
2696*e038c9c4Sjoerg           Builder.CreateMemCpy(
2697*e038c9c4Sjoerg               AlignedTemp.getPointer(), AlignedTemp.getAlignment().getAsAlign(),
2698*e038c9c4Sjoerg               ParamAddr.getPointer(), ParamAddr.getAlignment().getAsAlign(),
2699*e038c9c4Sjoerg               llvm::ConstantInt::get(IntPtrTy, Size.getQuantity()));
27007330f729Sjoerg           V = AlignedTemp;
27017330f729Sjoerg         }
27027330f729Sjoerg         ArgVals.push_back(ParamValue::forIndirect(V));
27037330f729Sjoerg       } else {
27047330f729Sjoerg         // Load scalar value from indirect argument.
27057330f729Sjoerg         llvm::Value *V =
27067330f729Sjoerg             EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc());
27077330f729Sjoerg 
27087330f729Sjoerg         if (isPromoted)
27097330f729Sjoerg           V = emitArgumentDemotion(*this, Arg, V);
27107330f729Sjoerg         ArgVals.push_back(ParamValue::forDirect(V));
27117330f729Sjoerg       }
27127330f729Sjoerg       break;
27137330f729Sjoerg     }
27147330f729Sjoerg 
27157330f729Sjoerg     case ABIArgInfo::Extend:
27167330f729Sjoerg     case ABIArgInfo::Direct: {
2717*e038c9c4Sjoerg       auto AI = Fn->getArg(FirstIRArg);
2718*e038c9c4Sjoerg       llvm::Type *LTy = ConvertType(Arg->getType());
27197330f729Sjoerg 
2720*e038c9c4Sjoerg       // Prepare parameter attributes. So far, only attributes for pointer
2721*e038c9c4Sjoerg       // parameters are prepared. See
2722*e038c9c4Sjoerg       // http://llvm.org/docs/LangRef.html#paramattrs.
2723*e038c9c4Sjoerg       if (ArgI.getDirectOffset() == 0 && LTy->isPointerTy() &&
2724*e038c9c4Sjoerg           ArgI.getCoerceToType()->isPointerTy()) {
27257330f729Sjoerg         assert(NumIRArgs == 1);
27267330f729Sjoerg 
27277330f729Sjoerg         if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
2728*e038c9c4Sjoerg           // Set `nonnull` attribute if any.
27297330f729Sjoerg           if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
27307330f729Sjoerg                              PVD->getFunctionScopeIndex()) &&
27317330f729Sjoerg               !CGM.getCodeGenOpts().NullPointerIsValid)
27327330f729Sjoerg             AI->addAttr(llvm::Attribute::NonNull);
27337330f729Sjoerg 
27347330f729Sjoerg           QualType OTy = PVD->getOriginalType();
27357330f729Sjoerg           if (const auto *ArrTy =
27367330f729Sjoerg               getContext().getAsConstantArrayType(OTy)) {
27377330f729Sjoerg             // A C99 array parameter declaration with the static keyword also
27387330f729Sjoerg             // indicates dereferenceability, and if the size is constant we can
27397330f729Sjoerg             // use the dereferenceable attribute (which requires the size in
27407330f729Sjoerg             // bytes).
27417330f729Sjoerg             if (ArrTy->getSizeModifier() == ArrayType::Static) {
27427330f729Sjoerg               QualType ETy = ArrTy->getElementType();
2743*e038c9c4Sjoerg               llvm::Align Alignment =
2744*e038c9c4Sjoerg                   CGM.getNaturalTypeAlignment(ETy).getAsAlign();
2745*e038c9c4Sjoerg               AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(Alignment));
27467330f729Sjoerg               uint64_t ArrSize = ArrTy->getSize().getZExtValue();
27477330f729Sjoerg               if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
27487330f729Sjoerg                   ArrSize) {
27497330f729Sjoerg                 llvm::AttrBuilder Attrs;
27507330f729Sjoerg                 Attrs.addDereferenceableAttr(
2751*e038c9c4Sjoerg                     getContext().getTypeSizeInChars(ETy).getQuantity() *
2752*e038c9c4Sjoerg                     ArrSize);
27537330f729Sjoerg                 AI->addAttrs(Attrs);
2754*e038c9c4Sjoerg               } else if (getContext().getTargetInfo().getNullPointerValue(
2755*e038c9c4Sjoerg                              ETy.getAddressSpace()) == 0 &&
27567330f729Sjoerg                          !CGM.getCodeGenOpts().NullPointerIsValid) {
27577330f729Sjoerg                 AI->addAttr(llvm::Attribute::NonNull);
27587330f729Sjoerg               }
27597330f729Sjoerg             }
27607330f729Sjoerg           } else if (const auto *ArrTy =
27617330f729Sjoerg                      getContext().getAsVariableArrayType(OTy)) {
27627330f729Sjoerg             // For C99 VLAs with the static keyword, we don't know the size so
27637330f729Sjoerg             // we can't use the dereferenceable attribute, but in addrspace(0)
27647330f729Sjoerg             // we know that it must be nonnull.
2765*e038c9c4Sjoerg             if (ArrTy->getSizeModifier() == VariableArrayType::Static) {
2766*e038c9c4Sjoerg               QualType ETy = ArrTy->getElementType();
2767*e038c9c4Sjoerg               llvm::Align Alignment =
2768*e038c9c4Sjoerg                   CGM.getNaturalTypeAlignment(ETy).getAsAlign();
2769*e038c9c4Sjoerg               AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(Alignment));
2770*e038c9c4Sjoerg               if (!getContext().getTargetAddressSpace(ETy) &&
27717330f729Sjoerg                   !CGM.getCodeGenOpts().NullPointerIsValid)
27727330f729Sjoerg                 AI->addAttr(llvm::Attribute::NonNull);
27737330f729Sjoerg             }
2774*e038c9c4Sjoerg           }
27757330f729Sjoerg 
2776*e038c9c4Sjoerg           // Set `align` attribute if any.
27777330f729Sjoerg           const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
27787330f729Sjoerg           if (!AVAttr)
27797330f729Sjoerg             if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
27807330f729Sjoerg               AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
27817330f729Sjoerg           if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) {
27827330f729Sjoerg             // If alignment-assumption sanitizer is enabled, we do *not* add
27837330f729Sjoerg             // alignment attribute here, but emit normal alignment assumption,
27847330f729Sjoerg             // so the UBSAN check could function.
27857330f729Sjoerg             llvm::ConstantInt *AlignmentCI =
2786*e038c9c4Sjoerg                 cast<llvm::ConstantInt>(EmitScalarExpr(AVAttr->getAlignment()));
2787*e038c9c4Sjoerg             unsigned AlignmentInt =
2788*e038c9c4Sjoerg                 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment);
2789*e038c9c4Sjoerg             if (AI->getParamAlign().valueOrOne() < AlignmentInt) {
2790*e038c9c4Sjoerg               AI->removeAttr(llvm::Attribute::AttrKind::Alignment);
2791*e038c9c4Sjoerg               AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(
2792*e038c9c4Sjoerg                   llvm::Align(AlignmentInt)));
2793*e038c9c4Sjoerg             }
27947330f729Sjoerg           }
27957330f729Sjoerg         }
27967330f729Sjoerg 
2797*e038c9c4Sjoerg         // Set 'noalias' if an argument type has the `restrict` qualifier.
27987330f729Sjoerg         if (Arg->getType().isRestrictQualified())
27997330f729Sjoerg           AI->addAttr(llvm::Attribute::NoAlias);
2800*e038c9c4Sjoerg       }
2801*e038c9c4Sjoerg 
2802*e038c9c4Sjoerg       // Prepare the argument value. If we have the trivial case, handle it
2803*e038c9c4Sjoerg       // with no muss and fuss.
2804*e038c9c4Sjoerg       if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
2805*e038c9c4Sjoerg           ArgI.getCoerceToType() == ConvertType(Ty) &&
2806*e038c9c4Sjoerg           ArgI.getDirectOffset() == 0) {
2807*e038c9c4Sjoerg         assert(NumIRArgs == 1);
28087330f729Sjoerg 
28097330f729Sjoerg         // LLVM expects swifterror parameters to be used in very restricted
28107330f729Sjoerg         // ways.  Copy the value into a less-restricted temporary.
2811*e038c9c4Sjoerg         llvm::Value *V = AI;
28127330f729Sjoerg         if (FI.getExtParameterInfo(ArgNo).getABI()
28137330f729Sjoerg               == ParameterABI::SwiftErrorResult) {
28147330f729Sjoerg           QualType pointeeTy = Ty->getPointeeType();
28157330f729Sjoerg           assert(pointeeTy->isPointerType());
28167330f729Sjoerg           Address temp =
28177330f729Sjoerg             CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
28187330f729Sjoerg           Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy));
28197330f729Sjoerg           llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
28207330f729Sjoerg           Builder.CreateStore(incomingErrorValue, temp);
28217330f729Sjoerg           V = temp.getPointer();
28227330f729Sjoerg 
28237330f729Sjoerg           // Push a cleanup to copy the value back at the end of the function.
28247330f729Sjoerg           // The convention does not guarantee that the value will be written
28257330f729Sjoerg           // back if the function exits with an unwind exception.
28267330f729Sjoerg           EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
28277330f729Sjoerg         }
28287330f729Sjoerg 
28297330f729Sjoerg         // Ensure the argument is the correct type.
28307330f729Sjoerg         if (V->getType() != ArgI.getCoerceToType())
28317330f729Sjoerg           V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
28327330f729Sjoerg 
28337330f729Sjoerg         if (isPromoted)
28347330f729Sjoerg           V = emitArgumentDemotion(*this, Arg, V);
28357330f729Sjoerg 
28367330f729Sjoerg         // Because of merging of function types from multiple decls it is
28377330f729Sjoerg         // possible for the type of an argument to not match the corresponding
28387330f729Sjoerg         // type in the function type. Since we are codegening the callee
28397330f729Sjoerg         // in here, add a cast to the argument type.
28407330f729Sjoerg         llvm::Type *LTy = ConvertType(Arg->getType());
28417330f729Sjoerg         if (V->getType() != LTy)
28427330f729Sjoerg           V = Builder.CreateBitCast(V, LTy);
28437330f729Sjoerg 
28447330f729Sjoerg         ArgVals.push_back(ParamValue::forDirect(V));
28457330f729Sjoerg         break;
28467330f729Sjoerg       }
28477330f729Sjoerg 
2848*e038c9c4Sjoerg       // VLST arguments are coerced to VLATs at the function boundary for
2849*e038c9c4Sjoerg       // ABI consistency. If this is a VLST that was coerced to
2850*e038c9c4Sjoerg       // a VLAT at the function boundary and the types match up, use
2851*e038c9c4Sjoerg       // llvm.experimental.vector.extract to convert back to the original
2852*e038c9c4Sjoerg       // VLST.
2853*e038c9c4Sjoerg       if (auto *VecTyTo = dyn_cast<llvm::FixedVectorType>(ConvertType(Ty))) {
2854*e038c9c4Sjoerg         auto *Coerced = Fn->getArg(FirstIRArg);
2855*e038c9c4Sjoerg         if (auto *VecTyFrom =
2856*e038c9c4Sjoerg                 dyn_cast<llvm::ScalableVectorType>(Coerced->getType())) {
2857*e038c9c4Sjoerg           if (VecTyFrom->getElementType() == VecTyTo->getElementType()) {
2858*e038c9c4Sjoerg             llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty);
2859*e038c9c4Sjoerg 
2860*e038c9c4Sjoerg             assert(NumIRArgs == 1);
2861*e038c9c4Sjoerg             Coerced->setName(Arg->getName() + ".coerce");
2862*e038c9c4Sjoerg             ArgVals.push_back(ParamValue::forDirect(Builder.CreateExtractVector(
2863*e038c9c4Sjoerg                 VecTyTo, Coerced, Zero, "castFixedSve")));
2864*e038c9c4Sjoerg             break;
2865*e038c9c4Sjoerg           }
2866*e038c9c4Sjoerg         }
2867*e038c9c4Sjoerg       }
2868*e038c9c4Sjoerg 
28697330f729Sjoerg       Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
28707330f729Sjoerg                                      Arg->getName());
28717330f729Sjoerg 
28727330f729Sjoerg       // Pointer to store into.
28737330f729Sjoerg       Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
28747330f729Sjoerg 
28757330f729Sjoerg       // Fast-isel and the optimizer generally like scalar values better than
28767330f729Sjoerg       // FCAs, so we flatten them if this is safe to do for this argument.
28777330f729Sjoerg       llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
28787330f729Sjoerg       if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
28797330f729Sjoerg           STy->getNumElements() > 1) {
28807330f729Sjoerg         uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
28817330f729Sjoerg         llvm::Type *DstTy = Ptr.getElementType();
28827330f729Sjoerg         uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
28837330f729Sjoerg 
28847330f729Sjoerg         Address AddrToStoreInto = Address::invalid();
28857330f729Sjoerg         if (SrcSize <= DstSize) {
28867330f729Sjoerg           AddrToStoreInto = Builder.CreateElementBitCast(Ptr, STy);
28877330f729Sjoerg         } else {
28887330f729Sjoerg           AddrToStoreInto =
28897330f729Sjoerg             CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
28907330f729Sjoerg         }
28917330f729Sjoerg 
28927330f729Sjoerg         assert(STy->getNumElements() == NumIRArgs);
28937330f729Sjoerg         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2894*e038c9c4Sjoerg           auto AI = Fn->getArg(FirstIRArg + i);
28957330f729Sjoerg           AI->setName(Arg->getName() + ".coerce" + Twine(i));
28967330f729Sjoerg           Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i);
28977330f729Sjoerg           Builder.CreateStore(AI, EltPtr);
28987330f729Sjoerg         }
28997330f729Sjoerg 
29007330f729Sjoerg         if (SrcSize > DstSize) {
29017330f729Sjoerg           Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
29027330f729Sjoerg         }
29037330f729Sjoerg 
29047330f729Sjoerg       } else {
29057330f729Sjoerg         // Simple case, just do a coerced store of the argument into the alloca.
29067330f729Sjoerg         assert(NumIRArgs == 1);
2907*e038c9c4Sjoerg         auto AI = Fn->getArg(FirstIRArg);
29087330f729Sjoerg         AI->setName(Arg->getName() + ".coerce");
29097330f729Sjoerg         CreateCoercedStore(AI, Ptr, /*DstIsVolatile=*/false, *this);
29107330f729Sjoerg       }
29117330f729Sjoerg 
29127330f729Sjoerg       // Match to what EmitParmDecl is expecting for this type.
29137330f729Sjoerg       if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
29147330f729Sjoerg         llvm::Value *V =
29157330f729Sjoerg             EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc());
29167330f729Sjoerg         if (isPromoted)
29177330f729Sjoerg           V = emitArgumentDemotion(*this, Arg, V);
29187330f729Sjoerg         ArgVals.push_back(ParamValue::forDirect(V));
29197330f729Sjoerg       } else {
29207330f729Sjoerg         ArgVals.push_back(ParamValue::forIndirect(Alloca));
29217330f729Sjoerg       }
29227330f729Sjoerg       break;
29237330f729Sjoerg     }
29247330f729Sjoerg 
29257330f729Sjoerg     case ABIArgInfo::CoerceAndExpand: {
29267330f729Sjoerg       // Reconstruct into a temporary.
29277330f729Sjoerg       Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
29287330f729Sjoerg       ArgVals.push_back(ParamValue::forIndirect(alloca));
29297330f729Sjoerg 
29307330f729Sjoerg       auto coercionType = ArgI.getCoerceAndExpandType();
29317330f729Sjoerg       alloca = Builder.CreateElementBitCast(alloca, coercionType);
29327330f729Sjoerg 
29337330f729Sjoerg       unsigned argIndex = FirstIRArg;
29347330f729Sjoerg       for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
29357330f729Sjoerg         llvm::Type *eltType = coercionType->getElementType(i);
29367330f729Sjoerg         if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
29377330f729Sjoerg           continue;
29387330f729Sjoerg 
29397330f729Sjoerg         auto eltAddr = Builder.CreateStructGEP(alloca, i);
2940*e038c9c4Sjoerg         auto elt = Fn->getArg(argIndex++);
29417330f729Sjoerg         Builder.CreateStore(elt, eltAddr);
29427330f729Sjoerg       }
29437330f729Sjoerg       assert(argIndex == FirstIRArg + NumIRArgs);
29447330f729Sjoerg       break;
29457330f729Sjoerg     }
29467330f729Sjoerg 
29477330f729Sjoerg     case ABIArgInfo::Expand: {
29487330f729Sjoerg       // If this structure was expanded into multiple arguments then
29497330f729Sjoerg       // we need to create a temporary and reconstruct it from the
29507330f729Sjoerg       // arguments.
29517330f729Sjoerg       Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
29527330f729Sjoerg       LValue LV = MakeAddrLValue(Alloca, Ty);
29537330f729Sjoerg       ArgVals.push_back(ParamValue::forIndirect(Alloca));
29547330f729Sjoerg 
2955*e038c9c4Sjoerg       auto FnArgIter = Fn->arg_begin() + FirstIRArg;
29567330f729Sjoerg       ExpandTypeFromArgs(Ty, LV, FnArgIter);
2957*e038c9c4Sjoerg       assert(FnArgIter == Fn->arg_begin() + FirstIRArg + NumIRArgs);
29587330f729Sjoerg       for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2959*e038c9c4Sjoerg         auto AI = Fn->getArg(FirstIRArg + i);
29607330f729Sjoerg         AI->setName(Arg->getName() + "." + Twine(i));
29617330f729Sjoerg       }
29627330f729Sjoerg       break;
29637330f729Sjoerg     }
29647330f729Sjoerg 
29657330f729Sjoerg     case ABIArgInfo::Ignore:
29667330f729Sjoerg       assert(NumIRArgs == 0);
29677330f729Sjoerg       // Initialize the local variable appropriately.
29687330f729Sjoerg       if (!hasScalarEvaluationKind(Ty)) {
29697330f729Sjoerg         ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
29707330f729Sjoerg       } else {
29717330f729Sjoerg         llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
29727330f729Sjoerg         ArgVals.push_back(ParamValue::forDirect(U));
29737330f729Sjoerg       }
29747330f729Sjoerg       break;
29757330f729Sjoerg     }
29767330f729Sjoerg   }
29777330f729Sjoerg 
29787330f729Sjoerg   if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
29797330f729Sjoerg     for (int I = Args.size() - 1; I >= 0; --I)
29807330f729Sjoerg       EmitParmDecl(*Args[I], ArgVals[I], I + 1);
29817330f729Sjoerg   } else {
29827330f729Sjoerg     for (unsigned I = 0, E = Args.size(); I != E; ++I)
29837330f729Sjoerg       EmitParmDecl(*Args[I], ArgVals[I], I + 1);
29847330f729Sjoerg   }
29857330f729Sjoerg }
29867330f729Sjoerg 
eraseUnusedBitCasts(llvm::Instruction * insn)29877330f729Sjoerg static void eraseUnusedBitCasts(llvm::Instruction *insn) {
29887330f729Sjoerg   while (insn->use_empty()) {
29897330f729Sjoerg     llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
29907330f729Sjoerg     if (!bitcast) return;
29917330f729Sjoerg 
29927330f729Sjoerg     // This is "safe" because we would have used a ConstantExpr otherwise.
29937330f729Sjoerg     insn = cast<llvm::Instruction>(bitcast->getOperand(0));
29947330f729Sjoerg     bitcast->eraseFromParent();
29957330f729Sjoerg   }
29967330f729Sjoerg }
29977330f729Sjoerg 
29987330f729Sjoerg /// Try to emit a fused autorelease of a return result.
tryEmitFusedAutoreleaseOfResult(CodeGenFunction & CGF,llvm::Value * result)29997330f729Sjoerg static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
30007330f729Sjoerg                                                     llvm::Value *result) {
30017330f729Sjoerg   // We must be immediately followed the cast.
30027330f729Sjoerg   llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
30037330f729Sjoerg   if (BB->empty()) return nullptr;
30047330f729Sjoerg   if (&BB->back() != result) return nullptr;
30057330f729Sjoerg 
30067330f729Sjoerg   llvm::Type *resultType = result->getType();
30077330f729Sjoerg 
30087330f729Sjoerg   // result is in a BasicBlock and is therefore an Instruction.
30097330f729Sjoerg   llvm::Instruction *generator = cast<llvm::Instruction>(result);
30107330f729Sjoerg 
30117330f729Sjoerg   SmallVector<llvm::Instruction *, 4> InstsToKill;
30127330f729Sjoerg 
30137330f729Sjoerg   // Look for:
30147330f729Sjoerg   //  %generator = bitcast %type1* %generator2 to %type2*
30157330f729Sjoerg   while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
30167330f729Sjoerg     // We would have emitted this as a constant if the operand weren't
30177330f729Sjoerg     // an Instruction.
30187330f729Sjoerg     generator = cast<llvm::Instruction>(bitcast->getOperand(0));
30197330f729Sjoerg 
30207330f729Sjoerg     // Require the generator to be immediately followed by the cast.
30217330f729Sjoerg     if (generator->getNextNode() != bitcast)
30227330f729Sjoerg       return nullptr;
30237330f729Sjoerg 
30247330f729Sjoerg     InstsToKill.push_back(bitcast);
30257330f729Sjoerg   }
30267330f729Sjoerg 
30277330f729Sjoerg   // Look for:
30287330f729Sjoerg   //   %generator = call i8* @objc_retain(i8* %originalResult)
30297330f729Sjoerg   // or
30307330f729Sjoerg   //   %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
30317330f729Sjoerg   llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
30327330f729Sjoerg   if (!call) return nullptr;
30337330f729Sjoerg 
30347330f729Sjoerg   bool doRetainAutorelease;
30357330f729Sjoerg 
3036*e038c9c4Sjoerg   if (call->getCalledOperand() == CGF.CGM.getObjCEntrypoints().objc_retain) {
30377330f729Sjoerg     doRetainAutorelease = true;
3038*e038c9c4Sjoerg   } else if (call->getCalledOperand() ==
3039*e038c9c4Sjoerg              CGF.CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue) {
30407330f729Sjoerg     doRetainAutorelease = false;
30417330f729Sjoerg 
30427330f729Sjoerg     // If we emitted an assembly marker for this call (and the
30437330f729Sjoerg     // ARCEntrypoints field should have been set if so), go looking
30447330f729Sjoerg     // for that call.  If we can't find it, we can't do this
30457330f729Sjoerg     // optimization.  But it should always be the immediately previous
30467330f729Sjoerg     // instruction, unless we needed bitcasts around the call.
30477330f729Sjoerg     if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
30487330f729Sjoerg       llvm::Instruction *prev = call->getPrevNode();
30497330f729Sjoerg       assert(prev);
30507330f729Sjoerg       if (isa<llvm::BitCastInst>(prev)) {
30517330f729Sjoerg         prev = prev->getPrevNode();
30527330f729Sjoerg         assert(prev);
30537330f729Sjoerg       }
30547330f729Sjoerg       assert(isa<llvm::CallInst>(prev));
3055*e038c9c4Sjoerg       assert(cast<llvm::CallInst>(prev)->getCalledOperand() ==
30567330f729Sjoerg              CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
30577330f729Sjoerg       InstsToKill.push_back(prev);
30587330f729Sjoerg     }
30597330f729Sjoerg   } else {
30607330f729Sjoerg     return nullptr;
30617330f729Sjoerg   }
30627330f729Sjoerg 
30637330f729Sjoerg   result = call->getArgOperand(0);
30647330f729Sjoerg   InstsToKill.push_back(call);
30657330f729Sjoerg 
30667330f729Sjoerg   // Keep killing bitcasts, for sanity.  Note that we no longer care
30677330f729Sjoerg   // about precise ordering as long as there's exactly one use.
30687330f729Sjoerg   while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
30697330f729Sjoerg     if (!bitcast->hasOneUse()) break;
30707330f729Sjoerg     InstsToKill.push_back(bitcast);
30717330f729Sjoerg     result = bitcast->getOperand(0);
30727330f729Sjoerg   }
30737330f729Sjoerg 
30747330f729Sjoerg   // Delete all the unnecessary instructions, from latest to earliest.
30757330f729Sjoerg   for (auto *I : InstsToKill)
30767330f729Sjoerg     I->eraseFromParent();
30777330f729Sjoerg 
30787330f729Sjoerg   // Do the fused retain/autorelease if we were asked to.
30797330f729Sjoerg   if (doRetainAutorelease)
30807330f729Sjoerg     result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
30817330f729Sjoerg 
30827330f729Sjoerg   // Cast back to the result type.
30837330f729Sjoerg   return CGF.Builder.CreateBitCast(result, resultType);
30847330f729Sjoerg }
30857330f729Sjoerg 
30867330f729Sjoerg /// If this is a +1 of the value of an immutable 'self', remove it.
tryRemoveRetainOfSelf(CodeGenFunction & CGF,llvm::Value * result)30877330f729Sjoerg static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
30887330f729Sjoerg                                           llvm::Value *result) {
30897330f729Sjoerg   // This is only applicable to a method with an immutable 'self'.
30907330f729Sjoerg   const ObjCMethodDecl *method =
30917330f729Sjoerg     dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
30927330f729Sjoerg   if (!method) return nullptr;
30937330f729Sjoerg   const VarDecl *self = method->getSelfDecl();
30947330f729Sjoerg   if (!self->getType().isConstQualified()) return nullptr;
30957330f729Sjoerg 
30967330f729Sjoerg   // Look for a retain call.
30977330f729Sjoerg   llvm::CallInst *retainCall =
30987330f729Sjoerg     dyn_cast<llvm::CallInst>(result->stripPointerCasts());
3099*e038c9c4Sjoerg   if (!retainCall || retainCall->getCalledOperand() !=
3100*e038c9c4Sjoerg                          CGF.CGM.getObjCEntrypoints().objc_retain)
31017330f729Sjoerg     return nullptr;
31027330f729Sjoerg 
31037330f729Sjoerg   // Look for an ordinary load of 'self'.
31047330f729Sjoerg   llvm::Value *retainedValue = retainCall->getArgOperand(0);
31057330f729Sjoerg   llvm::LoadInst *load =
31067330f729Sjoerg     dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
31077330f729Sjoerg   if (!load || load->isAtomic() || load->isVolatile() ||
31087330f729Sjoerg       load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
31097330f729Sjoerg     return nullptr;
31107330f729Sjoerg 
31117330f729Sjoerg   // Okay!  Burn it all down.  This relies for correctness on the
31127330f729Sjoerg   // assumption that the retain is emitted as part of the return and
31137330f729Sjoerg   // that thereafter everything is used "linearly".
31147330f729Sjoerg   llvm::Type *resultType = result->getType();
31157330f729Sjoerg   eraseUnusedBitCasts(cast<llvm::Instruction>(result));
31167330f729Sjoerg   assert(retainCall->use_empty());
31177330f729Sjoerg   retainCall->eraseFromParent();
31187330f729Sjoerg   eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
31197330f729Sjoerg 
31207330f729Sjoerg   return CGF.Builder.CreateBitCast(load, resultType);
31217330f729Sjoerg }
31227330f729Sjoerg 
31237330f729Sjoerg /// Emit an ARC autorelease of the result of a function.
31247330f729Sjoerg ///
31257330f729Sjoerg /// \return the value to actually return from the function
emitAutoreleaseOfResult(CodeGenFunction & CGF,llvm::Value * result)31267330f729Sjoerg static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
31277330f729Sjoerg                                             llvm::Value *result) {
31287330f729Sjoerg   // If we're returning 'self', kill the initial retain.  This is a
31297330f729Sjoerg   // heuristic attempt to "encourage correctness" in the really unfortunate
31307330f729Sjoerg   // case where we have a return of self during a dealloc and we desperately
31317330f729Sjoerg   // need to avoid the possible autorelease.
31327330f729Sjoerg   if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
31337330f729Sjoerg     return self;
31347330f729Sjoerg 
31357330f729Sjoerg   // At -O0, try to emit a fused retain/autorelease.
31367330f729Sjoerg   if (CGF.shouldUseFusedARCCalls())
31377330f729Sjoerg     if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
31387330f729Sjoerg       return fused;
31397330f729Sjoerg 
31407330f729Sjoerg   return CGF.EmitARCAutoreleaseReturnValue(result);
31417330f729Sjoerg }
31427330f729Sjoerg 
31437330f729Sjoerg /// Heuristically search for a dominating store to the return-value slot.
findDominatingStoreToReturnValue(CodeGenFunction & CGF)31447330f729Sjoerg static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
31457330f729Sjoerg   // Check if a User is a store which pointerOperand is the ReturnValue.
31467330f729Sjoerg   // We are looking for stores to the ReturnValue, not for stores of the
31477330f729Sjoerg   // ReturnValue to some other location.
31487330f729Sjoerg   auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
31497330f729Sjoerg     auto *SI = dyn_cast<llvm::StoreInst>(U);
31507330f729Sjoerg     if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
31517330f729Sjoerg       return nullptr;
31527330f729Sjoerg     // These aren't actually possible for non-coerced returns, and we
31537330f729Sjoerg     // only care about non-coerced returns on this code path.
31547330f729Sjoerg     assert(!SI->isAtomic() && !SI->isVolatile());
31557330f729Sjoerg     return SI;
31567330f729Sjoerg   };
31577330f729Sjoerg   // If there are multiple uses of the return-value slot, just check
31587330f729Sjoerg   // for something immediately preceding the IP.  Sometimes this can
31597330f729Sjoerg   // happen with how we generate implicit-returns; it can also happen
31607330f729Sjoerg   // with noreturn cleanups.
31617330f729Sjoerg   if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
31627330f729Sjoerg     llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
31637330f729Sjoerg     if (IP->empty()) return nullptr;
31647330f729Sjoerg     llvm::Instruction *I = &IP->back();
31657330f729Sjoerg 
31667330f729Sjoerg     // Skip lifetime markers
31677330f729Sjoerg     for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
31687330f729Sjoerg                                             IE = IP->rend();
31697330f729Sjoerg          II != IE; ++II) {
31707330f729Sjoerg       if (llvm::IntrinsicInst *Intrinsic =
31717330f729Sjoerg               dyn_cast<llvm::IntrinsicInst>(&*II)) {
31727330f729Sjoerg         if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
31737330f729Sjoerg           const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
31747330f729Sjoerg           ++II;
31757330f729Sjoerg           if (II == IE)
31767330f729Sjoerg             break;
31777330f729Sjoerg           if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
31787330f729Sjoerg             continue;
31797330f729Sjoerg         }
31807330f729Sjoerg       }
31817330f729Sjoerg       I = &*II;
31827330f729Sjoerg       break;
31837330f729Sjoerg     }
31847330f729Sjoerg 
31857330f729Sjoerg     return GetStoreIfValid(I);
31867330f729Sjoerg   }
31877330f729Sjoerg 
31887330f729Sjoerg   llvm::StoreInst *store =
31897330f729Sjoerg       GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
31907330f729Sjoerg   if (!store) return nullptr;
31917330f729Sjoerg 
31927330f729Sjoerg   // Now do a first-and-dirty dominance check: just walk up the
31937330f729Sjoerg   // single-predecessors chain from the current insertion point.
31947330f729Sjoerg   llvm::BasicBlock *StoreBB = store->getParent();
31957330f729Sjoerg   llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
31967330f729Sjoerg   while (IP != StoreBB) {
31977330f729Sjoerg     if (!(IP = IP->getSinglePredecessor()))
31987330f729Sjoerg       return nullptr;
31997330f729Sjoerg   }
32007330f729Sjoerg 
32017330f729Sjoerg   // Okay, the store's basic block dominates the insertion point; we
32027330f729Sjoerg   // can do our thing.
32037330f729Sjoerg   return store;
32047330f729Sjoerg }
32057330f729Sjoerg 
3206*e038c9c4Sjoerg // Helper functions for EmitCMSEClearRecord
3207*e038c9c4Sjoerg 
3208*e038c9c4Sjoerg // Set the bits corresponding to a field having width `BitWidth` and located at
3209*e038c9c4Sjoerg // offset `BitOffset` (from the least significant bit) within a storage unit of
3210*e038c9c4Sjoerg // `Bits.size()` bytes. Each element of `Bits` corresponds to one target byte.
3211*e038c9c4Sjoerg // Use little-endian layout, i.e.`Bits[0]` is the LSB.
setBitRange(SmallVectorImpl<uint64_t> & Bits,int BitOffset,int BitWidth,int CharWidth)3212*e038c9c4Sjoerg static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int BitOffset,
3213*e038c9c4Sjoerg                         int BitWidth, int CharWidth) {
3214*e038c9c4Sjoerg   assert(CharWidth <= 64);
3215*e038c9c4Sjoerg   assert(static_cast<unsigned>(BitWidth) <= Bits.size() * CharWidth);
3216*e038c9c4Sjoerg 
3217*e038c9c4Sjoerg   int Pos = 0;
3218*e038c9c4Sjoerg   if (BitOffset >= CharWidth) {
3219*e038c9c4Sjoerg     Pos += BitOffset / CharWidth;
3220*e038c9c4Sjoerg     BitOffset = BitOffset % CharWidth;
3221*e038c9c4Sjoerg   }
3222*e038c9c4Sjoerg 
3223*e038c9c4Sjoerg   const uint64_t Used = (uint64_t(1) << CharWidth) - 1;
3224*e038c9c4Sjoerg   if (BitOffset + BitWidth >= CharWidth) {
3225*e038c9c4Sjoerg     Bits[Pos++] |= (Used << BitOffset) & Used;
3226*e038c9c4Sjoerg     BitWidth -= CharWidth - BitOffset;
3227*e038c9c4Sjoerg     BitOffset = 0;
3228*e038c9c4Sjoerg   }
3229*e038c9c4Sjoerg 
3230*e038c9c4Sjoerg   while (BitWidth >= CharWidth) {
3231*e038c9c4Sjoerg     Bits[Pos++] = Used;
3232*e038c9c4Sjoerg     BitWidth -= CharWidth;
3233*e038c9c4Sjoerg   }
3234*e038c9c4Sjoerg 
3235*e038c9c4Sjoerg   if (BitWidth > 0)
3236*e038c9c4Sjoerg     Bits[Pos++] |= (Used >> (CharWidth - BitWidth)) << BitOffset;
3237*e038c9c4Sjoerg }
3238*e038c9c4Sjoerg 
3239*e038c9c4Sjoerg // Set the bits corresponding to a field having width `BitWidth` and located at
3240*e038c9c4Sjoerg // offset `BitOffset` (from the least significant bit) within a storage unit of
3241*e038c9c4Sjoerg // `StorageSize` bytes, located at `StorageOffset` in `Bits`. Each element of
3242*e038c9c4Sjoerg // `Bits` corresponds to one target byte. Use target endian layout.
setBitRange(SmallVectorImpl<uint64_t> & Bits,int StorageOffset,int StorageSize,int BitOffset,int BitWidth,int CharWidth,bool BigEndian)3243*e038c9c4Sjoerg static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int StorageOffset,
3244*e038c9c4Sjoerg                         int StorageSize, int BitOffset, int BitWidth,
3245*e038c9c4Sjoerg                         int CharWidth, bool BigEndian) {
3246*e038c9c4Sjoerg 
3247*e038c9c4Sjoerg   SmallVector<uint64_t, 8> TmpBits(StorageSize);
3248*e038c9c4Sjoerg   setBitRange(TmpBits, BitOffset, BitWidth, CharWidth);
3249*e038c9c4Sjoerg 
3250*e038c9c4Sjoerg   if (BigEndian)
3251*e038c9c4Sjoerg     std::reverse(TmpBits.begin(), TmpBits.end());
3252*e038c9c4Sjoerg 
3253*e038c9c4Sjoerg   for (uint64_t V : TmpBits)
3254*e038c9c4Sjoerg     Bits[StorageOffset++] |= V;
3255*e038c9c4Sjoerg }
3256*e038c9c4Sjoerg 
3257*e038c9c4Sjoerg static void setUsedBits(CodeGenModule &, QualType, int,
3258*e038c9c4Sjoerg                         SmallVectorImpl<uint64_t> &);
3259*e038c9c4Sjoerg 
3260*e038c9c4Sjoerg // Set the bits in `Bits`, which correspond to the value representations of
3261*e038c9c4Sjoerg // the actual members of the record type `RTy`. Note that this function does
3262*e038c9c4Sjoerg // not handle base classes, virtual tables, etc, since they cannot happen in
3263*e038c9c4Sjoerg // CMSE function arguments or return. The bit mask corresponds to the target
3264*e038c9c4Sjoerg // memory layout, i.e. it's endian dependent.
setUsedBits(CodeGenModule & CGM,const RecordType * RTy,int Offset,SmallVectorImpl<uint64_t> & Bits)3265*e038c9c4Sjoerg static void setUsedBits(CodeGenModule &CGM, const RecordType *RTy, int Offset,
3266*e038c9c4Sjoerg                         SmallVectorImpl<uint64_t> &Bits) {
3267*e038c9c4Sjoerg   ASTContext &Context = CGM.getContext();
3268*e038c9c4Sjoerg   int CharWidth = Context.getCharWidth();
3269*e038c9c4Sjoerg   const RecordDecl *RD = RTy->getDecl()->getDefinition();
3270*e038c9c4Sjoerg   const ASTRecordLayout &ASTLayout = Context.getASTRecordLayout(RD);
3271*e038c9c4Sjoerg   const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(RD);
3272*e038c9c4Sjoerg 
3273*e038c9c4Sjoerg   int Idx = 0;
3274*e038c9c4Sjoerg   for (auto I = RD->field_begin(), E = RD->field_end(); I != E; ++I, ++Idx) {
3275*e038c9c4Sjoerg     const FieldDecl *F = *I;
3276*e038c9c4Sjoerg 
3277*e038c9c4Sjoerg     if (F->isUnnamedBitfield() || F->isZeroLengthBitField(Context) ||
3278*e038c9c4Sjoerg         F->getType()->isIncompleteArrayType())
3279*e038c9c4Sjoerg       continue;
3280*e038c9c4Sjoerg 
3281*e038c9c4Sjoerg     if (F->isBitField()) {
3282*e038c9c4Sjoerg       const CGBitFieldInfo &BFI = Layout.getBitFieldInfo(F);
3283*e038c9c4Sjoerg       setBitRange(Bits, Offset + BFI.StorageOffset.getQuantity(),
3284*e038c9c4Sjoerg                   BFI.StorageSize / CharWidth, BFI.Offset,
3285*e038c9c4Sjoerg                   BFI.Size, CharWidth,
3286*e038c9c4Sjoerg                   CGM.getDataLayout().isBigEndian());
3287*e038c9c4Sjoerg       continue;
3288*e038c9c4Sjoerg     }
3289*e038c9c4Sjoerg 
3290*e038c9c4Sjoerg     setUsedBits(CGM, F->getType(),
3291*e038c9c4Sjoerg                 Offset + ASTLayout.getFieldOffset(Idx) / CharWidth, Bits);
3292*e038c9c4Sjoerg   }
3293*e038c9c4Sjoerg }
3294*e038c9c4Sjoerg 
3295*e038c9c4Sjoerg // Set the bits in `Bits`, which correspond to the value representations of
3296*e038c9c4Sjoerg // the elements of an array type `ATy`.
setUsedBits(CodeGenModule & CGM,const ConstantArrayType * ATy,int Offset,SmallVectorImpl<uint64_t> & Bits)3297*e038c9c4Sjoerg static void setUsedBits(CodeGenModule &CGM, const ConstantArrayType *ATy,
3298*e038c9c4Sjoerg                         int Offset, SmallVectorImpl<uint64_t> &Bits) {
3299*e038c9c4Sjoerg   const ASTContext &Context = CGM.getContext();
3300*e038c9c4Sjoerg 
3301*e038c9c4Sjoerg   QualType ETy = Context.getBaseElementType(ATy);
3302*e038c9c4Sjoerg   int Size = Context.getTypeSizeInChars(ETy).getQuantity();
3303*e038c9c4Sjoerg   SmallVector<uint64_t, 4> TmpBits(Size);
3304*e038c9c4Sjoerg   setUsedBits(CGM, ETy, 0, TmpBits);
3305*e038c9c4Sjoerg 
3306*e038c9c4Sjoerg   for (int I = 0, N = Context.getConstantArrayElementCount(ATy); I < N; ++I) {
3307*e038c9c4Sjoerg     auto Src = TmpBits.begin();
3308*e038c9c4Sjoerg     auto Dst = Bits.begin() + Offset + I * Size;
3309*e038c9c4Sjoerg     for (int J = 0; J < Size; ++J)
3310*e038c9c4Sjoerg       *Dst++ |= *Src++;
3311*e038c9c4Sjoerg   }
3312*e038c9c4Sjoerg }
3313*e038c9c4Sjoerg 
3314*e038c9c4Sjoerg // Set the bits in `Bits`, which correspond to the value representations of
3315*e038c9c4Sjoerg // the type `QTy`.
setUsedBits(CodeGenModule & CGM,QualType QTy,int Offset,SmallVectorImpl<uint64_t> & Bits)3316*e038c9c4Sjoerg static void setUsedBits(CodeGenModule &CGM, QualType QTy, int Offset,
3317*e038c9c4Sjoerg                         SmallVectorImpl<uint64_t> &Bits) {
3318*e038c9c4Sjoerg   if (const auto *RTy = QTy->getAs<RecordType>())
3319*e038c9c4Sjoerg     return setUsedBits(CGM, RTy, Offset, Bits);
3320*e038c9c4Sjoerg 
3321*e038c9c4Sjoerg   ASTContext &Context = CGM.getContext();
3322*e038c9c4Sjoerg   if (const auto *ATy = Context.getAsConstantArrayType(QTy))
3323*e038c9c4Sjoerg     return setUsedBits(CGM, ATy, Offset, Bits);
3324*e038c9c4Sjoerg 
3325*e038c9c4Sjoerg   int Size = Context.getTypeSizeInChars(QTy).getQuantity();
3326*e038c9c4Sjoerg   if (Size <= 0)
3327*e038c9c4Sjoerg     return;
3328*e038c9c4Sjoerg 
3329*e038c9c4Sjoerg   std::fill_n(Bits.begin() + Offset, Size,
3330*e038c9c4Sjoerg               (uint64_t(1) << Context.getCharWidth()) - 1);
3331*e038c9c4Sjoerg }
3332*e038c9c4Sjoerg 
buildMultiCharMask(const SmallVectorImpl<uint64_t> & Bits,int Pos,int Size,int CharWidth,bool BigEndian)3333*e038c9c4Sjoerg static uint64_t buildMultiCharMask(const SmallVectorImpl<uint64_t> &Bits,
3334*e038c9c4Sjoerg                                    int Pos, int Size, int CharWidth,
3335*e038c9c4Sjoerg                                    bool BigEndian) {
3336*e038c9c4Sjoerg   assert(Size > 0);
3337*e038c9c4Sjoerg   uint64_t Mask = 0;
3338*e038c9c4Sjoerg   if (BigEndian) {
3339*e038c9c4Sjoerg     for (auto P = Bits.begin() + Pos, E = Bits.begin() + Pos + Size; P != E;
3340*e038c9c4Sjoerg          ++P)
3341*e038c9c4Sjoerg       Mask = (Mask << CharWidth) | *P;
3342*e038c9c4Sjoerg   } else {
3343*e038c9c4Sjoerg     auto P = Bits.begin() + Pos + Size, End = Bits.begin() + Pos;
3344*e038c9c4Sjoerg     do
3345*e038c9c4Sjoerg       Mask = (Mask << CharWidth) | *--P;
3346*e038c9c4Sjoerg     while (P != End);
3347*e038c9c4Sjoerg   }
3348*e038c9c4Sjoerg   return Mask;
3349*e038c9c4Sjoerg }
3350*e038c9c4Sjoerg 
3351*e038c9c4Sjoerg // Emit code to clear the bits in a record, which aren't a part of any user
3352*e038c9c4Sjoerg // declared member, when the record is a function return.
EmitCMSEClearRecord(llvm::Value * Src,llvm::IntegerType * ITy,QualType QTy)3353*e038c9c4Sjoerg llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3354*e038c9c4Sjoerg                                                   llvm::IntegerType *ITy,
3355*e038c9c4Sjoerg                                                   QualType QTy) {
3356*e038c9c4Sjoerg   assert(Src->getType() == ITy);
3357*e038c9c4Sjoerg   assert(ITy->getScalarSizeInBits() <= 64);
3358*e038c9c4Sjoerg 
3359*e038c9c4Sjoerg   const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3360*e038c9c4Sjoerg   int Size = DataLayout.getTypeStoreSize(ITy);
3361*e038c9c4Sjoerg   SmallVector<uint64_t, 4> Bits(Size);
3362*e038c9c4Sjoerg   setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
3363*e038c9c4Sjoerg 
3364*e038c9c4Sjoerg   int CharWidth = CGM.getContext().getCharWidth();
3365*e038c9c4Sjoerg   uint64_t Mask =
3366*e038c9c4Sjoerg       buildMultiCharMask(Bits, 0, Size, CharWidth, DataLayout.isBigEndian());
3367*e038c9c4Sjoerg 
3368*e038c9c4Sjoerg   return Builder.CreateAnd(Src, Mask, "cmse.clear");
3369*e038c9c4Sjoerg }
3370*e038c9c4Sjoerg 
3371*e038c9c4Sjoerg // Emit code to clear the bits in a record, which aren't a part of any user
3372*e038c9c4Sjoerg // declared member, when the record is a function argument.
EmitCMSEClearRecord(llvm::Value * Src,llvm::ArrayType * ATy,QualType QTy)3373*e038c9c4Sjoerg llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3374*e038c9c4Sjoerg                                                   llvm::ArrayType *ATy,
3375*e038c9c4Sjoerg                                                   QualType QTy) {
3376*e038c9c4Sjoerg   const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3377*e038c9c4Sjoerg   int Size = DataLayout.getTypeStoreSize(ATy);
3378*e038c9c4Sjoerg   SmallVector<uint64_t, 16> Bits(Size);
3379*e038c9c4Sjoerg   setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
3380*e038c9c4Sjoerg 
3381*e038c9c4Sjoerg   // Clear each element of the LLVM array.
3382*e038c9c4Sjoerg   int CharWidth = CGM.getContext().getCharWidth();
3383*e038c9c4Sjoerg   int CharsPerElt =
3384*e038c9c4Sjoerg       ATy->getArrayElementType()->getScalarSizeInBits() / CharWidth;
3385*e038c9c4Sjoerg   int MaskIndex = 0;
3386*e038c9c4Sjoerg   llvm::Value *R = llvm::UndefValue::get(ATy);
3387*e038c9c4Sjoerg   for (int I = 0, N = ATy->getArrayNumElements(); I != N; ++I) {
3388*e038c9c4Sjoerg     uint64_t Mask = buildMultiCharMask(Bits, MaskIndex, CharsPerElt, CharWidth,
3389*e038c9c4Sjoerg                                        DataLayout.isBigEndian());
3390*e038c9c4Sjoerg     MaskIndex += CharsPerElt;
3391*e038c9c4Sjoerg     llvm::Value *T0 = Builder.CreateExtractValue(Src, I);
3392*e038c9c4Sjoerg     llvm::Value *T1 = Builder.CreateAnd(T0, Mask, "cmse.clear");
3393*e038c9c4Sjoerg     R = Builder.CreateInsertValue(R, T1, I);
3394*e038c9c4Sjoerg   }
3395*e038c9c4Sjoerg 
3396*e038c9c4Sjoerg   return R;
3397*e038c9c4Sjoerg }
3398*e038c9c4Sjoerg 
EmitFunctionEpilog(const CGFunctionInfo & FI,bool EmitRetDbgLoc,SourceLocation EndLoc)33997330f729Sjoerg void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
34007330f729Sjoerg                                          bool EmitRetDbgLoc,
34017330f729Sjoerg                                          SourceLocation EndLoc) {
34027330f729Sjoerg   if (FI.isNoReturn()) {
34037330f729Sjoerg     // Noreturn functions don't return.
34047330f729Sjoerg     EmitUnreachable(EndLoc);
34057330f729Sjoerg     return;
34067330f729Sjoerg   }
34077330f729Sjoerg 
34087330f729Sjoerg   if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
34097330f729Sjoerg     // Naked functions don't have epilogues.
34107330f729Sjoerg     Builder.CreateUnreachable();
34117330f729Sjoerg     return;
34127330f729Sjoerg   }
34137330f729Sjoerg 
34147330f729Sjoerg   // Functions with no result always return void.
34157330f729Sjoerg   if (!ReturnValue.isValid()) {
34167330f729Sjoerg     Builder.CreateRetVoid();
34177330f729Sjoerg     return;
34187330f729Sjoerg   }
34197330f729Sjoerg 
34207330f729Sjoerg   llvm::DebugLoc RetDbgLoc;
34217330f729Sjoerg   llvm::Value *RV = nullptr;
34227330f729Sjoerg   QualType RetTy = FI.getReturnType();
34237330f729Sjoerg   const ABIArgInfo &RetAI = FI.getReturnInfo();
34247330f729Sjoerg 
34257330f729Sjoerg   switch (RetAI.getKind()) {
34267330f729Sjoerg   case ABIArgInfo::InAlloca:
34277330f729Sjoerg     // Aggregrates get evaluated directly into the destination.  Sometimes we
34287330f729Sjoerg     // need to return the sret value in a register, though.
34297330f729Sjoerg     assert(hasAggregateEvaluationKind(RetTy));
34307330f729Sjoerg     if (RetAI.getInAllocaSRet()) {
34317330f729Sjoerg       llvm::Function::arg_iterator EI = CurFn->arg_end();
34327330f729Sjoerg       --EI;
34337330f729Sjoerg       llvm::Value *ArgStruct = &*EI;
34347330f729Sjoerg       llvm::Value *SRet = Builder.CreateStructGEP(
34357330f729Sjoerg           nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
3436*e038c9c4Sjoerg       llvm::Type *Ty =
3437*e038c9c4Sjoerg           cast<llvm::GetElementPtrInst>(SRet)->getResultElementType();
3438*e038c9c4Sjoerg       RV = Builder.CreateAlignedLoad(Ty, SRet, getPointerAlign(), "sret");
34397330f729Sjoerg     }
34407330f729Sjoerg     break;
34417330f729Sjoerg 
34427330f729Sjoerg   case ABIArgInfo::Indirect: {
34437330f729Sjoerg     auto AI = CurFn->arg_begin();
34447330f729Sjoerg     if (RetAI.isSRetAfterThis())
34457330f729Sjoerg       ++AI;
34467330f729Sjoerg     switch (getEvaluationKind(RetTy)) {
34477330f729Sjoerg     case TEK_Complex: {
34487330f729Sjoerg       ComplexPairTy RT =
34497330f729Sjoerg         EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
34507330f729Sjoerg       EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
34517330f729Sjoerg                          /*isInit*/ true);
34527330f729Sjoerg       break;
34537330f729Sjoerg     }
34547330f729Sjoerg     case TEK_Aggregate:
34557330f729Sjoerg       // Do nothing; aggregrates get evaluated directly into the destination.
34567330f729Sjoerg       break;
34577330f729Sjoerg     case TEK_Scalar:
34587330f729Sjoerg       EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
34597330f729Sjoerg                         MakeNaturalAlignAddrLValue(&*AI, RetTy),
34607330f729Sjoerg                         /*isInit*/ true);
34617330f729Sjoerg       break;
34627330f729Sjoerg     }
34637330f729Sjoerg     break;
34647330f729Sjoerg   }
34657330f729Sjoerg 
34667330f729Sjoerg   case ABIArgInfo::Extend:
34677330f729Sjoerg   case ABIArgInfo::Direct:
34687330f729Sjoerg     if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
34697330f729Sjoerg         RetAI.getDirectOffset() == 0) {
34707330f729Sjoerg       // The internal return value temp always will have pointer-to-return-type
34717330f729Sjoerg       // type, just do a load.
34727330f729Sjoerg 
34737330f729Sjoerg       // If there is a dominating store to ReturnValue, we can elide
34747330f729Sjoerg       // the load, zap the store, and usually zap the alloca.
34757330f729Sjoerg       if (llvm::StoreInst *SI =
34767330f729Sjoerg               findDominatingStoreToReturnValue(*this)) {
34777330f729Sjoerg         // Reuse the debug location from the store unless there is
34787330f729Sjoerg         // cleanup code to be emitted between the store and return
34797330f729Sjoerg         // instruction.
34807330f729Sjoerg         if (EmitRetDbgLoc && !AutoreleaseResult)
34817330f729Sjoerg           RetDbgLoc = SI->getDebugLoc();
34827330f729Sjoerg         // Get the stored value and nuke the now-dead store.
34837330f729Sjoerg         RV = SI->getValueOperand();
34847330f729Sjoerg         SI->eraseFromParent();
34857330f729Sjoerg 
34867330f729Sjoerg       // Otherwise, we have to do a simple load.
34877330f729Sjoerg       } else {
34887330f729Sjoerg         RV = Builder.CreateLoad(ReturnValue);
34897330f729Sjoerg       }
34907330f729Sjoerg     } else {
34917330f729Sjoerg       // If the value is offset in memory, apply the offset now.
34927330f729Sjoerg       Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
34937330f729Sjoerg 
34947330f729Sjoerg       RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
34957330f729Sjoerg     }
34967330f729Sjoerg 
34977330f729Sjoerg     // In ARC, end functions that return a retainable type with a call
34987330f729Sjoerg     // to objc_autoreleaseReturnValue.
34997330f729Sjoerg     if (AutoreleaseResult) {
35007330f729Sjoerg #ifndef NDEBUG
35017330f729Sjoerg       // Type::isObjCRetainabletype has to be called on a QualType that hasn't
35027330f729Sjoerg       // been stripped of the typedefs, so we cannot use RetTy here. Get the
35037330f729Sjoerg       // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
35047330f729Sjoerg       // CurCodeDecl or BlockInfo.
35057330f729Sjoerg       QualType RT;
35067330f729Sjoerg 
35077330f729Sjoerg       if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
35087330f729Sjoerg         RT = FD->getReturnType();
35097330f729Sjoerg       else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
35107330f729Sjoerg         RT = MD->getReturnType();
35117330f729Sjoerg       else if (isa<BlockDecl>(CurCodeDecl))
35127330f729Sjoerg         RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
35137330f729Sjoerg       else
35147330f729Sjoerg         llvm_unreachable("Unexpected function/method type");
35157330f729Sjoerg 
35167330f729Sjoerg       assert(getLangOpts().ObjCAutoRefCount &&
35177330f729Sjoerg              !FI.isReturnsRetained() &&
35187330f729Sjoerg              RT->isObjCRetainableType());
35197330f729Sjoerg #endif
35207330f729Sjoerg       RV = emitAutoreleaseOfResult(*this, RV);
35217330f729Sjoerg     }
35227330f729Sjoerg 
35237330f729Sjoerg     break;
35247330f729Sjoerg 
35257330f729Sjoerg   case ABIArgInfo::Ignore:
35267330f729Sjoerg     break;
35277330f729Sjoerg 
35287330f729Sjoerg   case ABIArgInfo::CoerceAndExpand: {
35297330f729Sjoerg     auto coercionType = RetAI.getCoerceAndExpandType();
35307330f729Sjoerg 
35317330f729Sjoerg     // Load all of the coerced elements out into results.
35327330f729Sjoerg     llvm::SmallVector<llvm::Value*, 4> results;
35337330f729Sjoerg     Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
35347330f729Sjoerg     for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
35357330f729Sjoerg       auto coercedEltType = coercionType->getElementType(i);
35367330f729Sjoerg       if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
35377330f729Sjoerg         continue;
35387330f729Sjoerg 
35397330f729Sjoerg       auto eltAddr = Builder.CreateStructGEP(addr, i);
35407330f729Sjoerg       auto elt = Builder.CreateLoad(eltAddr);
35417330f729Sjoerg       results.push_back(elt);
35427330f729Sjoerg     }
35437330f729Sjoerg 
35447330f729Sjoerg     // If we have one result, it's the single direct result type.
35457330f729Sjoerg     if (results.size() == 1) {
35467330f729Sjoerg       RV = results[0];
35477330f729Sjoerg 
35487330f729Sjoerg     // Otherwise, we need to make a first-class aggregate.
35497330f729Sjoerg     } else {
35507330f729Sjoerg       // Construct a return type that lacks padding elements.
35517330f729Sjoerg       llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
35527330f729Sjoerg 
35537330f729Sjoerg       RV = llvm::UndefValue::get(returnType);
35547330f729Sjoerg       for (unsigned i = 0, e = results.size(); i != e; ++i) {
35557330f729Sjoerg         RV = Builder.CreateInsertValue(RV, results[i], i);
35567330f729Sjoerg       }
35577330f729Sjoerg     }
35587330f729Sjoerg     break;
35597330f729Sjoerg   }
35607330f729Sjoerg   case ABIArgInfo::Expand:
3561*e038c9c4Sjoerg   case ABIArgInfo::IndirectAliased:
35627330f729Sjoerg     llvm_unreachable("Invalid ABI kind for return argument");
35637330f729Sjoerg   }
35647330f729Sjoerg 
35657330f729Sjoerg   llvm::Instruction *Ret;
35667330f729Sjoerg   if (RV) {
3567*e038c9c4Sjoerg     if (CurFuncDecl && CurFuncDecl->hasAttr<CmseNSEntryAttr>()) {
3568*e038c9c4Sjoerg       // For certain return types, clear padding bits, as they may reveal
3569*e038c9c4Sjoerg       // sensitive information.
3570*e038c9c4Sjoerg       // Small struct/union types are passed as integers.
3571*e038c9c4Sjoerg       auto *ITy = dyn_cast<llvm::IntegerType>(RV->getType());
3572*e038c9c4Sjoerg       if (ITy != nullptr && isa<RecordType>(RetTy.getCanonicalType()))
3573*e038c9c4Sjoerg         RV = EmitCMSEClearRecord(RV, ITy, RetTy);
3574*e038c9c4Sjoerg     }
35757330f729Sjoerg     EmitReturnValueCheck(RV);
35767330f729Sjoerg     Ret = Builder.CreateRet(RV);
35777330f729Sjoerg   } else {
35787330f729Sjoerg     Ret = Builder.CreateRetVoid();
35797330f729Sjoerg   }
35807330f729Sjoerg 
35817330f729Sjoerg   if (RetDbgLoc)
35827330f729Sjoerg     Ret->setDebugLoc(std::move(RetDbgLoc));
35837330f729Sjoerg }
35847330f729Sjoerg 
EmitReturnValueCheck(llvm::Value * RV)35857330f729Sjoerg void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) {
35867330f729Sjoerg   // A current decl may not be available when emitting vtable thunks.
35877330f729Sjoerg   if (!CurCodeDecl)
35887330f729Sjoerg     return;
35897330f729Sjoerg 
3590*e038c9c4Sjoerg   // If the return block isn't reachable, neither is this check, so don't emit
3591*e038c9c4Sjoerg   // it.
3592*e038c9c4Sjoerg   if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty())
3593*e038c9c4Sjoerg     return;
3594*e038c9c4Sjoerg 
35957330f729Sjoerg   ReturnsNonNullAttr *RetNNAttr = nullptr;
35967330f729Sjoerg   if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
35977330f729Sjoerg     RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
35987330f729Sjoerg 
35997330f729Sjoerg   if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
36007330f729Sjoerg     return;
36017330f729Sjoerg 
36027330f729Sjoerg   // Prefer the returns_nonnull attribute if it's present.
36037330f729Sjoerg   SourceLocation AttrLoc;
36047330f729Sjoerg   SanitizerMask CheckKind;
36057330f729Sjoerg   SanitizerHandler Handler;
36067330f729Sjoerg   if (RetNNAttr) {
36077330f729Sjoerg     assert(!requiresReturnValueNullabilityCheck() &&
36087330f729Sjoerg            "Cannot check nullability and the nonnull attribute");
36097330f729Sjoerg     AttrLoc = RetNNAttr->getLocation();
36107330f729Sjoerg     CheckKind = SanitizerKind::ReturnsNonnullAttribute;
36117330f729Sjoerg     Handler = SanitizerHandler::NonnullReturn;
36127330f729Sjoerg   } else {
36137330f729Sjoerg     if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl))
36147330f729Sjoerg       if (auto *TSI = DD->getTypeSourceInfo())
3615*e038c9c4Sjoerg         if (auto FTL = TSI->getTypeLoc().getAsAdjusted<FunctionTypeLoc>())
36167330f729Sjoerg           AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
36177330f729Sjoerg     CheckKind = SanitizerKind::NullabilityReturn;
36187330f729Sjoerg     Handler = SanitizerHandler::NullabilityReturn;
36197330f729Sjoerg   }
36207330f729Sjoerg 
36217330f729Sjoerg   SanitizerScope SanScope(this);
36227330f729Sjoerg 
36237330f729Sjoerg   // Make sure the "return" source location is valid. If we're checking a
36247330f729Sjoerg   // nullability annotation, make sure the preconditions for the check are met.
36257330f729Sjoerg   llvm::BasicBlock *Check = createBasicBlock("nullcheck");
36267330f729Sjoerg   llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck");
36277330f729Sjoerg   llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load");
36287330f729Sjoerg   llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr);
36297330f729Sjoerg   if (requiresReturnValueNullabilityCheck())
36307330f729Sjoerg     CanNullCheck =
36317330f729Sjoerg         Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition);
36327330f729Sjoerg   Builder.CreateCondBr(CanNullCheck, Check, NoCheck);
36337330f729Sjoerg   EmitBlock(Check);
36347330f729Sjoerg 
36357330f729Sjoerg   // Now do the null check.
36367330f729Sjoerg   llvm::Value *Cond = Builder.CreateIsNotNull(RV);
36377330f729Sjoerg   llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)};
36387330f729Sjoerg   llvm::Value *DynamicData[] = {SLocPtr};
36397330f729Sjoerg   EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData);
36407330f729Sjoerg 
36417330f729Sjoerg   EmitBlock(NoCheck);
36427330f729Sjoerg 
36437330f729Sjoerg #ifndef NDEBUG
36447330f729Sjoerg   // The return location should not be used after the check has been emitted.
36457330f729Sjoerg   ReturnLocation = Address::invalid();
36467330f729Sjoerg #endif
36477330f729Sjoerg }
36487330f729Sjoerg 
isInAllocaArgument(CGCXXABI & ABI,QualType type)36497330f729Sjoerg static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
36507330f729Sjoerg   const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
36517330f729Sjoerg   return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
36527330f729Sjoerg }
36537330f729Sjoerg 
createPlaceholderSlot(CodeGenFunction & CGF,QualType Ty)36547330f729Sjoerg static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
36557330f729Sjoerg                                           QualType Ty) {
36567330f729Sjoerg   // FIXME: Generate IR in one pass, rather than going back and fixing up these
36577330f729Sjoerg   // placeholders.
36587330f729Sjoerg   llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
36597330f729Sjoerg   llvm::Type *IRPtrTy = IRTy->getPointerTo();
36607330f729Sjoerg   llvm::Value *Placeholder = llvm::UndefValue::get(IRPtrTy->getPointerTo());
36617330f729Sjoerg 
36627330f729Sjoerg   // FIXME: When we generate this IR in one pass, we shouldn't need
36637330f729Sjoerg   // this win32-specific alignment hack.
36647330f729Sjoerg   CharUnits Align = CharUnits::fromQuantity(4);
36657330f729Sjoerg   Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
36667330f729Sjoerg 
36677330f729Sjoerg   return AggValueSlot::forAddr(Address(Placeholder, Align),
36687330f729Sjoerg                                Ty.getQualifiers(),
36697330f729Sjoerg                                AggValueSlot::IsNotDestructed,
36707330f729Sjoerg                                AggValueSlot::DoesNotNeedGCBarriers,
36717330f729Sjoerg                                AggValueSlot::IsNotAliased,
36727330f729Sjoerg                                AggValueSlot::DoesNotOverlap);
36737330f729Sjoerg }
36747330f729Sjoerg 
EmitDelegateCallArg(CallArgList & args,const VarDecl * param,SourceLocation loc)36757330f729Sjoerg void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
36767330f729Sjoerg                                           const VarDecl *param,
36777330f729Sjoerg                                           SourceLocation loc) {
36787330f729Sjoerg   // StartFunction converted the ABI-lowered parameter(s) into a
36797330f729Sjoerg   // local alloca.  We need to turn that into an r-value suitable
36807330f729Sjoerg   // for EmitCall.
36817330f729Sjoerg   Address local = GetAddrOfLocalVar(param);
36827330f729Sjoerg 
36837330f729Sjoerg   QualType type = param->getType();
36847330f729Sjoerg 
36857330f729Sjoerg   if (isInAllocaArgument(CGM.getCXXABI(), type)) {
36867330f729Sjoerg     CGM.ErrorUnsupported(param, "forwarded non-trivially copyable parameter");
36877330f729Sjoerg   }
36887330f729Sjoerg 
36897330f729Sjoerg   // GetAddrOfLocalVar returns a pointer-to-pointer for references,
36907330f729Sjoerg   // but the argument needs to be the original pointer.
36917330f729Sjoerg   if (type->isReferenceType()) {
36927330f729Sjoerg     args.add(RValue::get(Builder.CreateLoad(local)), type);
36937330f729Sjoerg 
36947330f729Sjoerg   // In ARC, move out of consumed arguments so that the release cleanup
36957330f729Sjoerg   // entered by StartFunction doesn't cause an over-release.  This isn't
36967330f729Sjoerg   // optimal -O0 code generation, but it should get cleaned up when
36977330f729Sjoerg   // optimization is enabled.  This also assumes that delegate calls are
36987330f729Sjoerg   // performed exactly once for a set of arguments, but that should be safe.
36997330f729Sjoerg   } else if (getLangOpts().ObjCAutoRefCount &&
37007330f729Sjoerg              param->hasAttr<NSConsumedAttr>() &&
37017330f729Sjoerg              type->isObjCRetainableType()) {
37027330f729Sjoerg     llvm::Value *ptr = Builder.CreateLoad(local);
37037330f729Sjoerg     auto null =
37047330f729Sjoerg       llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
37057330f729Sjoerg     Builder.CreateStore(null, local);
37067330f729Sjoerg     args.add(RValue::get(ptr), type);
37077330f729Sjoerg 
37087330f729Sjoerg   // For the most part, we just need to load the alloca, except that
37097330f729Sjoerg   // aggregate r-values are actually pointers to temporaries.
37107330f729Sjoerg   } else {
37117330f729Sjoerg     args.add(convertTempToRValue(local, type, loc), type);
37127330f729Sjoerg   }
37137330f729Sjoerg 
37147330f729Sjoerg   // Deactivate the cleanup for the callee-destructed param that was pushed.
3715*e038c9c4Sjoerg   if (type->isRecordType() && !CurFuncIsThunk &&
37167330f729Sjoerg       type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee() &&
37177330f729Sjoerg       param->needsDestruction(getContext())) {
37187330f729Sjoerg     EHScopeStack::stable_iterator cleanup =
37197330f729Sjoerg         CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param));
37207330f729Sjoerg     assert(cleanup.isValid() &&
37217330f729Sjoerg            "cleanup for callee-destructed param not recorded");
37227330f729Sjoerg     // This unreachable is a temporary marker which will be removed later.
37237330f729Sjoerg     llvm::Instruction *isActive = Builder.CreateUnreachable();
37247330f729Sjoerg     args.addArgCleanupDeactivation(cleanup, isActive);
37257330f729Sjoerg   }
37267330f729Sjoerg }
37277330f729Sjoerg 
isProvablyNull(llvm::Value * addr)37287330f729Sjoerg static bool isProvablyNull(llvm::Value *addr) {
37297330f729Sjoerg   return isa<llvm::ConstantPointerNull>(addr);
37307330f729Sjoerg }
37317330f729Sjoerg 
37327330f729Sjoerg /// Emit the actual writing-back of a writeback.
emitWriteback(CodeGenFunction & CGF,const CallArgList::Writeback & writeback)37337330f729Sjoerg static void emitWriteback(CodeGenFunction &CGF,
37347330f729Sjoerg                           const CallArgList::Writeback &writeback) {
37357330f729Sjoerg   const LValue &srcLV = writeback.Source;
3736*e038c9c4Sjoerg   Address srcAddr = srcLV.getAddress(CGF);
37377330f729Sjoerg   assert(!isProvablyNull(srcAddr.getPointer()) &&
37387330f729Sjoerg          "shouldn't have writeback for provably null argument");
37397330f729Sjoerg 
37407330f729Sjoerg   llvm::BasicBlock *contBB = nullptr;
37417330f729Sjoerg 
37427330f729Sjoerg   // If the argument wasn't provably non-null, we need to null check
37437330f729Sjoerg   // before doing the store.
37447330f729Sjoerg   bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
37457330f729Sjoerg                                               CGF.CGM.getDataLayout());
37467330f729Sjoerg   if (!provablyNonNull) {
37477330f729Sjoerg     llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
37487330f729Sjoerg     contBB = CGF.createBasicBlock("icr.done");
37497330f729Sjoerg 
37507330f729Sjoerg     llvm::Value *isNull =
37517330f729Sjoerg       CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
37527330f729Sjoerg     CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
37537330f729Sjoerg     CGF.EmitBlock(writebackBB);
37547330f729Sjoerg   }
37557330f729Sjoerg 
37567330f729Sjoerg   // Load the value to writeback.
37577330f729Sjoerg   llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
37587330f729Sjoerg 
37597330f729Sjoerg   // Cast it back, in case we're writing an id to a Foo* or something.
37607330f729Sjoerg   value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
37617330f729Sjoerg                                     "icr.writeback-cast");
37627330f729Sjoerg 
37637330f729Sjoerg   // Perform the writeback.
37647330f729Sjoerg 
37657330f729Sjoerg   // If we have a "to use" value, it's something we need to emit a use
37667330f729Sjoerg   // of.  This has to be carefully threaded in: if it's done after the
37677330f729Sjoerg   // release it's potentially undefined behavior (and the optimizer
37687330f729Sjoerg   // will ignore it), and if it happens before the retain then the
37697330f729Sjoerg   // optimizer could move the release there.
37707330f729Sjoerg   if (writeback.ToUse) {
37717330f729Sjoerg     assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
37727330f729Sjoerg 
37737330f729Sjoerg     // Retain the new value.  No need to block-copy here:  the block's
37747330f729Sjoerg     // being passed up the stack.
37757330f729Sjoerg     value = CGF.EmitARCRetainNonBlock(value);
37767330f729Sjoerg 
37777330f729Sjoerg     // Emit the intrinsic use here.
37787330f729Sjoerg     CGF.EmitARCIntrinsicUse(writeback.ToUse);
37797330f729Sjoerg 
37807330f729Sjoerg     // Load the old value (primitively).
37817330f729Sjoerg     llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
37827330f729Sjoerg 
37837330f729Sjoerg     // Put the new value in place (primitively).
37847330f729Sjoerg     CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
37857330f729Sjoerg 
37867330f729Sjoerg     // Release the old value.
37877330f729Sjoerg     CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
37887330f729Sjoerg 
37897330f729Sjoerg   // Otherwise, we can just do a normal lvalue store.
37907330f729Sjoerg   } else {
37917330f729Sjoerg     CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
37927330f729Sjoerg   }
37937330f729Sjoerg 
37947330f729Sjoerg   // Jump to the continuation block.
37957330f729Sjoerg   if (!provablyNonNull)
37967330f729Sjoerg     CGF.EmitBlock(contBB);
37977330f729Sjoerg }
37987330f729Sjoerg 
emitWritebacks(CodeGenFunction & CGF,const CallArgList & args)37997330f729Sjoerg static void emitWritebacks(CodeGenFunction &CGF,
38007330f729Sjoerg                            const CallArgList &args) {
38017330f729Sjoerg   for (const auto &I : args.writebacks())
38027330f729Sjoerg     emitWriteback(CGF, I);
38037330f729Sjoerg }
38047330f729Sjoerg 
deactivateArgCleanupsBeforeCall(CodeGenFunction & CGF,const CallArgList & CallArgs)38057330f729Sjoerg static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
38067330f729Sjoerg                                             const CallArgList &CallArgs) {
38077330f729Sjoerg   ArrayRef<CallArgList::CallArgCleanup> Cleanups =
38087330f729Sjoerg     CallArgs.getCleanupsToDeactivate();
38097330f729Sjoerg   // Iterate in reverse to increase the likelihood of popping the cleanup.
38107330f729Sjoerg   for (const auto &I : llvm::reverse(Cleanups)) {
38117330f729Sjoerg     CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
38127330f729Sjoerg     I.IsActiveIP->eraseFromParent();
38137330f729Sjoerg   }
38147330f729Sjoerg }
38157330f729Sjoerg 
maybeGetUnaryAddrOfOperand(const Expr * E)38167330f729Sjoerg static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
38177330f729Sjoerg   if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
38187330f729Sjoerg     if (uop->getOpcode() == UO_AddrOf)
38197330f729Sjoerg       return uop->getSubExpr();
38207330f729Sjoerg   return nullptr;
38217330f729Sjoerg }
38227330f729Sjoerg 
38237330f729Sjoerg /// Emit an argument that's being passed call-by-writeback.  That is,
38247330f729Sjoerg /// we are passing the address of an __autoreleased temporary; it
38257330f729Sjoerg /// might be copy-initialized with the current value of the given
38267330f729Sjoerg /// address, but it will definitely be copied out of after the call.
emitWritebackArg(CodeGenFunction & CGF,CallArgList & args,const ObjCIndirectCopyRestoreExpr * CRE)38277330f729Sjoerg static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
38287330f729Sjoerg                              const ObjCIndirectCopyRestoreExpr *CRE) {
38297330f729Sjoerg   LValue srcLV;
38307330f729Sjoerg 
38317330f729Sjoerg   // Make an optimistic effort to emit the address as an l-value.
38327330f729Sjoerg   // This can fail if the argument expression is more complicated.
38337330f729Sjoerg   if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
38347330f729Sjoerg     srcLV = CGF.EmitLValue(lvExpr);
38357330f729Sjoerg 
38367330f729Sjoerg   // Otherwise, just emit it as a scalar.
38377330f729Sjoerg   } else {
38387330f729Sjoerg     Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
38397330f729Sjoerg 
38407330f729Sjoerg     QualType srcAddrType =
38417330f729Sjoerg       CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
38427330f729Sjoerg     srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
38437330f729Sjoerg   }
3844*e038c9c4Sjoerg   Address srcAddr = srcLV.getAddress(CGF);
38457330f729Sjoerg 
38467330f729Sjoerg   // The dest and src types don't necessarily match in LLVM terms
38477330f729Sjoerg   // because of the crazy ObjC compatibility rules.
38487330f729Sjoerg 
38497330f729Sjoerg   llvm::PointerType *destType =
38507330f729Sjoerg     cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
38517330f729Sjoerg 
38527330f729Sjoerg   // If the address is a constant null, just pass the appropriate null.
38537330f729Sjoerg   if (isProvablyNull(srcAddr.getPointer())) {
38547330f729Sjoerg     args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
38557330f729Sjoerg              CRE->getType());
38567330f729Sjoerg     return;
38577330f729Sjoerg   }
38587330f729Sjoerg 
38597330f729Sjoerg   // Create the temporary.
38607330f729Sjoerg   Address temp = CGF.CreateTempAlloca(destType->getElementType(),
38617330f729Sjoerg                                       CGF.getPointerAlign(),
38627330f729Sjoerg                                       "icr.temp");
38637330f729Sjoerg   // Loading an l-value can introduce a cleanup if the l-value is __weak,
38647330f729Sjoerg   // and that cleanup will be conditional if we can't prove that the l-value
38657330f729Sjoerg   // isn't null, so we need to register a dominating point so that the cleanups
38667330f729Sjoerg   // system will make valid IR.
38677330f729Sjoerg   CodeGenFunction::ConditionalEvaluation condEval(CGF);
38687330f729Sjoerg 
38697330f729Sjoerg   // Zero-initialize it if we're not doing a copy-initialization.
38707330f729Sjoerg   bool shouldCopy = CRE->shouldCopy();
38717330f729Sjoerg   if (!shouldCopy) {
38727330f729Sjoerg     llvm::Value *null =
38737330f729Sjoerg       llvm::ConstantPointerNull::get(
38747330f729Sjoerg         cast<llvm::PointerType>(destType->getElementType()));
38757330f729Sjoerg     CGF.Builder.CreateStore(null, temp);
38767330f729Sjoerg   }
38777330f729Sjoerg 
38787330f729Sjoerg   llvm::BasicBlock *contBB = nullptr;
38797330f729Sjoerg   llvm::BasicBlock *originBB = nullptr;
38807330f729Sjoerg 
38817330f729Sjoerg   // If the address is *not* known to be non-null, we need to switch.
38827330f729Sjoerg   llvm::Value *finalArgument;
38837330f729Sjoerg 
38847330f729Sjoerg   bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
38857330f729Sjoerg                                               CGF.CGM.getDataLayout());
38867330f729Sjoerg   if (provablyNonNull) {
38877330f729Sjoerg     finalArgument = temp.getPointer();
38887330f729Sjoerg   } else {
38897330f729Sjoerg     llvm::Value *isNull =
38907330f729Sjoerg       CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
38917330f729Sjoerg 
38927330f729Sjoerg     finalArgument = CGF.Builder.CreateSelect(isNull,
38937330f729Sjoerg                                    llvm::ConstantPointerNull::get(destType),
38947330f729Sjoerg                                              temp.getPointer(), "icr.argument");
38957330f729Sjoerg 
38967330f729Sjoerg     // If we need to copy, then the load has to be conditional, which
38977330f729Sjoerg     // means we need control flow.
38987330f729Sjoerg     if (shouldCopy) {
38997330f729Sjoerg       originBB = CGF.Builder.GetInsertBlock();
39007330f729Sjoerg       contBB = CGF.createBasicBlock("icr.cont");
39017330f729Sjoerg       llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
39027330f729Sjoerg       CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
39037330f729Sjoerg       CGF.EmitBlock(copyBB);
39047330f729Sjoerg       condEval.begin(CGF);
39057330f729Sjoerg     }
39067330f729Sjoerg   }
39077330f729Sjoerg 
39087330f729Sjoerg   llvm::Value *valueToUse = nullptr;
39097330f729Sjoerg 
39107330f729Sjoerg   // Perform a copy if necessary.
39117330f729Sjoerg   if (shouldCopy) {
39127330f729Sjoerg     RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
39137330f729Sjoerg     assert(srcRV.isScalar());
39147330f729Sjoerg 
39157330f729Sjoerg     llvm::Value *src = srcRV.getScalarVal();
39167330f729Sjoerg     src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
39177330f729Sjoerg                                     "icr.cast");
39187330f729Sjoerg 
39197330f729Sjoerg     // Use an ordinary store, not a store-to-lvalue.
39207330f729Sjoerg     CGF.Builder.CreateStore(src, temp);
39217330f729Sjoerg 
39227330f729Sjoerg     // If optimization is enabled, and the value was held in a
39237330f729Sjoerg     // __strong variable, we need to tell the optimizer that this
39247330f729Sjoerg     // value has to stay alive until we're doing the store back.
39257330f729Sjoerg     // This is because the temporary is effectively unretained,
39267330f729Sjoerg     // and so otherwise we can violate the high-level semantics.
39277330f729Sjoerg     if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
39287330f729Sjoerg         srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
39297330f729Sjoerg       valueToUse = src;
39307330f729Sjoerg     }
39317330f729Sjoerg   }
39327330f729Sjoerg 
39337330f729Sjoerg   // Finish the control flow if we needed it.
39347330f729Sjoerg   if (shouldCopy && !provablyNonNull) {
39357330f729Sjoerg     llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
39367330f729Sjoerg     CGF.EmitBlock(contBB);
39377330f729Sjoerg 
39387330f729Sjoerg     // Make a phi for the value to intrinsically use.
39397330f729Sjoerg     if (valueToUse) {
39407330f729Sjoerg       llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
39417330f729Sjoerg                                                       "icr.to-use");
39427330f729Sjoerg       phiToUse->addIncoming(valueToUse, copyBB);
39437330f729Sjoerg       phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
39447330f729Sjoerg                             originBB);
39457330f729Sjoerg       valueToUse = phiToUse;
39467330f729Sjoerg     }
39477330f729Sjoerg 
39487330f729Sjoerg     condEval.end(CGF);
39497330f729Sjoerg   }
39507330f729Sjoerg 
39517330f729Sjoerg   args.addWriteback(srcLV, temp, valueToUse);
39527330f729Sjoerg   args.add(RValue::get(finalArgument), CRE->getType());
39537330f729Sjoerg }
39547330f729Sjoerg 
allocateArgumentMemory(CodeGenFunction & CGF)39557330f729Sjoerg void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
39567330f729Sjoerg   assert(!StackBase);
39577330f729Sjoerg 
39587330f729Sjoerg   // Save the stack.
39597330f729Sjoerg   llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
39607330f729Sjoerg   StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
39617330f729Sjoerg }
39627330f729Sjoerg 
freeArgumentMemory(CodeGenFunction & CGF) const39637330f729Sjoerg void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
39647330f729Sjoerg   if (StackBase) {
39657330f729Sjoerg     // Restore the stack after the call.
39667330f729Sjoerg     llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
39677330f729Sjoerg     CGF.Builder.CreateCall(F, StackBase);
39687330f729Sjoerg   }
39697330f729Sjoerg }
39707330f729Sjoerg 
EmitNonNullArgCheck(RValue RV,QualType ArgType,SourceLocation ArgLoc,AbstractCallee AC,unsigned ParmNum)39717330f729Sjoerg void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
39727330f729Sjoerg                                           SourceLocation ArgLoc,
39737330f729Sjoerg                                           AbstractCallee AC,
39747330f729Sjoerg                                           unsigned ParmNum) {
39757330f729Sjoerg   if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
39767330f729Sjoerg                          SanOpts.has(SanitizerKind::NullabilityArg)))
39777330f729Sjoerg     return;
39787330f729Sjoerg 
39797330f729Sjoerg   // The param decl may be missing in a variadic function.
39807330f729Sjoerg   auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr;
39817330f729Sjoerg   unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
39827330f729Sjoerg 
39837330f729Sjoerg   // Prefer the nonnull attribute if it's present.
39847330f729Sjoerg   const NonNullAttr *NNAttr = nullptr;
39857330f729Sjoerg   if (SanOpts.has(SanitizerKind::NonnullAttribute))
39867330f729Sjoerg     NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
39877330f729Sjoerg 
39887330f729Sjoerg   bool CanCheckNullability = false;
39897330f729Sjoerg   if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD) {
39907330f729Sjoerg     auto Nullability = PVD->getType()->getNullability(getContext());
39917330f729Sjoerg     CanCheckNullability = Nullability &&
39927330f729Sjoerg                           *Nullability == NullabilityKind::NonNull &&
39937330f729Sjoerg                           PVD->getTypeSourceInfo();
39947330f729Sjoerg   }
39957330f729Sjoerg 
39967330f729Sjoerg   if (!NNAttr && !CanCheckNullability)
39977330f729Sjoerg     return;
39987330f729Sjoerg 
39997330f729Sjoerg   SourceLocation AttrLoc;
40007330f729Sjoerg   SanitizerMask CheckKind;
40017330f729Sjoerg   SanitizerHandler Handler;
40027330f729Sjoerg   if (NNAttr) {
40037330f729Sjoerg     AttrLoc = NNAttr->getLocation();
40047330f729Sjoerg     CheckKind = SanitizerKind::NonnullAttribute;
40057330f729Sjoerg     Handler = SanitizerHandler::NonnullArg;
40067330f729Sjoerg   } else {
40077330f729Sjoerg     AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
40087330f729Sjoerg     CheckKind = SanitizerKind::NullabilityArg;
40097330f729Sjoerg     Handler = SanitizerHandler::NullabilityArg;
40107330f729Sjoerg   }
40117330f729Sjoerg 
40127330f729Sjoerg   SanitizerScope SanScope(this);
4013*e038c9c4Sjoerg   llvm::Value *Cond = EmitNonNullRValueCheck(RV, ArgType);
40147330f729Sjoerg   llvm::Constant *StaticData[] = {
40157330f729Sjoerg       EmitCheckSourceLocation(ArgLoc), EmitCheckSourceLocation(AttrLoc),
40167330f729Sjoerg       llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
40177330f729Sjoerg   };
40187330f729Sjoerg   EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, None);
40197330f729Sjoerg }
40207330f729Sjoerg 
4021*e038c9c4Sjoerg // Check if the call is going to use the inalloca convention. This needs to
4022*e038c9c4Sjoerg // agree with CGFunctionInfo::usesInAlloca. The CGFunctionInfo is arranged
4023*e038c9c4Sjoerg // later, so we can't check it directly.
hasInAllocaArgs(CodeGenModule & CGM,CallingConv ExplicitCC,ArrayRef<QualType> ArgTypes)4024*e038c9c4Sjoerg static bool hasInAllocaArgs(CodeGenModule &CGM, CallingConv ExplicitCC,
4025*e038c9c4Sjoerg                             ArrayRef<QualType> ArgTypes) {
4026*e038c9c4Sjoerg   // The Swift calling convention doesn't go through the target-specific
4027*e038c9c4Sjoerg   // argument classification, so it never uses inalloca.
4028*e038c9c4Sjoerg   // TODO: Consider limiting inalloca use to only calling conventions supported
4029*e038c9c4Sjoerg   // by MSVC.
4030*e038c9c4Sjoerg   if (ExplicitCC == CC_Swift)
4031*e038c9c4Sjoerg     return false;
4032*e038c9c4Sjoerg   if (!CGM.getTarget().getCXXABI().isMicrosoft())
4033*e038c9c4Sjoerg     return false;
4034*e038c9c4Sjoerg   return llvm::any_of(ArgTypes, [&](QualType Ty) {
4035*e038c9c4Sjoerg     return isInAllocaArgument(CGM.getCXXABI(), Ty);
4036*e038c9c4Sjoerg   });
4037*e038c9c4Sjoerg }
4038*e038c9c4Sjoerg 
4039*e038c9c4Sjoerg #ifndef NDEBUG
4040*e038c9c4Sjoerg // Determine whether the given argument is an Objective-C method
4041*e038c9c4Sjoerg // that may have type parameters in its signature.
isObjCMethodWithTypeParams(const ObjCMethodDecl * method)4042*e038c9c4Sjoerg static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
4043*e038c9c4Sjoerg   const DeclContext *dc = method->getDeclContext();
4044*e038c9c4Sjoerg   if (const ObjCInterfaceDecl *classDecl = dyn_cast<ObjCInterfaceDecl>(dc)) {
4045*e038c9c4Sjoerg     return classDecl->getTypeParamListAsWritten();
4046*e038c9c4Sjoerg   }
4047*e038c9c4Sjoerg 
4048*e038c9c4Sjoerg   if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
4049*e038c9c4Sjoerg     return catDecl->getTypeParamList();
4050*e038c9c4Sjoerg   }
4051*e038c9c4Sjoerg 
4052*e038c9c4Sjoerg   return false;
4053*e038c9c4Sjoerg }
4054*e038c9c4Sjoerg #endif
4055*e038c9c4Sjoerg 
4056*e038c9c4Sjoerg /// EmitCallArgs - Emit call arguments for a function.
EmitCallArgs(CallArgList & Args,PrototypeWrapper Prototype,llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,AbstractCallee AC,unsigned ParamsToSkip,EvaluationOrder Order)40577330f729Sjoerg void CodeGenFunction::EmitCallArgs(
4058*e038c9c4Sjoerg     CallArgList &Args, PrototypeWrapper Prototype,
40597330f729Sjoerg     llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
40607330f729Sjoerg     AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
4061*e038c9c4Sjoerg   SmallVector<QualType, 16> ArgTypes;
4062*e038c9c4Sjoerg 
4063*e038c9c4Sjoerg   assert((ParamsToSkip == 0 || Prototype.P) &&
4064*e038c9c4Sjoerg          "Can't skip parameters if type info is not provided");
4065*e038c9c4Sjoerg 
4066*e038c9c4Sjoerg   // This variable only captures *explicitly* written conventions, not those
4067*e038c9c4Sjoerg   // applied by default via command line flags or target defaults, such as
4068*e038c9c4Sjoerg   // thiscall, aapcs, stdcall via -mrtd, etc. Computing that correctly would
4069*e038c9c4Sjoerg   // require knowing if this is a C++ instance method or being able to see
4070*e038c9c4Sjoerg   // unprototyped FunctionTypes.
4071*e038c9c4Sjoerg   CallingConv ExplicitCC = CC_C;
4072*e038c9c4Sjoerg 
4073*e038c9c4Sjoerg   // First, if a prototype was provided, use those argument types.
4074*e038c9c4Sjoerg   bool IsVariadic = false;
4075*e038c9c4Sjoerg   if (Prototype.P) {
4076*e038c9c4Sjoerg     const auto *MD = Prototype.P.dyn_cast<const ObjCMethodDecl *>();
4077*e038c9c4Sjoerg     if (MD) {
4078*e038c9c4Sjoerg       IsVariadic = MD->isVariadic();
4079*e038c9c4Sjoerg       ExplicitCC = getCallingConventionForDecl(
4080*e038c9c4Sjoerg           MD, CGM.getTarget().getTriple().isOSWindows());
4081*e038c9c4Sjoerg       ArgTypes.assign(MD->param_type_begin() + ParamsToSkip,
4082*e038c9c4Sjoerg                       MD->param_type_end());
4083*e038c9c4Sjoerg     } else {
4084*e038c9c4Sjoerg       const auto *FPT = Prototype.P.get<const FunctionProtoType *>();
4085*e038c9c4Sjoerg       IsVariadic = FPT->isVariadic();
4086*e038c9c4Sjoerg       ExplicitCC = FPT->getExtInfo().getCC();
4087*e038c9c4Sjoerg       ArgTypes.assign(FPT->param_type_begin() + ParamsToSkip,
4088*e038c9c4Sjoerg                       FPT->param_type_end());
4089*e038c9c4Sjoerg     }
4090*e038c9c4Sjoerg 
4091*e038c9c4Sjoerg #ifndef NDEBUG
4092*e038c9c4Sjoerg     // Check that the prototyped types match the argument expression types.
4093*e038c9c4Sjoerg     bool isGenericMethod = MD && isObjCMethodWithTypeParams(MD);
4094*e038c9c4Sjoerg     CallExpr::const_arg_iterator Arg = ArgRange.begin();
4095*e038c9c4Sjoerg     for (QualType Ty : ArgTypes) {
4096*e038c9c4Sjoerg       assert(Arg != ArgRange.end() && "Running over edge of argument list!");
4097*e038c9c4Sjoerg       assert(
4098*e038c9c4Sjoerg           (isGenericMethod || Ty->isVariablyModifiedType() ||
4099*e038c9c4Sjoerg            Ty.getNonReferenceType()->isObjCRetainableType() ||
4100*e038c9c4Sjoerg            getContext()
4101*e038c9c4Sjoerg                    .getCanonicalType(Ty.getNonReferenceType())
4102*e038c9c4Sjoerg                    .getTypePtr() ==
4103*e038c9c4Sjoerg                getContext().getCanonicalType((*Arg)->getType()).getTypePtr()) &&
4104*e038c9c4Sjoerg           "type mismatch in call argument!");
4105*e038c9c4Sjoerg       ++Arg;
4106*e038c9c4Sjoerg     }
4107*e038c9c4Sjoerg 
4108*e038c9c4Sjoerg     // Either we've emitted all the call args, or we have a call to variadic
4109*e038c9c4Sjoerg     // function.
4110*e038c9c4Sjoerg     assert((Arg == ArgRange.end() || IsVariadic) &&
4111*e038c9c4Sjoerg            "Extra arguments in non-variadic function!");
4112*e038c9c4Sjoerg #endif
4113*e038c9c4Sjoerg   }
4114*e038c9c4Sjoerg 
4115*e038c9c4Sjoerg   // If we still have any arguments, emit them using the type of the argument.
4116*e038c9c4Sjoerg   for (auto *A : llvm::make_range(std::next(ArgRange.begin(), ArgTypes.size()),
4117*e038c9c4Sjoerg                                   ArgRange.end()))
4118*e038c9c4Sjoerg     ArgTypes.push_back(IsVariadic ? getVarArgType(A) : A->getType());
41197330f729Sjoerg   assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
41207330f729Sjoerg 
4121*e038c9c4Sjoerg   // We must evaluate arguments from right to left in the MS C++ ABI,
41227330f729Sjoerg   // because arguments are destroyed left to right in the callee. As a special
41237330f729Sjoerg   // case, there are certain language constructs that require left-to-right
41247330f729Sjoerg   // evaluation, and in those cases we consider the evaluation order requirement
41257330f729Sjoerg   // to trump the "destruction order is reverse construction order" guarantee.
41267330f729Sjoerg   bool LeftToRight =
41277330f729Sjoerg       CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
41287330f729Sjoerg           ? Order == EvaluationOrder::ForceLeftToRight
41297330f729Sjoerg           : Order != EvaluationOrder::ForceRightToLeft;
41307330f729Sjoerg 
41317330f729Sjoerg   auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
41327330f729Sjoerg                                          RValue EmittedArg) {
41337330f729Sjoerg     if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
41347330f729Sjoerg       return;
41357330f729Sjoerg     auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
41367330f729Sjoerg     if (PS == nullptr)
41377330f729Sjoerg       return;
41387330f729Sjoerg 
41397330f729Sjoerg     const auto &Context = getContext();
41407330f729Sjoerg     auto SizeTy = Context.getSizeType();
41417330f729Sjoerg     auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
41427330f729Sjoerg     assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?");
41437330f729Sjoerg     llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
41447330f729Sjoerg                                                      EmittedArg.getScalarVal(),
41457330f729Sjoerg                                                      PS->isDynamic());
41467330f729Sjoerg     Args.add(RValue::get(V), SizeTy);
41477330f729Sjoerg     // If we're emitting args in reverse, be sure to do so with
41487330f729Sjoerg     // pass_object_size, as well.
41497330f729Sjoerg     if (!LeftToRight)
41507330f729Sjoerg       std::swap(Args.back(), *(&Args.back() - 1));
41517330f729Sjoerg   };
41527330f729Sjoerg 
41537330f729Sjoerg   // Insert a stack save if we're going to need any inalloca args.
4154*e038c9c4Sjoerg   if (hasInAllocaArgs(CGM, ExplicitCC, ArgTypes)) {
4155*e038c9c4Sjoerg     assert(getTarget().getTriple().getArch() == llvm::Triple::x86 &&
4156*e038c9c4Sjoerg            "inalloca only supported on x86");
41577330f729Sjoerg     Args.allocateArgumentMemory(*this);
41587330f729Sjoerg   }
41597330f729Sjoerg 
41607330f729Sjoerg   // Evaluate each argument in the appropriate order.
41617330f729Sjoerg   size_t CallArgsStart = Args.size();
41627330f729Sjoerg   for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
41637330f729Sjoerg     unsigned Idx = LeftToRight ? I : E - I - 1;
41647330f729Sjoerg     CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
41657330f729Sjoerg     unsigned InitialArgSize = Args.size();
41667330f729Sjoerg     // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of
41677330f729Sjoerg     // the argument and parameter match or the objc method is parameterized.
41687330f729Sjoerg     assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) ||
41697330f729Sjoerg             getContext().hasSameUnqualifiedType((*Arg)->getType(),
41707330f729Sjoerg                                                 ArgTypes[Idx]) ||
41717330f729Sjoerg             (isa<ObjCMethodDecl>(AC.getDecl()) &&
41727330f729Sjoerg              isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) &&
41737330f729Sjoerg            "Argument and parameter types don't match");
41747330f729Sjoerg     EmitCallArg(Args, *Arg, ArgTypes[Idx]);
41757330f729Sjoerg     // In particular, we depend on it being the last arg in Args, and the
41767330f729Sjoerg     // objectsize bits depend on there only being one arg if !LeftToRight.
41777330f729Sjoerg     assert(InitialArgSize + 1 == Args.size() &&
41787330f729Sjoerg            "The code below depends on only adding one arg per EmitCallArg");
41797330f729Sjoerg     (void)InitialArgSize;
41807330f729Sjoerg     // Since pointer argument are never emitted as LValue, it is safe to emit
41817330f729Sjoerg     // non-null argument check for r-value only.
41827330f729Sjoerg     if (!Args.back().hasLValue()) {
41837330f729Sjoerg       RValue RVArg = Args.back().getKnownRValue();
41847330f729Sjoerg       EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
41857330f729Sjoerg                           ParamsToSkip + Idx);
41867330f729Sjoerg       // @llvm.objectsize should never have side-effects and shouldn't need
41877330f729Sjoerg       // destruction/cleanups, so we can safely "emit" it after its arg,
41887330f729Sjoerg       // regardless of right-to-leftness
41897330f729Sjoerg       MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
41907330f729Sjoerg     }
41917330f729Sjoerg   }
41927330f729Sjoerg 
41937330f729Sjoerg   if (!LeftToRight) {
41947330f729Sjoerg     // Un-reverse the arguments we just evaluated so they match up with the LLVM
41957330f729Sjoerg     // IR function.
41967330f729Sjoerg     std::reverse(Args.begin() + CallArgsStart, Args.end());
41977330f729Sjoerg   }
41987330f729Sjoerg }
41997330f729Sjoerg 
42007330f729Sjoerg namespace {
42017330f729Sjoerg 
42027330f729Sjoerg struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
DestroyUnpassedArg__anon6af8234f0c11::DestroyUnpassedArg42037330f729Sjoerg   DestroyUnpassedArg(Address Addr, QualType Ty)
42047330f729Sjoerg       : Addr(Addr), Ty(Ty) {}
42057330f729Sjoerg 
42067330f729Sjoerg   Address Addr;
42077330f729Sjoerg   QualType Ty;
42087330f729Sjoerg 
Emit__anon6af8234f0c11::DestroyUnpassedArg42097330f729Sjoerg   void Emit(CodeGenFunction &CGF, Flags flags) override {
42107330f729Sjoerg     QualType::DestructionKind DtorKind = Ty.isDestructedType();
42117330f729Sjoerg     if (DtorKind == QualType::DK_cxx_destructor) {
42127330f729Sjoerg       const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
42137330f729Sjoerg       assert(!Dtor->isTrivial());
42147330f729Sjoerg       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
42157330f729Sjoerg                                 /*Delegating=*/false, Addr, Ty);
42167330f729Sjoerg     } else {
42177330f729Sjoerg       CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty));
42187330f729Sjoerg     }
42197330f729Sjoerg   }
42207330f729Sjoerg };
42217330f729Sjoerg 
42227330f729Sjoerg struct DisableDebugLocationUpdates {
42237330f729Sjoerg   CodeGenFunction &CGF;
42247330f729Sjoerg   bool disabledDebugInfo;
DisableDebugLocationUpdates__anon6af8234f0c11::DisableDebugLocationUpdates42257330f729Sjoerg   DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
42267330f729Sjoerg     if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
42277330f729Sjoerg       CGF.disableDebugInfo();
42287330f729Sjoerg   }
~DisableDebugLocationUpdates__anon6af8234f0c11::DisableDebugLocationUpdates42297330f729Sjoerg   ~DisableDebugLocationUpdates() {
42307330f729Sjoerg     if (disabledDebugInfo)
42317330f729Sjoerg       CGF.enableDebugInfo();
42327330f729Sjoerg   }
42337330f729Sjoerg };
42347330f729Sjoerg 
42357330f729Sjoerg } // end anonymous namespace
42367330f729Sjoerg 
getRValue(CodeGenFunction & CGF) const42377330f729Sjoerg RValue CallArg::getRValue(CodeGenFunction &CGF) const {
42387330f729Sjoerg   if (!HasLV)
42397330f729Sjoerg     return RV;
42407330f729Sjoerg   LValue Copy = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty), Ty);
42417330f729Sjoerg   CGF.EmitAggregateCopy(Copy, LV, Ty, AggValueSlot::DoesNotOverlap,
42427330f729Sjoerg                         LV.isVolatile());
42437330f729Sjoerg   IsUsed = true;
4244*e038c9c4Sjoerg   return RValue::getAggregate(Copy.getAddress(CGF));
42457330f729Sjoerg }
42467330f729Sjoerg 
copyInto(CodeGenFunction & CGF,Address Addr) const42477330f729Sjoerg void CallArg::copyInto(CodeGenFunction &CGF, Address Addr) const {
42487330f729Sjoerg   LValue Dst = CGF.MakeAddrLValue(Addr, Ty);
42497330f729Sjoerg   if (!HasLV && RV.isScalar())
42507330f729Sjoerg     CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*isInit=*/true);
42517330f729Sjoerg   else if (!HasLV && RV.isComplex())
42527330f729Sjoerg     CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true);
42537330f729Sjoerg   else {
4254*e038c9c4Sjoerg     auto Addr = HasLV ? LV.getAddress(CGF) : RV.getAggregateAddress();
42557330f729Sjoerg     LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty);
42567330f729Sjoerg     // We assume that call args are never copied into subobjects.
42577330f729Sjoerg     CGF.EmitAggregateCopy(Dst, SrcLV, Ty, AggValueSlot::DoesNotOverlap,
42587330f729Sjoerg                           HasLV ? LV.isVolatileQualified()
42597330f729Sjoerg                                 : RV.isVolatileQualified());
42607330f729Sjoerg   }
42617330f729Sjoerg   IsUsed = true;
42627330f729Sjoerg }
42637330f729Sjoerg 
EmitCallArg(CallArgList & args,const Expr * E,QualType type)42647330f729Sjoerg void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
42657330f729Sjoerg                                   QualType type) {
42667330f729Sjoerg   DisableDebugLocationUpdates Dis(*this, E);
42677330f729Sjoerg   if (const ObjCIndirectCopyRestoreExpr *CRE
42687330f729Sjoerg         = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
42697330f729Sjoerg     assert(getLangOpts().ObjCAutoRefCount);
42707330f729Sjoerg     return emitWritebackArg(*this, args, CRE);
42717330f729Sjoerg   }
42727330f729Sjoerg 
42737330f729Sjoerg   assert(type->isReferenceType() == E->isGLValue() &&
42747330f729Sjoerg          "reference binding to unmaterialized r-value!");
42757330f729Sjoerg 
42767330f729Sjoerg   if (E->isGLValue()) {
42777330f729Sjoerg     assert(E->getObjectKind() == OK_Ordinary);
42787330f729Sjoerg     return args.add(EmitReferenceBindingToExpr(E), type);
42797330f729Sjoerg   }
42807330f729Sjoerg 
42817330f729Sjoerg   bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
42827330f729Sjoerg 
42837330f729Sjoerg   // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
42847330f729Sjoerg   // However, we still have to push an EH-only cleanup in case we unwind before
42857330f729Sjoerg   // we make it to the call.
4286*e038c9c4Sjoerg   if (type->isRecordType() &&
42877330f729Sjoerg       type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
42887330f729Sjoerg     // If we're using inalloca, use the argument memory.  Otherwise, use a
42897330f729Sjoerg     // temporary.
42907330f729Sjoerg     AggValueSlot Slot;
42917330f729Sjoerg     if (args.isUsingInAlloca())
42927330f729Sjoerg       Slot = createPlaceholderSlot(*this, type);
42937330f729Sjoerg     else
42947330f729Sjoerg       Slot = CreateAggTemp(type, "agg.tmp");
42957330f729Sjoerg 
42967330f729Sjoerg     bool DestroyedInCallee = true, NeedsEHCleanup = true;
42977330f729Sjoerg     if (const auto *RD = type->getAsCXXRecordDecl())
42987330f729Sjoerg       DestroyedInCallee = RD->hasNonTrivialDestructor();
42997330f729Sjoerg     else
43007330f729Sjoerg       NeedsEHCleanup = needsEHCleanup(type.isDestructedType());
43017330f729Sjoerg 
43027330f729Sjoerg     if (DestroyedInCallee)
43037330f729Sjoerg       Slot.setExternallyDestructed();
43047330f729Sjoerg 
43057330f729Sjoerg     EmitAggExpr(E, Slot);
43067330f729Sjoerg     RValue RV = Slot.asRValue();
43077330f729Sjoerg     args.add(RV, type);
43087330f729Sjoerg 
43097330f729Sjoerg     if (DestroyedInCallee && NeedsEHCleanup) {
43107330f729Sjoerg       // Create a no-op GEP between the placeholder and the cleanup so we can
43117330f729Sjoerg       // RAUW it successfully.  It also serves as a marker of the first
43127330f729Sjoerg       // instruction where the cleanup is active.
43137330f729Sjoerg       pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
43147330f729Sjoerg                                               type);
43157330f729Sjoerg       // This unreachable is a temporary marker which will be removed later.
43167330f729Sjoerg       llvm::Instruction *IsActive = Builder.CreateUnreachable();
43177330f729Sjoerg       args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
43187330f729Sjoerg     }
43197330f729Sjoerg     return;
43207330f729Sjoerg   }
43217330f729Sjoerg 
43227330f729Sjoerg   if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
43237330f729Sjoerg       cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
43247330f729Sjoerg     LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
43257330f729Sjoerg     assert(L.isSimple());
43267330f729Sjoerg     args.addUncopiedAggregate(L, type);
43277330f729Sjoerg     return;
43287330f729Sjoerg   }
43297330f729Sjoerg 
43307330f729Sjoerg   args.add(EmitAnyExprToTemp(E), type);
43317330f729Sjoerg }
43327330f729Sjoerg 
getVarArgType(const Expr * Arg)43337330f729Sjoerg QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
43347330f729Sjoerg   // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
43357330f729Sjoerg   // implicitly widens null pointer constants that are arguments to varargs
43367330f729Sjoerg   // functions to pointer-sized ints.
43377330f729Sjoerg   if (!getTarget().getTriple().isOSWindows())
43387330f729Sjoerg     return Arg->getType();
43397330f729Sjoerg 
43407330f729Sjoerg   if (Arg->getType()->isIntegerType() &&
43417330f729Sjoerg       getContext().getTypeSize(Arg->getType()) <
43427330f729Sjoerg           getContext().getTargetInfo().getPointerWidth(0) &&
43437330f729Sjoerg       Arg->isNullPointerConstant(getContext(),
43447330f729Sjoerg                                  Expr::NPC_ValueDependentIsNotNull)) {
43457330f729Sjoerg     return getContext().getIntPtrType();
43467330f729Sjoerg   }
43477330f729Sjoerg 
43487330f729Sjoerg   return Arg->getType();
43497330f729Sjoerg }
43507330f729Sjoerg 
43517330f729Sjoerg // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
43527330f729Sjoerg // optimizer it can aggressively ignore unwind edges.
43537330f729Sjoerg void
AddObjCARCExceptionMetadata(llvm::Instruction * Inst)43547330f729Sjoerg CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
43557330f729Sjoerg   if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
43567330f729Sjoerg       !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
43577330f729Sjoerg     Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
43587330f729Sjoerg                       CGM.getNoObjCARCExceptionsMetadata());
43597330f729Sjoerg }
43607330f729Sjoerg 
43617330f729Sjoerg /// Emits a call to the given no-arguments nounwind runtime function.
43627330f729Sjoerg llvm::CallInst *
EmitNounwindRuntimeCall(llvm::FunctionCallee callee,const llvm::Twine & name)43637330f729Sjoerg CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
43647330f729Sjoerg                                          const llvm::Twine &name) {
43657330f729Sjoerg   return EmitNounwindRuntimeCall(callee, None, name);
43667330f729Sjoerg }
43677330f729Sjoerg 
43687330f729Sjoerg /// Emits a call to the given nounwind runtime function.
43697330f729Sjoerg llvm::CallInst *
EmitNounwindRuntimeCall(llvm::FunctionCallee callee,ArrayRef<llvm::Value * > args,const llvm::Twine & name)43707330f729Sjoerg CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
43717330f729Sjoerg                                          ArrayRef<llvm::Value *> args,
43727330f729Sjoerg                                          const llvm::Twine &name) {
43737330f729Sjoerg   llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
43747330f729Sjoerg   call->setDoesNotThrow();
43757330f729Sjoerg   return call;
43767330f729Sjoerg }
43777330f729Sjoerg 
43787330f729Sjoerg /// Emits a simple call (never an invoke) to the given no-arguments
43797330f729Sjoerg /// runtime function.
EmitRuntimeCall(llvm::FunctionCallee callee,const llvm::Twine & name)43807330f729Sjoerg llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
43817330f729Sjoerg                                                  const llvm::Twine &name) {
43827330f729Sjoerg   return EmitRuntimeCall(callee, None, name);
43837330f729Sjoerg }
43847330f729Sjoerg 
43857330f729Sjoerg // Calls which may throw must have operand bundles indicating which funclet
43867330f729Sjoerg // they are nested within.
43877330f729Sjoerg SmallVector<llvm::OperandBundleDef, 1>
getBundlesForFunclet(llvm::Value * Callee)43887330f729Sjoerg CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) {
43897330f729Sjoerg   SmallVector<llvm::OperandBundleDef, 1> BundleList;
43907330f729Sjoerg   // There is no need for a funclet operand bundle if we aren't inside a
43917330f729Sjoerg   // funclet.
43927330f729Sjoerg   if (!CurrentFuncletPad)
43937330f729Sjoerg     return BundleList;
43947330f729Sjoerg 
43957330f729Sjoerg   // Skip intrinsics which cannot throw.
43967330f729Sjoerg   auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
43977330f729Sjoerg   if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
43987330f729Sjoerg     return BundleList;
43997330f729Sjoerg 
44007330f729Sjoerg   BundleList.emplace_back("funclet", CurrentFuncletPad);
44017330f729Sjoerg   return BundleList;
44027330f729Sjoerg }
44037330f729Sjoerg 
44047330f729Sjoerg /// Emits a simple call (never an invoke) to the given runtime function.
EmitRuntimeCall(llvm::FunctionCallee callee,ArrayRef<llvm::Value * > args,const llvm::Twine & name)44057330f729Sjoerg llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
44067330f729Sjoerg                                                  ArrayRef<llvm::Value *> args,
44077330f729Sjoerg                                                  const llvm::Twine &name) {
44087330f729Sjoerg   llvm::CallInst *call = Builder.CreateCall(
44097330f729Sjoerg       callee, args, getBundlesForFunclet(callee.getCallee()), name);
44107330f729Sjoerg   call->setCallingConv(getRuntimeCC());
44117330f729Sjoerg   return call;
44127330f729Sjoerg }
44137330f729Sjoerg 
44147330f729Sjoerg /// Emits a call or invoke to the given noreturn runtime function.
EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee,ArrayRef<llvm::Value * > args)44157330f729Sjoerg void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(
44167330f729Sjoerg     llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) {
44177330f729Sjoerg   SmallVector<llvm::OperandBundleDef, 1> BundleList =
44187330f729Sjoerg       getBundlesForFunclet(callee.getCallee());
44197330f729Sjoerg 
44207330f729Sjoerg   if (getInvokeDest()) {
44217330f729Sjoerg     llvm::InvokeInst *invoke =
44227330f729Sjoerg       Builder.CreateInvoke(callee,
44237330f729Sjoerg                            getUnreachableBlock(),
44247330f729Sjoerg                            getInvokeDest(),
44257330f729Sjoerg                            args,
44267330f729Sjoerg                            BundleList);
44277330f729Sjoerg     invoke->setDoesNotReturn();
44287330f729Sjoerg     invoke->setCallingConv(getRuntimeCC());
44297330f729Sjoerg   } else {
44307330f729Sjoerg     llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
44317330f729Sjoerg     call->setDoesNotReturn();
44327330f729Sjoerg     call->setCallingConv(getRuntimeCC());
44337330f729Sjoerg     Builder.CreateUnreachable();
44347330f729Sjoerg   }
44357330f729Sjoerg }
44367330f729Sjoerg 
44377330f729Sjoerg /// Emits a call or invoke instruction to the given nullary runtime function.
44387330f729Sjoerg llvm::CallBase *
EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,const Twine & name)44397330f729Sjoerg CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
44407330f729Sjoerg                                          const Twine &name) {
44417330f729Sjoerg   return EmitRuntimeCallOrInvoke(callee, None, name);
44427330f729Sjoerg }
44437330f729Sjoerg 
44447330f729Sjoerg /// Emits a call or invoke instruction to the given runtime function.
44457330f729Sjoerg llvm::CallBase *
EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,ArrayRef<llvm::Value * > args,const Twine & name)44467330f729Sjoerg CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
44477330f729Sjoerg                                          ArrayRef<llvm::Value *> args,
44487330f729Sjoerg                                          const Twine &name) {
44497330f729Sjoerg   llvm::CallBase *call = EmitCallOrInvoke(callee, args, name);
44507330f729Sjoerg   call->setCallingConv(getRuntimeCC());
44517330f729Sjoerg   return call;
44527330f729Sjoerg }
44537330f729Sjoerg 
44547330f729Sjoerg /// Emits a call or invoke instruction to the given function, depending
44557330f729Sjoerg /// on the current state of the EH stack.
EmitCallOrInvoke(llvm::FunctionCallee Callee,ArrayRef<llvm::Value * > Args,const Twine & Name)44567330f729Sjoerg llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee,
44577330f729Sjoerg                                                   ArrayRef<llvm::Value *> Args,
44587330f729Sjoerg                                                   const Twine &Name) {
44597330f729Sjoerg   llvm::BasicBlock *InvokeDest = getInvokeDest();
44607330f729Sjoerg   SmallVector<llvm::OperandBundleDef, 1> BundleList =
44617330f729Sjoerg       getBundlesForFunclet(Callee.getCallee());
44627330f729Sjoerg 
44637330f729Sjoerg   llvm::CallBase *Inst;
44647330f729Sjoerg   if (!InvokeDest)
44657330f729Sjoerg     Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
44667330f729Sjoerg   else {
44677330f729Sjoerg     llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
44687330f729Sjoerg     Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
44697330f729Sjoerg                                 Name);
44707330f729Sjoerg     EmitBlock(ContBB);
44717330f729Sjoerg   }
44727330f729Sjoerg 
44737330f729Sjoerg   // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
44747330f729Sjoerg   // optimizer it can aggressively ignore unwind edges.
44757330f729Sjoerg   if (CGM.getLangOpts().ObjCAutoRefCount)
44767330f729Sjoerg     AddObjCARCExceptionMetadata(Inst);
44777330f729Sjoerg 
44787330f729Sjoerg   return Inst;
44797330f729Sjoerg }
44807330f729Sjoerg 
deferPlaceholderReplacement(llvm::Instruction * Old,llvm::Value * New)44817330f729Sjoerg void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
44827330f729Sjoerg                                                   llvm::Value *New) {
4483*e038c9c4Sjoerg   DeferredReplacements.push_back(
4484*e038c9c4Sjoerg       std::make_pair(llvm::WeakTrackingVH(Old), New));
44857330f729Sjoerg }
44867330f729Sjoerg 
4487*e038c9c4Sjoerg namespace {
4488*e038c9c4Sjoerg 
4489*e038c9c4Sjoerg /// Specify given \p NewAlign as the alignment of return value attribute. If
4490*e038c9c4Sjoerg /// such attribute already exists, re-set it to the maximal one of two options.
4491*e038c9c4Sjoerg LLVM_NODISCARD llvm::AttributeList
maybeRaiseRetAlignmentAttribute(llvm::LLVMContext & Ctx,const llvm::AttributeList & Attrs,llvm::Align NewAlign)4492*e038c9c4Sjoerg maybeRaiseRetAlignmentAttribute(llvm::LLVMContext &Ctx,
4493*e038c9c4Sjoerg                                 const llvm::AttributeList &Attrs,
4494*e038c9c4Sjoerg                                 llvm::Align NewAlign) {
4495*e038c9c4Sjoerg   llvm::Align CurAlign = Attrs.getRetAlignment().valueOrOne();
4496*e038c9c4Sjoerg   if (CurAlign >= NewAlign)
4497*e038c9c4Sjoerg     return Attrs;
4498*e038c9c4Sjoerg   llvm::Attribute AlignAttr = llvm::Attribute::getWithAlignment(Ctx, NewAlign);
4499*e038c9c4Sjoerg   return Attrs
4500*e038c9c4Sjoerg       .removeAttribute(Ctx, llvm::AttributeList::ReturnIndex,
4501*e038c9c4Sjoerg                        llvm::Attribute::AttrKind::Alignment)
4502*e038c9c4Sjoerg       .addAttribute(Ctx, llvm::AttributeList::ReturnIndex, AlignAttr);
4503*e038c9c4Sjoerg }
4504*e038c9c4Sjoerg 
4505*e038c9c4Sjoerg template <typename AlignedAttrTy> class AbstractAssumeAlignedAttrEmitter {
4506*e038c9c4Sjoerg protected:
4507*e038c9c4Sjoerg   CodeGenFunction &CGF;
4508*e038c9c4Sjoerg 
4509*e038c9c4Sjoerg   /// We do nothing if this is, or becomes, nullptr.
4510*e038c9c4Sjoerg   const AlignedAttrTy *AA = nullptr;
4511*e038c9c4Sjoerg 
4512*e038c9c4Sjoerg   llvm::Value *Alignment = nullptr;      // May or may not be a constant.
4513*e038c9c4Sjoerg   llvm::ConstantInt *OffsetCI = nullptr; // Constant, hopefully zero.
4514*e038c9c4Sjoerg 
AbstractAssumeAlignedAttrEmitter(CodeGenFunction & CGF_,const Decl * FuncDecl)4515*e038c9c4Sjoerg   AbstractAssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
4516*e038c9c4Sjoerg       : CGF(CGF_) {
4517*e038c9c4Sjoerg     if (!FuncDecl)
4518*e038c9c4Sjoerg       return;
4519*e038c9c4Sjoerg     AA = FuncDecl->getAttr<AlignedAttrTy>();
4520*e038c9c4Sjoerg   }
4521*e038c9c4Sjoerg 
4522*e038c9c4Sjoerg public:
4523*e038c9c4Sjoerg   /// If we can, materialize the alignment as an attribute on return value.
4524*e038c9c4Sjoerg   LLVM_NODISCARD llvm::AttributeList
TryEmitAsCallSiteAttribute(const llvm::AttributeList & Attrs)4525*e038c9c4Sjoerg   TryEmitAsCallSiteAttribute(const llvm::AttributeList &Attrs) {
4526*e038c9c4Sjoerg     if (!AA || OffsetCI || CGF.SanOpts.has(SanitizerKind::Alignment))
4527*e038c9c4Sjoerg       return Attrs;
4528*e038c9c4Sjoerg     const auto *AlignmentCI = dyn_cast<llvm::ConstantInt>(Alignment);
4529*e038c9c4Sjoerg     if (!AlignmentCI)
4530*e038c9c4Sjoerg       return Attrs;
4531*e038c9c4Sjoerg     // We may legitimately have non-power-of-2 alignment here.
4532*e038c9c4Sjoerg     // If so, this is UB land, emit it via `@llvm.assume` instead.
4533*e038c9c4Sjoerg     if (!AlignmentCI->getValue().isPowerOf2())
4534*e038c9c4Sjoerg       return Attrs;
4535*e038c9c4Sjoerg     llvm::AttributeList NewAttrs = maybeRaiseRetAlignmentAttribute(
4536*e038c9c4Sjoerg         CGF.getLLVMContext(), Attrs,
4537*e038c9c4Sjoerg         llvm::Align(
4538*e038c9c4Sjoerg             AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment)));
4539*e038c9c4Sjoerg     AA = nullptr; // We're done. Disallow doing anything else.
4540*e038c9c4Sjoerg     return NewAttrs;
4541*e038c9c4Sjoerg   }
4542*e038c9c4Sjoerg 
4543*e038c9c4Sjoerg   /// Emit alignment assumption.
4544*e038c9c4Sjoerg   /// This is a general fallback that we take if either there is an offset,
4545*e038c9c4Sjoerg   /// or the alignment is variable or we are sanitizing for alignment.
EmitAsAnAssumption(SourceLocation Loc,QualType RetTy,RValue & Ret)4546*e038c9c4Sjoerg   void EmitAsAnAssumption(SourceLocation Loc, QualType RetTy, RValue &Ret) {
4547*e038c9c4Sjoerg     if (!AA)
4548*e038c9c4Sjoerg       return;
4549*e038c9c4Sjoerg     CGF.emitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc,
4550*e038c9c4Sjoerg                                 AA->getLocation(), Alignment, OffsetCI);
4551*e038c9c4Sjoerg     AA = nullptr; // We're done. Disallow doing anything else.
4552*e038c9c4Sjoerg   }
4553*e038c9c4Sjoerg };
4554*e038c9c4Sjoerg 
4555*e038c9c4Sjoerg /// Helper data structure to emit `AssumeAlignedAttr`.
4556*e038c9c4Sjoerg class AssumeAlignedAttrEmitter final
4557*e038c9c4Sjoerg     : public AbstractAssumeAlignedAttrEmitter<AssumeAlignedAttr> {
4558*e038c9c4Sjoerg public:
AssumeAlignedAttrEmitter(CodeGenFunction & CGF_,const Decl * FuncDecl)4559*e038c9c4Sjoerg   AssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
4560*e038c9c4Sjoerg       : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
4561*e038c9c4Sjoerg     if (!AA)
4562*e038c9c4Sjoerg       return;
4563*e038c9c4Sjoerg     // It is guaranteed that the alignment/offset are constants.
4564*e038c9c4Sjoerg     Alignment = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AA->getAlignment()));
4565*e038c9c4Sjoerg     if (Expr *Offset = AA->getOffset()) {
4566*e038c9c4Sjoerg       OffsetCI = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(Offset));
4567*e038c9c4Sjoerg       if (OffsetCI->isNullValue()) // Canonicalize zero offset to no offset.
4568*e038c9c4Sjoerg         OffsetCI = nullptr;
4569*e038c9c4Sjoerg     }
4570*e038c9c4Sjoerg   }
4571*e038c9c4Sjoerg };
4572*e038c9c4Sjoerg 
4573*e038c9c4Sjoerg /// Helper data structure to emit `AllocAlignAttr`.
4574*e038c9c4Sjoerg class AllocAlignAttrEmitter final
4575*e038c9c4Sjoerg     : public AbstractAssumeAlignedAttrEmitter<AllocAlignAttr> {
4576*e038c9c4Sjoerg public:
AllocAlignAttrEmitter(CodeGenFunction & CGF_,const Decl * FuncDecl,const CallArgList & CallArgs)4577*e038c9c4Sjoerg   AllocAlignAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl,
4578*e038c9c4Sjoerg                         const CallArgList &CallArgs)
4579*e038c9c4Sjoerg       : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
4580*e038c9c4Sjoerg     if (!AA)
4581*e038c9c4Sjoerg       return;
4582*e038c9c4Sjoerg     // Alignment may or may not be a constant, and that is okay.
4583*e038c9c4Sjoerg     Alignment = CallArgs[AA->getParamIndex().getLLVMIndex()]
4584*e038c9c4Sjoerg                     .getRValue(CGF)
4585*e038c9c4Sjoerg                     .getScalarVal();
4586*e038c9c4Sjoerg   }
4587*e038c9c4Sjoerg };
4588*e038c9c4Sjoerg 
4589*e038c9c4Sjoerg } // namespace
4590*e038c9c4Sjoerg 
EmitCall(const CGFunctionInfo & CallInfo,const CGCallee & Callee,ReturnValueSlot ReturnValue,const CallArgList & CallArgs,llvm::CallBase ** callOrInvoke,bool IsMustTail,SourceLocation Loc)45917330f729Sjoerg RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
45927330f729Sjoerg                                  const CGCallee &Callee,
45937330f729Sjoerg                                  ReturnValueSlot ReturnValue,
45947330f729Sjoerg                                  const CallArgList &CallArgs,
4595*e038c9c4Sjoerg                                  llvm::CallBase **callOrInvoke, bool IsMustTail,
45967330f729Sjoerg                                  SourceLocation Loc) {
45977330f729Sjoerg   // FIXME: We no longer need the types from CallArgs; lift up and simplify.
45987330f729Sjoerg 
45997330f729Sjoerg   assert(Callee.isOrdinary() || Callee.isVirtual());
46007330f729Sjoerg 
46017330f729Sjoerg   // Handle struct-return functions by passing a pointer to the
46027330f729Sjoerg   // location that we would like to return into.
46037330f729Sjoerg   QualType RetTy = CallInfo.getReturnType();
46047330f729Sjoerg   const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
46057330f729Sjoerg 
46067330f729Sjoerg   llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
46077330f729Sjoerg 
46087330f729Sjoerg   const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
4609*e038c9c4Sjoerg   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
46107330f729Sjoerg     // We can only guarantee that a function is called from the correct
46117330f729Sjoerg     // context/function based on the appropriate target attributes,
46127330f729Sjoerg     // so only check in the case where we have both always_inline and target
46137330f729Sjoerg     // since otherwise we could be making a conditional call after a check for
46147330f729Sjoerg     // the proper cpu features (and it won't cause code generation issues due to
46157330f729Sjoerg     // function based code generation).
46167330f729Sjoerg     if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
46177330f729Sjoerg         TargetDecl->hasAttr<TargetAttr>())
46187330f729Sjoerg       checkTargetFeatures(Loc, FD);
46197330f729Sjoerg 
4620*e038c9c4Sjoerg     // Some architectures (such as x86-64) have the ABI changed based on
4621*e038c9c4Sjoerg     // attribute-target/features. Give them a chance to diagnose.
4622*e038c9c4Sjoerg     CGM.getTargetCodeGenInfo().checkFunctionCallABI(
4623*e038c9c4Sjoerg         CGM, Loc, dyn_cast_or_null<FunctionDecl>(CurCodeDecl), FD, CallArgs);
4624*e038c9c4Sjoerg   }
4625*e038c9c4Sjoerg 
46267330f729Sjoerg #ifndef NDEBUG
46277330f729Sjoerg   if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) {
46287330f729Sjoerg     // For an inalloca varargs function, we don't expect CallInfo to match the
46297330f729Sjoerg     // function pointer's type, because the inalloca struct a will have extra
46307330f729Sjoerg     // fields in it for the varargs parameters.  Code later in this function
46317330f729Sjoerg     // bitcasts the function pointer to the type derived from CallInfo.
46327330f729Sjoerg     //
46337330f729Sjoerg     // In other cases, we assert that the types match up (until pointers stop
46347330f729Sjoerg     // having pointee types).
46357330f729Sjoerg     llvm::Type *TypeFromVal;
46367330f729Sjoerg     if (Callee.isVirtual())
46377330f729Sjoerg       TypeFromVal = Callee.getVirtualFunctionType();
46387330f729Sjoerg     else
46397330f729Sjoerg       TypeFromVal =
46407330f729Sjoerg           Callee.getFunctionPointer()->getType()->getPointerElementType();
46417330f729Sjoerg     assert(IRFuncTy == TypeFromVal);
46427330f729Sjoerg   }
46437330f729Sjoerg #endif
46447330f729Sjoerg 
46457330f729Sjoerg   // 1. Set up the arguments.
46467330f729Sjoerg 
46477330f729Sjoerg   // If we're using inalloca, insert the allocation after the stack save.
46487330f729Sjoerg   // FIXME: Do this earlier rather than hacking it in here!
46497330f729Sjoerg   Address ArgMemory = Address::invalid();
46507330f729Sjoerg   if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
46517330f729Sjoerg     const llvm::DataLayout &DL = CGM.getDataLayout();
46527330f729Sjoerg     llvm::Instruction *IP = CallArgs.getStackBase();
46537330f729Sjoerg     llvm::AllocaInst *AI;
46547330f729Sjoerg     if (IP) {
46557330f729Sjoerg       IP = IP->getNextNode();
46567330f729Sjoerg       AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(),
46577330f729Sjoerg                                 "argmem", IP);
46587330f729Sjoerg     } else {
46597330f729Sjoerg       AI = CreateTempAlloca(ArgStruct, "argmem");
46607330f729Sjoerg     }
46617330f729Sjoerg     auto Align = CallInfo.getArgStructAlignment();
46627330f729Sjoerg     AI->setAlignment(Align.getAsAlign());
46637330f729Sjoerg     AI->setUsedWithInAlloca(true);
46647330f729Sjoerg     assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
46657330f729Sjoerg     ArgMemory = Address(AI, Align);
46667330f729Sjoerg   }
46677330f729Sjoerg 
46687330f729Sjoerg   ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
46697330f729Sjoerg   SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
46707330f729Sjoerg 
46717330f729Sjoerg   // If the call returns a temporary with struct return, create a temporary
46727330f729Sjoerg   // alloca to hold the result, unless one is given to us.
46737330f729Sjoerg   Address SRetPtr = Address::invalid();
46747330f729Sjoerg   Address SRetAlloca = Address::invalid();
46757330f729Sjoerg   llvm::Value *UnusedReturnSizePtr = nullptr;
46767330f729Sjoerg   if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
46777330f729Sjoerg     if (!ReturnValue.isNull()) {
46787330f729Sjoerg       SRetPtr = ReturnValue.getValue();
46797330f729Sjoerg     } else {
46807330f729Sjoerg       SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca);
46817330f729Sjoerg       if (HaveInsertPoint() && ReturnValue.isUnused()) {
46827330f729Sjoerg         uint64_t size =
46837330f729Sjoerg             CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
46847330f729Sjoerg         UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer());
46857330f729Sjoerg       }
46867330f729Sjoerg     }
46877330f729Sjoerg     if (IRFunctionArgs.hasSRetArg()) {
46887330f729Sjoerg       IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
46897330f729Sjoerg     } else if (RetAI.isInAlloca()) {
46907330f729Sjoerg       Address Addr =
46917330f729Sjoerg           Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
46927330f729Sjoerg       Builder.CreateStore(SRetPtr.getPointer(), Addr);
46937330f729Sjoerg     }
46947330f729Sjoerg   }
46957330f729Sjoerg 
46967330f729Sjoerg   Address swiftErrorTemp = Address::invalid();
46977330f729Sjoerg   Address swiftErrorArg = Address::invalid();
46987330f729Sjoerg 
46997330f729Sjoerg   // When passing arguments using temporary allocas, we need to add the
47007330f729Sjoerg   // appropriate lifetime markers. This vector keeps track of all the lifetime
47017330f729Sjoerg   // markers that need to be ended right after the call.
47027330f729Sjoerg   SmallVector<CallLifetimeEnd, 2> CallLifetimeEndAfterCall;
47037330f729Sjoerg 
47047330f729Sjoerg   // Translate all of the arguments as necessary to match the IR lowering.
47057330f729Sjoerg   assert(CallInfo.arg_size() == CallArgs.size() &&
47067330f729Sjoerg          "Mismatch between function signature & arguments.");
47077330f729Sjoerg   unsigned ArgNo = 0;
47087330f729Sjoerg   CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
47097330f729Sjoerg   for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
47107330f729Sjoerg        I != E; ++I, ++info_it, ++ArgNo) {
47117330f729Sjoerg     const ABIArgInfo &ArgInfo = info_it->info;
47127330f729Sjoerg 
47137330f729Sjoerg     // Insert a padding argument to ensure proper alignment.
47147330f729Sjoerg     if (IRFunctionArgs.hasPaddingArg(ArgNo))
47157330f729Sjoerg       IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
47167330f729Sjoerg           llvm::UndefValue::get(ArgInfo.getPaddingType());
47177330f729Sjoerg 
47187330f729Sjoerg     unsigned FirstIRArg, NumIRArgs;
47197330f729Sjoerg     std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
47207330f729Sjoerg 
47217330f729Sjoerg     switch (ArgInfo.getKind()) {
47227330f729Sjoerg     case ABIArgInfo::InAlloca: {
47237330f729Sjoerg       assert(NumIRArgs == 0);
47247330f729Sjoerg       assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
47257330f729Sjoerg       if (I->isAggregate()) {
47267330f729Sjoerg         Address Addr = I->hasLValue()
4727*e038c9c4Sjoerg                            ? I->getKnownLValue().getAddress(*this)
47287330f729Sjoerg                            : I->getKnownRValue().getAggregateAddress();
47297330f729Sjoerg         llvm::Instruction *Placeholder =
47307330f729Sjoerg             cast<llvm::Instruction>(Addr.getPointer());
4731*e038c9c4Sjoerg 
4732*e038c9c4Sjoerg         if (!ArgInfo.getInAllocaIndirect()) {
4733*e038c9c4Sjoerg           // Replace the placeholder with the appropriate argument slot GEP.
47347330f729Sjoerg           CGBuilderTy::InsertPoint IP = Builder.saveIP();
47357330f729Sjoerg           Builder.SetInsertPoint(Placeholder);
4736*e038c9c4Sjoerg           Addr = Builder.CreateStructGEP(ArgMemory,
4737*e038c9c4Sjoerg                                          ArgInfo.getInAllocaFieldIndex());
47387330f729Sjoerg           Builder.restoreIP(IP);
4739*e038c9c4Sjoerg         } else {
4740*e038c9c4Sjoerg           // For indirect things such as overaligned structs, replace the
4741*e038c9c4Sjoerg           // placeholder with a regular aggregate temporary alloca. Store the
4742*e038c9c4Sjoerg           // address of this alloca into the struct.
4743*e038c9c4Sjoerg           Addr = CreateMemTemp(info_it->type, "inalloca.indirect.tmp");
4744*e038c9c4Sjoerg           Address ArgSlot = Builder.CreateStructGEP(
4745*e038c9c4Sjoerg               ArgMemory, ArgInfo.getInAllocaFieldIndex());
4746*e038c9c4Sjoerg           Builder.CreateStore(Addr.getPointer(), ArgSlot);
4747*e038c9c4Sjoerg         }
47487330f729Sjoerg         deferPlaceholderReplacement(Placeholder, Addr.getPointer());
4749*e038c9c4Sjoerg       } else if (ArgInfo.getInAllocaIndirect()) {
4750*e038c9c4Sjoerg         // Make a temporary alloca and store the address of it into the argument
4751*e038c9c4Sjoerg         // struct.
4752*e038c9c4Sjoerg         Address Addr = CreateMemTempWithoutCast(
4753*e038c9c4Sjoerg             I->Ty, getContext().getTypeAlignInChars(I->Ty),
4754*e038c9c4Sjoerg             "indirect-arg-temp");
4755*e038c9c4Sjoerg         I->copyInto(*this, Addr);
4756*e038c9c4Sjoerg         Address ArgSlot =
4757*e038c9c4Sjoerg             Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
4758*e038c9c4Sjoerg         Builder.CreateStore(Addr.getPointer(), ArgSlot);
47597330f729Sjoerg       } else {
47607330f729Sjoerg         // Store the RValue into the argument struct.
47617330f729Sjoerg         Address Addr =
47627330f729Sjoerg             Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
47637330f729Sjoerg         unsigned AS = Addr.getType()->getPointerAddressSpace();
47647330f729Sjoerg         llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
47657330f729Sjoerg         // There are some cases where a trivial bitcast is not avoidable.  The
47667330f729Sjoerg         // definition of a type later in a translation unit may change it's type
47677330f729Sjoerg         // from {}* to (%struct.foo*)*.
47687330f729Sjoerg         if (Addr.getType() != MemType)
47697330f729Sjoerg           Addr = Builder.CreateBitCast(Addr, MemType);
47707330f729Sjoerg         I->copyInto(*this, Addr);
47717330f729Sjoerg       }
47727330f729Sjoerg       break;
47737330f729Sjoerg     }
47747330f729Sjoerg 
4775*e038c9c4Sjoerg     case ABIArgInfo::Indirect:
4776*e038c9c4Sjoerg     case ABIArgInfo::IndirectAliased: {
47777330f729Sjoerg       assert(NumIRArgs == 1);
47787330f729Sjoerg       if (!I->isAggregate()) {
47797330f729Sjoerg         // Make a temporary alloca to pass the argument.
47807330f729Sjoerg         Address Addr = CreateMemTempWithoutCast(
47817330f729Sjoerg             I->Ty, ArgInfo.getIndirectAlign(), "indirect-arg-temp");
47827330f729Sjoerg         IRCallArgs[FirstIRArg] = Addr.getPointer();
47837330f729Sjoerg 
47847330f729Sjoerg         I->copyInto(*this, Addr);
47857330f729Sjoerg       } else {
47867330f729Sjoerg         // We want to avoid creating an unnecessary temporary+copy here;
47877330f729Sjoerg         // however, we need one in three cases:
47887330f729Sjoerg         // 1. If the argument is not byval, and we are required to copy the
47897330f729Sjoerg         //    source.  (This case doesn't occur on any common architecture.)
47907330f729Sjoerg         // 2. If the argument is byval, RV is not sufficiently aligned, and
47917330f729Sjoerg         //    we cannot force it to be sufficiently aligned.
47927330f729Sjoerg         // 3. If the argument is byval, but RV is not located in default
47937330f729Sjoerg         //    or alloca address space.
47947330f729Sjoerg         Address Addr = I->hasLValue()
4795*e038c9c4Sjoerg                            ? I->getKnownLValue().getAddress(*this)
47967330f729Sjoerg                            : I->getKnownRValue().getAggregateAddress();
47977330f729Sjoerg         llvm::Value *V = Addr.getPointer();
47987330f729Sjoerg         CharUnits Align = ArgInfo.getIndirectAlign();
47997330f729Sjoerg         const llvm::DataLayout *TD = &CGM.getDataLayout();
48007330f729Sjoerg 
48017330f729Sjoerg         assert((FirstIRArg >= IRFuncTy->getNumParams() ||
48027330f729Sjoerg                 IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() ==
48037330f729Sjoerg                     TD->getAllocaAddrSpace()) &&
48047330f729Sjoerg                "indirect argument must be in alloca address space");
48057330f729Sjoerg 
48067330f729Sjoerg         bool NeedCopy = false;
48077330f729Sjoerg 
48087330f729Sjoerg         if (Addr.getAlignment() < Align &&
4809*e038c9c4Sjoerg             llvm::getOrEnforceKnownAlignment(V, Align.getAsAlign(), *TD) <
4810*e038c9c4Sjoerg                 Align.getAsAlign()) {
48117330f729Sjoerg           NeedCopy = true;
48127330f729Sjoerg         } else if (I->hasLValue()) {
48137330f729Sjoerg           auto LV = I->getKnownLValue();
48147330f729Sjoerg           auto AS = LV.getAddressSpace();
48157330f729Sjoerg 
4816*e038c9c4Sjoerg           if (!ArgInfo.getIndirectByVal() ||
4817*e038c9c4Sjoerg               (LV.getAlignment() < getContext().getTypeAlignInChars(I->Ty))) {
48187330f729Sjoerg             NeedCopy = true;
48197330f729Sjoerg           }
48207330f729Sjoerg           if (!getLangOpts().OpenCL) {
48217330f729Sjoerg             if ((ArgInfo.getIndirectByVal() &&
48227330f729Sjoerg                 (AS != LangAS::Default &&
48237330f729Sjoerg                  AS != CGM.getASTAllocaAddressSpace()))) {
48247330f729Sjoerg               NeedCopy = true;
48257330f729Sjoerg             }
48267330f729Sjoerg           }
48277330f729Sjoerg           // For OpenCL even if RV is located in default or alloca address space
48287330f729Sjoerg           // we don't want to perform address space cast for it.
48297330f729Sjoerg           else if ((ArgInfo.getIndirectByVal() &&
48307330f729Sjoerg                     Addr.getType()->getAddressSpace() != IRFuncTy->
48317330f729Sjoerg                       getParamType(FirstIRArg)->getPointerAddressSpace())) {
48327330f729Sjoerg             NeedCopy = true;
48337330f729Sjoerg           }
48347330f729Sjoerg         }
48357330f729Sjoerg 
48367330f729Sjoerg         if (NeedCopy) {
48377330f729Sjoerg           // Create an aligned temporary, and copy to it.
48387330f729Sjoerg           Address AI = CreateMemTempWithoutCast(
48397330f729Sjoerg               I->Ty, ArgInfo.getIndirectAlign(), "byval-temp");
48407330f729Sjoerg           IRCallArgs[FirstIRArg] = AI.getPointer();
48417330f729Sjoerg 
48427330f729Sjoerg           // Emit lifetime markers for the temporary alloca.
48437330f729Sjoerg           uint64_t ByvalTempElementSize =
48447330f729Sjoerg               CGM.getDataLayout().getTypeAllocSize(AI.getElementType());
48457330f729Sjoerg           llvm::Value *LifetimeSize =
48467330f729Sjoerg               EmitLifetimeStart(ByvalTempElementSize, AI.getPointer());
48477330f729Sjoerg 
48487330f729Sjoerg           // Add cleanup code to emit the end lifetime marker after the call.
48497330f729Sjoerg           if (LifetimeSize) // In case we disabled lifetime markers.
48507330f729Sjoerg             CallLifetimeEndAfterCall.emplace_back(AI, LifetimeSize);
48517330f729Sjoerg 
48527330f729Sjoerg           // Generate the copy.
48537330f729Sjoerg           I->copyInto(*this, AI);
48547330f729Sjoerg         } else {
48557330f729Sjoerg           // Skip the extra memcpy call.
48567330f729Sjoerg           auto *T = V->getType()->getPointerElementType()->getPointerTo(
48577330f729Sjoerg               CGM.getDataLayout().getAllocaAddrSpace());
48587330f729Sjoerg           IRCallArgs[FirstIRArg] = getTargetHooks().performAddrSpaceCast(
48597330f729Sjoerg               *this, V, LangAS::Default, CGM.getASTAllocaAddressSpace(), T,
48607330f729Sjoerg               true);
48617330f729Sjoerg         }
48627330f729Sjoerg       }
48637330f729Sjoerg       break;
48647330f729Sjoerg     }
48657330f729Sjoerg 
48667330f729Sjoerg     case ABIArgInfo::Ignore:
48677330f729Sjoerg       assert(NumIRArgs == 0);
48687330f729Sjoerg       break;
48697330f729Sjoerg 
48707330f729Sjoerg     case ABIArgInfo::Extend:
48717330f729Sjoerg     case ABIArgInfo::Direct: {
48727330f729Sjoerg       if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
48737330f729Sjoerg           ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
48747330f729Sjoerg           ArgInfo.getDirectOffset() == 0) {
48757330f729Sjoerg         assert(NumIRArgs == 1);
48767330f729Sjoerg         llvm::Value *V;
48777330f729Sjoerg         if (!I->isAggregate())
48787330f729Sjoerg           V = I->getKnownRValue().getScalarVal();
48797330f729Sjoerg         else
48807330f729Sjoerg           V = Builder.CreateLoad(
4881*e038c9c4Sjoerg               I->hasLValue() ? I->getKnownLValue().getAddress(*this)
48827330f729Sjoerg                              : I->getKnownRValue().getAggregateAddress());
48837330f729Sjoerg 
48847330f729Sjoerg         // Implement swifterror by copying into a new swifterror argument.
48857330f729Sjoerg         // We'll write back in the normal path out of the call.
48867330f729Sjoerg         if (CallInfo.getExtParameterInfo(ArgNo).getABI()
48877330f729Sjoerg               == ParameterABI::SwiftErrorResult) {
48887330f729Sjoerg           assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
48897330f729Sjoerg 
48907330f729Sjoerg           QualType pointeeTy = I->Ty->getPointeeType();
48917330f729Sjoerg           swiftErrorArg =
48927330f729Sjoerg             Address(V, getContext().getTypeAlignInChars(pointeeTy));
48937330f729Sjoerg 
48947330f729Sjoerg           swiftErrorTemp =
48957330f729Sjoerg             CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
48967330f729Sjoerg           V = swiftErrorTemp.getPointer();
48977330f729Sjoerg           cast<llvm::AllocaInst>(V)->setSwiftError(true);
48987330f729Sjoerg 
48997330f729Sjoerg           llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
49007330f729Sjoerg           Builder.CreateStore(errorValue, swiftErrorTemp);
49017330f729Sjoerg         }
49027330f729Sjoerg 
49037330f729Sjoerg         // We might have to widen integers, but we should never truncate.
49047330f729Sjoerg         if (ArgInfo.getCoerceToType() != V->getType() &&
49057330f729Sjoerg             V->getType()->isIntegerTy())
49067330f729Sjoerg           V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
49077330f729Sjoerg 
49087330f729Sjoerg         // If the argument doesn't match, perform a bitcast to coerce it.  This
49097330f729Sjoerg         // can happen due to trivial type mismatches.
49107330f729Sjoerg         if (FirstIRArg < IRFuncTy->getNumParams() &&
49117330f729Sjoerg             V->getType() != IRFuncTy->getParamType(FirstIRArg))
49127330f729Sjoerg           V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
49137330f729Sjoerg 
49147330f729Sjoerg         IRCallArgs[FirstIRArg] = V;
49157330f729Sjoerg         break;
49167330f729Sjoerg       }
49177330f729Sjoerg 
49187330f729Sjoerg       // FIXME: Avoid the conversion through memory if possible.
49197330f729Sjoerg       Address Src = Address::invalid();
49207330f729Sjoerg       if (!I->isAggregate()) {
49217330f729Sjoerg         Src = CreateMemTemp(I->Ty, "coerce");
49227330f729Sjoerg         I->copyInto(*this, Src);
49237330f729Sjoerg       } else {
4924*e038c9c4Sjoerg         Src = I->hasLValue() ? I->getKnownLValue().getAddress(*this)
49257330f729Sjoerg                              : I->getKnownRValue().getAggregateAddress();
49267330f729Sjoerg       }
49277330f729Sjoerg 
49287330f729Sjoerg       // If the value is offset in memory, apply the offset now.
49297330f729Sjoerg       Src = emitAddressAtOffset(*this, Src, ArgInfo);
49307330f729Sjoerg 
49317330f729Sjoerg       // Fast-isel and the optimizer generally like scalar values better than
49327330f729Sjoerg       // FCAs, so we flatten them if this is safe to do for this argument.
49337330f729Sjoerg       llvm::StructType *STy =
49347330f729Sjoerg             dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
49357330f729Sjoerg       if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
4936*e038c9c4Sjoerg         llvm::Type *SrcTy = Src.getElementType();
49377330f729Sjoerg         uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
49387330f729Sjoerg         uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
49397330f729Sjoerg 
49407330f729Sjoerg         // If the source type is smaller than the destination type of the
49417330f729Sjoerg         // coerce-to logic, copy the source value into a temp alloca the size
49427330f729Sjoerg         // of the destination type to allow loading all of it. The bits past
49437330f729Sjoerg         // the source value are left undef.
49447330f729Sjoerg         if (SrcSize < DstSize) {
49457330f729Sjoerg           Address TempAlloca
49467330f729Sjoerg             = CreateTempAlloca(STy, Src.getAlignment(),
49477330f729Sjoerg                                Src.getName() + ".coerce");
49487330f729Sjoerg           Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
49497330f729Sjoerg           Src = TempAlloca;
49507330f729Sjoerg         } else {
49517330f729Sjoerg           Src = Builder.CreateBitCast(Src,
49527330f729Sjoerg                                       STy->getPointerTo(Src.getAddressSpace()));
49537330f729Sjoerg         }
49547330f729Sjoerg 
49557330f729Sjoerg         assert(NumIRArgs == STy->getNumElements());
49567330f729Sjoerg         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
49577330f729Sjoerg           Address EltPtr = Builder.CreateStructGEP(Src, i);
49587330f729Sjoerg           llvm::Value *LI = Builder.CreateLoad(EltPtr);
49597330f729Sjoerg           IRCallArgs[FirstIRArg + i] = LI;
49607330f729Sjoerg         }
49617330f729Sjoerg       } else {
49627330f729Sjoerg         // In the simple case, just pass the coerced loaded value.
49637330f729Sjoerg         assert(NumIRArgs == 1);
4964*e038c9c4Sjoerg         llvm::Value *Load =
49657330f729Sjoerg             CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
4966*e038c9c4Sjoerg 
4967*e038c9c4Sjoerg         if (CallInfo.isCmseNSCall()) {
4968*e038c9c4Sjoerg           // For certain parameter types, clear padding bits, as they may reveal
4969*e038c9c4Sjoerg           // sensitive information.
4970*e038c9c4Sjoerg           // Small struct/union types are passed as integer arrays.
4971*e038c9c4Sjoerg           auto *ATy = dyn_cast<llvm::ArrayType>(Load->getType());
4972*e038c9c4Sjoerg           if (ATy != nullptr && isa<RecordType>(I->Ty.getCanonicalType()))
4973*e038c9c4Sjoerg             Load = EmitCMSEClearRecord(Load, ATy, I->Ty);
4974*e038c9c4Sjoerg         }
4975*e038c9c4Sjoerg         IRCallArgs[FirstIRArg] = Load;
49767330f729Sjoerg       }
49777330f729Sjoerg 
49787330f729Sjoerg       break;
49797330f729Sjoerg     }
49807330f729Sjoerg 
49817330f729Sjoerg     case ABIArgInfo::CoerceAndExpand: {
49827330f729Sjoerg       auto coercionType = ArgInfo.getCoerceAndExpandType();
49837330f729Sjoerg       auto layout = CGM.getDataLayout().getStructLayout(coercionType);
49847330f729Sjoerg 
49857330f729Sjoerg       llvm::Value *tempSize = nullptr;
49867330f729Sjoerg       Address addr = Address::invalid();
49877330f729Sjoerg       Address AllocaAddr = Address::invalid();
49887330f729Sjoerg       if (I->isAggregate()) {
4989*e038c9c4Sjoerg         addr = I->hasLValue() ? I->getKnownLValue().getAddress(*this)
49907330f729Sjoerg                               : I->getKnownRValue().getAggregateAddress();
49917330f729Sjoerg 
49927330f729Sjoerg       } else {
49937330f729Sjoerg         RValue RV = I->getKnownRValue();
49947330f729Sjoerg         assert(RV.isScalar()); // complex should always just be direct
49957330f729Sjoerg 
49967330f729Sjoerg         llvm::Type *scalarType = RV.getScalarVal()->getType();
49977330f729Sjoerg         auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
49987330f729Sjoerg         auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType);
49997330f729Sjoerg 
50007330f729Sjoerg         // Materialize to a temporary.
50017330f729Sjoerg         addr = CreateTempAlloca(
50027330f729Sjoerg             RV.getScalarVal()->getType(),
50037330f729Sjoerg             CharUnits::fromQuantity(std::max(
50047330f729Sjoerg                 (unsigned)layout->getAlignment().value(), scalarAlign)),
50057330f729Sjoerg             "tmp",
50067330f729Sjoerg             /*ArraySize=*/nullptr, &AllocaAddr);
50077330f729Sjoerg         tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer());
50087330f729Sjoerg 
50097330f729Sjoerg         Builder.CreateStore(RV.getScalarVal(), addr);
50107330f729Sjoerg       }
50117330f729Sjoerg 
50127330f729Sjoerg       addr = Builder.CreateElementBitCast(addr, coercionType);
50137330f729Sjoerg 
50147330f729Sjoerg       unsigned IRArgPos = FirstIRArg;
50157330f729Sjoerg       for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
50167330f729Sjoerg         llvm::Type *eltType = coercionType->getElementType(i);
50177330f729Sjoerg         if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
50187330f729Sjoerg         Address eltAddr = Builder.CreateStructGEP(addr, i);
50197330f729Sjoerg         llvm::Value *elt = Builder.CreateLoad(eltAddr);
50207330f729Sjoerg         IRCallArgs[IRArgPos++] = elt;
50217330f729Sjoerg       }
50227330f729Sjoerg       assert(IRArgPos == FirstIRArg + NumIRArgs);
50237330f729Sjoerg 
50247330f729Sjoerg       if (tempSize) {
50257330f729Sjoerg         EmitLifetimeEnd(tempSize, AllocaAddr.getPointer());
50267330f729Sjoerg       }
50277330f729Sjoerg 
50287330f729Sjoerg       break;
50297330f729Sjoerg     }
50307330f729Sjoerg 
5031*e038c9c4Sjoerg     case ABIArgInfo::Expand: {
50327330f729Sjoerg       unsigned IRArgPos = FirstIRArg;
50337330f729Sjoerg       ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos);
50347330f729Sjoerg       assert(IRArgPos == FirstIRArg + NumIRArgs);
50357330f729Sjoerg       break;
50367330f729Sjoerg     }
50377330f729Sjoerg     }
5038*e038c9c4Sjoerg   }
50397330f729Sjoerg 
50407330f729Sjoerg   const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this);
50417330f729Sjoerg   llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer();
50427330f729Sjoerg 
50437330f729Sjoerg   // If we're using inalloca, set up that argument.
50447330f729Sjoerg   if (ArgMemory.isValid()) {
50457330f729Sjoerg     llvm::Value *Arg = ArgMemory.getPointer();
50467330f729Sjoerg     if (CallInfo.isVariadic()) {
50477330f729Sjoerg       // When passing non-POD arguments by value to variadic functions, we will
50487330f729Sjoerg       // end up with a variadic prototype and an inalloca call site.  In such
50497330f729Sjoerg       // cases, we can't do any parameter mismatch checks.  Give up and bitcast
50507330f729Sjoerg       // the callee.
50517330f729Sjoerg       unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace();
50527330f729Sjoerg       CalleePtr =
50537330f729Sjoerg           Builder.CreateBitCast(CalleePtr, IRFuncTy->getPointerTo(CalleeAS));
50547330f729Sjoerg     } else {
50557330f729Sjoerg       llvm::Type *LastParamTy =
50567330f729Sjoerg           IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
50577330f729Sjoerg       if (Arg->getType() != LastParamTy) {
50587330f729Sjoerg #ifndef NDEBUG
50597330f729Sjoerg         // Assert that these structs have equivalent element types.
50607330f729Sjoerg         llvm::StructType *FullTy = CallInfo.getArgStruct();
50617330f729Sjoerg         llvm::StructType *DeclaredTy = cast<llvm::StructType>(
50627330f729Sjoerg             cast<llvm::PointerType>(LastParamTy)->getElementType());
50637330f729Sjoerg         assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
50647330f729Sjoerg         for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
50657330f729Sjoerg                                                 DE = DeclaredTy->element_end(),
50667330f729Sjoerg                                                 FI = FullTy->element_begin();
50677330f729Sjoerg              DI != DE; ++DI, ++FI)
50687330f729Sjoerg           assert(*DI == *FI);
50697330f729Sjoerg #endif
50707330f729Sjoerg         Arg = Builder.CreateBitCast(Arg, LastParamTy);
50717330f729Sjoerg       }
50727330f729Sjoerg     }
50737330f729Sjoerg     assert(IRFunctionArgs.hasInallocaArg());
50747330f729Sjoerg     IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
50757330f729Sjoerg   }
50767330f729Sjoerg 
50777330f729Sjoerg   // 2. Prepare the function pointer.
50787330f729Sjoerg 
50797330f729Sjoerg   // If the callee is a bitcast of a non-variadic function to have a
50807330f729Sjoerg   // variadic function pointer type, check to see if we can remove the
50817330f729Sjoerg   // bitcast.  This comes up with unprototyped functions.
50827330f729Sjoerg   //
50837330f729Sjoerg   // This makes the IR nicer, but more importantly it ensures that we
50847330f729Sjoerg   // can inline the function at -O0 if it is marked always_inline.
50857330f729Sjoerg   auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT,
50867330f729Sjoerg                                    llvm::Value *Ptr) -> llvm::Function * {
50877330f729Sjoerg     if (!CalleeFT->isVarArg())
50887330f729Sjoerg       return nullptr;
50897330f729Sjoerg 
50907330f729Sjoerg     // Get underlying value if it's a bitcast
50917330f729Sjoerg     if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) {
50927330f729Sjoerg       if (CE->getOpcode() == llvm::Instruction::BitCast)
50937330f729Sjoerg         Ptr = CE->getOperand(0);
50947330f729Sjoerg     }
50957330f729Sjoerg 
50967330f729Sjoerg     llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr);
50977330f729Sjoerg     if (!OrigFn)
50987330f729Sjoerg       return nullptr;
50997330f729Sjoerg 
51007330f729Sjoerg     llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
51017330f729Sjoerg 
51027330f729Sjoerg     // If the original type is variadic, or if any of the component types
51037330f729Sjoerg     // disagree, we cannot remove the cast.
51047330f729Sjoerg     if (OrigFT->isVarArg() ||
51057330f729Sjoerg         OrigFT->getNumParams() != CalleeFT->getNumParams() ||
51067330f729Sjoerg         OrigFT->getReturnType() != CalleeFT->getReturnType())
51077330f729Sjoerg       return nullptr;
51087330f729Sjoerg 
51097330f729Sjoerg     for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
51107330f729Sjoerg       if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
51117330f729Sjoerg         return nullptr;
51127330f729Sjoerg 
51137330f729Sjoerg     return OrigFn;
51147330f729Sjoerg   };
51157330f729Sjoerg 
51167330f729Sjoerg   if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) {
51177330f729Sjoerg     CalleePtr = OrigFn;
51187330f729Sjoerg     IRFuncTy = OrigFn->getFunctionType();
51197330f729Sjoerg   }
51207330f729Sjoerg 
51217330f729Sjoerg   // 3. Perform the actual call.
51227330f729Sjoerg 
51237330f729Sjoerg   // Deactivate any cleanups that we're supposed to do immediately before
51247330f729Sjoerg   // the call.
51257330f729Sjoerg   if (!CallArgs.getCleanupsToDeactivate().empty())
51267330f729Sjoerg     deactivateArgCleanupsBeforeCall(*this, CallArgs);
51277330f729Sjoerg 
51287330f729Sjoerg   // Assert that the arguments we computed match up.  The IR verifier
51297330f729Sjoerg   // will catch this, but this is a common enough source of problems
51307330f729Sjoerg   // during IRGen changes that it's way better for debugging to catch
51317330f729Sjoerg   // it ourselves here.
51327330f729Sjoerg #ifndef NDEBUG
51337330f729Sjoerg   assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
51347330f729Sjoerg   for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
51357330f729Sjoerg     // Inalloca argument can have different type.
51367330f729Sjoerg     if (IRFunctionArgs.hasInallocaArg() &&
51377330f729Sjoerg         i == IRFunctionArgs.getInallocaArgNo())
51387330f729Sjoerg       continue;
51397330f729Sjoerg     if (i < IRFuncTy->getNumParams())
51407330f729Sjoerg       assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
51417330f729Sjoerg   }
51427330f729Sjoerg #endif
51437330f729Sjoerg 
51447330f729Sjoerg   // Update the largest vector width if any arguments have vector types.
51457330f729Sjoerg   for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
51467330f729Sjoerg     if (auto *VT = dyn_cast<llvm::VectorType>(IRCallArgs[i]->getType()))
5147*e038c9c4Sjoerg       LargestVectorWidth =
5148*e038c9c4Sjoerg           std::max((uint64_t)LargestVectorWidth,
5149*e038c9c4Sjoerg                    VT->getPrimitiveSizeInBits().getKnownMinSize());
51507330f729Sjoerg   }
51517330f729Sjoerg 
51527330f729Sjoerg   // Compute the calling convention and attributes.
51537330f729Sjoerg   unsigned CallingConv;
51547330f729Sjoerg   llvm::AttributeList Attrs;
51557330f729Sjoerg   CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
51567330f729Sjoerg                              Callee.getAbstractInfo(), Attrs, CallingConv,
5157*e038c9c4Sjoerg                              /*AttrOnCallSite=*/true,
5158*e038c9c4Sjoerg                              /*IsThunk=*/false);
5159*e038c9c4Sjoerg 
5160*e038c9c4Sjoerg   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
5161*e038c9c4Sjoerg     if (FD->hasAttr<StrictFPAttr>())
5162*e038c9c4Sjoerg       // All calls within a strictfp function are marked strictfp
5163*e038c9c4Sjoerg       Attrs =
5164*e038c9c4Sjoerg         Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
5165*e038c9c4Sjoerg                            llvm::Attribute::StrictFP);
5166*e038c9c4Sjoerg 
5167*e038c9c4Sjoerg   // Add call-site nomerge attribute if exists.
5168*e038c9c4Sjoerg   if (InNoMergeAttributedStmt)
5169*e038c9c4Sjoerg     Attrs =
5170*e038c9c4Sjoerg         Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
5171*e038c9c4Sjoerg                            llvm::Attribute::NoMerge);
51727330f729Sjoerg 
51737330f729Sjoerg   // Apply some call-site-specific attributes.
51747330f729Sjoerg   // TODO: work this into building the attribute set.
51757330f729Sjoerg 
51767330f729Sjoerg   // Apply always_inline to all calls within flatten functions.
51777330f729Sjoerg   // FIXME: should this really take priority over __try, below?
51787330f729Sjoerg   if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
51797330f729Sjoerg       !(TargetDecl && TargetDecl->hasAttr<NoInlineAttr>())) {
51807330f729Sjoerg     Attrs =
51817330f729Sjoerg         Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
51827330f729Sjoerg                            llvm::Attribute::AlwaysInline);
51837330f729Sjoerg   }
51847330f729Sjoerg 
51857330f729Sjoerg   // Disable inlining inside SEH __try blocks.
51867330f729Sjoerg   if (isSEHTryScope()) {
51877330f729Sjoerg     Attrs =
51887330f729Sjoerg         Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
51897330f729Sjoerg                            llvm::Attribute::NoInline);
51907330f729Sjoerg   }
51917330f729Sjoerg 
51927330f729Sjoerg   // Decide whether to use a call or an invoke.
51937330f729Sjoerg   bool CannotThrow;
51947330f729Sjoerg   if (currentFunctionUsesSEHTry()) {
51957330f729Sjoerg     // SEH cares about asynchronous exceptions, so everything can "throw."
51967330f729Sjoerg     CannotThrow = false;
51977330f729Sjoerg   } else if (isCleanupPadScope() &&
51987330f729Sjoerg              EHPersonality::get(*this).isMSVCXXPersonality()) {
51997330f729Sjoerg     // The MSVC++ personality will implicitly terminate the program if an
52007330f729Sjoerg     // exception is thrown during a cleanup outside of a try/catch.
52017330f729Sjoerg     // We don't need to model anything in IR to get this behavior.
52027330f729Sjoerg     CannotThrow = true;
52037330f729Sjoerg   } else {
52047330f729Sjoerg     // Otherwise, nounwind call sites will never throw.
5205*e038c9c4Sjoerg     CannotThrow = Attrs.hasFnAttribute(llvm::Attribute::NoUnwind);
5206*e038c9c4Sjoerg 
5207*e038c9c4Sjoerg     if (auto *FPtr = dyn_cast<llvm::Function>(CalleePtr))
5208*e038c9c4Sjoerg       if (FPtr->hasFnAttribute(llvm::Attribute::NoUnwind))
5209*e038c9c4Sjoerg         CannotThrow = true;
52107330f729Sjoerg   }
52117330f729Sjoerg 
52127330f729Sjoerg   // If we made a temporary, be sure to clean up after ourselves. Note that we
52137330f729Sjoerg   // can't depend on being inside of an ExprWithCleanups, so we need to manually
52147330f729Sjoerg   // pop this cleanup later on. Being eager about this is OK, since this
52157330f729Sjoerg   // temporary is 'invisible' outside of the callee.
52167330f729Sjoerg   if (UnusedReturnSizePtr)
52177330f729Sjoerg     pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca,
52187330f729Sjoerg                                          UnusedReturnSizePtr);
52197330f729Sjoerg 
52207330f729Sjoerg   llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
52217330f729Sjoerg 
52227330f729Sjoerg   SmallVector<llvm::OperandBundleDef, 1> BundleList =
52237330f729Sjoerg       getBundlesForFunclet(CalleePtr);
52247330f729Sjoerg 
5225*e038c9c4Sjoerg   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
5226*e038c9c4Sjoerg     if (FD->hasAttr<StrictFPAttr>())
5227*e038c9c4Sjoerg       // All calls within a strictfp function are marked strictfp
5228*e038c9c4Sjoerg       Attrs =
5229*e038c9c4Sjoerg         Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
5230*e038c9c4Sjoerg                            llvm::Attribute::StrictFP);
5231*e038c9c4Sjoerg 
5232*e038c9c4Sjoerg   AssumeAlignedAttrEmitter AssumeAlignedAttrEmitter(*this, TargetDecl);
5233*e038c9c4Sjoerg   Attrs = AssumeAlignedAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
5234*e038c9c4Sjoerg 
5235*e038c9c4Sjoerg   AllocAlignAttrEmitter AllocAlignAttrEmitter(*this, TargetDecl, CallArgs);
5236*e038c9c4Sjoerg   Attrs = AllocAlignAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
5237*e038c9c4Sjoerg 
52387330f729Sjoerg   // Emit the actual call/invoke instruction.
52397330f729Sjoerg   llvm::CallBase *CI;
52407330f729Sjoerg   if (!InvokeDest) {
52417330f729Sjoerg     CI = Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList);
52427330f729Sjoerg   } else {
52437330f729Sjoerg     llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
52447330f729Sjoerg     CI = Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs,
52457330f729Sjoerg                               BundleList);
52467330f729Sjoerg     EmitBlock(Cont);
52477330f729Sjoerg   }
52487330f729Sjoerg   if (callOrInvoke)
52497330f729Sjoerg     *callOrInvoke = CI;
52507330f729Sjoerg 
5251*e038c9c4Sjoerg   // If this is within a function that has the guard(nocf) attribute and is an
5252*e038c9c4Sjoerg   // indirect call, add the "guard_nocf" attribute to this call to indicate that
5253*e038c9c4Sjoerg   // Control Flow Guard checks should not be added, even if the call is inlined.
5254*e038c9c4Sjoerg   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
5255*e038c9c4Sjoerg     if (const auto *A = FD->getAttr<CFGuardAttr>()) {
5256*e038c9c4Sjoerg       if (A->getGuard() == CFGuardAttr::GuardArg::nocf && !CI->getCalledFunction())
5257*e038c9c4Sjoerg         Attrs = Attrs.addAttribute(
5258*e038c9c4Sjoerg             getLLVMContext(), llvm::AttributeList::FunctionIndex, "guard_nocf");
5259*e038c9c4Sjoerg     }
5260*e038c9c4Sjoerg   }
5261*e038c9c4Sjoerg 
52627330f729Sjoerg   // Apply the attributes and calling convention.
52637330f729Sjoerg   CI->setAttributes(Attrs);
52647330f729Sjoerg   CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
52657330f729Sjoerg 
52667330f729Sjoerg   // Apply various metadata.
52677330f729Sjoerg 
52687330f729Sjoerg   if (!CI->getType()->isVoidTy())
52697330f729Sjoerg     CI->setName("call");
52707330f729Sjoerg 
52717330f729Sjoerg   // Update largest vector width from the return type.
52727330f729Sjoerg   if (auto *VT = dyn_cast<llvm::VectorType>(CI->getType()))
5273*e038c9c4Sjoerg     LargestVectorWidth =
5274*e038c9c4Sjoerg         std::max((uint64_t)LargestVectorWidth,
5275*e038c9c4Sjoerg                  VT->getPrimitiveSizeInBits().getKnownMinSize());
52767330f729Sjoerg 
52777330f729Sjoerg   // Insert instrumentation or attach profile metadata at indirect call sites.
52787330f729Sjoerg   // For more details, see the comment before the definition of
52797330f729Sjoerg   // IPVK_IndirectCallTarget in InstrProfData.inc.
52807330f729Sjoerg   if (!CI->getCalledFunction())
52817330f729Sjoerg     PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
52827330f729Sjoerg                      CI, CalleePtr);
52837330f729Sjoerg 
52847330f729Sjoerg   // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
52857330f729Sjoerg   // optimizer it can aggressively ignore unwind edges.
52867330f729Sjoerg   if (CGM.getLangOpts().ObjCAutoRefCount)
52877330f729Sjoerg     AddObjCARCExceptionMetadata(CI);
52887330f729Sjoerg 
5289*e038c9c4Sjoerg   // Set tail call kind if necessary.
52907330f729Sjoerg   if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
52917330f729Sjoerg     if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
52927330f729Sjoerg       Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
5293*e038c9c4Sjoerg     else if (IsMustTail)
5294*e038c9c4Sjoerg       Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
52957330f729Sjoerg   }
52967330f729Sjoerg 
52977330f729Sjoerg   // Add metadata for calls to MSAllocator functions
52987330f729Sjoerg   if (getDebugInfo() && TargetDecl &&
52997330f729Sjoerg       TargetDecl->hasAttr<MSAllocatorAttr>())
5300*e038c9c4Sjoerg     getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy->getPointeeType(), Loc);
53017330f729Sjoerg 
53027330f729Sjoerg   // 4. Finish the call.
53037330f729Sjoerg 
53047330f729Sjoerg   // If the call doesn't return, finish the basic block and clear the
53057330f729Sjoerg   // insertion point; this allows the rest of IRGen to discard
53067330f729Sjoerg   // unreachable code.
53077330f729Sjoerg   if (CI->doesNotReturn()) {
53087330f729Sjoerg     if (UnusedReturnSizePtr)
53097330f729Sjoerg       PopCleanupBlock();
53107330f729Sjoerg 
53117330f729Sjoerg     // Strip away the noreturn attribute to better diagnose unreachable UB.
53127330f729Sjoerg     if (SanOpts.has(SanitizerKind::Unreachable)) {
53137330f729Sjoerg       // Also remove from function since CallBase::hasFnAttr additionally checks
53147330f729Sjoerg       // attributes of the called function.
53157330f729Sjoerg       if (auto *F = CI->getCalledFunction())
53167330f729Sjoerg         F->removeFnAttr(llvm::Attribute::NoReturn);
53177330f729Sjoerg       CI->removeAttribute(llvm::AttributeList::FunctionIndex,
53187330f729Sjoerg                           llvm::Attribute::NoReturn);
53197330f729Sjoerg 
53207330f729Sjoerg       // Avoid incompatibility with ASan which relies on the `noreturn`
53217330f729Sjoerg       // attribute to insert handler calls.
53227330f729Sjoerg       if (SanOpts.hasOneOf(SanitizerKind::Address |
53237330f729Sjoerg                            SanitizerKind::KernelAddress)) {
53247330f729Sjoerg         SanitizerScope SanScope(this);
53257330f729Sjoerg         llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder);
53267330f729Sjoerg         Builder.SetInsertPoint(CI);
53277330f729Sjoerg         auto *FnType = llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
53287330f729Sjoerg         llvm::FunctionCallee Fn =
53297330f729Sjoerg             CGM.CreateRuntimeFunction(FnType, "__asan_handle_no_return");
53307330f729Sjoerg         EmitNounwindRuntimeCall(Fn);
53317330f729Sjoerg       }
53327330f729Sjoerg     }
53337330f729Sjoerg 
53347330f729Sjoerg     EmitUnreachable(Loc);
53357330f729Sjoerg     Builder.ClearInsertionPoint();
53367330f729Sjoerg 
53377330f729Sjoerg     // FIXME: For now, emit a dummy basic block because expr emitters in
53387330f729Sjoerg     // generally are not ready to handle emitting expressions at unreachable
53397330f729Sjoerg     // points.
53407330f729Sjoerg     EnsureInsertPoint();
53417330f729Sjoerg 
53427330f729Sjoerg     // Return a reasonable RValue.
53437330f729Sjoerg     return GetUndefRValue(RetTy);
53447330f729Sjoerg   }
53457330f729Sjoerg 
5346*e038c9c4Sjoerg   // If this is a musttail call, return immediately. We do not branch to the
5347*e038c9c4Sjoerg   // epilogue in this case.
5348*e038c9c4Sjoerg   if (IsMustTail) {
5349*e038c9c4Sjoerg     for (auto it = EHStack.find(CurrentCleanupScopeDepth); it != EHStack.end();
5350*e038c9c4Sjoerg          ++it) {
5351*e038c9c4Sjoerg       EHCleanupScope *Cleanup = dyn_cast<EHCleanupScope>(&*it);
5352*e038c9c4Sjoerg       if (!(Cleanup && Cleanup->getCleanup()->isRedundantBeforeReturn()))
5353*e038c9c4Sjoerg         CGM.ErrorUnsupported(MustTailCall, "tail call skipping over cleanups");
5354*e038c9c4Sjoerg     }
5355*e038c9c4Sjoerg     if (CI->getType()->isVoidTy())
5356*e038c9c4Sjoerg       Builder.CreateRetVoid();
5357*e038c9c4Sjoerg     else
5358*e038c9c4Sjoerg       Builder.CreateRet(CI);
5359*e038c9c4Sjoerg     Builder.ClearInsertionPoint();
5360*e038c9c4Sjoerg     EnsureInsertPoint();
5361*e038c9c4Sjoerg     return GetUndefRValue(RetTy);
5362*e038c9c4Sjoerg   }
5363*e038c9c4Sjoerg 
53647330f729Sjoerg   // Perform the swifterror writeback.
53657330f729Sjoerg   if (swiftErrorTemp.isValid()) {
53667330f729Sjoerg     llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
53677330f729Sjoerg     Builder.CreateStore(errorResult, swiftErrorArg);
53687330f729Sjoerg   }
53697330f729Sjoerg 
53707330f729Sjoerg   // Emit any call-associated writebacks immediately.  Arguably this
53717330f729Sjoerg   // should happen after any return-value munging.
53727330f729Sjoerg   if (CallArgs.hasWritebacks())
53737330f729Sjoerg     emitWritebacks(*this, CallArgs);
53747330f729Sjoerg 
53757330f729Sjoerg   // The stack cleanup for inalloca arguments has to run out of the normal
53767330f729Sjoerg   // lexical order, so deactivate it and run it manually here.
53777330f729Sjoerg   CallArgs.freeArgumentMemory(*this);
53787330f729Sjoerg 
53797330f729Sjoerg   // Extract the return value.
53807330f729Sjoerg   RValue Ret = [&] {
53817330f729Sjoerg     switch (RetAI.getKind()) {
53827330f729Sjoerg     case ABIArgInfo::CoerceAndExpand: {
53837330f729Sjoerg       auto coercionType = RetAI.getCoerceAndExpandType();
53847330f729Sjoerg 
53857330f729Sjoerg       Address addr = SRetPtr;
53867330f729Sjoerg       addr = Builder.CreateElementBitCast(addr, coercionType);
53877330f729Sjoerg 
53887330f729Sjoerg       assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
53897330f729Sjoerg       bool requiresExtract = isa<llvm::StructType>(CI->getType());
53907330f729Sjoerg 
53917330f729Sjoerg       unsigned unpaddedIndex = 0;
53927330f729Sjoerg       for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
53937330f729Sjoerg         llvm::Type *eltType = coercionType->getElementType(i);
53947330f729Sjoerg         if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
53957330f729Sjoerg         Address eltAddr = Builder.CreateStructGEP(addr, i);
53967330f729Sjoerg         llvm::Value *elt = CI;
53977330f729Sjoerg         if (requiresExtract)
53987330f729Sjoerg           elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
53997330f729Sjoerg         else
54007330f729Sjoerg           assert(unpaddedIndex == 0);
54017330f729Sjoerg         Builder.CreateStore(elt, eltAddr);
54027330f729Sjoerg       }
54037330f729Sjoerg       // FALLTHROUGH
54047330f729Sjoerg       LLVM_FALLTHROUGH;
54057330f729Sjoerg     }
54067330f729Sjoerg 
54077330f729Sjoerg     case ABIArgInfo::InAlloca:
54087330f729Sjoerg     case ABIArgInfo::Indirect: {
54097330f729Sjoerg       RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
54107330f729Sjoerg       if (UnusedReturnSizePtr)
54117330f729Sjoerg         PopCleanupBlock();
54127330f729Sjoerg       return ret;
54137330f729Sjoerg     }
54147330f729Sjoerg 
54157330f729Sjoerg     case ABIArgInfo::Ignore:
54167330f729Sjoerg       // If we are ignoring an argument that had a result, make sure to
54177330f729Sjoerg       // construct the appropriate return value for our caller.
54187330f729Sjoerg       return GetUndefRValue(RetTy);
54197330f729Sjoerg 
54207330f729Sjoerg     case ABIArgInfo::Extend:
54217330f729Sjoerg     case ABIArgInfo::Direct: {
54227330f729Sjoerg       llvm::Type *RetIRTy = ConvertType(RetTy);
54237330f729Sjoerg       if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
54247330f729Sjoerg         switch (getEvaluationKind(RetTy)) {
54257330f729Sjoerg         case TEK_Complex: {
54267330f729Sjoerg           llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
54277330f729Sjoerg           llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
54287330f729Sjoerg           return RValue::getComplex(std::make_pair(Real, Imag));
54297330f729Sjoerg         }
54307330f729Sjoerg         case TEK_Aggregate: {
54317330f729Sjoerg           Address DestPtr = ReturnValue.getValue();
54327330f729Sjoerg           bool DestIsVolatile = ReturnValue.isVolatile();
54337330f729Sjoerg 
54347330f729Sjoerg           if (!DestPtr.isValid()) {
54357330f729Sjoerg             DestPtr = CreateMemTemp(RetTy, "agg.tmp");
54367330f729Sjoerg             DestIsVolatile = false;
54377330f729Sjoerg           }
5438*e038c9c4Sjoerg           EmitAggregateStore(CI, DestPtr, DestIsVolatile);
54397330f729Sjoerg           return RValue::getAggregate(DestPtr);
54407330f729Sjoerg         }
54417330f729Sjoerg         case TEK_Scalar: {
54427330f729Sjoerg           // If the argument doesn't match, perform a bitcast to coerce it.  This
54437330f729Sjoerg           // can happen due to trivial type mismatches.
54447330f729Sjoerg           llvm::Value *V = CI;
54457330f729Sjoerg           if (V->getType() != RetIRTy)
54467330f729Sjoerg             V = Builder.CreateBitCast(V, RetIRTy);
54477330f729Sjoerg           return RValue::get(V);
54487330f729Sjoerg         }
54497330f729Sjoerg         }
54507330f729Sjoerg         llvm_unreachable("bad evaluation kind");
54517330f729Sjoerg       }
54527330f729Sjoerg 
54537330f729Sjoerg       Address DestPtr = ReturnValue.getValue();
54547330f729Sjoerg       bool DestIsVolatile = ReturnValue.isVolatile();
54557330f729Sjoerg 
54567330f729Sjoerg       if (!DestPtr.isValid()) {
54577330f729Sjoerg         DestPtr = CreateMemTemp(RetTy, "coerce");
54587330f729Sjoerg         DestIsVolatile = false;
54597330f729Sjoerg       }
54607330f729Sjoerg 
54617330f729Sjoerg       // If the value is offset in memory, apply the offset now.
54627330f729Sjoerg       Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
54637330f729Sjoerg       CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
54647330f729Sjoerg 
54657330f729Sjoerg       return convertTempToRValue(DestPtr, RetTy, SourceLocation());
54667330f729Sjoerg     }
54677330f729Sjoerg 
54687330f729Sjoerg     case ABIArgInfo::Expand:
5469*e038c9c4Sjoerg     case ABIArgInfo::IndirectAliased:
54707330f729Sjoerg       llvm_unreachable("Invalid ABI kind for return argument");
54717330f729Sjoerg     }
54727330f729Sjoerg 
54737330f729Sjoerg     llvm_unreachable("Unhandled ABIArgInfo::Kind");
54747330f729Sjoerg   } ();
54757330f729Sjoerg 
54767330f729Sjoerg   // Emit the assume_aligned check on the return value.
54777330f729Sjoerg   if (Ret.isScalar() && TargetDecl) {
5478*e038c9c4Sjoerg     AssumeAlignedAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
5479*e038c9c4Sjoerg     AllocAlignAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
54807330f729Sjoerg   }
54817330f729Sjoerg 
54827330f729Sjoerg   // Explicitly call CallLifetimeEnd::Emit just to re-use the code even though
54837330f729Sjoerg   // we can't use the full cleanup mechanism.
54847330f729Sjoerg   for (CallLifetimeEnd &LifetimeEnd : CallLifetimeEndAfterCall)
54857330f729Sjoerg     LifetimeEnd.Emit(*this, /*Flags=*/{});
54867330f729Sjoerg 
5487*e038c9c4Sjoerg   if (!ReturnValue.isExternallyDestructed() &&
5488*e038c9c4Sjoerg       RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct)
5489*e038c9c4Sjoerg     pushDestroy(QualType::DK_nontrivial_c_struct, Ret.getAggregateAddress(),
5490*e038c9c4Sjoerg                 RetTy);
5491*e038c9c4Sjoerg 
54927330f729Sjoerg   return Ret;
54937330f729Sjoerg }
54947330f729Sjoerg 
prepareConcreteCallee(CodeGenFunction & CGF) const54957330f729Sjoerg CGCallee CGCallee::prepareConcreteCallee(CodeGenFunction &CGF) const {
54967330f729Sjoerg   if (isVirtual()) {
54977330f729Sjoerg     const CallExpr *CE = getVirtualCallExpr();
54987330f729Sjoerg     return CGF.CGM.getCXXABI().getVirtualFunctionPointer(
54997330f729Sjoerg         CGF, getVirtualMethodDecl(), getThisAddress(), getVirtualFunctionType(),
55007330f729Sjoerg         CE ? CE->getBeginLoc() : SourceLocation());
55017330f729Sjoerg   }
55027330f729Sjoerg 
55037330f729Sjoerg   return *this;
55047330f729Sjoerg }
55057330f729Sjoerg 
55067330f729Sjoerg /* VarArg handling */
55077330f729Sjoerg 
EmitVAArg(VAArgExpr * VE,Address & VAListAddr)55087330f729Sjoerg Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
55097330f729Sjoerg   VAListAddr = VE->isMicrosoftABI()
55107330f729Sjoerg                  ? EmitMSVAListRef(VE->getSubExpr())
55117330f729Sjoerg                  : EmitVAListRef(VE->getSubExpr());
55127330f729Sjoerg   QualType Ty = VE->getType();
55137330f729Sjoerg   if (VE->isMicrosoftABI())
55147330f729Sjoerg     return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
55157330f729Sjoerg   return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
55167330f729Sjoerg }
5517