blob: b589ae3f88fe6101cdec0d6c495383f60db73d74 [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CGCXXABI.h"
David Majnemer4e52d6f2015-12-12 05:39:21 +000018#include "CGCleanup.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000019#include "CodeGenFunction.h"
Daniel Dunbarc68897d2008-09-10 00:41:16 +000020#include "CodeGenModule.h"
John McCalla729c622012-02-17 03:33:10 +000021#include "TargetInfo.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000022#include "clang/AST/Decl.h"
Anders Carlssonb15b55c2009-04-03 22:48:58 +000023#include "clang/AST/DeclCXX.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000024#include "clang/AST/DeclObjC.h"
Eric Christopher15709992015-10-15 23:47:11 +000025#include "clang/Basic/TargetBuiltins.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000027#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000028#include "clang/Frontend/CodeGenOptions.h"
Bill Wendling706469b2013-02-28 22:49:57 +000029#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000030#include "llvm/IR/Attributes.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000031#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/InlineAsm.h"
Reid Kleckner314ef7b2014-02-01 00:04:45 +000034#include "llvm/IR/Intrinsics.h"
David Majnemerdc012fa2015-04-22 21:38:15 +000035#include "llvm/IR/IntrinsicInst.h"
Eli Friedmanf7456192011-06-15 22:09:18 +000036#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000037using namespace clang;
38using namespace CodeGen;
39
40/***/
41
John McCallab26cfa2010-02-05 21:31:56 +000042static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
43 switch (CC) {
44 default: return llvm::CallingConv::C;
45 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
46 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000047 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davisb5a214e2013-08-30 04:39:01 +000048 case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
49 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000050 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
51 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000052 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Reid Klecknerd7857f02014-10-24 17:42:17 +000053 // TODO: Add support for __pascal to LLVM.
54 case CC_X86Pascal: return llvm::CallingConv::C;
55 // TODO: Add support for __vectorcall to LLVM.
Reid Kleckner80944df2014-10-31 22:00:51 +000056 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
Alexander Kornienko21de0ae2015-01-20 11:20:41 +000057 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
58 case CC_SpirKernel: return llvm::CallingConv::SPIR_KERNEL;
John McCallab26cfa2010-02-05 21:31:56 +000059 }
60}
61
John McCall8ee376f2010-02-24 07:14:12 +000062/// Derives the 'this' type for codegen purposes, i.e. ignoring method
63/// qualification.
64/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000065static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
66 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
67 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000068}
69
John McCall8ee376f2010-02-24 07:14:12 +000070/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000071static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
72 return MD->getType()->getCanonicalTypeUnqualified()
73 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000074}
75
76/// Returns the "extra-canonicalized" return type, which discards
77/// qualifiers on the return type. Codegen doesn't care about them,
78/// and it makes ABI code a little easier to be able to assume that
79/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000080static CanQualType GetReturnType(QualType RetTy) {
81 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000082}
83
John McCall8dda7b22012-07-07 06:41:13 +000084/// Arrange the argument and result information for a value of the given
85/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000086const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000087CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000088 // When translating an unprototyped function type, always use a
89 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000090 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Peter Collingbournef7706832014-12-12 23:41:25 +000091 /*instanceMethod=*/false,
92 /*chainCall=*/false, None,
93 FTNP->getExtInfo(), RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +000094}
95
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000096/// Adds the formal paramaters in FPT to the given prefix. If any parameter in
97/// FPT has pass_object_size attrs, then we'll add parameters for those, too.
98static void appendParameterTypes(const CodeGenTypes &CGT,
99 SmallVectorImpl<CanQualType> &prefix,
100 const CanQual<FunctionProtoType> &FPT,
101 const FunctionDecl *FD) {
102 // Fast path: unknown target.
103 if (FD == nullptr) {
104 prefix.append(FPT->param_type_begin(), FPT->param_type_end());
105 return;
106 }
107
108 // In the vast majority cases, we'll have precisely FPT->getNumParams()
109 // parameters; the only thing that can change this is the presence of
110 // pass_object_size. So, we preallocate for the common case.
111 prefix.reserve(prefix.size() + FPT->getNumParams());
112
113 assert(FD->getNumParams() == FPT->getNumParams());
114 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
115 prefix.push_back(FPT->getParamType(I));
116 if (FD->getParamDecl(I)->hasAttr<PassObjectSizeAttr>())
117 prefix.push_back(CGT.getContext().getSizeType());
118 }
119}
120
John McCall8dda7b22012-07-07 06:41:13 +0000121/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000122/// type, on top of any implicit parameters already stored.
123static const CGFunctionInfo &
Peter Collingbournef7706832014-12-12 23:41:25 +0000124arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000125 SmallVectorImpl<CanQualType> &prefix,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000126 CanQual<FunctionProtoType> FTP,
127 const FunctionDecl *FD) {
John McCall8dda7b22012-07-07 06:41:13 +0000128 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000129 // FIXME: Kill copy.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000130 appendParameterTypes(CGT, prefix, FTP, FD);
Alp Toker314cc812014-01-25 16:55:45 +0000131 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
Peter Collingbournef7706832014-12-12 23:41:25 +0000132 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
133 /*chainCall=*/false, prefix,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000134 FTP->getExtInfo(), required);
John McCall8ee376f2010-02-24 07:14:12 +0000135}
136
John McCalla729c622012-02-17 03:33:10 +0000137/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000138/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000139const CGFunctionInfo &
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000140CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP,
141 const FunctionDecl *FD) {
John McCalla729c622012-02-17 03:33:10 +0000142 SmallVector<CanQualType, 16> argTypes;
Peter Collingbournef7706832014-12-12 23:41:25 +0000143 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000144 FTP, FD);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000145}
146
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000147static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000148 // Set the appropriate calling convention for the Function.
149 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000150 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000151
152 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000153 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000154
Douglas Gregora941dca2010-05-18 16:57:00 +0000155 if (D->hasAttr<ThisCallAttr>())
156 return CC_X86ThisCall;
157
Reid Klecknerd7857f02014-10-24 17:42:17 +0000158 if (D->hasAttr<VectorCallAttr>())
159 return CC_X86VectorCall;
160
Dawn Perchik335e16b2010-09-03 01:29:35 +0000161 if (D->hasAttr<PascalAttr>())
162 return CC_X86Pascal;
163
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000164 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
165 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
166
Guy Benyeif0a014b2012-12-25 08:53:55 +0000167 if (D->hasAttr<IntelOclBiccAttr>())
168 return CC_IntelOclBicc;
169
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000170 if (D->hasAttr<MSABIAttr>())
171 return IsWindows ? CC_C : CC_X86_64Win64;
172
173 if (D->hasAttr<SysVABIAttr>())
174 return IsWindows ? CC_X86_64SysV : CC_C;
175
John McCallab26cfa2010-02-05 21:31:56 +0000176 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000177}
178
John McCalla729c622012-02-17 03:33:10 +0000179/// Arrange the argument and result information for a call to an
180/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000181/// (Zero value of RD means we don't have any meaningful "this" argument type,
182/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000183/// The member function must be an ordinary function, i.e. not a
184/// constructor or destructor.
185const CGFunctionInfo &
186CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000187 const FunctionProtoType *FTP,
188 const CXXMethodDecl *MD) {
John McCalla729c622012-02-17 03:33:10 +0000189 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000190
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000191 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000192 if (RD)
193 argTypes.push_back(GetThisType(Context, RD));
194 else
195 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000196
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000197 return ::arrangeLLVMFunctionInfo(
198 *this, true, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000199 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>(), MD);
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000200}
201
John McCalla729c622012-02-17 03:33:10 +0000202/// Arrange the argument and result information for a declaration or
203/// definition of the given C++ non-static member function. The
204/// member function must be an ordinary function, i.e. not a
205/// constructor or destructor.
206const CGFunctionInfo &
207CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000208 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000209 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
210
John McCalla729c622012-02-17 03:33:10 +0000211 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000212
John McCalla729c622012-02-17 03:33:10 +0000213 if (MD->isInstance()) {
214 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000215 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000216 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
John McCalla729c622012-02-17 03:33:10 +0000217 }
218
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000219 return arrangeFreeFunctionType(prototype, MD);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000220}
221
John McCalla729c622012-02-17 03:33:10 +0000222const CGFunctionInfo &
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000223CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
224 StructorType Type) {
225
John McCalla729c622012-02-17 03:33:10 +0000226 SmallVector<CanQualType, 16> argTypes;
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000227 argTypes.push_back(GetThisType(Context, MD->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000228
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000229 GlobalDecl GD;
230 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
231 GD = GlobalDecl(CD, toCXXCtorType(Type));
232 } else {
233 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
234 GD = GlobalDecl(DD, toCXXDtorType(Type));
235 }
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000236
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000237 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall5d865c322010-08-31 07:33:07 +0000238
239 // Add the formal parameters.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000240 appendParameterTypes(*this, argTypes, FTP, MD);
John McCall5d865c322010-08-31 07:33:07 +0000241
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000242 TheCXXABI.buildStructorSignature(MD, Type, argTypes);
Reid Kleckner89077a12013-12-17 19:46:40 +0000243
244 RequiredArgs required =
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000245 (MD->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
Reid Kleckner89077a12013-12-17 19:46:40 +0000246
John McCall8dda7b22012-07-07 06:41:13 +0000247 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000248 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
249 ? argTypes.front()
250 : TheCXXABI.hasMostDerivedReturn(GD)
251 ? CGM.getContext().VoidPtrTy
252 : Context.VoidTy;
Peter Collingbournef7706832014-12-12 23:41:25 +0000253 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
254 /*chainCall=*/false, argTypes, extInfo,
255 required);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000256}
257
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000258/// Arrange a call to a C++ method, passing the given arguments.
259const CGFunctionInfo &
260CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
261 const CXXConstructorDecl *D,
262 CXXCtorType CtorKind,
263 unsigned ExtraArgs) {
264 // FIXME: Kill copy.
265 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000266 for (const auto &Arg : args)
267 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000268
269 CanQual<FunctionProtoType> FPT = GetFormalType(D);
270 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
271 GlobalDecl GD(D, CtorKind);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000272 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
273 ? ArgTypes.front()
274 : TheCXXABI.hasMostDerivedReturn(GD)
275 ? CGM.getContext().VoidPtrTy
276 : Context.VoidTy;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000277
278 FunctionType::ExtInfo Info = FPT->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000279 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
280 /*chainCall=*/false, ArgTypes, Info,
281 Required);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000282}
283
John McCalla729c622012-02-17 03:33:10 +0000284/// Arrange the argument and result information for the declaration or
285/// definition of the given function.
286const CGFunctionInfo &
287CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000288 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000289 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000290 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000291
John McCall2da83a32010-02-26 00:48:12 +0000292 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000293
John McCall2da83a32010-02-26 00:48:12 +0000294 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000295
296 // When declaring a function without a prototype, always use a
297 // non-variadic type.
298 if (isa<FunctionNoProtoType>(FTy)) {
299 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Peter Collingbournef7706832014-12-12 23:41:25 +0000300 return arrangeLLVMFunctionInfo(
301 noProto->getReturnType(), /*instanceMethod=*/false,
302 /*chainCall=*/false, None, noProto->getExtInfo(), RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000303 }
304
John McCall2da83a32010-02-26 00:48:12 +0000305 assert(isa<FunctionProtoType>(FTy));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000306 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>(), FD);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000307}
308
John McCalla729c622012-02-17 03:33:10 +0000309/// Arrange the argument and result information for the declaration or
310/// definition of an Objective-C method.
311const CGFunctionInfo &
312CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
313 // It happens that this is the same as a call with no optional
314 // arguments, except also using the formal 'self' type.
315 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
316}
317
318/// Arrange the argument and result information for the function type
319/// through which to perform a send to the given Objective-C method,
320/// using the given receiver type. The receiver type is not always
321/// the 'self' type of the method or even an Objective-C pointer type.
322/// This is *not* the right method for actually performing such a
323/// message send, due to the possibility of optional arguments.
324const CGFunctionInfo &
325CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
326 QualType receiverType) {
327 SmallVector<CanQualType, 16> argTys;
328 argTys.push_back(Context.getCanonicalParamType(receiverType));
329 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000330 // FIXME: Kill copy?
Aaron Ballman43b68be2014-03-07 17:50:17 +0000331 for (const auto *I : MD->params()) {
332 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000333 }
John McCall31168b02011-06-15 23:02:42 +0000334
335 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000336 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
337 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000338
David Blaikiebbafb8a2012-03-11 07:00:24 +0000339 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000340 MD->hasAttr<NSReturnsRetainedAttr>())
341 einfo = einfo.withProducesResult(true);
342
John McCalla729c622012-02-17 03:33:10 +0000343 RequiredArgs required =
344 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
345
Peter Collingbournef7706832014-12-12 23:41:25 +0000346 return arrangeLLVMFunctionInfo(
347 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
348 /*chainCall=*/false, argTys, einfo, required);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000349}
350
John McCalla729c622012-02-17 03:33:10 +0000351const CGFunctionInfo &
352CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000353 // FIXME: Do we need to handle ObjCMethodDecl?
354 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000355
Anders Carlsson6710c532010-02-06 02:44:09 +0000356 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000357 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
Anders Carlsson6710c532010-02-06 02:44:09 +0000358
359 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000360 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000361
John McCalla729c622012-02-17 03:33:10 +0000362 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000363}
364
Reid Klecknerc3473512014-08-29 21:43:29 +0000365/// Arrange a thunk that takes 'this' as the first parameter followed by
366/// varargs. Return a void pointer, regardless of the actual return type.
367/// The body of the thunk will end in a musttail call to a function of the
368/// correct type, and the caller will bitcast the function to the correct
369/// prototype.
370const CGFunctionInfo &
371CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
372 assert(MD->isVirtual() && "only virtual memptrs have thunks");
373 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
374 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
Peter Collingbournef7706832014-12-12 23:41:25 +0000375 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
376 /*chainCall=*/false, ArgTys,
Reid Klecknerc3473512014-08-29 21:43:29 +0000377 FTP->getExtInfo(), RequiredArgs(1));
378}
379
David Majnemerdfa6d202015-03-11 18:36:39 +0000380const CGFunctionInfo &
David Majnemer37fd66e2015-03-13 22:36:55 +0000381CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
382 CXXCtorType CT) {
383 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
384
David Majnemerdfa6d202015-03-11 18:36:39 +0000385 CanQual<FunctionProtoType> FTP = GetFormalType(CD);
386 SmallVector<CanQualType, 2> ArgTys;
387 const CXXRecordDecl *RD = CD->getParent();
388 ArgTys.push_back(GetThisType(Context, RD));
David Majnemer37fd66e2015-03-13 22:36:55 +0000389 if (CT == Ctor_CopyingClosure)
390 ArgTys.push_back(*FTP->param_type_begin());
David Majnemerdfa6d202015-03-11 18:36:39 +0000391 if (RD->getNumVBases() > 0)
392 ArgTys.push_back(Context.IntTy);
393 CallingConv CC = Context.getDefaultCallingConvention(
394 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
395 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
396 /*chainCall=*/false, ArgTys,
397 FunctionType::ExtInfo(CC), RequiredArgs::All);
398}
399
John McCallc818bbb2012-12-07 07:03:17 +0000400/// Arrange a call as unto a free function, except possibly with an
401/// additional number of formal parameters considered required.
402static const CGFunctionInfo &
403arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000404 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000405 const CallArgList &args,
406 const FunctionType *fnType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000407 unsigned numExtraRequiredArgs,
408 bool chainCall) {
John McCallc818bbb2012-12-07 07:03:17 +0000409 assert(args.size() >= numExtraRequiredArgs);
410
411 // In most cases, there are no optional arguments.
412 RequiredArgs required = RequiredArgs::All;
413
414 // If we have a variadic prototype, the required arguments are the
415 // extra prefix plus the arguments in the prototype.
416 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
417 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000418 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000419
420 // If we don't have a prototype at all, but we're supposed to
421 // explicitly use the variadic convention for unprototyped calls,
422 // treat all of the arguments as required but preserve the nominal
423 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000424 } else if (CGM.getTargetCodeGenInfo()
425 .isNoProtoCallVariadic(args,
426 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000427 required = RequiredArgs(args.size());
428 }
429
Peter Collingbournef7706832014-12-12 23:41:25 +0000430 // FIXME: Kill copy.
431 SmallVector<CanQualType, 16> argTypes;
432 for (const auto &arg : args)
433 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
434 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
435 /*instanceMethod=*/false, chainCall,
436 argTypes, fnType->getExtInfo(), required);
John McCallc818bbb2012-12-07 07:03:17 +0000437}
438
John McCalla729c622012-02-17 03:33:10 +0000439/// Figure out the rules for calling a function with the given formal
440/// type using the given arguments. The arguments are necessary
441/// because the function might be unprototyped, in which case it's
442/// target-dependent in crazy ways.
443const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000444CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
Peter Collingbournef7706832014-12-12 23:41:25 +0000445 const FunctionType *fnType,
446 bool chainCall) {
447 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
448 chainCall ? 1 : 0, chainCall);
John McCallc818bbb2012-12-07 07:03:17 +0000449}
John McCalla729c622012-02-17 03:33:10 +0000450
John McCallc818bbb2012-12-07 07:03:17 +0000451/// A block function call is essentially a free-function call with an
452/// extra implicit argument.
453const CGFunctionInfo &
454CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
455 const FunctionType *fnType) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000456 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
457 /*chainCall=*/false);
John McCalla729c622012-02-17 03:33:10 +0000458}
459
460const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000461CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
462 const CallArgList &args,
463 FunctionType::ExtInfo info,
464 RequiredArgs required) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000465 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000466 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000467 for (const auto &Arg : args)
468 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Peter Collingbournef7706832014-12-12 23:41:25 +0000469 return arrangeLLVMFunctionInfo(
470 GetReturnType(resultType), /*instanceMethod=*/false,
471 /*chainCall=*/false, argTypes, info, required);
John McCall8dda7b22012-07-07 06:41:13 +0000472}
473
474/// Arrange a call to a C++ method, passing the given arguments.
475const CGFunctionInfo &
476CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
477 const FunctionProtoType *FPT,
478 RequiredArgs required) {
479 // FIXME: Kill copy.
480 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000481 for (const auto &Arg : args)
482 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
John McCall8dda7b22012-07-07 06:41:13 +0000483
484 FunctionType::ExtInfo info = FPT->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000485 return arrangeLLVMFunctionInfo(
486 GetReturnType(FPT->getReturnType()), /*instanceMethod=*/true,
487 /*chainCall=*/false, argTypes, info, required);
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000488}
489
Reid Kleckner4982b822014-01-31 22:54:50 +0000490const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
491 QualType resultType, const FunctionArgList &args,
492 const FunctionType::ExtInfo &info, bool isVariadic) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000493 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000494 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000495 for (auto Arg : args)
496 argTypes.push_back(Context.getCanonicalParamType(Arg->getType()));
John McCalla729c622012-02-17 03:33:10 +0000497
498 RequiredArgs required =
499 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
Peter Collingbournef7706832014-12-12 23:41:25 +0000500 return arrangeLLVMFunctionInfo(
501 GetReturnType(resultType), /*instanceMethod=*/false,
502 /*chainCall=*/false, argTypes, info, required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000503}
504
John McCalla729c622012-02-17 03:33:10 +0000505const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Peter Collingbournef7706832014-12-12 23:41:25 +0000506 return arrangeLLVMFunctionInfo(
507 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
508 None, FunctionType::ExtInfo(), RequiredArgs::All);
John McCalla738c252011-03-09 04:27:21 +0000509}
510
John McCalla729c622012-02-17 03:33:10 +0000511/// Arrange the argument and result information for an abstract value
512/// of a given function type. This is the method which all of the
513/// above functions ultimately defer to.
514const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000515CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000516 bool instanceMethod,
517 bool chainCall,
John McCall8dda7b22012-07-07 06:41:13 +0000518 ArrayRef<CanQualType> argTypes,
519 FunctionType::ExtInfo info,
520 RequiredArgs required) {
Saleem Abdulrasool32d1a962014-11-25 03:49:50 +0000521 assert(std::all_of(argTypes.begin(), argTypes.end(),
522 std::mem_fun_ref(&CanQualType::isCanonicalAsParam)));
John McCall2da83a32010-02-26 00:48:12 +0000523
John McCalla729c622012-02-17 03:33:10 +0000524 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCallab26cfa2010-02-05 21:31:56 +0000525
Daniel Dunbare0be8292009-02-03 00:07:12 +0000526 // Lookup or create unique function info.
527 llvm::FoldingSetNodeID ID;
Peter Collingbournef7706832014-12-12 23:41:25 +0000528 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, required,
529 resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000530
Craig Topper8a13c412014-05-21 05:09:00 +0000531 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000532 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000533 if (FI)
534 return *FI;
535
John McCalla729c622012-02-17 03:33:10 +0000536 // Construct the function info. We co-allocate the ArgInfos.
Peter Collingbournef7706832014-12-12 23:41:25 +0000537 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
538 resultType, argTypes, required);
John McCalla729c622012-02-17 03:33:10 +0000539 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000540
David Blaikie82e95a32014-11-19 07:49:47 +0000541 bool inserted = FunctionsBeingProcessed.insert(FI).second;
542 (void)inserted;
John McCalla729c622012-02-17 03:33:10 +0000543 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000544
Daniel Dunbar313321e2009-02-03 05:31:23 +0000545 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000546 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000547
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000548 // Loop over all of the computed argument and return value info. If any of
549 // them are direct or extend without a specified coerce type, specify the
550 // default now.
John McCalla729c622012-02-17 03:33:10 +0000551 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000552 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000553 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000554
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000555 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000556 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000557 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000558
John McCalla729c622012-02-17 03:33:10 +0000559 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
560 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000561
Daniel Dunbare0be8292009-02-03 00:07:12 +0000562 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000563}
564
John McCalla729c622012-02-17 03:33:10 +0000565CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Peter Collingbournef7706832014-12-12 23:41:25 +0000566 bool instanceMethod,
567 bool chainCall,
John McCalla729c622012-02-17 03:33:10 +0000568 const FunctionType::ExtInfo &info,
569 CanQualType resultType,
570 ArrayRef<CanQualType> argTypes,
571 RequiredArgs required) {
572 void *buffer = operator new(sizeof(CGFunctionInfo) +
573 sizeof(ArgInfo) * (argTypes.size() + 1));
574 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
575 FI->CallingConvention = llvmCC;
576 FI->EffectiveCallingConvention = llvmCC;
577 FI->ASTCallingConvention = info.getCC();
Peter Collingbournef7706832014-12-12 23:41:25 +0000578 FI->InstanceMethod = instanceMethod;
579 FI->ChainCall = chainCall;
John McCalla729c622012-02-17 03:33:10 +0000580 FI->NoReturn = info.getNoReturn();
581 FI->ReturnsRetained = info.getProducesResult();
582 FI->Required = required;
583 FI->HasRegParm = info.getHasRegParm();
584 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000585 FI->ArgStruct = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +0000586 FI->ArgStructAlign = 0;
John McCalla729c622012-02-17 03:33:10 +0000587 FI->NumArgs = argTypes.size();
588 FI->getArgsBuffer()[0].type = resultType;
589 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
590 FI->getArgsBuffer()[i + 1].type = argTypes[i];
591 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000592}
593
594/***/
595
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000596namespace {
597// ABIArgInfo::Expand implementation.
598
599// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
600struct TypeExpansion {
601 enum TypeExpansionKind {
602 // Elements of constant arrays are expanded recursively.
603 TEK_ConstantArray,
604 // Record fields are expanded recursively (but if record is a union, only
605 // the field with the largest size is expanded).
606 TEK_Record,
607 // For complex types, real and imaginary parts are expanded recursively.
608 TEK_Complex,
609 // All other types are not expandable.
610 TEK_None
611 };
612
613 const TypeExpansionKind Kind;
614
615 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000616 virtual ~TypeExpansion() {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000617};
618
619struct ConstantArrayExpansion : TypeExpansion {
620 QualType EltTy;
621 uint64_t NumElts;
622
623 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
624 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
625 static bool classof(const TypeExpansion *TE) {
626 return TE->Kind == TEK_ConstantArray;
627 }
628};
629
630struct RecordExpansion : TypeExpansion {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000631 SmallVector<const CXXBaseSpecifier *, 1> Bases;
632
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000633 SmallVector<const FieldDecl *, 1> Fields;
634
Reid Klecknere9f6a712014-10-31 17:10:41 +0000635 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
636 SmallVector<const FieldDecl *, 1> &&Fields)
637 : TypeExpansion(TEK_Record), Bases(Bases), Fields(Fields) {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000638 static bool classof(const TypeExpansion *TE) {
639 return TE->Kind == TEK_Record;
640 }
641};
642
643struct ComplexExpansion : TypeExpansion {
644 QualType EltTy;
645
646 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
647 static bool classof(const TypeExpansion *TE) {
648 return TE->Kind == TEK_Complex;
649 }
650};
651
652struct NoExpansion : TypeExpansion {
653 NoExpansion() : TypeExpansion(TEK_None) {}
654 static bool classof(const TypeExpansion *TE) {
655 return TE->Kind == TEK_None;
656 }
657};
658} // namespace
659
660static std::unique_ptr<TypeExpansion>
661getTypeExpansion(QualType Ty, const ASTContext &Context) {
662 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
663 return llvm::make_unique<ConstantArrayExpansion>(
664 AT->getElementType(), AT->getSize().getZExtValue());
665 }
666 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000667 SmallVector<const CXXBaseSpecifier *, 1> Bases;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000668 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000669 const RecordDecl *RD = RT->getDecl();
670 assert(!RD->hasFlexibleArrayMember() &&
671 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000672 if (RD->isUnion()) {
673 // Unions can be here only in degenerative cases - all the fields are same
674 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000675 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000676 CharUnits UnionSize = CharUnits::Zero();
677
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000678 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000679 // Skip zero length bitfields.
680 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
681 continue;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000682 assert(!FD->isBitField() &&
683 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000684 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000685 if (UnionSize < FieldSize) {
686 UnionSize = FieldSize;
687 LargestFD = FD;
688 }
689 }
690 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000691 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000692 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000693 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
694 assert(!CXXRD->isDynamicClass() &&
695 "cannot expand vtable pointers in dynamic classes");
696 for (const CXXBaseSpecifier &BS : CXXRD->bases())
697 Bases.push_back(&BS);
698 }
699
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000700 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000701 // Skip zero length bitfields.
702 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
703 continue;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000704 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000705 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000706 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000707 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000708 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000709 return llvm::make_unique<RecordExpansion>(std::move(Bases),
710 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000711 }
712 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
713 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
714 }
715 return llvm::make_unique<NoExpansion>();
716}
717
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000718static int getExpansionSize(QualType Ty, const ASTContext &Context) {
719 auto Exp = getTypeExpansion(Ty, Context);
720 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
721 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
722 }
723 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
724 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000725 for (auto BS : RExp->Bases)
726 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000727 for (auto FD : RExp->Fields)
728 Res += getExpansionSize(FD->getType(), Context);
729 return Res;
730 }
731 if (isa<ComplexExpansion>(Exp.get()))
732 return 2;
733 assert(isa<NoExpansion>(Exp.get()));
734 return 1;
735}
736
Alexey Samsonov153004f2014-09-29 22:08:00 +0000737void
738CodeGenTypes::getExpandedTypes(QualType Ty,
739 SmallVectorImpl<llvm::Type *>::iterator &TI) {
740 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000741 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
742 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000743 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000744 }
745 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000746 for (auto BS : RExp->Bases)
747 getExpandedTypes(BS->getType(), TI);
748 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000749 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000750 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
751 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000752 *TI++ = EltTy;
753 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000754 } else {
755 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000756 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000757 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000758}
759
John McCall7f416cc2015-09-08 08:05:57 +0000760static void forConstantArrayExpansion(CodeGenFunction &CGF,
761 ConstantArrayExpansion *CAE,
762 Address BaseAddr,
763 llvm::function_ref<void(Address)> Fn) {
764 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
765 CharUnits EltAlign =
766 BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
767
768 for (int i = 0, n = CAE->NumElts; i < n; i++) {
769 llvm::Value *EltAddr =
770 CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
771 Fn(Address(EltAddr, EltAlign));
772 }
773}
774
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000775void CodeGenFunction::ExpandTypeFromArgs(
776 QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000777 assert(LV.isSimple() &&
778 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000779
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000780 auto Exp = getTypeExpansion(Ty, getContext());
781 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000782 forConstantArrayExpansion(*this, CAExp, LV.getAddress(),
783 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000784 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
785 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
John McCall7f416cc2015-09-08 08:05:57 +0000786 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000787 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000788 Address This = LV.getAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000789 for (const CXXBaseSpecifier *BS : RExp->Bases) {
790 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +0000791 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +0000792 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
793 /*NullCheckValue=*/false, SourceLocation());
794 LValue SubLV = MakeAddrLValue(Base, BS->getType());
795
796 // Recurse onto bases.
797 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
798 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000799 for (auto FD : RExp->Fields) {
800 // FIXME: What are the right qualifiers here?
801 LValue SubLV = EmitLValueForField(LV, FD);
802 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000803 }
John McCall7f416cc2015-09-08 08:05:57 +0000804 } else if (isa<ComplexExpansion>(Exp.get())) {
805 auto realValue = *AI++;
806 auto imagValue = *AI++;
807 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000808 } else {
809 assert(isa<NoExpansion>(Exp.get()));
810 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000811 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000812}
813
814void CodeGenFunction::ExpandTypeToArgs(
815 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
816 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
817 auto Exp = getTypeExpansion(Ty, getContext());
818 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000819 forConstantArrayExpansion(*this, CAExp, RV.getAggregateAddress(),
820 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000821 RValue EltRV =
822 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
823 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
John McCall7f416cc2015-09-08 08:05:57 +0000824 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000825 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000826 Address This = RV.getAggregateAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000827 for (const CXXBaseSpecifier *BS : RExp->Bases) {
828 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +0000829 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +0000830 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
831 /*NullCheckValue=*/false, SourceLocation());
832 RValue BaseRV = RValue::getAggregate(Base);
833
834 // Recurse onto bases.
835 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
836 IRCallArgPos);
837 }
838
839 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000840 for (auto FD : RExp->Fields) {
841 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
842 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
843 IRCallArgPos);
844 }
845 } else if (isa<ComplexExpansion>(Exp.get())) {
846 ComplexPairTy CV = RV.getComplexVal();
847 IRCallArgs[IRCallArgPos++] = CV.first;
848 IRCallArgs[IRCallArgPos++] = CV.second;
849 } else {
850 assert(isa<NoExpansion>(Exp.get()));
851 assert(RV.isScalar() &&
852 "Unexpected non-scalar rvalue during struct expansion.");
853
854 // Insert a bitcast as needed.
855 llvm::Value *V = RV.getScalarVal();
856 if (IRCallArgPos < IRFuncTy->getNumParams() &&
857 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
858 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
859
860 IRCallArgs[IRCallArgPos++] = V;
861 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000862}
863
John McCall7f416cc2015-09-08 08:05:57 +0000864/// Create a temporary allocation for the purposes of coercion.
865static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
866 CharUnits MinAlign) {
867 // Don't use an alignment that's worse than what LLVM would prefer.
868 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
869 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
870
871 return CGF.CreateTempAlloca(Ty, Align);
872}
873
Chris Lattner895c52b2010-06-27 06:04:18 +0000874/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000875/// accessing some number of bytes out of it, try to gep into the struct to get
876/// at its inner goodness. Dive as deep as possible without entering an element
877/// with an in-memory size smaller than DstSize.
John McCall7f416cc2015-09-08 08:05:57 +0000878static Address
879EnterStructPointerForCoercedAccess(Address SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000880 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000881 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000882 // We can't dive into a zero-element struct.
883 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000884
Chris Lattner2192fe52011-07-18 04:24:23 +0000885 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000886
Chris Lattner1cd66982010-06-27 05:56:15 +0000887 // 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 +0000888 // first element is the same size as the whole struct, we can enter it. The
889 // comparison must be made on the store size and not the alloca size. Using
890 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000891 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +0000892 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000893 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +0000894 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000895 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000896
Chris Lattner1cd66982010-06-27 05:56:15 +0000897 // GEP into the first element.
John McCall7f416cc2015-09-08 08:05:57 +0000898 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, CharUnits(), "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000899
Chris Lattner1cd66982010-06-27 05:56:15 +0000900 // If the first element is a struct, recurse.
John McCall7f416cc2015-09-08 08:05:57 +0000901 llvm::Type *SrcTy = SrcPtr.getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000902 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000903 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000904
905 return SrcPtr;
906}
907
Chris Lattner055097f2010-06-27 06:26:04 +0000908/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
909/// are either integers or pointers. This does a truncation of the value if it
910/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000911///
912/// This behaves as if the value were coerced through memory, so on big-endian
913/// targets the high bits are preserved in a truncation, while little-endian
914/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000915static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000916 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000917 CodeGenFunction &CGF) {
918 if (Val->getType() == Ty)
919 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000920
Chris Lattner055097f2010-06-27 06:26:04 +0000921 if (isa<llvm::PointerType>(Val->getType())) {
922 // If this is Pointer->Pointer avoid conversion to and from int.
923 if (isa<llvm::PointerType>(Ty))
924 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000925
Chris Lattner055097f2010-06-27 06:26:04 +0000926 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000927 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000928 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000929
Chris Lattner2192fe52011-07-18 04:24:23 +0000930 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000931 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000932 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000933
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000934 if (Val->getType() != DestIntTy) {
935 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
936 if (DL.isBigEndian()) {
937 // Preserve the high bits on big-endian targets.
938 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +0000939 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
940 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
941
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000942 if (SrcSize > DstSize) {
943 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
944 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
945 } else {
946 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
947 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
948 }
949 } else {
950 // Little-endian targets preserve the low bits. No shifts required.
951 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
952 }
953 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000954
Chris Lattner055097f2010-06-27 06:26:04 +0000955 if (isa<llvm::PointerType>(Ty))
956 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
957 return Val;
958}
959
Chris Lattner1cd66982010-06-27 05:56:15 +0000960
961
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000962/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
Ulrich Weigand6e2cea62015-07-10 11:31:43 +0000963/// a pointer to an object of type \arg Ty, known to be aligned to
964/// \arg SrcAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000965///
966/// This safely handles the case when the src type is smaller than the
967/// destination type; in this situation the values of bits which not
968/// present in the src are undefined.
John McCall7f416cc2015-09-08 08:05:57 +0000969static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000970 CodeGenFunction &CGF) {
John McCall7f416cc2015-09-08 08:05:57 +0000971 llvm::Type *SrcTy = Src.getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000972
Chris Lattnerd200eda2010-06-28 22:51:39 +0000973 // If SrcTy and Ty are the same, just do a load.
974 if (SrcTy == Ty)
John McCall7f416cc2015-09-08 08:05:57 +0000975 return CGF.Builder.CreateLoad(Src);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000976
Micah Villmowdd31ca12012-10-08 16:25:52 +0000977 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000978
Chris Lattner2192fe52011-07-18 04:24:23 +0000979 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
John McCall7f416cc2015-09-08 08:05:57 +0000980 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF);
981 SrcTy = Src.getType()->getElementType();
Chris Lattner1cd66982010-06-27 05:56:15 +0000982 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000983
Micah Villmowdd31ca12012-10-08 16:25:52 +0000984 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000985
Chris Lattner055097f2010-06-27 06:26:04 +0000986 // If the source and destination are integer or pointer types, just do an
987 // extension or truncation to the desired type.
988 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
989 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
John McCall7f416cc2015-09-08 08:05:57 +0000990 llvm::Value *Load = CGF.Builder.CreateLoad(Src);
Chris Lattner055097f2010-06-27 06:26:04 +0000991 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
992 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000993
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000994 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000995 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000996 // Generally SrcSize is never greater than DstSize, since this means we are
997 // losing bits. However, this can happen in cases where the structure has
998 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000999 //
Mike Stump18bb9282009-05-16 07:57:57 +00001000 // FIXME: Assert that we aren't truncating non-padding bits when have access
1001 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001002 Src = CGF.Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(Ty));
1003 return CGF.Builder.CreateLoad(Src);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001004 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001005
John McCall7f416cc2015-09-08 08:05:57 +00001006 // Otherwise do coercion through memory. This is stupid, but simple.
1007 Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment());
1008 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1009 Address SrcCasted = CGF.Builder.CreateBitCast(Src, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001010 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
1011 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
John McCall7f416cc2015-09-08 08:05:57 +00001012 false);
1013 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001014}
1015
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001016// Function to store a first-class aggregate into memory. We prefer to
1017// store the elements rather than the aggregate to be more friendly to
1018// fast-isel.
1019// FIXME: Do we need to recurse here?
1020static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
John McCall7f416cc2015-09-08 08:05:57 +00001021 Address Dest, bool DestIsVolatile) {
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001022 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +00001023 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001024 dyn_cast<llvm::StructType>(Val->getType())) {
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001025 const llvm::StructLayout *Layout =
1026 CGF.CGM.getDataLayout().getStructLayout(STy);
1027
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001028 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00001029 auto EltOffset = CharUnits::fromQuantity(Layout->getElementOffset(i));
1030 Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i, EltOffset);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001031 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
John McCall7f416cc2015-09-08 08:05:57 +00001032 CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001033 }
1034 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001035 CGF.Builder.CreateStore(Val, Dest, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001036 }
1037}
1038
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001039/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001040/// where the source and destination may have different types. The
1041/// destination is known to be aligned to \arg DstAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001042///
1043/// This safely handles the case when the src type is larger than the
1044/// destination type; the upper bits of the src will be lost.
1045static void CreateCoercedStore(llvm::Value *Src,
John McCall7f416cc2015-09-08 08:05:57 +00001046 Address Dst,
Anders Carlsson17490832009-12-24 20:40:36 +00001047 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001048 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001049 llvm::Type *SrcTy = Src->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001050 llvm::Type *DstTy = Dst.getType()->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +00001051 if (SrcTy == DstTy) {
John McCall7f416cc2015-09-08 08:05:57 +00001052 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattnerd200eda2010-06-28 22:51:39 +00001053 return;
1054 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001055
Micah Villmowdd31ca12012-10-08 16:25:52 +00001056 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001057
Chris Lattner2192fe52011-07-18 04:24:23 +00001058 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001059 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF);
1060 DstTy = Dst.getType()->getElementType();
Chris Lattner895c52b2010-06-27 06:04:18 +00001061 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001062
Chris Lattner055097f2010-06-27 06:26:04 +00001063 // If the source and destination are integer or pointer types, just do an
1064 // extension or truncation to the desired type.
1065 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1066 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1067 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001068 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattner055097f2010-06-27 06:26:04 +00001069 return;
1070 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001071
Micah Villmowdd31ca12012-10-08 16:25:52 +00001072 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001073
Daniel Dunbar313321e2009-02-03 05:31:23 +00001074 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001075 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00001076 Dst = CGF.Builder.CreateBitCast(Dst, llvm::PointerType::getUnqual(SrcTy));
1077 BuildAggStore(CGF, Src, Dst, DstIsVolatile);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001078 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001079 // Otherwise do coercion through memory. This is stupid, but
1080 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001081
1082 // Generally SrcSize is never greater than DstSize, since this means we are
1083 // losing bits. However, this can happen in cases where the structure has
1084 // additional padding, for example due to a user specified alignment.
1085 //
1086 // FIXME: Assert that we aren't truncating non-padding bits when have access
1087 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001088 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1089 CGF.Builder.CreateStore(Src, Tmp);
1090 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1091 Address DstCasted = CGF.Builder.CreateBitCast(Dst, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001092 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1093 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
John McCall7f416cc2015-09-08 08:05:57 +00001094 false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001095 }
1096}
1097
John McCall7f416cc2015-09-08 08:05:57 +00001098static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
1099 const ABIArgInfo &info) {
1100 if (unsigned offset = info.getDirectOffset()) {
1101 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
1102 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1103 CharUnits::fromQuantity(offset));
1104 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
1105 }
1106 return addr;
1107}
1108
Alexey Samsonov153004f2014-09-29 22:08:00 +00001109namespace {
1110
1111/// Encapsulates information about the way function arguments from
1112/// CGFunctionInfo should be passed to actual LLVM IR function.
1113class ClangToLLVMArgMapping {
1114 static const unsigned InvalidIndex = ~0U;
1115 unsigned InallocaArgNo;
1116 unsigned SRetArgNo;
1117 unsigned TotalIRArgs;
1118
1119 /// Arguments of LLVM IR function corresponding to single Clang argument.
1120 struct IRArgs {
1121 unsigned PaddingArgIndex;
1122 // Argument is expanded to IR arguments at positions
1123 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1124 unsigned FirstArgIndex;
1125 unsigned NumberOfArgs;
1126
1127 IRArgs()
1128 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1129 NumberOfArgs(0) {}
1130 };
1131
1132 SmallVector<IRArgs, 8> ArgInfo;
1133
1134public:
1135 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1136 bool OnlyRequiredArgs = false)
1137 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1138 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1139 construct(Context, FI, OnlyRequiredArgs);
1140 }
1141
1142 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1143 unsigned getInallocaArgNo() const {
1144 assert(hasInallocaArg());
1145 return InallocaArgNo;
1146 }
1147
1148 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1149 unsigned getSRetArgNo() const {
1150 assert(hasSRetArg());
1151 return SRetArgNo;
1152 }
1153
1154 unsigned totalIRArgs() const { return TotalIRArgs; }
1155
1156 bool hasPaddingArg(unsigned ArgNo) const {
1157 assert(ArgNo < ArgInfo.size());
1158 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1159 }
1160 unsigned getPaddingArgNo(unsigned ArgNo) const {
1161 assert(hasPaddingArg(ArgNo));
1162 return ArgInfo[ArgNo].PaddingArgIndex;
1163 }
1164
1165 /// Returns index of first IR argument corresponding to ArgNo, and their
1166 /// quantity.
1167 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1168 assert(ArgNo < ArgInfo.size());
1169 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1170 ArgInfo[ArgNo].NumberOfArgs);
1171 }
1172
1173private:
1174 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1175 bool OnlyRequiredArgs);
1176};
1177
1178void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1179 const CGFunctionInfo &FI,
1180 bool OnlyRequiredArgs) {
1181 unsigned IRArgNo = 0;
1182 bool SwapThisWithSRet = false;
1183 const ABIArgInfo &RetAI = FI.getReturnInfo();
1184
1185 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1186 SwapThisWithSRet = RetAI.isSRetAfterThis();
1187 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1188 }
1189
1190 unsigned ArgNo = 0;
1191 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1192 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1193 ++I, ++ArgNo) {
1194 assert(I != FI.arg_end());
1195 QualType ArgType = I->type;
1196 const ABIArgInfo &AI = I->info;
1197 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1198 auto &IRArgs = ArgInfo[ArgNo];
1199
1200 if (AI.getPaddingType())
1201 IRArgs.PaddingArgIndex = IRArgNo++;
1202
1203 switch (AI.getKind()) {
1204 case ABIArgInfo::Extend:
1205 case ABIArgInfo::Direct: {
1206 // FIXME: handle sseregparm someday...
1207 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1208 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1209 IRArgs.NumberOfArgs = STy->getNumElements();
1210 } else {
1211 IRArgs.NumberOfArgs = 1;
1212 }
1213 break;
1214 }
1215 case ABIArgInfo::Indirect:
1216 IRArgs.NumberOfArgs = 1;
1217 break;
1218 case ABIArgInfo::Ignore:
1219 case ABIArgInfo::InAlloca:
1220 // ignore and inalloca doesn't have matching LLVM parameters.
1221 IRArgs.NumberOfArgs = 0;
1222 break;
1223 case ABIArgInfo::Expand: {
1224 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1225 break;
1226 }
1227 }
1228
1229 if (IRArgs.NumberOfArgs > 0) {
1230 IRArgs.FirstArgIndex = IRArgNo;
1231 IRArgNo += IRArgs.NumberOfArgs;
1232 }
1233
1234 // Skip over the sret parameter when it comes second. We already handled it
1235 // above.
1236 if (IRArgNo == 1 && SwapThisWithSRet)
1237 IRArgNo++;
1238 }
1239 assert(ArgNo == ArgInfo.size());
1240
1241 if (FI.usesInAlloca())
1242 InallocaArgNo = IRArgNo++;
1243
1244 TotalIRArgs = IRArgNo;
1245}
1246} // namespace
1247
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001248/***/
1249
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001250bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001251 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001252}
1253
Tim Northovere77cc392014-03-29 13:28:05 +00001254bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1255 return ReturnTypeUsesSRet(FI) &&
1256 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1257}
1258
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001259bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1260 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1261 switch (BT->getKind()) {
1262 default:
1263 return false;
1264 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001265 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001266 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001267 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001268 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001269 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001270 }
1271 }
1272
1273 return false;
1274}
1275
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001276bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1277 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1278 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1279 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001280 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001281 }
1282 }
1283
1284 return false;
1285}
1286
Chris Lattnera5f58b02011-07-09 17:41:47 +00001287llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001288 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1289 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001290}
1291
Chris Lattnera5f58b02011-07-09 17:41:47 +00001292llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001293CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001294
David Blaikie82e95a32014-11-19 07:49:47 +00001295 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1296 (void)Inserted;
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001297 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001298
Alexey Samsonov153004f2014-09-29 22:08:00 +00001299 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001300 const ABIArgInfo &retAI = FI.getReturnInfo();
1301 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001302 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001303 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001304
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001305 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001306 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001307 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001308 break;
1309
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001310 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001311 if (retAI.getInAllocaSRet()) {
1312 // sret things on win32 aren't void, they return the sret pointer.
1313 QualType ret = FI.getReturnType();
1314 llvm::Type *ty = ConvertType(ret);
1315 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1316 resultType = llvm::PointerType::get(ty, addressSpace);
1317 } else {
1318 resultType = llvm::Type::getVoidTy(getLLVMContext());
1319 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001320 break;
1321
John McCall7f416cc2015-09-08 08:05:57 +00001322 case ABIArgInfo::Indirect:
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001323 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001324 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001325 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001326 }
Mike Stump11289f42009-09-09 15:08:12 +00001327
Alexey Samsonov153004f2014-09-29 22:08:00 +00001328 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1329 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1330
1331 // Add type for sret argument.
1332 if (IRFunctionArgs.hasSRetArg()) {
1333 QualType Ret = FI.getReturnType();
1334 llvm::Type *Ty = ConvertType(Ret);
1335 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1336 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1337 llvm::PointerType::get(Ty, AddressSpace);
1338 }
1339
1340 // Add type for inalloca argument.
1341 if (IRFunctionArgs.hasInallocaArg()) {
1342 auto ArgStruct = FI.getArgStruct();
1343 assert(ArgStruct);
1344 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1345 }
1346
John McCallc818bbb2012-12-07 07:03:17 +00001347 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001348 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001349 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1350 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001351 for (; it != ie; ++it, ++ArgNo) {
1352 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001353
Rafael Espindolafad28de2012-10-24 01:59:00 +00001354 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001355 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1356 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1357 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001358
Alexey Samsonov153004f2014-09-29 22:08:00 +00001359 unsigned FirstIRArg, NumIRArgs;
1360 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1361
1362 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001363 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001364 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001365 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001366 break;
1367
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001368 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001369 assert(NumIRArgs == 1);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001370 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001371 llvm::Type *LTy = ConvertTypeForMem(it->type);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001372 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001373 break;
1374 }
1375
1376 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001377 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001378 // Fast-isel and the optimizer generally like scalar values better than
1379 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001380 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001381 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001382 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1383 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001384 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001385 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001386 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001387 assert(NumIRArgs == 1);
1388 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001389 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001390 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001391 }
Mike Stump11289f42009-09-09 15:08:12 +00001392
Daniel Dunbard3674e62008-09-11 01:48:57 +00001393 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001394 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1395 getExpandedTypes(it->type, ArgTypesIter);
1396 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001397 break;
1398 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001399 }
1400
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001401 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1402 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001403
1404 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001405}
1406
Chris Lattner2192fe52011-07-18 04:24:23 +00001407llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001408 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001409 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001410
Chris Lattner8806e322011-07-10 00:18:59 +00001411 if (!isFuncTypeConvertible(FPT))
1412 return llvm::StructType::get(getLLVMContext());
1413
1414 const CGFunctionInfo *Info;
1415 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001416 Info =
1417 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001418 else
John McCalla729c622012-02-17 03:33:10 +00001419 Info = &arrangeCXXMethodDeclaration(MD);
1420 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001421}
1422
Samuel Antao798f11c2015-11-23 22:04:44 +00001423static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
1424 llvm::AttrBuilder &FuncAttrs,
1425 const FunctionProtoType *FPT) {
1426 if (!FPT)
1427 return;
1428
1429 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
1430 FPT->isNothrow(Ctx))
1431 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1432}
1433
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001434void CodeGenModule::ConstructAttributeList(
1435 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo,
1436 AttributeListType &PAL, unsigned &CallingConv, bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001437 llvm::AttrBuilder FuncAttrs;
1438 llvm::AttrBuilder RetAttrs;
Paul Robinson08556952014-12-11 20:14:04 +00001439 bool HasOptnone = false;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001440
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001441 CallingConv = FI.getEffectiveCallingConvention();
1442
John McCallab26cfa2010-02-05 21:31:56 +00001443 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001444 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001445
Samuel Antao798f11c2015-11-23 22:04:44 +00001446 // If we have information about the function prototype, we can learn
1447 // attributes form there.
1448 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
1449 CalleeInfo.getCalleeFunctionProtoType());
1450
1451 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
1452
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001453 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001454 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001455 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001456 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001457 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001458 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001459 if (TargetDecl->hasAttr<NoReturnAttr>())
1460 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001461 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1462 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001463
1464 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
Samuel Antao798f11c2015-11-23 22:04:44 +00001465 AddAttributesFromFunctionProtoType(
1466 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
Richard Smith49af6292013-03-05 08:30:04 +00001467 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1468 // These attributes are not inherited by overloads.
1469 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1470 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001471 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001472 }
1473
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001474 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
Eric Christopherbf005ec2011-08-15 22:38:22 +00001475 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001476 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1477 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001478 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001479 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1480 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001481 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
1482 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
1483 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001484 }
David Majnemer631a90b2015-02-04 07:23:21 +00001485 if (TargetDecl->hasAttr<RestrictAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001486 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001487 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1488 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Paul Robinson08556952014-12-11 20:14:04 +00001489
1490 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001491 }
1492
Paul Robinson08556952014-12-11 20:14:04 +00001493 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1494 if (!HasOptnone) {
1495 if (CodeGenOpts.OptimizeSize)
1496 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1497 if (CodeGenOpts.OptimizeSize == 2)
1498 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1499 }
1500
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001501 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001502 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001503 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001504 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001505 if (CodeGenOpts.EnableSegmentedStacks &&
1506 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001507 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001508
Bill Wendling2f81db62013-02-22 20:53:29 +00001509 if (AttrOnCallSite) {
1510 // Attributes that should go on the call site only.
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001511 if (!CodeGenOpts.SimplifyLibCalls ||
1512 CodeGenOpts.isNoBuiltinFunc(Name.data()))
Bill Wendling2f81db62013-02-22 20:53:29 +00001513 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00001514 if (!CodeGenOpts.TrapFuncName.empty())
1515 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
Bill Wendling706469b2013-02-28 22:49:57 +00001516 } else {
1517 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001518 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001519 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001520 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001521 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001522 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001523 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001524 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001525 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001526 }
1527
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001528 bool DisableTailCalls =
1529 CodeGenOpts.DisableTailCalls ||
1530 (TargetDecl && TargetDecl->hasAttr<DisableTailCallsAttr>());
Akira Hatanaka262a4c42015-06-09 19:04:36 +00001531 FuncAttrs.addAttribute("disable-tail-calls",
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001532 llvm::toStringRef(DisableTailCalls));
1533
Bill Wendlingdabafea2013-03-13 22:24:33 +00001534 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001535 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001536 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001537 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001538 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001539 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001540 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001541 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001542 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001543 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001544 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001545 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001546
Akira Hatanakaaecca042015-09-11 18:55:09 +00001547 if (CodeGenOpts.StackRealignment)
1548 FuncAttrs.addAttribute("stackrealign");
Eric Christopher70c16652015-03-25 23:14:47 +00001549
Eric Christopher11acf732015-06-12 01:35:52 +00001550 // Add target-cpu and target-features attributes to functions. If
1551 // we have a decl for the function and it has a target attribute then
1552 // parse that and add it to the feature set.
1553 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
Eric Christopher11acf732015-06-12 01:35:52 +00001554 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
Eric Christopherb57804a2015-09-01 22:03:56 +00001555 if (FD && FD->hasAttr<TargetAttr>()) {
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001556 llvm::StringMap<bool> FeatureMap;
Eric Christopher2b90a642015-11-11 23:05:08 +00001557 getFunctionFeatureMap(FeatureMap, FD);
Eric Christopher11acf732015-06-12 01:35:52 +00001558
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001559 // Produce the canonical string for this set of features.
1560 std::vector<std::string> Features;
1561 for (llvm::StringMap<bool>::const_iterator it = FeatureMap.begin(),
1562 ie = FeatureMap.end();
1563 it != ie; ++it)
1564 Features.push_back((it->second ? "+" : "-") + it->first().str());
Eric Christopher2249b812015-07-01 00:08:29 +00001565
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001566 // Now add the target-cpu and target-features to the function.
Eric Christopher2b90a642015-11-11 23:05:08 +00001567 // While we populated the feature map above, we still need to
1568 // get and parse the target attribute so we can get the cpu for
1569 // the function.
1570 const auto *TD = FD->getAttr<TargetAttr>();
1571 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1572 if (ParsedAttr.second != "")
1573 TargetCPU = ParsedAttr.second;
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001574 if (TargetCPU != "")
1575 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1576 if (!Features.empty()) {
1577 std::sort(Features.begin(), Features.end());
1578 FuncAttrs.addAttribute(
1579 "target-features",
1580 llvm::join(Features.begin(), Features.end(), ","));
1581 }
1582 } else {
1583 // Otherwise just add the existing target cpu and target features to the
1584 // function.
1585 std::vector<std::string> &Features = getTarget().getTargetOpts().Features;
1586 if (TargetCPU != "")
1587 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1588 if (!Features.empty()) {
1589 std::sort(Features.begin(), Features.end());
1590 FuncAttrs.addAttribute(
1591 "target-features",
1592 llvm::join(Features.begin(), Features.end(), ","));
1593 }
Eric Christopher70c16652015-03-25 23:14:47 +00001594 }
Bill Wendling985d1c52013-02-15 21:30:01 +00001595 }
1596
Alexey Samsonov153004f2014-09-29 22:08:00 +00001597 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001598
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001599 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001600 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001601 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001602 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001603 if (RetTy->hasSignedIntegerRepresentation())
1604 RetAttrs.addAttribute(llvm::Attribute::SExt);
1605 else if (RetTy->hasUnsignedIntegerRepresentation())
1606 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001607 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001608 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001609 if (RetAI.getInReg())
1610 RetAttrs.addAttribute(llvm::Attribute::InReg);
1611 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001612 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001613 break;
1614
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001615 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001616 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001617 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001618 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1619 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001620 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001621 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001622
Daniel Dunbard3674e62008-09-11 01:48:57 +00001623 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001624 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001625 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001626
Hal Finkela2347ba2014-07-18 15:52:10 +00001627 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1628 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001629 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001630 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1631 .getQuantity());
1632 else if (getContext().getTargetAddressSpace(PTy) == 0)
1633 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1634 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001635
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001636 // Attach return attributes.
1637 if (RetAttrs.hasAttributes()) {
1638 PAL.push_back(llvm::AttributeSet::get(
1639 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1640 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001641
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001642 // Attach attributes to sret.
1643 if (IRFunctionArgs.hasSRetArg()) {
1644 llvm::AttrBuilder SRETAttrs;
1645 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1646 if (RetAI.getInReg())
1647 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1648 PAL.push_back(llvm::AttributeSet::get(
1649 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1650 }
1651
1652 // Attach attributes to inalloca argument.
1653 if (IRFunctionArgs.hasInallocaArg()) {
1654 llvm::AttrBuilder Attrs;
1655 Attrs.addAttribute(llvm::Attribute::InAlloca);
1656 PAL.push_back(llvm::AttributeSet::get(
1657 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1658 }
1659
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001660 unsigned ArgNo = 0;
1661 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1662 E = FI.arg_end();
1663 I != E; ++I, ++ArgNo) {
1664 QualType ParamType = I->type;
1665 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001666 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001667
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001668 // Add attribute for padding argument, if necessary.
1669 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001670 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001671 PAL.push_back(llvm::AttributeSet::get(
1672 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1673 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001674 }
1675
John McCall39ec71f2010-03-27 00:47:27 +00001676 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1677 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001678 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001679 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001680 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001681 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001682 Attrs.addAttribute(llvm::Attribute::SExt);
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00001683 else if (ParamType->isUnsignedIntegerOrEnumerationType()) {
1684 if (getTypes().getABIInfo().shouldSignExtUnsignedType(ParamType))
1685 Attrs.addAttribute(llvm::Attribute::SExt);
1686 else
1687 Attrs.addAttribute(llvm::Attribute::ZExt);
1688 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001689 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001690 case ABIArgInfo::Direct:
Peter Collingbournef7706832014-12-12 23:41:25 +00001691 if (ArgNo == 0 && FI.isChainCall())
1692 Attrs.addAttribute(llvm::Attribute::Nest);
1693 else if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001694 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001695 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001696
James Y Knight71608572015-08-21 18:19:06 +00001697 case ABIArgInfo::Indirect: {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001698 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001699 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001700
Anders Carlsson20759ad2009-09-16 15:53:40 +00001701 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001702 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001703
John McCall7f416cc2015-09-08 08:05:57 +00001704 CharUnits Align = AI.getIndirectAlign();
James Y Knight71608572015-08-21 18:19:06 +00001705
1706 // In a byval argument, it is important that the required
1707 // alignment of the type is honored, as LLVM might be creating a
1708 // *new* stack object, and needs to know what alignment to give
1709 // it. (Sometimes it can deduce a sensible alignment on its own,
1710 // but not if clang decides it must emit a packed struct, or the
1711 // user specifies increased alignment requirements.)
1712 //
1713 // This is different from indirect *not* byval, where the object
1714 // exists already, and the align attribute is purely
1715 // informative.
John McCall7f416cc2015-09-08 08:05:57 +00001716 assert(!Align.isZero());
James Y Knight71608572015-08-21 18:19:06 +00001717
John McCall7f416cc2015-09-08 08:05:57 +00001718 // For now, only add this when we have a byval argument.
1719 // TODO: be less lazy about updating test cases.
1720 if (AI.getIndirectByVal())
1721 Attrs.addAlignmentAttr(Align.getQuantity());
Bill Wendlinga7912f82012-10-10 07:36:56 +00001722
Daniel Dunbarc2304432009-03-18 19:51:01 +00001723 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001724 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1725 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001726 break;
James Y Knight71608572015-08-21 18:19:06 +00001727 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001728 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001729 case ABIArgInfo::Expand:
Mike Stump11289f42009-09-09 15:08:12 +00001730 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001731
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001732 case ABIArgInfo::InAlloca:
1733 // inalloca disables readnone and readonly.
1734 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1735 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001736 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001737 }
Mike Stump11289f42009-09-09 15:08:12 +00001738
Hal Finkela2347ba2014-07-18 15:52:10 +00001739 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1740 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001741 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001742 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1743 .getQuantity());
1744 else if (getContext().getTargetAddressSpace(PTy) == 0)
1745 Attrs.addAttribute(llvm::Attribute::NonNull);
1746 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001747
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001748 if (Attrs.hasAttributes()) {
1749 unsigned FirstIRArg, NumIRArgs;
1750 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1751 for (unsigned i = 0; i < NumIRArgs; i++)
1752 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1753 FirstIRArg + i + 1, Attrs));
1754 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001755 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001756 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001757
Bill Wendlinga7912f82012-10-10 07:36:56 +00001758 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001759 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001760 AttributeSet::get(getLLVMContext(),
1761 llvm::AttributeSet::FunctionIndex,
1762 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001763}
1764
John McCalla738c252011-03-09 04:27:21 +00001765/// An argument came in as a promoted argument; demote it back to its
1766/// declared type.
1767static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1768 const VarDecl *var,
1769 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001770 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001771
1772 // This can happen with promotions that actually don't change the
1773 // underlying type, like the enum promotions.
1774 if (value->getType() == varType) return value;
1775
1776 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1777 && "unexpected promotion type");
1778
1779 if (isa<llvm::IntegerType>(varType))
1780 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1781
1782 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1783}
1784
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001785/// Returns the attribute (either parameter attribute, or function
1786/// attribute), which declares argument ArgNo to be non-null.
1787static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
1788 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001789 // FIXME: __attribute__((nonnull)) can also be applied to:
1790 // - references to pointers, where the pointee is known to be
1791 // nonnull (apparently a Clang extension)
1792 // - transparent unions containing pointers
1793 // In the former case, LLVM IR cannot represent the constraint. In
1794 // the latter case, we have no guarantee that the transparent union
1795 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001796 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
1797 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001798 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001799 if (PVD) {
1800 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
1801 return ParmNNAttr;
1802 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001803 // Check function attributes.
1804 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001805 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001806 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001807 if (NNAttr->isNonNull(ArgNo))
1808 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001809 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001810 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001811}
1812
Daniel Dunbard931a872009-02-02 22:03:45 +00001813void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1814 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001815 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00001816 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
1817 // Naked functions don't have prologues.
1818 return;
1819
John McCallcaa19452009-07-28 01:00:58 +00001820 // If this is an implicit-return-zero function, go ahead and
1821 // initialize the return value. TODO: it might be nice to have
1822 // a more general mechanism for this that didn't require synthesized
1823 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001824 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001825 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00001826 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001827 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001828 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001829 Builder.CreateStore(Zero, ReturnValue);
1830 }
1831 }
1832
Mike Stump18bb9282009-05-16 07:57:57 +00001833 // FIXME: We no longer need the types from FunctionArgList; lift up and
1834 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001835
Alexey Samsonov153004f2014-09-29 22:08:00 +00001836 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001837 // Flattened function arguments.
1838 SmallVector<llvm::Argument *, 16> FnArgs;
1839 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
1840 for (auto &Arg : Fn->args()) {
1841 FnArgs.push_back(&Arg);
1842 }
1843 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00001844
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001845 // If we're using inalloca, all the memory arguments are GEPs off of the last
1846 // parameter, which is a pointer to the complete memory area.
John McCall7f416cc2015-09-08 08:05:57 +00001847 Address ArgStruct = Address::invalid();
1848 const llvm::StructLayout *ArgStructLayout = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001849 if (IRFunctionArgs.hasInallocaArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00001850 ArgStructLayout = CGM.getDataLayout().getStructLayout(FI.getArgStruct());
1851 ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()],
1852 FI.getArgStructAlignment());
1853
1854 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001855 }
1856
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001857 // Name the struct return parameter.
1858 if (IRFunctionArgs.hasSRetArg()) {
1859 auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()];
Daniel Dunbar613855c2008-09-09 23:27:19 +00001860 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00001861 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001862 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00001863 }
Mike Stump11289f42009-09-09 15:08:12 +00001864
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001865 // Track if we received the parameter as a pointer (indirect, byval, or
1866 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
1867 // into a local alloca for us.
John McCall7f416cc2015-09-08 08:05:57 +00001868 SmallVector<ParamValue, 16> ArgVals;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001869 ArgVals.reserve(Args.size());
1870
Reid Kleckner739756c2013-12-04 19:23:12 +00001871 // Create a pointer value for every parameter declaration. This usually
1872 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1873 // any cleanups or do anything that might unwind. We do that separately, so
1874 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001875 assert(FI.arg_size() == Args.size() &&
1876 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001877 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001878 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001879 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00001880 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001881 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001882 QualType Ty = info_it->type;
1883 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001884
John McCalla738c252011-03-09 04:27:21 +00001885 bool isPromoted =
1886 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1887
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001888 unsigned FirstIRArg, NumIRArgs;
1889 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00001890
Daniel Dunbard3674e62008-09-11 01:48:57 +00001891 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001892 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001893 assert(NumIRArgs == 0);
John McCall7f416cc2015-09-08 08:05:57 +00001894 auto FieldIndex = ArgI.getInAllocaFieldIndex();
1895 CharUnits FieldOffset =
1896 CharUnits::fromQuantity(ArgStructLayout->getElementOffset(FieldIndex));
1897 Address V = Builder.CreateStructGEP(ArgStruct, FieldIndex, FieldOffset,
1898 Arg->getName());
1899 ArgVals.push_back(ParamValue::forIndirect(V));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001900 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001901 }
1902
Daniel Dunbar747865a2009-02-05 09:16:39 +00001903 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001904 assert(NumIRArgs == 1);
John McCall7f416cc2015-09-08 08:05:57 +00001905 Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign());
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001906
John McCall47fb9502013-03-07 21:37:08 +00001907 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001908 // Aggregates and complex variables are accessed by reference. All we
John McCall7f416cc2015-09-08 08:05:57 +00001909 // need to do is realign the value, if requested.
1910 Address V = ParamAddr;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001911 if (ArgI.getIndirectRealign()) {
John McCall7f416cc2015-09-08 08:05:57 +00001912 Address AlignedTemp = CreateMemTemp(Ty, "coerce");
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001913
1914 // Copy from the incoming argument pointer to the temporary with the
1915 // appropriate alignment.
1916 //
1917 // FIXME: We should have a common utility for generating an aggregate
1918 // copy.
Ken Dyck705ba072011-01-19 01:58:38 +00001919 CharUnits Size = getContext().getTypeSizeInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00001920 auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity());
1921 Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy);
1922 Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy);
1923 Builder.CreateMemCpy(Dst, Src, SizeVal, false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001924 V = AlignedTemp;
1925 }
John McCall7f416cc2015-09-08 08:05:57 +00001926 ArgVals.push_back(ParamValue::forIndirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001927 } else {
1928 // Load scalar value from indirect argument.
John McCall7f416cc2015-09-08 08:05:57 +00001929 llvm::Value *V =
1930 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001931
1932 if (isPromoted)
1933 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00001934 ArgVals.push_back(ParamValue::forDirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001935 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001936 break;
1937 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001938
1939 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001940 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001941
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001942 // If we have the trivial case, handle it with no muss and fuss.
1943 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001944 ArgI.getCoerceToType() == ConvertType(Ty) &&
1945 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001946 assert(NumIRArgs == 1);
1947 auto AI = FnArgs[FirstIRArg];
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001948 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001949
Hal Finkel48d53e22014-07-19 01:41:07 +00001950 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001951 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
1952 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00001953 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1954 AI->getArgNo() + 1,
1955 llvm::Attribute::NonNull));
1956
Hal Finkel48d53e22014-07-19 01:41:07 +00001957 QualType OTy = PVD->getOriginalType();
1958 if (const auto *ArrTy =
1959 getContext().getAsConstantArrayType(OTy)) {
1960 // A C99 array parameter declaration with the static keyword also
1961 // indicates dereferenceability, and if the size is constant we can
1962 // use the dereferenceable attribute (which requires the size in
1963 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00001964 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00001965 QualType ETy = ArrTy->getElementType();
1966 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
1967 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
1968 ArrSize) {
1969 llvm::AttrBuilder Attrs;
1970 Attrs.addDereferenceableAttr(
1971 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
1972 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1973 AI->getArgNo() + 1, Attrs));
1974 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
1975 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1976 AI->getArgNo() + 1,
1977 llvm::Attribute::NonNull));
1978 }
1979 }
1980 } else if (const auto *ArrTy =
1981 getContext().getAsVariableArrayType(OTy)) {
1982 // For C99 VLAs with the static keyword, we don't know the size so
1983 // we can't use the dereferenceable attribute, but in addrspace(0)
1984 // we know that it must be nonnull.
1985 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
1986 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
1987 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1988 AI->getArgNo() + 1,
1989 llvm::Attribute::NonNull));
1990 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00001991
1992 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
1993 if (!AVAttr)
1994 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
1995 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
1996 if (AVAttr) {
1997 llvm::Value *AlignmentValue =
1998 EmitScalarExpr(AVAttr->getAlignment());
1999 llvm::ConstantInt *AlignmentCI =
2000 cast<llvm::ConstantInt>(AlignmentValue);
2001 unsigned Alignment =
2002 std::min((unsigned) AlignmentCI->getZExtValue(),
2003 +llvm::Value::MaximumAlignment);
2004
2005 llvm::AttrBuilder Attrs;
2006 Attrs.addAlignmentAttr(Alignment);
2007 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2008 AI->getArgNo() + 1, Attrs));
2009 }
Hal Finkel48d53e22014-07-19 01:41:07 +00002010 }
2011
Bill Wendling507c3512012-10-16 05:23:44 +00002012 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002013 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2014 AI->getArgNo() + 1,
2015 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00002016
Chris Lattner7369c142011-07-20 06:29:00 +00002017 // Ensure the argument is the correct type.
2018 if (V->getType() != ArgI.getCoerceToType())
2019 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
2020
John McCalla738c252011-03-09 04:27:21 +00002021 if (isPromoted)
2022 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00002023
Nick Lewycky5fa40c32013-10-01 21:51:38 +00002024 if (const CXXMethodDecl *MD =
2025 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00002026 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00002027 V = CGM.getCXXABI().
2028 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00002029 }
2030
Rafael Espindola8778c282012-11-29 16:09:03 +00002031 // Because of merging of function types from multiple decls it is
2032 // possible for the type of an argument to not match the corresponding
2033 // type in the function type. Since we are codegening the callee
2034 // in here, add a cast to the argument type.
2035 llvm::Type *LTy = ConvertType(Arg->getType());
2036 if (V->getType() != LTy)
2037 V = Builder.CreateBitCast(V, LTy);
2038
John McCall7f416cc2015-09-08 08:05:57 +00002039 ArgVals.push_back(ParamValue::forDirect(V));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002040 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00002041 }
Mike Stump11289f42009-09-09 15:08:12 +00002042
John McCall7f416cc2015-09-08 08:05:57 +00002043 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
2044 Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002045
John McCall7f416cc2015-09-08 08:05:57 +00002046 // Pointer to store into.
2047 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002048
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002049 // Fast-isel and the optimizer generally like scalar values better than
2050 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002051 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002052 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
2053 STy->getNumElements() > 1) {
John McCall7f416cc2015-09-08 08:05:57 +00002054 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002055 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
John McCall7f416cc2015-09-08 08:05:57 +00002056 llvm::Type *DstTy = Ptr.getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002057 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002058
John McCall7f416cc2015-09-08 08:05:57 +00002059 Address AddrToStoreInto = Address::invalid();
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002060 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00002061 AddrToStoreInto =
2062 Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002063 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002064 AddrToStoreInto =
2065 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
Chris Lattner15ec3612010-06-29 00:06:42 +00002066 }
John McCall7f416cc2015-09-08 08:05:57 +00002067
2068 assert(STy->getNumElements() == NumIRArgs);
2069 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2070 auto AI = FnArgs[FirstIRArg + i];
2071 AI->setName(Arg->getName() + ".coerce" + Twine(i));
2072 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
2073 Address EltPtr =
2074 Builder.CreateStructGEP(AddrToStoreInto, i, Offset);
2075 Builder.CreateStore(AI, EltPtr);
2076 }
2077
2078 if (SrcSize > DstSize) {
2079 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
2080 }
2081
Chris Lattner15ec3612010-06-29 00:06:42 +00002082 } else {
2083 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002084 assert(NumIRArgs == 1);
2085 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00002086 AI->setName(Arg->getName() + ".coerce");
John McCall7f416cc2015-09-08 08:05:57 +00002087 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00002088 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002089
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002090 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00002091 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002092 llvm::Value *V =
2093 EmitLoadOfScalar(Alloca, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002094 if (isPromoted)
2095 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002096 ArgVals.push_back(ParamValue::forDirect(V));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002097 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002098 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00002099 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002100 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002101 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002102
2103 case ABIArgInfo::Expand: {
2104 // If this structure was expanded into multiple arguments then
2105 // we need to create a temporary and reconstruct it from the
2106 // arguments.
John McCall7f416cc2015-09-08 08:05:57 +00002107 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2108 LValue LV = MakeAddrLValue(Alloca, Ty);
2109 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002110
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002111 auto FnArgIter = FnArgs.begin() + FirstIRArg;
2112 ExpandTypeFromArgs(Ty, LV, FnArgIter);
2113 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
2114 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2115 auto AI = FnArgs[FirstIRArg + i];
2116 AI->setName(Arg->getName() + "." + Twine(i));
2117 }
2118 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002119 }
2120
2121 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002122 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002123 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002124 if (!hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002125 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002126 } else {
2127 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002128 ArgVals.push_back(ParamValue::forDirect(U));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002129 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002130 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002131 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002132 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002133
Reid Kleckner739756c2013-12-04 19:23:12 +00002134 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2135 for (int I = Args.size() - 1; I >= 0; --I)
John McCall7f416cc2015-09-08 08:05:57 +00002136 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002137 } else {
2138 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall7f416cc2015-09-08 08:05:57 +00002139 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002140 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002141}
2142
John McCallffa2c1a2012-01-29 07:46:59 +00002143static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2144 while (insn->use_empty()) {
2145 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2146 if (!bitcast) return;
2147
2148 // This is "safe" because we would have used a ConstantExpr otherwise.
2149 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2150 bitcast->eraseFromParent();
2151 }
2152}
2153
John McCall31168b02011-06-15 23:02:42 +00002154/// Try to emit a fused autorelease of a return result.
2155static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2156 llvm::Value *result) {
2157 // We must be immediately followed the cast.
2158 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002159 if (BB->empty()) return nullptr;
2160 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002161
Chris Lattner2192fe52011-07-18 04:24:23 +00002162 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00002163
2164 // result is in a BasicBlock and is therefore an Instruction.
2165 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2166
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002167 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00002168
2169 // Look for:
2170 // %generator = bitcast %type1* %generator2 to %type2*
2171 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2172 // We would have emitted this as a constant if the operand weren't
2173 // an Instruction.
2174 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2175
2176 // Require the generator to be immediately followed by the cast.
2177 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002178 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002179
2180 insnsToKill.push_back(bitcast);
2181 }
2182
2183 // Look for:
2184 // %generator = call i8* @objc_retain(i8* %originalResult)
2185 // or
2186 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2187 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002188 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002189
2190 bool doRetainAutorelease;
2191
John McCallb04ecb72015-10-21 18:06:43 +00002192 if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) {
John McCall31168b02011-06-15 23:02:42 +00002193 doRetainAutorelease = true;
John McCallb04ecb72015-10-21 18:06:43 +00002194 } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints()
John McCall31168b02011-06-15 23:02:42 +00002195 .objc_retainAutoreleasedReturnValue) {
2196 doRetainAutorelease = false;
2197
John McCallcfa4e9b2012-09-07 23:30:50 +00002198 // If we emitted an assembly marker for this call (and the
2199 // ARCEntrypoints field should have been set if so), go looking
2200 // for that call. If we can't find it, we can't do this
2201 // optimization. But it should always be the immediately previous
2202 // instruction, unless we needed bitcasts around the call.
John McCallb04ecb72015-10-21 18:06:43 +00002203 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
John McCallcfa4e9b2012-09-07 23:30:50 +00002204 llvm::Instruction *prev = call->getPrevNode();
2205 assert(prev);
2206 if (isa<llvm::BitCastInst>(prev)) {
2207 prev = prev->getPrevNode();
2208 assert(prev);
2209 }
2210 assert(isa<llvm::CallInst>(prev));
2211 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
John McCallb04ecb72015-10-21 18:06:43 +00002212 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
John McCallcfa4e9b2012-09-07 23:30:50 +00002213 insnsToKill.push_back(prev);
2214 }
John McCall31168b02011-06-15 23:02:42 +00002215 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002216 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002217 }
2218
2219 result = call->getArgOperand(0);
2220 insnsToKill.push_back(call);
2221
2222 // Keep killing bitcasts, for sanity. Note that we no longer care
2223 // about precise ordering as long as there's exactly one use.
2224 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2225 if (!bitcast->hasOneUse()) break;
2226 insnsToKill.push_back(bitcast);
2227 result = bitcast->getOperand(0);
2228 }
2229
2230 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002231 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00002232 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
2233 (*i)->eraseFromParent();
2234
2235 // Do the fused retain/autorelease if we were asked to.
2236 if (doRetainAutorelease)
2237 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2238
2239 // Cast back to the result type.
2240 return CGF.Builder.CreateBitCast(result, resultType);
2241}
2242
John McCallffa2c1a2012-01-29 07:46:59 +00002243/// If this is a +1 of the value of an immutable 'self', remove it.
2244static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2245 llvm::Value *result) {
2246 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002247 const ObjCMethodDecl *method =
2248 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002249 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002250 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002251 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002252
2253 // Look for a retain call.
2254 llvm::CallInst *retainCall =
2255 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2256 if (!retainCall ||
John McCallb04ecb72015-10-21 18:06:43 +00002257 retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002258 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002259
2260 // Look for an ordinary load of 'self'.
2261 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2262 llvm::LoadInst *load =
2263 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2264 if (!load || load->isAtomic() || load->isVolatile() ||
John McCall7f416cc2015-09-08 08:05:57 +00002265 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
Craig Topper8a13c412014-05-21 05:09:00 +00002266 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002267
2268 // Okay! Burn it all down. This relies for correctness on the
2269 // assumption that the retain is emitted as part of the return and
2270 // that thereafter everything is used "linearly".
2271 llvm::Type *resultType = result->getType();
2272 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2273 assert(retainCall->use_empty());
2274 retainCall->eraseFromParent();
2275 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2276
2277 return CGF.Builder.CreateBitCast(load, resultType);
2278}
2279
John McCall31168b02011-06-15 23:02:42 +00002280/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002281///
2282/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002283static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2284 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002285 // If we're returning 'self', kill the initial retain. This is a
2286 // heuristic attempt to "encourage correctness" in the really unfortunate
2287 // case where we have a return of self during a dealloc and we desperately
2288 // need to avoid the possible autorelease.
2289 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2290 return self;
2291
John McCall31168b02011-06-15 23:02:42 +00002292 // At -O0, try to emit a fused retain/autorelease.
2293 if (CGF.shouldUseFusedARCCalls())
2294 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2295 return fused;
2296
2297 return CGF.EmitARCAutoreleaseReturnValue(result);
2298}
2299
John McCall6e1c0122012-01-29 02:35:02 +00002300/// Heuristically search for a dominating store to the return-value slot.
2301static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002302 // Check if a User is a store which pointerOperand is the ReturnValue.
2303 // We are looking for stores to the ReturnValue, not for stores of the
2304 // ReturnValue to some other location.
2305 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
2306 auto *SI = dyn_cast<llvm::StoreInst>(U);
2307 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
2308 return nullptr;
2309 // These aren't actually possible for non-coerced returns, and we
2310 // only care about non-coerced returns on this code path.
2311 assert(!SI->isAtomic() && !SI->isVolatile());
2312 return SI;
2313 };
John McCall6e1c0122012-01-29 02:35:02 +00002314 // If there are multiple uses of the return-value slot, just check
2315 // for something immediately preceding the IP. Sometimes this can
2316 // happen with how we generate implicit-returns; it can also happen
2317 // with noreturn cleanups.
John McCall7f416cc2015-09-08 08:05:57 +00002318 if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
John McCall6e1c0122012-01-29 02:35:02 +00002319 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002320 if (IP->empty()) return nullptr;
David Majnemerdc012fa2015-04-22 21:38:15 +00002321 llvm::Instruction *I = &IP->back();
2322
2323 // Skip lifetime markers
2324 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
2325 IE = IP->rend();
2326 II != IE; ++II) {
2327 if (llvm::IntrinsicInst *Intrinsic =
2328 dyn_cast<llvm::IntrinsicInst>(&*II)) {
2329 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
2330 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
2331 ++II;
Alexey Samsonov10544202015-06-12 21:05:32 +00002332 if (II == IE)
2333 break;
2334 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
2335 continue;
David Majnemerdc012fa2015-04-22 21:38:15 +00002336 }
2337 }
2338 I = &*II;
2339 break;
2340 }
2341
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002342 return GetStoreIfValid(I);
John McCall6e1c0122012-01-29 02:35:02 +00002343 }
2344
2345 llvm::StoreInst *store =
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002346 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002347 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002348
John McCall6e1c0122012-01-29 02:35:02 +00002349 // Now do a first-and-dirty dominance check: just walk up the
2350 // single-predecessors chain from the current insertion point.
2351 llvm::BasicBlock *StoreBB = store->getParent();
2352 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2353 while (IP != StoreBB) {
2354 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002355 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002356 }
2357
2358 // Okay, the store's basic block dominates the insertion point; we
2359 // can do our thing.
2360 return store;
2361}
2362
Adrian Prantl3be10542013-05-02 17:30:20 +00002363void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002364 bool EmitRetDbgLoc,
2365 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002366 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2367 // Naked functions don't have epilogues.
2368 Builder.CreateUnreachable();
2369 return;
2370 }
2371
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002372 // Functions with no result always return void.
John McCall7f416cc2015-09-08 08:05:57 +00002373 if (!ReturnValue.isValid()) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002374 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002375 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002376 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002377
Dan Gohman481e40c2010-07-20 20:13:52 +00002378 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002379 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002380 QualType RetTy = FI.getReturnType();
2381 const ABIArgInfo &RetAI = FI.getReturnInfo();
2382
2383 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002384 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002385 // Aggregrates get evaluated directly into the destination. Sometimes we
2386 // need to return the sret value in a register, though.
2387 assert(hasAggregateEvaluationKind(RetTy));
2388 if (RetAI.getInAllocaSRet()) {
2389 llvm::Function::arg_iterator EI = CurFn->arg_end();
2390 --EI;
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002391 llvm::Value *ArgStruct = &*EI;
David Blaikie2e804282015-04-05 22:47:07 +00002392 llvm::Value *SRet = Builder.CreateStructGEP(
2393 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
John McCall7f416cc2015-09-08 08:05:57 +00002394 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret");
Reid Klecknerfab1e892014-02-25 00:59:14 +00002395 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002396 break;
2397
Daniel Dunbar03816342010-08-21 02:24:36 +00002398 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002399 auto AI = CurFn->arg_begin();
2400 if (RetAI.isSRetAfterThis())
2401 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002402 switch (getEvaluationKind(RetTy)) {
2403 case TEK_Complex: {
2404 ComplexPairTy RT =
John McCall7f416cc2015-09-08 08:05:57 +00002405 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002406 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002407 /*isInit*/ true);
2408 break;
2409 }
2410 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002411 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002412 break;
2413 case TEK_Scalar:
2414 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002415 MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002416 /*isInit*/ true);
2417 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002418 }
2419 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002420 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002421
2422 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002423 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002424 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2425 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002426 // The internal return value temp always will have pointer-to-return-type
2427 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002428
John McCall6e1c0122012-01-29 02:35:02 +00002429 // If there is a dominating store to ReturnValue, we can elide
2430 // the load, zap the store, and usually zap the alloca.
David Majnemerdc012fa2015-04-22 21:38:15 +00002431 if (llvm::StoreInst *SI =
2432 findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002433 // Reuse the debug location from the store unless there is
2434 // cleanup code to be emitted between the store and return
2435 // instruction.
2436 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002437 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002438 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002439 RV = SI->getValueOperand();
2440 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002441
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002442 // If that was the only use of the return value, nuke it as well now.
John McCall7f416cc2015-09-08 08:05:57 +00002443 auto returnValueInst = ReturnValue.getPointer();
2444 if (returnValueInst->use_empty()) {
2445 if (auto alloca = dyn_cast<llvm::AllocaInst>(returnValueInst)) {
2446 alloca->eraseFromParent();
2447 ReturnValue = Address::invalid();
2448 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002449 }
John McCall6e1c0122012-01-29 02:35:02 +00002450
2451 // Otherwise, we have to do a simple load.
2452 } else {
2453 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002454 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002455 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002456 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00002457 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002458
John McCall7f416cc2015-09-08 08:05:57 +00002459 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002460 }
John McCall31168b02011-06-15 23:02:42 +00002461
2462 // In ARC, end functions that return a retainable type with a call
2463 // to objc_autoreleaseReturnValue.
2464 if (AutoreleaseResult) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002465 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002466 !FI.isReturnsRetained() &&
2467 RetTy->isObjCRetainableType());
2468 RV = emitAutoreleaseOfResult(*this, RV);
2469 }
2470
Chris Lattner726b3d02010-06-26 23:13:19 +00002471 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002472
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002473 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002474 break;
2475
2476 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002477 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002478 }
2479
Alexey Samsonovde443c52014-08-13 00:26:40 +00002480 llvm::Instruction *Ret;
2481 if (RV) {
John McCall9a2c1c92015-09-10 00:57:46 +00002482 if (CurCodeDecl && SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
2483 if (auto RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>()) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002484 SanitizerScope SanScope(this);
2485 llvm::Value *Cond = Builder.CreateICmpNE(
2486 RV, llvm::Constant::getNullValue(RV->getType()));
2487 llvm::Constant *StaticData[] = {
2488 EmitCheckSourceLocation(EndLoc),
2489 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2490 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002491 EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
2492 "nonnull_return", StaticData, None);
Alexey Samsonov90452df2014-09-08 20:17:19 +00002493 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002494 }
2495 Ret = Builder.CreateRet(RV);
2496 } else {
2497 Ret = Builder.CreateRetVoid();
2498 }
2499
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00002500 if (RetDbgLoc)
Benjamin Kramer03278662015-02-07 13:15:54 +00002501 Ret->setDebugLoc(std::move(RetDbgLoc));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002502}
2503
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002504static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2505 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2506 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2507}
2508
John McCall7f416cc2015-09-08 08:05:57 +00002509static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
2510 QualType Ty) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002511 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2512 // placeholders.
2513 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2514 llvm::Value *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00002515 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2516 Placeholder = CGF.Builder.CreateDefaultAlignedLoad(Placeholder);
2517
2518 // FIXME: When we generate this IR in one pass, we shouldn't need
2519 // this win32-specific alignment hack.
2520 CharUnits Align = CharUnits::fromQuantity(4);
2521
2522 return AggValueSlot::forAddr(Address(Placeholder, Align),
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002523 Ty.getQualifiers(),
2524 AggValueSlot::IsNotDestructed,
2525 AggValueSlot::DoesNotNeedGCBarriers,
2526 AggValueSlot::IsNotAliased);
2527}
2528
John McCall32ea9692011-03-11 20:59:21 +00002529void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002530 const VarDecl *param,
2531 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002532 // StartFunction converted the ABI-lowered parameter(s) into a
2533 // local alloca. We need to turn that into an r-value suitable
2534 // for EmitCall.
John McCall7f416cc2015-09-08 08:05:57 +00002535 Address local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002536
John McCall32ea9692011-03-11 20:59:21 +00002537 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002538
John McCall23f66262010-05-26 22:34:26 +00002539 // For the most part, we just need to load the alloca, except:
2540 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00002541 // 2) references to non-scalars are pointers directly to the aggregate.
2542 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00002543 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00002544 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00002545 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00002546
2547 // Locals which are references to scalars are represented
2548 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00002549 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00002550 }
2551
Reid Klecknerab2090d2014-07-26 01:34:32 +00002552 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2553 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002554
Nick Lewycky2d84e842013-10-02 02:29:49 +00002555 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002556}
2557
John McCall31168b02011-06-15 23:02:42 +00002558static bool isProvablyNull(llvm::Value *addr) {
2559 return isa<llvm::ConstantPointerNull>(addr);
2560}
2561
2562static bool isProvablyNonNull(llvm::Value *addr) {
2563 return isa<llvm::AllocaInst>(addr);
2564}
2565
2566/// Emit the actual writing-back of a writeback.
2567static void emitWriteback(CodeGenFunction &CGF,
2568 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002569 const LValue &srcLV = writeback.Source;
John McCall7f416cc2015-09-08 08:05:57 +00002570 Address srcAddr = srcLV.getAddress();
2571 assert(!isProvablyNull(srcAddr.getPointer()) &&
John McCall31168b02011-06-15 23:02:42 +00002572 "shouldn't have writeback for provably null argument");
2573
Craig Topper8a13c412014-05-21 05:09:00 +00002574 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002575
2576 // If the argument wasn't provably non-null, we need to null check
2577 // before doing the store.
John McCall7f416cc2015-09-08 08:05:57 +00002578 bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002579 if (!provablyNonNull) {
2580 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2581 contBB = CGF.createBasicBlock("icr.done");
2582
John McCall7f416cc2015-09-08 08:05:57 +00002583 llvm::Value *isNull =
2584 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00002585 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2586 CGF.EmitBlock(writebackBB);
2587 }
2588
2589 // Load the value to writeback.
2590 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2591
2592 // Cast it back, in case we're writing an id to a Foo* or something.
John McCall7f416cc2015-09-08 08:05:57 +00002593 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
2594 "icr.writeback-cast");
John McCall31168b02011-06-15 23:02:42 +00002595
2596 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002597
2598 // If we have a "to use" value, it's something we need to emit a use
2599 // of. This has to be carefully threaded in: if it's done after the
2600 // release it's potentially undefined behavior (and the optimizer
2601 // will ignore it), and if it happens before the retain then the
2602 // optimizer could move the release there.
2603 if (writeback.ToUse) {
2604 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2605
2606 // Retain the new value. No need to block-copy here: the block's
2607 // being passed up the stack.
2608 value = CGF.EmitARCRetainNonBlock(value);
2609
2610 // Emit the intrinsic use here.
2611 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2612
2613 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002614 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002615
2616 // Put the new value in place (primitively).
2617 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2618
2619 // Release the old value.
2620 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2621
2622 // Otherwise, we can just do a normal lvalue store.
2623 } else {
2624 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2625 }
John McCall31168b02011-06-15 23:02:42 +00002626
2627 // Jump to the continuation block.
2628 if (!provablyNonNull)
2629 CGF.EmitBlock(contBB);
2630}
2631
2632static void emitWritebacks(CodeGenFunction &CGF,
2633 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002634 for (const auto &I : args.writebacks())
2635 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002636}
2637
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002638static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2639 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002640 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002641 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2642 CallArgs.getCleanupsToDeactivate();
2643 // Iterate in reverse to increase the likelihood of popping the cleanup.
Pete Cooper57d3f142015-07-30 17:22:52 +00002644 for (const auto &I : llvm::reverse(Cleanups)) {
2645 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
2646 I.IsActiveIP->eraseFromParent();
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002647 }
2648}
2649
John McCalleff18842013-03-23 02:35:54 +00002650static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2651 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2652 if (uop->getOpcode() == UO_AddrOf)
2653 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002654 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002655}
2656
John McCall31168b02011-06-15 23:02:42 +00002657/// Emit an argument that's being passed call-by-writeback. That is,
John McCall7f416cc2015-09-08 08:05:57 +00002658/// we are passing the address of an __autoreleased temporary; it
2659/// might be copy-initialized with the current value of the given
2660/// address, but it will definitely be copied out of after the call.
John McCall31168b02011-06-15 23:02:42 +00002661static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2662 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002663 LValue srcLV;
2664
2665 // Make an optimistic effort to emit the address as an l-value.
Eric Christopher2c4555a2015-06-19 01:52:53 +00002666 // This can fail if the argument expression is more complicated.
John McCalleff18842013-03-23 02:35:54 +00002667 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2668 srcLV = CGF.EmitLValue(lvExpr);
2669
2670 // Otherwise, just emit it as a scalar.
2671 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002672 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
John McCalleff18842013-03-23 02:35:54 +00002673
2674 QualType srcAddrType =
2675 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00002676 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
John McCalleff18842013-03-23 02:35:54 +00002677 }
John McCall7f416cc2015-09-08 08:05:57 +00002678 Address srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002679
2680 // The dest and src types don't necessarily match in LLVM terms
2681 // because of the crazy ObjC compatibility rules.
2682
Chris Lattner2192fe52011-07-18 04:24:23 +00002683 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00002684 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2685
2686 // If the address is a constant null, just pass the appropriate null.
John McCall7f416cc2015-09-08 08:05:57 +00002687 if (isProvablyNull(srcAddr.getPointer())) {
John McCall31168b02011-06-15 23:02:42 +00002688 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2689 CRE->getType());
2690 return;
2691 }
2692
John McCall31168b02011-06-15 23:02:42 +00002693 // Create the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00002694 Address temp = CGF.CreateTempAlloca(destType->getElementType(),
2695 CGF.getPointerAlign(),
2696 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002697 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2698 // and that cleanup will be conditional if we can't prove that the l-value
2699 // isn't null, so we need to register a dominating point so that the cleanups
2700 // system will make valid IR.
2701 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2702
John McCall31168b02011-06-15 23:02:42 +00002703 // Zero-initialize it if we're not doing a copy-initialization.
2704 bool shouldCopy = CRE->shouldCopy();
2705 if (!shouldCopy) {
2706 llvm::Value *null =
2707 llvm::ConstantPointerNull::get(
2708 cast<llvm::PointerType>(destType->getElementType()));
2709 CGF.Builder.CreateStore(null, temp);
2710 }
Craig Topper8a13c412014-05-21 05:09:00 +00002711
2712 llvm::BasicBlock *contBB = nullptr;
2713 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002714
2715 // If the address is *not* known to be non-null, we need to switch.
2716 llvm::Value *finalArgument;
2717
John McCall7f416cc2015-09-08 08:05:57 +00002718 bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002719 if (provablyNonNull) {
John McCall7f416cc2015-09-08 08:05:57 +00002720 finalArgument = temp.getPointer();
John McCall31168b02011-06-15 23:02:42 +00002721 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002722 llvm::Value *isNull =
2723 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00002724
2725 finalArgument = CGF.Builder.CreateSelect(isNull,
2726 llvm::ConstantPointerNull::get(destType),
John McCall7f416cc2015-09-08 08:05:57 +00002727 temp.getPointer(), "icr.argument");
John McCall31168b02011-06-15 23:02:42 +00002728
2729 // If we need to copy, then the load has to be conditional, which
2730 // means we need control flow.
2731 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00002732 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002733 contBB = CGF.createBasicBlock("icr.cont");
2734 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2735 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2736 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002737 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00002738 }
2739 }
2740
Craig Topper8a13c412014-05-21 05:09:00 +00002741 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00002742
John McCall31168b02011-06-15 23:02:42 +00002743 // Perform a copy if necessary.
2744 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002745 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002746 assert(srcRV.isScalar());
2747
2748 llvm::Value *src = srcRV.getScalarVal();
2749 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2750 "icr.cast");
2751
2752 // Use an ordinary store, not a store-to-lvalue.
2753 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00002754
2755 // If optimization is enabled, and the value was held in a
2756 // __strong variable, we need to tell the optimizer that this
2757 // value has to stay alive until we're doing the store back.
2758 // This is because the temporary is effectively unretained,
2759 // and so otherwise we can violate the high-level semantics.
2760 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2761 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2762 valueToUse = src;
2763 }
John McCall31168b02011-06-15 23:02:42 +00002764 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002765
John McCall31168b02011-06-15 23:02:42 +00002766 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002767 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00002768 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002769 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00002770
2771 // Make a phi for the value to intrinsically use.
2772 if (valueToUse) {
2773 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2774 "icr.to-use");
2775 phiToUse->addIncoming(valueToUse, copyBB);
2776 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2777 originBB);
2778 valueToUse = phiToUse;
2779 }
2780
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002781 condEval.end(CGF);
2782 }
John McCall31168b02011-06-15 23:02:42 +00002783
John McCalleff18842013-03-23 02:35:54 +00002784 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002785 args.add(RValue::get(finalArgument), CRE->getType());
2786}
2787
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002788void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2789 assert(!StackBase && !StackCleanup.isValid());
2790
2791 // Save the stack.
2792 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie43f9bb72015-05-18 22:14:03 +00002793 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002794}
2795
Nico Weber8cdb3f92015-08-25 18:43:32 +00002796void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2797 if (StackBase) {
Reid Kleckner7c2f9e82015-10-08 00:17:45 +00002798 // Restore the stack after the call.
Nico Weber8cdb3f92015-08-25 18:43:32 +00002799 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
Nico Weber8cdb3f92015-08-25 18:43:32 +00002800 CGF.Builder.CreateCall(F, StackBase);
2801 }
2802}
2803
Nuno Lopes1ba2d782015-05-30 16:11:40 +00002804void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
2805 SourceLocation ArgLoc,
2806 const FunctionDecl *FD,
2807 unsigned ParmNum) {
2808 if (!SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002809 return;
2810 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
2811 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
2812 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
2813 if (!NNAttr)
2814 return;
Nuno Lopes1ba2d782015-05-30 16:11:40 +00002815 SanitizerScope SanScope(this);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002816 assert(RV.isScalar());
2817 llvm::Value *V = RV.getScalarVal();
2818 llvm::Value *Cond =
Nuno Lopes1ba2d782015-05-30 16:11:40 +00002819 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002820 llvm::Constant *StaticData[] = {
Nuno Lopes1ba2d782015-05-30 16:11:40 +00002821 EmitCheckSourceLocation(ArgLoc),
2822 EmitCheckSourceLocation(NNAttr->getLocation()),
2823 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002824 };
Nuno Lopes1ba2d782015-05-30 16:11:40 +00002825 EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002826 "nonnull_arg", StaticData, None);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002827}
2828
David Blaikief05779e2015-07-21 18:37:18 +00002829void CodeGenFunction::EmitCallArgs(
2830 CallArgList &Args, ArrayRef<QualType> ArgTypes,
2831 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
2832 const FunctionDecl *CalleeDecl, unsigned ParamsToSkip) {
2833 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002834
2835 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg) {
2836 if (CalleeDecl == nullptr || I >= CalleeDecl->getNumParams())
2837 return;
2838 auto *PS = CalleeDecl->getParamDecl(I)->getAttr<PassObjectSizeAttr>();
2839 if (PS == nullptr)
2840 return;
2841
2842 const auto &Context = getContext();
2843 auto SizeTy = Context.getSizeType();
2844 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
2845 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T);
2846 Args.add(RValue::get(V), SizeTy);
2847 };
2848
Reid Kleckner739756c2013-12-04 19:23:12 +00002849 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2850 // because arguments are destroyed left to right in the callee.
2851 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002852 // Insert a stack save if we're going to need any inalloca args.
2853 bool HasInAllocaArgs = false;
2854 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2855 I != E && !HasInAllocaArgs; ++I)
2856 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2857 if (HasInAllocaArgs) {
2858 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2859 Args.allocateArgumentMemory(*this);
2860 }
2861
2862 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00002863 size_t CallArgsStart = Args.size();
2864 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
David Blaikief05779e2015-07-21 18:37:18 +00002865 CallExpr::const_arg_iterator Arg = ArgRange.begin() + I;
Reid Kleckner739756c2013-12-04 19:23:12 +00002866 EmitCallArg(Args, *Arg, ArgTypes[I]);
Benjamin Kramerf48ee442015-07-18 14:35:53 +00002867 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002868 CalleeDecl, ParamsToSkip + I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002869 MaybeEmitImplicitObjectSize(I, *Arg);
Reid Kleckner739756c2013-12-04 19:23:12 +00002870 }
2871
2872 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2873 // IR function.
2874 std::reverse(Args.begin() + CallArgsStart, Args.end());
2875 return;
2876 }
2877
2878 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
David Blaikief05779e2015-07-21 18:37:18 +00002879 CallExpr::const_arg_iterator Arg = ArgRange.begin() + I;
2880 assert(Arg != ArgRange.end());
Reid Kleckner739756c2013-12-04 19:23:12 +00002881 EmitCallArg(Args, *Arg, ArgTypes[I]);
Benjamin Kramerf48ee442015-07-18 14:35:53 +00002882 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002883 CalleeDecl, ParamsToSkip + I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002884 MaybeEmitImplicitObjectSize(I, *Arg);
Reid Kleckner739756c2013-12-04 19:23:12 +00002885 }
2886}
2887
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002888namespace {
2889
David Blaikie7e70d682015-08-18 22:40:54 +00002890struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +00002891 DestroyUnpassedArg(Address Addr, QualType Ty)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002892 : Addr(Addr), Ty(Ty) {}
2893
John McCall7f416cc2015-09-08 08:05:57 +00002894 Address Addr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002895 QualType Ty;
2896
Craig Topper4f12f102014-03-12 06:41:41 +00002897 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002898 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2899 assert(!Dtor->isTrivial());
2900 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2901 /*Delegating=*/false, Addr);
2902 }
2903};
2904
David Blaikie38b25912015-02-09 19:13:51 +00002905struct DisableDebugLocationUpdates {
2906 CodeGenFunction &CGF;
2907 bool disabledDebugInfo;
2908 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
2909 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
2910 CGF.disableDebugInfo();
2911 }
2912 ~DisableDebugLocationUpdates() {
2913 if (disabledDebugInfo)
2914 CGF.enableDebugInfo();
2915 }
2916};
2917
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002918} // end anonymous namespace
2919
John McCall32ea9692011-03-11 20:59:21 +00002920void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2921 QualType type) {
David Blaikie38b25912015-02-09 19:13:51 +00002922 DisableDebugLocationUpdates Dis(*this, E);
John McCall31168b02011-06-15 23:02:42 +00002923 if (const ObjCIndirectCopyRestoreExpr *CRE
2924 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002925 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002926 assert(getContext().hasSameType(E->getType(), type));
2927 return emitWritebackArg(*this, args, CRE);
2928 }
2929
John McCall0a76c0c2011-08-26 18:42:59 +00002930 assert(type->isReferenceType() == E->isGLValue() &&
2931 "reference binding to unmaterialized r-value!");
2932
John McCall17054bd62011-08-26 21:08:13 +00002933 if (E->isGLValue()) {
2934 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002935 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002936 }
Mike Stump11289f42009-09-09 15:08:12 +00002937
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002938 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2939
2940 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2941 // However, we still have to push an EH-only cleanup in case we unwind before
2942 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00002943 if (HasAggregateEvalKind &&
2944 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2945 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00002946 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00002947 AggValueSlot Slot;
2948 if (args.isUsingInAlloca())
2949 Slot = createPlaceholderSlot(*this, type);
2950 else
2951 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00002952
2953 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2954 bool DestroyedInCallee =
2955 RD && RD->hasNonTrivialDestructor() &&
2956 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
2957 if (DestroyedInCallee)
2958 Slot.setExternallyDestructed();
2959
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002960 EmitAggExpr(E, Slot);
2961 RValue RV = Slot.asRValue();
2962 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002963
Reid Klecknere39ee212014-05-03 00:33:28 +00002964 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002965 // Create a no-op GEP between the placeholder and the cleanup so we can
2966 // RAUW it successfully. It also serves as a marker of the first
2967 // instruction where the cleanup is active.
John McCall7f416cc2015-09-08 08:05:57 +00002968 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
2969 type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002970 // This unreachable is a temporary marker which will be removed later.
2971 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2972 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002973 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002974 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002975 }
2976
2977 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00002978 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2979 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2980 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00002981 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2982 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2983 } else {
2984 // We can't represent a misaligned lvalue in the CallArgList, so copy
2985 // to an aligned temporary now.
John McCall7f416cc2015-09-08 08:05:57 +00002986 Address tmp = CreateMemTemp(type);
2987 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile());
Eli Friedman61f615a2013-06-11 01:08:22 +00002988 args.add(RValue::getAggregate(tmp), type);
2989 }
Eli Friedmandf968192011-05-26 00:10:27 +00002990 return;
2991 }
2992
John McCall32ea9692011-03-11 20:59:21 +00002993 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00002994}
2995
Reid Kleckner79b0fd72014-10-10 00:05:45 +00002996QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
2997 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
2998 // implicitly widens null pointer constants that are arguments to varargs
2999 // functions to pointer-sized ints.
3000 if (!getTarget().getTriple().isOSWindows())
3001 return Arg->getType();
3002
3003 if (Arg->getType()->isIntegerType() &&
3004 getContext().getTypeSize(Arg->getType()) <
3005 getContext().getTargetInfo().getPointerWidth(0) &&
3006 Arg->isNullPointerConstant(getContext(),
3007 Expr::NPC_ValueDependentIsNotNull)) {
3008 return getContext().getIntPtrType();
3009 }
3010
3011 return Arg->getType();
3012}
3013
Dan Gohman515a60d2012-02-16 00:57:37 +00003014// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3015// optimizer it can aggressively ignore unwind edges.
3016void
3017CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
3018 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3019 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
3020 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
3021 CGM.getNoObjCARCExceptionsMetadata());
3022}
3023
John McCall882987f2013-02-28 19:01:20 +00003024/// Emits a call to the given no-arguments nounwind runtime function.
3025llvm::CallInst *
3026CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3027 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003028 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003029}
3030
3031/// Emits a call to the given nounwind runtime function.
3032llvm::CallInst *
3033CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3034 ArrayRef<llvm::Value*> args,
3035 const llvm::Twine &name) {
3036 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
3037 call->setDoesNotThrow();
3038 return call;
3039}
3040
3041/// Emits a simple call (never an invoke) to the given no-arguments
3042/// runtime function.
3043llvm::CallInst *
3044CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3045 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003046 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003047}
3048
Sanjay Patel846b63b2016-01-18 22:15:33 +00003049/// Emits a simple call (never an invoke) to the given runtime function.
John McCall882987f2013-02-28 19:01:20 +00003050llvm::CallInst *
3051CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3052 ArrayRef<llvm::Value*> args,
3053 const llvm::Twine &name) {
3054 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
3055 call->setCallingConv(getRuntimeCC());
3056 return call;
3057}
3058
David Majnemer0b17d442015-12-15 21:27:59 +00003059// Calls which may throw must have operand bundles indicating which funclet
3060// they are nested within.
3061static void
Sanjay Patel846b63b2016-01-18 22:15:33 +00003062getBundlesForFunclet(llvm::Value *Callee, llvm::Instruction *CurrentFuncletPad,
David Majnemer0b17d442015-12-15 21:27:59 +00003063 SmallVectorImpl<llvm::OperandBundleDef> &BundleList) {
Sanjay Patel846b63b2016-01-18 22:15:33 +00003064 // There is no need for a funclet operand bundle if we aren't inside a
3065 // funclet.
David Majnemer0b17d442015-12-15 21:27:59 +00003066 if (!CurrentFuncletPad)
3067 return;
3068
3069 // Skip intrinsics which cannot throw.
3070 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
3071 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
3072 return;
3073
3074 BundleList.emplace_back("funclet", CurrentFuncletPad);
3075}
3076
John McCall882987f2013-02-28 19:01:20 +00003077/// Emits a call or invoke to the given noreturn runtime function.
3078void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3079 ArrayRef<llvm::Value*> args) {
David Majnemer0b17d442015-12-15 21:27:59 +00003080 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3081 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3082
John McCall882987f2013-02-28 19:01:20 +00003083 if (getInvokeDest()) {
3084 llvm::InvokeInst *invoke =
3085 Builder.CreateInvoke(callee,
3086 getUnreachableBlock(),
3087 getInvokeDest(),
David Majnemer0b17d442015-12-15 21:27:59 +00003088 args,
3089 BundleList);
John McCall882987f2013-02-28 19:01:20 +00003090 invoke->setDoesNotReturn();
3091 invoke->setCallingConv(getRuntimeCC());
3092 } else {
David Majnemer0b17d442015-12-15 21:27:59 +00003093 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
John McCall882987f2013-02-28 19:01:20 +00003094 call->setDoesNotReturn();
3095 call->setCallingConv(getRuntimeCC());
3096 Builder.CreateUnreachable();
3097 }
3098}
3099
Sanjay Patel846b63b2016-01-18 22:15:33 +00003100/// Emits a call or invoke instruction to the given nullary runtime function.
John McCall882987f2013-02-28 19:01:20 +00003101llvm::CallSite
3102CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3103 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003104 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003105}
3106
3107/// Emits a call or invoke instruction to the given runtime function.
3108llvm::CallSite
3109CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3110 ArrayRef<llvm::Value*> args,
3111 const Twine &name) {
3112 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
3113 callSite.setCallingConv(getRuntimeCC());
3114 return callSite;
3115}
3116
John McCallbd309292010-07-06 01:34:17 +00003117/// Emits a call or invoke instruction to the given function, depending
3118/// on the current state of the EH stack.
3119llvm::CallSite
3120CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00003121 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003122 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00003123 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00003124
Dan Gohman515a60d2012-02-16 00:57:37 +00003125 llvm::Instruction *Inst;
3126 if (!InvokeDest)
3127 Inst = Builder.CreateCall(Callee, Args, Name);
3128 else {
3129 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
3130 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
3131 EmitBlock(ContBB);
3132 }
3133
3134 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3135 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003136 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003137 AddObjCARCExceptionMetadata(Inst);
3138
Benjamin Kramerc19cde12015-04-10 14:49:31 +00003139 return llvm::CallSite(Inst);
John McCallbd309292010-07-06 01:34:17 +00003140}
3141
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003142/// \brief Store a non-aggregate value to an address to initialize it. For
3143/// initialization, a non-atomic store will be used.
3144static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
3145 LValue Dst) {
3146 if (Src.isScalar())
3147 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
3148 else
3149 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
3150}
3151
3152void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
3153 llvm::Value *New) {
3154 DeferredReplacements.push_back(std::make_pair(Old, New));
3155}
Chris Lattnerd59d8672011-07-12 06:29:11 +00003156
Daniel Dunbard931a872009-02-02 22:03:45 +00003157RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00003158 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00003159 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003160 const CallArgList &CallArgs,
Samuel Antao798f11c2015-11-23 22:04:44 +00003161 CGCalleeInfo CalleeInfo,
David Chisnallff5f88c2010-05-02 13:41:58 +00003162 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00003163 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00003164
3165 // Handle struct-return functions by passing a pointer to the
3166 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00003167 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003168 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003169
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003170 llvm::FunctionType *IRFuncTy =
3171 cast<llvm::FunctionType>(
3172 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00003173
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003174 // If we're using inalloca, insert the allocation after the stack save.
3175 // FIXME: Do this earlier rather than hacking it in here!
John McCall7f416cc2015-09-08 08:05:57 +00003176 Address ArgMemory = Address::invalid();
3177 const llvm::StructLayout *ArgMemoryLayout = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003178 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
John McCall7f416cc2015-09-08 08:05:57 +00003179 ArgMemoryLayout = CGM.getDataLayout().getStructLayout(ArgStruct);
Reid Kleckner9df1d972014-04-10 01:40:15 +00003180 llvm::Instruction *IP = CallArgs.getStackBase();
3181 llvm::AllocaInst *AI;
3182 if (IP) {
3183 IP = IP->getNextNode();
3184 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
3185 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00003186 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00003187 }
John McCall7f416cc2015-09-08 08:05:57 +00003188 auto Align = CallInfo.getArgStructAlignment();
3189 AI->setAlignment(Align.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003190 AI->setUsedWithInAlloca(true);
3191 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
John McCall7f416cc2015-09-08 08:05:57 +00003192 ArgMemory = Address(AI, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003193 }
3194
John McCall7f416cc2015-09-08 08:05:57 +00003195 // Helper function to drill into the inalloca allocation.
3196 auto createInAllocaStructGEP = [&](unsigned FieldIndex) -> Address {
3197 auto FieldOffset =
3198 CharUnits::fromQuantity(ArgMemoryLayout->getElementOffset(FieldIndex));
3199 return Builder.CreateStructGEP(ArgMemory, FieldIndex, FieldOffset);
3200 };
3201
Alexey Samsonov153004f2014-09-29 22:08:00 +00003202 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003203 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3204
Chris Lattner4ca97c32009-06-13 00:26:38 +00003205 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00003206 // alloca to hold the result, unless one is given to us.
John McCall7f416cc2015-09-08 08:05:57 +00003207 Address SRetPtr = Address::invalid();
Leny Kholodov6aab1112015-06-08 10:23:49 +00003208 size_t UnusedReturnSize = 0;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003209 if (RetAI.isIndirect() || RetAI.isInAlloca()) {
John McCall7f416cc2015-09-08 08:05:57 +00003210 if (!ReturnValue.isNull()) {
3211 SRetPtr = ReturnValue.getValue();
3212 } else {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003213 SRetPtr = CreateMemTemp(RetTy);
Leny Kholodov6aab1112015-06-08 10:23:49 +00003214 if (HaveInsertPoint() && ReturnValue.isUnused()) {
3215 uint64_t size =
3216 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
John McCall7f416cc2015-09-08 08:05:57 +00003217 if (EmitLifetimeStart(size, SRetPtr.getPointer()))
Leny Kholodov6aab1112015-06-08 10:23:49 +00003218 UnusedReturnSize = size;
3219 }
3220 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003221 if (IRFunctionArgs.hasSRetArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00003222 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003223 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003224 Address Addr = createInAllocaStructGEP(RetAI.getInAllocaFieldIndex());
3225 Builder.CreateStore(SRetPtr.getPointer(), Addr);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003226 }
Anders Carlsson17490832009-12-24 20:40:36 +00003227 }
Mike Stump11289f42009-09-09 15:08:12 +00003228
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00003229 assert(CallInfo.arg_size() == CallArgs.size() &&
3230 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003231 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003232 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00003233 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003234 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003235 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003236 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003237
Rafael Espindolafad28de2012-10-24 01:59:00 +00003238 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003239 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3240 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3241 llvm::UndefValue::get(ArgInfo.getPaddingType());
3242
3243 unsigned FirstIRArg, NumIRArgs;
3244 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003245
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003246 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003247 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003248 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003249 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3250 if (RV.isAggregate()) {
3251 // Replace the placeholder with the appropriate argument slot GEP.
3252 llvm::Instruction *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00003253 cast<llvm::Instruction>(RV.getAggregatePointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003254 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3255 Builder.SetInsertPoint(Placeholder);
John McCall7f416cc2015-09-08 08:05:57 +00003256 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003257 Builder.restoreIP(IP);
John McCall7f416cc2015-09-08 08:05:57 +00003258 deferPlaceholderReplacement(Placeholder, Addr.getPointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003259 } else {
3260 // Store the RValue into the argument struct.
John McCall7f416cc2015-09-08 08:05:57 +00003261 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
3262 unsigned AS = Addr.getType()->getPointerAddressSpace();
David Majnemer32b57b02014-03-31 16:12:47 +00003263 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3264 // There are some cases where a trivial bitcast is not avoidable. The
3265 // definition of a type later in a translation unit may change it's type
3266 // from {}* to (%struct.foo*)*.
John McCall7f416cc2015-09-08 08:05:57 +00003267 if (Addr.getType() != MemType)
David Majnemer32b57b02014-03-31 16:12:47 +00003268 Addr = Builder.CreateBitCast(Addr, MemType);
John McCall7f416cc2015-09-08 08:05:57 +00003269 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003270 EmitInitStoreOfNonAggregate(*this, RV, argLV);
3271 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003272 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003273 }
3274
Daniel Dunbar03816342010-08-21 02:24:36 +00003275 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003276 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003277 if (RV.isScalar() || RV.isComplex()) {
3278 // Make a temporary alloca to pass the argument.
John McCall7f416cc2015-09-08 08:05:57 +00003279 Address Addr = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3280 IRCallArgs[FirstIRArg] = Addr.getPointer();
John McCall47fb9502013-03-07 21:37:08 +00003281
John McCall7f416cc2015-09-08 08:05:57 +00003282 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003283 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003284 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003285 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003286 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003287 // 1. If the argument is not byval, and we are required to copy the
3288 // source. (This case doesn't occur on any common architecture.)
3289 // 2. If the argument is byval, RV is not sufficiently aligned, and
3290 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00003291 // 3. If the argument is byval, but RV is located in an address space
3292 // different than that of the argument (0).
John McCall7f416cc2015-09-08 08:05:57 +00003293 Address Addr = RV.getAggregateAddress();
3294 CharUnits Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003295 const llvm::DataLayout *TD = &CGM.getDataLayout();
John McCall7f416cc2015-09-08 08:05:57 +00003296 const unsigned RVAddrSpace = Addr.getType()->getAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003297 const unsigned ArgAddrSpace =
3298 (FirstIRArg < IRFuncTy->getNumParams()
3299 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3300 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00003301 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall7f416cc2015-09-08 08:05:57 +00003302 (ArgInfo.getIndirectByVal() && Addr.getAlignment() < Align &&
3303 llvm::getOrEnforceKnownAlignment(Addr.getPointer(),
3304 Align.getQuantity(), *TD)
3305 < Align.getQuantity()) ||
Mehdi Aminib3d52092015-03-10 02:36:43 +00003306 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003307 // Create an aligned temporary, and copy to it.
John McCall7f416cc2015-09-08 08:05:57 +00003308 Address AI = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3309 IRCallArgs[FirstIRArg] = AI.getPointer();
Chad Rosier615ed1a2012-03-29 17:37:10 +00003310 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003311 } else {
3312 // Skip the extra memcpy call.
John McCall7f416cc2015-09-08 08:05:57 +00003313 IRCallArgs[FirstIRArg] = Addr.getPointer();
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003314 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003315 }
3316 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003317 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003318
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003319 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003320 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003321 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003322
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003323 case ABIArgInfo::Extend:
3324 case ABIArgInfo::Direct: {
3325 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003326 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3327 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003328 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003329 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003330 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003331 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003332 else
John McCall7f416cc2015-09-08 08:05:57 +00003333 V = Builder.CreateLoad(RV.getAggregateAddress());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003334
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003335 // We might have to widen integers, but we should never truncate.
3336 if (ArgInfo.getCoerceToType() != V->getType() &&
3337 V->getType()->isIntegerTy())
3338 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3339
Chris Lattner3ce86682011-07-12 04:53:39 +00003340 // If the argument doesn't match, perform a bitcast to coerce it. This
3341 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003342 if (FirstIRArg < IRFuncTy->getNumParams() &&
3343 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3344 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
3345 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003346 break;
3347 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003348
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003349 // FIXME: Avoid the conversion through memory if possible.
John McCall7f416cc2015-09-08 08:05:57 +00003350 Address Src = Address::invalid();
John McCall47fb9502013-03-07 21:37:08 +00003351 if (RV.isScalar() || RV.isComplex()) {
John McCall7f416cc2015-09-08 08:05:57 +00003352 Src = CreateMemTemp(I->Ty, "coerce");
3353 LValue SrcLV = MakeAddrLValue(Src, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003354 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003355 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003356 Src = RV.getAggregateAddress();
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003357 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003358
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003359 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00003360 Src = emitAddressAtOffset(*this, Src, ArgInfo);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003361
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003362 // Fast-isel and the optimizer generally like scalar values better than
3363 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00003364 llvm::StructType *STy =
3365 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003366 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
John McCall7f416cc2015-09-08 08:05:57 +00003367 llvm::Type *SrcTy = Src.getType()->getElementType();
Chandler Carrutha6399a52012-10-10 11:29:08 +00003368 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3369 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3370
3371 // If the source type is smaller than the destination type of the
3372 // coerce-to logic, copy the source value into a temp alloca the size
3373 // of the destination type to allow loading all of it. The bits past
3374 // the source value are left undef.
3375 if (SrcSize < DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00003376 Address TempAlloca
3377 = CreateTempAlloca(STy, Src.getAlignment(),
3378 Src.getName() + ".coerce");
3379 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
3380 Src = TempAlloca;
Chandler Carrutha6399a52012-10-10 11:29:08 +00003381 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003382 Src = Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(STy));
Chandler Carrutha6399a52012-10-10 11:29:08 +00003383 }
3384
John McCall7f416cc2015-09-08 08:05:57 +00003385 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003386 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00003387 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00003388 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
3389 Address EltPtr = Builder.CreateStructGEP(Src, i, Offset);
3390 llvm::Value *LI = Builder.CreateLoad(EltPtr);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003391 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003392 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003393 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003394 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003395 assert(NumIRArgs == 1);
3396 IRCallArgs[FirstIRArg] =
John McCall7f416cc2015-09-08 08:05:57 +00003397 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003398 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003399
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003400 break;
3401 }
3402
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003403 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003404 unsigned IRArgPos = FirstIRArg;
3405 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3406 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003407 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003408 }
3409 }
Mike Stump11289f42009-09-09 15:08:12 +00003410
John McCall7f416cc2015-09-08 08:05:57 +00003411 if (ArgMemory.isValid()) {
3412 llvm::Value *Arg = ArgMemory.getPointer();
Reid Klecknerafba553e2014-07-08 02:24:27 +00003413 if (CallInfo.isVariadic()) {
3414 // When passing non-POD arguments by value to variadic functions, we will
3415 // end up with a variadic prototype and an inalloca call site. In such
3416 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3417 // the callee.
3418 unsigned CalleeAS =
3419 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
3420 Callee = Builder.CreateBitCast(
3421 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
3422 } else {
3423 llvm::Type *LastParamTy =
3424 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3425 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003426#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003427 // Assert that these structs have equivalent element types.
3428 llvm::StructType *FullTy = CallInfo.getArgStruct();
3429 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3430 cast<llvm::PointerType>(LastParamTy)->getElementType());
3431 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3432 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3433 DE = DeclaredTy->element_end(),
3434 FI = FullTy->element_begin();
3435 DI != DE; ++DI, ++FI)
3436 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003437#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003438 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3439 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003440 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003441 assert(IRFunctionArgs.hasInallocaArg());
3442 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003443 }
3444
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003445 if (!CallArgs.getCleanupsToDeactivate().empty())
3446 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3447
Chris Lattner4ca97c32009-06-13 00:26:38 +00003448 // If the callee is a bitcast of a function to a varargs pointer to function
3449 // type, check to see if we can remove the bitcast. This handles some cases
3450 // with unprototyped functions.
3451 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3452 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003453 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3454 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00003455 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00003456 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00003457
Chris Lattner4ca97c32009-06-13 00:26:38 +00003458 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3459 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00003460 ActualFT->getNumParams() == CurFT->getNumParams() &&
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003461 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00003462 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00003463 bool ArgsMatch = true;
3464 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3465 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3466 ArgsMatch = false;
3467 break;
3468 }
Mike Stump11289f42009-09-09 15:08:12 +00003469
Chris Lattner4ca97c32009-06-13 00:26:38 +00003470 // Strip the cast if we can get away with it. This is a nice cleanup,
3471 // but also allows us to inline the function at -O0 if it is marked
3472 // always_inline.
3473 if (ArgsMatch)
3474 Callee = CalleeF;
3475 }
3476 }
Mike Stump11289f42009-09-09 15:08:12 +00003477
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003478 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3479 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3480 // Inalloca argument can have different type.
3481 if (IRFunctionArgs.hasInallocaArg() &&
3482 i == IRFunctionArgs.getInallocaArgNo())
3483 continue;
3484 if (i < IRFuncTy->getNumParams())
3485 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3486 }
3487
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003488 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003489 CodeGen::AttributeListType AttributeList;
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00003490 CGM.ConstructAttributeList(Callee->getName(), CallInfo, CalleeInfo,
3491 AttributeList, CallingConv,
3492 /*AttrOnCallSite=*/true);
Bill Wendling3087d022012-12-07 23:17:26 +00003493 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003494 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003495
David Majnemer4e52d6f2015-12-12 05:39:21 +00003496 bool CannotThrow;
3497 if (currentFunctionUsesSEHTry()) {
3498 // SEH cares about asynchronous exceptions, everything can "throw."
3499 CannotThrow = false;
3500 } else if (isCleanupPadScope() &&
3501 EHPersonality::get(*this).isMSVCXXPersonality()) {
3502 // The MSVC++ personality will implicitly terminate the program if an
3503 // exception is thrown. An unwind edge cannot be reached.
3504 CannotThrow = true;
3505 } else {
3506 // Otherwise, nowunind callsites will never throw.
3507 CannotThrow = Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
3508 llvm::Attribute::NoUnwind);
3509 }
3510 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00003511
David Majnemer0b17d442015-12-15 21:27:59 +00003512 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3513 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList);
3514
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003515 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003516 if (!InvokeDest) {
David Majnemer0b17d442015-12-15 21:27:59 +00003517 CS = Builder.CreateCall(Callee, IRCallArgs, BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00003518 } else {
3519 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
David Majnemer0b17d442015-12-15 21:27:59 +00003520 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs,
3521 BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00003522 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003523 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003524 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003525 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003526
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003527 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3528 !CS.hasFnAttr(llvm::Attribute::NoInline))
3529 Attrs =
3530 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3531 llvm::Attribute::AlwaysInline);
3532
David Majnemer4e52d6f2015-12-12 05:39:21 +00003533 // Disable inlining inside SEH __try blocks.
3534 if (isSEHTryScope())
Reid Klecknera5930002015-02-11 21:40:48 +00003535 Attrs =
3536 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3537 llvm::Attribute::NoInline);
3538
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003539 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003540 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003541
Betul Buyukkurt518276a2016-01-23 22:50:44 +00003542 // Insert instrumentation or attach profile metadata at indirect call sites
3543 if (!CS.getCalledFunction())
3544 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
3545 CS.getInstruction(), Callee);
3546
Dan Gohman515a60d2012-02-16 00:57:37 +00003547 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3548 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003549 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003550 AddObjCARCExceptionMetadata(CS.getInstruction());
3551
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003552 // If the call doesn't return, finish the basic block and clear the
3553 // insertion point; this allows the rest of IRgen to discard
3554 // unreachable code.
3555 if (CS.doesNotReturn()) {
Leny Kholodov6aab1112015-06-08 10:23:49 +00003556 if (UnusedReturnSize)
3557 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
John McCall7f416cc2015-09-08 08:05:57 +00003558 SRetPtr.getPointer());
Leny Kholodov6aab1112015-06-08 10:23:49 +00003559
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003560 Builder.CreateUnreachable();
3561 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003562
Mike Stump18bb9282009-05-16 07:57:57 +00003563 // FIXME: For now, emit a dummy basic block because expr emitters in
3564 // generally are not ready to handle emitting expressions at unreachable
3565 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003566 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003567
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003568 // Return a reasonable RValue.
3569 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003570 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003571
3572 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00003573 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003574 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003575
John McCall31168b02011-06-15 23:02:42 +00003576 // Emit any writebacks immediately. Arguably this should happen
3577 // after any return-value munging.
3578 if (CallArgs.hasWritebacks())
3579 emitWritebacks(*this, CallArgs);
3580
Nico Weber8cdb3f92015-08-25 18:43:32 +00003581 // The stack cleanup for inalloca arguments has to run out of the normal
3582 // lexical order, so deactivate it and run it manually here.
3583 CallArgs.freeArgumentMemory(*this);
3584
Samuel Antao798f11c2015-11-23 22:04:44 +00003585 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
3586 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
Akira Hatanakac8667622015-11-06 23:56:15 +00003587 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
3588 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
Samuel Antao798f11c2015-11-23 22:04:44 +00003589 }
Akira Hatanakac8667622015-11-06 23:56:15 +00003590
Hal Finkelee90a222014-09-26 05:04:30 +00003591 RValue Ret = [&] {
3592 switch (RetAI.getKind()) {
3593 case ABIArgInfo::InAlloca:
Leny Kholodov6aab1112015-06-08 10:23:49 +00003594 case ABIArgInfo::Indirect: {
3595 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
3596 if (UnusedReturnSize)
3597 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
John McCall7f416cc2015-09-08 08:05:57 +00003598 SRetPtr.getPointer());
Leny Kholodov6aab1112015-06-08 10:23:49 +00003599 return ret;
3600 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003601
Hal Finkelee90a222014-09-26 05:04:30 +00003602 case ABIArgInfo::Ignore:
3603 // If we are ignoring an argument that had a result, make sure to
3604 // construct the appropriate return value for our caller.
3605 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003606
Hal Finkelee90a222014-09-26 05:04:30 +00003607 case ABIArgInfo::Extend:
3608 case ABIArgInfo::Direct: {
3609 llvm::Type *RetIRTy = ConvertType(RetTy);
3610 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
3611 switch (getEvaluationKind(RetTy)) {
3612 case TEK_Complex: {
3613 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
3614 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
3615 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003616 }
Hal Finkelee90a222014-09-26 05:04:30 +00003617 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00003618 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00003619 bool DestIsVolatile = ReturnValue.isVolatile();
3620
John McCall7f416cc2015-09-08 08:05:57 +00003621 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00003622 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3623 DestIsVolatile = false;
3624 }
John McCall7f416cc2015-09-08 08:05:57 +00003625 BuildAggStore(*this, CI, DestPtr, DestIsVolatile);
Hal Finkelee90a222014-09-26 05:04:30 +00003626 return RValue::getAggregate(DestPtr);
3627 }
3628 case TEK_Scalar: {
3629 // If the argument doesn't match, perform a bitcast to coerce it. This
3630 // can happen due to trivial type mismatches.
3631 llvm::Value *V = CI;
3632 if (V->getType() != RetIRTy)
3633 V = Builder.CreateBitCast(V, RetIRTy);
3634 return RValue::get(V);
3635 }
3636 }
3637 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003638 }
Hal Finkelee90a222014-09-26 05:04:30 +00003639
John McCall7f416cc2015-09-08 08:05:57 +00003640 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00003641 bool DestIsVolatile = ReturnValue.isVolatile();
3642
John McCall7f416cc2015-09-08 08:05:57 +00003643 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00003644 DestPtr = CreateMemTemp(RetTy, "coerce");
3645 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00003646 }
Hal Finkelee90a222014-09-26 05:04:30 +00003647
3648 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00003649 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
3650 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Hal Finkelee90a222014-09-26 05:04:30 +00003651
3652 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003653 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003654
Hal Finkelee90a222014-09-26 05:04:30 +00003655 case ABIArgInfo::Expand:
3656 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00003657 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003658
Hal Finkelee90a222014-09-26 05:04:30 +00003659 llvm_unreachable("Unhandled ABIArgInfo::Kind");
3660 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003661
Samuel Antao798f11c2015-11-23 22:04:44 +00003662 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
3663
Hal Finkelee90a222014-09-26 05:04:30 +00003664 if (Ret.isScalar() && TargetDecl) {
3665 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
3666 llvm::Value *OffsetValue = nullptr;
3667 if (const auto *Offset = AA->getOffset())
3668 OffsetValue = EmitScalarExpr(Offset);
3669
3670 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
3671 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
3672 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
3673 OffsetValue);
3674 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00003675 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003676
Hal Finkelee90a222014-09-26 05:04:30 +00003677 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003678}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003679
3680/* VarArg handling */
3681
Charles Davisc7d5c942015-09-17 20:55:33 +00003682Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
3683 VAListAddr = VE->isMicrosoftABI()
3684 ? EmitMSVAListRef(VE->getSubExpr())
3685 : EmitVAListRef(VE->getSubExpr());
3686 QualType Ty = VE->getType();
3687 if (VE->isMicrosoftABI())
3688 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003689 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003690}