blob: cf6aec0ff24351ca80dd6768fa9ee8e36226f398 [file] [log] [blame]
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001//===--- CGCall.cpp - Encapsulate calling convention details --------------===//
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGCall.h"
Chris Lattnere70a0072010-06-29 16:40:28 +000016#include "ABIInfo.h"
Akira Hatanaka9d8ac612016-02-17 21:09:50 +000017#include "CGBlocks.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CGCXXABI.h"
David Majnemer4e52d6f2015-12-12 05:39:21 +000019#include "CGCleanup.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000020#include "CodeGenFunction.h"
Daniel Dunbarc68897d2008-09-10 00:41:16 +000021#include "CodeGenModule.h"
John McCalla729c622012-02-17 03:33:10 +000022#include "TargetInfo.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000023#include "clang/AST/Decl.h"
Anders Carlssonb15b55c2009-04-03 22:48:58 +000024#include "clang/AST/DeclCXX.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000025#include "clang/AST/DeclObjC.h"
Eric Christopher15709992015-10-15 23:47:11 +000026#include "clang/Basic/TargetBuiltins.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000028#include "clang/CodeGen/CGFunctionInfo.h"
John McCall12f23522016-04-04 18:33:08 +000029#include "clang/CodeGen/SwiftCallingConv.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000030#include "clang/Frontend/CodeGenOptions.h"
Bill Wendling706469b2013-02-28 22:49:57 +000031#include "llvm/ADT/StringExtras.h"
David Blaikie181a6132018-06-04 21:23:29 +000032#include "llvm/Transforms/Utils/Local.h"
Nick Lewyckyd9bce502016-09-20 15:49:58 +000033#include "llvm/Analysis/ValueTracking.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000034#include "llvm/IR/Attributes.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000035#include "llvm/IR/CallSite.h"
David Blaikief47ca252018-03-21 22:34:27 +000036#include "llvm/IR/CallingConv.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000037#include "llvm/IR/DataLayout.h"
38#include "llvm/IR/InlineAsm.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000039#include "llvm/IR/IntrinsicInst.h"
David Blaikief47ca252018-03-21 22:34:27 +000040#include "llvm/IR/Intrinsics.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000041using namespace clang;
42using namespace CodeGen;
43
44/***/
45
Nikolay Haustov8c6538b2016-06-30 09:06:33 +000046unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC) {
John McCallab26cfa2010-02-05 21:31:56 +000047 switch (CC) {
48 default: return llvm::CallingConv::C;
49 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
50 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Erich Keane757d3172016-11-02 18:29:35 +000051 case CC_X86RegCall: return llvm::CallingConv::X86_RegCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000052 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Martin Storsjo022e7822017-07-17 20:49:45 +000053 case CC_Win64: return llvm::CallingConv::Win64;
Charles Davisb5a214e2013-08-30 04:39:01 +000054 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000055 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
56 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000057 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Reid Klecknerd7857f02014-10-24 17:42:17 +000058 // TODO: Add support for __pascal to LLVM.
59 case CC_X86Pascal: return llvm::CallingConv::C;
60 // TODO: Add support for __vectorcall to LLVM.
Reid Kleckner80944df2014-10-31 22:00:51 +000061 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
Alexander Kornienko21de0ae2015-01-20 11:20:41 +000062 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +000063 case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv();
Roman Levenstein35aa5ce2016-03-16 18:00:46 +000064 case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
65 case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
John McCall12f23522016-04-04 18:33:08 +000066 case CC_Swift: return llvm::CallingConv::Swift;
John McCallab26cfa2010-02-05 21:31:56 +000067 }
68}
69
John McCall8ee376f2010-02-24 07:14:12 +000070/// Derives the 'this' type for codegen purposes, i.e. ignoring method
71/// qualification.
72/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000073static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
74 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
75 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000076}
77
John McCall8ee376f2010-02-24 07:14:12 +000078/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000079static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
80 return MD->getType()->getCanonicalTypeUnqualified()
81 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000082}
83
84/// Returns the "extra-canonicalized" return type, which discards
85/// qualifiers on the return type. Codegen doesn't care about them,
86/// and it makes ABI code a little easier to be able to assume that
87/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000088static CanQualType GetReturnType(QualType RetTy) {
89 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000090}
91
John McCall8dda7b22012-07-07 06:41:13 +000092/// Arrange the argument and result information for a value of the given
93/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000094const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000095CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000096 // When translating an unprototyped function type, always use a
97 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000098 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Peter Collingbournef7706832014-12-12 23:41:25 +000099 /*instanceMethod=*/false,
100 /*chainCall=*/false, None,
John McCallc56a8b32016-03-11 04:30:31 +0000101 FTNP->getExtInfo(), {}, RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +0000102}
103
George Burgess IVb7760212017-02-24 02:49:47 +0000104static void addExtParameterInfosForCall(
105 llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
106 const FunctionProtoType *proto,
107 unsigned prefixArgs,
108 unsigned totalArgs) {
109 assert(proto->hasExtParameterInfos());
110 assert(paramInfos.size() <= prefixArgs);
111 assert(proto->getNumParams() + prefixArgs <= totalArgs);
112
113 paramInfos.reserve(totalArgs);
114
115 // Add default infos for any prefix args that don't already have infos.
116 paramInfos.resize(prefixArgs);
117
118 // Add infos for the prototype.
119 for (const auto &ParamInfo : proto->getExtParameterInfos()) {
120 paramInfos.push_back(ParamInfo);
121 // pass_object_size params have no parameter info.
122 if (ParamInfo.hasPassObjectSize())
123 paramInfos.emplace_back();
124 }
125
126 assert(paramInfos.size() <= totalArgs &&
127 "Did we forget to insert pass_object_size args?");
128 // Add default infos for the variadic and/or suffix arguments.
129 paramInfos.resize(totalArgs);
130}
131
Hiroshi Inouec5e54dd2017-07-03 08:49:44 +0000132/// Adds the formal parameters in FPT to the given prefix. If any parameter in
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000133/// FPT has pass_object_size attrs, then we'll add parameters for those, too.
134static void appendParameterTypes(const CodeGenTypes &CGT,
135 SmallVectorImpl<CanQualType> &prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000136 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
George Burgess IVb7760212017-02-24 02:49:47 +0000137 CanQual<FunctionProtoType> FPT) {
138 // Fast path: don't touch param info if we don't need to.
139 if (!FPT->hasExtParameterInfos()) {
140 assert(paramInfos.empty() &&
141 "We have paramInfos, but the prototype doesn't?");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000142 prefix.append(FPT->param_type_begin(), FPT->param_type_end());
143 return;
144 }
145
George Burgess IVb7760212017-02-24 02:49:47 +0000146 unsigned PrefixSize = prefix.size();
147 // In the vast majority of cases, we'll have precisely FPT->getNumParams()
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000148 // parameters; the only thing that can change this is the presence of
149 // pass_object_size. So, we preallocate for the common case.
150 prefix.reserve(prefix.size() + FPT->getNumParams());
151
George Burgess IVb7760212017-02-24 02:49:47 +0000152 auto ExtInfos = FPT->getExtParameterInfos();
153 assert(ExtInfos.size() == FPT->getNumParams());
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000154 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
155 prefix.push_back(FPT->getParamType(I));
George Burgess IVb7760212017-02-24 02:49:47 +0000156 if (ExtInfos[I].hasPassObjectSize())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000157 prefix.push_back(CGT.getContext().getSizeType());
158 }
George Burgess IVb7760212017-02-24 02:49:47 +0000159
160 addExtParameterInfosForCall(paramInfos, FPT.getTypePtr(), PrefixSize,
161 prefix.size());
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000162}
163
John McCall8dda7b22012-07-07 06:41:13 +0000164/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000165/// type, on top of any implicit parameters already stored.
166static const CGFunctionInfo &
Peter Collingbournef7706832014-12-12 23:41:25 +0000167arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000168 SmallVectorImpl<CanQualType> &prefix,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000169 CanQual<FunctionProtoType> FTP,
170 const FunctionDecl *FD) {
John McCallc56a8b32016-03-11 04:30:31 +0000171 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
George Burgess IV419996c2016-06-16 23:06:04 +0000172 RequiredArgs Required =
173 RequiredArgs::forPrototypePlus(FTP, prefix.size(), FD);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000174 // FIXME: Kill copy.
George Burgess IVb7760212017-02-24 02:49:47 +0000175 appendParameterTypes(CGT, prefix, paramInfos, FTP);
Alp Toker314cc812014-01-25 16:55:45 +0000176 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
John McCallc56a8b32016-03-11 04:30:31 +0000177
Peter Collingbournef7706832014-12-12 23:41:25 +0000178 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
179 /*chainCall=*/false, prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000180 FTP->getExtInfo(), paramInfos,
George Burgess IV419996c2016-06-16 23:06:04 +0000181 Required);
John McCall8ee376f2010-02-24 07:14:12 +0000182}
183
John McCalla729c622012-02-17 03:33:10 +0000184/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000185/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000186const CGFunctionInfo &
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000187CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP,
188 const FunctionDecl *FD) {
John McCalla729c622012-02-17 03:33:10 +0000189 SmallVector<CanQualType, 16> argTypes;
Peter Collingbournef7706832014-12-12 23:41:25 +0000190 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000191 FTP, FD);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000192}
193
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000194static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000195 // Set the appropriate calling convention for the Function.
196 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000197 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000198
199 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000200 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000201
Erich Keane757d3172016-11-02 18:29:35 +0000202 if (D->hasAttr<RegCallAttr>())
203 return CC_X86RegCall;
204
Douglas Gregora941dca2010-05-18 16:57:00 +0000205 if (D->hasAttr<ThisCallAttr>())
206 return CC_X86ThisCall;
207
Reid Klecknerd7857f02014-10-24 17:42:17 +0000208 if (D->hasAttr<VectorCallAttr>())
209 return CC_X86VectorCall;
210
Dawn Perchik335e16b2010-09-03 01:29:35 +0000211 if (D->hasAttr<PascalAttr>())
212 return CC_X86Pascal;
213
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000214 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
215 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
216
Guy Benyeif0a014b2012-12-25 08:53:55 +0000217 if (D->hasAttr<IntelOclBiccAttr>())
218 return CC_IntelOclBicc;
219
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000220 if (D->hasAttr<MSABIAttr>())
Martin Storsjo022e7822017-07-17 20:49:45 +0000221 return IsWindows ? CC_C : CC_Win64;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000222
223 if (D->hasAttr<SysVABIAttr>())
224 return IsWindows ? CC_X86_64SysV : CC_C;
225
Roman Levenstein35aa5ce2016-03-16 18:00:46 +0000226 if (D->hasAttr<PreserveMostAttr>())
227 return CC_PreserveMost;
228
229 if (D->hasAttr<PreserveAllAttr>())
230 return CC_PreserveAll;
231
John McCallab26cfa2010-02-05 21:31:56 +0000232 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000233}
234
John McCalla729c622012-02-17 03:33:10 +0000235/// Arrange the argument and result information for a call to an
236/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000237/// (Zero value of RD means we don't have any meaningful "this" argument type,
238/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000239/// The member function must be an ordinary function, i.e. not a
240/// constructor or destructor.
241const CGFunctionInfo &
242CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000243 const FunctionProtoType *FTP,
244 const CXXMethodDecl *MD) {
John McCalla729c622012-02-17 03:33:10 +0000245 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000246
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000247 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000248 if (RD)
249 argTypes.push_back(GetThisType(Context, RD));
250 else
251 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000252
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000253 return ::arrangeLLVMFunctionInfo(
254 *this, true, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000255 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>(), MD);
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000256}
257
Yaxun Liu6c10a662018-06-12 00:16:33 +0000258/// Set calling convention for CUDA/HIP kernel.
259static void setCUDAKernelCallingConvention(CanQualType &FTy, CodeGenModule &CGM,
260 const FunctionDecl *FD) {
261 if (FD->hasAttr<CUDAGlobalAttr>()) {
262 const FunctionType *FT = FTy->getAs<FunctionType>();
263 CGM.getTargetCodeGenInfo().setCUDAKernelCallingConvention(FT);
264 FTy = FT->getCanonicalTypeUnqualified();
265 }
266}
267
John McCalla729c622012-02-17 03:33:10 +0000268/// Arrange the argument and result information for a declaration or
269/// definition of the given C++ non-static member function. The
270/// member function must be an ordinary function, i.e. not a
271/// constructor or destructor.
272const CGFunctionInfo &
273CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000274 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000275 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
276
Yaxun Liu6c10a662018-06-12 00:16:33 +0000277 CanQualType FT = GetFormalType(MD).getAs<Type>();
278 setCUDAKernelCallingConvention(FT, CGM, MD);
279 auto prototype = FT.getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +0000280
John McCalla729c622012-02-17 03:33:10 +0000281 if (MD->isInstance()) {
282 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000283 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000284 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
John McCalla729c622012-02-17 03:33:10 +0000285 }
286
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000287 return arrangeFreeFunctionType(prototype, MD);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000288}
289
Richard Smith5179eb72016-06-28 19:03:57 +0000290bool CodeGenTypes::inheritingCtorHasParams(
291 const InheritedConstructor &Inherited, CXXCtorType Type) {
292 // Parameters are unnecessary if we're constructing a base class subobject
293 // and the inherited constructor lives in a virtual base.
294 return Type == Ctor_Complete ||
295 !Inherited.getShadowDecl()->constructsVirtualBase() ||
296 !Target.getCXXABI().hasConstructorVariants();
297 }
298
John McCalla729c622012-02-17 03:33:10 +0000299const CGFunctionInfo &
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000300CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
301 StructorType Type) {
302
John McCalla729c622012-02-17 03:33:10 +0000303 SmallVector<CanQualType, 16> argTypes;
John McCallc56a8b32016-03-11 04:30:31 +0000304 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000305 argTypes.push_back(GetThisType(Context, MD->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000306
Richard Smith5179eb72016-06-28 19:03:57 +0000307 bool PassParams = true;
308
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000309 GlobalDecl GD;
310 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
311 GD = GlobalDecl(CD, toCXXCtorType(Type));
Richard Smith5179eb72016-06-28 19:03:57 +0000312
313 // A base class inheriting constructor doesn't get forwarded arguments
314 // needed to construct a virtual base (or base class thereof).
315 if (auto Inherited = CD->getInheritedConstructor())
316 PassParams = inheritingCtorHasParams(Inherited, toCXXCtorType(Type));
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000317 } else {
318 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
319 GD = GlobalDecl(DD, toCXXDtorType(Type));
320 }
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000321
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000322 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall5d865c322010-08-31 07:33:07 +0000323
324 // Add the formal parameters.
Richard Smith5179eb72016-06-28 19:03:57 +0000325 if (PassParams)
George Burgess IVb7760212017-02-24 02:49:47 +0000326 appendParameterTypes(*this, argTypes, paramInfos, FTP);
John McCall5d865c322010-08-31 07:33:07 +0000327
George Burgess IV75b34a92017-02-22 22:38:25 +0000328 CGCXXABI::AddedStructorArgs AddedArgs =
329 TheCXXABI.buildStructorSignature(MD, Type, argTypes);
330 if (!paramInfos.empty()) {
331 // Note: prefix implies after the first param.
332 if (AddedArgs.Prefix)
333 paramInfos.insert(paramInfos.begin() + 1, AddedArgs.Prefix,
334 FunctionProtoType::ExtParameterInfo{});
335 if (AddedArgs.Suffix)
336 paramInfos.append(AddedArgs.Suffix,
337 FunctionProtoType::ExtParameterInfo{});
338 }
Reid Kleckner89077a12013-12-17 19:46:40 +0000339
340 RequiredArgs required =
Richard Smith5179eb72016-06-28 19:03:57 +0000341 (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
342 : RequiredArgs::All);
Reid Kleckner89077a12013-12-17 19:46:40 +0000343
John McCall8dda7b22012-07-07 06:41:13 +0000344 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000345 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
346 ? argTypes.front()
347 : TheCXXABI.hasMostDerivedReturn(GD)
348 ? CGM.getContext().VoidPtrTy
349 : Context.VoidTy;
Peter Collingbournef7706832014-12-12 23:41:25 +0000350 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
351 /*chainCall=*/false, argTypes, extInfo,
John McCallc56a8b32016-03-11 04:30:31 +0000352 paramInfos, required);
353}
354
355static SmallVector<CanQualType, 16>
356getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
357 SmallVector<CanQualType, 16> argTypes;
358 for (auto &arg : args)
359 argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
360 return argTypes;
361}
362
363static SmallVector<CanQualType, 16>
364getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
365 SmallVector<CanQualType, 16> argTypes;
366 for (auto &arg : args)
367 argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
368 return argTypes;
369}
370
John McCallc56a8b32016-03-11 04:30:31 +0000371static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
372getExtParameterInfosForCall(const FunctionProtoType *proto,
373 unsigned prefixArgs, unsigned totalArgs) {
374 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
375 if (proto->hasExtParameterInfos()) {
376 addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
377 }
378 return result;
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000379}
380
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000381/// Arrange a call to a C++ method, passing the given arguments.
George Burgess IVd0a9e802017-02-23 22:07:35 +0000382///
383/// ExtraPrefixArgs is the number of ABI-specific args passed after the `this`
384/// parameter.
385/// ExtraSuffixArgs is the number of ABI-specific args passed at the end of
386/// args.
387/// PassProtoArgs indicates whether `args` has args for the parameters in the
388/// given CXXConstructorDecl.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000389const CGFunctionInfo &
390CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
391 const CXXConstructorDecl *D,
392 CXXCtorType CtorKind,
George Burgess IVd0a9e802017-02-23 22:07:35 +0000393 unsigned ExtraPrefixArgs,
394 unsigned ExtraSuffixArgs,
395 bool PassProtoArgs) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000396 // FIXME: Kill copy.
397 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000398 for (const auto &Arg : args)
399 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000400
George Burgess IVd0a9e802017-02-23 22:07:35 +0000401 // +1 for implicit this, which should always be args[0].
402 unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs;
403
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000404 CanQual<FunctionProtoType> FPT = GetFormalType(D);
George Burgess IVd0a9e802017-02-23 22:07:35 +0000405 RequiredArgs Required =
406 RequiredArgs::forPrototypePlus(FPT, TotalPrefixArgs + ExtraSuffixArgs, D);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000407 GlobalDecl GD(D, CtorKind);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000408 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
409 ? ArgTypes.front()
410 : TheCXXABI.hasMostDerivedReturn(GD)
411 ? CGM.getContext().VoidPtrTy
412 : Context.VoidTy;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000413
414 FunctionType::ExtInfo Info = FPT->getExtInfo();
George Burgess IVd0a9e802017-02-23 22:07:35 +0000415 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> ParamInfos;
416 // If the prototype args are elided, we should only have ABI-specific args,
417 // which never have param info.
418 if (PassProtoArgs && FPT->hasExtParameterInfos()) {
419 // ABI-specific suffix arguments are treated the same as variadic arguments.
420 addExtParameterInfosForCall(ParamInfos, FPT.getTypePtr(), TotalPrefixArgs,
421 ArgTypes.size());
422 }
Peter Collingbournef7706832014-12-12 23:41:25 +0000423 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
424 /*chainCall=*/false, ArgTypes, Info,
John McCallc56a8b32016-03-11 04:30:31 +0000425 ParamInfos, Required);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000426}
427
John McCalla729c622012-02-17 03:33:10 +0000428/// Arrange the argument and result information for the declaration or
429/// definition of the given function.
430const CGFunctionInfo &
431CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000432 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000433 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000434 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000435
John McCall2da83a32010-02-26 00:48:12 +0000436 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000437
John McCall2da83a32010-02-26 00:48:12 +0000438 assert(isa<FunctionType>(FTy));
Yaxun Liu6c10a662018-06-12 00:16:33 +0000439 setCUDAKernelCallingConvention(FTy, CGM, FD);
John McCalla729c622012-02-17 03:33:10 +0000440
441 // When declaring a function without a prototype, always use a
442 // non-variadic type.
George Burgess IV35cfca22017-01-06 19:10:48 +0000443 if (CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>()) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000444 return arrangeLLVMFunctionInfo(
445 noProto->getReturnType(), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000446 /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000447 }
448
George Burgess IV35cfca22017-01-06 19:10:48 +0000449 return arrangeFreeFunctionType(FTy.castAs<FunctionProtoType>(), FD);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000450}
451
John McCalla729c622012-02-17 03:33:10 +0000452/// Arrange the argument and result information for the declaration or
453/// definition of an Objective-C method.
454const CGFunctionInfo &
455CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
456 // It happens that this is the same as a call with no optional
457 // arguments, except also using the formal 'self' type.
458 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
459}
460
461/// Arrange the argument and result information for the function type
462/// through which to perform a send to the given Objective-C method,
463/// using the given receiver type. The receiver type is not always
464/// the 'self' type of the method or even an Objective-C pointer type.
465/// This is *not* the right method for actually performing such a
466/// message send, due to the possibility of optional arguments.
467const CGFunctionInfo &
468CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
469 QualType receiverType) {
470 SmallVector<CanQualType, 16> argTys;
Akira Hatanaka98a49332017-09-22 00:41:05 +0000471 SmallVector<FunctionProtoType::ExtParameterInfo, 4> extParamInfos(2);
John McCalla729c622012-02-17 03:33:10 +0000472 argTys.push_back(Context.getCanonicalParamType(receiverType));
473 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000474 // FIXME: Kill copy?
David Majnemer59f77922016-06-24 04:05:48 +0000475 for (const auto *I : MD->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000476 argTys.push_back(Context.getCanonicalParamType(I->getType()));
Akira Hatanaka98a49332017-09-22 00:41:05 +0000477 auto extParamInfo = FunctionProtoType::ExtParameterInfo().withIsNoEscape(
478 I->hasAttr<NoEscapeAttr>());
479 extParamInfos.push_back(extParamInfo);
John McCall8ee376f2010-02-24 07:14:12 +0000480 }
John McCall31168b02011-06-15 23:02:42 +0000481
482 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000483 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
484 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000485
David Blaikiebbafb8a2012-03-11 07:00:24 +0000486 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000487 MD->hasAttr<NSReturnsRetainedAttr>())
488 einfo = einfo.withProducesResult(true);
489
John McCalla729c622012-02-17 03:33:10 +0000490 RequiredArgs required =
491 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
492
Peter Collingbournef7706832014-12-12 23:41:25 +0000493 return arrangeLLVMFunctionInfo(
494 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
Akira Hatanaka98a49332017-09-22 00:41:05 +0000495 /*chainCall=*/false, argTys, einfo, extParamInfos, required);
John McCallc56a8b32016-03-11 04:30:31 +0000496}
497
498const CGFunctionInfo &
499CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
500 const CallArgList &args) {
501 auto argTypes = getArgTypesForCall(Context, args);
502 FunctionType::ExtInfo einfo;
503
504 return arrangeLLVMFunctionInfo(
505 GetReturnType(returnType), /*instanceMethod=*/false,
506 /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000507}
508
John McCalla729c622012-02-17 03:33:10 +0000509const CGFunctionInfo &
510CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000511 // FIXME: Do we need to handle ObjCMethodDecl?
512 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000513
Anders Carlsson6710c532010-02-06 02:44:09 +0000514 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000515 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
Anders Carlsson6710c532010-02-06 02:44:09 +0000516
517 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000518 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000519
John McCalla729c622012-02-17 03:33:10 +0000520 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000521}
522
Reid Klecknerc3473512014-08-29 21:43:29 +0000523/// Arrange a thunk that takes 'this' as the first parameter followed by
524/// varargs. Return a void pointer, regardless of the actual return type.
525/// The body of the thunk will end in a musttail call to a function of the
526/// correct type, and the caller will bitcast the function to the correct
527/// prototype.
528const CGFunctionInfo &
Reid Kleckner399d96e2018-04-02 20:20:33 +0000529CodeGenTypes::arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD) {
530 assert(MD->isVirtual() && "only methods have thunks");
Reid Klecknerc3473512014-08-29 21:43:29 +0000531 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
532 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
Peter Collingbournef7706832014-12-12 23:41:25 +0000533 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
534 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000535 FTP->getExtInfo(), {}, RequiredArgs(1));
Reid Klecknerc3473512014-08-29 21:43:29 +0000536}
537
David Majnemerdfa6d202015-03-11 18:36:39 +0000538const CGFunctionInfo &
David Majnemer37fd66e2015-03-13 22:36:55 +0000539CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
540 CXXCtorType CT) {
541 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
542
David Majnemerdfa6d202015-03-11 18:36:39 +0000543 CanQual<FunctionProtoType> FTP = GetFormalType(CD);
544 SmallVector<CanQualType, 2> ArgTys;
545 const CXXRecordDecl *RD = CD->getParent();
546 ArgTys.push_back(GetThisType(Context, RD));
David Majnemer37fd66e2015-03-13 22:36:55 +0000547 if (CT == Ctor_CopyingClosure)
548 ArgTys.push_back(*FTP->param_type_begin());
David Majnemerdfa6d202015-03-11 18:36:39 +0000549 if (RD->getNumVBases() > 0)
550 ArgTys.push_back(Context.IntTy);
551 CallingConv CC = Context.getDefaultCallingConvention(
552 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
553 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
554 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000555 FunctionType::ExtInfo(CC), {},
556 RequiredArgs::All);
David Majnemerdfa6d202015-03-11 18:36:39 +0000557}
558
John McCallc818bbb2012-12-07 07:03:17 +0000559/// Arrange a call as unto a free function, except possibly with an
560/// additional number of formal parameters considered required.
561static const CGFunctionInfo &
562arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000563 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000564 const CallArgList &args,
565 const FunctionType *fnType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000566 unsigned numExtraRequiredArgs,
567 bool chainCall) {
John McCallc818bbb2012-12-07 07:03:17 +0000568 assert(args.size() >= numExtraRequiredArgs);
569
John McCallc56a8b32016-03-11 04:30:31 +0000570 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
571
John McCallc818bbb2012-12-07 07:03:17 +0000572 // In most cases, there are no optional arguments.
573 RequiredArgs required = RequiredArgs::All;
574
575 // If we have a variadic prototype, the required arguments are the
576 // extra prefix plus the arguments in the prototype.
577 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
578 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000579 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000580
John McCallc56a8b32016-03-11 04:30:31 +0000581 if (proto->hasExtParameterInfos())
582 addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
583 args.size());
584
John McCallc818bbb2012-12-07 07:03:17 +0000585 // If we don't have a prototype at all, but we're supposed to
586 // explicitly use the variadic convention for unprototyped calls,
587 // treat all of the arguments as required but preserve the nominal
588 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000589 } else if (CGM.getTargetCodeGenInfo()
590 .isNoProtoCallVariadic(args,
591 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000592 required = RequiredArgs(args.size());
593 }
594
Peter Collingbournef7706832014-12-12 23:41:25 +0000595 // FIXME: Kill copy.
596 SmallVector<CanQualType, 16> argTypes;
597 for (const auto &arg : args)
598 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
599 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
600 /*instanceMethod=*/false, chainCall,
John McCallc56a8b32016-03-11 04:30:31 +0000601 argTypes, fnType->getExtInfo(), paramInfos,
602 required);
John McCallc818bbb2012-12-07 07:03:17 +0000603}
604
John McCalla729c622012-02-17 03:33:10 +0000605/// Figure out the rules for calling a function with the given formal
606/// type using the given arguments. The arguments are necessary
607/// because the function might be unprototyped, in which case it's
608/// target-dependent in crazy ways.
609const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000610CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
Peter Collingbournef7706832014-12-12 23:41:25 +0000611 const FunctionType *fnType,
612 bool chainCall) {
613 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
614 chainCall ? 1 : 0, chainCall);
John McCallc818bbb2012-12-07 07:03:17 +0000615}
John McCalla729c622012-02-17 03:33:10 +0000616
John McCallc56a8b32016-03-11 04:30:31 +0000617/// A block function is essentially a free function with an
John McCallc818bbb2012-12-07 07:03:17 +0000618/// extra implicit argument.
619const CGFunctionInfo &
620CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
621 const FunctionType *fnType) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000622 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
623 /*chainCall=*/false);
John McCalla729c622012-02-17 03:33:10 +0000624}
625
626const CGFunctionInfo &
John McCallc56a8b32016-03-11 04:30:31 +0000627CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
628 const FunctionArgList &params) {
629 auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
630 auto argTypes = getArgTypesForDeclaration(Context, params);
631
George Burgess IV419996c2016-06-16 23:06:04 +0000632 return arrangeLLVMFunctionInfo(
633 GetReturnType(proto->getReturnType()),
634 /*instanceMethod*/ false, /*chainCall*/ false, argTypes,
635 proto->getExtInfo(), paramInfos,
636 RequiredArgs::forPrototypePlus(proto, 1, nullptr));
John McCallc56a8b32016-03-11 04:30:31 +0000637}
638
639const CGFunctionInfo &
640CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
641 const CallArgList &args) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000642 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000643 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000644 for (const auto &Arg : args)
645 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Peter Collingbournef7706832014-12-12 23:41:25 +0000646 return arrangeLLVMFunctionInfo(
647 GetReturnType(resultType), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000648 /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
649 /*paramInfos=*/ {}, RequiredArgs::All);
John McCall8dda7b22012-07-07 06:41:13 +0000650}
651
John McCallc56a8b32016-03-11 04:30:31 +0000652const CGFunctionInfo &
653CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
654 const FunctionArgList &args) {
655 auto argTypes = getArgTypesForDeclaration(Context, args);
656
657 return arrangeLLVMFunctionInfo(
658 GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
659 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
660}
661
662const CGFunctionInfo &
663CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
664 ArrayRef<CanQualType> argTypes) {
665 return arrangeLLVMFunctionInfo(
666 resultType, /*instanceMethod=*/false, /*chainCall=*/false,
667 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
668}
669
John McCall8dda7b22012-07-07 06:41:13 +0000670/// Arrange a call to a C++ method, passing the given arguments.
George Burgess IVd0a9e802017-02-23 22:07:35 +0000671///
672/// numPrefixArgs is the number of ABI-specific prefix arguments we have. It
673/// does not count `this`.
John McCall8dda7b22012-07-07 06:41:13 +0000674const CGFunctionInfo &
675CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
John McCallc56a8b32016-03-11 04:30:31 +0000676 const FunctionProtoType *proto,
George Burgess IVd0a9e802017-02-23 22:07:35 +0000677 RequiredArgs required,
678 unsigned numPrefixArgs) {
679 assert(numPrefixArgs + 1 <= args.size() &&
680 "Emitting a call with less args than the required prefix?");
681 // Add one to account for `this`. It's a bit awkward here, but we don't count
682 // `this` in similar places elsewhere.
John McCallc56a8b32016-03-11 04:30:31 +0000683 auto paramInfos =
George Burgess IVd0a9e802017-02-23 22:07:35 +0000684 getExtParameterInfosForCall(proto, numPrefixArgs + 1, args.size());
John McCallc56a8b32016-03-11 04:30:31 +0000685
John McCall8dda7b22012-07-07 06:41:13 +0000686 // FIXME: Kill copy.
John McCallc56a8b32016-03-11 04:30:31 +0000687 auto argTypes = getArgTypesForCall(Context, args);
John McCall8dda7b22012-07-07 06:41:13 +0000688
John McCallc56a8b32016-03-11 04:30:31 +0000689 FunctionType::ExtInfo info = proto->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000690 return arrangeLLVMFunctionInfo(
John McCallc56a8b32016-03-11 04:30:31 +0000691 GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
692 /*chainCall=*/false, argTypes, info, paramInfos, required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000693}
694
John McCalla729c622012-02-17 03:33:10 +0000695const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Peter Collingbournef7706832014-12-12 23:41:25 +0000696 return arrangeLLVMFunctionInfo(
697 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000698 None, FunctionType::ExtInfo(), {}, RequiredArgs::All);
699}
700
701const CGFunctionInfo &
702CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
703 const CallArgList &args) {
704 assert(signature.arg_size() <= args.size());
705 if (signature.arg_size() == args.size())
706 return signature;
707
708 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
709 auto sigParamInfos = signature.getExtParameterInfos();
710 if (!sigParamInfos.empty()) {
711 paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
712 paramInfos.resize(args.size());
713 }
714
715 auto argTypes = getArgTypesForCall(Context, args);
716
717 assert(signature.getRequiredArgs().allowsOptionalArgs());
718 return arrangeLLVMFunctionInfo(signature.getReturnType(),
719 signature.isInstanceMethod(),
720 signature.isChainCall(),
721 argTypes,
722 signature.getExtInfo(),
723 paramInfos,
724 signature.getRequiredArgs());
John McCalla738c252011-03-09 04:27:21 +0000725}
726
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +0000727namespace clang {
728namespace CodeGen {
729void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI);
730}
731}
732
John McCalla729c622012-02-17 03:33:10 +0000733/// Arrange the argument and result information for an abstract value
734/// of a given function type. This is the method which all of the
735/// above functions ultimately defer to.
736const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000737CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000738 bool instanceMethod,
739 bool chainCall,
John McCall8dda7b22012-07-07 06:41:13 +0000740 ArrayRef<CanQualType> argTypes,
741 FunctionType::ExtInfo info,
John McCallc56a8b32016-03-11 04:30:31 +0000742 ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
John McCall8dda7b22012-07-07 06:41:13 +0000743 RequiredArgs required) {
Fangrui Song3117b172018-10-20 17:53:42 +0000744 assert(llvm::all_of(argTypes,
745 [](CanQualType T) { return T.isCanonicalAsParam(); }));
John McCall2da83a32010-02-26 00:48:12 +0000746
Daniel Dunbare0be8292009-02-03 00:07:12 +0000747 // Lookup or create unique function info.
748 llvm::FoldingSetNodeID ID;
John McCallc56a8b32016-03-11 04:30:31 +0000749 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
750 required, resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000751
Craig Topper8a13c412014-05-21 05:09:00 +0000752 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000753 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000754 if (FI)
755 return *FI;
756
John McCallc56a8b32016-03-11 04:30:31 +0000757 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
758
John McCalla729c622012-02-17 03:33:10 +0000759 // Construct the function info. We co-allocate the ArgInfos.
Peter Collingbournef7706832014-12-12 23:41:25 +0000760 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
John McCallc56a8b32016-03-11 04:30:31 +0000761 paramInfos, resultType, argTypes, required);
John McCalla729c622012-02-17 03:33:10 +0000762 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000763
David Blaikie82e95a32014-11-19 07:49:47 +0000764 bool inserted = FunctionsBeingProcessed.insert(FI).second;
765 (void)inserted;
John McCalla729c622012-02-17 03:33:10 +0000766 assert(inserted && "Recursively being processed?");
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +0000767
Daniel Dunbar313321e2009-02-03 05:31:23 +0000768 // Compute ABI information.
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +0000769 if (CC == llvm::CallingConv::SPIR_KERNEL) {
770 // Force target independent argument handling for the host visible
771 // kernel functions.
772 computeSPIRKernelABIInfo(CGM, *FI);
773 } else if (info.getCC() == CC_Swift) {
John McCall12f23522016-04-04 18:33:08 +0000774 swiftcall::computeABIInfo(CGM, *FI);
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +0000775 } else {
776 getABIInfo().computeInfo(*FI);
John McCall12f23522016-04-04 18:33:08 +0000777 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000778
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000779 // Loop over all of the computed argument and return value info. If any of
780 // them are direct or extend without a specified coerce type, specify the
781 // default now.
John McCalla729c622012-02-17 03:33:10 +0000782 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000783 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000784 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000785
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000786 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000787 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000788 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000789
John McCalla729c622012-02-17 03:33:10 +0000790 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
791 assert(erased && "Not in set?");
Fangrui Song6907ce22018-07-30 19:24:48 +0000792
Daniel Dunbare0be8292009-02-03 00:07:12 +0000793 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000794}
795
John McCalla729c622012-02-17 03:33:10 +0000796CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Peter Collingbournef7706832014-12-12 23:41:25 +0000797 bool instanceMethod,
798 bool chainCall,
John McCalla729c622012-02-17 03:33:10 +0000799 const FunctionType::ExtInfo &info,
John McCallc56a8b32016-03-11 04:30:31 +0000800 ArrayRef<ExtParameterInfo> paramInfos,
John McCalla729c622012-02-17 03:33:10 +0000801 CanQualType resultType,
802 ArrayRef<CanQualType> argTypes,
803 RequiredArgs required) {
John McCallc56a8b32016-03-11 04:30:31 +0000804 assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
805
806 void *buffer =
807 operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
808 argTypes.size() + 1, paramInfos.size()));
809
John McCalla729c622012-02-17 03:33:10 +0000810 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
811 FI->CallingConvention = llvmCC;
812 FI->EffectiveCallingConvention = llvmCC;
813 FI->ASTCallingConvention = info.getCC();
Peter Collingbournef7706832014-12-12 23:41:25 +0000814 FI->InstanceMethod = instanceMethod;
815 FI->ChainCall = chainCall;
John McCalla729c622012-02-17 03:33:10 +0000816 FI->NoReturn = info.getNoReturn();
817 FI->ReturnsRetained = info.getProducesResult();
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +0000818 FI->NoCallerSavedRegs = info.getNoCallerSavedRegs();
Oren Ben Simhon220671a2018-03-17 13:31:35 +0000819 FI->NoCfCheck = info.getNoCfCheck();
John McCalla729c622012-02-17 03:33:10 +0000820 FI->Required = required;
821 FI->HasRegParm = info.getHasRegParm();
822 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000823 FI->ArgStruct = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +0000824 FI->ArgStructAlign = 0;
John McCalla729c622012-02-17 03:33:10 +0000825 FI->NumArgs = argTypes.size();
John McCallc56a8b32016-03-11 04:30:31 +0000826 FI->HasExtParameterInfos = !paramInfos.empty();
John McCalla729c622012-02-17 03:33:10 +0000827 FI->getArgsBuffer()[0].type = resultType;
828 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
829 FI->getArgsBuffer()[i + 1].type = argTypes[i];
John McCallc56a8b32016-03-11 04:30:31 +0000830 for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
831 FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
John McCalla729c622012-02-17 03:33:10 +0000832 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000833}
834
835/***/
836
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000837namespace {
838// ABIArgInfo::Expand implementation.
839
840// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
841struct TypeExpansion {
842 enum TypeExpansionKind {
843 // Elements of constant arrays are expanded recursively.
844 TEK_ConstantArray,
845 // Record fields are expanded recursively (but if record is a union, only
846 // the field with the largest size is expanded).
847 TEK_Record,
848 // For complex types, real and imaginary parts are expanded recursively.
849 TEK_Complex,
850 // All other types are not expandable.
851 TEK_None
852 };
853
854 const TypeExpansionKind Kind;
855
856 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000857 virtual ~TypeExpansion() {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000858};
859
860struct ConstantArrayExpansion : TypeExpansion {
861 QualType EltTy;
862 uint64_t NumElts;
863
864 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
865 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
866 static bool classof(const TypeExpansion *TE) {
867 return TE->Kind == TEK_ConstantArray;
868 }
869};
870
871struct RecordExpansion : TypeExpansion {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000872 SmallVector<const CXXBaseSpecifier *, 1> Bases;
873
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000874 SmallVector<const FieldDecl *, 1> Fields;
875
Reid Klecknere9f6a712014-10-31 17:10:41 +0000876 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
877 SmallVector<const FieldDecl *, 1> &&Fields)
Benjamin Kramer0bb97742016-02-13 16:00:13 +0000878 : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
879 Fields(std::move(Fields)) {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000880 static bool classof(const TypeExpansion *TE) {
881 return TE->Kind == TEK_Record;
882 }
883};
884
885struct ComplexExpansion : TypeExpansion {
886 QualType EltTy;
887
888 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
889 static bool classof(const TypeExpansion *TE) {
890 return TE->Kind == TEK_Complex;
891 }
892};
893
894struct NoExpansion : TypeExpansion {
895 NoExpansion() : TypeExpansion(TEK_None) {}
896 static bool classof(const TypeExpansion *TE) {
897 return TE->Kind == TEK_None;
898 }
899};
900} // namespace
901
902static std::unique_ptr<TypeExpansion>
903getTypeExpansion(QualType Ty, const ASTContext &Context) {
904 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
905 return llvm::make_unique<ConstantArrayExpansion>(
906 AT->getElementType(), AT->getSize().getZExtValue());
907 }
908 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000909 SmallVector<const CXXBaseSpecifier *, 1> Bases;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000910 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000911 const RecordDecl *RD = RT->getDecl();
912 assert(!RD->hasFlexibleArrayMember() &&
913 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000914 if (RD->isUnion()) {
915 // Unions can be here only in degenerative cases - all the fields are same
916 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000917 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000918 CharUnits UnionSize = CharUnits::Zero();
919
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000920 for (const auto *FD : RD->fields()) {
Richard Smith866dee42018-04-02 18:29:43 +0000921 if (FD->isZeroLengthBitField(Context))
Reid Kleckner80944df2014-10-31 22:00:51 +0000922 continue;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000923 assert(!FD->isBitField() &&
924 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000925 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000926 if (UnionSize < FieldSize) {
927 UnionSize = FieldSize;
928 LargestFD = FD;
929 }
930 }
931 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000932 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000933 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000934 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
935 assert(!CXXRD->isDynamicClass() &&
936 "cannot expand vtable pointers in dynamic classes");
937 for (const CXXBaseSpecifier &BS : CXXRD->bases())
938 Bases.push_back(&BS);
939 }
940
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000941 for (const auto *FD : RD->fields()) {
Richard Smith866dee42018-04-02 18:29:43 +0000942 if (FD->isZeroLengthBitField(Context))
Reid Kleckner80944df2014-10-31 22:00:51 +0000943 continue;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000944 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000945 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000946 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000947 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000948 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000949 return llvm::make_unique<RecordExpansion>(std::move(Bases),
950 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000951 }
952 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
953 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
954 }
955 return llvm::make_unique<NoExpansion>();
956}
957
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000958static int getExpansionSize(QualType Ty, const ASTContext &Context) {
959 auto Exp = getTypeExpansion(Ty, Context);
960 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
961 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
962 }
963 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
964 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000965 for (auto BS : RExp->Bases)
966 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000967 for (auto FD : RExp->Fields)
968 Res += getExpansionSize(FD->getType(), Context);
969 return Res;
970 }
971 if (isa<ComplexExpansion>(Exp.get()))
972 return 2;
973 assert(isa<NoExpansion>(Exp.get()));
974 return 1;
975}
976
Alexey Samsonov153004f2014-09-29 22:08:00 +0000977void
978CodeGenTypes::getExpandedTypes(QualType Ty,
979 SmallVectorImpl<llvm::Type *>::iterator &TI) {
980 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000981 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
982 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000983 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000984 }
985 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000986 for (auto BS : RExp->Bases)
987 getExpandedTypes(BS->getType(), TI);
988 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000989 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000990 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
991 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000992 *TI++ = EltTy;
993 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000994 } else {
995 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000996 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000997 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000998}
999
John McCall7f416cc2015-09-08 08:05:57 +00001000static void forConstantArrayExpansion(CodeGenFunction &CGF,
1001 ConstantArrayExpansion *CAE,
1002 Address BaseAddr,
1003 llvm::function_ref<void(Address)> Fn) {
1004 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
1005 CharUnits EltAlign =
1006 BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
1007
1008 for (int i = 0, n = CAE->NumElts; i < n; i++) {
1009 llvm::Value *EltAddr =
1010 CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
1011 Fn(Address(EltAddr, EltAlign));
1012 }
1013}
1014
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001015void CodeGenFunction::ExpandTypeFromArgs(
John McCall12f23522016-04-04 18:33:08 +00001016 QualType Ty, LValue LV, SmallVectorImpl<llvm::Value *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +00001017 assert(LV.isSimple() &&
1018 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001019
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001020 auto Exp = getTypeExpansion(Ty, getContext());
1021 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +00001022 forConstantArrayExpansion(*this, CAExp, LV.getAddress(),
1023 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001024 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
1025 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
John McCall7f416cc2015-09-08 08:05:57 +00001026 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001027 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +00001028 Address This = LV.getAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +00001029 for (const CXXBaseSpecifier *BS : RExp->Bases) {
1030 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +00001031 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +00001032 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1033 /*NullCheckValue=*/false, SourceLocation());
1034 LValue SubLV = MakeAddrLValue(Base, BS->getType());
1035
1036 // Recurse onto bases.
1037 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
1038 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001039 for (auto FD : RExp->Fields) {
1040 // FIXME: What are the right qualifiers here?
Reid Kleckner9d031092016-05-02 22:42:34 +00001041 LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001042 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +00001043 }
John McCall7f416cc2015-09-08 08:05:57 +00001044 } else if (isa<ComplexExpansion>(Exp.get())) {
1045 auto realValue = *AI++;
1046 auto imagValue = *AI++;
1047 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001048 } else {
1049 assert(isa<NoExpansion>(Exp.get()));
1050 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001051 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001052}
1053
1054void CodeGenFunction::ExpandTypeToArgs(
Yaxun Liu5b330e82018-03-15 15:25:19 +00001055 QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001056 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
1057 auto Exp = getTypeExpansion(Ty, getContext());
1058 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
Yaxun Liu5b330e82018-03-15 15:25:19 +00001059 Address Addr = Arg.hasLValue() ? Arg.getKnownLValue().getAddress()
1060 : Arg.getKnownRValue().getAggregateAddress();
1061 forConstantArrayExpansion(
1062 *this, CAExp, Addr, [&](Address EltAddr) {
1063 CallArg EltArg = CallArg(
1064 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation()),
1065 CAExp->EltTy);
1066 ExpandTypeToArgs(CAExp->EltTy, EltArg, IRFuncTy, IRCallArgs,
1067 IRCallArgPos);
1068 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001069 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Yaxun Liu5b330e82018-03-15 15:25:19 +00001070 Address This = Arg.hasLValue() ? Arg.getKnownLValue().getAddress()
1071 : Arg.getKnownRValue().getAggregateAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +00001072 for (const CXXBaseSpecifier *BS : RExp->Bases) {
1073 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +00001074 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +00001075 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1076 /*NullCheckValue=*/false, SourceLocation());
Yaxun Liu5b330e82018-03-15 15:25:19 +00001077 CallArg BaseArg = CallArg(RValue::getAggregate(Base), BS->getType());
Reid Klecknere9f6a712014-10-31 17:10:41 +00001078
1079 // Recurse onto bases.
Yaxun Liu5b330e82018-03-15 15:25:19 +00001080 ExpandTypeToArgs(BS->getType(), BaseArg, IRFuncTy, IRCallArgs,
Reid Klecknere9f6a712014-10-31 17:10:41 +00001081 IRCallArgPos);
1082 }
1083
1084 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001085 for (auto FD : RExp->Fields) {
Yaxun Liu5b330e82018-03-15 15:25:19 +00001086 CallArg FldArg =
1087 CallArg(EmitRValueForField(LV, FD, SourceLocation()), FD->getType());
1088 ExpandTypeToArgs(FD->getType(), FldArg, IRFuncTy, IRCallArgs,
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001089 IRCallArgPos);
1090 }
1091 } else if (isa<ComplexExpansion>(Exp.get())) {
Yaxun Liu5b330e82018-03-15 15:25:19 +00001092 ComplexPairTy CV = Arg.getKnownRValue().getComplexVal();
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001093 IRCallArgs[IRCallArgPos++] = CV.first;
1094 IRCallArgs[IRCallArgPos++] = CV.second;
1095 } else {
1096 assert(isa<NoExpansion>(Exp.get()));
Yaxun Liu5b330e82018-03-15 15:25:19 +00001097 auto RV = Arg.getKnownRValue();
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001098 assert(RV.isScalar() &&
1099 "Unexpected non-scalar rvalue during struct expansion.");
1100
1101 // Insert a bitcast as needed.
1102 llvm::Value *V = RV.getScalarVal();
1103 if (IRCallArgPos < IRFuncTy->getNumParams() &&
1104 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
1105 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
1106
1107 IRCallArgs[IRCallArgPos++] = V;
1108 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001109}
1110
John McCall7f416cc2015-09-08 08:05:57 +00001111/// Create a temporary allocation for the purposes of coercion.
1112static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
1113 CharUnits MinAlign) {
1114 // Don't use an alignment that's worse than what LLVM would prefer.
1115 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
1116 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
1117
1118 return CGF.CreateTempAlloca(Ty, Align);
1119}
1120
Chris Lattner895c52b2010-06-27 06:04:18 +00001121/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +00001122/// accessing some number of bytes out of it, try to gep into the struct to get
1123/// at its inner goodness. Dive as deep as possible without entering an element
1124/// with an in-memory size smaller than DstSize.
John McCall7f416cc2015-09-08 08:05:57 +00001125static Address
1126EnterStructPointerForCoercedAccess(Address SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +00001127 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +00001128 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +00001129 // We can't dive into a zero-element struct.
1130 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001131
Chris Lattner2192fe52011-07-18 04:24:23 +00001132 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001133
Chris Lattner1cd66982010-06-27 05:56:15 +00001134 // If the first elt is at least as large as what we're looking for, or if the
James Molloy90d61012014-08-29 10:17:52 +00001135 // first element is the same size as the whole struct, we can enter it. The
1136 // comparison must be made on the store size and not the alloca size. Using
1137 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001138 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +00001139 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001140 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +00001141 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +00001142 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001143
Chris Lattner1cd66982010-06-27 05:56:15 +00001144 // GEP into the first element.
John McCall7f416cc2015-09-08 08:05:57 +00001145 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, CharUnits(), "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001146
Chris Lattner1cd66982010-06-27 05:56:15 +00001147 // If the first element is a struct, recurse.
John McCall7f416cc2015-09-08 08:05:57 +00001148 llvm::Type *SrcTy = SrcPtr.getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001149 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +00001150 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +00001151
1152 return SrcPtr;
1153}
1154
Chris Lattner055097f2010-06-27 06:26:04 +00001155/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1156/// are either integers or pointers. This does a truncation of the value if it
1157/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001158///
1159/// This behaves as if the value were coerced through memory, so on big-endian
1160/// targets the high bits are preserved in a truncation, while little-endian
1161/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +00001162static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +00001163 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +00001164 CodeGenFunction &CGF) {
1165 if (Val->getType() == Ty)
1166 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001167
Chris Lattner055097f2010-06-27 06:26:04 +00001168 if (isa<llvm::PointerType>(Val->getType())) {
1169 // If this is Pointer->Pointer avoid conversion to and from int.
1170 if (isa<llvm::PointerType>(Ty))
1171 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001172
Chris Lattner055097f2010-06-27 06:26:04 +00001173 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +00001174 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +00001175 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001176
Chris Lattner2192fe52011-07-18 04:24:23 +00001177 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +00001178 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +00001179 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001180
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001181 if (Val->getType() != DestIntTy) {
1182 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
1183 if (DL.isBigEndian()) {
1184 // Preserve the high bits on big-endian targets.
1185 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +00001186 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1187 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1188
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001189 if (SrcSize > DstSize) {
1190 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
1191 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
1192 } else {
1193 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
1194 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
1195 }
1196 } else {
1197 // Little-endian targets preserve the low bits. No shifts required.
1198 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
1199 }
1200 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001201
Chris Lattner055097f2010-06-27 06:26:04 +00001202 if (isa<llvm::PointerType>(Ty))
1203 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
1204 return Val;
1205}
1206
Chris Lattner1cd66982010-06-27 05:56:15 +00001207
1208
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001209/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001210/// a pointer to an object of type \arg Ty, known to be aligned to
1211/// \arg SrcAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001212///
1213/// This safely handles the case when the src type is smaller than the
1214/// destination type; in this situation the values of bits which not
1215/// present in the src are undefined.
John McCall7f416cc2015-09-08 08:05:57 +00001216static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001217 CodeGenFunction &CGF) {
John McCall7f416cc2015-09-08 08:05:57 +00001218 llvm::Type *SrcTy = Src.getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001219
Chris Lattnerd200eda2010-06-28 22:51:39 +00001220 // If SrcTy and Ty are the same, just do a load.
1221 if (SrcTy == Ty)
John McCall7f416cc2015-09-08 08:05:57 +00001222 return CGF.Builder.CreateLoad(Src);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001223
Micah Villmowdd31ca12012-10-08 16:25:52 +00001224 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001225
Chris Lattner2192fe52011-07-18 04:24:23 +00001226 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001227 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF);
1228 SrcTy = Src.getType()->getElementType();
Chris Lattner1cd66982010-06-27 05:56:15 +00001229 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001230
Micah Villmowdd31ca12012-10-08 16:25:52 +00001231 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001232
Chris Lattner055097f2010-06-27 06:26:04 +00001233 // If the source and destination are integer or pointer types, just do an
1234 // extension or truncation to the desired type.
1235 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
1236 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
John McCall7f416cc2015-09-08 08:05:57 +00001237 llvm::Value *Load = CGF.Builder.CreateLoad(Src);
Chris Lattner055097f2010-06-27 06:26:04 +00001238 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
1239 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001240
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001241 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001242 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +00001243 // Generally SrcSize is never greater than DstSize, since this means we are
1244 // losing bits. However, this can happen in cases where the structure has
1245 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001246 //
Mike Stump18bb9282009-05-16 07:57:57 +00001247 // FIXME: Assert that we aren't truncating non-padding bits when have access
1248 // to that information.
Matt Arsenault7a124f32017-08-01 20:36:57 +00001249 Src = CGF.Builder.CreateBitCast(Src,
1250 Ty->getPointerTo(Src.getAddressSpace()));
John McCall7f416cc2015-09-08 08:05:57 +00001251 return CGF.Builder.CreateLoad(Src);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001252 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001253
John McCall7f416cc2015-09-08 08:05:57 +00001254 // Otherwise do coercion through memory. This is stupid, but simple.
1255 Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment());
Yaxun Liuc325d302017-12-07 01:39:52 +00001256 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.AllocaInt8PtrTy);
1257 Address SrcCasted = CGF.Builder.CreateBitCast(Src, CGF.AllocaInt8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001258 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
1259 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
John McCall7f416cc2015-09-08 08:05:57 +00001260 false);
1261 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001262}
1263
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001264// Function to store a first-class aggregate into memory. We prefer to
1265// store the elements rather than the aggregate to be more friendly to
1266// fast-isel.
1267// FIXME: Do we need to recurse here?
1268static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
John McCall7f416cc2015-09-08 08:05:57 +00001269 Address Dest, bool DestIsVolatile) {
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001270 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +00001271 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001272 dyn_cast<llvm::StructType>(Val->getType())) {
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001273 const llvm::StructLayout *Layout =
1274 CGF.CGM.getDataLayout().getStructLayout(STy);
1275
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001276 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00001277 auto EltOffset = CharUnits::fromQuantity(Layout->getElementOffset(i));
1278 Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i, EltOffset);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001279 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
John McCall7f416cc2015-09-08 08:05:57 +00001280 CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001281 }
1282 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001283 CGF.Builder.CreateStore(Val, Dest, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001284 }
1285}
1286
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001287/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001288/// where the source and destination may have different types. The
1289/// destination is known to be aligned to \arg DstAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001290///
1291/// This safely handles the case when the src type is larger than the
1292/// destination type; the upper bits of the src will be lost.
1293static void CreateCoercedStore(llvm::Value *Src,
John McCall7f416cc2015-09-08 08:05:57 +00001294 Address Dst,
Anders Carlsson17490832009-12-24 20:40:36 +00001295 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001296 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001297 llvm::Type *SrcTy = Src->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001298 llvm::Type *DstTy = Dst.getType()->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +00001299 if (SrcTy == DstTy) {
John McCall7f416cc2015-09-08 08:05:57 +00001300 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattnerd200eda2010-06-28 22:51:39 +00001301 return;
1302 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001303
Micah Villmowdd31ca12012-10-08 16:25:52 +00001304 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001305
Chris Lattner2192fe52011-07-18 04:24:23 +00001306 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001307 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF);
1308 DstTy = Dst.getType()->getElementType();
Chris Lattner895c52b2010-06-27 06:04:18 +00001309 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001310
Chris Lattner055097f2010-06-27 06:26:04 +00001311 // If the source and destination are integer or pointer types, just do an
1312 // extension or truncation to the desired type.
1313 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1314 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1315 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001316 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattner055097f2010-06-27 06:26:04 +00001317 return;
1318 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001319
Micah Villmowdd31ca12012-10-08 16:25:52 +00001320 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001321
Daniel Dunbar313321e2009-02-03 05:31:23 +00001322 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001323 if (SrcSize <= DstSize) {
Yaxun Liue9e5c4f2017-06-29 18:47:45 +00001324 Dst = CGF.Builder.CreateElementBitCast(Dst, SrcTy);
John McCall7f416cc2015-09-08 08:05:57 +00001325 BuildAggStore(CGF, Src, Dst, DstIsVolatile);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001326 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001327 // Otherwise do coercion through memory. This is stupid, but
1328 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001329
1330 // Generally SrcSize is never greater than DstSize, since this means we are
1331 // losing bits. However, this can happen in cases where the structure has
1332 // additional padding, for example due to a user specified alignment.
1333 //
1334 // FIXME: Assert that we aren't truncating non-padding bits when have access
1335 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001336 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1337 CGF.Builder.CreateStore(Src, Tmp);
Yaxun Liuc325d302017-12-07 01:39:52 +00001338 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.AllocaInt8PtrTy);
1339 Address DstCasted = CGF.Builder.CreateBitCast(Dst, CGF.AllocaInt8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001340 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1341 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
John McCall7f416cc2015-09-08 08:05:57 +00001342 false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001343 }
1344}
1345
John McCall7f416cc2015-09-08 08:05:57 +00001346static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
Fangrui Song6907ce22018-07-30 19:24:48 +00001347 const ABIArgInfo &info) {
John McCall7f416cc2015-09-08 08:05:57 +00001348 if (unsigned offset = info.getDirectOffset()) {
1349 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
1350 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1351 CharUnits::fromQuantity(offset));
1352 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
1353 }
1354 return addr;
1355}
1356
Alexey Samsonov153004f2014-09-29 22:08:00 +00001357namespace {
1358
1359/// Encapsulates information about the way function arguments from
1360/// CGFunctionInfo should be passed to actual LLVM IR function.
1361class ClangToLLVMArgMapping {
1362 static const unsigned InvalidIndex = ~0U;
1363 unsigned InallocaArgNo;
1364 unsigned SRetArgNo;
1365 unsigned TotalIRArgs;
1366
1367 /// Arguments of LLVM IR function corresponding to single Clang argument.
1368 struct IRArgs {
1369 unsigned PaddingArgIndex;
1370 // Argument is expanded to IR arguments at positions
1371 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1372 unsigned FirstArgIndex;
1373 unsigned NumberOfArgs;
1374
1375 IRArgs()
1376 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1377 NumberOfArgs(0) {}
1378 };
1379
1380 SmallVector<IRArgs, 8> ArgInfo;
1381
1382public:
1383 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1384 bool OnlyRequiredArgs = false)
1385 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1386 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1387 construct(Context, FI, OnlyRequiredArgs);
1388 }
1389
1390 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1391 unsigned getInallocaArgNo() const {
1392 assert(hasInallocaArg());
1393 return InallocaArgNo;
1394 }
1395
1396 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1397 unsigned getSRetArgNo() const {
1398 assert(hasSRetArg());
1399 return SRetArgNo;
1400 }
1401
1402 unsigned totalIRArgs() const { return TotalIRArgs; }
1403
1404 bool hasPaddingArg(unsigned ArgNo) const {
1405 assert(ArgNo < ArgInfo.size());
1406 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1407 }
1408 unsigned getPaddingArgNo(unsigned ArgNo) const {
1409 assert(hasPaddingArg(ArgNo));
1410 return ArgInfo[ArgNo].PaddingArgIndex;
1411 }
1412
1413 /// Returns index of first IR argument corresponding to ArgNo, and their
1414 /// quantity.
1415 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1416 assert(ArgNo < ArgInfo.size());
1417 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1418 ArgInfo[ArgNo].NumberOfArgs);
1419 }
1420
1421private:
1422 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1423 bool OnlyRequiredArgs);
1424};
1425
1426void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1427 const CGFunctionInfo &FI,
1428 bool OnlyRequiredArgs) {
1429 unsigned IRArgNo = 0;
1430 bool SwapThisWithSRet = false;
1431 const ABIArgInfo &RetAI = FI.getReturnInfo();
1432
1433 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1434 SwapThisWithSRet = RetAI.isSRetAfterThis();
1435 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1436 }
1437
1438 unsigned ArgNo = 0;
1439 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1440 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1441 ++I, ++ArgNo) {
1442 assert(I != FI.arg_end());
1443 QualType ArgType = I->type;
1444 const ABIArgInfo &AI = I->info;
1445 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1446 auto &IRArgs = ArgInfo[ArgNo];
1447
1448 if (AI.getPaddingType())
1449 IRArgs.PaddingArgIndex = IRArgNo++;
1450
1451 switch (AI.getKind()) {
1452 case ABIArgInfo::Extend:
1453 case ABIArgInfo::Direct: {
1454 // FIXME: handle sseregparm someday...
1455 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1456 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1457 IRArgs.NumberOfArgs = STy->getNumElements();
1458 } else {
1459 IRArgs.NumberOfArgs = 1;
1460 }
1461 break;
1462 }
1463 case ABIArgInfo::Indirect:
1464 IRArgs.NumberOfArgs = 1;
1465 break;
1466 case ABIArgInfo::Ignore:
1467 case ABIArgInfo::InAlloca:
1468 // ignore and inalloca doesn't have matching LLVM parameters.
1469 IRArgs.NumberOfArgs = 0;
1470 break;
John McCallf26e73d2016-03-11 04:30:43 +00001471 case ABIArgInfo::CoerceAndExpand:
1472 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1473 break;
1474 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001475 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1476 break;
1477 }
Alexey Samsonov153004f2014-09-29 22:08:00 +00001478
1479 if (IRArgs.NumberOfArgs > 0) {
1480 IRArgs.FirstArgIndex = IRArgNo;
1481 IRArgNo += IRArgs.NumberOfArgs;
1482 }
1483
1484 // Skip over the sret parameter when it comes second. We already handled it
1485 // above.
1486 if (IRArgNo == 1 && SwapThisWithSRet)
1487 IRArgNo++;
1488 }
1489 assert(ArgNo == ArgInfo.size());
1490
1491 if (FI.usesInAlloca())
1492 InallocaArgNo = IRArgNo++;
1493
1494 TotalIRArgs = IRArgNo;
1495}
1496} // namespace
1497
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001498/***/
1499
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001500bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Saleem Abdulrasoolf181f1a2018-02-28 20:16:12 +00001501 const auto &RI = FI.getReturnInfo();
1502 return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet());
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001503}
1504
Tim Northovere77cc392014-03-29 13:28:05 +00001505bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1506 return ReturnTypeUsesSRet(FI) &&
1507 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1508}
1509
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001510bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1511 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1512 switch (BT->getKind()) {
1513 default:
1514 return false;
1515 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001516 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001517 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001518 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001519 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001520 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001521 }
1522 }
1523
1524 return false;
1525}
1526
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001527bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1528 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1529 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1530 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001531 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001532 }
1533 }
1534
1535 return false;
1536}
1537
Chris Lattnera5f58b02011-07-09 17:41:47 +00001538llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001539 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1540 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001541}
1542
Chris Lattnera5f58b02011-07-09 17:41:47 +00001543llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001544CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001545
David Blaikie82e95a32014-11-19 07:49:47 +00001546 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1547 (void)Inserted;
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001548 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001549
Alexey Samsonov153004f2014-09-29 22:08:00 +00001550 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001551 const ABIArgInfo &retAI = FI.getReturnInfo();
1552 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001553 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001554 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001555
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001556 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001557 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001558 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001559 break;
1560
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001561 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001562 if (retAI.getInAllocaSRet()) {
1563 // sret things on win32 aren't void, they return the sret pointer.
1564 QualType ret = FI.getReturnType();
1565 llvm::Type *ty = ConvertType(ret);
1566 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1567 resultType = llvm::PointerType::get(ty, addressSpace);
1568 } else {
1569 resultType = llvm::Type::getVoidTy(getLLVMContext());
1570 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001571 break;
1572
John McCall7f416cc2015-09-08 08:05:57 +00001573 case ABIArgInfo::Indirect:
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001574 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001575 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001576 break;
John McCallf26e73d2016-03-11 04:30:43 +00001577
1578 case ABIArgInfo::CoerceAndExpand:
1579 resultType = retAI.getUnpaddedCoerceAndExpandType();
1580 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001581 }
Mike Stump11289f42009-09-09 15:08:12 +00001582
Alexey Samsonov153004f2014-09-29 22:08:00 +00001583 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1584 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1585
1586 // Add type for sret argument.
1587 if (IRFunctionArgs.hasSRetArg()) {
1588 QualType Ret = FI.getReturnType();
1589 llvm::Type *Ty = ConvertType(Ret);
1590 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1591 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1592 llvm::PointerType::get(Ty, AddressSpace);
1593 }
1594
1595 // Add type for inalloca argument.
1596 if (IRFunctionArgs.hasInallocaArg()) {
1597 auto ArgStruct = FI.getArgStruct();
1598 assert(ArgStruct);
1599 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1600 }
1601
John McCallc818bbb2012-12-07 07:03:17 +00001602 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001603 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001604 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1605 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001606 for (; it != ie; ++it, ++ArgNo) {
1607 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001608
Rafael Espindolafad28de2012-10-24 01:59:00 +00001609 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001610 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1611 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1612 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001613
Alexey Samsonov153004f2014-09-29 22:08:00 +00001614 unsigned FirstIRArg, NumIRArgs;
1615 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1616
1617 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001618 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001619 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001620 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001621 break;
1622
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001623 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001624 assert(NumIRArgs == 1);
Yaxun Liud7523282017-04-17 20:10:44 +00001625 // indirect arguments are always on the stack, which is alloca addr space.
Chris Lattner2192fe52011-07-18 04:24:23 +00001626 llvm::Type *LTy = ConvertTypeForMem(it->type);
Yaxun Liud7523282017-04-17 20:10:44 +00001627 ArgTypes[FirstIRArg] = LTy->getPointerTo(
1628 CGM.getDataLayout().getAllocaAddrSpace());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001629 break;
1630 }
1631
1632 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001633 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001634 // Fast-isel and the optimizer generally like scalar values better than
1635 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001636 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001637 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001638 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1639 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001640 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001641 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001642 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001643 assert(NumIRArgs == 1);
1644 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001645 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001646 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001647 }
Mike Stump11289f42009-09-09 15:08:12 +00001648
John McCallf26e73d2016-03-11 04:30:43 +00001649 case ABIArgInfo::CoerceAndExpand: {
1650 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1651 for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1652 *ArgTypesIter++ = EltTy;
1653 }
1654 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1655 break;
1656 }
1657
Daniel Dunbard3674e62008-09-11 01:48:57 +00001658 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001659 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1660 getExpandedTypes(it->type, ArgTypesIter);
1661 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001662 break;
1663 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001664 }
1665
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001666 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1667 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001668
1669 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001670}
1671
Chris Lattner2192fe52011-07-18 04:24:23 +00001672llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001673 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001674 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001675
Chris Lattner8806e322011-07-10 00:18:59 +00001676 if (!isFuncTypeConvertible(FPT))
1677 return llvm::StructType::get(getLLVMContext());
Fangrui Song6907ce22018-07-30 19:24:48 +00001678
Chris Lattner8806e322011-07-10 00:18:59 +00001679 const CGFunctionInfo *Info;
1680 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001681 Info =
1682 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001683 else
John McCalla729c622012-02-17 03:33:10 +00001684 Info = &arrangeCXXMethodDeclaration(MD);
1685 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001686}
1687
Samuel Antao798f11c2015-11-23 22:04:44 +00001688static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
1689 llvm::AttrBuilder &FuncAttrs,
1690 const FunctionProtoType *FPT) {
1691 if (!FPT)
1692 return;
1693
1694 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
Richard Smitheaf11ad2018-05-03 03:58:32 +00001695 FPT->isNothrow())
Samuel Antao798f11c2015-11-23 22:04:44 +00001696 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1697}
1698
Justin Lebarb080b632017-01-25 21:29:48 +00001699void CodeGenModule::ConstructDefaultFnAttrList(StringRef Name, bool HasOptnone,
1700 bool AttrOnCallSite,
1701 llvm::AttrBuilder &FuncAttrs) {
1702 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1703 if (!HasOptnone) {
1704 if (CodeGenOpts.OptimizeSize)
1705 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1706 if (CodeGenOpts.OptimizeSize == 2)
1707 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1708 }
1709
1710 if (CodeGenOpts.DisableRedZone)
1711 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Kristina Brooks7f569b72018-10-18 14:07:02 +00001712 if (CodeGenOpts.IndirectTlsSegRefs)
1713 FuncAttrs.addAttribute("indirect-tls-seg-refs");
Justin Lebarb080b632017-01-25 21:29:48 +00001714 if (CodeGenOpts.NoImplicitFloat)
1715 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
1716
1717 if (AttrOnCallSite) {
1718 // Attributes that should go on the call site only.
1719 if (!CodeGenOpts.SimplifyLibCalls ||
1720 CodeGenOpts.isNoBuiltinFunc(Name.data()))
1721 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
1722 if (!CodeGenOpts.TrapFuncName.empty())
1723 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
1724 } else {
1725 // Attributes that should go on the function, but not the call site.
1726 if (!CodeGenOpts.DisableFPElim) {
1727 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
1728 } else if (CodeGenOpts.OmitLeafFramePointer) {
1729 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
1730 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
1731 } else {
1732 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
1733 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
1734 }
1735
1736 FuncAttrs.addAttribute("less-precise-fpmad",
1737 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
1738
Manoj Guptada08f6a2018-07-19 00:44:52 +00001739 if (CodeGenOpts.NullPointerIsValid)
1740 FuncAttrs.addAttribute("null-pointer-is-valid", "true");
Justin Lebarb080b632017-01-25 21:29:48 +00001741 if (!CodeGenOpts.FPDenormalMode.empty())
1742 FuncAttrs.addAttribute("denormal-fp-math", CodeGenOpts.FPDenormalMode);
1743
1744 FuncAttrs.addAttribute("no-trapping-math",
1745 llvm::toStringRef(CodeGenOpts.NoTrappingMath));
1746
Sanjay Patelc81450e2018-04-30 18:19:03 +00001747 // Strict (compliant) code is the default, so only add this attribute to
1748 // indicate that we are trying to workaround a problem case.
1749 if (!CodeGenOpts.StrictFloatCastOverflow)
1750 FuncAttrs.addAttribute("strict-float-cast-overflow", "false");
Sanjay Pateld1754762018-04-27 14:22:48 +00001751
Justin Lebarb080b632017-01-25 21:29:48 +00001752 // TODO: Are these all needed?
1753 // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
1754 FuncAttrs.addAttribute("no-infs-fp-math",
1755 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
1756 FuncAttrs.addAttribute("no-nans-fp-math",
1757 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
1758 FuncAttrs.addAttribute("unsafe-fp-math",
1759 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
1760 FuncAttrs.addAttribute("use-soft-float",
1761 llvm::toStringRef(CodeGenOpts.SoftFloat));
1762 FuncAttrs.addAttribute("stack-protector-buffer-size",
1763 llvm::utostr(CodeGenOpts.SSPBufferSize));
1764 FuncAttrs.addAttribute("no-signed-zeros-fp-math",
1765 llvm::toStringRef(CodeGenOpts.NoSignedZeros));
1766 FuncAttrs.addAttribute(
1767 "correctly-rounded-divide-sqrt-fp-math",
1768 llvm::toStringRef(CodeGenOpts.CorrectlyRoundedDivSqrt));
1769
Alexey Sotkin3858e262018-04-20 08:08:04 +00001770 if (getLangOpts().OpenCL)
1771 FuncAttrs.addAttribute("denorms-are-zero",
1772 llvm::toStringRef(CodeGenOpts.FlushDenorm));
1773
Justin Lebarb080b632017-01-25 21:29:48 +00001774 // TODO: Reciprocal estimate codegen options should apply to instructions?
Craig Topper402b4312017-11-20 17:09:22 +00001775 const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals;
Justin Lebarb080b632017-01-25 21:29:48 +00001776 if (!Recips.empty())
1777 FuncAttrs.addAttribute("reciprocal-estimates",
Erich Keane857ac592017-10-27 18:45:06 +00001778 llvm::join(Recips, ","));
Justin Lebarb080b632017-01-25 21:29:48 +00001779
Craig Topper9a724aa2017-12-11 21:09:19 +00001780 if (!CodeGenOpts.PreferVectorWidth.empty() &&
1781 CodeGenOpts.PreferVectorWidth != "none")
1782 FuncAttrs.addAttribute("prefer-vector-width",
1783 CodeGenOpts.PreferVectorWidth);
1784
Justin Lebarb080b632017-01-25 21:29:48 +00001785 if (CodeGenOpts.StackRealignment)
1786 FuncAttrs.addAttribute("stackrealign");
1787 if (CodeGenOpts.Backchain)
1788 FuncAttrs.addAttribute("backchain");
Chandler Carruth664aa862018-09-04 12:38:00 +00001789
1790 if (CodeGenOpts.SpeculativeLoadHardening)
1791 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
Justin Lebarb080b632017-01-25 21:29:48 +00001792 }
1793
Matt Arsenaulta1cf61b2017-10-06 19:34:40 +00001794 if (getLangOpts().assumeFunctionsAreConvergent()) {
1795 // Conservatively, mark all functions and calls in CUDA and OpenCL as
1796 // convergent (meaning, they may call an intrinsically convergent op, such
1797 // as __syncthreads() / barrier(), and so can't have certain optimizations
1798 // applied around them). LLVM will remove this attribute where it safely
1799 // can.
Justin Lebarb080b632017-01-25 21:29:48 +00001800 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
Matt Arsenaulta1cf61b2017-10-06 19:34:40 +00001801 }
Justin Lebarb080b632017-01-25 21:29:48 +00001802
Matt Arsenaulta1cf61b2017-10-06 19:34:40 +00001803 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
Justin Lebarb080b632017-01-25 21:29:48 +00001804 // Exceptions aren't supported in CUDA device code.
1805 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1806
1807 // Respect -fcuda-flush-denormals-to-zero.
Yaxun Liue1bfbc52018-07-21 02:02:22 +00001808 if (CodeGenOpts.FlushDenorm)
Justin Lebarb080b632017-01-25 21:29:48 +00001809 FuncAttrs.addAttribute("nvptx-f32ftz", "true");
1810 }
1811}
1812
1813void CodeGenModule::AddDefaultFnAttrs(llvm::Function &F) {
1814 llvm::AttrBuilder FuncAttrs;
1815 ConstructDefaultFnAttrList(F.getName(),
1816 F.hasFnAttribute(llvm::Attribute::OptimizeNone),
1817 /* AttrOnCallsite = */ false, FuncAttrs);
Reid Kleckneree4930b2017-05-02 22:07:37 +00001818 F.addAttributes(llvm::AttributeList::FunctionIndex, FuncAttrs);
Justin Lebarb080b632017-01-25 21:29:48 +00001819}
1820
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001821void CodeGenModule::ConstructAttributeList(
1822 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo,
Reid Klecknercdd26792017-04-18 23:50:03 +00001823 llvm::AttributeList &AttrList, unsigned &CallingConv, bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001824 llvm::AttrBuilder FuncAttrs;
1825 llvm::AttrBuilder RetAttrs;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001826
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001827 CallingConv = FI.getEffectiveCallingConvention();
John McCallab26cfa2010-02-05 21:31:56 +00001828 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001829 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001830
Samuel Antao798f11c2015-11-23 22:04:44 +00001831 // If we have information about the function prototype, we can learn
Craig Topper13d759f2018-04-30 22:02:48 +00001832 // attributes from there.
Samuel Antao798f11c2015-11-23 22:04:44 +00001833 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
1834 CalleeInfo.getCalleeFunctionProtoType());
1835
1836 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
1837
Justin Lebarb080b632017-01-25 21:29:48 +00001838 bool HasOptnone = false;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001839 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001840 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001841 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001842 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001843 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001844 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001845 if (TargetDecl->hasAttr<NoReturnAttr>())
1846 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Xinliang David Li4ec36062017-06-13 21:14:07 +00001847 if (TargetDecl->hasAttr<ColdAttr>())
1848 FuncAttrs.addAttribute(llvm::Attribute::Cold);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001849 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1850 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Yaxun Liu7d07ae72016-11-01 18:45:32 +00001851 if (TargetDecl->hasAttr<ConvergentAttr>())
1852 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
Richard Smithdebc59d2013-01-30 05:45:05 +00001853
Chandler Carruth45bbe012017-03-24 09:11:57 +00001854 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
Samuel Antao798f11c2015-11-23 22:04:44 +00001855 AddAttributesFromFunctionProtoType(
Chandler Carruth45bbe012017-03-24 09:11:57 +00001856 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
Richard Smith49af6292013-03-05 08:30:04 +00001857 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1858 // These attributes are not inherited by overloads.
Chandler Carruth45bbe012017-03-24 09:11:57 +00001859 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1860 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001861 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001862 }
1863
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001864 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
Eric Christopherbf005ec2011-08-15 22:38:22 +00001865 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001866 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1867 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001868 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001869 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1870 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001871 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
1872 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
1873 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001874 }
David Majnemer631a90b2015-02-04 07:23:21 +00001875 if (TargetDecl->hasAttr<RestrictAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001876 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Manoj Guptada08f6a2018-07-19 00:44:52 +00001877 if (TargetDecl->hasAttr<ReturnsNonNullAttr>() &&
1878 !CodeGenOpts.NullPointerIsValid)
Hal Finkeld8442b12014-07-12 04:51:04 +00001879 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00001880 if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
1881 FuncAttrs.addAttribute("no_caller_saved_registers");
Oren Ben Simhon220671a2018-03-17 13:31:35 +00001882 if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>())
1883 FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck);
Paul Robinson08556952014-12-11 20:14:04 +00001884
1885 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
George Burgess IVe3763372016-12-22 02:50:20 +00001886 if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
1887 Optional<unsigned> NumElemsParam;
Joel E. Denny81508102018-03-13 14:51:22 +00001888 if (AllocSize->getNumElemsParam().isValid())
1889 NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
1890 FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(),
George Burgess IVe3763372016-12-22 02:50:20 +00001891 NumElemsParam);
1892 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001893 }
1894
Justin Lebarb080b632017-01-25 21:29:48 +00001895 ConstructDefaultFnAttrList(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
Paul Robinson08556952014-12-11 20:14:04 +00001896
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001897 if (CodeGenOpts.EnableSegmentedStacks &&
1898 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001899 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001900
Sriraman Tallam5c651482017-11-07 19:37:51 +00001901 // Add NonLazyBind attribute to function declarations when -fno-plt
1902 // is used.
1903 if (TargetDecl && CodeGenOpts.NoPLT) {
1904 if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
1905 if (!Fn->isDefined() && !AttrOnCallSite) {
1906 FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind);
1907 }
1908 }
1909 }
1910
Alexey Sotkin20f65922018-02-22 11:54:14 +00001911 if (TargetDecl && TargetDecl->hasAttr<OpenCLKernelAttr>()) {
1912 if (getLangOpts().OpenCLVersion <= 120) {
1913 // OpenCL v1.2 Work groups are always uniform
1914 FuncAttrs.addAttribute("uniform-work-group-size", "true");
1915 } else {
1916 // OpenCL v2.0 Work groups may be whether uniform or not.
1917 // '-cl-uniform-work-group-size' compile option gets a hint
1918 // to the compiler that the global work-size be a multiple of
1919 // the work-group size specified to clEnqueueNDRangeKernel
1920 // (i.e. work groups are uniform).
1921 FuncAttrs.addAttribute("uniform-work-group-size",
1922 llvm::toStringRef(CodeGenOpts.UniformWGSize));
1923 }
1924 }
1925
Justin Lebarb080b632017-01-25 21:29:48 +00001926 if (!AttrOnCallSite) {
Akira Hatanaka627586b2018-03-02 01:53:15 +00001927 bool DisableTailCalls = false;
1928
1929 if (CodeGenOpts.DisableTailCalls)
1930 DisableTailCalls = true;
1931 else if (TargetDecl) {
1932 if (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
1933 TargetDecl->hasAttr<AnyX86InterruptAttr>())
1934 DisableTailCalls = true;
1935 else if (CodeGenOpts.NoEscapingBlockTailCalls) {
1936 if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl))
1937 if (!BD->doesNotEscape())
1938 DisableTailCalls = true;
1939 }
1940 }
1941
Justin Lebarb080b632017-01-25 21:29:48 +00001942 FuncAttrs.addAttribute("disable-tail-calls",
1943 llvm::toStringRef(DisableTailCalls));
Erich Keane93e58662018-02-12 17:01:41 +00001944 GetCPUAndFeaturesAttributes(TargetDecl, FuncAttrs);
Bill Wendling985d1c52013-02-15 21:30:01 +00001945 }
1946
Alexey Samsonov153004f2014-09-29 22:08:00 +00001947 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001948
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001949 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001950 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001951 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001952 case ABIArgInfo::Extend:
Alex Bradburye41a5e22018-01-12 20:08:16 +00001953 if (RetAI.isSignExt())
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001954 RetAttrs.addAttribute(llvm::Attribute::SExt);
Alex Bradburye41a5e22018-01-12 20:08:16 +00001955 else
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001956 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001957 LLVM_FALLTHROUGH;
Daniel Dunbar67dace892009-02-03 06:17:37 +00001958 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001959 if (RetAI.getInReg())
1960 RetAttrs.addAttribute(llvm::Attribute::InReg);
1961 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001962 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001963 break;
1964
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001965 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001966 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001967 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001968 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1969 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001970 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001971 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001972
John McCallf26e73d2016-03-11 04:30:43 +00001973 case ABIArgInfo::CoerceAndExpand:
1974 break;
1975
Daniel Dunbard3674e62008-09-11 01:48:57 +00001976 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001977 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001978 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001979
Hal Finkela2347ba2014-07-18 15:52:10 +00001980 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1981 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001982 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001983 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1984 .getQuantity());
Manoj Guptada08f6a2018-07-19 00:44:52 +00001985 else if (getContext().getTargetAddressSpace(PTy) == 0 &&
1986 !CodeGenOpts.NullPointerIsValid)
Hal Finkela2347ba2014-07-18 15:52:10 +00001987 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1988 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001989
John McCall12f23522016-04-04 18:33:08 +00001990 bool hasUsedSRet = false;
Reid Klecknercdd26792017-04-18 23:50:03 +00001991 SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs());
John McCall12f23522016-04-04 18:33:08 +00001992
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001993 // Attach attributes to sret.
1994 if (IRFunctionArgs.hasSRetArg()) {
1995 llvm::AttrBuilder SRETAttrs;
Mandeep Singh Grang2a153102018-07-26 18:07:59 +00001996 if (!RetAI.getSuppressSRet())
1997 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
John McCall12f23522016-04-04 18:33:08 +00001998 hasUsedSRet = true;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001999 if (RetAI.getInReg())
2000 SRETAttrs.addAttribute(llvm::Attribute::InReg);
Reid Klecknercdd26792017-04-18 23:50:03 +00002001 ArgAttrs[IRFunctionArgs.getSRetArgNo()] =
2002 llvm::AttributeSet::get(getLLVMContext(), SRETAttrs);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002003 }
2004
2005 // Attach attributes to inalloca argument.
2006 if (IRFunctionArgs.hasInallocaArg()) {
2007 llvm::AttrBuilder Attrs;
2008 Attrs.addAttribute(llvm::Attribute::InAlloca);
Reid Klecknercdd26792017-04-18 23:50:03 +00002009 ArgAttrs[IRFunctionArgs.getInallocaArgNo()] =
2010 llvm::AttributeSet::get(getLLVMContext(), Attrs);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002011 }
2012
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002013 unsigned ArgNo = 0;
2014 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
2015 E = FI.arg_end();
2016 I != E; ++I, ++ArgNo) {
2017 QualType ParamType = I->type;
2018 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00002019 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00002020
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002021 // Add attribute for padding argument, if necessary.
2022 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Reid Klecknercdd26792017-04-18 23:50:03 +00002023 if (AI.getPaddingInReg()) {
2024 ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2025 llvm::AttributeSet::get(
2026 getLLVMContext(),
2027 llvm::AttrBuilder().addAttribute(llvm::Attribute::InReg));
2028 }
Rafael Espindolafad28de2012-10-24 01:59:00 +00002029 }
2030
John McCall39ec71f2010-03-27 00:47:27 +00002031 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
2032 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00002033 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00002034 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002035 case ABIArgInfo::Extend:
Alex Bradburye41a5e22018-01-12 20:08:16 +00002036 if (AI.isSignExt())
Bill Wendling207f0532012-12-20 19:27:06 +00002037 Attrs.addAttribute(llvm::Attribute::SExt);
Alex Bradburye41a5e22018-01-12 20:08:16 +00002038 else
2039 Attrs.addAttribute(llvm::Attribute::ZExt);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00002040 LLVM_FALLTHROUGH;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002041 case ABIArgInfo::Direct:
Peter Collingbournef7706832014-12-12 23:41:25 +00002042 if (ArgNo == 0 && FI.isChainCall())
2043 Attrs.addAttribute(llvm::Attribute::Nest);
2044 else if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00002045 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002046 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002047
James Y Knight71608572015-08-21 18:19:06 +00002048 case ABIArgInfo::Indirect: {
Rafael Espindola703c47f2012-10-19 05:04:37 +00002049 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00002050 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00002051
Anders Carlsson20759ad2009-09-16 15:53:40 +00002052 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00002053 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002054
John McCall7f416cc2015-09-08 08:05:57 +00002055 CharUnits Align = AI.getIndirectAlign();
James Y Knight71608572015-08-21 18:19:06 +00002056
2057 // In a byval argument, it is important that the required
2058 // alignment of the type is honored, as LLVM might be creating a
2059 // *new* stack object, and needs to know what alignment to give
2060 // it. (Sometimes it can deduce a sensible alignment on its own,
2061 // but not if clang decides it must emit a packed struct, or the
2062 // user specifies increased alignment requirements.)
2063 //
2064 // This is different from indirect *not* byval, where the object
2065 // exists already, and the align attribute is purely
2066 // informative.
John McCall7f416cc2015-09-08 08:05:57 +00002067 assert(!Align.isZero());
James Y Knight71608572015-08-21 18:19:06 +00002068
John McCall7f416cc2015-09-08 08:05:57 +00002069 // For now, only add this when we have a byval argument.
2070 // TODO: be less lazy about updating test cases.
2071 if (AI.getIndirectByVal())
2072 Attrs.addAlignmentAttr(Align.getQuantity());
Bill Wendlinga7912f82012-10-10 07:36:56 +00002073
Daniel Dunbarc2304432009-03-18 19:51:01 +00002074 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00002075 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
2076 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00002077 break;
James Y Knight71608572015-08-21 18:19:06 +00002078 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002079 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002080 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00002081 case ABIArgInfo::CoerceAndExpand:
2082 break;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002083
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002084 case ABIArgInfo::InAlloca:
2085 // inalloca disables readnone and readonly.
2086 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
2087 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002088 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00002089 }
Mike Stump11289f42009-09-09 15:08:12 +00002090
Hal Finkela2347ba2014-07-18 15:52:10 +00002091 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
2092 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00002093 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00002094 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
2095 .getQuantity());
Manoj Guptada08f6a2018-07-19 00:44:52 +00002096 else if (getContext().getTargetAddressSpace(PTy) == 0 &&
2097 !CodeGenOpts.NullPointerIsValid)
Hal Finkela2347ba2014-07-18 15:52:10 +00002098 Attrs.addAttribute(llvm::Attribute::NonNull);
2099 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00002100
John McCall12f23522016-04-04 18:33:08 +00002101 switch (FI.getExtParameterInfo(ArgNo).getABI()) {
2102 case ParameterABI::Ordinary:
2103 break;
2104
2105 case ParameterABI::SwiftIndirectResult: {
2106 // Add 'sret' if we haven't already used it for something, but
2107 // only if the result is void.
2108 if (!hasUsedSRet && RetTy->isVoidType()) {
2109 Attrs.addAttribute(llvm::Attribute::StructRet);
2110 hasUsedSRet = true;
2111 }
2112
2113 // Add 'noalias' in either case.
2114 Attrs.addAttribute(llvm::Attribute::NoAlias);
2115
2116 // Add 'dereferenceable' and 'alignment'.
2117 auto PTy = ParamType->getPointeeType();
2118 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2119 auto info = getContext().getTypeInfoInChars(PTy);
2120 Attrs.addDereferenceableAttr(info.first.getQuantity());
2121 Attrs.addAttribute(llvm::Attribute::getWithAlignment(getLLVMContext(),
2122 info.second.getQuantity()));
2123 }
2124 break;
2125 }
2126
2127 case ParameterABI::SwiftErrorResult:
2128 Attrs.addAttribute(llvm::Attribute::SwiftError);
2129 break;
2130
2131 case ParameterABI::SwiftContext:
2132 Attrs.addAttribute(llvm::Attribute::SwiftSelf);
2133 break;
2134 }
2135
Akira Hatanaka98a49332017-09-22 00:41:05 +00002136 if (FI.getExtParameterInfo(ArgNo).isNoEscape())
2137 Attrs.addAttribute(llvm::Attribute::NoCapture);
2138
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002139 if (Attrs.hasAttributes()) {
2140 unsigned FirstIRArg, NumIRArgs;
2141 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2142 for (unsigned i = 0; i < NumIRArgs; i++)
Reid Klecknercdd26792017-04-18 23:50:03 +00002143 ArgAttrs[FirstIRArg + i] =
2144 llvm::AttributeSet::get(getLLVMContext(), Attrs);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002145 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00002146 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002147 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002148
Reid Klecknercdd26792017-04-18 23:50:03 +00002149 AttrList = llvm::AttributeList::get(
2150 getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs),
2151 llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs);
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00002152}
2153
John McCalla738c252011-03-09 04:27:21 +00002154/// An argument came in as a promoted argument; demote it back to its
2155/// declared type.
2156static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
2157 const VarDecl *var,
2158 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002159 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00002160
2161 // This can happen with promotions that actually don't change the
2162 // underlying type, like the enum promotions.
2163 if (value->getType() == varType) return value;
2164
2165 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
2166 && "unexpected promotion type");
2167
2168 if (isa<llvm::IntegerType>(varType))
2169 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2170
2171 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2172}
2173
Chandler Carruth45bbe012017-03-24 09:11:57 +00002174/// Returns the attribute (either parameter attribute, or function
2175/// attribute), which declares argument ArgNo to be non-null.
2176static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2177 QualType ArgType, unsigned ArgNo) {
2178 // FIXME: __attribute__((nonnull)) can also be applied to:
2179 // - references to pointers, where the pointee is known to be
2180 // nonnull (apparently a Clang extension)
2181 // - transparent unions containing pointers
2182 // In the former case, LLVM IR cannot represent the constraint. In
2183 // the latter case, we have no guarantee that the transparent union
2184 // is in fact passed as a pointer.
2185 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2186 return nullptr;
2187 // First, check attribute on parameter itself.
2188 if (PVD) {
2189 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2190 return ParmNNAttr;
2191 }
2192 // Check function attributes.
2193 if (!FD)
2194 return nullptr;
2195 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
2196 if (NNAttr->isNonNull(ArgNo))
2197 return NNAttr;
2198 }
2199 return nullptr;
2200}
2201
John McCall12f23522016-04-04 18:33:08 +00002202namespace {
2203 struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2204 Address Temp;
2205 Address Arg;
2206 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
2207 void Emit(CodeGenFunction &CGF, Flags flags) override {
2208 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2209 CGF.Builder.CreateStore(errorValue, Arg);
2210 }
2211 };
2212}
2213
Daniel Dunbard931a872009-02-02 22:03:45 +00002214void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
2215 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00002216 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002217 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
2218 // Naked functions don't have prologues.
2219 return;
2220
John McCallcaa19452009-07-28 01:00:58 +00002221 // If this is an implicit-return-zero function, go ahead and
2222 // initialize the return value. TODO: it might be nice to have
2223 // a more general mechanism for this that didn't require synthesized
2224 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00002225 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00002226 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00002227 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00002228 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00002229 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00002230 Builder.CreateStore(Zero, ReturnValue);
2231 }
2232 }
2233
Mike Stump18bb9282009-05-16 07:57:57 +00002234 // FIXME: We no longer need the types from FunctionArgList; lift up and
2235 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00002236
Alexey Samsonov153004f2014-09-29 22:08:00 +00002237 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002238 // Flattened function arguments.
John McCall12f23522016-04-04 18:33:08 +00002239 SmallVector<llvm::Value *, 16> FnArgs;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002240 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
2241 for (auto &Arg : Fn->args()) {
2242 FnArgs.push_back(&Arg);
2243 }
2244 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00002245
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002246 // If we're using inalloca, all the memory arguments are GEPs off of the last
2247 // parameter, which is a pointer to the complete memory area.
John McCall7f416cc2015-09-08 08:05:57 +00002248 Address ArgStruct = Address::invalid();
2249 const llvm::StructLayout *ArgStructLayout = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002250 if (IRFunctionArgs.hasInallocaArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00002251 ArgStructLayout = CGM.getDataLayout().getStructLayout(FI.getArgStruct());
2252 ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()],
2253 FI.getArgStructAlignment());
2254
2255 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002256 }
2257
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002258 // Name the struct return parameter.
2259 if (IRFunctionArgs.hasSRetArg()) {
John McCall12f23522016-04-04 18:33:08 +00002260 auto AI = cast<llvm::Argument>(FnArgs[IRFunctionArgs.getSRetArgNo()]);
Daniel Dunbar613855c2008-09-09 23:27:19 +00002261 AI->setName("agg.result");
Reid Klecknercdd26792017-04-18 23:50:03 +00002262 AI->addAttr(llvm::Attribute::NoAlias);
Daniel Dunbar613855c2008-09-09 23:27:19 +00002263 }
Mike Stump11289f42009-09-09 15:08:12 +00002264
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002265 // Track if we received the parameter as a pointer (indirect, byval, or
2266 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
2267 // into a local alloca for us.
John McCall7f416cc2015-09-08 08:05:57 +00002268 SmallVector<ParamValue, 16> ArgVals;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002269 ArgVals.reserve(Args.size());
2270
Reid Kleckner739756c2013-12-04 19:23:12 +00002271 // Create a pointer value for every parameter declaration. This usually
2272 // entails copying one or more LLVM IR arguments into an alloca. Don't push
2273 // any cleanups or do anything that might unwind. We do that separately, so
2274 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002275 assert(FI.arg_size() == Args.size() &&
2276 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002277 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002278 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002279 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00002280 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00002281 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002282 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002283
John McCalla738c252011-03-09 04:27:21 +00002284 bool isPromoted =
2285 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
Volodymyr Sapsai17ebdb22018-01-22 22:29:24 +00002286 // We are converting from ABIArgInfo type to VarDecl type directly, unless
2287 // the parameter is promoted. In this case we convert to
2288 // CGFunctionInfo::ArgInfo type with subsequent argument demotion.
2289 QualType Ty = isPromoted ? info_it->type : Arg->getType();
2290 assert(hasScalarEvaluationKind(Ty) ==
2291 hasScalarEvaluationKind(Arg->getType()));
John McCalla738c252011-03-09 04:27:21 +00002292
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002293 unsigned FirstIRArg, NumIRArgs;
2294 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002295
Daniel Dunbard3674e62008-09-11 01:48:57 +00002296 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002297 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002298 assert(NumIRArgs == 0);
John McCall7f416cc2015-09-08 08:05:57 +00002299 auto FieldIndex = ArgI.getInAllocaFieldIndex();
2300 CharUnits FieldOffset =
2301 CharUnits::fromQuantity(ArgStructLayout->getElementOffset(FieldIndex));
2302 Address V = Builder.CreateStructGEP(ArgStruct, FieldIndex, FieldOffset,
2303 Arg->getName());
2304 ArgVals.push_back(ParamValue::forIndirect(V));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002305 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002306 }
2307
Daniel Dunbar747865a2009-02-05 09:16:39 +00002308 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002309 assert(NumIRArgs == 1);
John McCall7f416cc2015-09-08 08:05:57 +00002310 Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign());
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002311
John McCall47fb9502013-03-07 21:37:08 +00002312 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002313 // Aggregates and complex variables are accessed by reference. All we
John McCall7f416cc2015-09-08 08:05:57 +00002314 // need to do is realign the value, if requested.
2315 Address V = ParamAddr;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002316 if (ArgI.getIndirectRealign()) {
John McCall7f416cc2015-09-08 08:05:57 +00002317 Address AlignedTemp = CreateMemTemp(Ty, "coerce");
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002318
2319 // Copy from the incoming argument pointer to the temporary with the
2320 // appropriate alignment.
2321 //
2322 // FIXME: We should have a common utility for generating an aggregate
2323 // copy.
Ken Dyck705ba072011-01-19 01:58:38 +00002324 CharUnits Size = getContext().getTypeSizeInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002325 auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity());
2326 Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy);
2327 Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy);
2328 Builder.CreateMemCpy(Dst, Src, SizeVal, false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002329 V = AlignedTemp;
2330 }
John McCall7f416cc2015-09-08 08:05:57 +00002331 ArgVals.push_back(ParamValue::forIndirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002332 } else {
2333 // Load scalar value from indirect argument.
John McCall7f416cc2015-09-08 08:05:57 +00002334 llvm::Value *V =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002335 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc());
John McCalla738c252011-03-09 04:27:21 +00002336
2337 if (isPromoted)
2338 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002339 ArgVals.push_back(ParamValue::forDirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002340 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002341 break;
2342 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002343
2344 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00002345 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00002346
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002347 // If we have the trivial case, handle it with no muss and fuss.
2348 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Volodymyr Sapsai22b00ec2017-12-21 20:52:59 +00002349 ArgI.getCoerceToType() == ConvertType(Ty) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002350 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002351 assert(NumIRArgs == 1);
John McCall12f23522016-04-04 18:33:08 +00002352 llvm::Value *V = FnArgs[FirstIRArg];
2353 auto AI = cast<llvm::Argument>(V);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002354
Hal Finkel48d53e22014-07-19 01:41:07 +00002355 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002356 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
Manoj Guptada08f6a2018-07-19 00:44:52 +00002357 PVD->getFunctionScopeIndex()) &&
2358 !CGM.getCodeGenOpts().NullPointerIsValid)
Reid Klecknercdd26792017-04-18 23:50:03 +00002359 AI->addAttr(llvm::Attribute::NonNull);
Hal Finkel82504f02014-07-11 17:35:21 +00002360
Hal Finkel48d53e22014-07-19 01:41:07 +00002361 QualType OTy = PVD->getOriginalType();
2362 if (const auto *ArrTy =
2363 getContext().getAsConstantArrayType(OTy)) {
2364 // A C99 array parameter declaration with the static keyword also
2365 // indicates dereferenceability, and if the size is constant we can
2366 // use the dereferenceable attribute (which requires the size in
2367 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00002368 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00002369 QualType ETy = ArrTy->getElementType();
2370 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
2371 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
2372 ArrSize) {
2373 llvm::AttrBuilder Attrs;
2374 Attrs.addDereferenceableAttr(
2375 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
Reid Kleckner9d16fa02017-04-19 17:28:52 +00002376 AI->addAttrs(Attrs);
Manoj Guptada08f6a2018-07-19 00:44:52 +00002377 } else if (getContext().getTargetAddressSpace(ETy) == 0 &&
2378 !CGM.getCodeGenOpts().NullPointerIsValid) {
Reid Klecknercdd26792017-04-18 23:50:03 +00002379 AI->addAttr(llvm::Attribute::NonNull);
Hal Finkel48d53e22014-07-19 01:41:07 +00002380 }
2381 }
2382 } else if (const auto *ArrTy =
2383 getContext().getAsVariableArrayType(OTy)) {
2384 // For C99 VLAs with the static keyword, we don't know the size so
2385 // we can't use the dereferenceable attribute, but in addrspace(0)
2386 // we know that it must be nonnull.
2387 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
Manoj Guptada08f6a2018-07-19 00:44:52 +00002388 !getContext().getTargetAddressSpace(ArrTy->getElementType()) &&
2389 !CGM.getCodeGenOpts().NullPointerIsValid)
Reid Klecknercdd26792017-04-18 23:50:03 +00002390 AI->addAttr(llvm::Attribute::NonNull);
Hal Finkel48d53e22014-07-19 01:41:07 +00002391 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00002392
2393 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
2394 if (!AVAttr)
2395 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
2396 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
Reid Kleckner9d16fa02017-04-19 17:28:52 +00002397 if (AVAttr) {
Hal Finkel1b0d24e2014-10-02 21:21:25 +00002398 llvm::Value *AlignmentValue =
2399 EmitScalarExpr(AVAttr->getAlignment());
2400 llvm::ConstantInt *AlignmentCI =
2401 cast<llvm::ConstantInt>(AlignmentValue);
Reid Kleckner9d16fa02017-04-19 17:28:52 +00002402 unsigned Alignment = std::min((unsigned)AlignmentCI->getZExtValue(),
2403 +llvm::Value::MaximumAlignment);
2404 AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(Alignment));
Hal Finkel1b0d24e2014-10-02 21:21:25 +00002405 }
Hal Finkel48d53e22014-07-19 01:41:07 +00002406 }
2407
Bill Wendling507c3512012-10-16 05:23:44 +00002408 if (Arg->getType().isRestrictQualified())
Reid Klecknercdd26792017-04-18 23:50:03 +00002409 AI->addAttr(llvm::Attribute::NoAlias);
John McCall39ec71f2010-03-27 00:47:27 +00002410
John McCall12f23522016-04-04 18:33:08 +00002411 // LLVM expects swifterror parameters to be used in very restricted
2412 // ways. Copy the value into a less-restricted temporary.
2413 if (FI.getExtParameterInfo(ArgNo).getABI()
2414 == ParameterABI::SwiftErrorResult) {
2415 QualType pointeeTy = Ty->getPointeeType();
2416 assert(pointeeTy->isPointerType());
2417 Address temp =
2418 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
2419 Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy));
2420 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
2421 Builder.CreateStore(incomingErrorValue, temp);
2422 V = temp.getPointer();
2423
2424 // Push a cleanup to copy the value back at the end of the function.
2425 // The convention does not guarantee that the value will be written
2426 // back if the function exits with an unwind exception.
2427 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
2428 }
2429
Chris Lattner7369c142011-07-20 06:29:00 +00002430 // Ensure the argument is the correct type.
2431 if (V->getType() != ArgI.getCoerceToType())
2432 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
2433
John McCalla738c252011-03-09 04:27:21 +00002434 if (isPromoted)
2435 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00002436
2437 // Because of merging of function types from multiple decls it is
2438 // possible for the type of an argument to not match the corresponding
2439 // type in the function type. Since we are codegening the callee
2440 // in here, add a cast to the argument type.
2441 llvm::Type *LTy = ConvertType(Arg->getType());
2442 if (V->getType() != LTy)
2443 V = Builder.CreateBitCast(V, LTy);
2444
John McCall7f416cc2015-09-08 08:05:57 +00002445 ArgVals.push_back(ParamValue::forDirect(V));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002446 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00002447 }
Mike Stump11289f42009-09-09 15:08:12 +00002448
Volodymyr Sapsai22b00ec2017-12-21 20:52:59 +00002449 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
2450 Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002451
John McCall7f416cc2015-09-08 08:05:57 +00002452 // Pointer to store into.
2453 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002454
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002455 // Fast-isel and the optimizer generally like scalar values better than
2456 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002457 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002458 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
2459 STy->getNumElements() > 1) {
John McCall7f416cc2015-09-08 08:05:57 +00002460 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002461 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
John McCall7f416cc2015-09-08 08:05:57 +00002462 llvm::Type *DstTy = Ptr.getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002463 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002464
John McCall7f416cc2015-09-08 08:05:57 +00002465 Address AddrToStoreInto = Address::invalid();
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002466 if (SrcSize <= DstSize) {
Yaxun Liue9e5c4f2017-06-29 18:47:45 +00002467 AddrToStoreInto = Builder.CreateElementBitCast(Ptr, STy);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002468 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002469 AddrToStoreInto =
2470 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
Chris Lattner15ec3612010-06-29 00:06:42 +00002471 }
John McCall7f416cc2015-09-08 08:05:57 +00002472
2473 assert(STy->getNumElements() == NumIRArgs);
2474 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2475 auto AI = FnArgs[FirstIRArg + i];
2476 AI->setName(Arg->getName() + ".coerce" + Twine(i));
2477 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
2478 Address EltPtr =
2479 Builder.CreateStructGEP(AddrToStoreInto, i, Offset);
2480 Builder.CreateStore(AI, EltPtr);
2481 }
2482
2483 if (SrcSize > DstSize) {
2484 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
2485 }
2486
Chris Lattner15ec3612010-06-29 00:06:42 +00002487 } else {
2488 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002489 assert(NumIRArgs == 1);
2490 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00002491 AI->setName(Arg->getName() + ".coerce");
John McCall7f416cc2015-09-08 08:05:57 +00002492 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00002493 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002494
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002495 // Match to what EmitParmDecl is expecting for this type.
Volodymyr Sapsai22b00ec2017-12-21 20:52:59 +00002496 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002497 llvm::Value *V =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002498 EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc());
John McCalla738c252011-03-09 04:27:21 +00002499 if (isPromoted)
2500 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002501 ArgVals.push_back(ParamValue::forDirect(V));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002502 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002503 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00002504 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002505 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002506 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002507
John McCallf26e73d2016-03-11 04:30:43 +00002508 case ABIArgInfo::CoerceAndExpand: {
2509 // Reconstruct into a temporary.
2510 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2511 ArgVals.push_back(ParamValue::forIndirect(alloca));
2512
2513 auto coercionType = ArgI.getCoerceAndExpandType();
2514 alloca = Builder.CreateElementBitCast(alloca, coercionType);
2515 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2516
2517 unsigned argIndex = FirstIRArg;
2518 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2519 llvm::Type *eltType = coercionType->getElementType(i);
2520 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
2521 continue;
2522
2523 auto eltAddr = Builder.CreateStructGEP(alloca, i, layout);
2524 auto elt = FnArgs[argIndex++];
2525 Builder.CreateStore(elt, eltAddr);
2526 }
2527 assert(argIndex == FirstIRArg + NumIRArgs);
2528 break;
2529 }
2530
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002531 case ABIArgInfo::Expand: {
2532 // If this structure was expanded into multiple arguments then
2533 // we need to create a temporary and reconstruct it from the
2534 // arguments.
John McCall7f416cc2015-09-08 08:05:57 +00002535 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2536 LValue LV = MakeAddrLValue(Alloca, Ty);
2537 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002538
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002539 auto FnArgIter = FnArgs.begin() + FirstIRArg;
2540 ExpandTypeFromArgs(Ty, LV, FnArgIter);
2541 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
2542 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2543 auto AI = FnArgs[FirstIRArg + i];
2544 AI->setName(Arg->getName() + "." + Twine(i));
2545 }
2546 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002547 }
2548
2549 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002550 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002551 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002552 if (!hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002553 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002554 } else {
2555 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002556 ArgVals.push_back(ParamValue::forDirect(U));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002557 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002558 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002559 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002560 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002561
Reid Kleckner739756c2013-12-04 19:23:12 +00002562 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2563 for (int I = Args.size() - 1; I >= 0; --I)
John McCall7f416cc2015-09-08 08:05:57 +00002564 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002565 } else {
2566 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall7f416cc2015-09-08 08:05:57 +00002567 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002568 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002569}
2570
John McCallffa2c1a2012-01-29 07:46:59 +00002571static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2572 while (insn->use_empty()) {
2573 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2574 if (!bitcast) return;
2575
2576 // This is "safe" because we would have used a ConstantExpr otherwise.
2577 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2578 bitcast->eraseFromParent();
2579 }
2580}
2581
John McCall31168b02011-06-15 23:02:42 +00002582/// Try to emit a fused autorelease of a return result.
2583static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2584 llvm::Value *result) {
2585 // We must be immediately followed the cast.
2586 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002587 if (BB->empty()) return nullptr;
2588 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002589
Chris Lattner2192fe52011-07-18 04:24:23 +00002590 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00002591
2592 // result is in a BasicBlock and is therefore an Instruction.
2593 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2594
Justin Bogner882f8612016-08-18 21:46:54 +00002595 SmallVector<llvm::Instruction *, 4> InstsToKill;
John McCall31168b02011-06-15 23:02:42 +00002596
2597 // Look for:
2598 // %generator = bitcast %type1* %generator2 to %type2*
2599 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2600 // We would have emitted this as a constant if the operand weren't
2601 // an Instruction.
2602 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2603
2604 // Require the generator to be immediately followed by the cast.
2605 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002606 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002607
Justin Bogner882f8612016-08-18 21:46:54 +00002608 InstsToKill.push_back(bitcast);
John McCall31168b02011-06-15 23:02:42 +00002609 }
2610
2611 // Look for:
2612 // %generator = call i8* @objc_retain(i8* %originalResult)
2613 // or
2614 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2615 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002616 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002617
2618 bool doRetainAutorelease;
2619
John McCallb04ecb72015-10-21 18:06:43 +00002620 if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) {
John McCall31168b02011-06-15 23:02:42 +00002621 doRetainAutorelease = true;
John McCallb04ecb72015-10-21 18:06:43 +00002622 } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints()
John McCall31168b02011-06-15 23:02:42 +00002623 .objc_retainAutoreleasedReturnValue) {
2624 doRetainAutorelease = false;
2625
John McCallcfa4e9b2012-09-07 23:30:50 +00002626 // If we emitted an assembly marker for this call (and the
2627 // ARCEntrypoints field should have been set if so), go looking
2628 // for that call. If we can't find it, we can't do this
2629 // optimization. But it should always be the immediately previous
2630 // instruction, unless we needed bitcasts around the call.
John McCallb04ecb72015-10-21 18:06:43 +00002631 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
John McCallcfa4e9b2012-09-07 23:30:50 +00002632 llvm::Instruction *prev = call->getPrevNode();
2633 assert(prev);
2634 if (isa<llvm::BitCastInst>(prev)) {
2635 prev = prev->getPrevNode();
2636 assert(prev);
2637 }
2638 assert(isa<llvm::CallInst>(prev));
2639 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
John McCallb04ecb72015-10-21 18:06:43 +00002640 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
Justin Bogner882f8612016-08-18 21:46:54 +00002641 InstsToKill.push_back(prev);
John McCallcfa4e9b2012-09-07 23:30:50 +00002642 }
John McCall31168b02011-06-15 23:02:42 +00002643 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002644 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002645 }
2646
2647 result = call->getArgOperand(0);
Justin Bogner882f8612016-08-18 21:46:54 +00002648 InstsToKill.push_back(call);
John McCall31168b02011-06-15 23:02:42 +00002649
2650 // Keep killing bitcasts, for sanity. Note that we no longer care
2651 // about precise ordering as long as there's exactly one use.
2652 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2653 if (!bitcast->hasOneUse()) break;
Justin Bogner882f8612016-08-18 21:46:54 +00002654 InstsToKill.push_back(bitcast);
John McCall31168b02011-06-15 23:02:42 +00002655 result = bitcast->getOperand(0);
2656 }
2657
2658 // Delete all the unnecessary instructions, from latest to earliest.
Justin Bogner882f8612016-08-18 21:46:54 +00002659 for (auto *I : InstsToKill)
Saleem Abdulrasoolbe25c482016-08-18 21:40:06 +00002660 I->eraseFromParent();
John McCall31168b02011-06-15 23:02:42 +00002661
2662 // Do the fused retain/autorelease if we were asked to.
2663 if (doRetainAutorelease)
2664 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2665
2666 // Cast back to the result type.
2667 return CGF.Builder.CreateBitCast(result, resultType);
2668}
2669
John McCallffa2c1a2012-01-29 07:46:59 +00002670/// If this is a +1 of the value of an immutable 'self', remove it.
2671static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2672 llvm::Value *result) {
2673 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002674 const ObjCMethodDecl *method =
2675 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002676 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002677 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002678 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002679
2680 // Look for a retain call.
2681 llvm::CallInst *retainCall =
2682 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2683 if (!retainCall ||
John McCallb04ecb72015-10-21 18:06:43 +00002684 retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002685 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002686
2687 // Look for an ordinary load of 'self'.
2688 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2689 llvm::LoadInst *load =
2690 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
Fangrui Song6907ce22018-07-30 19:24:48 +00002691 if (!load || load->isAtomic() || load->isVolatile() ||
John McCall7f416cc2015-09-08 08:05:57 +00002692 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
Craig Topper8a13c412014-05-21 05:09:00 +00002693 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002694
2695 // Okay! Burn it all down. This relies for correctness on the
2696 // assumption that the retain is emitted as part of the return and
2697 // that thereafter everything is used "linearly".
2698 llvm::Type *resultType = result->getType();
2699 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2700 assert(retainCall->use_empty());
2701 retainCall->eraseFromParent();
2702 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2703
2704 return CGF.Builder.CreateBitCast(load, resultType);
2705}
2706
John McCall31168b02011-06-15 23:02:42 +00002707/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002708///
2709/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002710static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2711 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002712 // If we're returning 'self', kill the initial retain. This is a
2713 // heuristic attempt to "encourage correctness" in the really unfortunate
2714 // case where we have a return of self during a dealloc and we desperately
2715 // need to avoid the possible autorelease.
2716 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2717 return self;
2718
John McCall31168b02011-06-15 23:02:42 +00002719 // At -O0, try to emit a fused retain/autorelease.
2720 if (CGF.shouldUseFusedARCCalls())
2721 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2722 return fused;
2723
2724 return CGF.EmitARCAutoreleaseReturnValue(result);
2725}
2726
John McCall6e1c0122012-01-29 02:35:02 +00002727/// Heuristically search for a dominating store to the return-value slot.
2728static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002729 // Check if a User is a store which pointerOperand is the ReturnValue.
2730 // We are looking for stores to the ReturnValue, not for stores of the
2731 // ReturnValue to some other location.
2732 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
2733 auto *SI = dyn_cast<llvm::StoreInst>(U);
2734 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
2735 return nullptr;
2736 // These aren't actually possible for non-coerced returns, and we
2737 // only care about non-coerced returns on this code path.
2738 assert(!SI->isAtomic() && !SI->isVolatile());
2739 return SI;
2740 };
John McCall6e1c0122012-01-29 02:35:02 +00002741 // If there are multiple uses of the return-value slot, just check
2742 // for something immediately preceding the IP. Sometimes this can
2743 // happen with how we generate implicit-returns; it can also happen
2744 // with noreturn cleanups.
John McCall7f416cc2015-09-08 08:05:57 +00002745 if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
John McCall6e1c0122012-01-29 02:35:02 +00002746 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002747 if (IP->empty()) return nullptr;
David Majnemerdc012fa2015-04-22 21:38:15 +00002748 llvm::Instruction *I = &IP->back();
2749
2750 // Skip lifetime markers
2751 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
2752 IE = IP->rend();
2753 II != IE; ++II) {
2754 if (llvm::IntrinsicInst *Intrinsic =
2755 dyn_cast<llvm::IntrinsicInst>(&*II)) {
2756 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
2757 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
2758 ++II;
Alexey Samsonov10544202015-06-12 21:05:32 +00002759 if (II == IE)
2760 break;
2761 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
2762 continue;
David Majnemerdc012fa2015-04-22 21:38:15 +00002763 }
2764 }
2765 I = &*II;
2766 break;
2767 }
2768
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002769 return GetStoreIfValid(I);
John McCall6e1c0122012-01-29 02:35:02 +00002770 }
2771
2772 llvm::StoreInst *store =
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002773 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002774 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002775
John McCall6e1c0122012-01-29 02:35:02 +00002776 // Now do a first-and-dirty dominance check: just walk up the
2777 // single-predecessors chain from the current insertion point.
2778 llvm::BasicBlock *StoreBB = store->getParent();
2779 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2780 while (IP != StoreBB) {
2781 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002782 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002783 }
2784
2785 // Okay, the store's basic block dominates the insertion point; we
2786 // can do our thing.
2787 return store;
2788}
2789
Adrian Prantl3be10542013-05-02 17:30:20 +00002790void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002791 bool EmitRetDbgLoc,
2792 SourceLocation EndLoc) {
Vedant Kumar09b5bfd2017-12-21 00:10:25 +00002793 if (FI.isNoReturn()) {
2794 // Noreturn functions don't return.
2795 EmitUnreachable(EndLoc);
2796 return;
2797 }
2798
Hans Wennborgd71907d2014-09-04 22:16:33 +00002799 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2800 // Naked functions don't have epilogues.
2801 Builder.CreateUnreachable();
2802 return;
2803 }
2804
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002805 // Functions with no result always return void.
John McCall7f416cc2015-09-08 08:05:57 +00002806 if (!ReturnValue.isValid()) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002807 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002808 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002809 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002810
Dan Gohman481e40c2010-07-20 20:13:52 +00002811 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002812 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002813 QualType RetTy = FI.getReturnType();
2814 const ABIArgInfo &RetAI = FI.getReturnInfo();
2815
2816 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002817 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002818 // Aggregrates get evaluated directly into the destination. Sometimes we
2819 // need to return the sret value in a register, though.
2820 assert(hasAggregateEvaluationKind(RetTy));
2821 if (RetAI.getInAllocaSRet()) {
2822 llvm::Function::arg_iterator EI = CurFn->arg_end();
2823 --EI;
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002824 llvm::Value *ArgStruct = &*EI;
David Blaikie2e804282015-04-05 22:47:07 +00002825 llvm::Value *SRet = Builder.CreateStructGEP(
2826 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
John McCall7f416cc2015-09-08 08:05:57 +00002827 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret");
Reid Klecknerfab1e892014-02-25 00:59:14 +00002828 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002829 break;
2830
Daniel Dunbar03816342010-08-21 02:24:36 +00002831 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002832 auto AI = CurFn->arg_begin();
2833 if (RetAI.isSRetAfterThis())
2834 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002835 switch (getEvaluationKind(RetTy)) {
2836 case TEK_Complex: {
2837 ComplexPairTy RT =
John McCall7f416cc2015-09-08 08:05:57 +00002838 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002839 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002840 /*isInit*/ true);
2841 break;
2842 }
2843 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002844 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002845 break;
2846 case TEK_Scalar:
2847 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002848 MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002849 /*isInit*/ true);
2850 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002851 }
2852 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002853 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002854
2855 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002856 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002857 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2858 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002859 // The internal return value temp always will have pointer-to-return-type
2860 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002861
John McCall6e1c0122012-01-29 02:35:02 +00002862 // If there is a dominating store to ReturnValue, we can elide
2863 // the load, zap the store, and usually zap the alloca.
David Majnemerdc012fa2015-04-22 21:38:15 +00002864 if (llvm::StoreInst *SI =
2865 findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002866 // Reuse the debug location from the store unless there is
2867 // cleanup code to be emitted between the store and return
2868 // instruction.
2869 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002870 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002871 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002872 RV = SI->getValueOperand();
2873 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002874
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002875 // If that was the only use of the return value, nuke it as well now.
John McCall7f416cc2015-09-08 08:05:57 +00002876 auto returnValueInst = ReturnValue.getPointer();
2877 if (returnValueInst->use_empty()) {
2878 if (auto alloca = dyn_cast<llvm::AllocaInst>(returnValueInst)) {
2879 alloca->eraseFromParent();
2880 ReturnValue = Address::invalid();
2881 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002882 }
John McCall6e1c0122012-01-29 02:35:02 +00002883
2884 // Otherwise, we have to do a simple load.
2885 } else {
2886 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002887 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002888 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002889 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00002890 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002891
John McCall7f416cc2015-09-08 08:05:57 +00002892 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002893 }
John McCall31168b02011-06-15 23:02:42 +00002894
2895 // In ARC, end functions that return a retainable type with a call
2896 // to objc_autoreleaseReturnValue.
2897 if (AutoreleaseResult) {
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002898#ifndef NDEBUG
2899 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
2900 // been stripped of the typedefs, so we cannot use RetTy here. Get the
2901 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
2902 // CurCodeDecl or BlockInfo.
2903 QualType RT;
2904
2905 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
2906 RT = FD->getReturnType();
2907 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
2908 RT = MD->getReturnType();
2909 else if (isa<BlockDecl>(CurCodeDecl))
2910 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
2911 else
2912 llvm_unreachable("Unexpected function/method type");
2913
David Blaikiebbafb8a2012-03-11 07:00:24 +00002914 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002915 !FI.isReturnsRetained() &&
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002916 RT->isObjCRetainableType());
2917#endif
John McCall31168b02011-06-15 23:02:42 +00002918 RV = emitAutoreleaseOfResult(*this, RV);
2919 }
2920
Chris Lattner726b3d02010-06-26 23:13:19 +00002921 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002922
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002923 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002924 break;
2925
John McCallf26e73d2016-03-11 04:30:43 +00002926 case ABIArgInfo::CoerceAndExpand: {
2927 auto coercionType = RetAI.getCoerceAndExpandType();
2928 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2929
2930 // Load all of the coerced elements out into results.
2931 llvm::SmallVector<llvm::Value*, 4> results;
2932 Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
2933 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2934 auto coercedEltType = coercionType->getElementType(i);
2935 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
2936 continue;
2937
2938 auto eltAddr = Builder.CreateStructGEP(addr, i, layout);
2939 auto elt = Builder.CreateLoad(eltAddr);
2940 results.push_back(elt);
2941 }
2942
2943 // If we have one result, it's the single direct result type.
2944 if (results.size() == 1) {
2945 RV = results[0];
2946
2947 // Otherwise, we need to make a first-class aggregate.
2948 } else {
2949 // Construct a return type that lacks padding elements.
2950 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
2951
2952 RV = llvm::UndefValue::get(returnType);
2953 for (unsigned i = 0, e = results.size(); i != e; ++i) {
2954 RV = Builder.CreateInsertValue(RV, results[i], i);
2955 }
2956 }
2957 break;
2958 }
2959
Chris Lattner726b3d02010-06-26 23:13:19 +00002960 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002961 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002962 }
2963
Alexey Samsonovde443c52014-08-13 00:26:40 +00002964 llvm::Instruction *Ret;
2965 if (RV) {
Vedant Kumarc34d3432017-06-23 21:32:38 +00002966 EmitReturnValueCheck(RV);
Alexey Samsonovde443c52014-08-13 00:26:40 +00002967 Ret = Builder.CreateRet(RV);
2968 } else {
2969 Ret = Builder.CreateRetVoid();
2970 }
2971
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00002972 if (RetDbgLoc)
Benjamin Kramer03278662015-02-07 13:15:54 +00002973 Ret->setDebugLoc(std::move(RetDbgLoc));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002974}
2975
Vedant Kumarc34d3432017-06-23 21:32:38 +00002976void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) {
Vedant Kumar42c17ec2017-03-14 01:56:34 +00002977 // A current decl may not be available when emitting vtable thunks.
2978 if (!CurCodeDecl)
2979 return;
2980
2981 ReturnsNonNullAttr *RetNNAttr = nullptr;
2982 if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
2983 RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
2984
2985 if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
2986 return;
2987
2988 // Prefer the returns_nonnull attribute if it's present.
2989 SourceLocation AttrLoc;
2990 SanitizerMask CheckKind;
Vedant Kumar2b9f48a2017-03-14 16:48:29 +00002991 SanitizerHandler Handler;
Vedant Kumar42c17ec2017-03-14 01:56:34 +00002992 if (RetNNAttr) {
2993 assert(!requiresReturnValueNullabilityCheck() &&
2994 "Cannot check nullability and the nonnull attribute");
2995 AttrLoc = RetNNAttr->getLocation();
2996 CheckKind = SanitizerKind::ReturnsNonnullAttribute;
Vedant Kumar2b9f48a2017-03-14 16:48:29 +00002997 Handler = SanitizerHandler::NonnullReturn;
Vedant Kumar42c17ec2017-03-14 01:56:34 +00002998 } else {
Vedant Kumar42c17ec2017-03-14 01:56:34 +00002999 if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl))
3000 if (auto *TSI = DD->getTypeSourceInfo())
3001 if (auto FTL = TSI->getTypeLoc().castAs<FunctionTypeLoc>())
3002 AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
3003 CheckKind = SanitizerKind::NullabilityReturn;
Vedant Kumar2b9f48a2017-03-14 16:48:29 +00003004 Handler = SanitizerHandler::NullabilityReturn;
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003005 }
3006
3007 SanitizerScope SanScope(this);
3008
Vedant Kumarc34d3432017-06-23 21:32:38 +00003009 // Make sure the "return" source location is valid. If we're checking a
3010 // nullability annotation, make sure the preconditions for the check are met.
3011 llvm::BasicBlock *Check = createBasicBlock("nullcheck");
3012 llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck");
3013 llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load");
3014 llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr);
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003015 if (requiresReturnValueNullabilityCheck())
Vedant Kumarc34d3432017-06-23 21:32:38 +00003016 CanNullCheck =
3017 Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition);
3018 Builder.CreateCondBr(CanNullCheck, Check, NoCheck);
3019 EmitBlock(Check);
3020
3021 // Now do the null check.
3022 llvm::Value *Cond = Builder.CreateIsNotNull(RV);
3023 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)};
3024 llvm::Value *DynamicData[] = {SLocPtr};
3025 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData);
3026
3027 EmitBlock(NoCheck);
3028
3029#ifndef NDEBUG
3030 // The return location should not be used after the check has been emitted.
3031 ReturnLocation = Address::invalid();
3032#endif
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003033}
3034
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003035static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
3036 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
3037 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
3038}
3039
John McCall7f416cc2015-09-08 08:05:57 +00003040static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
3041 QualType Ty) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003042 // FIXME: Generate IR in one pass, rather than going back and fixing up these
3043 // placeholders.
3044 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
Peter Collingbourneb367c562016-11-28 22:30:21 +00003045 llvm::Type *IRPtrTy = IRTy->getPointerTo();
3046 llvm::Value *Placeholder = llvm::UndefValue::get(IRPtrTy->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00003047
3048 // FIXME: When we generate this IR in one pass, we shouldn't need
3049 // this win32-specific alignment hack.
3050 CharUnits Align = CharUnits::fromQuantity(4);
Peter Collingbourneb367c562016-11-28 22:30:21 +00003051 Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
John McCall7f416cc2015-09-08 08:05:57 +00003052
3053 return AggValueSlot::forAddr(Address(Placeholder, Align),
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003054 Ty.getQualifiers(),
3055 AggValueSlot::IsNotDestructed,
3056 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00003057 AggValueSlot::IsNotAliased,
3058 AggValueSlot::DoesNotOverlap);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003059}
3060
John McCall32ea9692011-03-11 20:59:21 +00003061void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003062 const VarDecl *param,
3063 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00003064 // StartFunction converted the ABI-lowered parameter(s) into a
3065 // local alloca. We need to turn that into an r-value suitable
3066 // for EmitCall.
John McCall7f416cc2015-09-08 08:05:57 +00003067 Address local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00003068
John McCall32ea9692011-03-11 20:59:21 +00003069 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003070
Reid Klecknerab2090d2014-07-26 01:34:32 +00003071 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
3072 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003073
John McCall811b2912016-11-18 01:08:24 +00003074 // GetAddrOfLocalVar returns a pointer-to-pointer for references,
3075 // but the argument needs to be the original pointer.
3076 if (type->isReferenceType()) {
3077 args.add(RValue::get(Builder.CreateLoad(local)), type);
3078
3079 // In ARC, move out of consumed arguments so that the release cleanup
3080 // entered by StartFunction doesn't cause an over-release. This isn't
3081 // optimal -O0 code generation, but it should get cleaned up when
3082 // optimization is enabled. This also assumes that delegate calls are
3083 // performed exactly once for a set of arguments, but that should be safe.
3084 } else if (getLangOpts().ObjCAutoRefCount &&
3085 param->hasAttr<NSConsumedAttr>() &&
3086 type->isObjCRetainableType()) {
3087 llvm::Value *ptr = Builder.CreateLoad(local);
3088 auto null =
3089 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
3090 Builder.CreateStore(null, local);
3091 args.add(RValue::get(ptr), type);
3092
Richard Smithd62d4982016-06-14 01:13:21 +00003093 // For the most part, we just need to load the alloca, except that
3094 // aggregate r-values are actually pointers to temporaries.
John McCall811b2912016-11-18 01:08:24 +00003095 } else {
Richard Smithd62d4982016-06-14 01:13:21 +00003096 args.add(convertTempToRValue(local, type, loc), type);
John McCall811b2912016-11-18 01:08:24 +00003097 }
Akira Hatanakaccda3d22018-04-27 06:57:00 +00003098
3099 // Deactivate the cleanup for the callee-destructed param that was pushed.
3100 if (hasAggregateEvaluationKind(type) && !CurFuncIsThunk &&
Akira Hatanaka85282972018-05-15 21:00:30 +00003101 type->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee() &&
3102 type.isDestructedType()) {
Akira Hatanakaccda3d22018-04-27 06:57:00 +00003103 EHScopeStack::stable_iterator cleanup =
3104 CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param));
3105 assert(cleanup.isValid() &&
3106 "cleanup for callee-destructed param not recorded");
3107 // This unreachable is a temporary marker which will be removed later.
3108 llvm::Instruction *isActive = Builder.CreateUnreachable();
3109 args.addArgCleanupDeactivation(cleanup, isActive);
3110 }
John McCall23f66262010-05-26 22:34:26 +00003111}
3112
John McCall31168b02011-06-15 23:02:42 +00003113static bool isProvablyNull(llvm::Value *addr) {
3114 return isa<llvm::ConstantPointerNull>(addr);
3115}
3116
John McCall31168b02011-06-15 23:02:42 +00003117/// Emit the actual writing-back of a writeback.
3118static void emitWriteback(CodeGenFunction &CGF,
3119 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00003120 const LValue &srcLV = writeback.Source;
John McCall7f416cc2015-09-08 08:05:57 +00003121 Address srcAddr = srcLV.getAddress();
3122 assert(!isProvablyNull(srcAddr.getPointer()) &&
John McCall31168b02011-06-15 23:02:42 +00003123 "shouldn't have writeback for provably null argument");
3124
Craig Topper8a13c412014-05-21 05:09:00 +00003125 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00003126
3127 // If the argument wasn't provably non-null, we need to null check
3128 // before doing the store.
Nuno Lopes9211cee2017-09-09 18:25:36 +00003129 bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
3130 CGF.CGM.getDataLayout());
John McCall31168b02011-06-15 23:02:42 +00003131 if (!provablyNonNull) {
3132 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
3133 contBB = CGF.createBasicBlock("icr.done");
3134
John McCall7f416cc2015-09-08 08:05:57 +00003135 llvm::Value *isNull =
3136 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00003137 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
3138 CGF.EmitBlock(writebackBB);
3139 }
3140
3141 // Load the value to writeback.
3142 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
3143
3144 // Cast it back, in case we're writing an id to a Foo* or something.
John McCall7f416cc2015-09-08 08:05:57 +00003145 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
3146 "icr.writeback-cast");
Fangrui Song6907ce22018-07-30 19:24:48 +00003147
John McCall31168b02011-06-15 23:02:42 +00003148 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00003149
3150 // If we have a "to use" value, it's something we need to emit a use
3151 // of. This has to be carefully threaded in: if it's done after the
3152 // release it's potentially undefined behavior (and the optimizer
3153 // will ignore it), and if it happens before the retain then the
3154 // optimizer could move the release there.
3155 if (writeback.ToUse) {
3156 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
3157
3158 // Retain the new value. No need to block-copy here: the block's
3159 // being passed up the stack.
3160 value = CGF.EmitARCRetainNonBlock(value);
3161
3162 // Emit the intrinsic use here.
3163 CGF.EmitARCIntrinsicUse(writeback.ToUse);
3164
3165 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00003166 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00003167
3168 // Put the new value in place (primitively).
3169 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
3170
3171 // Release the old value.
3172 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
3173
3174 // Otherwise, we can just do a normal lvalue store.
3175 } else {
3176 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
3177 }
John McCall31168b02011-06-15 23:02:42 +00003178
3179 // Jump to the continuation block.
3180 if (!provablyNonNull)
3181 CGF.EmitBlock(contBB);
3182}
3183
3184static void emitWritebacks(CodeGenFunction &CGF,
3185 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00003186 for (const auto &I : args.writebacks())
3187 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00003188}
3189
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003190static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
3191 const CallArgList &CallArgs) {
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003192 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
3193 CallArgs.getCleanupsToDeactivate();
3194 // Iterate in reverse to increase the likelihood of popping the cleanup.
Pete Cooper57d3f142015-07-30 17:22:52 +00003195 for (const auto &I : llvm::reverse(Cleanups)) {
3196 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
3197 I.IsActiveIP->eraseFromParent();
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003198 }
3199}
3200
John McCalleff18842013-03-23 02:35:54 +00003201static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
3202 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
3203 if (uop->getOpcode() == UO_AddrOf)
3204 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00003205 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00003206}
3207
John McCall31168b02011-06-15 23:02:42 +00003208/// Emit an argument that's being passed call-by-writeback. That is,
John McCall7f416cc2015-09-08 08:05:57 +00003209/// we are passing the address of an __autoreleased temporary; it
3210/// might be copy-initialized with the current value of the given
3211/// address, but it will definitely be copied out of after the call.
John McCall31168b02011-06-15 23:02:42 +00003212static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
3213 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00003214 LValue srcLV;
3215
3216 // Make an optimistic effort to emit the address as an l-value.
Eric Christopher2c4555a2015-06-19 01:52:53 +00003217 // This can fail if the argument expression is more complicated.
John McCalleff18842013-03-23 02:35:54 +00003218 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
3219 srcLV = CGF.EmitLValue(lvExpr);
3220
3221 // Otherwise, just emit it as a scalar.
3222 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003223 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
John McCalleff18842013-03-23 02:35:54 +00003224
3225 QualType srcAddrType =
3226 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003227 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
John McCalleff18842013-03-23 02:35:54 +00003228 }
John McCall7f416cc2015-09-08 08:05:57 +00003229 Address srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00003230
3231 // The dest and src types don't necessarily match in LLVM terms
3232 // because of the crazy ObjC compatibility rules.
3233
Chris Lattner2192fe52011-07-18 04:24:23 +00003234 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00003235 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
3236
3237 // If the address is a constant null, just pass the appropriate null.
John McCall7f416cc2015-09-08 08:05:57 +00003238 if (isProvablyNull(srcAddr.getPointer())) {
John McCall31168b02011-06-15 23:02:42 +00003239 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
3240 CRE->getType());
3241 return;
3242 }
3243
John McCall31168b02011-06-15 23:02:42 +00003244 // Create the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003245 Address temp = CGF.CreateTempAlloca(destType->getElementType(),
3246 CGF.getPointerAlign(),
3247 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003248 // Loading an l-value can introduce a cleanup if the l-value is __weak,
3249 // and that cleanup will be conditional if we can't prove that the l-value
3250 // isn't null, so we need to register a dominating point so that the cleanups
3251 // system will make valid IR.
3252 CodeGenFunction::ConditionalEvaluation condEval(CGF);
Fangrui Song6907ce22018-07-30 19:24:48 +00003253
John McCall31168b02011-06-15 23:02:42 +00003254 // Zero-initialize it if we're not doing a copy-initialization.
3255 bool shouldCopy = CRE->shouldCopy();
3256 if (!shouldCopy) {
3257 llvm::Value *null =
3258 llvm::ConstantPointerNull::get(
3259 cast<llvm::PointerType>(destType->getElementType()));
3260 CGF.Builder.CreateStore(null, temp);
3261 }
Craig Topper8a13c412014-05-21 05:09:00 +00003262
3263 llvm::BasicBlock *contBB = nullptr;
3264 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00003265
3266 // If the address is *not* known to be non-null, we need to switch.
3267 llvm::Value *finalArgument;
3268
Nuno Lopes9211cee2017-09-09 18:25:36 +00003269 bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
3270 CGF.CGM.getDataLayout());
John McCall31168b02011-06-15 23:02:42 +00003271 if (provablyNonNull) {
John McCall7f416cc2015-09-08 08:05:57 +00003272 finalArgument = temp.getPointer();
John McCall31168b02011-06-15 23:02:42 +00003273 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003274 llvm::Value *isNull =
3275 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00003276
Fangrui Song6907ce22018-07-30 19:24:48 +00003277 finalArgument = CGF.Builder.CreateSelect(isNull,
John McCall31168b02011-06-15 23:02:42 +00003278 llvm::ConstantPointerNull::get(destType),
John McCall7f416cc2015-09-08 08:05:57 +00003279 temp.getPointer(), "icr.argument");
John McCall31168b02011-06-15 23:02:42 +00003280
3281 // If we need to copy, then the load has to be conditional, which
3282 // means we need control flow.
3283 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00003284 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00003285 contBB = CGF.createBasicBlock("icr.cont");
3286 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
3287 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
3288 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003289 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00003290 }
3291 }
3292
Craig Topper8a13c412014-05-21 05:09:00 +00003293 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00003294
John McCall31168b02011-06-15 23:02:42 +00003295 // Perform a copy if necessary.
3296 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00003297 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00003298 assert(srcRV.isScalar());
3299
3300 llvm::Value *src = srcRV.getScalarVal();
3301 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
3302 "icr.cast");
3303
3304 // Use an ordinary store, not a store-to-lvalue.
3305 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00003306
3307 // If optimization is enabled, and the value was held in a
3308 // __strong variable, we need to tell the optimizer that this
3309 // value has to stay alive until we're doing the store back.
3310 // This is because the temporary is effectively unretained,
3311 // and so otherwise we can violate the high-level semantics.
3312 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3313 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
3314 valueToUse = src;
3315 }
John McCall31168b02011-06-15 23:02:42 +00003316 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003317
John McCall31168b02011-06-15 23:02:42 +00003318 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003319 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00003320 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00003321 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00003322
3323 // Make a phi for the value to intrinsically use.
3324 if (valueToUse) {
3325 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
3326 "icr.to-use");
3327 phiToUse->addIncoming(valueToUse, copyBB);
3328 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
3329 originBB);
3330 valueToUse = phiToUse;
3331 }
3332
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003333 condEval.end(CGF);
3334 }
John McCall31168b02011-06-15 23:02:42 +00003335
John McCalleff18842013-03-23 02:35:54 +00003336 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00003337 args.add(RValue::get(finalArgument), CRE->getType());
3338}
3339
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003340void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
Richard Smith762672a2016-09-28 19:09:10 +00003341 assert(!StackBase);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003342
3343 // Save the stack.
3344 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie43f9bb72015-05-18 22:14:03 +00003345 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003346}
3347
Nico Weber8cdb3f92015-08-25 18:43:32 +00003348void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
3349 if (StackBase) {
Reid Kleckner7c2f9e82015-10-08 00:17:45 +00003350 // Restore the stack after the call.
Nico Weber8cdb3f92015-08-25 18:43:32 +00003351 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
Nico Weber8cdb3f92015-08-25 18:43:32 +00003352 CGF.Builder.CreateCall(F, StackBase);
3353 }
3354}
3355
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003356void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
3357 SourceLocation ArgLoc,
Vedant Kumared00ea02017-03-06 05:28:22 +00003358 AbstractCallee AC,
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003359 unsigned ParmNum) {
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003360 if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
3361 SanOpts.has(SanitizerKind::NullabilityArg)))
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003362 return;
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003363
3364 // The param decl may be missing in a variadic function.
Vedant Kumared00ea02017-03-06 05:28:22 +00003365 auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr;
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003366 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003367
Fangrui Song6907ce22018-07-30 19:24:48 +00003368 // Prefer the nonnull attribute if it's present.
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003369 const NonNullAttr *NNAttr = nullptr;
3370 if (SanOpts.has(SanitizerKind::NonnullAttribute))
3371 NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
3372
3373 bool CanCheckNullability = false;
3374 if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD) {
3375 auto Nullability = PVD->getType()->getNullability(getContext());
3376 CanCheckNullability = Nullability &&
3377 *Nullability == NullabilityKind::NonNull &&
3378 PVD->getTypeSourceInfo();
3379 }
3380
3381 if (!NNAttr && !CanCheckNullability)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003382 return;
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003383
3384 SourceLocation AttrLoc;
3385 SanitizerMask CheckKind;
Vedant Kumar2b9f48a2017-03-14 16:48:29 +00003386 SanitizerHandler Handler;
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003387 if (NNAttr) {
3388 AttrLoc = NNAttr->getLocation();
3389 CheckKind = SanitizerKind::NonnullAttribute;
Vedant Kumar2b9f48a2017-03-14 16:48:29 +00003390 Handler = SanitizerHandler::NonnullArg;
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003391 } else {
3392 AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
3393 CheckKind = SanitizerKind::NullabilityArg;
Vedant Kumar2b9f48a2017-03-14 16:48:29 +00003394 Handler = SanitizerHandler::NullabilityArg;
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003395 }
3396
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003397 SanitizerScope SanScope(this);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003398 assert(RV.isScalar());
3399 llvm::Value *V = RV.getScalarVal();
3400 llvm::Value *Cond =
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003401 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003402 llvm::Constant *StaticData[] = {
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003403 EmitCheckSourceLocation(ArgLoc), EmitCheckSourceLocation(AttrLoc),
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003404 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003405 };
Vedant Kumar2b9f48a2017-03-14 16:48:29 +00003406 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, None);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003407}
3408
David Blaikief05779e2015-07-21 18:37:18 +00003409void CodeGenFunction::EmitCallArgs(
3410 CallArgList &Args, ArrayRef<QualType> ArgTypes,
3411 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
Vedant Kumared00ea02017-03-06 05:28:22 +00003412 AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
David Blaikief05779e2015-07-21 18:37:18 +00003413 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003414
Reid Kleckner739756c2013-12-04 19:23:12 +00003415 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
Richard Smitha560ccf2016-09-29 21:30:12 +00003416 // because arguments are destroyed left to right in the callee. As a special
3417 // case, there are certain language constructs that require left-to-right
3418 // evaluation, and in those cases we consider the evaluation order requirement
3419 // to trump the "destruction order is reverse construction order" guarantee.
3420 bool LeftToRight =
3421 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
3422 ? Order == EvaluationOrder::ForceLeftToRight
3423 : Order != EvaluationOrder::ForceRightToLeft;
3424
George Burgess IV0d6592a2017-02-23 05:59:56 +00003425 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
3426 RValue EmittedArg) {
Vedant Kumared00ea02017-03-06 05:28:22 +00003427 if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
George Burgess IV0d6592a2017-02-23 05:59:56 +00003428 return;
Vedant Kumared00ea02017-03-06 05:28:22 +00003429 auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
George Burgess IV0d6592a2017-02-23 05:59:56 +00003430 if (PS == nullptr)
3431 return;
3432
3433 const auto &Context = getContext();
3434 auto SizeTy = Context.getSizeType();
3435 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
3436 assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?");
3437 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
3438 EmittedArg.getScalarVal());
3439 Args.add(RValue::get(V), SizeTy);
3440 // If we're emitting args in reverse, be sure to do so with
3441 // pass_object_size, as well.
3442 if (!LeftToRight)
3443 std::swap(Args.back(), *(&Args.back() - 1));
3444 };
3445
Richard Smitha560ccf2016-09-29 21:30:12 +00003446 // Insert a stack save if we're going to need any inalloca args.
3447 bool HasInAllocaArgs = false;
3448 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003449 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
3450 I != E && !HasInAllocaArgs; ++I)
3451 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
3452 if (HasInAllocaArgs) {
3453 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3454 Args.allocateArgumentMemory(*this);
3455 }
Richard Smitha560ccf2016-09-29 21:30:12 +00003456 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003457
Richard Smitha560ccf2016-09-29 21:30:12 +00003458 // Evaluate each argument in the appropriate order.
3459 size_t CallArgsStart = Args.size();
3460 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
3461 unsigned Idx = LeftToRight ? I : E - I - 1;
3462 CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
George Burgess IV0d6592a2017-02-23 05:59:56 +00003463 unsigned InitialArgSize = Args.size();
Akira Hatanaka46dd7dbc2017-06-28 00:42:48 +00003464 // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of
3465 // the argument and parameter match or the objc method is parameterized.
3466 assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) ||
3467 getContext().hasSameUnqualifiedType((*Arg)->getType(),
3468 ArgTypes[Idx]) ||
3469 (isa<ObjCMethodDecl>(AC.getDecl()) &&
3470 isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) &&
3471 "Argument and parameter types don't match");
Richard Smitha560ccf2016-09-29 21:30:12 +00003472 EmitCallArg(Args, *Arg, ArgTypes[Idx]);
George Burgess IV0d6592a2017-02-23 05:59:56 +00003473 // In particular, we depend on it being the last arg in Args, and the
3474 // objectsize bits depend on there only being one arg if !LeftToRight.
3475 assert(InitialArgSize + 1 == Args.size() &&
3476 "The code below depends on only adding one arg per EmitCallArg");
3477 (void)InitialArgSize;
Yaxun Liu5b330e82018-03-15 15:25:19 +00003478 // Since pointer argument are never emitted as LValue, it is safe to emit
3479 // non-null argument check for r-value only.
3480 if (!Args.back().hasLValue()) {
3481 RValue RVArg = Args.back().getKnownRValue();
3482 EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
3483 ParamsToSkip + Idx);
3484 // @llvm.objectsize should never have side-effects and shouldn't need
3485 // destruction/cleanups, so we can safely "emit" it after its arg,
3486 // regardless of right-to-leftness
3487 MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
3488 }
Richard Smitha560ccf2016-09-29 21:30:12 +00003489 }
Reid Kleckner739756c2013-12-04 19:23:12 +00003490
Richard Smitha560ccf2016-09-29 21:30:12 +00003491 if (!LeftToRight) {
Reid Kleckner739756c2013-12-04 19:23:12 +00003492 // Un-reverse the arguments we just evaluated so they match up with the LLVM
3493 // IR function.
3494 std::reverse(Args.begin() + CallArgsStart, Args.end());
Reid Kleckner739756c2013-12-04 19:23:12 +00003495 }
3496}
3497
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003498namespace {
3499
David Blaikie7e70d682015-08-18 22:40:54 +00003500struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +00003501 DestroyUnpassedArg(Address Addr, QualType Ty)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003502 : Addr(Addr), Ty(Ty) {}
3503
John McCall7f416cc2015-09-08 08:05:57 +00003504 Address Addr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003505 QualType Ty;
3506
Craig Topper4f12f102014-03-12 06:41:41 +00003507 void Emit(CodeGenFunction &CGF, Flags flags) override {
Akira Hatanaka7275da02018-02-28 07:15:55 +00003508 QualType::DestructionKind DtorKind = Ty.isDestructedType();
3509 if (DtorKind == QualType::DK_cxx_destructor) {
3510 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
3511 assert(!Dtor->isTrivial());
3512 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
3513 /*Delegating=*/false, Addr);
3514 } else {
3515 CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty));
3516 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003517 }
3518};
3519
David Blaikie38b25912015-02-09 19:13:51 +00003520struct DisableDebugLocationUpdates {
3521 CodeGenFunction &CGF;
3522 bool disabledDebugInfo;
3523 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
3524 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
3525 CGF.disableDebugInfo();
3526 }
3527 ~DisableDebugLocationUpdates() {
3528 if (disabledDebugInfo)
3529 CGF.enableDebugInfo();
3530 }
3531};
3532
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00003533} // end anonymous namespace
3534
Yaxun Liu5b330e82018-03-15 15:25:19 +00003535RValue CallArg::getRValue(CodeGenFunction &CGF) const {
3536 if (!HasLV)
3537 return RV;
3538 LValue Copy = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty), Ty);
Richard Smithe78fac52018-04-05 20:52:58 +00003539 CGF.EmitAggregateCopy(Copy, LV, Ty, AggValueSlot::DoesNotOverlap,
3540 LV.isVolatile());
Yaxun Liu5b330e82018-03-15 15:25:19 +00003541 IsUsed = true;
3542 return RValue::getAggregate(Copy.getAddress());
3543}
3544
3545void CallArg::copyInto(CodeGenFunction &CGF, Address Addr) const {
3546 LValue Dst = CGF.MakeAddrLValue(Addr, Ty);
3547 if (!HasLV && RV.isScalar())
3548 CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*init=*/true);
3549 else if (!HasLV && RV.isComplex())
3550 CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true);
3551 else {
3552 auto Addr = HasLV ? LV.getAddress() : RV.getAggregateAddress();
3553 LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty);
Richard Smithe78fac52018-04-05 20:52:58 +00003554 // We assume that call args are never copied into subobjects.
3555 CGF.EmitAggregateCopy(Dst, SrcLV, Ty, AggValueSlot::DoesNotOverlap,
Yaxun Liu5b330e82018-03-15 15:25:19 +00003556 HasLV ? LV.isVolatileQualified()
3557 : RV.isVolatileQualified());
3558 }
3559 IsUsed = true;
3560}
3561
John McCall32ea9692011-03-11 20:59:21 +00003562void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
3563 QualType type) {
David Blaikie38b25912015-02-09 19:13:51 +00003564 DisableDebugLocationUpdates Dis(*this, E);
John McCall31168b02011-06-15 23:02:42 +00003565 if (const ObjCIndirectCopyRestoreExpr *CRE
3566 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00003567 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00003568 return emitWritebackArg(*this, args, CRE);
3569 }
3570
John McCall0a76c0c2011-08-26 18:42:59 +00003571 assert(type->isReferenceType() == E->isGLValue() &&
3572 "reference binding to unmaterialized r-value!");
3573
John McCall17054bd62011-08-26 21:08:13 +00003574 if (E->isGLValue()) {
3575 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00003576 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00003577 }
Mike Stump11289f42009-09-09 15:08:12 +00003578
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003579 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
3580
3581 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
3582 // However, we still have to push an EH-only cleanup in case we unwind before
3583 // we make it to the call.
Akira Hatanaka85282972018-05-15 21:00:30 +00003584 if (HasAggregateEvalKind &&
3585 type->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
Reid Klecknerac640602014-05-01 03:07:18 +00003586 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00003587 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00003588 AggValueSlot Slot;
3589 if (args.isUsingInAlloca())
3590 Slot = createPlaceholderSlot(*this, type);
3591 else
3592 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00003593
Akira Hatanaka4ce0e5a2018-04-18 23:33:15 +00003594 bool DestroyedInCallee = true, NeedsEHCleanup = true;
3595 if (const auto *RD = type->getAsCXXRecordDecl())
3596 DestroyedInCallee = RD->hasNonTrivialDestructor();
3597 else
3598 NeedsEHCleanup = needsEHCleanup(type.isDestructedType());
3599
3600 if (DestroyedInCallee)
3601 Slot.setExternallyDestructed();
Reid Klecknere39ee212014-05-03 00:33:28 +00003602
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003603 EmitAggExpr(E, Slot);
3604 RValue RV = Slot.asRValue();
3605 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003606
Akira Hatanaka4ce0e5a2018-04-18 23:33:15 +00003607 if (DestroyedInCallee && NeedsEHCleanup) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003608 // Create a no-op GEP between the placeholder and the cleanup so we can
3609 // RAUW it successfully. It also serves as a marker of the first
3610 // instruction where the cleanup is active.
John McCall7f416cc2015-09-08 08:05:57 +00003611 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
3612 type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003613 // This unreachable is a temporary marker which will be removed later.
3614 llvm::Instruction *IsActive = Builder.CreateUnreachable();
3615 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003616 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003617 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003618 }
3619
3620 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00003621 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
3622 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
3623 assert(L.isSimple());
Yaxun Liu5b330e82018-03-15 15:25:19 +00003624 args.addUncopiedAggregate(L, type);
Eli Friedmandf968192011-05-26 00:10:27 +00003625 return;
3626 }
3627
John McCall32ea9692011-03-11 20:59:21 +00003628 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00003629}
3630
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003631QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
3632 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
3633 // implicitly widens null pointer constants that are arguments to varargs
3634 // functions to pointer-sized ints.
3635 if (!getTarget().getTriple().isOSWindows())
3636 return Arg->getType();
3637
3638 if (Arg->getType()->isIntegerType() &&
3639 getContext().getTypeSize(Arg->getType()) <
3640 getContext().getTargetInfo().getPointerWidth(0) &&
3641 Arg->isNullPointerConstant(getContext(),
3642 Expr::NPC_ValueDependentIsNotNull)) {
3643 return getContext().getIntPtrType();
3644 }
3645
3646 return Arg->getType();
3647}
3648
Dan Gohman515a60d2012-02-16 00:57:37 +00003649// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3650// optimizer it can aggressively ignore unwind edges.
3651void
3652CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
3653 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3654 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
3655 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
3656 CGM.getNoObjCARCExceptionsMetadata());
3657}
3658
John McCall882987f2013-02-28 19:01:20 +00003659/// Emits a call to the given no-arguments nounwind runtime function.
3660llvm::CallInst *
3661CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3662 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003663 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003664}
3665
3666/// Emits a call to the given nounwind runtime function.
3667llvm::CallInst *
3668CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3669 ArrayRef<llvm::Value*> args,
3670 const llvm::Twine &name) {
3671 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
3672 call->setDoesNotThrow();
3673 return call;
3674}
3675
3676/// Emits a simple call (never an invoke) to the given no-arguments
3677/// runtime function.
3678llvm::CallInst *
3679CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3680 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003681 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003682}
3683
David Majnemer0b17d442015-12-15 21:27:59 +00003684// Calls which may throw must have operand bundles indicating which funclet
3685// they are nested within.
Reid Klecknerb75a3f02018-02-09 00:16:41 +00003686SmallVector<llvm::OperandBundleDef, 1>
3687CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) {
3688 SmallVector<llvm::OperandBundleDef, 1> BundleList;
Sanjay Patel846b63b2016-01-18 22:15:33 +00003689 // There is no need for a funclet operand bundle if we aren't inside a
3690 // funclet.
David Majnemer0b17d442015-12-15 21:27:59 +00003691 if (!CurrentFuncletPad)
Reid Klecknerb75a3f02018-02-09 00:16:41 +00003692 return BundleList;
David Majnemer0b17d442015-12-15 21:27:59 +00003693
3694 // Skip intrinsics which cannot throw.
3695 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
3696 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
Reid Klecknerb75a3f02018-02-09 00:16:41 +00003697 return BundleList;
David Majnemer0b17d442015-12-15 21:27:59 +00003698
3699 BundleList.emplace_back("funclet", CurrentFuncletPad);
Reid Klecknerb75a3f02018-02-09 00:16:41 +00003700 return BundleList;
David Majnemer0b17d442015-12-15 21:27:59 +00003701}
3702
David Majnemer971d31b2016-02-24 17:02:45 +00003703/// Emits a simple call (never an invoke) to the given runtime function.
3704llvm::CallInst *
3705CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3706 ArrayRef<llvm::Value*> args,
3707 const llvm::Twine &name) {
Reid Klecknerb75a3f02018-02-09 00:16:41 +00003708 llvm::CallInst *call =
3709 Builder.CreateCall(callee, args, getBundlesForFunclet(callee), name);
David Majnemer971d31b2016-02-24 17:02:45 +00003710 call->setCallingConv(getRuntimeCC());
3711 return call;
3712}
3713
John McCall882987f2013-02-28 19:01:20 +00003714/// Emits a call or invoke to the given noreturn runtime function.
3715void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3716 ArrayRef<llvm::Value*> args) {
Reid Klecknerb75a3f02018-02-09 00:16:41 +00003717 SmallVector<llvm::OperandBundleDef, 1> BundleList =
3718 getBundlesForFunclet(callee);
David Majnemer0b17d442015-12-15 21:27:59 +00003719
John McCall882987f2013-02-28 19:01:20 +00003720 if (getInvokeDest()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003721 llvm::InvokeInst *invoke =
John McCall882987f2013-02-28 19:01:20 +00003722 Builder.CreateInvoke(callee,
3723 getUnreachableBlock(),
3724 getInvokeDest(),
David Majnemer0b17d442015-12-15 21:27:59 +00003725 args,
3726 BundleList);
John McCall882987f2013-02-28 19:01:20 +00003727 invoke->setDoesNotReturn();
3728 invoke->setCallingConv(getRuntimeCC());
3729 } else {
David Majnemer0b17d442015-12-15 21:27:59 +00003730 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
John McCall882987f2013-02-28 19:01:20 +00003731 call->setDoesNotReturn();
3732 call->setCallingConv(getRuntimeCC());
3733 Builder.CreateUnreachable();
3734 }
3735}
3736
Sanjay Patel846b63b2016-01-18 22:15:33 +00003737/// Emits a call or invoke instruction to the given nullary runtime function.
John McCall882987f2013-02-28 19:01:20 +00003738llvm::CallSite
3739CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3740 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003741 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003742}
3743
3744/// Emits a call or invoke instruction to the given runtime function.
3745llvm::CallSite
3746CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3747 ArrayRef<llvm::Value*> args,
3748 const Twine &name) {
3749 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
3750 callSite.setCallingConv(getRuntimeCC());
3751 return callSite;
3752}
3753
John McCallbd309292010-07-06 01:34:17 +00003754/// Emits a call or invoke instruction to the given function, depending
3755/// on the current state of the EH stack.
3756llvm::CallSite
3757CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00003758 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003759 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00003760 llvm::BasicBlock *InvokeDest = getInvokeDest();
Reid Klecknerb75a3f02018-02-09 00:16:41 +00003761 SmallVector<llvm::OperandBundleDef, 1> BundleList =
3762 getBundlesForFunclet(Callee);
John McCallbd309292010-07-06 01:34:17 +00003763
Dan Gohman515a60d2012-02-16 00:57:37 +00003764 llvm::Instruction *Inst;
3765 if (!InvokeDest)
David Majnemer3df77bc2016-01-26 23:14:47 +00003766 Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003767 else {
3768 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
David Majnemer3df77bc2016-01-26 23:14:47 +00003769 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
3770 Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003771 EmitBlock(ContBB);
3772 }
3773
3774 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3775 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003776 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003777 AddObjCARCExceptionMetadata(Inst);
3778
Benjamin Kramerc19cde12015-04-10 14:49:31 +00003779 return llvm::CallSite(Inst);
John McCallbd309292010-07-06 01:34:17 +00003780}
3781
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003782void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
3783 llvm::Value *New) {
3784 DeferredReplacements.push_back(std::make_pair(Old, New));
3785}
Chris Lattnerd59d8672011-07-12 06:29:11 +00003786
Daniel Dunbard931a872009-02-02 22:03:45 +00003787RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
John McCallb92ab1a2016-10-26 23:46:34 +00003788 const CGCallee &Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00003789 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003790 const CallArgList &CallArgs,
Vedant Kumar09b5bfd2017-12-21 00:10:25 +00003791 llvm::Instruction **callOrInvoke,
3792 SourceLocation Loc) {
Mike Stump18bb9282009-05-16 07:57:57 +00003793 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00003794
Peter Collingbourneea211002018-02-05 23:09:13 +00003795 assert(Callee.isOrdinary() || Callee.isVirtual());
John McCallb92ab1a2016-10-26 23:46:34 +00003796
Daniel Dunbar613855c2008-09-09 23:27:19 +00003797 // Handle struct-return functions by passing a pointer to the
3798 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00003799 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003800 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003801
John McCallb92ab1a2016-10-26 23:46:34 +00003802 llvm::FunctionType *IRFuncTy = Callee.getFunctionType();
3803
3804 // 1. Set up the arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003805
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003806 // If we're using inalloca, insert the allocation after the stack save.
3807 // FIXME: Do this earlier rather than hacking it in here!
John McCall7f416cc2015-09-08 08:05:57 +00003808 Address ArgMemory = Address::invalid();
3809 const llvm::StructLayout *ArgMemoryLayout = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003810 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
Matt Arsenault502ad602017-04-10 22:28:02 +00003811 const llvm::DataLayout &DL = CGM.getDataLayout();
3812 ArgMemoryLayout = DL.getStructLayout(ArgStruct);
Reid Kleckner9df1d972014-04-10 01:40:15 +00003813 llvm::Instruction *IP = CallArgs.getStackBase();
3814 llvm::AllocaInst *AI;
3815 if (IP) {
3816 IP = IP->getNextNode();
Matt Arsenault502ad602017-04-10 22:28:02 +00003817 AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(),
3818 "argmem", IP);
Reid Kleckner9df1d972014-04-10 01:40:15 +00003819 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00003820 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00003821 }
John McCall7f416cc2015-09-08 08:05:57 +00003822 auto Align = CallInfo.getArgStructAlignment();
3823 AI->setAlignment(Align.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003824 AI->setUsedWithInAlloca(true);
3825 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
John McCall7f416cc2015-09-08 08:05:57 +00003826 ArgMemory = Address(AI, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003827 }
3828
John McCall7f416cc2015-09-08 08:05:57 +00003829 // Helper function to drill into the inalloca allocation.
3830 auto createInAllocaStructGEP = [&](unsigned FieldIndex) -> Address {
3831 auto FieldOffset =
3832 CharUnits::fromQuantity(ArgMemoryLayout->getElementOffset(FieldIndex));
3833 return Builder.CreateStructGEP(ArgMemory, FieldIndex, FieldOffset);
3834 };
3835
Alexey Samsonov153004f2014-09-29 22:08:00 +00003836 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003837 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3838
Chris Lattner4ca97c32009-06-13 00:26:38 +00003839 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00003840 // alloca to hold the result, unless one is given to us.
John McCall7f416cc2015-09-08 08:05:57 +00003841 Address SRetPtr = Address::invalid();
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00003842 Address SRetAlloca = Address::invalid();
George Burgess IV003be7c2018-03-08 05:32:30 +00003843 llvm::Value *UnusedReturnSizePtr = nullptr;
John McCallf26e73d2016-03-11 04:30:43 +00003844 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
John McCall7f416cc2015-09-08 08:05:57 +00003845 if (!ReturnValue.isNull()) {
3846 SRetPtr = ReturnValue.getValue();
3847 } else {
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00003848 SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca);
Leny Kholodov6aab1112015-06-08 10:23:49 +00003849 if (HaveInsertPoint() && ReturnValue.isUnused()) {
3850 uint64_t size =
3851 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00003852 UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer());
Leny Kholodov6aab1112015-06-08 10:23:49 +00003853 }
3854 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003855 if (IRFunctionArgs.hasSRetArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00003856 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
John McCallf26e73d2016-03-11 04:30:43 +00003857 } else if (RetAI.isInAlloca()) {
John McCall7f416cc2015-09-08 08:05:57 +00003858 Address Addr = createInAllocaStructGEP(RetAI.getInAllocaFieldIndex());
3859 Builder.CreateStore(SRetPtr.getPointer(), Addr);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003860 }
Anders Carlsson17490832009-12-24 20:40:36 +00003861 }
Mike Stump11289f42009-09-09 15:08:12 +00003862
John McCall12f23522016-04-04 18:33:08 +00003863 Address swiftErrorTemp = Address::invalid();
3864 Address swiftErrorArg = Address::invalid();
3865
John McCallb92ab1a2016-10-26 23:46:34 +00003866 // Translate all of the arguments as necessary to match the IR lowering.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00003867 assert(CallInfo.arg_size() == CallArgs.size() &&
3868 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003869 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003870 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00003871 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003872 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003873 const ABIArgInfo &ArgInfo = info_it->info;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003874
Rafael Espindolafad28de2012-10-24 01:59:00 +00003875 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003876 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3877 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3878 llvm::UndefValue::get(ArgInfo.getPaddingType());
3879
3880 unsigned FirstIRArg, NumIRArgs;
3881 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003882
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003883 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003884 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003885 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003886 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
Yaxun Liu5b330e82018-03-15 15:25:19 +00003887 if (I->isAggregate()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003888 // Replace the placeholder with the appropriate argument slot GEP.
Yaxun Liu5b330e82018-03-15 15:25:19 +00003889 Address Addr = I->hasLValue()
3890 ? I->getKnownLValue().getAddress()
3891 : I->getKnownRValue().getAggregateAddress();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003892 llvm::Instruction *Placeholder =
Yaxun Liu5b330e82018-03-15 15:25:19 +00003893 cast<llvm::Instruction>(Addr.getPointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003894 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3895 Builder.SetInsertPoint(Placeholder);
Yaxun Liu5b330e82018-03-15 15:25:19 +00003896 Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003897 Builder.restoreIP(IP);
John McCall7f416cc2015-09-08 08:05:57 +00003898 deferPlaceholderReplacement(Placeholder, Addr.getPointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003899 } else {
3900 // Store the RValue into the argument struct.
John McCall7f416cc2015-09-08 08:05:57 +00003901 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
3902 unsigned AS = Addr.getType()->getPointerAddressSpace();
David Majnemer32b57b02014-03-31 16:12:47 +00003903 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3904 // There are some cases where a trivial bitcast is not avoidable. The
3905 // definition of a type later in a translation unit may change it's type
3906 // from {}* to (%struct.foo*)*.
John McCall7f416cc2015-09-08 08:05:57 +00003907 if (Addr.getType() != MemType)
David Majnemer32b57b02014-03-31 16:12:47 +00003908 Addr = Builder.CreateBitCast(Addr, MemType);
Yaxun Liu5b330e82018-03-15 15:25:19 +00003909 I->copyInto(*this, Addr);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003910 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003911 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003912 }
3913
Daniel Dunbar03816342010-08-21 02:24:36 +00003914 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003915 assert(NumIRArgs == 1);
Yaxun Liu5b330e82018-03-15 15:25:19 +00003916 if (!I->isAggregate()) {
Daniel Dunbar747865a2009-02-05 09:16:39 +00003917 // Make a temporary alloca to pass the argument.
Yaxun Liuaefdb8e2018-06-15 15:33:22 +00003918 Address Addr = CreateMemTempWithoutCast(
3919 I->Ty, ArgInfo.getIndirectAlign(), "indirect-arg-temp");
John McCall7f416cc2015-09-08 08:05:57 +00003920 IRCallArgs[FirstIRArg] = Addr.getPointer();
John McCall47fb9502013-03-07 21:37:08 +00003921
Yaxun Liu5b330e82018-03-15 15:25:19 +00003922 I->copyInto(*this, Addr);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003923 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003924 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003925 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003926 // 1. If the argument is not byval, and we are required to copy the
3927 // source. (This case doesn't occur on any common architecture.)
3928 // 2. If the argument is byval, RV is not sufficiently aligned, and
3929 // we cannot force it to be sufficiently aligned.
Yaxun Liu5b330e82018-03-15 15:25:19 +00003930 // 3. If the argument is byval, but RV is not located in default
3931 // or alloca address space.
3932 Address Addr = I->hasLValue()
3933 ? I->getKnownLValue().getAddress()
3934 : I->getKnownRValue().getAggregateAddress();
3935 llvm::Value *V = Addr.getPointer();
John McCall7f416cc2015-09-08 08:05:57 +00003936 CharUnits Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003937 const llvm::DataLayout *TD = &CGM.getDataLayout();
Yaxun Liu5b330e82018-03-15 15:25:19 +00003938
3939 assert((FirstIRArg >= IRFuncTy->getNumParams() ||
3940 IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() ==
3941 TD->getAllocaAddrSpace()) &&
3942 "indirect argument must be in alloca address space");
3943
3944 bool NeedCopy = false;
3945
3946 if (Addr.getAlignment() < Align &&
3947 llvm::getOrEnforceKnownAlignment(V, Align.getQuantity(), *TD) <
3948 Align.getQuantity()) {
3949 NeedCopy = true;
3950 } else if (I->hasLValue()) {
3951 auto LV = I->getKnownLValue();
3952 auto AS = LV.getAddressSpace();
3953 if ((!ArgInfo.getIndirectByVal() &&
3954 (LV.getAlignment() >=
3955 getContext().getTypeAlignInChars(I->Ty))) ||
3956 (ArgInfo.getIndirectByVal() &&
3957 ((AS != LangAS::Default && AS != LangAS::opencl_private &&
3958 AS != CGM.getASTAllocaAddressSpace())))) {
3959 NeedCopy = true;
3960 }
3961 }
3962 if (NeedCopy) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003963 // Create an aligned temporary, and copy to it.
Yaxun Liuaefdb8e2018-06-15 15:33:22 +00003964 Address AI = CreateMemTempWithoutCast(
3965 I->Ty, ArgInfo.getIndirectAlign(), "byval-temp");
John McCall7f416cc2015-09-08 08:05:57 +00003966 IRCallArgs[FirstIRArg] = AI.getPointer();
Yaxun Liu5b330e82018-03-15 15:25:19 +00003967 I->copyInto(*this, AI);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003968 } else {
3969 // Skip the extra memcpy call.
Yaxun Liu5b330e82018-03-15 15:25:19 +00003970 auto *T = V->getType()->getPointerElementType()->getPointerTo(
3971 CGM.getDataLayout().getAllocaAddrSpace());
3972 IRCallArgs[FirstIRArg] = getTargetHooks().performAddrSpaceCast(
3973 *this, V, LangAS::Default, CGM.getASTAllocaAddressSpace(), T,
3974 true);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003975 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003976 }
3977 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003978 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003979
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003980 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003981 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003982 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003983
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003984 case ABIArgInfo::Extend:
3985 case ABIArgInfo::Direct: {
3986 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003987 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3988 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003989 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003990 llvm::Value *V;
Yaxun Liu5b330e82018-03-15 15:25:19 +00003991 if (!I->isAggregate())
3992 V = I->getKnownRValue().getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003993 else
Yaxun Liu5b330e82018-03-15 15:25:19 +00003994 V = Builder.CreateLoad(
3995 I->hasLValue() ? I->getKnownLValue().getAddress()
3996 : I->getKnownRValue().getAggregateAddress());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003997
John McCall12f23522016-04-04 18:33:08 +00003998 // Implement swifterror by copying into a new swifterror argument.
3999 // We'll write back in the normal path out of the call.
4000 if (CallInfo.getExtParameterInfo(ArgNo).getABI()
4001 == ParameterABI::SwiftErrorResult) {
4002 assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
4003
4004 QualType pointeeTy = I->Ty->getPointeeType();
4005 swiftErrorArg =
4006 Address(V, getContext().getTypeAlignInChars(pointeeTy));
4007
4008 swiftErrorTemp =
4009 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
4010 V = swiftErrorTemp.getPointer();
4011 cast<llvm::AllocaInst>(V)->setSwiftError(true);
4012
4013 llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
4014 Builder.CreateStore(errorValue, swiftErrorTemp);
4015 }
4016
Reid Kleckner79b0fd72014-10-10 00:05:45 +00004017 // We might have to widen integers, but we should never truncate.
4018 if (ArgInfo.getCoerceToType() != V->getType() &&
4019 V->getType()->isIntegerTy())
4020 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
4021
Chris Lattner3ce86682011-07-12 04:53:39 +00004022 // If the argument doesn't match, perform a bitcast to coerce it. This
4023 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004024 if (FirstIRArg < IRFuncTy->getNumParams() &&
4025 V->getType() != IRFuncTy->getParamType(FirstIRArg))
4026 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
John McCall12f23522016-04-04 18:33:08 +00004027
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004028 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004029 break;
4030 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00004031
Daniel Dunbar2f219b02009-02-03 19:12:28 +00004032 // FIXME: Avoid the conversion through memory if possible.
John McCall7f416cc2015-09-08 08:05:57 +00004033 Address Src = Address::invalid();
Yaxun Liu5b330e82018-03-15 15:25:19 +00004034 if (!I->isAggregate()) {
John McCall7f416cc2015-09-08 08:05:57 +00004035 Src = CreateMemTemp(I->Ty, "coerce");
Yaxun Liu5b330e82018-03-15 15:25:19 +00004036 I->copyInto(*this, Src);
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00004037 } else {
Yaxun Liu5b330e82018-03-15 15:25:19 +00004038 Src = I->hasLValue() ? I->getKnownLValue().getAddress()
4039 : I->getKnownRValue().getAggregateAddress();
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00004040 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004041
Chris Lattner8a2f3c72010-07-30 04:02:24 +00004042 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00004043 Src = emitAddressAtOffset(*this, Src, ArgInfo);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004044
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004045 // Fast-isel and the optimizer generally like scalar values better than
4046 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00004047 llvm::StructType *STy =
4048 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004049 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
John McCall7f416cc2015-09-08 08:05:57 +00004050 llvm::Type *SrcTy = Src.getType()->getElementType();
Chandler Carrutha6399a52012-10-10 11:29:08 +00004051 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
4052 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
4053
4054 // If the source type is smaller than the destination type of the
4055 // coerce-to logic, copy the source value into a temp alloca the size
4056 // of the destination type to allow loading all of it. The bits past
4057 // the source value are left undef.
4058 if (SrcSize < DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00004059 Address TempAlloca
4060 = CreateTempAlloca(STy, Src.getAlignment(),
4061 Src.getName() + ".coerce");
4062 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
4063 Src = TempAlloca;
Chandler Carrutha6399a52012-10-10 11:29:08 +00004064 } else {
Matt Arsenault7a124f32017-08-01 20:36:57 +00004065 Src = Builder.CreateBitCast(Src,
4066 STy->getPointerTo(Src.getAddressSpace()));
Chandler Carrutha6399a52012-10-10 11:29:08 +00004067 }
4068
John McCall7f416cc2015-09-08 08:05:57 +00004069 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004070 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00004071 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00004072 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
4073 Address EltPtr = Builder.CreateStructGEP(Src, i, Offset);
4074 llvm::Value *LI = Builder.CreateLoad(EltPtr);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004075 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00004076 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00004077 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00004078 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004079 assert(NumIRArgs == 1);
4080 IRCallArgs[FirstIRArg] =
John McCall7f416cc2015-09-08 08:05:57 +00004081 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00004082 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004083
Daniel Dunbar2f219b02009-02-03 19:12:28 +00004084 break;
4085 }
4086
John McCallf26e73d2016-03-11 04:30:43 +00004087 case ABIArgInfo::CoerceAndExpand: {
John McCallf26e73d2016-03-11 04:30:43 +00004088 auto coercionType = ArgInfo.getCoerceAndExpandType();
4089 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
4090
John McCall12f23522016-04-04 18:33:08 +00004091 llvm::Value *tempSize = nullptr;
4092 Address addr = Address::invalid();
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00004093 Address AllocaAddr = Address::invalid();
Yaxun Liu5b330e82018-03-15 15:25:19 +00004094 if (I->isAggregate()) {
4095 addr = I->hasLValue() ? I->getKnownLValue().getAddress()
4096 : I->getKnownRValue().getAggregateAddress();
4097
John McCall12f23522016-04-04 18:33:08 +00004098 } else {
Yaxun Liu5b330e82018-03-15 15:25:19 +00004099 RValue RV = I->getKnownRValue();
John McCall12f23522016-04-04 18:33:08 +00004100 assert(RV.isScalar()); // complex should always just be direct
4101
4102 llvm::Type *scalarType = RV.getScalarVal()->getType();
4103 auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
4104 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType);
4105
John McCall12f23522016-04-04 18:33:08 +00004106 // Materialize to a temporary.
4107 addr = CreateTempAlloca(RV.getScalarVal()->getType(),
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00004108 CharUnits::fromQuantity(std::max(
4109 layout->getAlignment(), scalarAlign)),
4110 "tmp",
4111 /*ArraySize=*/nullptr, &AllocaAddr);
4112 tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer());
John McCall12f23522016-04-04 18:33:08 +00004113
4114 Builder.CreateStore(RV.getScalarVal(), addr);
4115 }
4116
John McCallf26e73d2016-03-11 04:30:43 +00004117 addr = Builder.CreateElementBitCast(addr, coercionType);
4118
4119 unsigned IRArgPos = FirstIRArg;
4120 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
4121 llvm::Type *eltType = coercionType->getElementType(i);
4122 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
4123 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
4124 llvm::Value *elt = Builder.CreateLoad(eltAddr);
4125 IRCallArgs[IRArgPos++] = elt;
4126 }
4127 assert(IRArgPos == FirstIRArg + NumIRArgs);
4128
John McCall12f23522016-04-04 18:33:08 +00004129 if (tempSize) {
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00004130 EmitLifetimeEnd(tempSize, AllocaAddr.getPointer());
John McCall12f23522016-04-04 18:33:08 +00004131 }
4132
John McCallf26e73d2016-03-11 04:30:43 +00004133 break;
4134 }
4135
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00004136 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004137 unsigned IRArgPos = FirstIRArg;
Yaxun Liu5b330e82018-03-15 15:25:19 +00004138 ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004139 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00004140 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00004141 }
4142 }
Mike Stump11289f42009-09-09 15:08:12 +00004143
John McCall9831b842018-02-06 18:52:44 +00004144 const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this);
4145 llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer();
John McCallb92ab1a2016-10-26 23:46:34 +00004146
4147 // If we're using inalloca, set up that argument.
John McCall7f416cc2015-09-08 08:05:57 +00004148 if (ArgMemory.isValid()) {
4149 llvm::Value *Arg = ArgMemory.getPointer();
Reid Klecknerafba553e2014-07-08 02:24:27 +00004150 if (CallInfo.isVariadic()) {
4151 // When passing non-POD arguments by value to variadic functions, we will
4152 // end up with a variadic prototype and an inalloca call site. In such
4153 // cases, we can't do any parameter mismatch checks. Give up and bitcast
4154 // the callee.
John McCallb92ab1a2016-10-26 23:46:34 +00004155 unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace();
4156 auto FnTy = getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS);
4157 CalleePtr = Builder.CreateBitCast(CalleePtr, FnTy);
Reid Klecknerafba553e2014-07-08 02:24:27 +00004158 } else {
4159 llvm::Type *LastParamTy =
4160 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
4161 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00004162#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00004163 // Assert that these structs have equivalent element types.
4164 llvm::StructType *FullTy = CallInfo.getArgStruct();
4165 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
4166 cast<llvm::PointerType>(LastParamTy)->getElementType());
4167 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
4168 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
4169 DE = DeclaredTy->element_end(),
4170 FI = FullTy->element_begin();
4171 DI != DE; ++DI, ++FI)
4172 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00004173#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00004174 Arg = Builder.CreateBitCast(Arg, LastParamTy);
4175 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00004176 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004177 assert(IRFunctionArgs.hasInallocaArg());
4178 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00004179 }
4180
John McCallb92ab1a2016-10-26 23:46:34 +00004181 // 2. Prepare the function pointer.
4182
4183 // If the callee is a bitcast of a non-variadic function to have a
4184 // variadic function pointer type, check to see if we can remove the
4185 // bitcast. This comes up with unprototyped functions.
4186 //
4187 // This makes the IR nicer, but more importantly it ensures that we
4188 // can inline the function at -O0 if it is marked always_inline.
4189 auto simplifyVariadicCallee = [](llvm::Value *Ptr) -> llvm::Value* {
4190 llvm::FunctionType *CalleeFT =
4191 cast<llvm::FunctionType>(Ptr->getType()->getPointerElementType());
4192 if (!CalleeFT->isVarArg())
4193 return Ptr;
4194
4195 llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr);
4196 if (!CE || CE->getOpcode() != llvm::Instruction::BitCast)
4197 return Ptr;
4198
4199 llvm::Function *OrigFn = dyn_cast<llvm::Function>(CE->getOperand(0));
4200 if (!OrigFn)
4201 return Ptr;
4202
4203 llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
4204
4205 // If the original type is variadic, or if any of the component types
4206 // disagree, we cannot remove the cast.
4207 if (OrigFT->isVarArg() ||
4208 OrigFT->getNumParams() != CalleeFT->getNumParams() ||
4209 OrigFT->getReturnType() != CalleeFT->getReturnType())
4210 return Ptr;
4211
4212 for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
4213 if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
4214 return Ptr;
4215
4216 return OrigFn;
4217 };
4218 CalleePtr = simplifyVariadicCallee(CalleePtr);
4219
4220 // 3. Perform the actual call.
4221
4222 // Deactivate any cleanups that we're supposed to do immediately before
4223 // the call.
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00004224 if (!CallArgs.getCleanupsToDeactivate().empty())
4225 deactivateArgCleanupsBeforeCall(*this, CallArgs);
4226
John McCallb92ab1a2016-10-26 23:46:34 +00004227 // Assert that the arguments we computed match up. The IR verifier
4228 // will catch this, but this is a common enough source of problems
4229 // during IRGen changes that it's way better for debugging to catch
4230 // it ourselves here.
4231#ifndef NDEBUG
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004232 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
4233 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
4234 // Inalloca argument can have different type.
4235 if (IRFunctionArgs.hasInallocaArg() &&
4236 i == IRFunctionArgs.getInallocaArgNo())
4237 continue;
4238 if (i < IRFuncTy->getNumParams())
4239 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
4240 }
John McCallb92ab1a2016-10-26 23:46:34 +00004241#endif
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004242
Craig Topper3113ec32018-10-24 17:42:17 +00004243 // Update the largest vector width if any arguments have vector types.
4244 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
4245 if (auto *VT = dyn_cast<llvm::VectorType>(IRCallArgs[i]->getType()))
4246 LargestVectorWidth = std::max(LargestVectorWidth,
4247 VT->getPrimitiveSizeInBits());
4248 }
4249
John McCallb92ab1a2016-10-26 23:46:34 +00004250 // Compute the calling convention and attributes.
Daniel Dunbar0ef34792009-09-12 00:59:20 +00004251 unsigned CallingConv;
Reid Klecknercdd26792017-04-18 23:50:03 +00004252 llvm::AttributeList Attrs;
John McCallb92ab1a2016-10-26 23:46:34 +00004253 CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
Reid Klecknercdd26792017-04-18 23:50:03 +00004254 Callee.getAbstractInfo(), Attrs, CallingConv,
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00004255 /*AttrOnCallSite=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004256
John McCallb92ab1a2016-10-26 23:46:34 +00004257 // Apply some call-site-specific attributes.
4258 // TODO: work this into building the attribute set.
4259
4260 // Apply always_inline to all calls within flatten functions.
4261 // FIXME: should this really take priority over __try, below?
4262 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
4263 !(Callee.getAbstractInfo().getCalleeDecl() &&
4264 Callee.getAbstractInfo().getCalleeDecl()->hasAttr<NoInlineAttr>())) {
4265 Attrs =
Reid Klecknerde864822017-03-21 16:57:30 +00004266 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
John McCallb92ab1a2016-10-26 23:46:34 +00004267 llvm::Attribute::AlwaysInline);
4268 }
4269
4270 // Disable inlining inside SEH __try blocks.
4271 if (isSEHTryScope()) {
4272 Attrs =
Reid Klecknerde864822017-03-21 16:57:30 +00004273 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
John McCallb92ab1a2016-10-26 23:46:34 +00004274 llvm::Attribute::NoInline);
4275 }
4276
4277 // Decide whether to use a call or an invoke.
David Majnemer4e52d6f2015-12-12 05:39:21 +00004278 bool CannotThrow;
4279 if (currentFunctionUsesSEHTry()) {
John McCallb92ab1a2016-10-26 23:46:34 +00004280 // SEH cares about asynchronous exceptions, so everything can "throw."
David Majnemer4e52d6f2015-12-12 05:39:21 +00004281 CannotThrow = false;
4282 } else if (isCleanupPadScope() &&
4283 EHPersonality::get(*this).isMSVCXXPersonality()) {
4284 // The MSVC++ personality will implicitly terminate the program if an
John McCallb92ab1a2016-10-26 23:46:34 +00004285 // exception is thrown during a cleanup outside of a try/catch.
4286 // We don't need to model anything in IR to get this behavior.
David Majnemer4e52d6f2015-12-12 05:39:21 +00004287 CannotThrow = true;
4288 } else {
John McCallb92ab1a2016-10-26 23:46:34 +00004289 // Otherwise, nounwind call sites will never throw.
Reid Klecknerde864822017-03-21 16:57:30 +00004290 CannotThrow = Attrs.hasAttribute(llvm::AttributeList::FunctionIndex,
David Majnemer4e52d6f2015-12-12 05:39:21 +00004291 llvm::Attribute::NoUnwind);
4292 }
George Burgess IV003be7c2018-03-08 05:32:30 +00004293
4294 // If we made a temporary, be sure to clean up after ourselves. Note that we
4295 // can't depend on being inside of an ExprWithCleanups, so we need to manually
4296 // pop this cleanup later on. Being eager about this is OK, since this
4297 // temporary is 'invisible' outside of the callee.
4298 if (UnusedReturnSizePtr)
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00004299 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca,
George Burgess IV003be7c2018-03-08 05:32:30 +00004300 UnusedReturnSizePtr);
4301
David Majnemer4e52d6f2015-12-12 05:39:21 +00004302 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00004303
Reid Klecknerb75a3f02018-02-09 00:16:41 +00004304 SmallVector<llvm::OperandBundleDef, 1> BundleList =
4305 getBundlesForFunclet(CalleePtr);
David Majnemer0b17d442015-12-15 21:27:59 +00004306
John McCallb92ab1a2016-10-26 23:46:34 +00004307 // Emit the actual call/invoke instruction.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004308 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00004309 if (!InvokeDest) {
John McCallb92ab1a2016-10-26 23:46:34 +00004310 CS = Builder.CreateCall(CalleePtr, IRCallArgs, BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00004311 } else {
4312 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
John McCallb92ab1a2016-10-26 23:46:34 +00004313 CS = Builder.CreateInvoke(CalleePtr, Cont, InvokeDest, IRCallArgs,
David Majnemer0b17d442015-12-15 21:27:59 +00004314 BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00004315 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00004316 }
John McCallb92ab1a2016-10-26 23:46:34 +00004317 llvm::Instruction *CI = CS.getInstruction();
Chris Lattnere70a0072010-06-29 16:40:28 +00004318 if (callOrInvoke)
John McCallb92ab1a2016-10-26 23:46:34 +00004319 *callOrInvoke = CI;
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00004320
John McCallb92ab1a2016-10-26 23:46:34 +00004321 // Apply the attributes and calling convention.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004322 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00004323 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004324
John McCallb92ab1a2016-10-26 23:46:34 +00004325 // Apply various metadata.
4326
4327 if (!CI->getType()->isVoidTy())
4328 CI->setName("call");
4329
Craig Topper3113ec32018-10-24 17:42:17 +00004330 // Update largest vector width from the return type.
4331 if (auto *VT = dyn_cast<llvm::VectorType>(CI->getType()))
4332 LargestVectorWidth = std::max(LargestVectorWidth,
4333 VT->getPrimitiveSizeInBits());
4334
Adam Nemet1e217bc2016-03-28 22:18:53 +00004335 // Insert instrumentation or attach profile metadata at indirect call sites.
4336 // For more details, see the comment before the definition of
4337 // IPVK_IndirectCallTarget in InstrProfData.inc.
Betul Buyukkurt518276a2016-01-23 22:50:44 +00004338 if (!CS.getCalledFunction())
4339 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
John McCallb92ab1a2016-10-26 23:46:34 +00004340 CI, CalleePtr);
Betul Buyukkurt518276a2016-01-23 22:50:44 +00004341
Dan Gohman515a60d2012-02-16 00:57:37 +00004342 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4343 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004344 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallb92ab1a2016-10-26 23:46:34 +00004345 AddObjCARCExceptionMetadata(CI);
4346
4347 // Suppress tail calls if requested.
4348 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
4349 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl();
4350 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
4351 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
4352 }
4353
4354 // 4. Finish the call.
Dan Gohman515a60d2012-02-16 00:57:37 +00004355
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004356 // If the call doesn't return, finish the basic block and clear the
John McCallb92ab1a2016-10-26 23:46:34 +00004357 // insertion point; this allows the rest of IRGen to discard
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004358 // unreachable code.
4359 if (CS.doesNotReturn()) {
George Burgess IV003be7c2018-03-08 05:32:30 +00004360 if (UnusedReturnSizePtr)
4361 PopCleanupBlock();
Leny Kholodov6aab1112015-06-08 10:23:49 +00004362
Vedant Kumar09b5bfd2017-12-21 00:10:25 +00004363 // Strip away the noreturn attribute to better diagnose unreachable UB.
4364 if (SanOpts.has(SanitizerKind::Unreachable)) {
4365 if (auto *F = CS.getCalledFunction())
4366 F->removeFnAttr(llvm::Attribute::NoReturn);
4367 CS.removeAttribute(llvm::AttributeList::FunctionIndex,
4368 llvm::Attribute::NoReturn);
4369 }
4370
4371 EmitUnreachable(Loc);
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004372 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00004373
Mike Stump18bb9282009-05-16 07:57:57 +00004374 // FIXME: For now, emit a dummy basic block because expr emitters in
4375 // generally are not ready to handle emitting expressions at unreachable
4376 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004377 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00004378
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004379 // Return a reasonable RValue.
4380 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00004381 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004382
John McCall12f23522016-04-04 18:33:08 +00004383 // Perform the swifterror writeback.
4384 if (swiftErrorTemp.isValid()) {
4385 llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
4386 Builder.CreateStore(errorResult, swiftErrorArg);
4387 }
4388
John McCallb92ab1a2016-10-26 23:46:34 +00004389 // Emit any call-associated writebacks immediately. Arguably this
4390 // should happen after any return-value munging.
John McCall31168b02011-06-15 23:02:42 +00004391 if (CallArgs.hasWritebacks())
4392 emitWritebacks(*this, CallArgs);
4393
Nico Weber8cdb3f92015-08-25 18:43:32 +00004394 // The stack cleanup for inalloca arguments has to run out of the normal
4395 // lexical order, so deactivate it and run it manually here.
4396 CallArgs.freeArgumentMemory(*this);
4397
John McCallb92ab1a2016-10-26 23:46:34 +00004398 // Extract the return value.
Hal Finkelee90a222014-09-26 05:04:30 +00004399 RValue Ret = [&] {
4400 switch (RetAI.getKind()) {
John McCallf26e73d2016-03-11 04:30:43 +00004401 case ABIArgInfo::CoerceAndExpand: {
4402 auto coercionType = RetAI.getCoerceAndExpandType();
4403 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
4404
4405 Address addr = SRetPtr;
4406 addr = Builder.CreateElementBitCast(addr, coercionType);
4407
John McCall12f23522016-04-04 18:33:08 +00004408 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
4409 bool requiresExtract = isa<llvm::StructType>(CI->getType());
4410
John McCallf26e73d2016-03-11 04:30:43 +00004411 unsigned unpaddedIndex = 0;
4412 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
4413 llvm::Type *eltType = coercionType->getElementType(i);
4414 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
4415 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
John McCall12f23522016-04-04 18:33:08 +00004416 llvm::Value *elt = CI;
4417 if (requiresExtract)
4418 elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
4419 else
4420 assert(unpaddedIndex == 0);
John McCallf26e73d2016-03-11 04:30:43 +00004421 Builder.CreateStore(elt, eltAddr);
4422 }
John McCall12f23522016-04-04 18:33:08 +00004423 // FALLTHROUGH
Galina Kistanova0872d6c2017-06-03 06:30:46 +00004424 LLVM_FALLTHROUGH;
John McCall12f23522016-04-04 18:33:08 +00004425 }
4426
4427 case ABIArgInfo::InAlloca:
4428 case ABIArgInfo::Indirect: {
4429 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
George Burgess IV003be7c2018-03-08 05:32:30 +00004430 if (UnusedReturnSizePtr)
4431 PopCleanupBlock();
John McCall12f23522016-04-04 18:33:08 +00004432 return ret;
John McCallf26e73d2016-03-11 04:30:43 +00004433 }
4434
Hal Finkelee90a222014-09-26 05:04:30 +00004435 case ABIArgInfo::Ignore:
4436 // If we are ignoring an argument that had a result, make sure to
4437 // construct the appropriate return value for our caller.
4438 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004439
Hal Finkelee90a222014-09-26 05:04:30 +00004440 case ABIArgInfo::Extend:
4441 case ABIArgInfo::Direct: {
4442 llvm::Type *RetIRTy = ConvertType(RetTy);
4443 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
4444 switch (getEvaluationKind(RetTy)) {
4445 case TEK_Complex: {
4446 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
4447 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
4448 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004449 }
Hal Finkelee90a222014-09-26 05:04:30 +00004450 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00004451 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00004452 bool DestIsVolatile = ReturnValue.isVolatile();
4453
John McCall7f416cc2015-09-08 08:05:57 +00004454 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00004455 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
4456 DestIsVolatile = false;
4457 }
John McCall7f416cc2015-09-08 08:05:57 +00004458 BuildAggStore(*this, CI, DestPtr, DestIsVolatile);
Hal Finkelee90a222014-09-26 05:04:30 +00004459 return RValue::getAggregate(DestPtr);
4460 }
4461 case TEK_Scalar: {
4462 // If the argument doesn't match, perform a bitcast to coerce it. This
4463 // can happen due to trivial type mismatches.
4464 llvm::Value *V = CI;
4465 if (V->getType() != RetIRTy)
4466 V = Builder.CreateBitCast(V, RetIRTy);
4467 return RValue::get(V);
4468 }
4469 }
4470 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004471 }
Hal Finkelee90a222014-09-26 05:04:30 +00004472
John McCall7f416cc2015-09-08 08:05:57 +00004473 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00004474 bool DestIsVolatile = ReturnValue.isVolatile();
4475
John McCall7f416cc2015-09-08 08:05:57 +00004476 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00004477 DestPtr = CreateMemTemp(RetTy, "coerce");
4478 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00004479 }
Hal Finkelee90a222014-09-26 05:04:30 +00004480
4481 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00004482 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
4483 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Hal Finkelee90a222014-09-26 05:04:30 +00004484
4485 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004486 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004487
Hal Finkelee90a222014-09-26 05:04:30 +00004488 case ABIArgInfo::Expand:
4489 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00004490 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004491
Hal Finkelee90a222014-09-26 05:04:30 +00004492 llvm_unreachable("Unhandled ABIArgInfo::Kind");
4493 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004494
John McCallb92ab1a2016-10-26 23:46:34 +00004495 // Emit the assume_aligned check on the return value.
4496 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl();
Hal Finkelee90a222014-09-26 05:04:30 +00004497 if (Ret.isScalar() && TargetDecl) {
4498 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
4499 llvm::Value *OffsetValue = nullptr;
4500 if (const auto *Offset = AA->getOffset())
4501 OffsetValue = EmitScalarExpr(Offset);
4502
4503 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
4504 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
4505 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
4506 OffsetValue);
Erich Keane623efd82017-03-30 21:48:55 +00004507 } else if (const auto *AA = TargetDecl->getAttr<AllocAlignAttr>()) {
4508 llvm::Value *ParamVal =
Yaxun Liu5b330e82018-03-15 15:25:19 +00004509 CallArgs[AA->getParamIndex().getLLVMIndex()].getRValue(
4510 *this).getScalarVal();
Erich Keane623efd82017-03-30 21:48:55 +00004511 EmitAlignmentAssumption(Ret.getScalarVal(), ParamVal);
Hal Finkelee90a222014-09-26 05:04:30 +00004512 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00004513 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00004514
Hal Finkelee90a222014-09-26 05:04:30 +00004515 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00004516}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00004517
John McCall9831b842018-02-06 18:52:44 +00004518CGCallee CGCallee::prepareConcreteCallee(CodeGenFunction &CGF) const {
4519 if (isVirtual()) {
4520 const CallExpr *CE = getVirtualCallExpr();
4521 return CGF.CGM.getCXXABI().getVirtualFunctionPointer(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004522 CGF, getVirtualMethodDecl(), getThisAddress(), getFunctionType(),
4523 CE ? CE->getBeginLoc() : SourceLocation());
John McCall9831b842018-02-06 18:52:44 +00004524 }
4525
4526 return *this;
4527}
4528
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00004529/* VarArg handling */
4530
Charles Davisc7d5c942015-09-17 20:55:33 +00004531Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
4532 VAListAddr = VE->isMicrosoftABI()
4533 ? EmitMSVAListRef(VE->getSubExpr())
4534 : EmitVAListRef(VE->getSubExpr());
4535 QualType Ty = VE->getType();
4536 if (VE->isMicrosoftABI())
4537 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004538 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00004539}