#include "CGCall.h"
#include "ABIInfo.h"
#include "CGBlocks.h"
#include "CGCXXABI.h"
#include "CGCleanup.h"
#include "CGRecordLayout.h"
#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "TargetInfo.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/Basic/CodeGenOptions.h"
#include "clang/Basic/TargetBuiltins.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/CodeGen/CGFunctionInfo.h"
#include "clang/CodeGen/SwiftCallingConv.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/Assumptions.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Type.h"
#include "llvm/Transforms/Utils/Local.h"
using namespace clang;
using namespace CodeGen;
unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC) {
switch (CC) {
default: return llvm::CallingConv::C;
case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
case CC_X86RegCall: return llvm::CallingConv::X86_RegCall;
case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
case CC_Win64: return llvm::CallingConv::Win64;
case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
case CC_X86Pascal: return llvm::CallingConv::C;
case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
case CC_AArch64VectorCall: return llvm::CallingConv::AArch64_VectorCall;
case CC_AArch64SVEPCS: return llvm::CallingConv::AArch64_SVE_VectorCall;
case CC_AMDGPUKernelCall: return llvm::CallingConv::AMDGPU_KERNEL;
case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv();
case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
case CC_Swift: return llvm::CallingConv::Swift;
case CC_SwiftAsync: return llvm::CallingConv::SwiftTail;
}
}
CanQualType CodeGenTypes::DeriveThisType(const CXXRecordDecl *RD,
const CXXMethodDecl *MD) {
QualType RecTy;
if (RD)
RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
else
RecTy = Context.VoidTy;
if (MD)
RecTy = Context.getAddrSpaceQualType(RecTy, MD->getMethodQualifiers().getAddressSpace());
return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
}
static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
return MD->getType()->getCanonicalTypeUnqualified()
.getAs<FunctionProtoType>();
}
static CanQualType GetReturnType(QualType RetTy) {
return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
}
const CGFunctionInfo &
CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
false,
false, None,
FTNP->getExtInfo(), {}, RequiredArgs(0));
}
static void addExtParameterInfosForCall(
llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> ¶mInfos,
const FunctionProtoType *proto,
unsigned prefixArgs,
unsigned totalArgs) {
assert(proto->hasExtParameterInfos());
assert(paramInfos.size() <= prefixArgs);
assert(proto->getNumParams() + prefixArgs <= totalArgs);
paramInfos.reserve(totalArgs);
paramInfos.resize(prefixArgs);
for (const auto &ParamInfo : proto->getExtParameterInfos()) {
paramInfos.push_back(ParamInfo);
if (ParamInfo.hasPassObjectSize())
paramInfos.emplace_back();
}
assert(paramInfos.size() <= totalArgs &&
"Did we forget to insert pass_object_size args?");
paramInfos.resize(totalArgs);
}
static void appendParameterTypes(const CodeGenTypes &CGT,
SmallVectorImpl<CanQualType> &prefix,
SmallVectorImpl<FunctionProtoType::ExtParameterInfo> ¶mInfos,
CanQual<FunctionProtoType> FPT) {
if (!FPT->hasExtParameterInfos()) {
assert(paramInfos.empty() &&
"We have paramInfos, but the prototype doesn't?");
prefix.append(FPT->param_type_begin(), FPT->param_type_end());
return;
}
unsigned PrefixSize = prefix.size();
prefix.reserve(prefix.size() + FPT->getNumParams());
auto ExtInfos = FPT->getExtParameterInfos();
assert(ExtInfos.size() == FPT->getNumParams());
for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
prefix.push_back(FPT->getParamType(I));
if (ExtInfos[I].hasPassObjectSize())
prefix.push_back(CGT.getContext().getSizeType());
}
addExtParameterInfosForCall(paramInfos, FPT.getTypePtr(), PrefixSize,
prefix.size());
}
static const CGFunctionInfo &
arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
SmallVectorImpl<CanQualType> &prefix,
CanQual<FunctionProtoType> FTP) {
SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
RequiredArgs Required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
appendParameterTypes(CGT, prefix, paramInfos, FTP);
CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
false, prefix,
FTP->getExtInfo(), paramInfos,
Required);
}
const CGFunctionInfo &
CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
SmallVector<CanQualType, 16> argTypes;
return ::arrangeLLVMFunctionInfo(*this, false, argTypes,
FTP);
}
static CallingConv getCallingConventionForDecl(const ObjCMethodDecl *D,
bool IsWindows) {
if (D->hasAttr<StdCallAttr>())
return CC_X86StdCall;
if (D->hasAttr<FastCallAttr>())
return CC_X86FastCall;
if (D->hasAttr<RegCallAttr>())
return CC_X86RegCall;
if (D->hasAttr<ThisCallAttr>())
return CC_X86ThisCall;
if (D->hasAttr<VectorCallAttr>())
return CC_X86VectorCall;
if (D->hasAttr<PascalAttr>())
return CC_X86Pascal;
if (PcsAttr *PCS = D->getAttr<PcsAttr>())
return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
if (D->hasAttr<AArch64VectorPcsAttr>())
return CC_AArch64VectorCall;
if (D->hasAttr<AArch64SVEPcsAttr>())
return CC_AArch64SVEPCS;
if (D->hasAttr<AMDGPUKernelCallAttr>())
return CC_AMDGPUKernelCall;
if (D->hasAttr<IntelOclBiccAttr>())
return CC_IntelOclBicc;
if (D->hasAttr<MSABIAttr>())
return IsWindows ? CC_C : CC_Win64;
if (D->hasAttr<SysVABIAttr>())
return IsWindows ? CC_X86_64SysV : CC_C;
if (D->hasAttr<PreserveMostAttr>())
return CC_PreserveMost;
if (D->hasAttr<PreserveAllAttr>())
return CC_PreserveAll;
return CC_C;
}
const CGFunctionInfo &
CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
const FunctionProtoType *FTP,
const CXXMethodDecl *MD) {
SmallVector<CanQualType, 16> argTypes;
argTypes.push_back(DeriveThisType(RD, MD));
return ::arrangeLLVMFunctionInfo(
*this, true, argTypes,
FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
}
static void setCUDAKernelCallingConvention(CanQualType &FTy, CodeGenModule &CGM,
const FunctionDecl *FD) {
if (FD->hasAttr<CUDAGlobalAttr>()) {
const FunctionType *FT = FTy->getAs<FunctionType>();
CGM.getTargetCodeGenInfo().setCUDAKernelCallingConvention(FT);
FTy = FT->getCanonicalTypeUnqualified();
}
}
const CGFunctionInfo &
CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
CanQualType FT = GetFormalType(MD).getAs<Type>();
setCUDAKernelCallingConvention(FT, CGM, MD);
auto prototype = FT.getAs<FunctionProtoType>();
if (MD->isInstance()) {
const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
}
return arrangeFreeFunctionType(prototype);
}
bool CodeGenTypes::inheritingCtorHasParams(
const InheritedConstructor &Inherited, CXXCtorType Type) {
return Type == Ctor_Complete ||
!Inherited.getShadowDecl()->constructsVirtualBase() ||
!Target.getCXXABI().hasConstructorVariants();
}
const CGFunctionInfo &
CodeGenTypes::arrangeCXXStructorDeclaration(GlobalDecl GD) {
auto *MD = cast<CXXMethodDecl>(GD.getDecl());
SmallVector<CanQualType, 16> argTypes;
SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
argTypes.push_back(DeriveThisType(MD->getParent(), MD));
bool PassParams = true;
if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
if (auto Inherited = CD->getInheritedConstructor())
PassParams = inheritingCtorHasParams(Inherited, GD.getCtorType());
}
CanQual<FunctionProtoType> FTP = GetFormalType(MD);
if (PassParams)
appendParameterTypes(*this, argTypes, paramInfos, FTP);
CGCXXABI::AddedStructorArgCounts AddedArgs =
TheCXXABI.buildStructorSignature(GD, argTypes);
if (!paramInfos.empty()) {
if (AddedArgs.Prefix)
paramInfos.insert(paramInfos.begin() + 1, AddedArgs.Prefix,
FunctionProtoType::ExtParameterInfo{});
if (AddedArgs.Suffix)
paramInfos.append(AddedArgs.Suffix,
FunctionProtoType::ExtParameterInfo{});
}
RequiredArgs required =
(PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
: RequiredArgs::All);
FunctionType::ExtInfo extInfo = FTP->getExtInfo();
CanQualType resultType = TheCXXABI.HasThisReturn(GD)
? argTypes.front()
: TheCXXABI.hasMostDerivedReturn(GD)
? CGM.getContext().VoidPtrTy
: Context.VoidTy;
return arrangeLLVMFunctionInfo(resultType, true,
false, argTypes, extInfo,
paramInfos, required);
}
static SmallVector<CanQualType, 16>
getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
SmallVector<CanQualType, 16> argTypes;
for (auto &arg : args)
argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
return argTypes;
}
static SmallVector<CanQualType, 16>
getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
SmallVector<CanQualType, 16> argTypes;
for (auto &arg : args)
argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
return argTypes;
}
static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
getExtParameterInfosForCall(const FunctionProtoType *proto,
unsigned prefixArgs, unsigned totalArgs) {
llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
if (proto->hasExtParameterInfos()) {
addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
}
return result;
}
const CGFunctionInfo &
CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
const CXXConstructorDecl *D,
CXXCtorType CtorKind,
unsigned ExtraPrefixArgs,
unsigned ExtraSuffixArgs,
bool PassProtoArgs) {
SmallVector<CanQualType, 16> ArgTypes;
for (const auto &Arg : args)
ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs;
CanQual<FunctionProtoType> FPT = GetFormalType(D);
RequiredArgs Required = PassProtoArgs
? RequiredArgs::forPrototypePlus(
FPT, TotalPrefixArgs + ExtraSuffixArgs)
: RequiredArgs::All;
GlobalDecl GD(D, CtorKind);
CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
? ArgTypes.front()
: TheCXXABI.hasMostDerivedReturn(GD)
? CGM.getContext().VoidPtrTy
: Context.VoidTy;
FunctionType::ExtInfo Info = FPT->getExtInfo();
llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> ParamInfos;
if (PassProtoArgs && FPT->hasExtParameterInfos()) {
addExtParameterInfosForCall(ParamInfos, FPT.getTypePtr(), TotalPrefixArgs,
ArgTypes.size());
}
return arrangeLLVMFunctionInfo(ResultType, true,
false, ArgTypes, Info,
ParamInfos, Required);
}
const CGFunctionInfo &
CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
if (MD->isInstance())
return arrangeCXXMethodDeclaration(MD);
CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
assert(isa<FunctionType>(FTy));
setCUDAKernelCallingConvention(FTy, CGM, FD);
if (CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>()) {
return arrangeLLVMFunctionInfo(
noProto->getReturnType(), false,
false, None, noProto->getExtInfo(), {},RequiredArgs::All);
}
return arrangeFreeFunctionType(FTy.castAs<FunctionProtoType>());
}
const CGFunctionInfo &
CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
}
const CGFunctionInfo &
CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
QualType receiverType) {
SmallVector<CanQualType, 16> argTys;
SmallVector<FunctionProtoType::ExtParameterInfo, 4> extParamInfos(2);
argTys.push_back(Context.getCanonicalParamType(receiverType));
argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
for (const auto *I : MD->parameters()) {
argTys.push_back(Context.getCanonicalParamType(I->getType()));
auto extParamInfo = FunctionProtoType::ExtParameterInfo().withIsNoEscape(
I->hasAttr<NoEscapeAttr>());
extParamInfos.push_back(extParamInfo);
}
FunctionType::ExtInfo einfo;
bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
if (getContext().getLangOpts().ObjCAutoRefCount &&
MD->hasAttr<NSReturnsRetainedAttr>())
einfo = einfo.withProducesResult(true);
RequiredArgs required =
(MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
return arrangeLLVMFunctionInfo(
GetReturnType(MD->getReturnType()), false,
false, argTys, einfo, extParamInfos, required);
}
const CGFunctionInfo &
CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
const CallArgList &args) {
auto argTypes = getArgTypesForCall(Context, args);
FunctionType::ExtInfo einfo;
return arrangeLLVMFunctionInfo(
GetReturnType(returnType), false,
false, argTypes, einfo, {}, RequiredArgs::All);
}
const CGFunctionInfo &
CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
if (isa<CXXConstructorDecl>(GD.getDecl()) ||
isa<CXXDestructorDecl>(GD.getDecl()))
return arrangeCXXStructorDeclaration(GD);
return arrangeFunctionDeclaration(FD);
}
const CGFunctionInfo &
CodeGenTypes::arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD) {
assert(MD->isVirtual() && "only methods have thunks");
CanQual<FunctionProtoType> FTP = GetFormalType(MD);
CanQualType ArgTys[] = {DeriveThisType(MD->getParent(), MD)};
return arrangeLLVMFunctionInfo(Context.VoidTy, false,
false, ArgTys,
FTP->getExtInfo(), {}, RequiredArgs(1));
}
const CGFunctionInfo &
CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
CXXCtorType CT) {
assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
CanQual<FunctionProtoType> FTP = GetFormalType(CD);
SmallVector<CanQualType, 2> ArgTys;
const CXXRecordDecl *RD = CD->getParent();
ArgTys.push_back(DeriveThisType(RD, CD));
if (CT == Ctor_CopyingClosure)
ArgTys.push_back(*FTP->param_type_begin());
if (RD->getNumVBases() > 0)
ArgTys.push_back(Context.IntTy);
CallingConv CC = Context.getDefaultCallingConvention(
false, true);
return arrangeLLVMFunctionInfo(Context.VoidTy, true,
false, ArgTys,
FunctionType::ExtInfo(CC), {},
RequiredArgs::All);
}
static const CGFunctionInfo &
arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
CodeGenModule &CGM,
const CallArgList &args,
const FunctionType *fnType,
unsigned numExtraRequiredArgs,
bool chainCall) {
assert(args.size() >= numExtraRequiredArgs);
llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
RequiredArgs required = RequiredArgs::All;
if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
if (proto->isVariadic())
required = RequiredArgs::forPrototypePlus(proto, numExtraRequiredArgs);
if (proto->hasExtParameterInfos())
addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
args.size());
} else if (CGM.getTargetCodeGenInfo()
.isNoProtoCallVariadic(args,
cast<FunctionNoProtoType>(fnType))) {
required = RequiredArgs(args.size());
}
SmallVector<CanQualType, 16> argTypes;
for (const auto &arg : args)
argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
false, chainCall,
argTypes, fnType->getExtInfo(), paramInfos,
required);
}
const CGFunctionInfo &
CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
const FunctionType *fnType,
bool chainCall) {
return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
chainCall ? 1 : 0, chainCall);
}
const CGFunctionInfo &
CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
const FunctionType *fnType) {
return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
false);
}
const CGFunctionInfo &
CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
const FunctionArgList ¶ms) {
auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
auto argTypes = getArgTypesForDeclaration(Context, params);
return arrangeLLVMFunctionInfo(GetReturnType(proto->getReturnType()),
false, false,
argTypes, proto->getExtInfo(), paramInfos,
RequiredArgs::forPrototypePlus(proto, 1));
}
const CGFunctionInfo &
CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
const CallArgList &args) {
SmallVector<CanQualType, 16> argTypes;
for (const auto &Arg : args)
argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
return arrangeLLVMFunctionInfo(
GetReturnType(resultType), false,
false, argTypes, FunctionType::ExtInfo(),
{}, RequiredArgs::All);
}
const CGFunctionInfo &
CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
const FunctionArgList &args) {
auto argTypes = getArgTypesForDeclaration(Context, args);
return arrangeLLVMFunctionInfo(
GetReturnType(resultType), false, false,
argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
}
const CGFunctionInfo &
CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
ArrayRef<CanQualType> argTypes) {
return arrangeLLVMFunctionInfo(
resultType, false, false,
argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
}
const CGFunctionInfo &
CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
const FunctionProtoType *proto,
RequiredArgs required,
unsigned numPrefixArgs) {
assert(numPrefixArgs + 1 <= args.size() &&
"Emitting a call with less args than the required prefix?");
auto paramInfos =
getExtParameterInfosForCall(proto, numPrefixArgs + 1, args.size());
auto argTypes = getArgTypesForCall(Context, args);
FunctionType::ExtInfo info = proto->getExtInfo();
return arrangeLLVMFunctionInfo(
GetReturnType(proto->getReturnType()), true,
false, argTypes, info, paramInfos, required);
}
const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
return arrangeLLVMFunctionInfo(
getContext().VoidTy, false, false,
None, FunctionType::ExtInfo(), {}, RequiredArgs::All);
}
const CGFunctionInfo &
CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
const CallArgList &args) {
assert(signature.arg_size() <= args.size());
if (signature.arg_size() == args.size())
return signature;
SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
auto sigParamInfos = signature.getExtParameterInfos();
if (!sigParamInfos.empty()) {
paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
paramInfos.resize(args.size());
}
auto argTypes = getArgTypesForCall(Context, args);
assert(signature.getRequiredArgs().allowsOptionalArgs());
return arrangeLLVMFunctionInfo(signature.getReturnType(),
signature.isInstanceMethod(),
signature.isChainCall(),
argTypes,
signature.getExtInfo(),
paramInfos,
signature.getRequiredArgs());
}
namespace clang {
namespace CodeGen {
void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI);
}
}
const CGFunctionInfo &
CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
bool instanceMethod,
bool chainCall,
ArrayRef<CanQualType> argTypes,
FunctionType::ExtInfo info,
ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
RequiredArgs required) {
assert(llvm::all_of(argTypes,
[](CanQualType T) { return T.isCanonicalAsParam(); }));
llvm::FoldingSetNodeID ID;
CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
required, resultType, argTypes);
void *insertPos = nullptr;
CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
if (FI)
return *FI;
unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
paramInfos, resultType, argTypes, required);
FunctionInfos.InsertNode(FI, insertPos);
bool inserted = FunctionsBeingProcessed.insert(FI).second;
(void)inserted;
assert(inserted && "Recursively being processed?");
if (CC == llvm::CallingConv::SPIR_KERNEL) {
computeSPIRKernelABIInfo(CGM, *FI);
} else if (info.getCC() == CC_Swift || info.getCC() == CC_SwiftAsync) {
swiftcall::computeABIInfo(CGM, *FI);
} else {
getABIInfo().computeInfo(*FI);
}
ABIArgInfo &retInfo = FI->getReturnInfo();
if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
for (auto &I : FI->arguments())
if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
I.info.setCoerceToType(ConvertType(I.type));
bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
assert(erased && "Not in set?");
return *FI;
}
CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
bool instanceMethod,
bool chainCall,
const FunctionType::ExtInfo &info,
ArrayRef<ExtParameterInfo> paramInfos,
CanQualType resultType,
ArrayRef<CanQualType> argTypes,
RequiredArgs required) {
assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
assert(!required.allowsOptionalArgs() ||
required.getNumRequiredArgs() <= argTypes.size());
void *buffer =
operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
argTypes.size() + 1, paramInfos.size()));
CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
FI->CallingConvention = llvmCC;
FI->EffectiveCallingConvention = llvmCC;
FI->ASTCallingConvention = info.getCC();
FI->InstanceMethod = instanceMethod;
FI->ChainCall = chainCall;
FI->CmseNSCall = info.getCmseNSCall();
FI->NoReturn = info.getNoReturn();
FI->ReturnsRetained = info.getProducesResult();
FI->NoCallerSavedRegs = info.getNoCallerSavedRegs();
FI->NoCfCheck = info.getNoCfCheck();
FI->Required = required;
FI->HasRegParm = info.getHasRegParm();
FI->RegParm = info.getRegParm();
FI->ArgStruct = nullptr;
FI->ArgStructAlign = 0;
FI->NumArgs = argTypes.size();
FI->HasExtParameterInfos = !paramInfos.empty();
FI->getArgsBuffer()[0].type = resultType;
FI->MaxVectorWidth = 0;
for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
FI->getArgsBuffer()[i + 1].type = argTypes[i];
for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
return FI;
}
namespace {
struct TypeExpansion {
enum TypeExpansionKind {
TEK_ConstantArray,
TEK_Record,
TEK_Complex,
TEK_None
};
const TypeExpansionKind Kind;
TypeExpansion(TypeExpansionKind K) : Kind(K) {}
virtual ~TypeExpansion() {}
};
struct ConstantArrayExpansion : TypeExpansion {
QualType EltTy;
uint64_t NumElts;
ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
: TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
static bool classof(const TypeExpansion *TE) {
return TE->Kind == TEK_ConstantArray;
}
};
struct RecordExpansion : TypeExpansion {
SmallVector<const CXXBaseSpecifier *, 1> Bases;
SmallVector<const FieldDecl *, 1> Fields;
RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
SmallVector<const FieldDecl *, 1> &&Fields)
: TypeExpansion(TEK_Record), Bases(std::move(Bases)),
Fields(std::move(Fields)) {}
static bool classof(const TypeExpansion *TE) {
return TE->Kind == TEK_Record;
}
};
struct ComplexExpansion : TypeExpansion {
QualType EltTy;
ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
static bool classof(const TypeExpansion *TE) {
return TE->Kind == TEK_Complex;
}
};
struct NoExpansion : TypeExpansion {
NoExpansion() : TypeExpansion(TEK_None) {}
static bool classof(const TypeExpansion *TE) {
return TE->Kind == TEK_None;
}
};
}
static std::unique_ptr<TypeExpansion>
getTypeExpansion(QualType Ty, const ASTContext &Context) {
if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
return std::make_unique<ConstantArrayExpansion>(
AT->getElementType(), AT->getSize().getZExtValue());
}
if (const RecordType *RT = Ty->getAs<RecordType>()) {
SmallVector<const CXXBaseSpecifier *, 1> Bases;
SmallVector<const FieldDecl *, 1> Fields;
const RecordDecl *RD = RT->getDecl();
assert(!RD->hasFlexibleArrayMember() &&
"Cannot expand structure with flexible array.");
if (RD->isUnion()) {
const FieldDecl *LargestFD = nullptr;
CharUnits UnionSize = CharUnits::Zero();
for (const auto *FD : RD->fields()) {
if (FD->isZeroLengthBitField(Context))
continue;
assert(!FD->isBitField() &&
"Cannot expand structure with bit-field members.");
CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
if (UnionSize < FieldSize) {
UnionSize = FieldSize;
LargestFD = FD;
}
}
if (LargestFD)
Fields.push_back(LargestFD);
} else {
if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
assert(!CXXRD->isDynamicClass() &&
"cannot expand vtable pointers in dynamic classes");
llvm::append_range(Bases, llvm::make_pointer_range(CXXRD->bases()));
}
for (const auto *FD : RD->fields()) {
if (FD->isZeroLengthBitField(Context))
continue;
assert(!FD->isBitField() &&
"Cannot expand structure with bit-field members.");
Fields.push_back(FD);
}
}
return std::make_unique<RecordExpansion>(std::move(Bases),
std::move(Fields));
}
if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
return std::make_unique<ComplexExpansion>(CT->getElementType());
}
return std::make_unique<NoExpansion>();
}
static int getExpansionSize(QualType Ty, const ASTContext &Context) {
auto Exp = getTypeExpansion(Ty, Context);
if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
}
if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
int Res = 0;
for (auto BS : RExp->Bases)
Res += getExpansionSize(BS->getType(), Context);
for (auto FD : RExp->Fields)
Res += getExpansionSize(FD->getType(), Context);
return Res;
}
if (isa<ComplexExpansion>(Exp.get()))
return 2;
assert(isa<NoExpansion>(Exp.get()));
return 1;
}
void
CodeGenTypes::getExpandedTypes(QualType Ty,
SmallVectorImpl<llvm::Type *>::iterator &TI) {
auto Exp = getTypeExpansion(Ty, Context);
if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
for (int i = 0, n = CAExp->NumElts; i < n; i++) {
getExpandedTypes(CAExp->EltTy, TI);
}
} else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
for (auto BS : RExp->Bases)
getExpandedTypes(BS->getType(), TI);
for (auto FD : RExp->Fields)
getExpandedTypes(FD->getType(), TI);
} else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
llvm::Type *EltTy = ConvertType(CExp->EltTy);
*TI++ = EltTy;
*TI++ = EltTy;
} else {
assert(isa<NoExpansion>(Exp.get()));
*TI++ = ConvertType(Ty);
}
}
static void forConstantArrayExpansion(CodeGenFunction &CGF,
ConstantArrayExpansion *CAE,
Address BaseAddr,
llvm::function_ref<void(Address)> Fn) {
CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
CharUnits EltAlign =
BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
llvm::Type *EltTy = CGF.ConvertTypeForMem(CAE->EltTy);
for (int i = 0, n = CAE->NumElts; i < n; i++) {
llvm::Value *EltAddr = CGF.Builder.CreateConstGEP2_32(
BaseAddr.getElementType(), BaseAddr.getPointer(), 0, i);
Fn(Address(EltAddr, EltTy, EltAlign));
}
}
void CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
llvm::Function::arg_iterator &AI) {
assert(LV.isSimple() &&
"Unexpected non-simple lvalue during struct expansion.");
auto Exp = getTypeExpansion(Ty, getContext());
if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
forConstantArrayExpansion(
*this, CAExp, LV.getAddress(*this), [&](Address EltAddr) {
LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
});
} else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Address This = LV.getAddress(*this);
for (const CXXBaseSpecifier *BS : RExp->Bases) {
Address Base =
GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
false, SourceLocation());
LValue SubLV = MakeAddrLValue(Base, BS->getType());
ExpandTypeFromArgs(BS->getType(), SubLV, AI);
}
for (auto FD : RExp->Fields) {
LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
ExpandTypeFromArgs(FD->getType(), SubLV, AI);
}
} else if (isa<ComplexExpansion>(Exp.get())) {
auto realValue = &*AI++;
auto imagValue = &*AI++;
EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, true);
} else {
assert(isa<NoExpansion>(Exp.get()));
llvm::Value *Arg = &*AI++;
if (LV.isBitField()) {
EmitStoreThroughLValue(RValue::get(Arg), LV);
} else {
if (Arg->getType()->isPointerTy()) {
Address Addr = LV.getAddress(*this);
Arg = Builder.CreateBitCast(Arg, Addr.getElementType());
}
EmitStoreOfScalar(Arg, LV);
}
}
}
void CodeGenFunction::ExpandTypeToArgs(
QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
auto Exp = getTypeExpansion(Ty, getContext());
if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
Address Addr = Arg.hasLValue() ? Arg.getKnownLValue().getAddress(*this)
: Arg.getKnownRValue().getAggregateAddress();
forConstantArrayExpansion(
*this, CAExp, Addr, [&](Address EltAddr) {
CallArg EltArg = CallArg(
convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation()),
CAExp->EltTy);
ExpandTypeToArgs(CAExp->EltTy, EltArg, IRFuncTy, IRCallArgs,
IRCallArgPos);
});
} else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Address This = Arg.hasLValue() ? Arg.getKnownLValue().getAddress(*this)
: Arg.getKnownRValue().getAggregateAddress();
for (const CXXBaseSpecifier *BS : RExp->Bases) {
Address Base =
GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
false, SourceLocation());
CallArg BaseArg = CallArg(RValue::getAggregate(Base), BS->getType());
ExpandTypeToArgs(BS->getType(), BaseArg, IRFuncTy, IRCallArgs,
IRCallArgPos);
}
LValue LV = MakeAddrLValue(This, Ty);
for (auto FD : RExp->Fields) {
CallArg FldArg =
CallArg(EmitRValueForField(LV, FD, SourceLocation()), FD->getType());
ExpandTypeToArgs(FD->getType(), FldArg, IRFuncTy, IRCallArgs,
IRCallArgPos);
}
} else if (isa<ComplexExpansion>(Exp.get())) {
ComplexPairTy CV = Arg.getKnownRValue().getComplexVal();
IRCallArgs[IRCallArgPos++] = CV.first;
IRCallArgs[IRCallArgPos++] = CV.second;
} else {
assert(isa<NoExpansion>(Exp.get()));
auto RV = Arg.getKnownRValue();
assert(RV.isScalar() &&
"Unexpected non-scalar rvalue during struct expansion.");
llvm::Value *V = RV.getScalarVal();
if (IRCallArgPos < IRFuncTy->getNumParams() &&
V->getType() != IRFuncTy->getParamType(IRCallArgPos))
V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
IRCallArgs[IRCallArgPos++] = V;
}
}
static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
CharUnits MinAlign,
const Twine &Name = "tmp") {
auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
return CGF.CreateTempAlloca(Ty, Align, Name + ".coerce");
}
static Address
EnterStructPointerForCoercedAccess(Address SrcPtr,
llvm::StructType *SrcSTy,
uint64_t DstSize, CodeGenFunction &CGF) {
if (SrcSTy->getNumElements() == 0) return SrcPtr;
llvm::Type *FirstElt = SrcSTy->getElementType(0);
uint64_t FirstEltSize =
CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
if (FirstEltSize < DstSize &&
FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
return SrcPtr;
SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, "coerce.dive");
llvm::Type *SrcTy = SrcPtr.getElementType();
if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
return SrcPtr;
}
static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
llvm::Type *Ty,
CodeGenFunction &CGF) {
if (Val->getType() == Ty)
return Val;
if (isa<llvm::PointerType>(Val->getType())) {
if (isa<llvm::PointerType>(Ty))
return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
}
llvm::Type *DestIntTy = Ty;
if (isa<llvm::PointerType>(DestIntTy))
DestIntTy = CGF.IntPtrTy;
if (Val->getType() != DestIntTy) {
const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
if (DL.isBigEndian()) {
uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
if (SrcSize > DstSize) {
Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
} else {
Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
}
} else {
Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
}
}
if (isa<llvm::PointerType>(Ty))
Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
return Val;
}
static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
CodeGenFunction &CGF) {
llvm::Type *SrcTy = Src.getElementType();
if (SrcTy == Ty)
return CGF.Builder.CreateLoad(Src);
llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Src = EnterStructPointerForCoercedAccess(Src, SrcSTy,
DstSize.getFixedSize(), CGF);
SrcTy = Src.getElementType();
}
llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
(isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
llvm::Value *Load = CGF.Builder.CreateLoad(Src);
return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
}
if (!SrcSize.isScalable() && !DstSize.isScalable() &&
SrcSize.getFixedSize() >= DstSize.getFixedSize()) {
Src = CGF.Builder.CreateElementBitCast(Src, Ty);
return CGF.Builder.CreateLoad(Src);
}
if (auto *ScalableDst = dyn_cast<llvm::ScalableVectorType>(Ty)) {
if (auto *FixedSrc = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
bool NeedsBitcast = false;
auto PredType =
llvm::ScalableVectorType::get(CGF.Builder.getInt1Ty(), 16);
llvm::Type *OrigType = Ty;
if (ScalableDst == PredType &&
FixedSrc->getElementType() == CGF.Builder.getInt8Ty()) {
ScalableDst = llvm::ScalableVectorType::get(CGF.Builder.getInt8Ty(), 2);
NeedsBitcast = true;
}
if (ScalableDst->getElementType() == FixedSrc->getElementType()) {
auto *Load = CGF.Builder.CreateLoad(Src);
auto *UndefVec = llvm::UndefValue::get(ScalableDst);
auto *Zero = llvm::Constant::getNullValue(CGF.CGM.Int64Ty);
llvm::Value *Result = CGF.Builder.CreateInsertVector(
ScalableDst, UndefVec, Load, Zero, "castScalableSve");
if (NeedsBitcast)
Result = CGF.Builder.CreateBitCast(Result, OrigType);
return Result;
}
}
}
Address Tmp =
CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment(), Src.getName());
CGF.Builder.CreateMemCpy(
Tmp.getPointer(), Tmp.getAlignment().getAsAlign(), Src.getPointer(),
Src.getAlignment().getAsAlign(),
llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize.getKnownMinSize()));
return CGF.Builder.CreateLoad(Tmp);
}
void CodeGenFunction::EmitAggregateStore(llvm::Value *Val, Address Dest,
bool DestIsVolatile) {
if (llvm::StructType *STy = dyn_cast<llvm::StructType>(Val->getType())) {
for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Address EltPtr = Builder.CreateStructGEP(Dest, i);
llvm::Value *Elt = Builder.CreateExtractValue(Val, i);
Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
}
} else {
Builder.CreateStore(Val, Dest, DestIsVolatile);
}
}
static void CreateCoercedStore(llvm::Value *Src,
Address Dst,
bool DstIsVolatile,
CodeGenFunction &CGF) {
llvm::Type *SrcTy = Src->getType();
llvm::Type *DstTy = Dst.getElementType();
if (SrcTy == DstTy) {
CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
return;
}
llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy,
SrcSize.getFixedSize(), CGF);
DstTy = Dst.getElementType();
}
llvm::PointerType *SrcPtrTy = llvm::dyn_cast<llvm::PointerType>(SrcTy);
llvm::PointerType *DstPtrTy = llvm::dyn_cast<llvm::PointerType>(DstTy);
if (SrcPtrTy && DstPtrTy &&
SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace()) {
Src = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy);
CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
return;
}
if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
(isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
return;
}
llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
if (isa<llvm::ScalableVectorType>(SrcTy) ||
isa<llvm::ScalableVectorType>(DstTy) ||
SrcSize.getFixedSize() <= DstSize.getFixedSize()) {
Dst = CGF.Builder.CreateElementBitCast(Dst, SrcTy);
CGF.EmitAggregateStore(Src, Dst, DstIsVolatile);
} else {
Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
CGF.Builder.CreateStore(Src, Tmp);
CGF.Builder.CreateMemCpy(
Dst.getPointer(), Dst.getAlignment().getAsAlign(), Tmp.getPointer(),
Tmp.getAlignment().getAsAlign(),
llvm::ConstantInt::get(CGF.IntPtrTy, DstSize.getFixedSize()));
}
}
static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
const ABIArgInfo &info) {
if (unsigned offset = info.getDirectOffset()) {
addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
CharUnits::fromQuantity(offset));
addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
}
return addr;
}
namespace {
class ClangToLLVMArgMapping {
static const unsigned InvalidIndex = ~0U;
unsigned InallocaArgNo;
unsigned SRetArgNo;
unsigned TotalIRArgs;
struct IRArgs {
unsigned PaddingArgIndex;
unsigned FirstArgIndex;
unsigned NumberOfArgs;
IRArgs()
: PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
NumberOfArgs(0) {}
};
SmallVector<IRArgs, 8> ArgInfo;
public:
ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
bool OnlyRequiredArgs = false)
: InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
construct(Context, FI, OnlyRequiredArgs);
}
bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
unsigned getInallocaArgNo() const {
assert(hasInallocaArg());
return InallocaArgNo;
}
bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
unsigned getSRetArgNo() const {
assert(hasSRetArg());
return SRetArgNo;
}
unsigned totalIRArgs() const { return TotalIRArgs; }
bool hasPaddingArg(unsigned ArgNo) const {
assert(ArgNo < ArgInfo.size());
return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
}
unsigned getPaddingArgNo(unsigned ArgNo) const {
assert(hasPaddingArg(ArgNo));
return ArgInfo[ArgNo].PaddingArgIndex;
}
std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
assert(ArgNo < ArgInfo.size());
return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
ArgInfo[ArgNo].NumberOfArgs);
}
private:
void construct(const ASTContext &Context, const CGFunctionInfo &FI,
bool OnlyRequiredArgs);
};
void ClangToLLVMArgMapping::construct(const ASTContext &Context,
const CGFunctionInfo &FI,
bool OnlyRequiredArgs) {
unsigned IRArgNo = 0;
bool SwapThisWithSRet = false;
const ABIArgInfo &RetAI = FI.getReturnInfo();
if (RetAI.getKind() == ABIArgInfo::Indirect) {
SwapThisWithSRet = RetAI.isSRetAfterThis();
SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
}
unsigned ArgNo = 0;
unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
++I, ++ArgNo) {
assert(I != FI.arg_end());
QualType ArgType = I->type;
const ABIArgInfo &AI = I->info;
auto &IRArgs = ArgInfo[ArgNo];
if (AI.getPaddingType())
IRArgs.PaddingArgIndex = IRArgNo++;
switch (AI.getKind()) {
case ABIArgInfo::Extend:
case ABIArgInfo::Direct: {
llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
IRArgs.NumberOfArgs = STy->getNumElements();
} else {
IRArgs.NumberOfArgs = 1;
}
break;
}
case ABIArgInfo::Indirect:
case ABIArgInfo::IndirectAliased:
IRArgs.NumberOfArgs = 1;
break;
case ABIArgInfo::Ignore:
case ABIArgInfo::InAlloca:
IRArgs.NumberOfArgs = 0;
break;
case ABIArgInfo::CoerceAndExpand:
IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
break;
case ABIArgInfo::Expand:
IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
break;
}
if (IRArgs.NumberOfArgs > 0) {
IRArgs.FirstArgIndex = IRArgNo;
IRArgNo += IRArgs.NumberOfArgs;
}
if (IRArgNo == 1 && SwapThisWithSRet)
IRArgNo++;
}
assert(ArgNo == ArgInfo.size());
if (FI.usesInAlloca())
InallocaArgNo = IRArgNo++;
TotalIRArgs = IRArgNo;
}
}
bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
const auto &RI = FI.getReturnInfo();
return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet());
}
bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
return ReturnTypeUsesSRet(FI) &&
getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
}
bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
switch (BT->getKind()) {
default:
return false;
case BuiltinType::Float:
return getTarget().useObjCFPRetForRealType(FloatModeKind::Float);
case BuiltinType::Double:
return getTarget().useObjCFPRetForRealType(FloatModeKind::Double);
case BuiltinType::LongDouble:
return getTarget().useObjCFPRetForRealType(FloatModeKind::LongDouble);
}
}
return false;
}
bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
if (BT->getKind() == BuiltinType::LongDouble)
return getTarget().useObjCFP2RetForComplexLongDouble();
}
}
return false;
}
llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
return GetFunctionType(FI);
}
llvm::FunctionType *
CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
(void)Inserted;
assert(Inserted && "Recursively being processed?");
llvm::Type *resultType = nullptr;
const ABIArgInfo &retAI = FI.getReturnInfo();
switch (retAI.getKind()) {
case ABIArgInfo::Expand:
case ABIArgInfo::IndirectAliased:
llvm_unreachable("Invalid ABI kind for return argument");
case ABIArgInfo::Extend:
case ABIArgInfo::Direct:
resultType = retAI.getCoerceToType();
break;
case ABIArgInfo::InAlloca:
if (retAI.getInAllocaSRet()) {
QualType ret = FI.getReturnType();
llvm::Type *ty = ConvertType(ret);
unsigned addressSpace = Context.getTargetAddressSpace(ret);
resultType = llvm::PointerType::get(ty, addressSpace);
} else {
resultType = llvm::Type::getVoidTy(getLLVMContext());
}
break;
case ABIArgInfo::Indirect:
case ABIArgInfo::Ignore:
resultType = llvm::Type::getVoidTy(getLLVMContext());
break;
case ABIArgInfo::CoerceAndExpand:
resultType = retAI.getUnpaddedCoerceAndExpandType();
break;
}
ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
if (IRFunctionArgs.hasSRetArg()) {
QualType Ret = FI.getReturnType();
llvm::Type *Ty = ConvertType(Ret);
unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
ArgTypes[IRFunctionArgs.getSRetArgNo()] =
llvm::PointerType::get(Ty, AddressSpace);
}
if (IRFunctionArgs.hasInallocaArg()) {
auto ArgStruct = FI.getArgStruct();
assert(ArgStruct);
ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
}
unsigned ArgNo = 0;
CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
ie = it + FI.getNumRequiredArgs();
for (; it != ie; ++it, ++ArgNo) {
const ABIArgInfo &ArgInfo = it->info;
if (IRFunctionArgs.hasPaddingArg(ArgNo))
ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
ArgInfo.getPaddingType();
unsigned FirstIRArg, NumIRArgs;
std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
switch (ArgInfo.getKind()) {
case ABIArgInfo::Ignore:
case ABIArgInfo::InAlloca:
assert(NumIRArgs == 0);
break;
case ABIArgInfo::Indirect: {
assert(NumIRArgs == 1);
llvm::Type *LTy = ConvertTypeForMem(it->type);
ArgTypes[FirstIRArg] = LTy->getPointerTo(
CGM.getDataLayout().getAllocaAddrSpace());
break;
}
case ABIArgInfo::IndirectAliased: {
assert(NumIRArgs == 1);
llvm::Type *LTy = ConvertTypeForMem(it->type);
ArgTypes[FirstIRArg] = LTy->getPointerTo(ArgInfo.getIndirectAddrSpace());
break;
}
case ABIArgInfo::Extend:
case ABIArgInfo::Direct: {
llvm::Type *argType = ArgInfo.getCoerceToType();
llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
assert(NumIRArgs == st->getNumElements());
for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
ArgTypes[FirstIRArg + i] = st->getElementType(i);
} else {
assert(NumIRArgs == 1);
ArgTypes[FirstIRArg] = argType;
}
break;
}
case ABIArgInfo::CoerceAndExpand: {
auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
*ArgTypesIter++ = EltTy;
}
assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
break;
}
case ABIArgInfo::Expand:
auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
getExpandedTypes(it->type, ArgTypesIter);
assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
break;
}
}
bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
assert(Erased && "Not in set?");
return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
}
llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
if (!isFuncTypeConvertible(FPT))
return llvm::StructType::get(getLLVMContext());
return GetFunctionType(GD);
}
static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
llvm::AttrBuilder &FuncAttrs,
const FunctionProtoType *FPT) {
if (!FPT)
return;
if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
FPT->isNothrow())
FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
}
static void AddAttributesFromAssumes(llvm::AttrBuilder &FuncAttrs,
const Decl *Callee) {
if (!Callee)
return;
SmallVector<StringRef, 4> Attrs;
for (const AssumptionAttr *AA : Callee->specific_attrs<AssumptionAttr>())
AA->getAssumption().split(Attrs, ",");
if (!Attrs.empty())
FuncAttrs.addAttribute(llvm::AssumptionAttrKey,
llvm::join(Attrs.begin(), Attrs.end(), ","));
}
bool CodeGenModule::MayDropFunctionReturn(const ASTContext &Context,
QualType ReturnType) {
if (const RecordType *RT =
ReturnType.getCanonicalType()->getAs<RecordType>()) {
if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
return ClassDecl->hasTrivialDestructor();
}
return ReturnType.isTriviallyCopyableType(Context);
}
void CodeGenModule::getDefaultFunctionAttributes(StringRef Name,
bool HasOptnone,
bool AttrOnCallSite,
llvm::AttrBuilder &FuncAttrs) {
if (!HasOptnone) {
if (CodeGenOpts.OptimizeSize)
FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
if (CodeGenOpts.OptimizeSize == 2)
FuncAttrs.addAttribute(llvm::Attribute::MinSize);
}
if (CodeGenOpts.DisableRedZone)
FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
if (CodeGenOpts.IndirectTlsSegRefs)
FuncAttrs.addAttribute("indirect-tls-seg-refs");
if (CodeGenOpts.NoImplicitFloat)
FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
if (AttrOnCallSite) {
if (!CodeGenOpts.SimplifyLibCalls || LangOpts.isNoBuiltinFunc(Name))
FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
if (!CodeGenOpts.TrapFuncName.empty())
FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
} else {
StringRef FpKind;
switch (CodeGenOpts.getFramePointer()) {
case CodeGenOptions::FramePointerKind::None:
FpKind = "none";
break;
case CodeGenOptions::FramePointerKind::NonLeaf:
FpKind = "non-leaf";
break;
case CodeGenOptions::FramePointerKind::All:
FpKind = "all";
break;
}
FuncAttrs.addAttribute("frame-pointer", FpKind);
if (CodeGenOpts.LessPreciseFPMAD)
FuncAttrs.addAttribute("less-precise-fpmad", "true");
if (CodeGenOpts.NullPointerIsValid)
FuncAttrs.addAttribute(llvm::Attribute::NullPointerIsValid);
if (CodeGenOpts.FPDenormalMode != llvm::DenormalMode::getIEEE())
FuncAttrs.addAttribute("denormal-fp-math",
CodeGenOpts.FPDenormalMode.str());
if (CodeGenOpts.FP32DenormalMode != CodeGenOpts.FPDenormalMode) {
FuncAttrs.addAttribute(
"denormal-fp-math-f32",
CodeGenOpts.FP32DenormalMode.str());
}
if (LangOpts.getDefaultExceptionMode() == LangOptions::FPE_Ignore)
FuncAttrs.addAttribute("no-trapping-math", "true");
if (LangOpts.NoHonorInfs)
FuncAttrs.addAttribute("no-infs-fp-math", "true");
if (LangOpts.NoHonorNaNs)
FuncAttrs.addAttribute("no-nans-fp-math", "true");
if (LangOpts.ApproxFunc)
FuncAttrs.addAttribute("approx-func-fp-math", "true");
if (LangOpts.UnsafeFPMath)
FuncAttrs.addAttribute("unsafe-fp-math", "true");
if (CodeGenOpts.SoftFloat)
FuncAttrs.addAttribute("use-soft-float", "true");
FuncAttrs.addAttribute("stack-protector-buffer-size",
llvm::utostr(CodeGenOpts.SSPBufferSize));
if (LangOpts.NoSignedZero)
FuncAttrs.addAttribute("no-signed-zeros-fp-math", "true");
const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals;
if (!Recips.empty())
FuncAttrs.addAttribute("reciprocal-estimates",
llvm::join(Recips, ","));
if (!CodeGenOpts.PreferVectorWidth.empty() &&
CodeGenOpts.PreferVectorWidth != "none")
FuncAttrs.addAttribute("prefer-vector-width",
CodeGenOpts.PreferVectorWidth);
if (CodeGenOpts.StackRealignment)
FuncAttrs.addAttribute("stackrealign");
if (CodeGenOpts.Backchain)
FuncAttrs.addAttribute("backchain");
if (CodeGenOpts.EnableSegmentedStacks)
FuncAttrs.addAttribute("split-stack");
if (CodeGenOpts.SpeculativeLoadHardening)
FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
switch (CodeGenOpts.getZeroCallUsedRegs()) {
case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Skip:
FuncAttrs.removeAttribute("zero-call-used-regs");
break;
case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPRArg:
FuncAttrs.addAttribute("zero-call-used-regs", "used-gpr-arg");
break;
case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPR:
FuncAttrs.addAttribute("zero-call-used-regs", "used-gpr");
break;
case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedArg:
FuncAttrs.addAttribute("zero-call-used-regs", "used-arg");
break;
case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Used:
FuncAttrs.addAttribute("zero-call-used-regs", "used");
break;
case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPRArg:
FuncAttrs.addAttribute("zero-call-used-regs", "all-gpr-arg");
break;
case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPR:
FuncAttrs.addAttribute("zero-call-used-regs", "all-gpr");
break;
case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllArg:
FuncAttrs.addAttribute("zero-call-used-regs", "all-arg");
break;
case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::All:
FuncAttrs.addAttribute("zero-call-used-regs", "all");
break;
}
}
if (getLangOpts().assumeFunctionsAreConvergent()) {
FuncAttrs.addAttribute(llvm::Attribute::Convergent);
}
if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
}
for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) {
StringRef Var, Value;
std::tie(Var, Value) = Attr.split('=');
FuncAttrs.addAttribute(Var, Value);
}
}
void CodeGenModule::addDefaultFunctionDefinitionAttributes(llvm::Function &F) {
llvm::AttrBuilder FuncAttrs(F.getContext());
getDefaultFunctionAttributes(F.getName(), F.hasOptNone(),
false, FuncAttrs);
F.addFnAttrs(FuncAttrs);
}
void CodeGenModule::addDefaultFunctionDefinitionAttributes(
llvm::AttrBuilder &attrs) {
getDefaultFunctionAttributes( "", false,
false, attrs);
GetCPUAndFeaturesAttributes(GlobalDecl(), attrs);
}
static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs,
const LangOptions &LangOpts,
const NoBuiltinAttr *NBA = nullptr) {
auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) {
SmallString<32> AttributeName;
AttributeName += "no-builtin-";
AttributeName += BuiltinName;
FuncAttrs.addAttribute(AttributeName);
};
if (LangOpts.NoBuiltin) {
FuncAttrs.addAttribute("no-builtins");
return;
}
llvm::for_each(LangOpts.NoBuiltinFuncs, AddNoBuiltinAttr);
if (!NBA)
return;
if (llvm::is_contained(NBA->builtinNames(), "*")) {
FuncAttrs.addAttribute("no-builtins");
return;
}
llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr);
}
static bool DetermineNoUndef(QualType QTy, CodeGenTypes &Types,
const llvm::DataLayout &DL, const ABIArgInfo &AI,
bool CheckCoerce = true) {
llvm::Type *Ty = Types.ConvertTypeForMem(QTy);
if (AI.getKind() == ABIArgInfo::Indirect)
return true;
if (AI.getKind() == ABIArgInfo::Extend)
return true;
if (!DL.typeSizeEqualsStoreSize(Ty))
return false;
if (CheckCoerce && AI.canHaveCoerceToType()) {
llvm::Type *CoerceTy = AI.getCoerceToType();
if (llvm::TypeSize::isKnownGT(DL.getTypeSizeInBits(CoerceTy),
DL.getTypeSizeInBits(Ty)))
return false;
}
if (QTy->isBitIntType())
return true;
if (QTy->isReferenceType())
return true;
if (QTy->isNullPtrType())
return false;
if (QTy->isMemberPointerType())
return false;
if (QTy->isScalarType()) {
if (const ComplexType *Complex = dyn_cast<ComplexType>(QTy))
return DetermineNoUndef(Complex->getElementType(), Types, DL, AI, false);
return true;
}
if (const VectorType *Vector = dyn_cast<VectorType>(QTy))
return DetermineNoUndef(Vector->getElementType(), Types, DL, AI, false);
if (const MatrixType *Matrix = dyn_cast<MatrixType>(QTy))
return DetermineNoUndef(Matrix->getElementType(), Types, DL, AI, false);
if (const ArrayType *Array = dyn_cast<ArrayType>(QTy))
return DetermineNoUndef(Array->getElementType(), Types, DL, AI, false);
return false;
}
void CodeGenModule::ConstructAttributeList(StringRef Name,
const CGFunctionInfo &FI,
CGCalleeInfo CalleeInfo,
llvm::AttributeList &AttrList,
unsigned &CallingConv,
bool AttrOnCallSite, bool IsThunk) {
llvm::AttrBuilder FuncAttrs(getLLVMContext());
llvm::AttrBuilder RetAttrs(getLLVMContext());
CallingConv = FI.getEffectiveCallingConvention();
if (FI.isNoReturn())
FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
if (FI.isCmseNSCall())
FuncAttrs.addAttribute("cmse_nonsecure_call");
AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
CalleeInfo.getCalleeFunctionProtoType());
const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl();
AddAttributesFromAssumes(FuncAttrs, TargetDecl);
bool HasOptnone = false;
const NoBuiltinAttr *NBA = nullptr;
if (TargetDecl) {
if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
if (TargetDecl->hasAttr<NoThrowAttr>())
FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
if (TargetDecl->hasAttr<NoReturnAttr>())
FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
if (TargetDecl->hasAttr<ColdAttr>())
FuncAttrs.addAttribute(llvm::Attribute::Cold);
if (TargetDecl->hasAttr<HotAttr>())
FuncAttrs.addAttribute(llvm::Attribute::Hot);
if (TargetDecl->hasAttr<NoDuplicateAttr>())
FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
if (TargetDecl->hasAttr<ConvergentAttr>())
FuncAttrs.addAttribute(llvm::Attribute::Convergent);
if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
AddAttributesFromFunctionProtoType(
getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
if (AttrOnCallSite && Fn->isReplaceableGlobalAllocationFunction()) {
auto Kind = Fn->getDeclName().getCXXOverloadedOperator();
if (getCodeGenOpts().AssumeSaneOperatorNew &&
(Kind == OO_New || Kind == OO_Array_New))
RetAttrs.addAttribute(llvm::Attribute::NoAlias);
}
const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
const bool IsVirtualCall = MD && MD->isVirtual();
if (!(AttrOnCallSite && IsVirtualCall)) {
if (Fn->isNoReturn())
FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
NBA = Fn->getAttr<NoBuiltinAttr>();
}
if (AttrOnCallSite && TargetDecl->hasAttr<NoMergeAttr>())
FuncAttrs.addAttribute(llvm::Attribute::NoMerge);
}
if (TargetDecl->hasAttr<ConstAttr>()) {
FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
} else if (TargetDecl->hasAttr<PureAttr>()) {
FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
} else if (TargetDecl->hasAttr<NoAliasAttr>()) {
FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
}
if (TargetDecl->hasAttr<RestrictAttr>())
RetAttrs.addAttribute(llvm::Attribute::NoAlias);
if (TargetDecl->hasAttr<ReturnsNonNullAttr>() &&
!CodeGenOpts.NullPointerIsValid)
RetAttrs.addAttribute(llvm::Attribute::NonNull);
if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
FuncAttrs.addAttribute("no_caller_saved_registers");
if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>())
FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck);
if (TargetDecl->hasAttr<LeafAttr>())
FuncAttrs.addAttribute(llvm::Attribute::NoCallback);
HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
Optional<unsigned> NumElemsParam;
if (AllocSize->getNumElemsParam().isValid())
NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(),
NumElemsParam);
}
if (TargetDecl->hasAttr<OpenCLKernelAttr>()) {
if (getLangOpts().OpenCLVersion <= 120) {
FuncAttrs.addAttribute("uniform-work-group-size", "true");
} else {
FuncAttrs.addAttribute("uniform-work-group-size",
llvm::toStringRef(CodeGenOpts.UniformWGSize));
}
}
}
addNoBuiltinAttributes(FuncAttrs, getLangOpts(), NBA);
getDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
if (TargetDecl) {
if (TargetDecl->hasAttr<NoSpeculativeLoadHardeningAttr>())
FuncAttrs.removeAttribute(llvm::Attribute::SpeculativeLoadHardening);
if (TargetDecl->hasAttr<SpeculativeLoadHardeningAttr>())
FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
if (TargetDecl->hasAttr<NoSplitStackAttr>())
FuncAttrs.removeAttribute("split-stack");
if (TargetDecl->hasAttr<ZeroCallUsedRegsAttr>()) {
auto Kind =
TargetDecl->getAttr<ZeroCallUsedRegsAttr>()->getZeroCallUsedRegs();
FuncAttrs.removeAttribute("zero-call-used-regs");
FuncAttrs.addAttribute(
"zero-call-used-regs",
ZeroCallUsedRegsAttr::ConvertZeroCallUsedRegsKindToStr(Kind));
}
if (CodeGenOpts.NoPLT) {
if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
if (!Fn->isDefined() && !AttrOnCallSite) {
FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind);
}
}
}
}
if (TargetDecl && CodeGenOpts.UniqueInternalLinkageNames) {
if (isa<FunctionDecl>(TargetDecl)) {
if (this->getFunctionLinkage(CalleeInfo.getCalleeDecl()) ==
llvm::GlobalValue::InternalLinkage)
FuncAttrs.addAttribute("sample-profile-suffix-elision-policy",
"selected");
}
}
if (!AttrOnCallSite) {
if (TargetDecl && TargetDecl->hasAttr<CmseNSEntryAttr>())
FuncAttrs.addAttribute("cmse_nonsecure_entry");
auto shouldDisableTailCalls = [&] {
if (CodeGenOpts.DisableTailCalls)
return true;
if (!TargetDecl)
return false;
if (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
TargetDecl->hasAttr<AnyX86InterruptAttr>())
return true;
if (CodeGenOpts.NoEscapingBlockTailCalls) {
if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl))
if (!BD->doesNotEscape())
return true;
}
return false;
};
if (shouldDisableTailCalls())
FuncAttrs.addAttribute("disable-tail-calls", "true");
GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs);
}
ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
QualType RetTy = FI.getReturnType();
const ABIArgInfo &RetAI = FI.getReturnInfo();
const llvm::DataLayout &DL = getDataLayout();
bool HasStrictReturn = getLangOpts().CPlusPlus;
if (TargetDecl && HasStrictReturn) {
if (const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(TargetDecl))
HasStrictReturn &= !FDecl->isExternC();
else if (const VarDecl *VDecl = dyn_cast<VarDecl>(TargetDecl))
HasStrictReturn &= !VDecl->isExternC();
}
HasStrictReturn &= getCodeGenOpts().StrictReturn ||
!MayDropFunctionReturn(getContext(), RetTy) ||
getLangOpts().Sanitize.has(SanitizerKind::Memory) ||
getLangOpts().Sanitize.has(SanitizerKind::Return);
if (CodeGenOpts.EnableNoundefAttrs && HasStrictReturn) {
if (!RetTy->isVoidType() && RetAI.getKind() != ABIArgInfo::Indirect &&
DetermineNoUndef(RetTy, getTypes(), DL, RetAI))
RetAttrs.addAttribute(llvm::Attribute::NoUndef);
}
switch (RetAI.getKind()) {
case ABIArgInfo::Extend:
if (RetAI.isSignExt())
RetAttrs.addAttribute(llvm::Attribute::SExt);
else
RetAttrs.addAttribute(llvm::Attribute::ZExt);
LLVM_FALLTHROUGH;
case ABIArgInfo::Direct:
if (RetAI.getInReg())
RetAttrs.addAttribute(llvm::Attribute::InReg);
break;
case ABIArgInfo::Ignore:
break;
case ABIArgInfo::InAlloca:
case ABIArgInfo::Indirect: {
FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
.removeAttribute(llvm::Attribute::ReadNone);
break;
}
case ABIArgInfo::CoerceAndExpand:
break;
case ABIArgInfo::Expand:
case ABIArgInfo::IndirectAliased:
llvm_unreachable("Invalid ABI kind for return argument");
}
if (!IsThunk) {
if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
QualType PTy = RefTy->getPointeeType();
if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
RetAttrs.addDereferenceableAttr(
getMinimumObjectSize(PTy).getQuantity());
if (getContext().getTargetAddressSpace(PTy) == 0 &&
!CodeGenOpts.NullPointerIsValid)
RetAttrs.addAttribute(llvm::Attribute::NonNull);
if (PTy->isObjectType()) {
llvm::Align Alignment =
getNaturalPointeeTypeAlignment(RetTy).getAsAlign();
RetAttrs.addAlignmentAttr(Alignment);
}
}
}
bool hasUsedSRet = false;
SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs());
if (IRFunctionArgs.hasSRetArg()) {
llvm::AttrBuilder SRETAttrs(getLLVMContext());
SRETAttrs.addStructRetAttr(getTypes().ConvertTypeForMem(RetTy));
hasUsedSRet = true;
if (RetAI.getInReg())
SRETAttrs.addAttribute(llvm::Attribute::InReg);
SRETAttrs.addAlignmentAttr(RetAI.getIndirectAlign().getQuantity());
ArgAttrs[IRFunctionArgs.getSRetArgNo()] =
llvm::AttributeSet::get(getLLVMContext(), SRETAttrs);
}
if (IRFunctionArgs.hasInallocaArg()) {
llvm::AttrBuilder Attrs(getLLVMContext());
Attrs.addInAllocaAttr(FI.getArgStruct());
ArgAttrs[IRFunctionArgs.getInallocaArgNo()] =
llvm::AttributeSet::get(getLLVMContext(), Attrs);
}
if (FI.isInstanceMethod() && !IRFunctionArgs.hasInallocaArg() &&
!FI.arg_begin()->type->isVoidPointerType() && !IsThunk) {
auto IRArgs = IRFunctionArgs.getIRArgs(0);
assert(IRArgs.second == 1 && "Expected only a single `this` pointer.");
llvm::AttrBuilder Attrs(getLLVMContext());
QualType ThisTy =
FI.arg_begin()->type.castAs<PointerType>()->getPointeeType();
if (!CodeGenOpts.NullPointerIsValid &&
getContext().getTargetAddressSpace(FI.arg_begin()->type) == 0) {
Attrs.addAttribute(llvm::Attribute::NonNull);
Attrs.addDereferenceableAttr(getMinimumObjectSize(ThisTy).getQuantity());
} else {
Attrs.addDereferenceableOrNullAttr(
getMinimumObjectSize(
FI.arg_begin()->type.castAs<PointerType>()->getPointeeType())
.getQuantity());
}
llvm::Align Alignment =
getNaturalTypeAlignment(ThisTy, nullptr,
nullptr, true)
.getAsAlign();
Attrs.addAlignmentAttr(Alignment);
ArgAttrs[IRArgs.first] = llvm::AttributeSet::get(getLLVMContext(), Attrs);
}
unsigned ArgNo = 0;
for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
E = FI.arg_end();
I != E; ++I, ++ArgNo) {
QualType ParamType = I->type;
const ABIArgInfo &AI = I->info;
llvm::AttrBuilder Attrs(getLLVMContext());
if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
if (AI.getPaddingInReg()) {
ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
llvm::AttributeSet::get(
getLLVMContext(),
llvm::AttrBuilder(getLLVMContext()).addAttribute(llvm::Attribute::InReg));
}
}
if (CodeGenOpts.EnableNoundefAttrs &&
DetermineNoUndef(ParamType, getTypes(), DL, AI)) {
Attrs.addAttribute(llvm::Attribute::NoUndef);
}
switch (AI.getKind()) {
case ABIArgInfo::Extend:
if (AI.isSignExt())
Attrs.addAttribute(llvm::Attribute::SExt);
else
Attrs.addAttribute(llvm::Attribute::ZExt);
LLVM_FALLTHROUGH;
case ABIArgInfo::Direct:
if (ArgNo == 0 && FI.isChainCall())
Attrs.addAttribute(llvm::Attribute::Nest);
else if (AI.getInReg())
Attrs.addAttribute(llvm::Attribute::InReg);
Attrs.addStackAlignmentAttr(llvm::MaybeAlign(AI.getDirectAlign()));
break;
case ABIArgInfo::Indirect: {
if (AI.getInReg())
Attrs.addAttribute(llvm::Attribute::InReg);
if (AI.getIndirectByVal())
Attrs.addByValAttr(getTypes().ConvertTypeForMem(ParamType));
auto *Decl = ParamType->getAsRecordDecl();
if (CodeGenOpts.PassByValueIsNoAlias && Decl &&
Decl->getArgPassingRestrictions() == RecordDecl::APK_CanPassInRegs)
Attrs.addAttribute(llvm::Attribute::NoAlias);
CharUnits Align = AI.getIndirectAlign();
assert(!Align.isZero());
if (AI.getIndirectByVal())
Attrs.addAlignmentAttr(Align.getQuantity());
FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
.removeAttribute(llvm::Attribute::ReadNone);
break;
}
case ABIArgInfo::IndirectAliased: {
CharUnits Align = AI.getIndirectAlign();
Attrs.addByRefAttr(getTypes().ConvertTypeForMem(ParamType));
Attrs.addAlignmentAttr(Align.getQuantity());
break;
}
case ABIArgInfo::Ignore:
case ABIArgInfo::Expand:
case ABIArgInfo::CoerceAndExpand:
break;
case ABIArgInfo::InAlloca:
FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
.removeAttribute(llvm::Attribute::ReadNone);
continue;
}
if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
QualType PTy = RefTy->getPointeeType();
if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Attrs.addDereferenceableAttr(
getMinimumObjectSize(PTy).getQuantity());
if (getContext().getTargetAddressSpace(PTy) == 0 &&
!CodeGenOpts.NullPointerIsValid)
Attrs.addAttribute(llvm::Attribute::NonNull);
if (PTy->isObjectType()) {
llvm::Align Alignment =
getNaturalPointeeTypeAlignment(ParamType).getAsAlign();
Attrs.addAlignmentAttr(Alignment);
}
}
if (TargetDecl && TargetDecl->hasAttr<OpenCLKernelAttr>() &&
ParamType->isPointerType()) {
QualType PTy = ParamType->getPointeeType();
if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
llvm::Align Alignment =
getNaturalPointeeTypeAlignment(ParamType).getAsAlign();
Attrs.addAlignmentAttr(Alignment);
}
}
switch (FI.getExtParameterInfo(ArgNo).getABI()) {
case ParameterABI::Ordinary:
break;
case ParameterABI::SwiftIndirectResult: {
if (!hasUsedSRet && RetTy->isVoidType()) {
Attrs.addStructRetAttr(getTypes().ConvertTypeForMem(ParamType));
hasUsedSRet = true;
}
Attrs.addAttribute(llvm::Attribute::NoAlias);
auto PTy = ParamType->getPointeeType();
if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
auto info = getContext().getTypeInfoInChars(PTy);
Attrs.addDereferenceableAttr(info.Width.getQuantity());
Attrs.addAlignmentAttr(info.Align.getAsAlign());
}
break;
}
case ParameterABI::SwiftErrorResult:
Attrs.addAttribute(llvm::Attribute::SwiftError);
break;
case ParameterABI::SwiftContext:
Attrs.addAttribute(llvm::Attribute::SwiftSelf);
break;
case ParameterABI::SwiftAsyncContext:
Attrs.addAttribute(llvm::Attribute::SwiftAsync);
break;
}
if (FI.getExtParameterInfo(ArgNo).isNoEscape())
Attrs.addAttribute(llvm::Attribute::NoCapture);
if (Attrs.hasAttributes()) {
unsigned FirstIRArg, NumIRArgs;
std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
for (unsigned i = 0; i < NumIRArgs; i++)
ArgAttrs[FirstIRArg + i] = ArgAttrs[FirstIRArg + i].addAttributes(
getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), Attrs));
}
}
assert(ArgNo == FI.arg_size());
AttrList = llvm::AttributeList::get(
getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs),
llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs);
}
static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
const VarDecl *var,
llvm::Value *value) {
llvm::Type *varType = CGF.ConvertType(var->getType());
if (value->getType() == varType) return value;
assert((varType->isIntegerTy() || varType->isFloatingPointTy())
&& "unexpected promotion type");
if (isa<llvm::IntegerType>(varType))
return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
}
static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
QualType ArgType, unsigned ArgNo) {
if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
return nullptr;
if (PVD) {
if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
return ParmNNAttr;
}
if (!FD)
return nullptr;
for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
if (NNAttr->isNonNull(ArgNo))
return NNAttr;
}
return nullptr;
}
namespace {
struct CopyBackSwiftError final : EHScopeStack::Cleanup {
Address Temp;
Address Arg;
CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
void Emit(CodeGenFunction &CGF, Flags flags) override {
llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
CGF.Builder.CreateStore(errorValue, Arg);
}
};
}
void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
llvm::Function *Fn,
const FunctionArgList &Args) {
if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
return;
if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
if (FD->hasImplicitReturnZero()) {
QualType RetTy = FD->getReturnType().getUnqualifiedType();
llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
Builder.CreateStore(Zero, ReturnValue);
}
}
ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
assert(Fn->arg_size() == IRFunctionArgs.totalIRArgs());
Address ArgStruct = Address::invalid();
if (IRFunctionArgs.hasInallocaArg()) {
ArgStruct = Address(Fn->getArg(IRFunctionArgs.getInallocaArgNo()),
FI.getArgStruct(), FI.getArgStructAlignment());
assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
}
if (IRFunctionArgs.hasSRetArg()) {
auto AI = Fn->getArg(IRFunctionArgs.getSRetArgNo());
AI->setName("agg.result");
AI->addAttr(llvm::Attribute::NoAlias);
}
SmallVector<ParamValue, 16> ArgVals;
ArgVals.reserve(Args.size());
assert(FI.arg_size() == Args.size() &&
"Mismatch between function signature & arguments.");
unsigned ArgNo = 0;
CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
i != e; ++i, ++info_it, ++ArgNo) {
const VarDecl *Arg = *i;
const ABIArgInfo &ArgI = info_it->info;
bool isPromoted =
isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
QualType Ty = isPromoted ? info_it->type : Arg->getType();
assert(hasScalarEvaluationKind(Ty) ==
hasScalarEvaluationKind(Arg->getType()));
unsigned FirstIRArg, NumIRArgs;
std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
switch (ArgI.getKind()) {
case ABIArgInfo::InAlloca: {
assert(NumIRArgs == 0);
auto FieldIndex = ArgI.getInAllocaFieldIndex();
Address V =
Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName());
if (ArgI.getInAllocaIndirect())
V = Address(Builder.CreateLoad(V), ConvertTypeForMem(Ty),
getContext().getTypeAlignInChars(Ty));
ArgVals.push_back(ParamValue::forIndirect(V));
break;
}
case ABIArgInfo::Indirect:
case ABIArgInfo::IndirectAliased: {
assert(NumIRArgs == 1);
Address ParamAddr = Address(Fn->getArg(FirstIRArg), ConvertTypeForMem(Ty),
ArgI.getIndirectAlign());
if (!hasScalarEvaluationKind(Ty)) {
Address V = ParamAddr;
if (ArgI.getIndirectRealign() || ArgI.isIndirectAliased()) {
Address AlignedTemp = CreateMemTemp(Ty, "coerce");
CharUnits Size = getContext().getTypeSizeInChars(Ty);
Builder.CreateMemCpy(
AlignedTemp.getPointer(), AlignedTemp.getAlignment().getAsAlign(),
ParamAddr.getPointer(), ParamAddr.getAlignment().getAsAlign(),
llvm::ConstantInt::get(IntPtrTy, Size.getQuantity()));
V = AlignedTemp;
}
ArgVals.push_back(ParamValue::forIndirect(V));
} else {
llvm::Value *V =
EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc());
if (isPromoted)
V = emitArgumentDemotion(*this, Arg, V);
ArgVals.push_back(ParamValue::forDirect(V));
}
break;
}
case ABIArgInfo::Extend:
case ABIArgInfo::Direct: {
auto AI = Fn->getArg(FirstIRArg);
llvm::Type *LTy = ConvertType(Arg->getType());
if (ArgI.getDirectOffset() == 0 && LTy->isPointerTy() &&
ArgI.getCoerceToType()->isPointerTy()) {
assert(NumIRArgs == 1);
if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
PVD->getFunctionScopeIndex()) &&
!CGM.getCodeGenOpts().NullPointerIsValid)
AI->addAttr(llvm::Attribute::NonNull);
QualType OTy = PVD->getOriginalType();
if (const auto *ArrTy =
getContext().getAsConstantArrayType(OTy)) {
if (ArrTy->getSizeModifier() == ArrayType::Static) {
QualType ETy = ArrTy->getElementType();
llvm::Align Alignment =
CGM.getNaturalTypeAlignment(ETy).getAsAlign();
AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(Alignment));
uint64_t ArrSize = ArrTy->getSize().getZExtValue();
if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
ArrSize) {
llvm::AttrBuilder Attrs(getLLVMContext());
Attrs.addDereferenceableAttr(
getContext().getTypeSizeInChars(ETy).getQuantity() *
ArrSize);
AI->addAttrs(Attrs);
} else if (getContext().getTargetInfo().getNullPointerValue(
ETy.getAddressSpace()) == 0 &&
!CGM.getCodeGenOpts().NullPointerIsValid) {
AI->addAttr(llvm::Attribute::NonNull);
}
}
} else if (const auto *ArrTy =
getContext().getAsVariableArrayType(OTy)) {
if (ArrTy->getSizeModifier() == VariableArrayType::Static) {
QualType ETy = ArrTy->getElementType();
llvm::Align Alignment =
CGM.getNaturalTypeAlignment(ETy).getAsAlign();
AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(Alignment));
if (!getContext().getTargetAddressSpace(ETy) &&
!CGM.getCodeGenOpts().NullPointerIsValid)
AI->addAttr(llvm::Attribute::NonNull);
}
}
const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
if (!AVAttr)
if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) {
llvm::ConstantInt *AlignmentCI =
cast<llvm::ConstantInt>(EmitScalarExpr(AVAttr->getAlignment()));
uint64_t AlignmentInt =
AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment);
if (AI->getParamAlign().valueOrOne() < AlignmentInt) {
AI->removeAttr(llvm::Attribute::AttrKind::Alignment);
AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(
llvm::Align(AlignmentInt)));
}
}
}
if (Arg->getType().isRestrictQualified())
AI->addAttr(llvm::Attribute::NoAlias);
}
if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
ArgI.getCoerceToType() == ConvertType(Ty) &&
ArgI.getDirectOffset() == 0) {
assert(NumIRArgs == 1);
llvm::Value *V = AI;
if (FI.getExtParameterInfo(ArgNo).getABI()
== ParameterABI::SwiftErrorResult) {
QualType pointeeTy = Ty->getPointeeType();
assert(pointeeTy->isPointerType());
Address temp =
CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
Address arg(V, ConvertTypeForMem(pointeeTy),
getContext().getTypeAlignInChars(pointeeTy));
llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
Builder.CreateStore(incomingErrorValue, temp);
V = temp.getPointer();
EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
}
if (V->getType() != ArgI.getCoerceToType())
V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
if (isPromoted)
V = emitArgumentDemotion(*this, Arg, V);
llvm::Type *LTy = ConvertType(Arg->getType());
if (V->getType() != LTy)
V = Builder.CreateBitCast(V, LTy);
ArgVals.push_back(ParamValue::forDirect(V));
break;
}
if (auto *VecTyTo = dyn_cast<llvm::FixedVectorType>(ConvertType(Ty))) {
llvm::Value *Coerced = Fn->getArg(FirstIRArg);
if (auto *VecTyFrom =
dyn_cast<llvm::ScalableVectorType>(Coerced->getType())) {
auto PredType =
llvm::ScalableVectorType::get(Builder.getInt1Ty(), 16);
if (VecTyFrom == PredType &&
VecTyTo->getElementType() == Builder.getInt8Ty()) {
VecTyFrom = llvm::ScalableVectorType::get(Builder.getInt8Ty(), 2);
Coerced = Builder.CreateBitCast(Coerced, VecTyFrom);
}
if (VecTyFrom->getElementType() == VecTyTo->getElementType()) {
llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty);
assert(NumIRArgs == 1);
Coerced->setName(Arg->getName() + ".coerce");
ArgVals.push_back(ParamValue::forDirect(Builder.CreateExtractVector(
VecTyTo, Coerced, Zero, "castFixedSve")));
break;
}
}
}
Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
Arg->getName());
Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
STy->getNumElements() > 1) {
uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
llvm::Type *DstTy = Ptr.getElementType();
uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Address AddrToStoreInto = Address::invalid();
if (SrcSize <= DstSize) {
AddrToStoreInto = Builder.CreateElementBitCast(Ptr, STy);
} else {
AddrToStoreInto =
CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
}
assert(STy->getNumElements() == NumIRArgs);
for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
auto AI = Fn->getArg(FirstIRArg + i);
AI->setName(Arg->getName() + ".coerce" + Twine(i));
Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i);
Builder.CreateStore(AI, EltPtr);
}
if (SrcSize > DstSize) {
Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
}
} else {
assert(NumIRArgs == 1);
auto AI = Fn->getArg(FirstIRArg);
AI->setName(Arg->getName() + ".coerce");
CreateCoercedStore(AI, Ptr, false, *this);
}
if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
llvm::Value *V =
EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc());
if (isPromoted)
V = emitArgumentDemotion(*this, Arg, V);
ArgVals.push_back(ParamValue::forDirect(V));
} else {
ArgVals.push_back(ParamValue::forIndirect(Alloca));
}
break;
}
case ABIArgInfo::CoerceAndExpand: {
Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
ArgVals.push_back(ParamValue::forIndirect(alloca));
auto coercionType = ArgI.getCoerceAndExpandType();
alloca = Builder.CreateElementBitCast(alloca, coercionType);
unsigned argIndex = FirstIRArg;
for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
llvm::Type *eltType = coercionType->getElementType(i);
if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
continue;
auto eltAddr = Builder.CreateStructGEP(alloca, i);
auto elt = Fn->getArg(argIndex++);
Builder.CreateStore(elt, eltAddr);
}
assert(argIndex == FirstIRArg + NumIRArgs);
break;
}
case ABIArgInfo::Expand: {
Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
LValue LV = MakeAddrLValue(Alloca, Ty);
ArgVals.push_back(ParamValue::forIndirect(Alloca));
auto FnArgIter = Fn->arg_begin() + FirstIRArg;
ExpandTypeFromArgs(Ty, LV, FnArgIter);
assert(FnArgIter == Fn->arg_begin() + FirstIRArg + NumIRArgs);
for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
auto AI = Fn->getArg(FirstIRArg + i);
AI->setName(Arg->getName() + "." + Twine(i));
}
break;
}
case ABIArgInfo::Ignore:
assert(NumIRArgs == 0);
if (!hasScalarEvaluationKind(Ty)) {
ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
} else {
llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
ArgVals.push_back(ParamValue::forDirect(U));
}
break;
}
}
if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
for (int I = Args.size() - 1; I >= 0; --I)
EmitParmDecl(*Args[I], ArgVals[I], I + 1);
} else {
for (unsigned I = 0, E = Args.size(); I != E; ++I)
EmitParmDecl(*Args[I], ArgVals[I], I + 1);
}
}
static void eraseUnusedBitCasts(llvm::Instruction *insn) {
while (insn->use_empty()) {
llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
if (!bitcast) return;
insn = cast<llvm::Instruction>(bitcast->getOperand(0));
bitcast->eraseFromParent();
}
}
static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
llvm::Value *result) {
llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
if (BB->empty()) return nullptr;
if (&BB->back() != result) return nullptr;
llvm::Type *resultType = result->getType();
llvm::Instruction *generator = cast<llvm::Instruction>(result);
SmallVector<llvm::Instruction *, 4> InstsToKill;
while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
generator = cast<llvm::Instruction>(bitcast->getOperand(0));
if (generator->getNextNode() != bitcast)
return nullptr;
InstsToKill.push_back(bitcast);
}
llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
if (!call) return nullptr;
bool doRetainAutorelease;
if (call->getCalledOperand() == CGF.CGM.getObjCEntrypoints().objc_retain) {
doRetainAutorelease = true;
} else if (call->getCalledOperand() ==
CGF.CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue) {
doRetainAutorelease = false;
if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
llvm::Instruction *prev = call->getPrevNode();
assert(prev);
if (isa<llvm::BitCastInst>(prev)) {
prev = prev->getPrevNode();
assert(prev);
}
assert(isa<llvm::CallInst>(prev));
assert(cast<llvm::CallInst>(prev)->getCalledOperand() ==
CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
InstsToKill.push_back(prev);
}
} else {
return nullptr;
}
result = call->getArgOperand(0);
InstsToKill.push_back(call);
while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
if (!bitcast->hasOneUse()) break;
InstsToKill.push_back(bitcast);
result = bitcast->getOperand(0);
}
for (auto *I : InstsToKill)
I->eraseFromParent();
if (doRetainAutorelease)
result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
return CGF.Builder.CreateBitCast(result, resultType);
}
static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
llvm::Value *result) {
const ObjCMethodDecl *method =
dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
if (!method) return nullptr;
const VarDecl *self = method->getSelfDecl();
if (!self->getType().isConstQualified()) return nullptr;
llvm::CallInst *retainCall =
dyn_cast<llvm::CallInst>(result->stripPointerCasts());
if (!retainCall || retainCall->getCalledOperand() !=
CGF.CGM.getObjCEntrypoints().objc_retain)
return nullptr;
llvm::Value *retainedValue = retainCall->getArgOperand(0);
llvm::LoadInst *load =
dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
if (!load || load->isAtomic() || load->isVolatile() ||
load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
return nullptr;
llvm::Type *resultType = result->getType();
eraseUnusedBitCasts(cast<llvm::Instruction>(result));
assert(retainCall->use_empty());
retainCall->eraseFromParent();
eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
return CGF.Builder.CreateBitCast(load, resultType);
}
static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
llvm::Value *result) {
if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
return self;
if (CGF.shouldUseFusedARCCalls())
if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
return fused;
return CGF.EmitARCAutoreleaseReturnValue(result);
}
static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
auto *SI = dyn_cast<llvm::StoreInst>(U);
if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer() ||
SI->getValueOperand()->getType() != CGF.ReturnValue.getElementType())
return nullptr;
assert(!SI->isAtomic() && !SI->isVolatile());
return SI;
};
if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
if (IP->empty()) return nullptr;
for (llvm::Instruction &I : make_range(IP->rbegin(), IP->rend())) {
if (isa<llvm::BitCastInst>(&I))
continue;
if (auto *II = dyn_cast<llvm::IntrinsicInst>(&I))
if (II->getIntrinsicID() == llvm::Intrinsic::lifetime_end)
continue;
return GetStoreIfValid(&I);
}
return nullptr;
}
llvm::StoreInst *store =
GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
if (!store) return nullptr;
llvm::BasicBlock *StoreBB = store->getParent();
llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
while (IP != StoreBB) {
if (!(IP = IP->getSinglePredecessor()))
return nullptr;
}
return store;
}
static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int BitOffset,
int BitWidth, int CharWidth) {
assert(CharWidth <= 64);
assert(static_cast<unsigned>(BitWidth) <= Bits.size() * CharWidth);
int Pos = 0;
if (BitOffset >= CharWidth) {
Pos += BitOffset / CharWidth;
BitOffset = BitOffset % CharWidth;
}
const uint64_t Used = (uint64_t(1) << CharWidth) - 1;
if (BitOffset + BitWidth >= CharWidth) {
Bits[Pos++] |= (Used << BitOffset) & Used;
BitWidth -= CharWidth - BitOffset;
BitOffset = 0;
}
while (BitWidth >= CharWidth) {
Bits[Pos++] = Used;
BitWidth -= CharWidth;
}
if (BitWidth > 0)
Bits[Pos++] |= (Used >> (CharWidth - BitWidth)) << BitOffset;
}
static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int StorageOffset,
int StorageSize, int BitOffset, int BitWidth,
int CharWidth, bool BigEndian) {
SmallVector<uint64_t, 8> TmpBits(StorageSize);
setBitRange(TmpBits, BitOffset, BitWidth, CharWidth);
if (BigEndian)
std::reverse(TmpBits.begin(), TmpBits.end());
for (uint64_t V : TmpBits)
Bits[StorageOffset++] |= V;
}
static void setUsedBits(CodeGenModule &, QualType, int,
SmallVectorImpl<uint64_t> &);
static void setUsedBits(CodeGenModule &CGM, const RecordType *RTy, int Offset,
SmallVectorImpl<uint64_t> &Bits) {
ASTContext &Context = CGM.getContext();
int CharWidth = Context.getCharWidth();
const RecordDecl *RD = RTy->getDecl()->getDefinition();
const ASTRecordLayout &ASTLayout = Context.getASTRecordLayout(RD);
const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(RD);
int Idx = 0;
for (auto I = RD->field_begin(), E = RD->field_end(); I != E; ++I, ++Idx) {
const FieldDecl *F = *I;
if (F->isUnnamedBitfield() || F->isZeroLengthBitField(Context) ||
F->getType()->isIncompleteArrayType())
continue;
if (F->isBitField()) {
const CGBitFieldInfo &BFI = Layout.getBitFieldInfo(F);
setBitRange(Bits, Offset + BFI.StorageOffset.getQuantity(),
BFI.StorageSize / CharWidth, BFI.Offset,
BFI.Size, CharWidth,
CGM.getDataLayout().isBigEndian());
continue;
}
setUsedBits(CGM, F->getType(),
Offset + ASTLayout.getFieldOffset(Idx) / CharWidth, Bits);
}
}
static void setUsedBits(CodeGenModule &CGM, const ConstantArrayType *ATy,
int Offset, SmallVectorImpl<uint64_t> &Bits) {
const ASTContext &Context = CGM.getContext();
QualType ETy = Context.getBaseElementType(ATy);
int Size = Context.getTypeSizeInChars(ETy).getQuantity();
SmallVector<uint64_t, 4> TmpBits(Size);
setUsedBits(CGM, ETy, 0, TmpBits);
for (int I = 0, N = Context.getConstantArrayElementCount(ATy); I < N; ++I) {
auto Src = TmpBits.begin();
auto Dst = Bits.begin() + Offset + I * Size;
for (int J = 0; J < Size; ++J)
*Dst++ |= *Src++;
}
}
static void setUsedBits(CodeGenModule &CGM, QualType QTy, int Offset,
SmallVectorImpl<uint64_t> &Bits) {
if (const auto *RTy = QTy->getAs<RecordType>())
return setUsedBits(CGM, RTy, Offset, Bits);
ASTContext &Context = CGM.getContext();
if (const auto *ATy = Context.getAsConstantArrayType(QTy))
return setUsedBits(CGM, ATy, Offset, Bits);
int Size = Context.getTypeSizeInChars(QTy).getQuantity();
if (Size <= 0)
return;
std::fill_n(Bits.begin() + Offset, Size,
(uint64_t(1) << Context.getCharWidth()) - 1);
}
static uint64_t buildMultiCharMask(const SmallVectorImpl<uint64_t> &Bits,
int Pos, int Size, int CharWidth,
bool BigEndian) {
assert(Size > 0);
uint64_t Mask = 0;
if (BigEndian) {
for (auto P = Bits.begin() + Pos, E = Bits.begin() + Pos + Size; P != E;
++P)
Mask = (Mask << CharWidth) | *P;
} else {
auto P = Bits.begin() + Pos + Size, End = Bits.begin() + Pos;
do
Mask = (Mask << CharWidth) | *--P;
while (P != End);
}
return Mask;
}
llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
llvm::IntegerType *ITy,
QualType QTy) {
assert(Src->getType() == ITy);
assert(ITy->getScalarSizeInBits() <= 64);
const llvm::DataLayout &DataLayout = CGM.getDataLayout();
int Size = DataLayout.getTypeStoreSize(ITy);
SmallVector<uint64_t, 4> Bits(Size);
setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
int CharWidth = CGM.getContext().getCharWidth();
uint64_t Mask =
buildMultiCharMask(Bits, 0, Size, CharWidth, DataLayout.isBigEndian());
return Builder.CreateAnd(Src, Mask, "cmse.clear");
}
llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
llvm::ArrayType *ATy,
QualType QTy) {
const llvm::DataLayout &DataLayout = CGM.getDataLayout();
int Size = DataLayout.getTypeStoreSize(ATy);
SmallVector<uint64_t, 16> Bits(Size);
setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
int CharWidth = CGM.getContext().getCharWidth();
int CharsPerElt =
ATy->getArrayElementType()->getScalarSizeInBits() / CharWidth;
int MaskIndex = 0;
llvm::Value *R = llvm::PoisonValue::get(ATy);
for (int I = 0, N = ATy->getArrayNumElements(); I != N; ++I) {
uint64_t Mask = buildMultiCharMask(Bits, MaskIndex, CharsPerElt, CharWidth,
DataLayout.isBigEndian());
MaskIndex += CharsPerElt;
llvm::Value *T0 = Builder.CreateExtractValue(Src, I);
llvm::Value *T1 = Builder.CreateAnd(T0, Mask, "cmse.clear");
R = Builder.CreateInsertValue(R, T1, I);
}
return R;
}
void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
bool EmitRetDbgLoc,
SourceLocation EndLoc) {
if (FI.isNoReturn()) {
EmitUnreachable(EndLoc);
return;
}
if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
Builder.CreateUnreachable();
return;
}
if (!ReturnValue.isValid()) {
Builder.CreateRetVoid();
return;
}
llvm::DebugLoc RetDbgLoc;
llvm::Value *RV = nullptr;
QualType RetTy = FI.getReturnType();
const ABIArgInfo &RetAI = FI.getReturnInfo();
switch (RetAI.getKind()) {
case ABIArgInfo::InAlloca:
assert(hasAggregateEvaluationKind(RetTy));
if (RetAI.getInAllocaSRet()) {
llvm::Function::arg_iterator EI = CurFn->arg_end();
--EI;
llvm::Value *ArgStruct = &*EI;
llvm::Value *SRet = Builder.CreateStructGEP(
FI.getArgStruct(), ArgStruct, RetAI.getInAllocaFieldIndex());
llvm::Type *Ty =
cast<llvm::GetElementPtrInst>(SRet)->getResultElementType();
RV = Builder.CreateAlignedLoad(Ty, SRet, getPointerAlign(), "sret");
}
break;
case ABIArgInfo::Indirect: {
auto AI = CurFn->arg_begin();
if (RetAI.isSRetAfterThis())
++AI;
switch (getEvaluationKind(RetTy)) {
case TEK_Complex: {
ComplexPairTy RT =
EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
true);
break;
}
case TEK_Aggregate:
break;
case TEK_Scalar: {
LValueBaseInfo BaseInfo;
TBAAAccessInfo TBAAInfo;
CharUnits Alignment =
CGM.getNaturalTypeAlignment(RetTy, &BaseInfo, &TBAAInfo);
Address ArgAddr(&*AI, ConvertType(RetTy), Alignment);
LValue ArgVal =
LValue::MakeAddr(ArgAddr, RetTy, getContext(), BaseInfo, TBAAInfo);
EmitStoreOfScalar(
Builder.CreateLoad(ReturnValue), ArgVal, true);
break;
}
}
break;
}
case ABIArgInfo::Extend:
case ABIArgInfo::Direct:
if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
RetAI.getDirectOffset() == 0) {
if (llvm::StoreInst *SI =
findDominatingStoreToReturnValue(*this)) {
if (EmitRetDbgLoc && !AutoreleaseResult)
RetDbgLoc = SI->getDebugLoc();
RV = SI->getValueOperand();
SI->eraseFromParent();
} else {
RV = Builder.CreateLoad(ReturnValue);
}
} else {
Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
}
if (AutoreleaseResult) {
#ifndef NDEBUG
QualType RT;
if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
RT = FD->getReturnType();
else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
RT = MD->getReturnType();
else if (isa<BlockDecl>(CurCodeDecl))
RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
else
llvm_unreachable("Unexpected function/method type");
assert(getLangOpts().ObjCAutoRefCount &&
!FI.isReturnsRetained() &&
RT->isObjCRetainableType());
#endif
RV = emitAutoreleaseOfResult(*this, RV);
}
break;
case ABIArgInfo::Ignore:
break;
case ABIArgInfo::CoerceAndExpand: {
auto coercionType = RetAI.getCoerceAndExpandType();
llvm::SmallVector<llvm::Value*, 4> results;
Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
auto coercedEltType = coercionType->getElementType(i);
if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
continue;
auto eltAddr = Builder.CreateStructGEP(addr, i);
auto elt = Builder.CreateLoad(eltAddr);
results.push_back(elt);
}
if (results.size() == 1) {
RV = results[0];
} else {
llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
RV = llvm::PoisonValue::get(returnType);
for (unsigned i = 0, e = results.size(); i != e; ++i) {
RV = Builder.CreateInsertValue(RV, results[i], i);
}
}
break;
}
case ABIArgInfo::Expand:
case ABIArgInfo::IndirectAliased:
llvm_unreachable("Invalid ABI kind for return argument");
}
llvm::Instruction *Ret;
if (RV) {
if (CurFuncDecl && CurFuncDecl->hasAttr<CmseNSEntryAttr>()) {
auto *ITy = dyn_cast<llvm::IntegerType>(RV->getType());
if (ITy != nullptr && isa<RecordType>(RetTy.getCanonicalType()))
RV = EmitCMSEClearRecord(RV, ITy, RetTy);
}
EmitReturnValueCheck(RV);
Ret = Builder.CreateRet(RV);
} else {
Ret = Builder.CreateRetVoid();
}
if (RetDbgLoc)
Ret->setDebugLoc(std::move(RetDbgLoc));
}
void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) {
if (!CurCodeDecl)
return;
if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty())
return;
ReturnsNonNullAttr *RetNNAttr = nullptr;
if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
return;
SourceLocation AttrLoc;
SanitizerMask CheckKind;
SanitizerHandler Handler;
if (RetNNAttr) {
assert(!requiresReturnValueNullabilityCheck() &&
"Cannot check nullability and the nonnull attribute");
AttrLoc = RetNNAttr->getLocation();
CheckKind = SanitizerKind::ReturnsNonnullAttribute;
Handler = SanitizerHandler::NonnullReturn;
} else {
if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl))
if (auto *TSI = DD->getTypeSourceInfo())
if (auto FTL = TSI->getTypeLoc().getAsAdjusted<FunctionTypeLoc>())
AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
CheckKind = SanitizerKind::NullabilityReturn;
Handler = SanitizerHandler::NullabilityReturn;
}
SanitizerScope SanScope(this);
llvm::BasicBlock *Check = createBasicBlock("nullcheck");
llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck");
llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load");
llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr);
if (requiresReturnValueNullabilityCheck())
CanNullCheck =
Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition);
Builder.CreateCondBr(CanNullCheck, Check, NoCheck);
EmitBlock(Check);
llvm::Value *Cond = Builder.CreateIsNotNull(RV);
llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)};
llvm::Value *DynamicData[] = {SLocPtr};
EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData);
EmitBlock(NoCheck);
#ifndef NDEBUG
ReturnLocation = Address::invalid();
#endif
}
static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
}
static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
QualType Ty) {
llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
llvm::Type *IRPtrTy = IRTy->getPointerTo();
llvm::Value *Placeholder = llvm::PoisonValue::get(IRPtrTy->getPointerTo());
CharUnits Align = CharUnits::fromQuantity(4);
Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
return AggValueSlot::forAddr(Address(Placeholder, IRTy, Align),
Ty.getQualifiers(),
AggValueSlot::IsNotDestructed,
AggValueSlot::DoesNotNeedGCBarriers,
AggValueSlot::IsNotAliased,
AggValueSlot::DoesNotOverlap);
}
void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
const VarDecl *param,
SourceLocation loc) {
Address local = GetAddrOfLocalVar(param);
QualType type = param->getType();
if (isInAllocaArgument(CGM.getCXXABI(), type)) {
CGM.ErrorUnsupported(param, "forwarded non-trivially copyable parameter");
}
if (type->isReferenceType()) {
args.add(RValue::get(Builder.CreateLoad(local)), type);
} else if (getLangOpts().ObjCAutoRefCount &&
param->hasAttr<NSConsumedAttr>() &&
type->isObjCRetainableType()) {
llvm::Value *ptr = Builder.CreateLoad(local);
auto null =
llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
Builder.CreateStore(null, local);
args.add(RValue::get(ptr), type);
} else {
args.add(convertTempToRValue(local, type, loc), type);
}
if (type->isRecordType() && !CurFuncIsThunk &&
type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee() &&
param->needsDestruction(getContext())) {
EHScopeStack::stable_iterator cleanup =
CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param));
assert(cleanup.isValid() &&
"cleanup for callee-destructed param not recorded");
llvm::Instruction *isActive = Builder.CreateUnreachable();
args.addArgCleanupDeactivation(cleanup, isActive);
}
}
static bool isProvablyNull(llvm::Value *addr) {
return isa<llvm::ConstantPointerNull>(addr);
}
static void emitWriteback(CodeGenFunction &CGF,
const CallArgList::Writeback &writeback) {
const LValue &srcLV = writeback.Source;
Address srcAddr = srcLV.getAddress(CGF);
assert(!isProvablyNull(srcAddr.getPointer()) &&
"shouldn't have writeback for provably null argument");
llvm::BasicBlock *contBB = nullptr;
bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
CGF.CGM.getDataLayout());
if (!provablyNonNull) {
llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
contBB = CGF.createBasicBlock("icr.done");
llvm::Value *isNull =
CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
CGF.EmitBlock(writebackBB);
}
llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
"icr.writeback-cast");
if (writeback.ToUse) {
assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
value = CGF.EmitARCRetainNonBlock(value);
CGF.EmitARCIntrinsicUse(writeback.ToUse);
llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
CGF.EmitStoreOfScalar(value, srcLV, false);
CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
} else {
CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
}
if (!provablyNonNull)
CGF.EmitBlock(contBB);
}
static void emitWritebacks(CodeGenFunction &CGF,
const CallArgList &args) {
for (const auto &I : args.writebacks())
emitWriteback(CGF, I);
}
static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
const CallArgList &CallArgs) {
ArrayRef<CallArgList::CallArgCleanup> Cleanups =
CallArgs.getCleanupsToDeactivate();
for (const auto &I : llvm::reverse(Cleanups)) {
CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
I.IsActiveIP->eraseFromParent();
}
}
static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
if (uop->getOpcode() == UO_AddrOf)
return uop->getSubExpr();
return nullptr;
}
static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
const ObjCIndirectCopyRestoreExpr *CRE) {
LValue srcLV;
if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
srcLV = CGF.EmitLValue(lvExpr);
} else {
Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
QualType srcAddrType =
CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
}
Address srcAddr = srcLV.getAddress(CGF);
llvm::PointerType *destType =
cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
llvm::Type *destElemType =
CGF.ConvertTypeForMem(CRE->getType()->getPointeeType());
if (isProvablyNull(srcAddr.getPointer())) {
args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
CRE->getType());
return;
}
Address temp =
CGF.CreateTempAlloca(destElemType, CGF.getPointerAlign(), "icr.temp");
CodeGenFunction::ConditionalEvaluation condEval(CGF);
bool shouldCopy = CRE->shouldCopy();
if (!shouldCopy) {
llvm::Value *null =
llvm::ConstantPointerNull::get(cast<llvm::PointerType>(destElemType));
CGF.Builder.CreateStore(null, temp);
}
llvm::BasicBlock *contBB = nullptr;
llvm::BasicBlock *originBB = nullptr;
llvm::Value *finalArgument;
bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
CGF.CGM.getDataLayout());
if (provablyNonNull) {
finalArgument = temp.getPointer();
} else {
llvm::Value *isNull =
CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
finalArgument = CGF.Builder.CreateSelect(isNull,
llvm::ConstantPointerNull::get(destType),
temp.getPointer(), "icr.argument");
if (shouldCopy) {
originBB = CGF.Builder.GetInsertBlock();
contBB = CGF.createBasicBlock("icr.cont");
llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
CGF.EmitBlock(copyBB);
condEval.begin(CGF);
}
}
llvm::Value *valueToUse = nullptr;
if (shouldCopy) {
RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
assert(srcRV.isScalar());
llvm::Value *src = srcRV.getScalarVal();
src = CGF.Builder.CreateBitCast(src, destElemType, "icr.cast");
CGF.Builder.CreateStore(src, temp);
if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
valueToUse = src;
}
}
if (shouldCopy && !provablyNonNull) {
llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
CGF.EmitBlock(contBB);
if (valueToUse) {
llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
"icr.to-use");
phiToUse->addIncoming(valueToUse, copyBB);
phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
originBB);
valueToUse = phiToUse;
}
condEval.end(CGF);
}
args.addWriteback(srcLV, temp, valueToUse);
args.add(RValue::get(finalArgument), CRE->getType());
}
void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
assert(!StackBase);
llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
}
void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
if (StackBase) {
llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
CGF.Builder.CreateCall(F, StackBase);
}
}
void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
SourceLocation ArgLoc,
AbstractCallee AC,
unsigned ParmNum) {
if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
SanOpts.has(SanitizerKind::NullabilityArg)))
return;
auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr;
unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
const NonNullAttr *NNAttr = nullptr;
if (SanOpts.has(SanitizerKind::NonnullAttribute))
NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
bool CanCheckNullability = false;
if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD) {
auto Nullability = PVD->getType()->getNullability(getContext());
CanCheckNullability = Nullability &&
*Nullability == NullabilityKind::NonNull &&
PVD->getTypeSourceInfo();
}
if (!NNAttr && !CanCheckNullability)
return;
SourceLocation AttrLoc;
SanitizerMask CheckKind;
SanitizerHandler Handler;
if (NNAttr) {
AttrLoc = NNAttr->getLocation();
CheckKind = SanitizerKind::NonnullAttribute;
Handler = SanitizerHandler::NonnullArg;
} else {
AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
CheckKind = SanitizerKind::NullabilityArg;
Handler = SanitizerHandler::NullabilityArg;
}
SanitizerScope SanScope(this);
llvm::Value *Cond = EmitNonNullRValueCheck(RV, ArgType);
llvm::Constant *StaticData[] = {
EmitCheckSourceLocation(ArgLoc), EmitCheckSourceLocation(AttrLoc),
llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
};
EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, None);
}
static bool hasInAllocaArgs(CodeGenModule &CGM, CallingConv ExplicitCC,
ArrayRef<QualType> ArgTypes) {
if (ExplicitCC == CC_Swift || ExplicitCC == CC_SwiftAsync)
return false;
if (!CGM.getTarget().getCXXABI().isMicrosoft())
return false;
return llvm::any_of(ArgTypes, [&](QualType Ty) {
return isInAllocaArgument(CGM.getCXXABI(), Ty);
});
}
#ifndef NDEBUG
static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
const DeclContext *dc = method->getDeclContext();
if (const ObjCInterfaceDecl *classDecl = dyn_cast<ObjCInterfaceDecl>(dc)) {
return classDecl->getTypeParamListAsWritten();
}
if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
return catDecl->getTypeParamList();
}
return false;
}
#endif
void CodeGenFunction::EmitCallArgs(
CallArgList &Args, PrototypeWrapper Prototype,
llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
SmallVector<QualType, 16> ArgTypes;
assert((ParamsToSkip == 0 || Prototype.P) &&
"Can't skip parameters if type info is not provided");
CallingConv ExplicitCC = CC_C;
bool IsVariadic = false;
if (Prototype.P) {
const auto *MD = Prototype.P.dyn_cast<const ObjCMethodDecl *>();
if (MD) {
IsVariadic = MD->isVariadic();
ExplicitCC = getCallingConventionForDecl(
MD, CGM.getTarget().getTriple().isOSWindows());
ArgTypes.assign(MD->param_type_begin() + ParamsToSkip,
MD->param_type_end());
} else {
const auto *FPT = Prototype.P.get<const FunctionProtoType *>();
IsVariadic = FPT->isVariadic();
ExplicitCC = FPT->getExtInfo().getCC();
ArgTypes.assign(FPT->param_type_begin() + ParamsToSkip,
FPT->param_type_end());
}
#ifndef NDEBUG
bool isGenericMethod = MD && isObjCMethodWithTypeParams(MD);
CallExpr::const_arg_iterator Arg = ArgRange.begin();
for (QualType Ty : ArgTypes) {
assert(Arg != ArgRange.end() && "Running over edge of argument list!");
assert(
(isGenericMethod || Ty->isVariablyModifiedType() ||
Ty.getNonReferenceType()->isObjCRetainableType() ||
getContext()
.getCanonicalType(Ty.getNonReferenceType())
.getTypePtr() ==
getContext().getCanonicalType((*Arg)->getType()).getTypePtr()) &&
"type mismatch in call argument!");
++Arg;
}
assert((Arg == ArgRange.end() || IsVariadic) &&
"Extra arguments in non-variadic function!");
#endif
}
for (auto *A : llvm::drop_begin(ArgRange, ArgTypes.size()))
ArgTypes.push_back(IsVariadic ? getVarArgType(A) : A->getType());
assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
bool LeftToRight =
CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
? Order == EvaluationOrder::ForceLeftToRight
: Order != EvaluationOrder::ForceRightToLeft;
auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
RValue EmittedArg) {
if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
return;
auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
if (PS == nullptr)
return;
const auto &Context = getContext();
auto SizeTy = Context.getSizeType();
auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?");
llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
EmittedArg.getScalarVal(),
PS->isDynamic());
Args.add(RValue::get(V), SizeTy);
if (!LeftToRight)
std::swap(Args.back(), *(&Args.back() - 1));
};
if (hasInAllocaArgs(CGM, ExplicitCC, ArgTypes)) {
assert(getTarget().getTriple().getArch() == llvm::Triple::x86 &&
"inalloca only supported on x86");
Args.allocateArgumentMemory(*this);
}
size_t CallArgsStart = Args.size();
for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
unsigned Idx = LeftToRight ? I : E - I - 1;
CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
unsigned InitialArgSize = Args.size();
assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) ||
getContext().hasSameUnqualifiedType((*Arg)->getType(),
ArgTypes[Idx]) ||
(isa<ObjCMethodDecl>(AC.getDecl()) &&
isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) &&
"Argument and parameter types don't match");
EmitCallArg(Args, *Arg, ArgTypes[Idx]);
assert(InitialArgSize + 1 == Args.size() &&
"The code below depends on only adding one arg per EmitCallArg");
(void)InitialArgSize;
if (!Args.back().hasLValue()) {
RValue RVArg = Args.back().getKnownRValue();
EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
ParamsToSkip + Idx);
MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
}
}
if (!LeftToRight) {
std::reverse(Args.begin() + CallArgsStart, Args.end());
}
}
namespace {
struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
DestroyUnpassedArg(Address Addr, QualType Ty)
: Addr(Addr), Ty(Ty) {}
Address Addr;
QualType Ty;
void Emit(CodeGenFunction &CGF, Flags flags) override {
QualType::DestructionKind DtorKind = Ty.isDestructedType();
if (DtorKind == QualType::DK_cxx_destructor) {
const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
assert(!Dtor->isTrivial());
CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, false,
false, Addr, Ty);
} else {
CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty));
}
}
};
struct DisableDebugLocationUpdates {
CodeGenFunction &CGF;
bool disabledDebugInfo;
DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
CGF.disableDebugInfo();
}
~DisableDebugLocationUpdates() {
if (disabledDebugInfo)
CGF.enableDebugInfo();
}
};
}
RValue CallArg::getRValue(CodeGenFunction &CGF) const {
if (!HasLV)
return RV;
LValue Copy = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty), Ty);
CGF.EmitAggregateCopy(Copy, LV, Ty, AggValueSlot::DoesNotOverlap,
LV.isVolatile());
IsUsed = true;
return RValue::getAggregate(Copy.getAddress(CGF));
}
void CallArg::copyInto(CodeGenFunction &CGF, Address Addr) const {
LValue Dst = CGF.MakeAddrLValue(Addr, Ty);
if (!HasLV && RV.isScalar())
CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, true);
else if (!HasLV && RV.isComplex())
CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, true);
else {
auto Addr = HasLV ? LV.getAddress(CGF) : RV.getAggregateAddress();
LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty);
CGF.EmitAggregateCopy(Dst, SrcLV, Ty, AggValueSlot::DoesNotOverlap,
HasLV ? LV.isVolatileQualified()
: RV.isVolatileQualified());
}
IsUsed = true;
}
void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
QualType type) {
DisableDebugLocationUpdates Dis(*this, E);
if (const ObjCIndirectCopyRestoreExpr *CRE
= dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
assert(getLangOpts().ObjCAutoRefCount);
return emitWritebackArg(*this, args, CRE);
}
assert(type->isReferenceType() == E->isGLValue() &&
"reference binding to unmaterialized r-value!");
if (E->isGLValue()) {
assert(E->getObjectKind() == OK_Ordinary);
return args.add(EmitReferenceBindingToExpr(E), type);
}
bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
if (type->isRecordType() &&
type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
AggValueSlot Slot = args.isUsingInAlloca()
? createPlaceholderSlot(*this, type) : CreateAggTemp(type, "agg.tmp");
bool DestroyedInCallee = true, NeedsEHCleanup = true;
if (const auto *RD = type->getAsCXXRecordDecl())
DestroyedInCallee = RD->hasNonTrivialDestructor();
else
NeedsEHCleanup = needsEHCleanup(type.isDestructedType());
if (DestroyedInCallee)
Slot.setExternallyDestructed();
EmitAggExpr(E, Slot);
RValue RV = Slot.asRValue();
args.add(RV, type);
if (DestroyedInCallee && NeedsEHCleanup) {
pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
type);
llvm::Instruction *IsActive = Builder.CreateUnreachable();
args.addArgCleanupDeactivation(EHStack.stable_begin(), IsActive);
}
return;
}
if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
assert(L.isSimple());
args.addUncopiedAggregate(L, type);
return;
}
args.add(EmitAnyExprToTemp(E), type);
}
QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
if (!getTarget().getTriple().isOSWindows())
return Arg->getType();
if (Arg->getType()->isIntegerType() &&
getContext().getTypeSize(Arg->getType()) <
getContext().getTargetInfo().getPointerWidth(0) &&
Arg->isNullPointerConstant(getContext(),
Expr::NPC_ValueDependentIsNotNull)) {
return getContext().getIntPtrType();
}
return Arg->getType();
}
void
CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
!CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
CGM.getNoObjCARCExceptionsMetadata());
}
llvm::CallInst *
CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
const llvm::Twine &name) {
return EmitNounwindRuntimeCall(callee, None, name);
}
llvm::CallInst *
CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
ArrayRef<llvm::Value *> args,
const llvm::Twine &name) {
llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
call->setDoesNotThrow();
return call;
}
llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
const llvm::Twine &name) {
return EmitRuntimeCall(callee, None, name);
}
SmallVector<llvm::OperandBundleDef, 1>
CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) {
if (!CurrentFuncletPad)
return (SmallVector<llvm::OperandBundleDef, 1>());
if (auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts())) {
if (CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow()) {
auto IID = CalleeFn->getIntrinsicID();
if (!llvm::IntrinsicInst::mayLowerToFunctionCall(IID))
return (SmallVector<llvm::OperandBundleDef, 1>());
}
}
SmallVector<llvm::OperandBundleDef, 1> BundleList;
BundleList.emplace_back("funclet", CurrentFuncletPad);
return BundleList;
}
llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
ArrayRef<llvm::Value *> args,
const llvm::Twine &name) {
llvm::CallInst *call = Builder.CreateCall(
callee, args, getBundlesForFunclet(callee.getCallee()), name);
call->setCallingConv(getRuntimeCC());
return call;
}
void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(
llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) {
SmallVector<llvm::OperandBundleDef, 1> BundleList =
getBundlesForFunclet(callee.getCallee());
if (getInvokeDest()) {
llvm::InvokeInst *invoke =
Builder.CreateInvoke(callee,
getUnreachableBlock(),
getInvokeDest(),
args,
BundleList);
invoke->setDoesNotReturn();
invoke->setCallingConv(getRuntimeCC());
} else {
llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
call->setDoesNotReturn();
call->setCallingConv(getRuntimeCC());
Builder.CreateUnreachable();
}
}
llvm::CallBase *
CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
const Twine &name) {
return EmitRuntimeCallOrInvoke(callee, None, name);
}
llvm::CallBase *
CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
ArrayRef<llvm::Value *> args,
const Twine &name) {
llvm::CallBase *call = EmitCallOrInvoke(callee, args, name);
call->setCallingConv(getRuntimeCC());
return call;
}
llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee,
ArrayRef<llvm::Value *> Args,
const Twine &Name) {
llvm::BasicBlock *InvokeDest = getInvokeDest();
SmallVector<llvm::OperandBundleDef, 1> BundleList =
getBundlesForFunclet(Callee.getCallee());
llvm::CallBase *Inst;
if (!InvokeDest)
Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
else {
llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
Name);
EmitBlock(ContBB);
}
if (CGM.getLangOpts().ObjCAutoRefCount)
AddObjCARCExceptionMetadata(Inst);
return Inst;
}
void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
llvm::Value *New) {
DeferredReplacements.push_back(
std::make_pair(llvm::WeakTrackingVH(Old), New));
}
namespace {
LLVM_NODISCARD llvm::AttributeList
maybeRaiseRetAlignmentAttribute(llvm::LLVMContext &Ctx,
const llvm::AttributeList &Attrs,
llvm::Align NewAlign) {
llvm::Align CurAlign = Attrs.getRetAlignment().valueOrOne();
if (CurAlign >= NewAlign)
return Attrs;
llvm::Attribute AlignAttr = llvm::Attribute::getWithAlignment(Ctx, NewAlign);
return Attrs.removeRetAttribute(Ctx, llvm::Attribute::AttrKind::Alignment)
.addRetAttribute(Ctx, AlignAttr);
}
template <typename AlignedAttrTy> class AbstractAssumeAlignedAttrEmitter {
protected:
CodeGenFunction &CGF;
const AlignedAttrTy *AA = nullptr;
llvm::Value *Alignment = nullptr; llvm::ConstantInt *OffsetCI = nullptr;
AbstractAssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
: CGF(CGF_) {
if (!FuncDecl)
return;
AA = FuncDecl->getAttr<AlignedAttrTy>();
}
public:
LLVM_NODISCARD llvm::AttributeList
TryEmitAsCallSiteAttribute(const llvm::AttributeList &Attrs) {
if (!AA || OffsetCI || CGF.SanOpts.has(SanitizerKind::Alignment))
return Attrs;
const auto *AlignmentCI = dyn_cast<llvm::ConstantInt>(Alignment);
if (!AlignmentCI)
return Attrs;
if (!AlignmentCI->getValue().isPowerOf2())
return Attrs;
llvm::AttributeList NewAttrs = maybeRaiseRetAlignmentAttribute(
CGF.getLLVMContext(), Attrs,
llvm::Align(
AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment)));
AA = nullptr; return NewAttrs;
}
void EmitAsAnAssumption(SourceLocation Loc, QualType RetTy, RValue &Ret) {
if (!AA)
return;
CGF.emitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc,
AA->getLocation(), Alignment, OffsetCI);
AA = nullptr; }
};
class AssumeAlignedAttrEmitter final
: public AbstractAssumeAlignedAttrEmitter<AssumeAlignedAttr> {
public:
AssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
: AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
if (!AA)
return;
Alignment = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AA->getAlignment()));
if (Expr *Offset = AA->getOffset()) {
OffsetCI = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(Offset));
if (OffsetCI->isNullValue()) OffsetCI = nullptr;
}
}
};
class AllocAlignAttrEmitter final
: public AbstractAssumeAlignedAttrEmitter<AllocAlignAttr> {
public:
AllocAlignAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl,
const CallArgList &CallArgs)
: AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
if (!AA)
return;
Alignment = CallArgs[AA->getParamIndex().getLLVMIndex()]
.getRValue(CGF)
.getScalarVal();
}
};
}
static unsigned getMaxVectorWidth(const llvm::Type *Ty) {
if (auto *VT = dyn_cast<llvm::VectorType>(Ty))
return VT->getPrimitiveSizeInBits().getKnownMinSize();
if (auto *AT = dyn_cast<llvm::ArrayType>(Ty))
return getMaxVectorWidth(AT->getElementType());
unsigned MaxVectorWidth = 0;
if (auto *ST = dyn_cast<llvm::StructType>(Ty))
for (auto *I : ST->elements())
MaxVectorWidth = std::max(MaxVectorWidth, getMaxVectorWidth(I));
return MaxVectorWidth;
}
RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
const CGCallee &Callee,
ReturnValueSlot ReturnValue,
const CallArgList &CallArgs,
llvm::CallBase **callOrInvoke, bool IsMustTail,
SourceLocation Loc) {
assert(Callee.isOrdinary() || Callee.isVirtual());
QualType RetTy = CallInfo.getReturnType();
const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
TargetDecl->hasAttr<TargetAttr>())
checkTargetFeatures(Loc, FD);
CGM.getTargetCodeGenInfo().checkFunctionCallABI(
CGM, Loc, dyn_cast_or_null<FunctionDecl>(CurCodeDecl), FD, CallArgs);
}
#ifndef NDEBUG
if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) {
if (Callee.isVirtual())
assert(IRFuncTy == Callee.getVirtualFunctionType());
else {
llvm::PointerType *PtrTy =
llvm::cast<llvm::PointerType>(Callee.getFunctionPointer()->getType());
assert(PtrTy->isOpaqueOrPointeeTypeMatches(IRFuncTy));
}
}
#endif
Address ArgMemory = Address::invalid();
if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
const llvm::DataLayout &DL = CGM.getDataLayout();
llvm::Instruction *IP = CallArgs.getStackBase();
llvm::AllocaInst *AI;
if (IP) {
IP = IP->getNextNode();
AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(),
"argmem", IP);
} else {
AI = CreateTempAlloca(ArgStruct, "argmem");
}
auto Align = CallInfo.getArgStructAlignment();
AI->setAlignment(Align.getAsAlign());
AI->setUsedWithInAlloca(true);
assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
ArgMemory = Address(AI, ArgStruct, Align);
}
ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
Address SRetPtr = Address::invalid();
Address SRetAlloca = Address::invalid();
llvm::Value *UnusedReturnSizePtr = nullptr;
if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
if (!ReturnValue.isNull()) {
SRetPtr = ReturnValue.getValue();
} else {
SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca);
if (HaveInsertPoint() && ReturnValue.isUnused()) {
llvm::TypeSize size =
CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer());
}
}
if (IRFunctionArgs.hasSRetArg()) {
IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
} else if (RetAI.isInAlloca()) {
Address Addr =
Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
Builder.CreateStore(SRetPtr.getPointer(), Addr);
}
}
Address swiftErrorTemp = Address::invalid();
Address swiftErrorArg = Address::invalid();
SmallVector<CallLifetimeEnd, 2> CallLifetimeEndAfterCall;
assert(CallInfo.arg_size() == CallArgs.size() &&
"Mismatch between function signature & arguments.");
unsigned ArgNo = 0;
CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
I != E; ++I, ++info_it, ++ArgNo) {
const ABIArgInfo &ArgInfo = info_it->info;
if (IRFunctionArgs.hasPaddingArg(ArgNo))
IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
llvm::UndefValue::get(ArgInfo.getPaddingType());
unsigned FirstIRArg, NumIRArgs;
std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
switch (ArgInfo.getKind()) {
case ABIArgInfo::InAlloca: {
assert(NumIRArgs == 0);
assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
if (I->isAggregate()) {
Address Addr = I->hasLValue()
? I->getKnownLValue().getAddress(*this)
: I->getKnownRValue().getAggregateAddress();
llvm::Instruction *Placeholder =
cast<llvm::Instruction>(Addr.getPointer());
if (!ArgInfo.getInAllocaIndirect()) {
CGBuilderTy::InsertPoint IP = Builder.saveIP();
Builder.SetInsertPoint(Placeholder);
Addr = Builder.CreateStructGEP(ArgMemory,
ArgInfo.getInAllocaFieldIndex());
Builder.restoreIP(IP);
} else {
Addr = CreateMemTemp(info_it->type, "inalloca.indirect.tmp");
Address ArgSlot = Builder.CreateStructGEP(
ArgMemory, ArgInfo.getInAllocaFieldIndex());
Builder.CreateStore(Addr.getPointer(), ArgSlot);
}
deferPlaceholderReplacement(Placeholder, Addr.getPointer());
} else if (ArgInfo.getInAllocaIndirect()) {
Address Addr = CreateMemTempWithoutCast(
I->Ty, getContext().getTypeAlignInChars(I->Ty),
"indirect-arg-temp");
I->copyInto(*this, Addr);
Address ArgSlot =
Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
Builder.CreateStore(Addr.getPointer(), ArgSlot);
} else {
Address Addr =
Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
Addr = Builder.CreateElementBitCast(Addr, ConvertTypeForMem(I->Ty));
I->copyInto(*this, Addr);
}
break;
}
case ABIArgInfo::Indirect:
case ABIArgInfo::IndirectAliased: {
assert(NumIRArgs == 1);
if (!I->isAggregate()) {
Address Addr = CreateMemTempWithoutCast(
I->Ty, ArgInfo.getIndirectAlign(), "indirect-arg-temp");
IRCallArgs[FirstIRArg] = Addr.getPointer();
I->copyInto(*this, Addr);
} else {
Address Addr = I->hasLValue()
? I->getKnownLValue().getAddress(*this)
: I->getKnownRValue().getAggregateAddress();
llvm::Value *V = Addr.getPointer();
CharUnits Align = ArgInfo.getIndirectAlign();
const llvm::DataLayout *TD = &CGM.getDataLayout();
assert((FirstIRArg >= IRFuncTy->getNumParams() ||
IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() ==
TD->getAllocaAddrSpace()) &&
"indirect argument must be in alloca address space");
bool NeedCopy = false;
if (Addr.getAlignment() < Align &&
llvm::getOrEnforceKnownAlignment(V, Align.getAsAlign(), *TD) <
Align.getAsAlign()) {
NeedCopy = true;
} else if (I->hasLValue()) {
auto LV = I->getKnownLValue();
auto AS = LV.getAddressSpace();
if (!ArgInfo.getIndirectByVal() ||
(LV.getAlignment() < getContext().getTypeAlignInChars(I->Ty))) {
NeedCopy = true;
}
if (!getLangOpts().OpenCL) {
if ((ArgInfo.getIndirectByVal() &&
(AS != LangAS::Default &&
AS != CGM.getASTAllocaAddressSpace()))) {
NeedCopy = true;
}
}
else if ((ArgInfo.getIndirectByVal() &&
Addr.getType()->getAddressSpace() != IRFuncTy->
getParamType(FirstIRArg)->getPointerAddressSpace())) {
NeedCopy = true;
}
}
if (NeedCopy) {
Address AI = CreateMemTempWithoutCast(
I->Ty, ArgInfo.getIndirectAlign(), "byval-temp");
IRCallArgs[FirstIRArg] = AI.getPointer();
llvm::TypeSize ByvalTempElementSize =
CGM.getDataLayout().getTypeAllocSize(AI.getElementType());
llvm::Value *LifetimeSize =
EmitLifetimeStart(ByvalTempElementSize, AI.getPointer());
if (LifetimeSize) CallLifetimeEndAfterCall.emplace_back(AI, LifetimeSize);
I->copyInto(*this, AI);
} else {
auto *T = llvm::PointerType::getWithSamePointeeType(
cast<llvm::PointerType>(V->getType()),
CGM.getDataLayout().getAllocaAddrSpace());
IRCallArgs[FirstIRArg] = getTargetHooks().performAddrSpaceCast(
*this, V, LangAS::Default, CGM.getASTAllocaAddressSpace(), T,
true);
}
}
break;
}
case ABIArgInfo::Ignore:
assert(NumIRArgs == 0);
break;
case ABIArgInfo::Extend:
case ABIArgInfo::Direct: {
if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
ArgInfo.getDirectOffset() == 0) {
assert(NumIRArgs == 1);
llvm::Value *V;
if (!I->isAggregate())
V = I->getKnownRValue().getScalarVal();
else
V = Builder.CreateLoad(
I->hasLValue() ? I->getKnownLValue().getAddress(*this)
: I->getKnownRValue().getAggregateAddress());
if (CallInfo.getExtParameterInfo(ArgNo).getABI()
== ParameterABI::SwiftErrorResult) {
assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
QualType pointeeTy = I->Ty->getPointeeType();
swiftErrorArg = Address(V, ConvertTypeForMem(pointeeTy),
getContext().getTypeAlignInChars(pointeeTy));
swiftErrorTemp =
CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
V = swiftErrorTemp.getPointer();
cast<llvm::AllocaInst>(V)->setSwiftError(true);
llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
Builder.CreateStore(errorValue, swiftErrorTemp);
}
if (ArgInfo.getCoerceToType() != V->getType() &&
V->getType()->isIntegerTy())
V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
if (FirstIRArg < IRFuncTy->getNumParams() &&
V->getType() != IRFuncTy->getParamType(FirstIRArg))
V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
IRCallArgs[FirstIRArg] = V;
break;
}
Address Src = Address::invalid();
if (!I->isAggregate()) {
Src = CreateMemTemp(I->Ty, "coerce");
I->copyInto(*this, Src);
} else {
Src = I->hasLValue() ? I->getKnownLValue().getAddress(*this)
: I->getKnownRValue().getAggregateAddress();
}
Src = emitAddressAtOffset(*this, Src, ArgInfo);
llvm::StructType *STy =
dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
llvm::Type *SrcTy = Src.getElementType();
uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
if (SrcSize < DstSize) {
Address TempAlloca
= CreateTempAlloca(STy, Src.getAlignment(),
Src.getName() + ".coerce");
Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
Src = TempAlloca;
} else {
Src = Builder.CreateElementBitCast(Src, STy);
}
assert(NumIRArgs == STy->getNumElements());
for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Address EltPtr = Builder.CreateStructGEP(Src, i);
llvm::Value *LI = Builder.CreateLoad(EltPtr);
IRCallArgs[FirstIRArg + i] = LI;
}
} else {
assert(NumIRArgs == 1);
llvm::Value *Load =
CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
if (CallInfo.isCmseNSCall()) {
auto *ATy = dyn_cast<llvm::ArrayType>(Load->getType());
if (ATy != nullptr && isa<RecordType>(I->Ty.getCanonicalType()))
Load = EmitCMSEClearRecord(Load, ATy, I->Ty);
}
IRCallArgs[FirstIRArg] = Load;
}
break;
}
case ABIArgInfo::CoerceAndExpand: {
auto coercionType = ArgInfo.getCoerceAndExpandType();
auto layout = CGM.getDataLayout().getStructLayout(coercionType);
llvm::Value *tempSize = nullptr;
Address addr = Address::invalid();
Address AllocaAddr = Address::invalid();
if (I->isAggregate()) {
addr = I->hasLValue() ? I->getKnownLValue().getAddress(*this)
: I->getKnownRValue().getAggregateAddress();
} else {
RValue RV = I->getKnownRValue();
assert(RV.isScalar());
llvm::Type *scalarType = RV.getScalarVal()->getType();
auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType);
addr =
CreateTempAlloca(RV.getScalarVal()->getType(),
CharUnits::fromQuantity(std::max(
layout->getAlignment().value(), scalarAlign)),
"tmp",
nullptr, &AllocaAddr);
tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer());
Builder.CreateStore(RV.getScalarVal(), addr);
}
addr = Builder.CreateElementBitCast(addr, coercionType);
unsigned IRArgPos = FirstIRArg;
for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
llvm::Type *eltType = coercionType->getElementType(i);
if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
Address eltAddr = Builder.CreateStructGEP(addr, i);
llvm::Value *elt = Builder.CreateLoad(eltAddr);
IRCallArgs[IRArgPos++] = elt;
}
assert(IRArgPos == FirstIRArg + NumIRArgs);
if (tempSize) {
EmitLifetimeEnd(tempSize, AllocaAddr.getPointer());
}
break;
}
case ABIArgInfo::Expand: {
unsigned IRArgPos = FirstIRArg;
ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos);
assert(IRArgPos == FirstIRArg + NumIRArgs);
break;
}
}
}
const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this);
llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer();
if (ArgMemory.isValid()) {
llvm::Value *Arg = ArgMemory.getPointer();
if (CallInfo.isVariadic()) {
unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace();
CalleePtr =
Builder.CreateBitCast(CalleePtr, IRFuncTy->getPointerTo(CalleeAS));
} else {
llvm::Type *LastParamTy =
IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
if (Arg->getType() != LastParamTy) {
#ifndef NDEBUG
llvm::StructType *FullTy = CallInfo.getArgStruct();
if (!LastParamTy->isOpaquePointerTy()) {
llvm::StructType *DeclaredTy = cast<llvm::StructType>(
LastParamTy->getNonOpaquePointerElementType());
assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
for (auto DI = DeclaredTy->element_begin(),
DE = DeclaredTy->element_end(),
FI = FullTy->element_begin();
DI != DE; ++DI, ++FI)
assert(*DI == *FI);
}
#endif
Arg = Builder.CreateBitCast(Arg, LastParamTy);
}
}
assert(IRFunctionArgs.hasInallocaArg());
IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
}
auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT,
llvm::Value *Ptr) -> llvm::Function * {
if (!CalleeFT->isVarArg())
return nullptr;
if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) {
if (CE->getOpcode() == llvm::Instruction::BitCast)
Ptr = CE->getOperand(0);
}
llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr);
if (!OrigFn)
return nullptr;
llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
if (OrigFT->isVarArg() ||
OrigFT->getNumParams() != CalleeFT->getNumParams() ||
OrigFT->getReturnType() != CalleeFT->getReturnType())
return nullptr;
for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
return nullptr;
return OrigFn;
};
if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) {
CalleePtr = OrigFn;
IRFuncTy = OrigFn->getFunctionType();
}
if (!CallArgs.getCleanupsToDeactivate().empty())
deactivateArgCleanupsBeforeCall(*this, CallArgs);
#ifndef NDEBUG
assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
if (IRFunctionArgs.hasInallocaArg() &&
i == IRFunctionArgs.getInallocaArgNo())
continue;
if (i < IRFuncTy->getNumParams())
assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
}
#endif
for (unsigned i = 0; i < IRCallArgs.size(); ++i)
LargestVectorWidth = std::max(LargestVectorWidth,
getMaxVectorWidth(IRCallArgs[i]->getType()));
unsigned CallingConv;
llvm::AttributeList Attrs;
CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
Callee.getAbstractInfo(), Attrs, CallingConv,
true,
false);
if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
if (FD->hasAttr<StrictFPAttr>())
Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::StrictFP);
if (InNoMergeAttributedStmt)
Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoMerge);
if (InNoInlineAttributedStmt)
Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoInline);
if (InAlwaysInlineAttributedStmt)
Attrs =
Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::AlwaysInline);
if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
!InNoInlineAttributedStmt &&
!(TargetDecl && TargetDecl->hasAttr<NoInlineAttr>())) {
Attrs =
Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::AlwaysInline);
}
if (isSEHTryScope()) {
Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoInline);
}
bool CannotThrow;
if (currentFunctionUsesSEHTry()) {
CannotThrow = false;
} else if (isCleanupPadScope() &&
EHPersonality::get(*this).isMSVCXXPersonality()) {
CannotThrow = true;
} else {
CannotThrow = Attrs.hasFnAttr(llvm::Attribute::NoUnwind);
if (auto *FPtr = dyn_cast<llvm::Function>(CalleePtr))
if (FPtr->hasFnAttribute(llvm::Attribute::NoUnwind))
CannotThrow = true;
}
if (UnusedReturnSizePtr)
pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca,
UnusedReturnSizePtr);
llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
SmallVector<llvm::OperandBundleDef, 1> BundleList =
getBundlesForFunclet(CalleePtr);
if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
if (FD->hasAttr<StrictFPAttr>())
Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::StrictFP);
AssumeAlignedAttrEmitter AssumeAlignedAttrEmitter(*this, TargetDecl);
Attrs = AssumeAlignedAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
AllocAlignAttrEmitter AllocAlignAttrEmitter(*this, TargetDecl, CallArgs);
Attrs = AllocAlignAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
llvm::CallBase *CI;
if (!InvokeDest) {
CI = Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList);
} else {
llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
CI = Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs,
BundleList);
EmitBlock(Cont);
}
if (callOrInvoke)
*callOrInvoke = CI;
if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
if (const auto *A = FD->getAttr<CFGuardAttr>()) {
if (A->getGuard() == CFGuardAttr::GuardArg::nocf && !CI->getCalledFunction())
Attrs = Attrs.addFnAttribute(getLLVMContext(), "guard_nocf");
}
}
CI->setAttributes(Attrs);
CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
if (!CI->getType()->isVoidTy())
CI->setName("call");
LargestVectorWidth =
std::max(LargestVectorWidth, getMaxVectorWidth(CI->getType()));
if (!CI->getCalledFunction())
PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
CI, CalleePtr);
if (CGM.getLangOpts().ObjCAutoRefCount)
AddObjCARCExceptionMetadata(CI);
if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
else if (IsMustTail)
Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
}
if (getDebugInfo() && TargetDecl &&
TargetDecl->hasAttr<MSAllocatorAttr>())
getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy->getPointeeType(), Loc);
if (TargetDecl && TargetDecl->hasAttr<ErrorAttr>()) {
llvm::ConstantInt *Line =
llvm::ConstantInt::get(Int32Ty, Loc.getRawEncoding());
llvm::ConstantAsMetadata *MD = llvm::ConstantAsMetadata::get(Line);
llvm::MDTuple *MDT = llvm::MDNode::get(getLLVMContext(), {MD});
CI->setMetadata("srcloc", MDT);
}
if (CI->doesNotReturn()) {
if (UnusedReturnSizePtr)
PopCleanupBlock();
if (SanOpts.has(SanitizerKind::Unreachable)) {
if (auto *F = CI->getCalledFunction())
F->removeFnAttr(llvm::Attribute::NoReturn);
CI->removeFnAttr(llvm::Attribute::NoReturn);
if (SanOpts.hasOneOf(SanitizerKind::Address |
SanitizerKind::KernelAddress)) {
SanitizerScope SanScope(this);
llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder);
Builder.SetInsertPoint(CI);
auto *FnType = llvm::FunctionType::get(CGM.VoidTy, false);
llvm::FunctionCallee Fn =
CGM.CreateRuntimeFunction(FnType, "__asan_handle_no_return");
EmitNounwindRuntimeCall(Fn);
}
}
EmitUnreachable(Loc);
Builder.ClearInsertionPoint();
EnsureInsertPoint();
return GetUndefRValue(RetTy);
}
if (IsMustTail) {
for (auto it = EHStack.find(CurrentCleanupScopeDepth); it != EHStack.end();
++it) {
EHCleanupScope *Cleanup = dyn_cast<EHCleanupScope>(&*it);
if (!(Cleanup && Cleanup->getCleanup()->isRedundantBeforeReturn()))
CGM.ErrorUnsupported(MustTailCall, "tail call skipping over cleanups");
}
if (CI->getType()->isVoidTy())
Builder.CreateRetVoid();
else
Builder.CreateRet(CI);
Builder.ClearInsertionPoint();
EnsureInsertPoint();
return GetUndefRValue(RetTy);
}
if (swiftErrorTemp.isValid()) {
llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
Builder.CreateStore(errorResult, swiftErrorArg);
}
if (CallArgs.hasWritebacks())
emitWritebacks(*this, CallArgs);
CallArgs.freeArgumentMemory(*this);
RValue Ret = [&] {
switch (RetAI.getKind()) {
case ABIArgInfo::CoerceAndExpand: {
auto coercionType = RetAI.getCoerceAndExpandType();
Address addr = SRetPtr;
addr = Builder.CreateElementBitCast(addr, coercionType);
assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
bool requiresExtract = isa<llvm::StructType>(CI->getType());
unsigned unpaddedIndex = 0;
for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
llvm::Type *eltType = coercionType->getElementType(i);
if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
Address eltAddr = Builder.CreateStructGEP(addr, i);
llvm::Value *elt = CI;
if (requiresExtract)
elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
else
assert(unpaddedIndex == 0);
Builder.CreateStore(elt, eltAddr);
}
LLVM_FALLTHROUGH;
}
case ABIArgInfo::InAlloca:
case ABIArgInfo::Indirect: {
RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
if (UnusedReturnSizePtr)
PopCleanupBlock();
return ret;
}
case ABIArgInfo::Ignore:
return GetUndefRValue(RetTy);
case ABIArgInfo::Extend:
case ABIArgInfo::Direct: {
llvm::Type *RetIRTy = ConvertType(RetTy);
if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
switch (getEvaluationKind(RetTy)) {
case TEK_Complex: {
llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
return RValue::getComplex(std::make_pair(Real, Imag));
}
case TEK_Aggregate: {
Address DestPtr = ReturnValue.getValue();
bool DestIsVolatile = ReturnValue.isVolatile();
if (!DestPtr.isValid()) {
DestPtr = CreateMemTemp(RetTy, "agg.tmp");
DestIsVolatile = false;
}
EmitAggregateStore(CI, DestPtr, DestIsVolatile);
return RValue::getAggregate(DestPtr);
}
case TEK_Scalar: {
llvm::Value *V = CI;
if (V->getType() != RetIRTy)
V = Builder.CreateBitCast(V, RetIRTy);
return RValue::get(V);
}
}
llvm_unreachable("bad evaluation kind");
}
Address DestPtr = ReturnValue.getValue();
bool DestIsVolatile = ReturnValue.isVolatile();
if (!DestPtr.isValid()) {
DestPtr = CreateMemTemp(RetTy, "coerce");
DestIsVolatile = false;
}
Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
return convertTempToRValue(DestPtr, RetTy, SourceLocation());
}
case ABIArgInfo::Expand:
case ABIArgInfo::IndirectAliased:
llvm_unreachable("Invalid ABI kind for return argument");
}
llvm_unreachable("Unhandled ABIArgInfo::Kind");
} ();
if (Ret.isScalar() && TargetDecl) {
AssumeAlignedAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
AllocAlignAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
}
for (CallLifetimeEnd &LifetimeEnd : CallLifetimeEndAfterCall)
LifetimeEnd.Emit(*this, {});
if (!ReturnValue.isExternallyDestructed() &&
RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct)
pushDestroy(QualType::DK_nontrivial_c_struct, Ret.getAggregateAddress(),
RetTy);
return Ret;
}
CGCallee CGCallee::prepareConcreteCallee(CodeGenFunction &CGF) const {
if (isVirtual()) {
const CallExpr *CE = getVirtualCallExpr();
return CGF.CGM.getCXXABI().getVirtualFunctionPointer(
CGF, getVirtualMethodDecl(), getThisAddress(), getVirtualFunctionType(),
CE ? CE->getBeginLoc() : SourceLocation());
}
return *this;
}
Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
VAListAddr = VE->isMicrosoftABI()
? EmitMSVAListRef(VE->getSubExpr())
: EmitVAListRef(VE->getSubExpr());
QualType Ty = VE->getType();
if (VE->isMicrosoftABI())
return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
}