blob: b40fa9d93d4a8c01c7ceb8fcafd7c69922b7cc6a [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"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000018#include "CodeGenFunction.h"
Daniel Dunbarc68897d2008-09-10 00:41:16 +000019#include "CodeGenModule.h"
John McCalla729c622012-02-17 03:33:10 +000020#include "TargetInfo.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000021#include "clang/AST/Decl.h"
Anders Carlssonb15b55c2009-04-03 22:48:58 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000023#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000025#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000026#include "clang/Frontend/CodeGenOptions.h"
Bill Wendling706469b2013-02-28 22:49:57 +000027#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000028#include "llvm/IR/Attributes.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000029#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/InlineAsm.h"
Reid Kleckner314ef7b2014-02-01 00:04:45 +000032#include "llvm/IR/Intrinsics.h"
Eli Friedmanf7456192011-06-15 22:09:18 +000033#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000034using namespace clang;
35using namespace CodeGen;
36
37/***/
38
John McCallab26cfa2010-02-05 21:31:56 +000039static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
40 switch (CC) {
41 default: return llvm::CallingConv::C;
42 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
43 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000044 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davisb5a214e2013-08-30 04:39:01 +000045 case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
46 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000047 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
48 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000049 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Dawn Perchik335e16b2010-09-03 01:29:35 +000050 // TODO: add support for CC_X86Pascal to llvm
John McCallab26cfa2010-02-05 21:31:56 +000051 }
52}
53
John McCall8ee376f2010-02-24 07:14:12 +000054/// Derives the 'this' type for codegen purposes, i.e. ignoring method
55/// qualification.
56/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000057static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
58 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
59 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000060}
61
John McCall8ee376f2010-02-24 07:14:12 +000062/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000063static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
64 return MD->getType()->getCanonicalTypeUnqualified()
65 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000066}
67
68/// Returns the "extra-canonicalized" return type, which discards
69/// qualifiers on the return type. Codegen doesn't care about them,
70/// and it makes ABI code a little easier to be able to assume that
71/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000072static CanQualType GetReturnType(QualType RetTy) {
73 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000074}
75
John McCall8dda7b22012-07-07 06:41:13 +000076/// Arrange the argument and result information for a value of the given
77/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000078const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000079CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000080 // When translating an unprototyped function type, always use a
81 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000082 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Reid Kleckner4982b822014-01-31 22:54:50 +000083 false, None, FTNP->getExtInfo(),
84 RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +000085}
86
John McCall8dda7b22012-07-07 06:41:13 +000087/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +000088/// type, on top of any implicit parameters already stored.
89static const CGFunctionInfo &
90arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool IsInstanceMethod,
91 SmallVectorImpl<CanQualType> &prefix,
92 CanQual<FunctionProtoType> FTP) {
John McCall8dda7b22012-07-07 06:41:13 +000093 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +000094 // FIXME: Kill copy.
Alp Toker9cacbab2014-01-20 20:26:09 +000095 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
96 prefix.push_back(FTP->getParamType(i));
Alp Toker314cc812014-01-25 16:55:45 +000097 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
Reid Kleckner4982b822014-01-31 22:54:50 +000098 return CGT.arrangeLLVMFunctionInfo(resultType, IsInstanceMethod, prefix,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +000099 FTP->getExtInfo(), required);
John McCall8ee376f2010-02-24 07:14:12 +0000100}
101
John McCalla729c622012-02-17 03:33:10 +0000102/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000103/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000104const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000105CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
John McCalla729c622012-02-17 03:33:10 +0000106 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000107 return ::arrangeLLVMFunctionInfo(*this, false, argTypes, FTP);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000108}
109
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000110static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000111 // Set the appropriate calling convention for the Function.
112 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000113 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000114
115 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000116 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000117
Douglas Gregora941dca2010-05-18 16:57:00 +0000118 if (D->hasAttr<ThisCallAttr>())
119 return CC_X86ThisCall;
120
Dawn Perchik335e16b2010-09-03 01:29:35 +0000121 if (D->hasAttr<PascalAttr>())
122 return CC_X86Pascal;
123
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000124 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
125 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
126
Derek Schuffa2020962012-10-16 22:30:41 +0000127 if (D->hasAttr<PnaclCallAttr>())
128 return CC_PnaclCall;
129
Guy Benyeif0a014b2012-12-25 08:53:55 +0000130 if (D->hasAttr<IntelOclBiccAttr>())
131 return CC_IntelOclBicc;
132
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000133 if (D->hasAttr<MSABIAttr>())
134 return IsWindows ? CC_C : CC_X86_64Win64;
135
136 if (D->hasAttr<SysVABIAttr>())
137 return IsWindows ? CC_X86_64SysV : CC_C;
138
John McCallab26cfa2010-02-05 21:31:56 +0000139 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000140}
141
John McCalla729c622012-02-17 03:33:10 +0000142/// Arrange the argument and result information for a call to an
143/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000144/// (Zero value of RD means we don't have any meaningful "this" argument type,
145/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000146/// The member function must be an ordinary function, i.e. not a
147/// constructor or destructor.
148const CGFunctionInfo &
149CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
150 const FunctionProtoType *FTP) {
151 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000152
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000153 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000154 if (RD)
155 argTypes.push_back(GetThisType(Context, RD));
156 else
157 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000158
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000159 return ::arrangeLLVMFunctionInfo(
160 *this, true, argTypes,
161 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000162}
163
John McCalla729c622012-02-17 03:33:10 +0000164/// Arrange the argument and result information for a declaration or
165/// definition of the given C++ non-static member function. The
166/// member function must be an ordinary function, i.e. not a
167/// constructor or destructor.
168const CGFunctionInfo &
169CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000170 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000171 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
172
John McCalla729c622012-02-17 03:33:10 +0000173 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000174
John McCalla729c622012-02-17 03:33:10 +0000175 if (MD->isInstance()) {
176 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000177 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000178 return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
John McCalla729c622012-02-17 03:33:10 +0000179 }
180
John McCall8dda7b22012-07-07 06:41:13 +0000181 return arrangeFreeFunctionType(prototype);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000182}
183
John McCalla729c622012-02-17 03:33:10 +0000184const CGFunctionInfo &
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000185CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
186 StructorType Type) {
187
John McCalla729c622012-02-17 03:33:10 +0000188 SmallVector<CanQualType, 16> argTypes;
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000189 argTypes.push_back(GetThisType(Context, MD->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000190
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000191 GlobalDecl GD;
192 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
193 GD = GlobalDecl(CD, toCXXCtorType(Type));
194 } else {
195 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
196 GD = GlobalDecl(DD, toCXXDtorType(Type));
197 }
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000198
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000199 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall5d865c322010-08-31 07:33:07 +0000200
201 // Add the formal parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000202 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
203 argTypes.push_back(FTP->getParamType(i));
John McCall5d865c322010-08-31 07:33:07 +0000204
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000205 TheCXXABI.buildStructorSignature(MD, Type, argTypes);
Reid Kleckner89077a12013-12-17 19:46:40 +0000206
207 RequiredArgs required =
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000208 (MD->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
Reid Kleckner89077a12013-12-17 19:46:40 +0000209
John McCall8dda7b22012-07-07 06:41:13 +0000210 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000211 CanQualType resultType =
212 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
Reid Kleckner4982b822014-01-31 22:54:50 +0000213 return arrangeLLVMFunctionInfo(resultType, true, argTypes, extInfo, required);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000214}
215
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000216/// Arrange a call to a C++ method, passing the given arguments.
217const CGFunctionInfo &
218CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
219 const CXXConstructorDecl *D,
220 CXXCtorType CtorKind,
221 unsigned ExtraArgs) {
222 // FIXME: Kill copy.
223 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000224 for (const auto &Arg : args)
225 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000226
227 CanQual<FunctionProtoType> FPT = GetFormalType(D);
228 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
229 GlobalDecl GD(D, CtorKind);
230 CanQualType ResultType =
231 TheCXXABI.HasThisReturn(GD) ? ArgTypes.front() : Context.VoidTy;
232
233 FunctionType::ExtInfo Info = FPT->getExtInfo();
234 return arrangeLLVMFunctionInfo(ResultType, true, ArgTypes, Info, Required);
235}
236
John McCalla729c622012-02-17 03:33:10 +0000237/// Arrange the argument and result information for the declaration or
238/// definition of the given function.
239const CGFunctionInfo &
240CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000241 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000242 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000243 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000244
John McCall2da83a32010-02-26 00:48:12 +0000245 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000246
John McCall2da83a32010-02-26 00:48:12 +0000247 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000248
249 // When declaring a function without a prototype, always use a
250 // non-variadic type.
251 if (isa<FunctionNoProtoType>(FTy)) {
252 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Reid Kleckner4982b822014-01-31 22:54:50 +0000253 return arrangeLLVMFunctionInfo(noProto->getReturnType(), false, None,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000254 noProto->getExtInfo(), RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000255 }
256
John McCall2da83a32010-02-26 00:48:12 +0000257 assert(isa<FunctionProtoType>(FTy));
John McCall8dda7b22012-07-07 06:41:13 +0000258 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000259}
260
John McCalla729c622012-02-17 03:33:10 +0000261/// Arrange the argument and result information for the declaration or
262/// definition of an Objective-C method.
263const CGFunctionInfo &
264CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
265 // It happens that this is the same as a call with no optional
266 // arguments, except also using the formal 'self' type.
267 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
268}
269
270/// Arrange the argument and result information for the function type
271/// through which to perform a send to the given Objective-C method,
272/// using the given receiver type. The receiver type is not always
273/// the 'self' type of the method or even an Objective-C pointer type.
274/// This is *not* the right method for actually performing such a
275/// message send, due to the possibility of optional arguments.
276const CGFunctionInfo &
277CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
278 QualType receiverType) {
279 SmallVector<CanQualType, 16> argTys;
280 argTys.push_back(Context.getCanonicalParamType(receiverType));
281 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000282 // FIXME: Kill copy?
Aaron Ballman43b68be2014-03-07 17:50:17 +0000283 for (const auto *I : MD->params()) {
284 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000285 }
John McCall31168b02011-06-15 23:02:42 +0000286
287 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000288 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
289 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000290
David Blaikiebbafb8a2012-03-11 07:00:24 +0000291 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000292 MD->hasAttr<NSReturnsRetainedAttr>())
293 einfo = einfo.withProducesResult(true);
294
John McCalla729c622012-02-17 03:33:10 +0000295 RequiredArgs required =
296 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
297
Reid Kleckner4982b822014-01-31 22:54:50 +0000298 return arrangeLLVMFunctionInfo(GetReturnType(MD->getReturnType()), false,
299 argTys, einfo, required);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000300}
301
John McCalla729c622012-02-17 03:33:10 +0000302const CGFunctionInfo &
303CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000304 // FIXME: Do we need to handle ObjCMethodDecl?
305 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000306
Anders Carlsson6710c532010-02-06 02:44:09 +0000307 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000308 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
Anders Carlsson6710c532010-02-06 02:44:09 +0000309
310 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000311 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000312
John McCalla729c622012-02-17 03:33:10 +0000313 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000314}
315
Reid Klecknerc3473512014-08-29 21:43:29 +0000316/// Arrange a thunk that takes 'this' as the first parameter followed by
317/// varargs. Return a void pointer, regardless of the actual return type.
318/// The body of the thunk will end in a musttail call to a function of the
319/// correct type, and the caller will bitcast the function to the correct
320/// prototype.
321const CGFunctionInfo &
322CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
323 assert(MD->isVirtual() && "only virtual memptrs have thunks");
324 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
325 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
326 return arrangeLLVMFunctionInfo(Context.VoidTy, false, ArgTys,
327 FTP->getExtInfo(), RequiredArgs(1));
328}
329
John McCallc818bbb2012-12-07 07:03:17 +0000330/// Arrange a call as unto a free function, except possibly with an
331/// additional number of formal parameters considered required.
332static const CGFunctionInfo &
333arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000334 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000335 const CallArgList &args,
336 const FunctionType *fnType,
337 unsigned numExtraRequiredArgs) {
338 assert(args.size() >= numExtraRequiredArgs);
339
340 // In most cases, there are no optional arguments.
341 RequiredArgs required = RequiredArgs::All;
342
343 // If we have a variadic prototype, the required arguments are the
344 // extra prefix plus the arguments in the prototype.
345 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
346 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000347 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000348
349 // If we don't have a prototype at all, but we're supposed to
350 // explicitly use the variadic convention for unprototyped calls,
351 // treat all of the arguments as required but preserve the nominal
352 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000353 } else if (CGM.getTargetCodeGenInfo()
354 .isNoProtoCallVariadic(args,
355 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000356 required = RequiredArgs(args.size());
357 }
358
Alp Toker314cc812014-01-25 16:55:45 +0000359 return CGT.arrangeFreeFunctionCall(fnType->getReturnType(), args,
John McCallc818bbb2012-12-07 07:03:17 +0000360 fnType->getExtInfo(), required);
361}
362
John McCalla729c622012-02-17 03:33:10 +0000363/// Figure out the rules for calling a function with the given formal
364/// type using the given arguments. The arguments are necessary
365/// because the function might be unprototyped, in which case it's
366/// target-dependent in crazy ways.
367const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000368CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
369 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000370 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 0);
John McCallc818bbb2012-12-07 07:03:17 +0000371}
John McCalla729c622012-02-17 03:33:10 +0000372
John McCallc818bbb2012-12-07 07:03:17 +0000373/// A block function call is essentially a free-function call with an
374/// extra implicit argument.
375const CGFunctionInfo &
376CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
377 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000378 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1);
John McCalla729c622012-02-17 03:33:10 +0000379}
380
381const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000382CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
383 const CallArgList &args,
384 FunctionType::ExtInfo info,
385 RequiredArgs required) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000386 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000387 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000388 for (const auto &Arg : args)
389 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner4982b822014-01-31 22:54:50 +0000390 return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes,
391 info, required);
John McCall8dda7b22012-07-07 06:41:13 +0000392}
393
394/// Arrange a call to a C++ method, passing the given arguments.
395const CGFunctionInfo &
396CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
397 const FunctionProtoType *FPT,
398 RequiredArgs required) {
399 // FIXME: Kill copy.
400 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000401 for (const auto &Arg : args)
402 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
John McCall8dda7b22012-07-07 06:41:13 +0000403
404 FunctionType::ExtInfo info = FPT->getExtInfo();
Reid Kleckner4982b822014-01-31 22:54:50 +0000405 return arrangeLLVMFunctionInfo(GetReturnType(FPT->getReturnType()), true,
406 argTypes, info, required);
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000407}
408
Reid Kleckner4982b822014-01-31 22:54:50 +0000409const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
410 QualType resultType, const FunctionArgList &args,
411 const FunctionType::ExtInfo &info, bool isVariadic) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000412 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000413 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000414 for (auto Arg : args)
415 argTypes.push_back(Context.getCanonicalParamType(Arg->getType()));
John McCalla729c622012-02-17 03:33:10 +0000416
417 RequiredArgs required =
418 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
Reid Kleckner4982b822014-01-31 22:54:50 +0000419 return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes, info,
John McCall8dda7b22012-07-07 06:41:13 +0000420 required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000421}
422
John McCalla729c622012-02-17 03:33:10 +0000423const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Reid Kleckner4982b822014-01-31 22:54:50 +0000424 return arrangeLLVMFunctionInfo(getContext().VoidTy, false, None,
John McCall8dda7b22012-07-07 06:41:13 +0000425 FunctionType::ExtInfo(), RequiredArgs::All);
John McCalla738c252011-03-09 04:27:21 +0000426}
427
John McCalla729c622012-02-17 03:33:10 +0000428/// Arrange the argument and result information for an abstract value
429/// of a given function type. This is the method which all of the
430/// above functions ultimately defer to.
431const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000432CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Reid Kleckner4982b822014-01-31 22:54:50 +0000433 bool IsInstanceMethod,
John McCall8dda7b22012-07-07 06:41:13 +0000434 ArrayRef<CanQualType> argTypes,
435 FunctionType::ExtInfo info,
436 RequiredArgs required) {
John McCall2da83a32010-02-26 00:48:12 +0000437#ifndef NDEBUG
John McCalla729c622012-02-17 03:33:10 +0000438 for (ArrayRef<CanQualType>::const_iterator
439 I = argTypes.begin(), E = argTypes.end(); I != E; ++I)
John McCall2da83a32010-02-26 00:48:12 +0000440 assert(I->isCanonicalAsParam());
441#endif
442
John McCalla729c622012-02-17 03:33:10 +0000443 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCallab26cfa2010-02-05 21:31:56 +0000444
Daniel Dunbare0be8292009-02-03 00:07:12 +0000445 // Lookup or create unique function info.
446 llvm::FoldingSetNodeID ID;
Reid Kleckner4982b822014-01-31 22:54:50 +0000447 CGFunctionInfo::Profile(ID, IsInstanceMethod, info, required, resultType,
448 argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000449
Craig Topper8a13c412014-05-21 05:09:00 +0000450 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000451 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000452 if (FI)
453 return *FI;
454
John McCalla729c622012-02-17 03:33:10 +0000455 // Construct the function info. We co-allocate the ArgInfos.
Reid Kleckner4982b822014-01-31 22:54:50 +0000456 FI = CGFunctionInfo::create(CC, IsInstanceMethod, info, resultType, argTypes,
457 required);
John McCalla729c622012-02-17 03:33:10 +0000458 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000459
John McCalla729c622012-02-17 03:33:10 +0000460 bool inserted = FunctionsBeingProcessed.insert(FI); (void)inserted;
461 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000462
Daniel Dunbar313321e2009-02-03 05:31:23 +0000463 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000464 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000465
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000466 // Loop over all of the computed argument and return value info. If any of
467 // them are direct or extend without a specified coerce type, specify the
468 // default now.
John McCalla729c622012-02-17 03:33:10 +0000469 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000470 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000471 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000472
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000473 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000474 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000475 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000476
John McCalla729c622012-02-17 03:33:10 +0000477 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
478 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000479
Daniel Dunbare0be8292009-02-03 00:07:12 +0000480 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000481}
482
John McCalla729c622012-02-17 03:33:10 +0000483CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Reid Kleckner4982b822014-01-31 22:54:50 +0000484 bool IsInstanceMethod,
John McCalla729c622012-02-17 03:33:10 +0000485 const FunctionType::ExtInfo &info,
486 CanQualType resultType,
487 ArrayRef<CanQualType> argTypes,
488 RequiredArgs required) {
489 void *buffer = operator new(sizeof(CGFunctionInfo) +
490 sizeof(ArgInfo) * (argTypes.size() + 1));
491 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
492 FI->CallingConvention = llvmCC;
493 FI->EffectiveCallingConvention = llvmCC;
494 FI->ASTCallingConvention = info.getCC();
Reid Kleckner4982b822014-01-31 22:54:50 +0000495 FI->InstanceMethod = IsInstanceMethod;
John McCalla729c622012-02-17 03:33:10 +0000496 FI->NoReturn = info.getNoReturn();
497 FI->ReturnsRetained = info.getProducesResult();
498 FI->Required = required;
499 FI->HasRegParm = info.getHasRegParm();
500 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000501 FI->ArgStruct = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000502 FI->NumArgs = argTypes.size();
503 FI->getArgsBuffer()[0].type = resultType;
504 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
505 FI->getArgsBuffer()[i + 1].type = argTypes[i];
506 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000507}
508
509/***/
510
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000511namespace {
512// ABIArgInfo::Expand implementation.
513
514// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
515struct TypeExpansion {
516 enum TypeExpansionKind {
517 // Elements of constant arrays are expanded recursively.
518 TEK_ConstantArray,
519 // Record fields are expanded recursively (but if record is a union, only
520 // the field with the largest size is expanded).
521 TEK_Record,
522 // For complex types, real and imaginary parts are expanded recursively.
523 TEK_Complex,
524 // All other types are not expandable.
525 TEK_None
526 };
527
528 const TypeExpansionKind Kind;
529
530 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
531 virtual ~TypeExpansion() {}
532};
533
534struct ConstantArrayExpansion : TypeExpansion {
535 QualType EltTy;
536 uint64_t NumElts;
537
538 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
539 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
540 static bool classof(const TypeExpansion *TE) {
541 return TE->Kind == TEK_ConstantArray;
542 }
543};
544
545struct RecordExpansion : TypeExpansion {
546 SmallVector<const FieldDecl *, 1> Fields;
547
548 RecordExpansion(SmallVector<const FieldDecl *, 1> &&Fields)
549 : TypeExpansion(TEK_Record), Fields(Fields) {}
550 static bool classof(const TypeExpansion *TE) {
551 return TE->Kind == TEK_Record;
552 }
553};
554
555struct ComplexExpansion : TypeExpansion {
556 QualType EltTy;
557
558 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
559 static bool classof(const TypeExpansion *TE) {
560 return TE->Kind == TEK_Complex;
561 }
562};
563
564struct NoExpansion : TypeExpansion {
565 NoExpansion() : TypeExpansion(TEK_None) {}
566 static bool classof(const TypeExpansion *TE) {
567 return TE->Kind == TEK_None;
568 }
569};
570} // namespace
571
572static std::unique_ptr<TypeExpansion>
573getTypeExpansion(QualType Ty, const ASTContext &Context) {
574 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
575 return llvm::make_unique<ConstantArrayExpansion>(
576 AT->getElementType(), AT->getSize().getZExtValue());
577 }
578 if (const RecordType *RT = Ty->getAs<RecordType>()) {
579 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000580 const RecordDecl *RD = RT->getDecl();
581 assert(!RD->hasFlexibleArrayMember() &&
582 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000583 if (RD->isUnion()) {
584 // Unions can be here only in degenerative cases - all the fields are same
585 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000586 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000587 CharUnits UnionSize = CharUnits::Zero();
588
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000589 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000590 assert(!FD->isBitField() &&
591 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000592 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000593 if (UnionSize < FieldSize) {
594 UnionSize = FieldSize;
595 LargestFD = FD;
596 }
597 }
598 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000599 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000600 } else {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000601 for (const auto *FD : RD->fields()) {
602 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000603 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000604 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000605 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000606 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000607 return llvm::make_unique<RecordExpansion>(std::move(Fields));
608 }
609 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
610 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
611 }
612 return llvm::make_unique<NoExpansion>();
613}
614
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000615static int getExpansionSize(QualType Ty, const ASTContext &Context) {
616 auto Exp = getTypeExpansion(Ty, Context);
617 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
618 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
619 }
620 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
621 int Res = 0;
622 for (auto FD : RExp->Fields)
623 Res += getExpansionSize(FD->getType(), Context);
624 return Res;
625 }
626 if (isa<ComplexExpansion>(Exp.get()))
627 return 2;
628 assert(isa<NoExpansion>(Exp.get()));
629 return 1;
630}
631
Alexey Samsonov153004f2014-09-29 22:08:00 +0000632void
633CodeGenTypes::getExpandedTypes(QualType Ty,
634 SmallVectorImpl<llvm::Type *>::iterator &TI) {
635 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000636 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
637 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000638 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000639 }
640 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
641 for (auto FD : RExp->Fields) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000642 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000643 }
644 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
645 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000646 *TI++ = EltTy;
647 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000648 } else {
649 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000650 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000651 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000652}
653
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000654void CodeGenFunction::ExpandTypeFromArgs(
655 QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000656 assert(LV.isSimple() &&
657 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000658
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000659 auto Exp = getTypeExpansion(Ty, getContext());
660 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
661 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
662 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, i);
663 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
664 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000665 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000666 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
667 for (auto FD : RExp->Fields) {
668 // FIXME: What are the right qualifiers here?
669 LValue SubLV = EmitLValueForField(LV, FD);
670 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000671 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000672 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000673 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000674 EmitStoreThroughLValue(RValue::get(*AI++),
675 MakeAddrLValue(RealAddr, CExp->EltTy));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000676 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000677 EmitStoreThroughLValue(RValue::get(*AI++),
678 MakeAddrLValue(ImagAddr, CExp->EltTy));
679 } else {
680 assert(isa<NoExpansion>(Exp.get()));
681 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000682 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000683}
684
685void CodeGenFunction::ExpandTypeToArgs(
686 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
687 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
688 auto Exp = getTypeExpansion(Ty, getContext());
689 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
690 llvm::Value *Addr = RV.getAggregateAddr();
691 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
692 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, i);
693 RValue EltRV =
694 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
695 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
696 }
697 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
698 LValue LV = MakeAddrLValue(RV.getAggregateAddr(), Ty);
699 for (auto FD : RExp->Fields) {
700 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
701 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
702 IRCallArgPos);
703 }
704 } else if (isa<ComplexExpansion>(Exp.get())) {
705 ComplexPairTy CV = RV.getComplexVal();
706 IRCallArgs[IRCallArgPos++] = CV.first;
707 IRCallArgs[IRCallArgPos++] = CV.second;
708 } else {
709 assert(isa<NoExpansion>(Exp.get()));
710 assert(RV.isScalar() &&
711 "Unexpected non-scalar rvalue during struct expansion.");
712
713 // Insert a bitcast as needed.
714 llvm::Value *V = RV.getScalarVal();
715 if (IRCallArgPos < IRFuncTy->getNumParams() &&
716 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
717 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
718
719 IRCallArgs[IRCallArgPos++] = V;
720 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000721}
722
Chris Lattner895c52b2010-06-27 06:04:18 +0000723/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000724/// accessing some number of bytes out of it, try to gep into the struct to get
725/// at its inner goodness. Dive as deep as possible without entering an element
726/// with an in-memory size smaller than DstSize.
727static llvm::Value *
Chris Lattner895c52b2010-06-27 06:04:18 +0000728EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000729 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000730 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000731 // We can't dive into a zero-element struct.
732 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000733
Chris Lattner2192fe52011-07-18 04:24:23 +0000734 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000735
Chris Lattner1cd66982010-06-27 05:56:15 +0000736 // 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 +0000737 // first element is the same size as the whole struct, we can enter it. The
738 // comparison must be made on the store size and not the alloca size. Using
739 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000740 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +0000741 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000742 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +0000743 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000744 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000745
Chris Lattner1cd66982010-06-27 05:56:15 +0000746 // GEP into the first element.
747 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000748
Chris Lattner1cd66982010-06-27 05:56:15 +0000749 // If the first element is a struct, recurse.
Chris Lattner2192fe52011-07-18 04:24:23 +0000750 llvm::Type *SrcTy =
Chris Lattner1cd66982010-06-27 05:56:15 +0000751 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000752 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000753 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000754
755 return SrcPtr;
756}
757
Chris Lattner055097f2010-06-27 06:26:04 +0000758/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
759/// are either integers or pointers. This does a truncation of the value if it
760/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000761///
762/// This behaves as if the value were coerced through memory, so on big-endian
763/// targets the high bits are preserved in a truncation, while little-endian
764/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000765static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000766 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000767 CodeGenFunction &CGF) {
768 if (Val->getType() == Ty)
769 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000770
Chris Lattner055097f2010-06-27 06:26:04 +0000771 if (isa<llvm::PointerType>(Val->getType())) {
772 // If this is Pointer->Pointer avoid conversion to and from int.
773 if (isa<llvm::PointerType>(Ty))
774 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000775
Chris Lattner055097f2010-06-27 06:26:04 +0000776 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000777 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000778 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000779
Chris Lattner2192fe52011-07-18 04:24:23 +0000780 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000781 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000782 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000783
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000784 if (Val->getType() != DestIntTy) {
785 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
786 if (DL.isBigEndian()) {
787 // Preserve the high bits on big-endian targets.
788 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +0000789 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
790 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
791
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000792 if (SrcSize > DstSize) {
793 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
794 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
795 } else {
796 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
797 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
798 }
799 } else {
800 // Little-endian targets preserve the low bits. No shifts required.
801 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
802 }
803 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000804
Chris Lattner055097f2010-06-27 06:26:04 +0000805 if (isa<llvm::PointerType>(Ty))
806 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
807 return Val;
808}
809
Chris Lattner1cd66982010-06-27 05:56:15 +0000810
811
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000812/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
813/// a pointer to an object of type \arg Ty.
814///
815/// This safely handles the case when the src type is smaller than the
816/// destination type; in this situation the values of bits which not
817/// present in the src are undefined.
818static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000819 llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000820 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000821 llvm::Type *SrcTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000822 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000823
Chris Lattnerd200eda2010-06-28 22:51:39 +0000824 // If SrcTy and Ty are the same, just do a load.
825 if (SrcTy == Ty)
826 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000827
Micah Villmowdd31ca12012-10-08 16:25:52 +0000828 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000829
Chris Lattner2192fe52011-07-18 04:24:23 +0000830 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000831 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000832 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
833 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000834
Micah Villmowdd31ca12012-10-08 16:25:52 +0000835 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000836
Chris Lattner055097f2010-06-27 06:26:04 +0000837 // If the source and destination are integer or pointer types, just do an
838 // extension or truncation to the desired type.
839 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
840 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
841 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
842 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
843 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000844
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000845 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000846 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000847 // Generally SrcSize is never greater than DstSize, since this means we are
848 // losing bits. However, this can happen in cases where the structure has
849 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000850 //
Mike Stump18bb9282009-05-16 07:57:57 +0000851 // FIXME: Assert that we aren't truncating non-padding bits when have access
852 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000853 llvm::Value *Casted =
854 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000855 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
856 // FIXME: Use better alignment / avoid requiring aligned load.
857 Load->setAlignment(1);
858 return Load;
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000859 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000860
Chris Lattner3fcc7902010-06-27 01:06:27 +0000861 // Otherwise do coercion through memory. This is stupid, but
862 // simple.
863 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Ren84b921f2012-11-28 22:08:52 +0000864 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
865 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
866 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000867 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000868 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
869 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
870 1, false);
Chris Lattner3fcc7902010-06-27 01:06:27 +0000871 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000872}
873
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000874// Function to store a first-class aggregate into memory. We prefer to
875// store the elements rather than the aggregate to be more friendly to
876// fast-isel.
877// FIXME: Do we need to recurse here?
878static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
879 llvm::Value *DestPtr, bool DestIsVolatile,
880 bool LowAlignment) {
881 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +0000882 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000883 dyn_cast<llvm::StructType>(Val->getType())) {
884 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
885 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
886 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
887 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
888 DestIsVolatile);
889 if (LowAlignment)
890 SI->setAlignment(1);
891 }
892 } else {
Bill Wendlingf6af30f2012-03-16 21:45:12 +0000893 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
894 if (LowAlignment)
895 SI->setAlignment(1);
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000896 }
897}
898
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000899/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
900/// where the source and destination may have different types.
901///
902/// This safely handles the case when the src type is larger than the
903/// destination type; the upper bits of the src will be lost.
904static void CreateCoercedStore(llvm::Value *Src,
905 llvm::Value *DstPtr,
Anders Carlsson17490832009-12-24 20:40:36 +0000906 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000907 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000908 llvm::Type *SrcTy = Src->getType();
909 llvm::Type *DstTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000910 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +0000911 if (SrcTy == DstTy) {
912 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
913 return;
914 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000915
Micah Villmowdd31ca12012-10-08 16:25:52 +0000916 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000917
Chris Lattner2192fe52011-07-18 04:24:23 +0000918 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000919 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
920 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
921 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000922
Chris Lattner055097f2010-06-27 06:26:04 +0000923 // If the source and destination are integer or pointer types, just do an
924 // extension or truncation to the desired type.
925 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
926 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
927 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
928 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
929 return;
930 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000931
Micah Villmowdd31ca12012-10-08 16:25:52 +0000932 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000933
Daniel Dunbar313321e2009-02-03 05:31:23 +0000934 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000935 if (SrcSize <= DstSize) {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000936 llvm::Value *Casted =
937 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000938 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000939 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000940 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000941 // Otherwise do coercion through memory. This is stupid, but
942 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000943
944 // Generally SrcSize is never greater than DstSize, since this means we are
945 // losing bits. However, this can happen in cases where the structure has
946 // additional padding, for example due to a user specified alignment.
947 //
948 // FIXME: Assert that we aren't truncating non-padding bits when have access
949 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000950 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
951 CGF.Builder.CreateStore(Src, Tmp);
Manman Ren84b921f2012-11-28 22:08:52 +0000952 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
953 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
954 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000955 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000956 CGF.Builder.CreateMemCpy(DstCasted, Casted,
957 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
958 1, false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000959 }
960}
961
Alexey Samsonov153004f2014-09-29 22:08:00 +0000962namespace {
963
964/// Encapsulates information about the way function arguments from
965/// CGFunctionInfo should be passed to actual LLVM IR function.
966class ClangToLLVMArgMapping {
967 static const unsigned InvalidIndex = ~0U;
968 unsigned InallocaArgNo;
969 unsigned SRetArgNo;
970 unsigned TotalIRArgs;
971
972 /// Arguments of LLVM IR function corresponding to single Clang argument.
973 struct IRArgs {
974 unsigned PaddingArgIndex;
975 // Argument is expanded to IR arguments at positions
976 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
977 unsigned FirstArgIndex;
978 unsigned NumberOfArgs;
979
980 IRArgs()
981 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
982 NumberOfArgs(0) {}
983 };
984
985 SmallVector<IRArgs, 8> ArgInfo;
986
987public:
988 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
989 bool OnlyRequiredArgs = false)
990 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
991 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
992 construct(Context, FI, OnlyRequiredArgs);
993 }
994
995 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
996 unsigned getInallocaArgNo() const {
997 assert(hasInallocaArg());
998 return InallocaArgNo;
999 }
1000
1001 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1002 unsigned getSRetArgNo() const {
1003 assert(hasSRetArg());
1004 return SRetArgNo;
1005 }
1006
1007 unsigned totalIRArgs() const { return TotalIRArgs; }
1008
1009 bool hasPaddingArg(unsigned ArgNo) const {
1010 assert(ArgNo < ArgInfo.size());
1011 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1012 }
1013 unsigned getPaddingArgNo(unsigned ArgNo) const {
1014 assert(hasPaddingArg(ArgNo));
1015 return ArgInfo[ArgNo].PaddingArgIndex;
1016 }
1017
1018 /// Returns index of first IR argument corresponding to ArgNo, and their
1019 /// quantity.
1020 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1021 assert(ArgNo < ArgInfo.size());
1022 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1023 ArgInfo[ArgNo].NumberOfArgs);
1024 }
1025
1026private:
1027 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1028 bool OnlyRequiredArgs);
1029};
1030
1031void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1032 const CGFunctionInfo &FI,
1033 bool OnlyRequiredArgs) {
1034 unsigned IRArgNo = 0;
1035 bool SwapThisWithSRet = false;
1036 const ABIArgInfo &RetAI = FI.getReturnInfo();
1037
1038 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1039 SwapThisWithSRet = RetAI.isSRetAfterThis();
1040 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1041 }
1042
1043 unsigned ArgNo = 0;
1044 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1045 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1046 ++I, ++ArgNo) {
1047 assert(I != FI.arg_end());
1048 QualType ArgType = I->type;
1049 const ABIArgInfo &AI = I->info;
1050 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1051 auto &IRArgs = ArgInfo[ArgNo];
1052
1053 if (AI.getPaddingType())
1054 IRArgs.PaddingArgIndex = IRArgNo++;
1055
1056 switch (AI.getKind()) {
1057 case ABIArgInfo::Extend:
1058 case ABIArgInfo::Direct: {
1059 // FIXME: handle sseregparm someday...
1060 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1061 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1062 IRArgs.NumberOfArgs = STy->getNumElements();
1063 } else {
1064 IRArgs.NumberOfArgs = 1;
1065 }
1066 break;
1067 }
1068 case ABIArgInfo::Indirect:
1069 IRArgs.NumberOfArgs = 1;
1070 break;
1071 case ABIArgInfo::Ignore:
1072 case ABIArgInfo::InAlloca:
1073 // ignore and inalloca doesn't have matching LLVM parameters.
1074 IRArgs.NumberOfArgs = 0;
1075 break;
1076 case ABIArgInfo::Expand: {
1077 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1078 break;
1079 }
1080 }
1081
1082 if (IRArgs.NumberOfArgs > 0) {
1083 IRArgs.FirstArgIndex = IRArgNo;
1084 IRArgNo += IRArgs.NumberOfArgs;
1085 }
1086
1087 // Skip over the sret parameter when it comes second. We already handled it
1088 // above.
1089 if (IRArgNo == 1 && SwapThisWithSRet)
1090 IRArgNo++;
1091 }
1092 assert(ArgNo == ArgInfo.size());
1093
1094 if (FI.usesInAlloca())
1095 InallocaArgNo = IRArgNo++;
1096
1097 TotalIRArgs = IRArgNo;
1098}
1099} // namespace
1100
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001101/***/
1102
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001103bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001104 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001105}
1106
Tim Northovere77cc392014-03-29 13:28:05 +00001107bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1108 return ReturnTypeUsesSRet(FI) &&
1109 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1110}
1111
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001112bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1113 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1114 switch (BT->getKind()) {
1115 default:
1116 return false;
1117 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001118 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001119 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001120 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001121 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001122 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001123 }
1124 }
1125
1126 return false;
1127}
1128
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001129bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1130 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1131 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1132 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001133 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001134 }
1135 }
1136
1137 return false;
1138}
1139
Chris Lattnera5f58b02011-07-09 17:41:47 +00001140llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001141 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1142 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001143}
1144
Chris Lattnera5f58b02011-07-09 17:41:47 +00001145llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001146CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001147
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001148 bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted;
1149 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001150
Alexey Samsonov153004f2014-09-29 22:08:00 +00001151 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001152 const ABIArgInfo &retAI = FI.getReturnInfo();
1153 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001154 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001155 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001156
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001157 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001158 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001159 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001160 break;
1161
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001162 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001163 if (retAI.getInAllocaSRet()) {
1164 // sret things on win32 aren't void, they return the sret pointer.
1165 QualType ret = FI.getReturnType();
1166 llvm::Type *ty = ConvertType(ret);
1167 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1168 resultType = llvm::PointerType::get(ty, addressSpace);
1169 } else {
1170 resultType = llvm::Type::getVoidTy(getLLVMContext());
1171 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001172 break;
1173
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001174 case ABIArgInfo::Indirect: {
John McCall85dd2c52011-05-15 02:19:42 +00001175 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
1176 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001177 break;
1178 }
1179
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001180 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001181 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001182 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001183 }
Mike Stump11289f42009-09-09 15:08:12 +00001184
Alexey Samsonov153004f2014-09-29 22:08:00 +00001185 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1186 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1187
1188 // Add type for sret argument.
1189 if (IRFunctionArgs.hasSRetArg()) {
1190 QualType Ret = FI.getReturnType();
1191 llvm::Type *Ty = ConvertType(Ret);
1192 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1193 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1194 llvm::PointerType::get(Ty, AddressSpace);
1195 }
1196
1197 // Add type for inalloca argument.
1198 if (IRFunctionArgs.hasInallocaArg()) {
1199 auto ArgStruct = FI.getArgStruct();
1200 assert(ArgStruct);
1201 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1202 }
1203
John McCallc818bbb2012-12-07 07:03:17 +00001204 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001205 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001206 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1207 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001208 for (; it != ie; ++it, ++ArgNo) {
1209 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001210
Rafael Espindolafad28de2012-10-24 01:59:00 +00001211 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001212 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1213 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1214 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001215
Alexey Samsonov153004f2014-09-29 22:08:00 +00001216 unsigned FirstIRArg, NumIRArgs;
1217 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1218
1219 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001220 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001221 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001222 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001223 break;
1224
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001225 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001226 assert(NumIRArgs == 1);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001227 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001228 llvm::Type *LTy = ConvertTypeForMem(it->type);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001229 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001230 break;
1231 }
1232
1233 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001234 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001235 // Fast-isel and the optimizer generally like scalar values better than
1236 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001237 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001238 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001239 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1240 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001241 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001242 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001243 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001244 assert(NumIRArgs == 1);
1245 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001246 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001247 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001248 }
Mike Stump11289f42009-09-09 15:08:12 +00001249
Daniel Dunbard3674e62008-09-11 01:48:57 +00001250 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001251 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1252 getExpandedTypes(it->type, ArgTypesIter);
1253 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001254 break;
1255 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001256 }
1257
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001258 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1259 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001260
1261 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001262}
1263
Chris Lattner2192fe52011-07-18 04:24:23 +00001264llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001265 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001266 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001267
Chris Lattner8806e322011-07-10 00:18:59 +00001268 if (!isFuncTypeConvertible(FPT))
1269 return llvm::StructType::get(getLLVMContext());
1270
1271 const CGFunctionInfo *Info;
1272 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001273 Info =
1274 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001275 else
John McCalla729c622012-02-17 03:33:10 +00001276 Info = &arrangeCXXMethodDeclaration(MD);
1277 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001278}
1279
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001280void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbard931a872009-02-02 22:03:45 +00001281 const Decl *TargetDecl,
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001282 AttributeListType &PAL,
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00001283 unsigned &CallingConv,
1284 bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001285 llvm::AttrBuilder FuncAttrs;
1286 llvm::AttrBuilder RetAttrs;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001287
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001288 CallingConv = FI.getEffectiveCallingConvention();
1289
John McCallab26cfa2010-02-05 21:31:56 +00001290 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001291 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001292
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001293 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001294 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001295 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001296 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001297 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001298 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001299 if (TargetDecl->hasAttr<NoReturnAttr>())
1300 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001301 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1302 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001303
1304 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCallbe349de2010-07-08 06:48:12 +00001305 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl31ad7542011-03-13 17:09:40 +00001306 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling207f0532012-12-20 19:27:06 +00001307 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith49af6292013-03-05 08:30:04 +00001308 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1309 // These attributes are not inherited by overloads.
1310 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1311 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001312 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001313 }
1314
Eric Christopherbf005ec2011-08-15 22:38:22 +00001315 // 'const' and 'pure' attribute functions are also nounwind.
1316 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001317 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1318 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001319 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001320 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1321 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001322 }
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001323 if (TargetDecl->hasAttr<MallocAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001324 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001325 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1326 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001327 }
1328
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001329 if (CodeGenOpts.OptimizeSize)
Bill Wendling207f0532012-12-20 19:27:06 +00001330 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
Quentin Colombet5ee5ca12012-10-26 00:29:48 +00001331 if (CodeGenOpts.OptimizeSize == 2)
Bill Wendling207f0532012-12-20 19:27:06 +00001332 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001333 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001334 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001335 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001336 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001337 if (CodeGenOpts.EnableSegmentedStacks &&
1338 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001339 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001340
Bill Wendling2f81db62013-02-22 20:53:29 +00001341 if (AttrOnCallSite) {
1342 // Attributes that should go on the call site only.
1343 if (!CodeGenOpts.SimplifyLibCalls)
1344 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendling706469b2013-02-28 22:49:57 +00001345 } else {
1346 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001347 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001348 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001349 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001350 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001351 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001352 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001353 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001354 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001355 }
1356
Bill Wendlingdabafea2013-03-13 22:24:33 +00001357 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001358 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001359 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001360 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001361 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001362 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001363 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001364 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001365 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001366 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001367 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001368 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001369
Bill Wendlingd8f49502013-08-01 21:41:02 +00001370 if (!CodeGenOpts.StackRealignment)
1371 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendling985d1c52013-02-15 21:30:01 +00001372 }
1373
Alexey Samsonov153004f2014-09-29 22:08:00 +00001374 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001375
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001376 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001377 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001378 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001379 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001380 if (RetTy->hasSignedIntegerRepresentation())
1381 RetAttrs.addAttribute(llvm::Attribute::SExt);
1382 else if (RetTy->hasUnsignedIntegerRepresentation())
1383 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001384 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001385 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001386 if (RetAI.getInReg())
1387 RetAttrs.addAttribute(llvm::Attribute::InReg);
1388 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001389 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001390 break;
1391
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001392 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001393 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001394 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001395 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1396 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001397 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001398 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001399
Daniel Dunbard3674e62008-09-11 01:48:57 +00001400 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001401 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001402 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001403
Hal Finkela2347ba2014-07-18 15:52:10 +00001404 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1405 QualType PTy = RefTy->getPointeeType();
1406 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1407 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1408 .getQuantity());
1409 else if (getContext().getTargetAddressSpace(PTy) == 0)
1410 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1411 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001412
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001413 // Attach return attributes.
1414 if (RetAttrs.hasAttributes()) {
1415 PAL.push_back(llvm::AttributeSet::get(
1416 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1417 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001418
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001419 // Attach attributes to sret.
1420 if (IRFunctionArgs.hasSRetArg()) {
1421 llvm::AttrBuilder SRETAttrs;
1422 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1423 if (RetAI.getInReg())
1424 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1425 PAL.push_back(llvm::AttributeSet::get(
1426 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1427 }
1428
1429 // Attach attributes to inalloca argument.
1430 if (IRFunctionArgs.hasInallocaArg()) {
1431 llvm::AttrBuilder Attrs;
1432 Attrs.addAttribute(llvm::Attribute::InAlloca);
1433 PAL.push_back(llvm::AttributeSet::get(
1434 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1435 }
1436
1437
1438 unsigned ArgNo = 0;
1439 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1440 E = FI.arg_end();
1441 I != E; ++I, ++ArgNo) {
1442 QualType ParamType = I->type;
1443 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001444 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001445
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001446 // Add attribute for padding argument, if necessary.
1447 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001448 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001449 PAL.push_back(llvm::AttributeSet::get(
1450 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1451 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001452 }
1453
John McCall39ec71f2010-03-27 00:47:27 +00001454 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1455 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001456 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001457 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001458 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001459 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001460 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001461 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001462 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001463 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001464 case ABIArgInfo::Direct:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001465 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001466 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001467 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001468
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001469 case ABIArgInfo::Indirect:
Rafael Espindola703c47f2012-10-19 05:04:37 +00001470 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001471 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001472
Anders Carlsson20759ad2009-09-16 15:53:40 +00001473 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001474 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001475
Bill Wendlinga7912f82012-10-10 07:36:56 +00001476 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1477
Daniel Dunbarc2304432009-03-18 19:51:01 +00001478 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001479 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1480 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001481 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001482
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001483 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001484 case ABIArgInfo::Expand:
Mike Stump11289f42009-09-09 15:08:12 +00001485 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001486
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001487 case ABIArgInfo::InAlloca:
1488 // inalloca disables readnone and readonly.
1489 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1490 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001491 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001492 }
Mike Stump11289f42009-09-09 15:08:12 +00001493
Hal Finkela2347ba2014-07-18 15:52:10 +00001494 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1495 QualType PTy = RefTy->getPointeeType();
1496 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1497 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1498 .getQuantity());
1499 else if (getContext().getTargetAddressSpace(PTy) == 0)
1500 Attrs.addAttribute(llvm::Attribute::NonNull);
1501 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001502
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001503 if (Attrs.hasAttributes()) {
1504 unsigned FirstIRArg, NumIRArgs;
1505 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1506 for (unsigned i = 0; i < NumIRArgs; i++)
1507 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1508 FirstIRArg + i + 1, Attrs));
1509 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001510 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001511 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001512
Bill Wendlinga7912f82012-10-10 07:36:56 +00001513 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001514 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001515 AttributeSet::get(getLLVMContext(),
1516 llvm::AttributeSet::FunctionIndex,
1517 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001518}
1519
John McCalla738c252011-03-09 04:27:21 +00001520/// An argument came in as a promoted argument; demote it back to its
1521/// declared type.
1522static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1523 const VarDecl *var,
1524 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001525 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001526
1527 // This can happen with promotions that actually don't change the
1528 // underlying type, like the enum promotions.
1529 if (value->getType() == varType) return value;
1530
1531 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1532 && "unexpected promotion type");
1533
1534 if (isa<llvm::IntegerType>(varType))
1535 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1536
1537 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1538}
1539
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001540/// Returns the attribute (either parameter attribute, or function
1541/// attribute), which declares argument ArgNo to be non-null.
1542static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
1543 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001544 // FIXME: __attribute__((nonnull)) can also be applied to:
1545 // - references to pointers, where the pointee is known to be
1546 // nonnull (apparently a Clang extension)
1547 // - transparent unions containing pointers
1548 // In the former case, LLVM IR cannot represent the constraint. In
1549 // the latter case, we have no guarantee that the transparent union
1550 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001551 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
1552 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001553 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001554 if (PVD) {
1555 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
1556 return ParmNNAttr;
1557 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001558 // Check function attributes.
1559 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001560 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001561 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001562 if (NNAttr->isNonNull(ArgNo))
1563 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001564 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001565 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001566}
1567
Daniel Dunbard931a872009-02-02 22:03:45 +00001568void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1569 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001570 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00001571 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
1572 // Naked functions don't have prologues.
1573 return;
1574
John McCallcaa19452009-07-28 01:00:58 +00001575 // If this is an implicit-return-zero function, go ahead and
1576 // initialize the return value. TODO: it might be nice to have
1577 // a more general mechanism for this that didn't require synthesized
1578 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001579 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001580 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00001581 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001582 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001583 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001584 Builder.CreateStore(Zero, ReturnValue);
1585 }
1586 }
1587
Mike Stump18bb9282009-05-16 07:57:57 +00001588 // FIXME: We no longer need the types from FunctionArgList; lift up and
1589 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001590
Alexey Samsonov153004f2014-09-29 22:08:00 +00001591 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001592 // Flattened function arguments.
1593 SmallVector<llvm::Argument *, 16> FnArgs;
1594 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
1595 for (auto &Arg : Fn->args()) {
1596 FnArgs.push_back(&Arg);
1597 }
1598 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00001599
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001600 // If we're using inalloca, all the memory arguments are GEPs off of the last
1601 // parameter, which is a pointer to the complete memory area.
Craig Topper8a13c412014-05-21 05:09:00 +00001602 llvm::Value *ArgStruct = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001603 if (IRFunctionArgs.hasInallocaArg()) {
1604 ArgStruct = FnArgs[IRFunctionArgs.getInallocaArgNo()];
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001605 assert(ArgStruct->getType() == FI.getArgStruct()->getPointerTo());
1606 }
1607
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001608 // Name the struct return parameter.
1609 if (IRFunctionArgs.hasSRetArg()) {
1610 auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()];
Daniel Dunbar613855c2008-09-09 23:27:19 +00001611 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00001612 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001613 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00001614 }
Mike Stump11289f42009-09-09 15:08:12 +00001615
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001616 // Track if we received the parameter as a pointer (indirect, byval, or
1617 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
1618 // into a local alloca for us.
1619 enum ValOrPointer { HaveValue = 0, HavePointer = 1 };
Reid Kleckner8ae16272014-02-01 00:23:22 +00001620 typedef llvm::PointerIntPair<llvm::Value *, 1> ValueAndIsPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001621 SmallVector<ValueAndIsPtr, 16> ArgVals;
1622 ArgVals.reserve(Args.size());
1623
Reid Kleckner739756c2013-12-04 19:23:12 +00001624 // Create a pointer value for every parameter declaration. This usually
1625 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1626 // any cleanups or do anything that might unwind. We do that separately, so
1627 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001628 assert(FI.arg_size() == Args.size() &&
1629 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001630 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001631 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001632 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00001633 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001634 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001635 QualType Ty = info_it->type;
1636 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001637
John McCalla738c252011-03-09 04:27:21 +00001638 bool isPromoted =
1639 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1640
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001641 unsigned FirstIRArg, NumIRArgs;
1642 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00001643
Daniel Dunbard3674e62008-09-11 01:48:57 +00001644 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001645 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001646 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001647 llvm::Value *V = Builder.CreateStructGEP(
1648 ArgStruct, ArgI.getInAllocaFieldIndex(), Arg->getName());
1649 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001650 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001651 }
1652
Daniel Dunbar747865a2009-02-05 09:16:39 +00001653 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001654 assert(NumIRArgs == 1);
1655 llvm::Value *V = FnArgs[FirstIRArg];
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001656
John McCall47fb9502013-03-07 21:37:08 +00001657 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001658 // Aggregates and complex variables are accessed by reference. All we
1659 // need to do is realign the value, if requested
1660 if (ArgI.getIndirectRealign()) {
1661 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1662
1663 // Copy from the incoming argument pointer to the temporary with the
1664 // appropriate alignment.
1665 //
1666 // FIXME: We should have a common utility for generating an aggregate
1667 // copy.
Chris Lattner2192fe52011-07-18 04:24:23 +00001668 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyck705ba072011-01-19 01:58:38 +00001669 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumidd634362011-03-10 14:02:21 +00001670 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1671 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1672 Builder.CreateMemCpy(Dst,
1673 Src,
Ken Dyck705ba072011-01-19 01:58:38 +00001674 llvm::ConstantInt::get(IntPtrTy,
1675 Size.getQuantity()),
Benjamin Krameracc6b4e2010-12-30 00:13:21 +00001676 ArgI.getIndirectAlign(),
1677 false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001678 V = AlignedTemp;
1679 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001680 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001681 } else {
1682 // Load scalar value from indirect argument.
Ken Dyck705ba072011-01-19 01:58:38 +00001683 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001684 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1685 Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001686
1687 if (isPromoted)
1688 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001689 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001690 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001691 break;
1692 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001693
1694 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001695 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001696
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001697 // If we have the trivial case, handle it with no muss and fuss.
1698 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001699 ArgI.getCoerceToType() == ConvertType(Ty) &&
1700 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001701 assert(NumIRArgs == 1);
1702 auto AI = FnArgs[FirstIRArg];
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001703 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001704
Hal Finkel48d53e22014-07-19 01:41:07 +00001705 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001706 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
1707 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00001708 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1709 AI->getArgNo() + 1,
1710 llvm::Attribute::NonNull));
1711
Hal Finkel48d53e22014-07-19 01:41:07 +00001712 QualType OTy = PVD->getOriginalType();
1713 if (const auto *ArrTy =
1714 getContext().getAsConstantArrayType(OTy)) {
1715 // A C99 array parameter declaration with the static keyword also
1716 // indicates dereferenceability, and if the size is constant we can
1717 // use the dereferenceable attribute (which requires the size in
1718 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00001719 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00001720 QualType ETy = ArrTy->getElementType();
1721 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
1722 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
1723 ArrSize) {
1724 llvm::AttrBuilder Attrs;
1725 Attrs.addDereferenceableAttr(
1726 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
1727 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1728 AI->getArgNo() + 1, Attrs));
1729 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
1730 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1731 AI->getArgNo() + 1,
1732 llvm::Attribute::NonNull));
1733 }
1734 }
1735 } else if (const auto *ArrTy =
1736 getContext().getAsVariableArrayType(OTy)) {
1737 // For C99 VLAs with the static keyword, we don't know the size so
1738 // we can't use the dereferenceable attribute, but in addrspace(0)
1739 // we know that it must be nonnull.
1740 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
1741 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
1742 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1743 AI->getArgNo() + 1,
1744 llvm::Attribute::NonNull));
1745 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00001746
1747 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
1748 if (!AVAttr)
1749 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
1750 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
1751 if (AVAttr) {
1752 llvm::Value *AlignmentValue =
1753 EmitScalarExpr(AVAttr->getAlignment());
1754 llvm::ConstantInt *AlignmentCI =
1755 cast<llvm::ConstantInt>(AlignmentValue);
1756 unsigned Alignment =
1757 std::min((unsigned) AlignmentCI->getZExtValue(),
1758 +llvm::Value::MaximumAlignment);
1759
1760 llvm::AttrBuilder Attrs;
1761 Attrs.addAlignmentAttr(Alignment);
1762 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1763 AI->getArgNo() + 1, Attrs));
1764 }
Hal Finkel48d53e22014-07-19 01:41:07 +00001765 }
1766
Bill Wendling507c3512012-10-16 05:23:44 +00001767 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001768 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1769 AI->getArgNo() + 1,
1770 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00001771
Chris Lattner7369c142011-07-20 06:29:00 +00001772 // Ensure the argument is the correct type.
1773 if (V->getType() != ArgI.getCoerceToType())
1774 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1775
John McCalla738c252011-03-09 04:27:21 +00001776 if (isPromoted)
1777 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00001778
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001779 if (const CXXMethodDecl *MD =
1780 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001781 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001782 V = CGM.getCXXABI().
1783 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001784 }
1785
Rafael Espindola8778c282012-11-29 16:09:03 +00001786 // Because of merging of function types from multiple decls it is
1787 // possible for the type of an argument to not match the corresponding
1788 // type in the function type. Since we are codegening the callee
1789 // in here, add a cast to the argument type.
1790 llvm::Type *LTy = ConvertType(Arg->getType());
1791 if (V->getType() != LTy)
1792 V = Builder.CreateBitCast(V, LTy);
1793
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001794 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001795 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00001796 }
Mike Stump11289f42009-09-09 15:08:12 +00001797
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001798 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001799
Chris Lattnerff941a62010-07-28 18:24:28 +00001800 // The alignment we need to use is the max of the requested alignment for
1801 // the argument plus the alignment required by our access code below.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001802 unsigned AlignmentToUse =
Micah Villmowdd31ca12012-10-08 16:25:52 +00001803 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerff941a62010-07-28 18:24:28 +00001804 AlignmentToUse = std::max(AlignmentToUse,
1805 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001806
Chris Lattnerff941a62010-07-28 18:24:28 +00001807 Alloca->setAlignment(AlignmentToUse);
Chris Lattnerc401de92010-07-05 20:21:00 +00001808 llvm::Value *V = Alloca;
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001809 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001810
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001811 // If the value is offset in memory, apply the offset now.
1812 if (unsigned Offs = ArgI.getDirectOffset()) {
1813 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1814 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001815 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001816 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1817 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001818
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001819 // Fast-isel and the optimizer generally like scalar values better than
1820 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001821 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001822 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
1823 STy->getNumElements() > 1) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001824 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001825 llvm::Type *DstTy =
1826 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00001827 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001828
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001829 if (SrcSize <= DstSize) {
1830 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1831
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001832 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001833 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001834 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001835 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1836 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001837 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001838 }
1839 } else {
1840 llvm::AllocaInst *TempAlloca =
1841 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1842 TempAlloca->setAlignment(AlignmentToUse);
1843 llvm::Value *TempV = TempAlloca;
1844
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001845 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001846 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001847 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001848 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1849 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001850 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001851 }
1852
1853 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner15ec3612010-06-29 00:06:42 +00001854 }
1855 } else {
1856 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001857 assert(NumIRArgs == 1);
1858 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00001859 AI->setName(Arg->getName() + ".coerce");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001860 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00001861 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001862
1863
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001864 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00001865 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001866 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001867 if (isPromoted)
1868 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001869 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1870 } else {
1871 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00001872 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001873 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001874 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001875
1876 case ABIArgInfo::Expand: {
1877 // If this structure was expanded into multiple arguments then
1878 // we need to create a temporary and reconstruct it from the
1879 // arguments.
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001880 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedmana0544d62011-12-03 04:14:32 +00001881 CharUnits Align = getContext().getDeclAlign(Arg);
1882 Alloca->setAlignment(Align.getQuantity());
1883 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001884 ArgVals.push_back(ValueAndIsPtr(Alloca, HavePointer));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001885
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001886 auto FnArgIter = FnArgs.begin() + FirstIRArg;
1887 ExpandTypeFromArgs(Ty, LV, FnArgIter);
1888 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
1889 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
1890 auto AI = FnArgs[FirstIRArg + i];
1891 AI->setName(Arg->getName() + "." + Twine(i));
1892 }
1893 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001894 }
1895
1896 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001897 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001898 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001899 if (!hasScalarEvaluationKind(Ty)) {
1900 ArgVals.push_back(ValueAndIsPtr(CreateMemTemp(Ty), HavePointer));
1901 } else {
1902 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
1903 ArgVals.push_back(ValueAndIsPtr(U, HaveValue));
1904 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001905 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001906 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001907 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001908
Reid Kleckner739756c2013-12-04 19:23:12 +00001909 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1910 for (int I = Args.size() - 1; I >= 0; --I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001911 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1912 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001913 } else {
1914 for (unsigned I = 0, E = Args.size(); I != E; ++I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001915 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1916 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001917 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001918}
1919
John McCallffa2c1a2012-01-29 07:46:59 +00001920static void eraseUnusedBitCasts(llvm::Instruction *insn) {
1921 while (insn->use_empty()) {
1922 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
1923 if (!bitcast) return;
1924
1925 // This is "safe" because we would have used a ConstantExpr otherwise.
1926 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
1927 bitcast->eraseFromParent();
1928 }
1929}
1930
John McCall31168b02011-06-15 23:02:42 +00001931/// Try to emit a fused autorelease of a return result.
1932static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1933 llvm::Value *result) {
1934 // We must be immediately followed the cast.
1935 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00001936 if (BB->empty()) return nullptr;
1937 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001938
Chris Lattner2192fe52011-07-18 04:24:23 +00001939 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00001940
1941 // result is in a BasicBlock and is therefore an Instruction.
1942 llvm::Instruction *generator = cast<llvm::Instruction>(result);
1943
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001944 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00001945
1946 // Look for:
1947 // %generator = bitcast %type1* %generator2 to %type2*
1948 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1949 // We would have emitted this as a constant if the operand weren't
1950 // an Instruction.
1951 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1952
1953 // Require the generator to be immediately followed by the cast.
1954 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00001955 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001956
1957 insnsToKill.push_back(bitcast);
1958 }
1959
1960 // Look for:
1961 // %generator = call i8* @objc_retain(i8* %originalResult)
1962 // or
1963 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
1964 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00001965 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001966
1967 bool doRetainAutorelease;
1968
1969 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
1970 doRetainAutorelease = true;
1971 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
1972 .objc_retainAutoreleasedReturnValue) {
1973 doRetainAutorelease = false;
1974
John McCallcfa4e9b2012-09-07 23:30:50 +00001975 // If we emitted an assembly marker for this call (and the
1976 // ARCEntrypoints field should have been set if so), go looking
1977 // for that call. If we can't find it, we can't do this
1978 // optimization. But it should always be the immediately previous
1979 // instruction, unless we needed bitcasts around the call.
1980 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
1981 llvm::Instruction *prev = call->getPrevNode();
1982 assert(prev);
1983 if (isa<llvm::BitCastInst>(prev)) {
1984 prev = prev->getPrevNode();
1985 assert(prev);
1986 }
1987 assert(isa<llvm::CallInst>(prev));
1988 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
1989 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
1990 insnsToKill.push_back(prev);
1991 }
John McCall31168b02011-06-15 23:02:42 +00001992 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00001993 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001994 }
1995
1996 result = call->getArgOperand(0);
1997 insnsToKill.push_back(call);
1998
1999 // Keep killing bitcasts, for sanity. Note that we no longer care
2000 // about precise ordering as long as there's exactly one use.
2001 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2002 if (!bitcast->hasOneUse()) break;
2003 insnsToKill.push_back(bitcast);
2004 result = bitcast->getOperand(0);
2005 }
2006
2007 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002008 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00002009 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
2010 (*i)->eraseFromParent();
2011
2012 // Do the fused retain/autorelease if we were asked to.
2013 if (doRetainAutorelease)
2014 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2015
2016 // Cast back to the result type.
2017 return CGF.Builder.CreateBitCast(result, resultType);
2018}
2019
John McCallffa2c1a2012-01-29 07:46:59 +00002020/// If this is a +1 of the value of an immutable 'self', remove it.
2021static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2022 llvm::Value *result) {
2023 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002024 const ObjCMethodDecl *method =
2025 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002026 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002027 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002028 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002029
2030 // Look for a retain call.
2031 llvm::CallInst *retainCall =
2032 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2033 if (!retainCall ||
2034 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002035 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002036
2037 // Look for an ordinary load of 'self'.
2038 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2039 llvm::LoadInst *load =
2040 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2041 if (!load || load->isAtomic() || load->isVolatile() ||
2042 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
Craig Topper8a13c412014-05-21 05:09:00 +00002043 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002044
2045 // Okay! Burn it all down. This relies for correctness on the
2046 // assumption that the retain is emitted as part of the return and
2047 // that thereafter everything is used "linearly".
2048 llvm::Type *resultType = result->getType();
2049 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2050 assert(retainCall->use_empty());
2051 retainCall->eraseFromParent();
2052 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2053
2054 return CGF.Builder.CreateBitCast(load, resultType);
2055}
2056
John McCall31168b02011-06-15 23:02:42 +00002057/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002058///
2059/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002060static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2061 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002062 // If we're returning 'self', kill the initial retain. This is a
2063 // heuristic attempt to "encourage correctness" in the really unfortunate
2064 // case where we have a return of self during a dealloc and we desperately
2065 // need to avoid the possible autorelease.
2066 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2067 return self;
2068
John McCall31168b02011-06-15 23:02:42 +00002069 // At -O0, try to emit a fused retain/autorelease.
2070 if (CGF.shouldUseFusedARCCalls())
2071 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2072 return fused;
2073
2074 return CGF.EmitARCAutoreleaseReturnValue(result);
2075}
2076
John McCall6e1c0122012-01-29 02:35:02 +00002077/// Heuristically search for a dominating store to the return-value slot.
2078static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
2079 // If there are multiple uses of the return-value slot, just check
2080 // for something immediately preceding the IP. Sometimes this can
2081 // happen with how we generate implicit-returns; it can also happen
2082 // with noreturn cleanups.
2083 if (!CGF.ReturnValue->hasOneUse()) {
2084 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002085 if (IP->empty()) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002086 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
Craig Topper8a13c412014-05-21 05:09:00 +00002087 if (!store) return nullptr;
2088 if (store->getPointerOperand() != CGF.ReturnValue) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002089 assert(!store->isAtomic() && !store->isVolatile()); // see below
2090 return store;
2091 }
2092
2093 llvm::StoreInst *store =
Chandler Carruth4d01fff2014-03-09 03:16:50 +00002094 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002095 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002096
2097 // These aren't actually possible for non-coerced returns, and we
2098 // only care about non-coerced returns on this code path.
2099 assert(!store->isAtomic() && !store->isVolatile());
2100
2101 // Now do a first-and-dirty dominance check: just walk up the
2102 // single-predecessors chain from the current insertion point.
2103 llvm::BasicBlock *StoreBB = store->getParent();
2104 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2105 while (IP != StoreBB) {
2106 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002107 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002108 }
2109
2110 // Okay, the store's basic block dominates the insertion point; we
2111 // can do our thing.
2112 return store;
2113}
2114
Adrian Prantl3be10542013-05-02 17:30:20 +00002115void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002116 bool EmitRetDbgLoc,
2117 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002118 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2119 // Naked functions don't have epilogues.
2120 Builder.CreateUnreachable();
2121 return;
2122 }
2123
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002124 // Functions with no result always return void.
Craig Topper8a13c412014-05-21 05:09:00 +00002125 if (!ReturnValue) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002126 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002127 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002128 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002129
Dan Gohman481e40c2010-07-20 20:13:52 +00002130 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002131 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002132 QualType RetTy = FI.getReturnType();
2133 const ABIArgInfo &RetAI = FI.getReturnInfo();
2134
2135 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002136 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002137 // Aggregrates get evaluated directly into the destination. Sometimes we
2138 // need to return the sret value in a register, though.
2139 assert(hasAggregateEvaluationKind(RetTy));
2140 if (RetAI.getInAllocaSRet()) {
2141 llvm::Function::arg_iterator EI = CurFn->arg_end();
2142 --EI;
2143 llvm::Value *ArgStruct = EI;
2144 llvm::Value *SRet =
2145 Builder.CreateStructGEP(ArgStruct, RetAI.getInAllocaFieldIndex());
2146 RV = Builder.CreateLoad(SRet, "sret");
2147 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002148 break;
2149
Daniel Dunbar03816342010-08-21 02:24:36 +00002150 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002151 auto AI = CurFn->arg_begin();
2152 if (RetAI.isSRetAfterThis())
2153 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002154 switch (getEvaluationKind(RetTy)) {
2155 case TEK_Complex: {
2156 ComplexPairTy RT =
Nick Lewycky2d84e842013-10-02 02:29:49 +00002157 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
2158 EndLoc);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002159 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002160 /*isInit*/ true);
2161 break;
2162 }
2163 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002164 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002165 break;
2166 case TEK_Scalar:
2167 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Reid Kleckner37abaca2014-05-09 22:46:15 +00002168 MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002169 /*isInit*/ true);
2170 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002171 }
2172 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002173 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002174
2175 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002176 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002177 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2178 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002179 // The internal return value temp always will have pointer-to-return-type
2180 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002181
John McCall6e1c0122012-01-29 02:35:02 +00002182 // If there is a dominating store to ReturnValue, we can elide
2183 // the load, zap the store, and usually zap the alloca.
2184 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002185 // Reuse the debug location from the store unless there is
2186 // cleanup code to be emitted between the store and return
2187 // instruction.
2188 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002189 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002190 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002191 RV = SI->getValueOperand();
2192 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002193
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002194 // If that was the only use of the return value, nuke it as well now.
2195 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
2196 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002197 ReturnValue = nullptr;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002198 }
John McCall6e1c0122012-01-29 02:35:02 +00002199
2200 // Otherwise, we have to do a simple load.
2201 } else {
2202 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002203 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002204 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002205 llvm::Value *V = ReturnValue;
2206 // If the value is offset in memory, apply the offset now.
2207 if (unsigned Offs = RetAI.getDirectOffset()) {
2208 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
2209 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002210 V = Builder.CreateBitCast(V,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002211 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2212 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002213
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002214 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002215 }
John McCall31168b02011-06-15 23:02:42 +00002216
2217 // In ARC, end functions that return a retainable type with a call
2218 // to objc_autoreleaseReturnValue.
2219 if (AutoreleaseResult) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002220 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002221 !FI.isReturnsRetained() &&
2222 RetTy->isObjCRetainableType());
2223 RV = emitAutoreleaseOfResult(*this, RV);
2224 }
2225
Chris Lattner726b3d02010-06-26 23:13:19 +00002226 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002227
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002228 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002229 break;
2230
2231 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002232 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002233 }
2234
Alexey Samsonovde443c52014-08-13 00:26:40 +00002235 llvm::Instruction *Ret;
2236 if (RV) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002237 if (SanOpts->ReturnsNonnullAttribute) {
2238 if (auto RetNNAttr = CurGD.getDecl()->getAttr<ReturnsNonNullAttr>()) {
2239 SanitizerScope SanScope(this);
2240 llvm::Value *Cond = Builder.CreateICmpNE(
2241 RV, llvm::Constant::getNullValue(RV->getType()));
2242 llvm::Constant *StaticData[] = {
2243 EmitCheckSourceLocation(EndLoc),
2244 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2245 };
2246 EmitCheck(Cond, "nonnull_return", StaticData, None, CRK_Recoverable);
2247 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002248 }
2249 Ret = Builder.CreateRet(RV);
2250 } else {
2251 Ret = Builder.CreateRetVoid();
2252 }
2253
Devang Patel65497582010-07-21 18:08:50 +00002254 if (!RetDbgLoc.isUnknown())
2255 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar613855c2008-09-09 23:27:19 +00002256}
2257
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002258static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2259 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2260 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2261}
2262
2263static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty) {
2264 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2265 // placeholders.
2266 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2267 llvm::Value *Placeholder =
2268 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2269 Placeholder = CGF.Builder.CreateLoad(Placeholder);
2270 return AggValueSlot::forAddr(Placeholder, CharUnits::Zero(),
2271 Ty.getQualifiers(),
2272 AggValueSlot::IsNotDestructed,
2273 AggValueSlot::DoesNotNeedGCBarriers,
2274 AggValueSlot::IsNotAliased);
2275}
2276
John McCall32ea9692011-03-11 20:59:21 +00002277void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002278 const VarDecl *param,
2279 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002280 // StartFunction converted the ABI-lowered parameter(s) into a
2281 // local alloca. We need to turn that into an r-value suitable
2282 // for EmitCall.
John McCall32ea9692011-03-11 20:59:21 +00002283 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002284
John McCall32ea9692011-03-11 20:59:21 +00002285 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002286
John McCall23f66262010-05-26 22:34:26 +00002287 // For the most part, we just need to load the alloca, except:
2288 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00002289 // 2) references to non-scalars are pointers directly to the aggregate.
2290 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00002291 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00002292 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00002293 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00002294
2295 // Locals which are references to scalars are represented
2296 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00002297 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00002298 }
2299
Reid Klecknerab2090d2014-07-26 01:34:32 +00002300 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2301 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002302
Nick Lewycky2d84e842013-10-02 02:29:49 +00002303 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002304}
2305
John McCall31168b02011-06-15 23:02:42 +00002306static bool isProvablyNull(llvm::Value *addr) {
2307 return isa<llvm::ConstantPointerNull>(addr);
2308}
2309
2310static bool isProvablyNonNull(llvm::Value *addr) {
2311 return isa<llvm::AllocaInst>(addr);
2312}
2313
2314/// Emit the actual writing-back of a writeback.
2315static void emitWriteback(CodeGenFunction &CGF,
2316 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002317 const LValue &srcLV = writeback.Source;
2318 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002319 assert(!isProvablyNull(srcAddr) &&
2320 "shouldn't have writeback for provably null argument");
2321
Craig Topper8a13c412014-05-21 05:09:00 +00002322 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002323
2324 // If the argument wasn't provably non-null, we need to null check
2325 // before doing the store.
2326 bool provablyNonNull = isProvablyNonNull(srcAddr);
2327 if (!provablyNonNull) {
2328 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2329 contBB = CGF.createBasicBlock("icr.done");
2330
2331 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2332 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2333 CGF.EmitBlock(writebackBB);
2334 }
2335
2336 // Load the value to writeback.
2337 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2338
2339 // Cast it back, in case we're writing an id to a Foo* or something.
2340 value = CGF.Builder.CreateBitCast(value,
2341 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
2342 "icr.writeback-cast");
2343
2344 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002345
2346 // If we have a "to use" value, it's something we need to emit a use
2347 // of. This has to be carefully threaded in: if it's done after the
2348 // release it's potentially undefined behavior (and the optimizer
2349 // will ignore it), and if it happens before the retain then the
2350 // optimizer could move the release there.
2351 if (writeback.ToUse) {
2352 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2353
2354 // Retain the new value. No need to block-copy here: the block's
2355 // being passed up the stack.
2356 value = CGF.EmitARCRetainNonBlock(value);
2357
2358 // Emit the intrinsic use here.
2359 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2360
2361 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002362 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002363
2364 // Put the new value in place (primitively).
2365 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2366
2367 // Release the old value.
2368 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2369
2370 // Otherwise, we can just do a normal lvalue store.
2371 } else {
2372 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2373 }
John McCall31168b02011-06-15 23:02:42 +00002374
2375 // Jump to the continuation block.
2376 if (!provablyNonNull)
2377 CGF.EmitBlock(contBB);
2378}
2379
2380static void emitWritebacks(CodeGenFunction &CGF,
2381 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002382 for (const auto &I : args.writebacks())
2383 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002384}
2385
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002386static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2387 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002388 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002389 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2390 CallArgs.getCleanupsToDeactivate();
2391 // Iterate in reverse to increase the likelihood of popping the cleanup.
2392 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
2393 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
2394 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
2395 I->IsActiveIP->eraseFromParent();
2396 }
2397}
2398
John McCalleff18842013-03-23 02:35:54 +00002399static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2400 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2401 if (uop->getOpcode() == UO_AddrOf)
2402 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002403 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002404}
2405
John McCall31168b02011-06-15 23:02:42 +00002406/// Emit an argument that's being passed call-by-writeback. That is,
2407/// we are passing the address of
2408static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2409 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002410 LValue srcLV;
2411
2412 // Make an optimistic effort to emit the address as an l-value.
2413 // This can fail if the the argument expression is more complicated.
2414 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2415 srcLV = CGF.EmitLValue(lvExpr);
2416
2417 // Otherwise, just emit it as a scalar.
2418 } else {
2419 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
2420
2421 QualType srcAddrType =
2422 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
2423 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
2424 }
2425 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002426
2427 // The dest and src types don't necessarily match in LLVM terms
2428 // because of the crazy ObjC compatibility rules.
2429
Chris Lattner2192fe52011-07-18 04:24:23 +00002430 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00002431 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2432
2433 // If the address is a constant null, just pass the appropriate null.
2434 if (isProvablyNull(srcAddr)) {
2435 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2436 CRE->getType());
2437 return;
2438 }
2439
John McCall31168b02011-06-15 23:02:42 +00002440 // Create the temporary.
2441 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
2442 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002443 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2444 // and that cleanup will be conditional if we can't prove that the l-value
2445 // isn't null, so we need to register a dominating point so that the cleanups
2446 // system will make valid IR.
2447 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2448
John McCall31168b02011-06-15 23:02:42 +00002449 // Zero-initialize it if we're not doing a copy-initialization.
2450 bool shouldCopy = CRE->shouldCopy();
2451 if (!shouldCopy) {
2452 llvm::Value *null =
2453 llvm::ConstantPointerNull::get(
2454 cast<llvm::PointerType>(destType->getElementType()));
2455 CGF.Builder.CreateStore(null, temp);
2456 }
Craig Topper8a13c412014-05-21 05:09:00 +00002457
2458 llvm::BasicBlock *contBB = nullptr;
2459 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002460
2461 // If the address is *not* known to be non-null, we need to switch.
2462 llvm::Value *finalArgument;
2463
2464 bool provablyNonNull = isProvablyNonNull(srcAddr);
2465 if (provablyNonNull) {
2466 finalArgument = temp;
2467 } else {
2468 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2469
2470 finalArgument = CGF.Builder.CreateSelect(isNull,
2471 llvm::ConstantPointerNull::get(destType),
2472 temp, "icr.argument");
2473
2474 // If we need to copy, then the load has to be conditional, which
2475 // means we need control flow.
2476 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00002477 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002478 contBB = CGF.createBasicBlock("icr.cont");
2479 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2480 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2481 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002482 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00002483 }
2484 }
2485
Craig Topper8a13c412014-05-21 05:09:00 +00002486 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00002487
John McCall31168b02011-06-15 23:02:42 +00002488 // Perform a copy if necessary.
2489 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002490 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002491 assert(srcRV.isScalar());
2492
2493 llvm::Value *src = srcRV.getScalarVal();
2494 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2495 "icr.cast");
2496
2497 // Use an ordinary store, not a store-to-lvalue.
2498 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00002499
2500 // If optimization is enabled, and the value was held in a
2501 // __strong variable, we need to tell the optimizer that this
2502 // value has to stay alive until we're doing the store back.
2503 // This is because the temporary is effectively unretained,
2504 // and so otherwise we can violate the high-level semantics.
2505 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2506 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2507 valueToUse = src;
2508 }
John McCall31168b02011-06-15 23:02:42 +00002509 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002510
John McCall31168b02011-06-15 23:02:42 +00002511 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002512 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00002513 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002514 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00002515
2516 // Make a phi for the value to intrinsically use.
2517 if (valueToUse) {
2518 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2519 "icr.to-use");
2520 phiToUse->addIncoming(valueToUse, copyBB);
2521 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2522 originBB);
2523 valueToUse = phiToUse;
2524 }
2525
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002526 condEval.end(CGF);
2527 }
John McCall31168b02011-06-15 23:02:42 +00002528
John McCalleff18842013-03-23 02:35:54 +00002529 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002530 args.add(RValue::get(finalArgument), CRE->getType());
2531}
2532
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002533void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2534 assert(!StackBase && !StackCleanup.isValid());
2535
2536 // Save the stack.
2537 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
2538 StackBase = CGF.Builder.CreateCall(F, "inalloca.save");
2539
2540 // Control gets really tied up in landing pads, so we have to spill the
2541 // stacksave to an alloca to avoid violating SSA form.
2542 // TODO: This is dead if we never emit the cleanup. We should create the
2543 // alloca and store lazily on the first cleanup emission.
2544 StackBaseMem = CGF.CreateTempAlloca(CGF.Int8PtrTy, "inalloca.spmem");
2545 CGF.Builder.CreateStore(StackBase, StackBaseMem);
2546 CGF.pushStackRestore(EHCleanup, StackBaseMem);
2547 StackCleanup = CGF.EHStack.getInnermostEHScope();
2548 assert(StackCleanup.isValid());
2549}
2550
2551void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2552 if (StackBase) {
2553 CGF.DeactivateCleanupBlock(StackCleanup, StackBase);
2554 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
2555 // We could load StackBase from StackBaseMem, but in the non-exceptional
2556 // case we can skip it.
2557 CGF.Builder.CreateCall(F, StackBase);
2558 }
2559}
2560
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002561static void emitNonNullArgCheck(CodeGenFunction &CGF, RValue RV,
2562 QualType ArgType, SourceLocation ArgLoc,
2563 const FunctionDecl *FD, unsigned ParmNum) {
2564 if (!CGF.SanOpts->NonnullAttribute || !FD)
2565 return;
2566 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
2567 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
2568 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
2569 if (!NNAttr)
2570 return;
2571 CodeGenFunction::SanitizerScope SanScope(&CGF);
2572 assert(RV.isScalar());
2573 llvm::Value *V = RV.getScalarVal();
2574 llvm::Value *Cond =
2575 CGF.Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
2576 llvm::Constant *StaticData[] = {
2577 CGF.EmitCheckSourceLocation(ArgLoc),
2578 CGF.EmitCheckSourceLocation(NNAttr->getLocation()),
2579 llvm::ConstantInt::get(CGF.Int32Ty, ArgNo + 1),
2580 };
2581 CGF.EmitCheck(Cond, "nonnull_arg", StaticData, None,
2582 CodeGenFunction::CRK_Recoverable);
2583}
2584
Reid Kleckner739756c2013-12-04 19:23:12 +00002585void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2586 ArrayRef<QualType> ArgTypes,
2587 CallExpr::const_arg_iterator ArgBeg,
2588 CallExpr::const_arg_iterator ArgEnd,
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002589 const FunctionDecl *CalleeDecl,
2590 unsigned ParamsToSkip,
Reid Kleckner739756c2013-12-04 19:23:12 +00002591 bool ForceColumnInfo) {
2592 CGDebugInfo *DI = getDebugInfo();
2593 SourceLocation CallLoc;
2594 if (DI) CallLoc = DI->getLocation();
2595
2596 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2597 // because arguments are destroyed left to right in the callee.
2598 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002599 // Insert a stack save if we're going to need any inalloca args.
2600 bool HasInAllocaArgs = false;
2601 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2602 I != E && !HasInAllocaArgs; ++I)
2603 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2604 if (HasInAllocaArgs) {
2605 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2606 Args.allocateArgumentMemory(*this);
2607 }
2608
2609 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00002610 size_t CallArgsStart = Args.size();
2611 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2612 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2613 EmitCallArg(Args, *Arg, ArgTypes[I]);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002614 emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
2615 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00002616 // Restore the debug location.
2617 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2618 }
2619
2620 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2621 // IR function.
2622 std::reverse(Args.begin() + CallArgsStart, Args.end());
2623 return;
2624 }
2625
2626 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2627 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2628 assert(Arg != ArgEnd);
2629 EmitCallArg(Args, *Arg, ArgTypes[I]);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002630 emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
2631 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00002632 // Restore the debug location.
2633 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2634 }
2635}
2636
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002637namespace {
2638
2639struct DestroyUnpassedArg : EHScopeStack::Cleanup {
2640 DestroyUnpassedArg(llvm::Value *Addr, QualType Ty)
2641 : Addr(Addr), Ty(Ty) {}
2642
2643 llvm::Value *Addr;
2644 QualType Ty;
2645
Craig Topper4f12f102014-03-12 06:41:41 +00002646 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002647 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2648 assert(!Dtor->isTrivial());
2649 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2650 /*Delegating=*/false, Addr);
2651 }
2652};
2653
2654}
2655
John McCall32ea9692011-03-11 20:59:21 +00002656void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2657 QualType type) {
John McCall31168b02011-06-15 23:02:42 +00002658 if (const ObjCIndirectCopyRestoreExpr *CRE
2659 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002660 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002661 assert(getContext().hasSameType(E->getType(), type));
2662 return emitWritebackArg(*this, args, CRE);
2663 }
2664
John McCall0a76c0c2011-08-26 18:42:59 +00002665 assert(type->isReferenceType() == E->isGLValue() &&
2666 "reference binding to unmaterialized r-value!");
2667
John McCall17054bd62011-08-26 21:08:13 +00002668 if (E->isGLValue()) {
2669 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002670 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002671 }
Mike Stump11289f42009-09-09 15:08:12 +00002672
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002673 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2674
2675 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2676 // However, we still have to push an EH-only cleanup in case we unwind before
2677 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00002678 if (HasAggregateEvalKind &&
2679 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2680 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00002681 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00002682 AggValueSlot Slot;
2683 if (args.isUsingInAlloca())
2684 Slot = createPlaceholderSlot(*this, type);
2685 else
2686 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00002687
2688 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2689 bool DestroyedInCallee =
2690 RD && RD->hasNonTrivialDestructor() &&
2691 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
2692 if (DestroyedInCallee)
2693 Slot.setExternallyDestructed();
2694
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002695 EmitAggExpr(E, Slot);
2696 RValue RV = Slot.asRValue();
2697 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002698
Reid Klecknere39ee212014-05-03 00:33:28 +00002699 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002700 // Create a no-op GEP between the placeholder and the cleanup so we can
2701 // RAUW it successfully. It also serves as a marker of the first
2702 // instruction where the cleanup is active.
2703 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddr(), type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002704 // This unreachable is a temporary marker which will be removed later.
2705 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2706 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002707 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002708 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002709 }
2710
2711 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00002712 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2713 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2714 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00002715 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2716 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2717 } else {
2718 // We can't represent a misaligned lvalue in the CallArgList, so copy
2719 // to an aligned temporary now.
2720 llvm::Value *tmp = CreateMemTemp(type);
2721 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2722 L.getAlignment());
2723 args.add(RValue::getAggregate(tmp), type);
2724 }
Eli Friedmandf968192011-05-26 00:10:27 +00002725 return;
2726 }
2727
John McCall32ea9692011-03-11 20:59:21 +00002728 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00002729}
2730
Dan Gohman515a60d2012-02-16 00:57:37 +00002731// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2732// optimizer it can aggressively ignore unwind edges.
2733void
2734CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2735 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2736 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2737 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2738 CGM.getNoObjCARCExceptionsMetadata());
2739}
2740
John McCall882987f2013-02-28 19:01:20 +00002741/// Emits a call to the given no-arguments nounwind runtime function.
2742llvm::CallInst *
2743CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2744 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002745 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002746}
2747
2748/// Emits a call to the given nounwind runtime function.
2749llvm::CallInst *
2750CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2751 ArrayRef<llvm::Value*> args,
2752 const llvm::Twine &name) {
2753 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2754 call->setDoesNotThrow();
2755 return call;
2756}
2757
2758/// Emits a simple call (never an invoke) to the given no-arguments
2759/// runtime function.
2760llvm::CallInst *
2761CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2762 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002763 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002764}
2765
2766/// Emits a simple call (never an invoke) to the given runtime
2767/// function.
2768llvm::CallInst *
2769CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2770 ArrayRef<llvm::Value*> args,
2771 const llvm::Twine &name) {
2772 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2773 call->setCallingConv(getRuntimeCC());
2774 return call;
2775}
2776
2777/// Emits a call or invoke to the given noreturn runtime function.
2778void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2779 ArrayRef<llvm::Value*> args) {
2780 if (getInvokeDest()) {
2781 llvm::InvokeInst *invoke =
2782 Builder.CreateInvoke(callee,
2783 getUnreachableBlock(),
2784 getInvokeDest(),
2785 args);
2786 invoke->setDoesNotReturn();
2787 invoke->setCallingConv(getRuntimeCC());
2788 } else {
2789 llvm::CallInst *call = Builder.CreateCall(callee, args);
2790 call->setDoesNotReturn();
2791 call->setCallingConv(getRuntimeCC());
2792 Builder.CreateUnreachable();
2793 }
Justin Bogner06bd6d02014-01-13 21:24:18 +00002794 PGO.setCurrentRegionUnreachable();
John McCall882987f2013-02-28 19:01:20 +00002795}
2796
2797/// Emits a call or invoke instruction to the given nullary runtime
2798/// function.
2799llvm::CallSite
2800CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2801 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002802 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002803}
2804
2805/// Emits a call or invoke instruction to the given runtime function.
2806llvm::CallSite
2807CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2808 ArrayRef<llvm::Value*> args,
2809 const Twine &name) {
2810 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2811 callSite.setCallingConv(getRuntimeCC());
2812 return callSite;
2813}
2814
2815llvm::CallSite
2816CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2817 const Twine &Name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002818 return EmitCallOrInvoke(Callee, None, Name);
John McCall882987f2013-02-28 19:01:20 +00002819}
2820
John McCallbd309292010-07-06 01:34:17 +00002821/// Emits a call or invoke instruction to the given function, depending
2822/// on the current state of the EH stack.
2823llvm::CallSite
2824CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00002825 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002826 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00002827 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00002828
Dan Gohman515a60d2012-02-16 00:57:37 +00002829 llvm::Instruction *Inst;
2830 if (!InvokeDest)
2831 Inst = Builder.CreateCall(Callee, Args, Name);
2832 else {
2833 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2834 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2835 EmitBlock(ContBB);
2836 }
2837
2838 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2839 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002840 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002841 AddObjCARCExceptionMetadata(Inst);
2842
2843 return Inst;
John McCallbd309292010-07-06 01:34:17 +00002844}
2845
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002846/// \brief Store a non-aggregate value to an address to initialize it. For
2847/// initialization, a non-atomic store will be used.
2848static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
2849 LValue Dst) {
2850 if (Src.isScalar())
2851 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
2852 else
2853 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
2854}
2855
2856void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
2857 llvm::Value *New) {
2858 DeferredReplacements.push_back(std::make_pair(Old, New));
2859}
Chris Lattnerd59d8672011-07-12 06:29:11 +00002860
Daniel Dunbard931a872009-02-02 22:03:45 +00002861RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00002862 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00002863 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002864 const CallArgList &CallArgs,
David Chisnall9eecafa2010-05-01 11:15:56 +00002865 const Decl *TargetDecl,
David Chisnallff5f88c2010-05-02 13:41:58 +00002866 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00002867 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00002868
2869 // Handle struct-return functions by passing a pointer to the
2870 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00002871 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002872 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002873
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002874 llvm::FunctionType *IRFuncTy =
2875 cast<llvm::FunctionType>(
2876 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00002877
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002878 // If we're using inalloca, insert the allocation after the stack save.
2879 // FIXME: Do this earlier rather than hacking it in here!
Craig Topper8a13c412014-05-21 05:09:00 +00002880 llvm::Value *ArgMemory = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002881 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
Reid Kleckner9df1d972014-04-10 01:40:15 +00002882 llvm::Instruction *IP = CallArgs.getStackBase();
2883 llvm::AllocaInst *AI;
2884 if (IP) {
2885 IP = IP->getNextNode();
2886 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
2887 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00002888 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00002889 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002890 AI->setUsedWithInAlloca(true);
2891 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
2892 ArgMemory = AI;
2893 }
2894
Alexey Samsonov153004f2014-09-29 22:08:00 +00002895 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002896 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
2897
Chris Lattner4ca97c32009-06-13 00:26:38 +00002898 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00002899 // alloca to hold the result, unless one is given to us.
Craig Topper8a13c412014-05-21 05:09:00 +00002900 llvm::Value *SRetPtr = nullptr;
Reid Kleckner37abaca2014-05-09 22:46:15 +00002901 if (RetAI.isIndirect() || RetAI.isInAlloca()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002902 SRetPtr = ReturnValue.getValue();
2903 if (!SRetPtr)
2904 SRetPtr = CreateMemTemp(RetTy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002905 if (IRFunctionArgs.hasSRetArg()) {
2906 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002907 } else {
2908 llvm::Value *Addr =
2909 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
2910 Builder.CreateStore(SRetPtr, Addr);
2911 }
Anders Carlsson17490832009-12-24 20:40:36 +00002912 }
Mike Stump11289f42009-09-09 15:08:12 +00002913
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002914 assert(CallInfo.arg_size() == CallArgs.size() &&
2915 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002916 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002917 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002918 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002919 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002920 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002921 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002922
John McCall47fb9502013-03-07 21:37:08 +00002923 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002924
2925 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002926 if (IRFunctionArgs.hasPaddingArg(ArgNo))
2927 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2928 llvm::UndefValue::get(ArgInfo.getPaddingType());
2929
2930 unsigned FirstIRArg, NumIRArgs;
2931 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002932
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002933 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002934 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002935 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002936 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2937 if (RV.isAggregate()) {
2938 // Replace the placeholder with the appropriate argument slot GEP.
2939 llvm::Instruction *Placeholder =
2940 cast<llvm::Instruction>(RV.getAggregateAddr());
2941 CGBuilderTy::InsertPoint IP = Builder.saveIP();
2942 Builder.SetInsertPoint(Placeholder);
2943 llvm::Value *Addr = Builder.CreateStructGEP(
2944 ArgMemory, ArgInfo.getInAllocaFieldIndex());
2945 Builder.restoreIP(IP);
2946 deferPlaceholderReplacement(Placeholder, Addr);
2947 } else {
2948 // Store the RValue into the argument struct.
2949 llvm::Value *Addr =
2950 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
David Majnemer32b57b02014-03-31 16:12:47 +00002951 unsigned AS = Addr->getType()->getPointerAddressSpace();
2952 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
2953 // There are some cases where a trivial bitcast is not avoidable. The
2954 // definition of a type later in a translation unit may change it's type
2955 // from {}* to (%struct.foo*)*.
2956 if (Addr->getType() != MemType)
2957 Addr = Builder.CreateBitCast(Addr, MemType);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002958 LValue argLV = MakeAddrLValue(Addr, I->Ty, TypeAlign);
2959 EmitInitStoreOfNonAggregate(*this, RV, argLV);
2960 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002961 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002962 }
2963
Daniel Dunbar03816342010-08-21 02:24:36 +00002964 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002965 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00002966 if (RV.isScalar() || RV.isComplex()) {
2967 // Make a temporary alloca to pass the argument.
Eli Friedman7e68c882011-06-15 18:26:32 +00002968 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2969 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
2970 AI->setAlignment(ArgInfo.getIndirectAlign());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002971 IRCallArgs[FirstIRArg] = AI;
John McCall47fb9502013-03-07 21:37:08 +00002972
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002973 LValue argLV = MakeAddrLValue(AI, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002974 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00002975 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002976 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00002977 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002978 // 1. If the argument is not byval, and we are required to copy the
2979 // source. (This case doesn't occur on any common architecture.)
2980 // 2. If the argument is byval, RV is not sufficiently aligned, and
2981 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00002982 // 3. If the argument is byval, but RV is located in an address space
2983 // different than that of the argument (0).
Eli Friedmanf7456192011-06-15 22:09:18 +00002984 llvm::Value *Addr = RV.getAggregateAddr();
2985 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002986 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyei3832bfd2013-03-10 12:59:00 +00002987 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002988 const unsigned ArgAddrSpace =
2989 (FirstIRArg < IRFuncTy->getNumParams()
2990 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
2991 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00002992 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall47fb9502013-03-07 21:37:08 +00002993 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Guy Benyei3832bfd2013-03-10 12:59:00 +00002994 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
2995 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002996 // Create an aligned temporary, and copy to it.
Eli Friedmanf7456192011-06-15 22:09:18 +00002997 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2998 if (Align > AI->getAlignment())
2999 AI->setAlignment(Align);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003000 IRCallArgs[FirstIRArg] = AI;
Chad Rosier615ed1a2012-03-29 17:37:10 +00003001 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003002 } else {
3003 // Skip the extra memcpy call.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003004 IRCallArgs[FirstIRArg] = Addr;
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003005 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003006 }
3007 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003008 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003009
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003010 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003011 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003012 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003013
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003014 case ABIArgInfo::Extend:
3015 case ABIArgInfo::Direct: {
3016 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003017 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3018 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003019 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003020 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003021 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003022 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003023 else
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003024 V = Builder.CreateLoad(RV.getAggregateAddr());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003025
Chris Lattner3ce86682011-07-12 04:53:39 +00003026 // If the argument doesn't match, perform a bitcast to coerce it. This
3027 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003028 if (FirstIRArg < IRFuncTy->getNumParams() &&
3029 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3030 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
3031 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003032 break;
3033 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003034
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003035 // FIXME: Avoid the conversion through memory if possible.
3036 llvm::Value *SrcPtr;
John McCall47fb9502013-03-07 21:37:08 +00003037 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003038 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall47fb9502013-03-07 21:37:08 +00003039 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003040 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Mike Stump11289f42009-09-09 15:08:12 +00003041 } else
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003042 SrcPtr = RV.getAggregateAddr();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003043
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003044 // If the value is offset in memory, apply the offset now.
3045 if (unsigned Offs = ArgInfo.getDirectOffset()) {
3046 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
3047 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003048 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003049 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
3050
3051 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003052
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003053 // Fast-isel and the optimizer generally like scalar values better than
3054 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00003055 llvm::StructType *STy =
3056 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003057 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
Chandler Carrutha6399a52012-10-10 11:29:08 +00003058 llvm::Type *SrcTy =
3059 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
3060 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3061 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3062
3063 // If the source type is smaller than the destination type of the
3064 // coerce-to logic, copy the source value into a temp alloca the size
3065 // of the destination type to allow loading all of it. The bits past
3066 // the source value are left undef.
3067 if (SrcSize < DstSize) {
3068 llvm::AllocaInst *TempAlloca
3069 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
3070 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
3071 SrcPtr = TempAlloca;
3072 } else {
3073 SrcPtr = Builder.CreateBitCast(SrcPtr,
3074 llvm::PointerType::getUnqual(STy));
3075 }
3076
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003077 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00003078 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3079 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerff941a62010-07-28 18:24:28 +00003080 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
3081 // We don't know what we're loading from.
3082 LI->setAlignment(1);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003083 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003084 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003085 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003086 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003087 assert(NumIRArgs == 1);
3088 IRCallArgs[FirstIRArg] =
3089 CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003090 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003091
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003092 break;
3093 }
3094
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003095 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003096 unsigned IRArgPos = FirstIRArg;
3097 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3098 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003099 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003100 }
3101 }
Mike Stump11289f42009-09-09 15:08:12 +00003102
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003103 if (ArgMemory) {
3104 llvm::Value *Arg = ArgMemory;
Reid Klecknerafba553e2014-07-08 02:24:27 +00003105 if (CallInfo.isVariadic()) {
3106 // When passing non-POD arguments by value to variadic functions, we will
3107 // end up with a variadic prototype and an inalloca call site. In such
3108 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3109 // the callee.
3110 unsigned CalleeAS =
3111 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
3112 Callee = Builder.CreateBitCast(
3113 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
3114 } else {
3115 llvm::Type *LastParamTy =
3116 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3117 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003118#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003119 // Assert that these structs have equivalent element types.
3120 llvm::StructType *FullTy = CallInfo.getArgStruct();
3121 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3122 cast<llvm::PointerType>(LastParamTy)->getElementType());
3123 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3124 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3125 DE = DeclaredTy->element_end(),
3126 FI = FullTy->element_begin();
3127 DI != DE; ++DI, ++FI)
3128 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003129#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003130 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3131 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003132 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003133 assert(IRFunctionArgs.hasInallocaArg());
3134 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003135 }
3136
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003137 if (!CallArgs.getCleanupsToDeactivate().empty())
3138 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3139
Chris Lattner4ca97c32009-06-13 00:26:38 +00003140 // If the callee is a bitcast of a function to a varargs pointer to function
3141 // type, check to see if we can remove the bitcast. This handles some cases
3142 // with unprototyped functions.
3143 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3144 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003145 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3146 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00003147 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00003148 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00003149
Chris Lattner4ca97c32009-06-13 00:26:38 +00003150 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3151 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00003152 ActualFT->getNumParams() == CurFT->getNumParams() &&
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003153 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00003154 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00003155 bool ArgsMatch = true;
3156 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3157 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3158 ArgsMatch = false;
3159 break;
3160 }
Mike Stump11289f42009-09-09 15:08:12 +00003161
Chris Lattner4ca97c32009-06-13 00:26:38 +00003162 // Strip the cast if we can get away with it. This is a nice cleanup,
3163 // but also allows us to inline the function at -O0 if it is marked
3164 // always_inline.
3165 if (ArgsMatch)
3166 Callee = CalleeF;
3167 }
3168 }
Mike Stump11289f42009-09-09 15:08:12 +00003169
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003170 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3171 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3172 // Inalloca argument can have different type.
3173 if (IRFunctionArgs.hasInallocaArg() &&
3174 i == IRFunctionArgs.getInallocaArgNo())
3175 continue;
3176 if (i < IRFuncTy->getNumParams())
3177 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3178 }
3179
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003180 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003181 CodeGen::AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003182 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
3183 CallingConv, true);
Bill Wendling3087d022012-12-07 23:17:26 +00003184 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003185 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003186
Craig Topper8a13c412014-05-21 05:09:00 +00003187 llvm::BasicBlock *InvokeDest = nullptr;
Bill Wendling5e85be42012-12-30 10:32:17 +00003188 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
3189 llvm::Attribute::NoUnwind))
John McCallbd309292010-07-06 01:34:17 +00003190 InvokeDest = getInvokeDest();
3191
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003192 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003193 if (!InvokeDest) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003194 CS = Builder.CreateCall(Callee, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003195 } else {
3196 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003197 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003198 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003199 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003200 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003201 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003202
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003203 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3204 !CS.hasFnAttr(llvm::Attribute::NoInline))
3205 Attrs =
3206 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3207 llvm::Attribute::AlwaysInline);
3208
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003209 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003210 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003211
Dan Gohman515a60d2012-02-16 00:57:37 +00003212 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3213 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003214 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003215 AddObjCARCExceptionMetadata(CS.getInstruction());
3216
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003217 // If the call doesn't return, finish the basic block and clear the
3218 // insertion point; this allows the rest of IRgen to discard
3219 // unreachable code.
3220 if (CS.doesNotReturn()) {
3221 Builder.CreateUnreachable();
3222 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003223
Mike Stump18bb9282009-05-16 07:57:57 +00003224 // FIXME: For now, emit a dummy basic block because expr emitters in
3225 // generally are not ready to handle emitting expressions at unreachable
3226 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003227 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003228
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003229 // Return a reasonable RValue.
3230 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003231 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003232
3233 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00003234 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003235 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003236
John McCall31168b02011-06-15 23:02:42 +00003237 // Emit any writebacks immediately. Arguably this should happen
3238 // after any return-value munging.
3239 if (CallArgs.hasWritebacks())
3240 emitWritebacks(*this, CallArgs);
3241
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003242 // The stack cleanup for inalloca arguments has to run out of the normal
3243 // lexical order, so deactivate it and run it manually here.
3244 CallArgs.freeArgumentMemory(*this);
3245
Hal Finkelee90a222014-09-26 05:04:30 +00003246 RValue Ret = [&] {
3247 switch (RetAI.getKind()) {
3248 case ABIArgInfo::InAlloca:
3249 case ABIArgInfo::Indirect:
3250 return convertTempToRValue(SRetPtr, RetTy, SourceLocation());
Daniel Dunbard3674e62008-09-11 01:48:57 +00003251
Hal Finkelee90a222014-09-26 05:04:30 +00003252 case ABIArgInfo::Ignore:
3253 // If we are ignoring an argument that had a result, make sure to
3254 // construct the appropriate return value for our caller.
3255 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003256
Hal Finkelee90a222014-09-26 05:04:30 +00003257 case ABIArgInfo::Extend:
3258 case ABIArgInfo::Direct: {
3259 llvm::Type *RetIRTy = ConvertType(RetTy);
3260 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
3261 switch (getEvaluationKind(RetTy)) {
3262 case TEK_Complex: {
3263 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
3264 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
3265 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003266 }
Hal Finkelee90a222014-09-26 05:04:30 +00003267 case TEK_Aggregate: {
3268 llvm::Value *DestPtr = ReturnValue.getValue();
3269 bool DestIsVolatile = ReturnValue.isVolatile();
3270
3271 if (!DestPtr) {
3272 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3273 DestIsVolatile = false;
3274 }
3275 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
3276 return RValue::getAggregate(DestPtr);
3277 }
3278 case TEK_Scalar: {
3279 // If the argument doesn't match, perform a bitcast to coerce it. This
3280 // can happen due to trivial type mismatches.
3281 llvm::Value *V = CI;
3282 if (V->getType() != RetIRTy)
3283 V = Builder.CreateBitCast(V, RetIRTy);
3284 return RValue::get(V);
3285 }
3286 }
3287 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003288 }
Hal Finkelee90a222014-09-26 05:04:30 +00003289
3290 llvm::Value *DestPtr = ReturnValue.getValue();
3291 bool DestIsVolatile = ReturnValue.isVolatile();
3292
3293 if (!DestPtr) {
3294 DestPtr = CreateMemTemp(RetTy, "coerce");
3295 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00003296 }
Hal Finkelee90a222014-09-26 05:04:30 +00003297
3298 // If the value is offset in memory, apply the offset now.
3299 llvm::Value *StorePtr = DestPtr;
3300 if (unsigned Offs = RetAI.getDirectOffset()) {
3301 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
3302 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
3303 StorePtr = Builder.CreateBitCast(StorePtr,
3304 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
John McCall47fb9502013-03-07 21:37:08 +00003305 }
Hal Finkelee90a222014-09-26 05:04:30 +00003306 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
3307
3308 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003309 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003310
Hal Finkelee90a222014-09-26 05:04:30 +00003311 case ABIArgInfo::Expand:
3312 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00003313 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003314
Hal Finkelee90a222014-09-26 05:04:30 +00003315 llvm_unreachable("Unhandled ABIArgInfo::Kind");
3316 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003317
Hal Finkelee90a222014-09-26 05:04:30 +00003318 if (Ret.isScalar() && TargetDecl) {
3319 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
3320 llvm::Value *OffsetValue = nullptr;
3321 if (const auto *Offset = AA->getOffset())
3322 OffsetValue = EmitScalarExpr(Offset);
3323
3324 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
3325 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
3326 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
3327 OffsetValue);
3328 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00003329 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003330
Hal Finkelee90a222014-09-26 05:04:30 +00003331 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003332}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003333
3334/* VarArg handling */
3335
3336llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
3337 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
3338}