blob: 726e808ed08aec0fb82b303df7d67d3b3afaf3a6 [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"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/InlineAsm.h"
Bill Wendling985d1c52013-02-15 21:30:01 +000031#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "llvm/Support/CallSite.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.
John McCall8dda7b22012-07-07 06:41:13 +000082 return arrangeLLVMFunctionInfo(FTNP->getResultType().getUnqualifiedType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000083 None, FTNP->getExtInfo(), RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +000084}
85
John McCall8dda7b22012-07-07 06:41:13 +000086/// Arrange the LLVM function layout for a value of the given function
87/// type, on top of any implicit parameters already stored. Use the
88/// given ExtInfo instead of the ExtInfo from the function type.
89static const CGFunctionInfo &arrangeLLVMFunctionInfo(CodeGenTypes &CGT,
90 SmallVectorImpl<CanQualType> &prefix,
91 CanQual<FunctionProtoType> FTP,
92 FunctionType::ExtInfo extInfo) {
93 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +000094 // FIXME: Kill copy.
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000095 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
John McCall8dda7b22012-07-07 06:41:13 +000096 prefix.push_back(FTP->getArgType(i));
John McCalla729c622012-02-17 03:33:10 +000097 CanQualType resultType = FTP->getResultType().getUnqualifiedType();
John McCall8dda7b22012-07-07 06:41:13 +000098 return CGT.arrangeLLVMFunctionInfo(resultType, prefix, extInfo, required);
99}
100
101/// Arrange the argument and result information for a free function (i.e.
102/// not a C++ or ObjC instance method) of the given type.
103static const CGFunctionInfo &arrangeFreeFunctionType(CodeGenTypes &CGT,
104 SmallVectorImpl<CanQualType> &prefix,
105 CanQual<FunctionProtoType> FTP) {
106 return arrangeLLVMFunctionInfo(CGT, prefix, FTP, FTP->getExtInfo());
107}
108
John McCall8dda7b22012-07-07 06:41:13 +0000109/// Arrange the argument and result information for a free function (i.e.
110/// not a C++ or ObjC instance method) of the given type.
111static const CGFunctionInfo &arrangeCXXMethodType(CodeGenTypes &CGT,
112 SmallVectorImpl<CanQualType> &prefix,
113 CanQual<FunctionProtoType> FTP) {
114 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
John McCall8dda7b22012-07-07 06:41:13 +0000115 return arrangeLLVMFunctionInfo(CGT, prefix, FTP, extInfo);
John McCall8ee376f2010-02-24 07:14:12 +0000116}
117
John McCalla729c622012-02-17 03:33:10 +0000118/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000119/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000120const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000121CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
John McCalla729c622012-02-17 03:33:10 +0000122 SmallVector<CanQualType, 16> argTypes;
John McCall8dda7b22012-07-07 06:41:13 +0000123 return ::arrangeFreeFunctionType(*this, argTypes, FTP);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000124}
125
John McCallab26cfa2010-02-05 21:31:56 +0000126static CallingConv getCallingConventionForDecl(const Decl *D) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000127 // Set the appropriate calling convention for the Function.
128 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000129 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000130
131 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000132 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000133
Douglas Gregora941dca2010-05-18 16:57:00 +0000134 if (D->hasAttr<ThisCallAttr>())
135 return CC_X86ThisCall;
136
Dawn Perchik335e16b2010-09-03 01:29:35 +0000137 if (D->hasAttr<PascalAttr>())
138 return CC_X86Pascal;
139
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000140 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
141 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
142
Derek Schuffa2020962012-10-16 22:30:41 +0000143 if (D->hasAttr<PnaclCallAttr>())
144 return CC_PnaclCall;
145
Guy Benyeif0a014b2012-12-25 08:53:55 +0000146 if (D->hasAttr<IntelOclBiccAttr>())
147 return CC_IntelOclBicc;
148
John McCallab26cfa2010-02-05 21:31:56 +0000149 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000150}
151
John McCalla729c622012-02-17 03:33:10 +0000152/// Arrange the argument and result information for a call to an
153/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000154/// (Zero value of RD means we don't have any meaningful "this" argument type,
155/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000156/// The member function must be an ordinary function, i.e. not a
157/// constructor or destructor.
158const CGFunctionInfo &
159CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
160 const FunctionProtoType *FTP) {
161 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000162
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000163 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000164 if (RD)
165 argTypes.push_back(GetThisType(Context, RD));
166 else
167 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000168
John McCall8dda7b22012-07-07 06:41:13 +0000169 return ::arrangeCXXMethodType(*this, argTypes,
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000170 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000171}
172
John McCalla729c622012-02-17 03:33:10 +0000173/// Arrange the argument and result information for a declaration or
174/// definition of the given C++ non-static member function. The
175/// member function must be an ordinary function, i.e. not a
176/// constructor or destructor.
177const CGFunctionInfo &
178CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000179 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000180 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
181
John McCalla729c622012-02-17 03:33:10 +0000182 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000183
John McCalla729c622012-02-17 03:33:10 +0000184 if (MD->isInstance()) {
185 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000186 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000187 return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
John McCalla729c622012-02-17 03:33:10 +0000188 }
189
John McCall8dda7b22012-07-07 06:41:13 +0000190 return arrangeFreeFunctionType(prototype);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000191}
192
John McCalla729c622012-02-17 03:33:10 +0000193/// Arrange the argument and result information for a declaration
194/// or definition to the given constructor variant.
195const CGFunctionInfo &
196CodeGenTypes::arrangeCXXConstructorDeclaration(const CXXConstructorDecl *D,
197 CXXCtorType ctorKind) {
198 SmallVector<CanQualType, 16> argTypes;
199 argTypes.push_back(GetThisType(Context, D->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000200
201 GlobalDecl GD(D, ctorKind);
202 CanQualType resultType =
203 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000204
John McCalla729c622012-02-17 03:33:10 +0000205 TheCXXABI.BuildConstructorSignature(D, ctorKind, resultType, argTypes);
John McCall8ee376f2010-02-24 07:14:12 +0000206
John McCall5d865c322010-08-31 07:33:07 +0000207 CanQual<FunctionProtoType> FTP = GetFormalType(D);
208
John McCalla729c622012-02-17 03:33:10 +0000209 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, argTypes.size());
210
John McCall5d865c322010-08-31 07:33:07 +0000211 // Add the formal parameters.
212 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
John McCalla729c622012-02-17 03:33:10 +0000213 argTypes.push_back(FTP->getArgType(i));
John McCall5d865c322010-08-31 07:33:07 +0000214
John McCall8dda7b22012-07-07 06:41:13 +0000215 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
John McCall8dda7b22012-07-07 06:41:13 +0000216 return arrangeLLVMFunctionInfo(resultType, argTypes, extInfo, required);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000217}
218
John McCalla729c622012-02-17 03:33:10 +0000219/// Arrange the argument and result information for a declaration,
220/// definition, or call to the given destructor variant. It so
221/// happens that all three cases produce the same information.
222const CGFunctionInfo &
223CodeGenTypes::arrangeCXXDestructor(const CXXDestructorDecl *D,
224 CXXDtorType dtorKind) {
225 SmallVector<CanQualType, 2> argTypes;
226 argTypes.push_back(GetThisType(Context, D->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000227
228 GlobalDecl GD(D, dtorKind);
229 CanQualType resultType =
230 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
John McCall8ee376f2010-02-24 07:14:12 +0000231
John McCalla729c622012-02-17 03:33:10 +0000232 TheCXXABI.BuildDestructorSignature(D, dtorKind, resultType, argTypes);
John McCall5d865c322010-08-31 07:33:07 +0000233
234 CanQual<FunctionProtoType> FTP = GetFormalType(D);
235 assert(FTP->getNumArgs() == 0 && "dtor with formal parameters");
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +0000236 assert(FTP->isVariadic() == 0 && "dtor with formal parameters");
John McCall5d865c322010-08-31 07:33:07 +0000237
John McCall8dda7b22012-07-07 06:41:13 +0000238 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
John McCall8dda7b22012-07-07 06:41:13 +0000239 return arrangeLLVMFunctionInfo(resultType, argTypes, extInfo,
240 RequiredArgs::All);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000241}
242
John McCalla729c622012-02-17 03:33:10 +0000243/// Arrange the argument and result information for the declaration or
244/// definition of the given function.
245const CGFunctionInfo &
246CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000247 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000248 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000249 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000250
John McCall2da83a32010-02-26 00:48:12 +0000251 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000252
John McCall2da83a32010-02-26 00:48:12 +0000253 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000254
255 // When declaring a function without a prototype, always use a
256 // non-variadic type.
257 if (isa<FunctionNoProtoType>(FTy)) {
258 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000259 return arrangeLLVMFunctionInfo(noProto->getResultType(), None,
260 noProto->getExtInfo(), RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000261 }
262
John McCall2da83a32010-02-26 00:48:12 +0000263 assert(isa<FunctionProtoType>(FTy));
John McCall8dda7b22012-07-07 06:41:13 +0000264 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000265}
266
John McCalla729c622012-02-17 03:33:10 +0000267/// Arrange the argument and result information for the declaration or
268/// definition of an Objective-C method.
269const CGFunctionInfo &
270CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
271 // It happens that this is the same as a call with no optional
272 // arguments, except also using the formal 'self' type.
273 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
274}
275
276/// Arrange the argument and result information for the function type
277/// through which to perform a send to the given Objective-C method,
278/// using the given receiver type. The receiver type is not always
279/// the 'self' type of the method or even an Objective-C pointer type.
280/// This is *not* the right method for actually performing such a
281/// message send, due to the possibility of optional arguments.
282const CGFunctionInfo &
283CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
284 QualType receiverType) {
285 SmallVector<CanQualType, 16> argTys;
286 argTys.push_back(Context.getCanonicalParamType(receiverType));
287 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000288 // FIXME: Kill copy?
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +0000289 for (ObjCMethodDecl::param_const_iterator i = MD->param_begin(),
John McCall8ee376f2010-02-24 07:14:12 +0000290 e = MD->param_end(); i != e; ++i) {
John McCalla729c622012-02-17 03:33:10 +0000291 argTys.push_back(Context.getCanonicalParamType((*i)->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000292 }
John McCall31168b02011-06-15 23:02:42 +0000293
294 FunctionType::ExtInfo einfo;
295 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD));
296
David Blaikiebbafb8a2012-03-11 07:00:24 +0000297 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000298 MD->hasAttr<NSReturnsRetainedAttr>())
299 einfo = einfo.withProducesResult(true);
300
John McCalla729c622012-02-17 03:33:10 +0000301 RequiredArgs required =
302 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
303
John McCall8dda7b22012-07-07 06:41:13 +0000304 return arrangeLLVMFunctionInfo(GetReturnType(MD->getResultType()), argTys,
305 einfo, required);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000306}
307
John McCalla729c622012-02-17 03:33:10 +0000308const CGFunctionInfo &
309CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000310 // FIXME: Do we need to handle ObjCMethodDecl?
311 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000312
Anders Carlsson6710c532010-02-06 02:44:09 +0000313 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
John McCalla729c622012-02-17 03:33:10 +0000314 return arrangeCXXConstructorDeclaration(CD, GD.getCtorType());
Anders Carlsson6710c532010-02-06 02:44:09 +0000315
316 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
John McCalla729c622012-02-17 03:33:10 +0000317 return arrangeCXXDestructor(DD, GD.getDtorType());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000318
John McCalla729c622012-02-17 03:33:10 +0000319 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000320}
321
John McCallc818bbb2012-12-07 07:03:17 +0000322/// Arrange a call as unto a free function, except possibly with an
323/// additional number of formal parameters considered required.
324static const CGFunctionInfo &
325arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000326 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000327 const CallArgList &args,
328 const FunctionType *fnType,
329 unsigned numExtraRequiredArgs) {
330 assert(args.size() >= numExtraRequiredArgs);
331
332 // In most cases, there are no optional arguments.
333 RequiredArgs required = RequiredArgs::All;
334
335 // If we have a variadic prototype, the required arguments are the
336 // extra prefix plus the arguments in the prototype.
337 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
338 if (proto->isVariadic())
339 required = RequiredArgs(proto->getNumArgs() + numExtraRequiredArgs);
340
341 // If we don't have a prototype at all, but we're supposed to
342 // explicitly use the variadic convention for unprototyped calls,
343 // treat all of the arguments as required but preserve the nominal
344 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000345 } else if (CGM.getTargetCodeGenInfo()
346 .isNoProtoCallVariadic(args,
347 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000348 required = RequiredArgs(args.size());
349 }
350
351 return CGT.arrangeFreeFunctionCall(fnType->getResultType(), args,
352 fnType->getExtInfo(), required);
353}
354
John McCalla729c622012-02-17 03:33:10 +0000355/// Figure out the rules for calling a function with the given formal
356/// type using the given arguments. The arguments are necessary
357/// because the function might be unprototyped, in which case it's
358/// target-dependent in crazy ways.
359const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000360CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
361 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000362 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 0);
John McCallc818bbb2012-12-07 07:03:17 +0000363}
John McCalla729c622012-02-17 03:33:10 +0000364
John McCallc818bbb2012-12-07 07:03:17 +0000365/// A block function call is essentially a free-function call with an
366/// extra implicit argument.
367const CGFunctionInfo &
368CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
369 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000370 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1);
John McCalla729c622012-02-17 03:33:10 +0000371}
372
373const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000374CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
375 const CallArgList &args,
376 FunctionType::ExtInfo info,
377 RequiredArgs required) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000378 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000379 SmallVector<CanQualType, 16> argTypes;
380 for (CallArgList::const_iterator i = args.begin(), e = args.end();
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000381 i != e; ++i)
John McCalla729c622012-02-17 03:33:10 +0000382 argTypes.push_back(Context.getCanonicalParamType(i->Ty));
John McCall8dda7b22012-07-07 06:41:13 +0000383 return arrangeLLVMFunctionInfo(GetReturnType(resultType), argTypes, info,
384 required);
385}
386
387/// Arrange a call to a C++ method, passing the given arguments.
388const CGFunctionInfo &
389CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
390 const FunctionProtoType *FPT,
391 RequiredArgs required) {
392 // FIXME: Kill copy.
393 SmallVector<CanQualType, 16> argTypes;
394 for (CallArgList::const_iterator i = args.begin(), e = args.end();
395 i != e; ++i)
396 argTypes.push_back(Context.getCanonicalParamType(i->Ty));
397
398 FunctionType::ExtInfo info = FPT->getExtInfo();
John McCall8dda7b22012-07-07 06:41:13 +0000399 return arrangeLLVMFunctionInfo(GetReturnType(FPT->getResultType()),
400 argTypes, info, required);
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000401}
402
John McCalla729c622012-02-17 03:33:10 +0000403const CGFunctionInfo &
404CodeGenTypes::arrangeFunctionDeclaration(QualType resultType,
405 const FunctionArgList &args,
406 const FunctionType::ExtInfo &info,
407 bool isVariadic) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000408 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000409 SmallVector<CanQualType, 16> argTypes;
410 for (FunctionArgList::const_iterator i = args.begin(), e = args.end();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +0000411 i != e; ++i)
John McCalla729c622012-02-17 03:33:10 +0000412 argTypes.push_back(Context.getCanonicalParamType((*i)->getType()));
413
414 RequiredArgs required =
415 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
John McCall8dda7b22012-07-07 06:41:13 +0000416 return arrangeLLVMFunctionInfo(GetReturnType(resultType), argTypes, info,
417 required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000418}
419
John McCalla729c622012-02-17 03:33:10 +0000420const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000421 return arrangeLLVMFunctionInfo(getContext().VoidTy, None,
John McCall8dda7b22012-07-07 06:41:13 +0000422 FunctionType::ExtInfo(), RequiredArgs::All);
John McCalla738c252011-03-09 04:27:21 +0000423}
424
John McCalla729c622012-02-17 03:33:10 +0000425/// Arrange the argument and result information for an abstract value
426/// of a given function type. This is the method which all of the
427/// above functions ultimately defer to.
428const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000429CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
430 ArrayRef<CanQualType> argTypes,
431 FunctionType::ExtInfo info,
432 RequiredArgs required) {
John McCall2da83a32010-02-26 00:48:12 +0000433#ifndef NDEBUG
John McCalla729c622012-02-17 03:33:10 +0000434 for (ArrayRef<CanQualType>::const_iterator
435 I = argTypes.begin(), E = argTypes.end(); I != E; ++I)
John McCall2da83a32010-02-26 00:48:12 +0000436 assert(I->isCanonicalAsParam());
437#endif
438
John McCalla729c622012-02-17 03:33:10 +0000439 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCallab26cfa2010-02-05 21:31:56 +0000440
Daniel Dunbare0be8292009-02-03 00:07:12 +0000441 // Lookup or create unique function info.
442 llvm::FoldingSetNodeID ID;
John McCalla729c622012-02-17 03:33:10 +0000443 CGFunctionInfo::Profile(ID, info, required, resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000444
John McCalla729c622012-02-17 03:33:10 +0000445 void *insertPos = 0;
446 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000447 if (FI)
448 return *FI;
449
John McCalla729c622012-02-17 03:33:10 +0000450 // Construct the function info. We co-allocate the ArgInfos.
451 FI = CGFunctionInfo::create(CC, info, resultType, argTypes, required);
452 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000453
John McCalla729c622012-02-17 03:33:10 +0000454 bool inserted = FunctionsBeingProcessed.insert(FI); (void)inserted;
455 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000456
Daniel Dunbar313321e2009-02-03 05:31:23 +0000457 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000458 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000459
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000460 // Loop over all of the computed argument and return value info. If any of
461 // them are direct or extend without a specified coerce type, specify the
462 // default now.
John McCalla729c622012-02-17 03:33:10 +0000463 ABIArgInfo &retInfo = FI->getReturnInfo();
464 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == 0)
465 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000466
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000467 for (CGFunctionInfo::arg_iterator I = FI->arg_begin(), E = FI->arg_end();
468 I != E; ++I)
469 if (I->info.canHaveCoerceToType() && I->info.getCoerceToType() == 0)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000470 I->info.setCoerceToType(ConvertType(I->type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000471
John McCalla729c622012-02-17 03:33:10 +0000472 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
473 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000474
Daniel Dunbare0be8292009-02-03 00:07:12 +0000475 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000476}
477
John McCalla729c622012-02-17 03:33:10 +0000478CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
479 const FunctionType::ExtInfo &info,
480 CanQualType resultType,
481 ArrayRef<CanQualType> argTypes,
482 RequiredArgs required) {
483 void *buffer = operator new(sizeof(CGFunctionInfo) +
484 sizeof(ArgInfo) * (argTypes.size() + 1));
485 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
486 FI->CallingConvention = llvmCC;
487 FI->EffectiveCallingConvention = llvmCC;
488 FI->ASTCallingConvention = info.getCC();
489 FI->NoReturn = info.getNoReturn();
490 FI->ReturnsRetained = info.getProducesResult();
491 FI->Required = required;
492 FI->HasRegParm = info.getHasRegParm();
493 FI->RegParm = info.getRegParm();
494 FI->NumArgs = argTypes.size();
495 FI->getArgsBuffer()[0].type = resultType;
496 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
497 FI->getArgsBuffer()[i + 1].type = argTypes[i];
498 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000499}
500
501/***/
502
John McCall85dd2c52011-05-15 02:19:42 +0000503void CodeGenTypes::GetExpandedTypes(QualType type,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000504 SmallVectorImpl<llvm::Type*> &expandedTypes) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000505 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(type)) {
506 uint64_t NumElts = AT->getSize().getZExtValue();
507 for (uint64_t Elt = 0; Elt < NumElts; ++Elt)
508 GetExpandedTypes(AT->getElementType(), expandedTypes);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000509 } else if (const RecordType *RT = type->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000510 const RecordDecl *RD = RT->getDecl();
511 assert(!RD->hasFlexibleArrayMember() &&
512 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000513 if (RD->isUnion()) {
514 // Unions can be here only in degenerative cases - all the fields are same
515 // after flattening. Thus we have to use the "largest" field.
516 const FieldDecl *LargestFD = 0;
517 CharUnits UnionSize = CharUnits::Zero();
518
519 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
520 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000521 const FieldDecl *FD = *i;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000522 assert(!FD->isBitField() &&
523 "Cannot expand structure with bit-field members.");
524 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
525 if (UnionSize < FieldSize) {
526 UnionSize = FieldSize;
527 LargestFD = FD;
528 }
529 }
530 if (LargestFD)
531 GetExpandedTypes(LargestFD->getType(), expandedTypes);
532 } else {
533 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
534 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000535 assert(!i->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000536 "Cannot expand structure with bit-field members.");
David Blaikie40ed2972012-06-06 20:45:41 +0000537 GetExpandedTypes(i->getType(), expandedTypes);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000538 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000539 }
540 } else if (const ComplexType *CT = type->getAs<ComplexType>()) {
541 llvm::Type *EltTy = ConvertType(CT->getElementType());
542 expandedTypes.push_back(EltTy);
543 expandedTypes.push_back(EltTy);
544 } else
545 expandedTypes.push_back(ConvertType(type));
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000546}
547
Mike Stump11289f42009-09-09 15:08:12 +0000548llvm::Function::arg_iterator
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000549CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
550 llvm::Function::arg_iterator AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000551 assert(LV.isSimple() &&
552 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000553
Bob Wilsone826a2a2011-08-03 05:58:22 +0000554 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
555 unsigned NumElts = AT->getSize().getZExtValue();
556 QualType EltTy = AT->getElementType();
557 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000558 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, Elt);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000559 LValue LV = MakeAddrLValue(EltAddr, EltTy);
560 AI = ExpandTypeFromArgs(EltTy, LV, AI);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000561 }
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000562 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000563 RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000564 if (RD->isUnion()) {
565 // Unions can be here only in degenerative cases - all the fields are same
566 // after flattening. Thus we have to use the "largest" field.
567 const FieldDecl *LargestFD = 0;
568 CharUnits UnionSize = CharUnits::Zero();
Bob Wilsone826a2a2011-08-03 05:58:22 +0000569
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000570 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
571 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000572 const FieldDecl *FD = *i;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000573 assert(!FD->isBitField() &&
574 "Cannot expand structure with bit-field members.");
575 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
576 if (UnionSize < FieldSize) {
577 UnionSize = FieldSize;
578 LargestFD = FD;
579 }
580 }
581 if (LargestFD) {
582 // FIXME: What are the right qualifiers here?
Eli Friedman7f1ff602012-04-16 03:54:45 +0000583 LValue SubLV = EmitLValueForField(LV, LargestFD);
584 AI = ExpandTypeFromArgs(LargestFD->getType(), SubLV, AI);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000585 }
586 } else {
587 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
588 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000589 FieldDecl *FD = *i;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000590 QualType FT = FD->getType();
591
592 // FIXME: What are the right qualifiers here?
Eli Friedman7f1ff602012-04-16 03:54:45 +0000593 LValue SubLV = EmitLValueForField(LV, FD);
594 AI = ExpandTypeFromArgs(FT, SubLV, AI);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000595 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000596 }
597 } else if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
598 QualType EltTy = CT->getElementType();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000599 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Bob Wilsone826a2a2011-08-03 05:58:22 +0000600 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(RealAddr, EltTy));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000601 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Bob Wilsone826a2a2011-08-03 05:58:22 +0000602 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(ImagAddr, EltTy));
603 } else {
604 EmitStoreThroughLValue(RValue::get(AI), LV);
605 ++AI;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000606 }
607
608 return AI;
609}
610
Chris Lattner895c52b2010-06-27 06:04:18 +0000611/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000612/// accessing some number of bytes out of it, try to gep into the struct to get
613/// at its inner goodness. Dive as deep as possible without entering an element
614/// with an in-memory size smaller than DstSize.
615static llvm::Value *
Chris Lattner895c52b2010-06-27 06:04:18 +0000616EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000617 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000618 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000619 // We can't dive into a zero-element struct.
620 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000621
Chris Lattner2192fe52011-07-18 04:24:23 +0000622 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000623
Chris Lattner1cd66982010-06-27 05:56:15 +0000624 // If the first elt is at least as large as what we're looking for, or if the
625 // first element is the same size as the whole struct, we can enter it.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000626 uint64_t FirstEltSize =
Micah Villmowdd31ca12012-10-08 16:25:52 +0000627 CGF.CGM.getDataLayout().getTypeAllocSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000628 if (FirstEltSize < DstSize &&
Micah Villmowdd31ca12012-10-08 16:25:52 +0000629 FirstEltSize < CGF.CGM.getDataLayout().getTypeAllocSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000630 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000631
Chris Lattner1cd66982010-06-27 05:56:15 +0000632 // GEP into the first element.
633 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000634
Chris Lattner1cd66982010-06-27 05:56:15 +0000635 // If the first element is a struct, recurse.
Chris Lattner2192fe52011-07-18 04:24:23 +0000636 llvm::Type *SrcTy =
Chris Lattner1cd66982010-06-27 05:56:15 +0000637 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000638 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000639 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000640
641 return SrcPtr;
642}
643
Chris Lattner055097f2010-06-27 06:26:04 +0000644/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
645/// are either integers or pointers. This does a truncation of the value if it
646/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000647///
648/// This behaves as if the value were coerced through memory, so on big-endian
649/// targets the high bits are preserved in a truncation, while little-endian
650/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000651static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000652 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000653 CodeGenFunction &CGF) {
654 if (Val->getType() == Ty)
655 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000656
Chris Lattner055097f2010-06-27 06:26:04 +0000657 if (isa<llvm::PointerType>(Val->getType())) {
658 // If this is Pointer->Pointer avoid conversion to and from int.
659 if (isa<llvm::PointerType>(Ty))
660 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000661
Chris Lattner055097f2010-06-27 06:26:04 +0000662 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000663 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000664 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000665
Chris Lattner2192fe52011-07-18 04:24:23 +0000666 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000667 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000668 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000669
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000670 if (Val->getType() != DestIntTy) {
671 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
672 if (DL.isBigEndian()) {
673 // Preserve the high bits on big-endian targets.
674 // That is what memory coercion does.
675 uint64_t SrcSize = DL.getTypeAllocSizeInBits(Val->getType());
676 uint64_t DstSize = DL.getTypeAllocSizeInBits(DestIntTy);
677 if (SrcSize > DstSize) {
678 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
679 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
680 } else {
681 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
682 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
683 }
684 } else {
685 // Little-endian targets preserve the low bits. No shifts required.
686 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
687 }
688 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000689
Chris Lattner055097f2010-06-27 06:26:04 +0000690 if (isa<llvm::PointerType>(Ty))
691 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
692 return Val;
693}
694
Chris Lattner1cd66982010-06-27 05:56:15 +0000695
696
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000697/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
698/// a pointer to an object of type \arg Ty.
699///
700/// This safely handles the case when the src type is smaller than the
701/// destination type; in this situation the values of bits which not
702/// present in the src are undefined.
703static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000704 llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000705 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000706 llvm::Type *SrcTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000707 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000708
Chris Lattnerd200eda2010-06-28 22:51:39 +0000709 // If SrcTy and Ty are the same, just do a load.
710 if (SrcTy == Ty)
711 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000712
Micah Villmowdd31ca12012-10-08 16:25:52 +0000713 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000714
Chris Lattner2192fe52011-07-18 04:24:23 +0000715 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000716 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000717 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
718 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000719
Micah Villmowdd31ca12012-10-08 16:25:52 +0000720 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000721
Chris Lattner055097f2010-06-27 06:26:04 +0000722 // If the source and destination are integer or pointer types, just do an
723 // extension or truncation to the desired type.
724 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
725 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
726 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
727 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
728 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000729
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000730 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000731 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000732 // Generally SrcSize is never greater than DstSize, since this means we are
733 // losing bits. However, this can happen in cases where the structure has
734 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000735 //
Mike Stump18bb9282009-05-16 07:57:57 +0000736 // FIXME: Assert that we aren't truncating non-padding bits when have access
737 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000738 llvm::Value *Casted =
739 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000740 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
741 // FIXME: Use better alignment / avoid requiring aligned load.
742 Load->setAlignment(1);
743 return Load;
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000744 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000745
Chris Lattner3fcc7902010-06-27 01:06:27 +0000746 // Otherwise do coercion through memory. This is stupid, but
747 // simple.
748 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Ren84b921f2012-11-28 22:08:52 +0000749 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
750 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
751 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000752 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000753 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
754 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
755 1, false);
Chris Lattner3fcc7902010-06-27 01:06:27 +0000756 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000757}
758
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000759// Function to store a first-class aggregate into memory. We prefer to
760// store the elements rather than the aggregate to be more friendly to
761// fast-isel.
762// FIXME: Do we need to recurse here?
763static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
764 llvm::Value *DestPtr, bool DestIsVolatile,
765 bool LowAlignment) {
766 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +0000767 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000768 dyn_cast<llvm::StructType>(Val->getType())) {
769 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
770 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
771 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
772 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
773 DestIsVolatile);
774 if (LowAlignment)
775 SI->setAlignment(1);
776 }
777 } else {
Bill Wendlingf6af30f2012-03-16 21:45:12 +0000778 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
779 if (LowAlignment)
780 SI->setAlignment(1);
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000781 }
782}
783
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000784/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
785/// where the source and destination may have different types.
786///
787/// This safely handles the case when the src type is larger than the
788/// destination type; the upper bits of the src will be lost.
789static void CreateCoercedStore(llvm::Value *Src,
790 llvm::Value *DstPtr,
Anders Carlsson17490832009-12-24 20:40:36 +0000791 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000792 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000793 llvm::Type *SrcTy = Src->getType();
794 llvm::Type *DstTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000795 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +0000796 if (SrcTy == DstTy) {
797 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
798 return;
799 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000800
Micah Villmowdd31ca12012-10-08 16:25:52 +0000801 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000802
Chris Lattner2192fe52011-07-18 04:24:23 +0000803 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000804 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
805 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
806 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000807
Chris Lattner055097f2010-06-27 06:26:04 +0000808 // If the source and destination are integer or pointer types, just do an
809 // extension or truncation to the desired type.
810 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
811 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
812 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
813 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
814 return;
815 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000816
Micah Villmowdd31ca12012-10-08 16:25:52 +0000817 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000818
Daniel Dunbar313321e2009-02-03 05:31:23 +0000819 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000820 if (SrcSize <= DstSize) {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000821 llvm::Value *Casted =
822 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000823 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000824 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000825 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000826 // Otherwise do coercion through memory. This is stupid, but
827 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000828
829 // Generally SrcSize is never greater than DstSize, since this means we are
830 // losing bits. However, this can happen in cases where the structure has
831 // additional padding, for example due to a user specified alignment.
832 //
833 // FIXME: Assert that we aren't truncating non-padding bits when have access
834 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000835 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
836 CGF.Builder.CreateStore(Src, Tmp);
Manman Ren84b921f2012-11-28 22:08:52 +0000837 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
838 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
839 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000840 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000841 CGF.Builder.CreateMemCpy(DstCasted, Casted,
842 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
843 1, false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000844 }
845}
846
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000847/***/
848
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000849bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000850 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +0000851}
852
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000853bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
854 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
855 switch (BT->getKind()) {
856 default:
857 return false;
858 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +0000859 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000860 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +0000861 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000862 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +0000863 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000864 }
865 }
866
867 return false;
868}
869
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000870bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
871 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
872 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
873 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +0000874 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000875 }
876 }
877
878 return false;
879}
880
Chris Lattnera5f58b02011-07-09 17:41:47 +0000881llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +0000882 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
883 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +0000884}
885
Chris Lattnera5f58b02011-07-09 17:41:47 +0000886llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +0000887CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000888
889 bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted;
890 assert(Inserted && "Recursively being processed?");
891
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000892 SmallVector<llvm::Type*, 8> argTypes;
Chris Lattner2192fe52011-07-18 04:24:23 +0000893 llvm::Type *resultType = 0;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000894
John McCall85dd2c52011-05-15 02:19:42 +0000895 const ABIArgInfo &retAI = FI.getReturnInfo();
896 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +0000897 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +0000898 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +0000899
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000900 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +0000901 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +0000902 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +0000903 break;
904
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000905 case ABIArgInfo::Indirect: {
John McCall85dd2c52011-05-15 02:19:42 +0000906 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
907 resultType = llvm::Type::getVoidTy(getLLVMContext());
908
909 QualType ret = FI.getReturnType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000910 llvm::Type *ty = ConvertType(ret);
John McCall85dd2c52011-05-15 02:19:42 +0000911 unsigned addressSpace = Context.getTargetAddressSpace(ret);
912 argTypes.push_back(llvm::PointerType::get(ty, addressSpace));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000913 break;
914 }
915
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000916 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +0000917 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000918 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000919 }
Mike Stump11289f42009-09-09 15:08:12 +0000920
John McCallc818bbb2012-12-07 07:03:17 +0000921 // Add in all of the required arguments.
922 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), ie;
923 if (FI.isVariadic()) {
924 ie = it + FI.getRequiredArgs().getNumRequiredArgs();
925 } else {
926 ie = FI.arg_end();
927 }
928 for (; it != ie; ++it) {
John McCall85dd2c52011-05-15 02:19:42 +0000929 const ABIArgInfo &argAI = it->info;
Mike Stump11289f42009-09-09 15:08:12 +0000930
Rafael Espindolafad28de2012-10-24 01:59:00 +0000931 // Insert a padding type to ensure proper alignment.
932 if (llvm::Type *PaddingType = argAI.getPaddingType())
933 argTypes.push_back(PaddingType);
934
John McCall85dd2c52011-05-15 02:19:42 +0000935 switch (argAI.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000936 case ABIArgInfo::Ignore:
937 break;
938
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000939 case ABIArgInfo::Indirect: {
940 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +0000941 llvm::Type *LTy = ConvertTypeForMem(it->type);
John McCall85dd2c52011-05-15 02:19:42 +0000942 argTypes.push_back(LTy->getPointerTo());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000943 break;
944 }
945
946 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +0000947 case ABIArgInfo::Direct: {
Chris Lattner3dd716c2010-06-28 23:44:11 +0000948 // If the coerce-to type is a first class aggregate, flatten it. Either
949 // way is semantically identical, but fast-isel and the optimizer
950 // generally likes scalar values better than FCAs.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000951 llvm::Type *argType = argAI.getCoerceToType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000952 if (llvm::StructType *st = dyn_cast<llvm::StructType>(argType)) {
John McCall85dd2c52011-05-15 02:19:42 +0000953 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
954 argTypes.push_back(st->getElementType(i));
Chris Lattner3dd716c2010-06-28 23:44:11 +0000955 } else {
John McCall85dd2c52011-05-15 02:19:42 +0000956 argTypes.push_back(argType);
Chris Lattner3dd716c2010-06-28 23:44:11 +0000957 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +0000958 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +0000959 }
Mike Stump11289f42009-09-09 15:08:12 +0000960
Daniel Dunbard3674e62008-09-11 01:48:57 +0000961 case ABIArgInfo::Expand:
Chris Lattnera5f58b02011-07-09 17:41:47 +0000962 GetExpandedTypes(it->type, argTypes);
Daniel Dunbard3674e62008-09-11 01:48:57 +0000963 break;
964 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000965 }
966
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000967 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
968 assert(Erased && "Not in set?");
969
John McCalla729c622012-02-17 03:33:10 +0000970 return llvm::FunctionType::get(resultType, argTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +0000971}
972
Chris Lattner2192fe52011-07-18 04:24:23 +0000973llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +0000974 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +0000975 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000976
Chris Lattner8806e322011-07-10 00:18:59 +0000977 if (!isFuncTypeConvertible(FPT))
978 return llvm::StructType::get(getLLVMContext());
979
980 const CGFunctionInfo *Info;
981 if (isa<CXXDestructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +0000982 Info = &arrangeCXXDestructor(cast<CXXDestructorDecl>(MD), GD.getDtorType());
Chris Lattner8806e322011-07-10 00:18:59 +0000983 else
John McCalla729c622012-02-17 03:33:10 +0000984 Info = &arrangeCXXMethodDeclaration(MD);
985 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +0000986}
987
Daniel Dunbar3668cb22009-02-02 23:43:58 +0000988void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbard931a872009-02-02 22:03:45 +0000989 const Decl *TargetDecl,
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000990 AttributeListType &PAL,
Bill Wendlingf4d64cb2013-02-22 00:13:35 +0000991 unsigned &CallingConv,
992 bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +0000993 llvm::AttrBuilder FuncAttrs;
994 llvm::AttrBuilder RetAttrs;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +0000995
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000996 CallingConv = FI.getEffectiveCallingConvention();
997
John McCallab26cfa2010-02-05 21:31:56 +0000998 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +0000999 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001000
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001001 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001002 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001003 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001004 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001005 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001006 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001007 if (TargetDecl->hasAttr<NoReturnAttr>())
1008 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1009
1010 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCallbe349de2010-07-08 06:48:12 +00001011 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl31ad7542011-03-13 17:09:40 +00001012 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling207f0532012-12-20 19:27:06 +00001013 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith49af6292013-03-05 08:30:04 +00001014 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1015 // These attributes are not inherited by overloads.
1016 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1017 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001018 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001019 }
1020
Eric Christopherbf005ec2011-08-15 22:38:22 +00001021 // 'const' and 'pure' attribute functions are also nounwind.
1022 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001023 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1024 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001025 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001026 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1027 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001028 }
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001029 if (TargetDecl->hasAttr<MallocAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001030 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001031 }
1032
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001033 if (CodeGenOpts.OptimizeSize)
Bill Wendling207f0532012-12-20 19:27:06 +00001034 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
Quentin Colombet5ee5ca12012-10-26 00:29:48 +00001035 if (CodeGenOpts.OptimizeSize == 2)
Bill Wendling207f0532012-12-20 19:27:06 +00001036 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001037 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001038 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001039 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001040 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Devang Patel6e467b12009-06-04 23:32:02 +00001041
Bill Wendling2f81db62013-02-22 20:53:29 +00001042 if (AttrOnCallSite) {
1043 // Attributes that should go on the call site only.
1044 if (!CodeGenOpts.SimplifyLibCalls)
1045 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendling706469b2013-02-28 22:49:57 +00001046 } else {
1047 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001048 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001049 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001050 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001051 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001052 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001053 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001054 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001055 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001056 }
1057
Bill Wendlingdabafea2013-03-13 22:24:33 +00001058 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001059 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001060 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001061 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001062 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001063 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001064 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001065 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001066 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001067 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001068 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001069 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001070
Bill Wendlingd8f49502013-08-01 21:41:02 +00001071 if (!CodeGenOpts.StackRealignment)
1072 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendling985d1c52013-02-15 21:30:01 +00001073 }
1074
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001075 QualType RetTy = FI.getReturnType();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001076 unsigned Index = 1;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001077 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001078 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001079 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001080 if (RetTy->hasSignedIntegerRepresentation())
1081 RetAttrs.addAttribute(llvm::Attribute::SExt);
1082 else if (RetTy->hasUnsignedIntegerRepresentation())
1083 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001084 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001085 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001086 if (RetAI.getInReg())
1087 RetAttrs.addAttribute(llvm::Attribute::InReg);
1088 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001089 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001090 break;
1091
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001092 case ABIArgInfo::Indirect: {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001093 llvm::AttrBuilder SRETAttrs;
Bill Wendling207f0532012-12-20 19:27:06 +00001094 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001095 if (RetAI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001096 SRETAttrs.addAttribute(llvm::Attribute::InReg);
Bill Wendlinga7912f82012-10-10 07:36:56 +00001097 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001098 AttributeSet::get(getLLVMContext(), Index, SRETAttrs));
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001099
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001100 ++Index;
Daniel Dunbarc2304432009-03-18 19:51:01 +00001101 // sret disables readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001102 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1103 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001104 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001105 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001106
Daniel Dunbard3674e62008-09-11 01:48:57 +00001107 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001108 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001109 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001110
Bill Wendlinga7912f82012-10-10 07:36:56 +00001111 if (RetAttrs.hasAttributes())
1112 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001113 AttributeSet::get(getLLVMContext(),
1114 llvm::AttributeSet::ReturnIndex,
1115 RetAttrs));
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001116
Mike Stump11289f42009-09-09 15:08:12 +00001117 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
Daniel Dunbar313321e2009-02-03 05:31:23 +00001118 ie = FI.arg_end(); it != ie; ++it) {
1119 QualType ParamType = it->type;
1120 const ABIArgInfo &AI = it->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001121 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001122
Rafael Espindolafad28de2012-10-24 01:59:00 +00001123 if (AI.getPaddingType()) {
Bill Wendling290d9522013-01-27 02:46:53 +00001124 if (AI.getPaddingInReg())
1125 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index,
1126 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001127 // Increment Index if there is padding.
1128 ++Index;
1129 }
1130
John McCall39ec71f2010-03-27 00:47:27 +00001131 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1132 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001133 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001134 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001135 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001136 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001137 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001138 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001139 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001140 // FALL THROUGH
1141 case ABIArgInfo::Direct:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001142 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001143 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001144
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001145 // FIXME: handle sseregparm someday...
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001146
Chris Lattner2192fe52011-07-18 04:24:23 +00001147 if (llvm::StructType *STy =
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001148 dyn_cast<llvm::StructType>(AI.getCoerceToType())) {
1149 unsigned Extra = STy->getNumElements()-1; // 1 will be added below.
Bill Wendlinga7912f82012-10-10 07:36:56 +00001150 if (Attrs.hasAttributes())
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001151 for (unsigned I = 0; I < Extra; ++I)
Bill Wendling290d9522013-01-27 02:46:53 +00001152 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index + I,
1153 Attrs));
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001154 Index += Extra;
1155 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001156 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001157
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001158 case ABIArgInfo::Indirect:
Rafael Espindola703c47f2012-10-19 05:04:37 +00001159 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001160 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001161
Anders Carlsson20759ad2009-09-16 15:53:40 +00001162 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001163 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001164
Bill Wendlinga7912f82012-10-10 07:36:56 +00001165 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1166
Daniel Dunbarc2304432009-03-18 19:51:01 +00001167 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001168 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1169 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001170 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001171
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001172 case ABIArgInfo::Ignore:
1173 // Skip increment, no matching LLVM parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001174 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001175
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001176 case ABIArgInfo::Expand: {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001177 SmallVector<llvm::Type*, 8> types;
Mike Stump18bb9282009-05-16 07:57:57 +00001178 // FIXME: This is rather inefficient. Do we ever actually need to do
1179 // anything here? The result should be just reconstructed on the other
1180 // side, so extension should be a non-issue.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001181 getTypes().GetExpandedTypes(ParamType, types);
John McCall85dd2c52011-05-15 02:19:42 +00001182 Index += types.size();
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001183 continue;
1184 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001185 }
Mike Stump11289f42009-09-09 15:08:12 +00001186
Bill Wendlinga7912f82012-10-10 07:36:56 +00001187 if (Attrs.hasAttributes())
Bill Wendling290d9522013-01-27 02:46:53 +00001188 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index, Attrs));
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001189 ++Index;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001190 }
Bill Wendlinga7912f82012-10-10 07:36:56 +00001191 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001192 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001193 AttributeSet::get(getLLVMContext(),
1194 llvm::AttributeSet::FunctionIndex,
1195 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001196}
1197
John McCalla738c252011-03-09 04:27:21 +00001198/// An argument came in as a promoted argument; demote it back to its
1199/// declared type.
1200static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1201 const VarDecl *var,
1202 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001203 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001204
1205 // This can happen with promotions that actually don't change the
1206 // underlying type, like the enum promotions.
1207 if (value->getType() == varType) return value;
1208
1209 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1210 && "unexpected promotion type");
1211
1212 if (isa<llvm::IntegerType>(varType))
1213 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1214
1215 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1216}
1217
Daniel Dunbard931a872009-02-02 22:03:45 +00001218void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1219 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001220 const FunctionArgList &Args) {
John McCallcaa19452009-07-28 01:00:58 +00001221 // If this is an implicit-return-zero function, go ahead and
1222 // initialize the return value. TODO: it might be nice to have
1223 // a more general mechanism for this that didn't require synthesized
1224 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001225 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001226 if (FD->hasImplicitReturnZero()) {
1227 QualType RetTy = FD->getResultType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001228 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001229 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001230 Builder.CreateStore(Zero, ReturnValue);
1231 }
1232 }
1233
Mike Stump18bb9282009-05-16 07:57:57 +00001234 // FIXME: We no longer need the types from FunctionArgList; lift up and
1235 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001236
Daniel Dunbar613855c2008-09-09 23:27:19 +00001237 // Emit allocs for param decls. Give the LLVM Argument nodes names.
1238 llvm::Function::arg_iterator AI = Fn->arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00001239
Daniel Dunbar613855c2008-09-09 23:27:19 +00001240 // Name the struct return argument.
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001241 if (CGM.ReturnTypeUsesSRet(FI)) {
Daniel Dunbar613855c2008-09-09 23:27:19 +00001242 AI->setName("agg.result");
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001243 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1244 AI->getArgNo() + 1,
1245 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00001246 ++AI;
1247 }
Mike Stump11289f42009-09-09 15:08:12 +00001248
Reid Kleckner739756c2013-12-04 19:23:12 +00001249 // Create a pointer value for every parameter declaration. This usually
1250 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1251 // any cleanups or do anything that might unwind. We do that separately, so
1252 // we can push the cleanups in the correct order for the ABI.
1253 SmallVector<llvm::Value *, 16> ArgVals;
1254 ArgVals.reserve(Args.size());
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001255 assert(FI.arg_size() == Args.size() &&
1256 "Mismatch between function signature & arguments.");
Devang Patel68a15252011-03-03 20:13:15 +00001257 unsigned ArgNo = 1;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001258 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Devang Patel68a15252011-03-03 20:13:15 +00001259 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1260 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001261 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001262 QualType Ty = info_it->type;
1263 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001264
John McCalla738c252011-03-09 04:27:21 +00001265 bool isPromoted =
1266 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1267
Rafael Espindolafad28de2012-10-24 01:59:00 +00001268 // Skip the dummy padding argument.
1269 if (ArgI.getPaddingType())
1270 ++AI;
1271
Daniel Dunbard3674e62008-09-11 01:48:57 +00001272 switch (ArgI.getKind()) {
Daniel Dunbar747865a2009-02-05 09:16:39 +00001273 case ABIArgInfo::Indirect: {
Chris Lattner3dd716c2010-06-28 23:44:11 +00001274 llvm::Value *V = AI;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001275
John McCall47fb9502013-03-07 21:37:08 +00001276 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001277 // Aggregates and complex variables are accessed by reference. All we
1278 // need to do is realign the value, if requested
1279 if (ArgI.getIndirectRealign()) {
1280 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1281
1282 // Copy from the incoming argument pointer to the temporary with the
1283 // appropriate alignment.
1284 //
1285 // FIXME: We should have a common utility for generating an aggregate
1286 // copy.
Chris Lattner2192fe52011-07-18 04:24:23 +00001287 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyck705ba072011-01-19 01:58:38 +00001288 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumidd634362011-03-10 14:02:21 +00001289 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1290 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1291 Builder.CreateMemCpy(Dst,
1292 Src,
Ken Dyck705ba072011-01-19 01:58:38 +00001293 llvm::ConstantInt::get(IntPtrTy,
1294 Size.getQuantity()),
Benjamin Krameracc6b4e2010-12-30 00:13:21 +00001295 ArgI.getIndirectAlign(),
1296 false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001297 V = AlignedTemp;
1298 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001299 } else {
1300 // Load scalar value from indirect argument.
Ken Dyck705ba072011-01-19 01:58:38 +00001301 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001302 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1303 Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001304
1305 if (isPromoted)
1306 V = emitArgumentDemotion(*this, Arg, V);
Daniel Dunbar747865a2009-02-05 09:16:39 +00001307 }
Reid Kleckner739756c2013-12-04 19:23:12 +00001308 ArgVals.push_back(V);
Daniel Dunbar747865a2009-02-05 09:16:39 +00001309 break;
1310 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001311
1312 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001313 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001314
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001315 // If we have the trivial case, handle it with no muss and fuss.
1316 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001317 ArgI.getCoerceToType() == ConvertType(Ty) &&
1318 ArgI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001319 assert(AI != Fn->arg_end() && "Argument mismatch!");
1320 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001321
Bill Wendling507c3512012-10-16 05:23:44 +00001322 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001323 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1324 AI->getArgNo() + 1,
1325 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00001326
Chris Lattner7369c142011-07-20 06:29:00 +00001327 // Ensure the argument is the correct type.
1328 if (V->getType() != ArgI.getCoerceToType())
1329 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1330
John McCalla738c252011-03-09 04:27:21 +00001331 if (isPromoted)
1332 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00001333
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001334 if (const CXXMethodDecl *MD =
1335 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001336 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001337 V = CGM.getCXXABI().
1338 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001339 }
1340
Rafael Espindola8778c282012-11-29 16:09:03 +00001341 // Because of merging of function types from multiple decls it is
1342 // possible for the type of an argument to not match the corresponding
1343 // type in the function type. Since we are codegening the callee
1344 // in here, add a cast to the argument type.
1345 llvm::Type *LTy = ConvertType(Arg->getType());
1346 if (V->getType() != LTy)
1347 V = Builder.CreateBitCast(V, LTy);
1348
Reid Kleckner739756c2013-12-04 19:23:12 +00001349 ArgVals.push_back(V);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001350 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00001351 }
Mike Stump11289f42009-09-09 15:08:12 +00001352
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001353 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001354
Chris Lattnerff941a62010-07-28 18:24:28 +00001355 // The alignment we need to use is the max of the requested alignment for
1356 // the argument plus the alignment required by our access code below.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001357 unsigned AlignmentToUse =
Micah Villmowdd31ca12012-10-08 16:25:52 +00001358 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerff941a62010-07-28 18:24:28 +00001359 AlignmentToUse = std::max(AlignmentToUse,
1360 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001361
Chris Lattnerff941a62010-07-28 18:24:28 +00001362 Alloca->setAlignment(AlignmentToUse);
Chris Lattnerc401de92010-07-05 20:21:00 +00001363 llvm::Value *V = Alloca;
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001364 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001365
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001366 // If the value is offset in memory, apply the offset now.
1367 if (unsigned Offs = ArgI.getDirectOffset()) {
1368 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1369 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001370 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001371 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1372 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001373
Chris Lattner15ec3612010-06-29 00:06:42 +00001374 // If the coerce-to type is a first class aggregate, we flatten it and
1375 // pass the elements. Either way is semantically identical, but fast-isel
1376 // and the optimizer generally likes scalar values better than FCAs.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001377 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
1378 if (STy && STy->getNumElements() > 1) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001379 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001380 llvm::Type *DstTy =
1381 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00001382 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001383
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001384 if (SrcSize <= DstSize) {
1385 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1386
1387 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1388 assert(AI != Fn->arg_end() && "Argument mismatch!");
1389 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1390 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
1391 Builder.CreateStore(AI++, EltPtr);
1392 }
1393 } else {
1394 llvm::AllocaInst *TempAlloca =
1395 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1396 TempAlloca->setAlignment(AlignmentToUse);
1397 llvm::Value *TempV = TempAlloca;
1398
1399 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1400 assert(AI != Fn->arg_end() && "Argument mismatch!");
1401 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1402 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
1403 Builder.CreateStore(AI++, EltPtr);
1404 }
1405
1406 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner15ec3612010-06-29 00:06:42 +00001407 }
1408 } else {
1409 // Simple case, just do a coerced store of the argument into the alloca.
1410 assert(AI != Fn->arg_end() && "Argument mismatch!");
Chris Lattner9e748e92010-06-29 00:14:52 +00001411 AI->setName(Arg->getName() + ".coerce");
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001412 CreateCoercedStore(AI++, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00001413 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001414
1415
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001416 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00001417 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001418 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001419 if (isPromoted)
1420 V = emitArgumentDemotion(*this, Arg, V);
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00001421 }
Reid Kleckner739756c2013-12-04 19:23:12 +00001422 ArgVals.push_back(V);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001423 continue; // Skip ++AI increment, already done.
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001424 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001425
1426 case ABIArgInfo::Expand: {
1427 // If this structure was expanded into multiple arguments then
1428 // we need to create a temporary and reconstruct it from the
1429 // arguments.
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001430 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedmana0544d62011-12-03 04:14:32 +00001431 CharUnits Align = getContext().getDeclAlign(Arg);
1432 Alloca->setAlignment(Align.getQuantity());
1433 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001434 llvm::Function::arg_iterator End = ExpandTypeFromArgs(Ty, LV, AI);
Reid Kleckner739756c2013-12-04 19:23:12 +00001435 ArgVals.push_back(Alloca);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001436
1437 // Name the arguments used in expansion and increment AI.
1438 unsigned Index = 0;
1439 for (; AI != End; ++AI, ++Index)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001440 AI->setName(Arg->getName() + "." + Twine(Index));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001441 continue;
1442 }
1443
1444 case ABIArgInfo::Ignore:
1445 // Initialize the local variable appropriately.
John McCall47fb9502013-03-07 21:37:08 +00001446 if (!hasScalarEvaluationKind(Ty))
Reid Kleckner739756c2013-12-04 19:23:12 +00001447 ArgVals.push_back(CreateMemTemp(Ty));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001448 else
Reid Kleckner739756c2013-12-04 19:23:12 +00001449 ArgVals.push_back(llvm::UndefValue::get(ConvertType(Arg->getType())));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001450
1451 // Skip increment, no matching LLVM parameter.
1452 continue;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001453 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001454
1455 ++AI;
Daniel Dunbar613855c2008-09-09 23:27:19 +00001456 }
1457 assert(AI == Fn->arg_end() && "Argument mismatch!");
Reid Kleckner739756c2013-12-04 19:23:12 +00001458
1459 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1460 for (int I = Args.size() - 1; I >= 0; --I)
1461 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
1462 } else {
1463 for (unsigned I = 0, E = Args.size(); I != E; ++I)
1464 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
1465 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001466}
1467
John McCallffa2c1a2012-01-29 07:46:59 +00001468static void eraseUnusedBitCasts(llvm::Instruction *insn) {
1469 while (insn->use_empty()) {
1470 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
1471 if (!bitcast) return;
1472
1473 // This is "safe" because we would have used a ConstantExpr otherwise.
1474 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
1475 bitcast->eraseFromParent();
1476 }
1477}
1478
John McCall31168b02011-06-15 23:02:42 +00001479/// Try to emit a fused autorelease of a return result.
1480static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1481 llvm::Value *result) {
1482 // We must be immediately followed the cast.
1483 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
1484 if (BB->empty()) return 0;
1485 if (&BB->back() != result) return 0;
1486
Chris Lattner2192fe52011-07-18 04:24:23 +00001487 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00001488
1489 // result is in a BasicBlock and is therefore an Instruction.
1490 llvm::Instruction *generator = cast<llvm::Instruction>(result);
1491
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001492 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00001493
1494 // Look for:
1495 // %generator = bitcast %type1* %generator2 to %type2*
1496 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1497 // We would have emitted this as a constant if the operand weren't
1498 // an Instruction.
1499 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1500
1501 // Require the generator to be immediately followed by the cast.
1502 if (generator->getNextNode() != bitcast)
1503 return 0;
1504
1505 insnsToKill.push_back(bitcast);
1506 }
1507
1508 // Look for:
1509 // %generator = call i8* @objc_retain(i8* %originalResult)
1510 // or
1511 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
1512 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
1513 if (!call) return 0;
1514
1515 bool doRetainAutorelease;
1516
1517 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
1518 doRetainAutorelease = true;
1519 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
1520 .objc_retainAutoreleasedReturnValue) {
1521 doRetainAutorelease = false;
1522
John McCallcfa4e9b2012-09-07 23:30:50 +00001523 // If we emitted an assembly marker for this call (and the
1524 // ARCEntrypoints field should have been set if so), go looking
1525 // for that call. If we can't find it, we can't do this
1526 // optimization. But it should always be the immediately previous
1527 // instruction, unless we needed bitcasts around the call.
1528 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
1529 llvm::Instruction *prev = call->getPrevNode();
1530 assert(prev);
1531 if (isa<llvm::BitCastInst>(prev)) {
1532 prev = prev->getPrevNode();
1533 assert(prev);
1534 }
1535 assert(isa<llvm::CallInst>(prev));
1536 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
1537 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
1538 insnsToKill.push_back(prev);
1539 }
John McCall31168b02011-06-15 23:02:42 +00001540 } else {
1541 return 0;
1542 }
1543
1544 result = call->getArgOperand(0);
1545 insnsToKill.push_back(call);
1546
1547 // Keep killing bitcasts, for sanity. Note that we no longer care
1548 // about precise ordering as long as there's exactly one use.
1549 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
1550 if (!bitcast->hasOneUse()) break;
1551 insnsToKill.push_back(bitcast);
1552 result = bitcast->getOperand(0);
1553 }
1554
1555 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001556 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00001557 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
1558 (*i)->eraseFromParent();
1559
1560 // Do the fused retain/autorelease if we were asked to.
1561 if (doRetainAutorelease)
1562 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
1563
1564 // Cast back to the result type.
1565 return CGF.Builder.CreateBitCast(result, resultType);
1566}
1567
John McCallffa2c1a2012-01-29 07:46:59 +00001568/// If this is a +1 of the value of an immutable 'self', remove it.
1569static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
1570 llvm::Value *result) {
1571 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00001572 const ObjCMethodDecl *method =
1573 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCallffa2c1a2012-01-29 07:46:59 +00001574 if (!method) return 0;
1575 const VarDecl *self = method->getSelfDecl();
1576 if (!self->getType().isConstQualified()) return 0;
1577
1578 // Look for a retain call.
1579 llvm::CallInst *retainCall =
1580 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
1581 if (!retainCall ||
1582 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
1583 return 0;
1584
1585 // Look for an ordinary load of 'self'.
1586 llvm::Value *retainedValue = retainCall->getArgOperand(0);
1587 llvm::LoadInst *load =
1588 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
1589 if (!load || load->isAtomic() || load->isVolatile() ||
1590 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
1591 return 0;
1592
1593 // Okay! Burn it all down. This relies for correctness on the
1594 // assumption that the retain is emitted as part of the return and
1595 // that thereafter everything is used "linearly".
1596 llvm::Type *resultType = result->getType();
1597 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
1598 assert(retainCall->use_empty());
1599 retainCall->eraseFromParent();
1600 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
1601
1602 return CGF.Builder.CreateBitCast(load, resultType);
1603}
1604
John McCall31168b02011-06-15 23:02:42 +00001605/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00001606///
1607/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00001608static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
1609 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00001610 // If we're returning 'self', kill the initial retain. This is a
1611 // heuristic attempt to "encourage correctness" in the really unfortunate
1612 // case where we have a return of self during a dealloc and we desperately
1613 // need to avoid the possible autorelease.
1614 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
1615 return self;
1616
John McCall31168b02011-06-15 23:02:42 +00001617 // At -O0, try to emit a fused retain/autorelease.
1618 if (CGF.shouldUseFusedARCCalls())
1619 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
1620 return fused;
1621
1622 return CGF.EmitARCAutoreleaseReturnValue(result);
1623}
1624
John McCall6e1c0122012-01-29 02:35:02 +00001625/// Heuristically search for a dominating store to the return-value slot.
1626static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
1627 // If there are multiple uses of the return-value slot, just check
1628 // for something immediately preceding the IP. Sometimes this can
1629 // happen with how we generate implicit-returns; it can also happen
1630 // with noreturn cleanups.
1631 if (!CGF.ReturnValue->hasOneUse()) {
1632 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1633 if (IP->empty()) return 0;
1634 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
1635 if (!store) return 0;
1636 if (store->getPointerOperand() != CGF.ReturnValue) return 0;
1637 assert(!store->isAtomic() && !store->isVolatile()); // see below
1638 return store;
1639 }
1640
1641 llvm::StoreInst *store =
1642 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->use_back());
1643 if (!store) return 0;
1644
1645 // These aren't actually possible for non-coerced returns, and we
1646 // only care about non-coerced returns on this code path.
1647 assert(!store->isAtomic() && !store->isVolatile());
1648
1649 // Now do a first-and-dirty dominance check: just walk up the
1650 // single-predecessors chain from the current insertion point.
1651 llvm::BasicBlock *StoreBB = store->getParent();
1652 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1653 while (IP != StoreBB) {
1654 if (!(IP = IP->getSinglePredecessor()))
1655 return 0;
1656 }
1657
1658 // Okay, the store's basic block dominates the insertion point; we
1659 // can do our thing.
1660 return store;
1661}
1662
Adrian Prantl3be10542013-05-02 17:30:20 +00001663void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001664 bool EmitRetDbgLoc,
1665 SourceLocation EndLoc) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001666 // Functions with no result always return void.
Chris Lattner726b3d02010-06-26 23:13:19 +00001667 if (ReturnValue == 0) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001668 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00001669 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001670 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00001671
Dan Gohman481e40c2010-07-20 20:13:52 +00001672 llvm::DebugLoc RetDbgLoc;
Chris Lattner726b3d02010-06-26 23:13:19 +00001673 llvm::Value *RV = 0;
1674 QualType RetTy = FI.getReturnType();
1675 const ABIArgInfo &RetAI = FI.getReturnInfo();
1676
1677 switch (RetAI.getKind()) {
Daniel Dunbar03816342010-08-21 02:24:36 +00001678 case ABIArgInfo::Indirect: {
John McCall47fb9502013-03-07 21:37:08 +00001679 switch (getEvaluationKind(RetTy)) {
1680 case TEK_Complex: {
1681 ComplexPairTy RT =
Nick Lewycky2d84e842013-10-02 02:29:49 +00001682 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
1683 EndLoc);
John McCall47fb9502013-03-07 21:37:08 +00001684 EmitStoreOfComplex(RT,
1685 MakeNaturalAlignAddrLValue(CurFn->arg_begin(), RetTy),
1686 /*isInit*/ true);
1687 break;
1688 }
1689 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00001690 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00001691 break;
1692 case TEK_Scalar:
1693 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
1694 MakeNaturalAlignAddrLValue(CurFn->arg_begin(), RetTy),
1695 /*isInit*/ true);
1696 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00001697 }
1698 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00001699 }
Chris Lattner726b3d02010-06-26 23:13:19 +00001700
1701 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001702 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001703 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
1704 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001705 // The internal return value temp always will have pointer-to-return-type
1706 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001707
John McCall6e1c0122012-01-29 02:35:02 +00001708 // If there is a dominating store to ReturnValue, we can elide
1709 // the load, zap the store, and usually zap the alloca.
1710 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00001711 // Reuse the debug location from the store unless there is
1712 // cleanup code to be emitted between the store and return
1713 // instruction.
1714 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00001715 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001716 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001717 RV = SI->getValueOperand();
1718 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001719
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001720 // If that was the only use of the return value, nuke it as well now.
1721 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
1722 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
1723 ReturnValue = 0;
1724 }
John McCall6e1c0122012-01-29 02:35:02 +00001725
1726 // Otherwise, we have to do a simple load.
1727 } else {
1728 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00001729 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001730 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001731 llvm::Value *V = ReturnValue;
1732 // If the value is offset in memory, apply the offset now.
1733 if (unsigned Offs = RetAI.getDirectOffset()) {
1734 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
1735 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001736 V = Builder.CreateBitCast(V,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001737 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
1738 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001739
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001740 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00001741 }
John McCall31168b02011-06-15 23:02:42 +00001742
1743 // In ARC, end functions that return a retainable type with a call
1744 // to objc_autoreleaseReturnValue.
1745 if (AutoreleaseResult) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001746 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001747 !FI.isReturnsRetained() &&
1748 RetTy->isObjCRetainableType());
1749 RV = emitAutoreleaseOfResult(*this, RV);
1750 }
1751
Chris Lattner726b3d02010-06-26 23:13:19 +00001752 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00001753
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001754 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00001755 break;
1756
1757 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001758 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00001759 }
1760
Daniel Dunbar6696e222010-06-30 21:27:58 +00001761 llvm::Instruction *Ret = RV ? Builder.CreateRet(RV) : Builder.CreateRetVoid();
Devang Patel65497582010-07-21 18:08:50 +00001762 if (!RetDbgLoc.isUnknown())
1763 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar613855c2008-09-09 23:27:19 +00001764}
1765
John McCall32ea9692011-03-11 20:59:21 +00001766void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001767 const VarDecl *param,
1768 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00001769 // StartFunction converted the ABI-lowered parameter(s) into a
1770 // local alloca. We need to turn that into an r-value suitable
1771 // for EmitCall.
John McCall32ea9692011-03-11 20:59:21 +00001772 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00001773
John McCall32ea9692011-03-11 20:59:21 +00001774 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001775
John McCall23f66262010-05-26 22:34:26 +00001776 // For the most part, we just need to load the alloca, except:
1777 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00001778 // 2) references to non-scalars are pointers directly to the aggregate.
1779 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00001780 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00001781 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00001782 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00001783
1784 // Locals which are references to scalars are represented
1785 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00001786 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00001787 }
1788
Nick Lewycky2d84e842013-10-02 02:29:49 +00001789 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00001790}
1791
John McCall31168b02011-06-15 23:02:42 +00001792static bool isProvablyNull(llvm::Value *addr) {
1793 return isa<llvm::ConstantPointerNull>(addr);
1794}
1795
1796static bool isProvablyNonNull(llvm::Value *addr) {
1797 return isa<llvm::AllocaInst>(addr);
1798}
1799
1800/// Emit the actual writing-back of a writeback.
1801static void emitWriteback(CodeGenFunction &CGF,
1802 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00001803 const LValue &srcLV = writeback.Source;
1804 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00001805 assert(!isProvablyNull(srcAddr) &&
1806 "shouldn't have writeback for provably null argument");
1807
1808 llvm::BasicBlock *contBB = 0;
1809
1810 // If the argument wasn't provably non-null, we need to null check
1811 // before doing the store.
1812 bool provablyNonNull = isProvablyNonNull(srcAddr);
1813 if (!provablyNonNull) {
1814 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
1815 contBB = CGF.createBasicBlock("icr.done");
1816
1817 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1818 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
1819 CGF.EmitBlock(writebackBB);
1820 }
1821
1822 // Load the value to writeback.
1823 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
1824
1825 // Cast it back, in case we're writing an id to a Foo* or something.
1826 value = CGF.Builder.CreateBitCast(value,
1827 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
1828 "icr.writeback-cast");
1829
1830 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00001831
1832 // If we have a "to use" value, it's something we need to emit a use
1833 // of. This has to be carefully threaded in: if it's done after the
1834 // release it's potentially undefined behavior (and the optimizer
1835 // will ignore it), and if it happens before the retain then the
1836 // optimizer could move the release there.
1837 if (writeback.ToUse) {
1838 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
1839
1840 // Retain the new value. No need to block-copy here: the block's
1841 // being passed up the stack.
1842 value = CGF.EmitARCRetainNonBlock(value);
1843
1844 // Emit the intrinsic use here.
1845 CGF.EmitARCIntrinsicUse(writeback.ToUse);
1846
1847 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00001848 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00001849
1850 // Put the new value in place (primitively).
1851 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
1852
1853 // Release the old value.
1854 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
1855
1856 // Otherwise, we can just do a normal lvalue store.
1857 } else {
1858 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
1859 }
John McCall31168b02011-06-15 23:02:42 +00001860
1861 // Jump to the continuation block.
1862 if (!provablyNonNull)
1863 CGF.EmitBlock(contBB);
1864}
1865
1866static void emitWritebacks(CodeGenFunction &CGF,
1867 const CallArgList &args) {
1868 for (CallArgList::writeback_iterator
1869 i = args.writeback_begin(), e = args.writeback_end(); i != e; ++i)
1870 emitWriteback(CGF, *i);
1871}
1872
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001873static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
1874 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00001875 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001876 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
1877 CallArgs.getCleanupsToDeactivate();
1878 // Iterate in reverse to increase the likelihood of popping the cleanup.
1879 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
1880 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
1881 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
1882 I->IsActiveIP->eraseFromParent();
1883 }
1884}
1885
John McCalleff18842013-03-23 02:35:54 +00001886static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
1887 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
1888 if (uop->getOpcode() == UO_AddrOf)
1889 return uop->getSubExpr();
1890 return 0;
1891}
1892
John McCall31168b02011-06-15 23:02:42 +00001893/// Emit an argument that's being passed call-by-writeback. That is,
1894/// we are passing the address of
1895static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
1896 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00001897 LValue srcLV;
1898
1899 // Make an optimistic effort to emit the address as an l-value.
1900 // This can fail if the the argument expression is more complicated.
1901 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
1902 srcLV = CGF.EmitLValue(lvExpr);
1903
1904 // Otherwise, just emit it as a scalar.
1905 } else {
1906 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
1907
1908 QualType srcAddrType =
1909 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
1910 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
1911 }
1912 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00001913
1914 // The dest and src types don't necessarily match in LLVM terms
1915 // because of the crazy ObjC compatibility rules.
1916
Chris Lattner2192fe52011-07-18 04:24:23 +00001917 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00001918 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
1919
1920 // If the address is a constant null, just pass the appropriate null.
1921 if (isProvablyNull(srcAddr)) {
1922 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
1923 CRE->getType());
1924 return;
1925 }
1926
John McCall31168b02011-06-15 23:02:42 +00001927 // Create the temporary.
1928 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
1929 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001930 // Loading an l-value can introduce a cleanup if the l-value is __weak,
1931 // and that cleanup will be conditional if we can't prove that the l-value
1932 // isn't null, so we need to register a dominating point so that the cleanups
1933 // system will make valid IR.
1934 CodeGenFunction::ConditionalEvaluation condEval(CGF);
1935
John McCall31168b02011-06-15 23:02:42 +00001936 // Zero-initialize it if we're not doing a copy-initialization.
1937 bool shouldCopy = CRE->shouldCopy();
1938 if (!shouldCopy) {
1939 llvm::Value *null =
1940 llvm::ConstantPointerNull::get(
1941 cast<llvm::PointerType>(destType->getElementType()));
1942 CGF.Builder.CreateStore(null, temp);
1943 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001944
John McCall31168b02011-06-15 23:02:42 +00001945 llvm::BasicBlock *contBB = 0;
John McCalleff18842013-03-23 02:35:54 +00001946 llvm::BasicBlock *originBB = 0;
John McCall31168b02011-06-15 23:02:42 +00001947
1948 // If the address is *not* known to be non-null, we need to switch.
1949 llvm::Value *finalArgument;
1950
1951 bool provablyNonNull = isProvablyNonNull(srcAddr);
1952 if (provablyNonNull) {
1953 finalArgument = temp;
1954 } else {
1955 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1956
1957 finalArgument = CGF.Builder.CreateSelect(isNull,
1958 llvm::ConstantPointerNull::get(destType),
1959 temp, "icr.argument");
1960
1961 // If we need to copy, then the load has to be conditional, which
1962 // means we need control flow.
1963 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00001964 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00001965 contBB = CGF.createBasicBlock("icr.cont");
1966 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
1967 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
1968 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001969 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00001970 }
1971 }
1972
John McCalleff18842013-03-23 02:35:54 +00001973 llvm::Value *valueToUse = 0;
1974
John McCall31168b02011-06-15 23:02:42 +00001975 // Perform a copy if necessary.
1976 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001977 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00001978 assert(srcRV.isScalar());
1979
1980 llvm::Value *src = srcRV.getScalarVal();
1981 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
1982 "icr.cast");
1983
1984 // Use an ordinary store, not a store-to-lvalue.
1985 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00001986
1987 // If optimization is enabled, and the value was held in a
1988 // __strong variable, we need to tell the optimizer that this
1989 // value has to stay alive until we're doing the store back.
1990 // This is because the temporary is effectively unretained,
1991 // and so otherwise we can violate the high-level semantics.
1992 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
1993 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
1994 valueToUse = src;
1995 }
John McCall31168b02011-06-15 23:02:42 +00001996 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001997
John McCall31168b02011-06-15 23:02:42 +00001998 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001999 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00002000 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002001 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00002002
2003 // Make a phi for the value to intrinsically use.
2004 if (valueToUse) {
2005 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2006 "icr.to-use");
2007 phiToUse->addIncoming(valueToUse, copyBB);
2008 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2009 originBB);
2010 valueToUse = phiToUse;
2011 }
2012
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002013 condEval.end(CGF);
2014 }
John McCall31168b02011-06-15 23:02:42 +00002015
John McCalleff18842013-03-23 02:35:54 +00002016 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002017 args.add(RValue::get(finalArgument), CRE->getType());
2018}
2019
Reid Kleckner739756c2013-12-04 19:23:12 +00002020void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2021 ArrayRef<QualType> ArgTypes,
2022 CallExpr::const_arg_iterator ArgBeg,
2023 CallExpr::const_arg_iterator ArgEnd,
2024 bool ForceColumnInfo) {
2025 CGDebugInfo *DI = getDebugInfo();
2026 SourceLocation CallLoc;
2027 if (DI) CallLoc = DI->getLocation();
2028
2029 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2030 // because arguments are destroyed left to right in the callee.
2031 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2032 size_t CallArgsStart = Args.size();
2033 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2034 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2035 EmitCallArg(Args, *Arg, ArgTypes[I]);
2036 // Restore the debug location.
2037 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2038 }
2039
2040 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2041 // IR function.
2042 std::reverse(Args.begin() + CallArgsStart, Args.end());
2043 return;
2044 }
2045
2046 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2047 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2048 assert(Arg != ArgEnd);
2049 EmitCallArg(Args, *Arg, ArgTypes[I]);
2050 // Restore the debug location.
2051 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2052 }
2053}
2054
John McCall32ea9692011-03-11 20:59:21 +00002055void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2056 QualType type) {
John McCall31168b02011-06-15 23:02:42 +00002057 if (const ObjCIndirectCopyRestoreExpr *CRE
2058 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002059 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002060 assert(getContext().hasSameType(E->getType(), type));
2061 return emitWritebackArg(*this, args, CRE);
2062 }
2063
John McCall0a76c0c2011-08-26 18:42:59 +00002064 assert(type->isReferenceType() == E->isGLValue() &&
2065 "reference binding to unmaterialized r-value!");
2066
John McCall17054bd62011-08-26 21:08:13 +00002067 if (E->isGLValue()) {
2068 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002069 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002070 }
Mike Stump11289f42009-09-09 15:08:12 +00002071
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002072 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2073
2074 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2075 // However, we still have to push an EH-only cleanup in case we unwind before
2076 // we make it to the call.
2077 if (HasAggregateEvalKind &&
Reid Kleckner739756c2013-12-04 19:23:12 +00002078 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002079 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2080 if (RD && RD->hasNonTrivialDestructor()) {
2081 AggValueSlot Slot = CreateAggTemp(type, "agg.arg.tmp");
2082 Slot.setExternallyDestructed();
2083 EmitAggExpr(E, Slot);
2084 RValue RV = Slot.asRValue();
2085 args.add(RV, type);
2086
2087 pushDestroy(EHCleanup, RV.getAggregateAddr(), type, destroyCXXObject,
2088 /*useEHCleanupForArray*/ true);
2089 // This unreachable is a temporary marker which will be removed later.
2090 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2091 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
2092 return;
2093 }
2094 }
2095
2096 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00002097 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2098 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2099 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00002100 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2101 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2102 } else {
2103 // We can't represent a misaligned lvalue in the CallArgList, so copy
2104 // to an aligned temporary now.
2105 llvm::Value *tmp = CreateMemTemp(type);
2106 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2107 L.getAlignment());
2108 args.add(RValue::getAggregate(tmp), type);
2109 }
Eli Friedmandf968192011-05-26 00:10:27 +00002110 return;
2111 }
2112
John McCall32ea9692011-03-11 20:59:21 +00002113 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00002114}
2115
Dan Gohman515a60d2012-02-16 00:57:37 +00002116// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2117// optimizer it can aggressively ignore unwind edges.
2118void
2119CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2120 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2121 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2122 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2123 CGM.getNoObjCARCExceptionsMetadata());
2124}
2125
John McCall882987f2013-02-28 19:01:20 +00002126/// Emits a call to the given no-arguments nounwind runtime function.
2127llvm::CallInst *
2128CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2129 const llvm::Twine &name) {
2130 return EmitNounwindRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2131}
2132
2133/// Emits a call to the given nounwind runtime function.
2134llvm::CallInst *
2135CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2136 ArrayRef<llvm::Value*> args,
2137 const llvm::Twine &name) {
2138 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2139 call->setDoesNotThrow();
2140 return call;
2141}
2142
2143/// Emits a simple call (never an invoke) to the given no-arguments
2144/// runtime function.
2145llvm::CallInst *
2146CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2147 const llvm::Twine &name) {
2148 return EmitRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2149}
2150
2151/// Emits a simple call (never an invoke) to the given runtime
2152/// function.
2153llvm::CallInst *
2154CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2155 ArrayRef<llvm::Value*> args,
2156 const llvm::Twine &name) {
2157 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2158 call->setCallingConv(getRuntimeCC());
2159 return call;
2160}
2161
2162/// Emits a call or invoke to the given noreturn runtime function.
2163void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2164 ArrayRef<llvm::Value*> args) {
2165 if (getInvokeDest()) {
2166 llvm::InvokeInst *invoke =
2167 Builder.CreateInvoke(callee,
2168 getUnreachableBlock(),
2169 getInvokeDest(),
2170 args);
2171 invoke->setDoesNotReturn();
2172 invoke->setCallingConv(getRuntimeCC());
2173 } else {
2174 llvm::CallInst *call = Builder.CreateCall(callee, args);
2175 call->setDoesNotReturn();
2176 call->setCallingConv(getRuntimeCC());
2177 Builder.CreateUnreachable();
2178 }
2179}
2180
2181/// Emits a call or invoke instruction to the given nullary runtime
2182/// function.
2183llvm::CallSite
2184CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2185 const Twine &name) {
2186 return EmitRuntimeCallOrInvoke(callee, ArrayRef<llvm::Value*>(), name);
2187}
2188
2189/// Emits a call or invoke instruction to the given runtime function.
2190llvm::CallSite
2191CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2192 ArrayRef<llvm::Value*> args,
2193 const Twine &name) {
2194 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2195 callSite.setCallingConv(getRuntimeCC());
2196 return callSite;
2197}
2198
2199llvm::CallSite
2200CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2201 const Twine &Name) {
2202 return EmitCallOrInvoke(Callee, ArrayRef<llvm::Value *>(), Name);
2203}
2204
John McCallbd309292010-07-06 01:34:17 +00002205/// Emits a call or invoke instruction to the given function, depending
2206/// on the current state of the EH stack.
2207llvm::CallSite
2208CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00002209 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002210 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00002211 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00002212
Dan Gohman515a60d2012-02-16 00:57:37 +00002213 llvm::Instruction *Inst;
2214 if (!InvokeDest)
2215 Inst = Builder.CreateCall(Callee, Args, Name);
2216 else {
2217 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2218 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2219 EmitBlock(ContBB);
2220 }
2221
2222 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2223 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002224 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002225 AddObjCARCExceptionMetadata(Inst);
2226
2227 return Inst;
John McCallbd309292010-07-06 01:34:17 +00002228}
2229
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002230static void checkArgMatches(llvm::Value *Elt, unsigned &ArgNo,
2231 llvm::FunctionType *FTy) {
2232 if (ArgNo < FTy->getNumParams())
2233 assert(Elt->getType() == FTy->getParamType(ArgNo));
2234 else
2235 assert(FTy->isVarArg());
2236 ++ArgNo;
2237}
2238
Chris Lattnerd59d8672011-07-12 06:29:11 +00002239void CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
Craig Topper5603df42013-07-05 19:34:19 +00002240 SmallVectorImpl<llvm::Value *> &Args,
Chris Lattnerd59d8672011-07-12 06:29:11 +00002241 llvm::FunctionType *IRFuncTy) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002242 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2243 unsigned NumElts = AT->getSize().getZExtValue();
2244 QualType EltTy = AT->getElementType();
2245 llvm::Value *Addr = RV.getAggregateAddr();
2246 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
2247 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, Elt);
Nick Lewycky2d84e842013-10-02 02:29:49 +00002248 RValue EltRV = convertTempToRValue(EltAddr, EltTy, SourceLocation());
Bob Wilsone826a2a2011-08-03 05:58:22 +00002249 ExpandTypeToArgs(EltTy, EltRV, Args, IRFuncTy);
Chris Lattnerd59d8672011-07-12 06:29:11 +00002250 }
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002251 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002252 RecordDecl *RD = RT->getDecl();
2253 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
Eli Friedman7f1ff602012-04-16 03:54:45 +00002254 LValue LV = MakeAddrLValue(RV.getAggregateAddr(), Ty);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002255
2256 if (RD->isUnion()) {
2257 const FieldDecl *LargestFD = 0;
2258 CharUnits UnionSize = CharUnits::Zero();
2259
2260 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2261 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00002262 const FieldDecl *FD = *i;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002263 assert(!FD->isBitField() &&
2264 "Cannot expand structure with bit-field members.");
2265 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
2266 if (UnionSize < FieldSize) {
2267 UnionSize = FieldSize;
2268 LargestFD = FD;
2269 }
2270 }
2271 if (LargestFD) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002272 RValue FldRV = EmitRValueForField(LV, LargestFD, SourceLocation());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002273 ExpandTypeToArgs(LargestFD->getType(), FldRV, Args, IRFuncTy);
2274 }
2275 } else {
2276 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2277 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00002278 FieldDecl *FD = *i;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002279
Nick Lewycky2d84e842013-10-02 02:29:49 +00002280 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002281 ExpandTypeToArgs(FD->getType(), FldRV, Args, IRFuncTy);
2282 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00002283 }
Eli Friedman95ff7002011-11-15 02:46:03 +00002284 } else if (Ty->isAnyComplexType()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002285 ComplexPairTy CV = RV.getComplexVal();
2286 Args.push_back(CV.first);
2287 Args.push_back(CV.second);
2288 } else {
Chris Lattnerd59d8672011-07-12 06:29:11 +00002289 assert(RV.isScalar() &&
2290 "Unexpected non-scalar rvalue during struct expansion.");
2291
2292 // Insert a bitcast as needed.
2293 llvm::Value *V = RV.getScalarVal();
2294 if (Args.size() < IRFuncTy->getNumParams() &&
2295 V->getType() != IRFuncTy->getParamType(Args.size()))
2296 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(Args.size()));
2297
2298 Args.push_back(V);
2299 }
2300}
2301
2302
Daniel Dunbard931a872009-02-02 22:03:45 +00002303RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00002304 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00002305 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002306 const CallArgList &CallArgs,
David Chisnall9eecafa2010-05-01 11:15:56 +00002307 const Decl *TargetDecl,
David Chisnallff5f88c2010-05-02 13:41:58 +00002308 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00002309 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002310 SmallVector<llvm::Value*, 16> Args;
Daniel Dunbar613855c2008-09-09 23:27:19 +00002311
2312 // Handle struct-return functions by passing a pointer to the
2313 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00002314 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002315 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002316
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002317 // IRArgNo - Keep track of the argument number in the callee we're looking at.
2318 unsigned IRArgNo = 0;
2319 llvm::FunctionType *IRFuncTy =
2320 cast<llvm::FunctionType>(
2321 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00002322
Chris Lattner4ca97c32009-06-13 00:26:38 +00002323 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00002324 // alloca to hold the result, unless one is given to us.
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00002325 if (CGM.ReturnTypeUsesSRet(CallInfo)) {
Anders Carlsson17490832009-12-24 20:40:36 +00002326 llvm::Value *Value = ReturnValue.getValue();
2327 if (!Value)
Daniel Dunbara7566f12010-02-09 02:48:28 +00002328 Value = CreateMemTemp(RetTy);
Anders Carlsson17490832009-12-24 20:40:36 +00002329 Args.push_back(Value);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002330 checkArgMatches(Value, IRArgNo, IRFuncTy);
Anders Carlsson17490832009-12-24 20:40:36 +00002331 }
Mike Stump11289f42009-09-09 15:08:12 +00002332
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002333 assert(CallInfo.arg_size() == CallArgs.size() &&
2334 "Mismatch between function signature & arguments.");
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002335 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002336 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002337 I != E; ++I, ++info_it) {
2338 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002339 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002340
John McCall47fb9502013-03-07 21:37:08 +00002341 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002342
2343 // Insert a padding argument to ensure proper alignment.
2344 if (llvm::Type *PaddingType = ArgInfo.getPaddingType()) {
2345 Args.push_back(llvm::UndefValue::get(PaddingType));
2346 ++IRArgNo;
2347 }
2348
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002349 switch (ArgInfo.getKind()) {
Daniel Dunbar03816342010-08-21 02:24:36 +00002350 case ABIArgInfo::Indirect: {
Daniel Dunbar747865a2009-02-05 09:16:39 +00002351 if (RV.isScalar() || RV.isComplex()) {
2352 // Make a temporary alloca to pass the argument.
Eli Friedman7e68c882011-06-15 18:26:32 +00002353 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2354 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
2355 AI->setAlignment(ArgInfo.getIndirectAlign());
2356 Args.push_back(AI);
John McCall47fb9502013-03-07 21:37:08 +00002357
2358 LValue argLV =
2359 MakeAddrLValue(Args.back(), I->Ty, TypeAlign);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002360
Daniel Dunbar747865a2009-02-05 09:16:39 +00002361 if (RV.isScalar())
John McCall47fb9502013-03-07 21:37:08 +00002362 EmitStoreOfScalar(RV.getScalarVal(), argLV, /*init*/ true);
Daniel Dunbar747865a2009-02-05 09:16:39 +00002363 else
John McCall47fb9502013-03-07 21:37:08 +00002364 EmitStoreOfComplex(RV.getComplexVal(), argLV, /*init*/ true);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002365
2366 // Validate argument match.
2367 checkArgMatches(AI, IRArgNo, IRFuncTy);
Daniel Dunbar747865a2009-02-05 09:16:39 +00002368 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002369 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00002370 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002371 // 1. If the argument is not byval, and we are required to copy the
2372 // source. (This case doesn't occur on any common architecture.)
2373 // 2. If the argument is byval, RV is not sufficiently aligned, and
2374 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00002375 // 3. If the argument is byval, but RV is located in an address space
2376 // different than that of the argument (0).
Eli Friedmanf7456192011-06-15 22:09:18 +00002377 llvm::Value *Addr = RV.getAggregateAddr();
2378 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002379 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyei3832bfd2013-03-10 12:59:00 +00002380 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
2381 const unsigned ArgAddrSpace = (IRArgNo < IRFuncTy->getNumParams() ?
2382 IRFuncTy->getParamType(IRArgNo)->getPointerAddressSpace() : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00002383 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall47fb9502013-03-07 21:37:08 +00002384 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Guy Benyei3832bfd2013-03-10 12:59:00 +00002385 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
2386 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002387 // Create an aligned temporary, and copy to it.
Eli Friedmanf7456192011-06-15 22:09:18 +00002388 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2389 if (Align > AI->getAlignment())
2390 AI->setAlignment(Align);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002391 Args.push_back(AI);
Chad Rosier615ed1a2012-03-29 17:37:10 +00002392 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002393
2394 // Validate argument match.
2395 checkArgMatches(AI, IRArgNo, IRFuncTy);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002396 } else {
2397 // Skip the extra memcpy call.
Eli Friedmanf7456192011-06-15 22:09:18 +00002398 Args.push_back(Addr);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002399
2400 // Validate argument match.
2401 checkArgMatches(Addr, IRArgNo, IRFuncTy);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002402 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002403 }
2404 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002405 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002406
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002407 case ABIArgInfo::Ignore:
2408 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002409
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002410 case ABIArgInfo::Extend:
2411 case ABIArgInfo::Direct: {
2412 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002413 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
2414 ArgInfo.getDirectOffset() == 0) {
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002415 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002416 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002417 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002418 else
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002419 V = Builder.CreateLoad(RV.getAggregateAddr());
2420
Chris Lattner3ce86682011-07-12 04:53:39 +00002421 // If the argument doesn't match, perform a bitcast to coerce it. This
2422 // can happen due to trivial type mismatches.
2423 if (IRArgNo < IRFuncTy->getNumParams() &&
2424 V->getType() != IRFuncTy->getParamType(IRArgNo))
2425 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRArgNo));
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002426 Args.push_back(V);
2427
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002428 checkArgMatches(V, IRArgNo, IRFuncTy);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002429 break;
2430 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002431
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002432 // FIXME: Avoid the conversion through memory if possible.
2433 llvm::Value *SrcPtr;
John McCall47fb9502013-03-07 21:37:08 +00002434 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002435 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall47fb9502013-03-07 21:37:08 +00002436 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
2437 if (RV.isScalar()) {
2438 EmitStoreOfScalar(RV.getScalarVal(), SrcLV, /*init*/ true);
2439 } else {
2440 EmitStoreOfComplex(RV.getComplexVal(), SrcLV, /*init*/ true);
2441 }
Mike Stump11289f42009-09-09 15:08:12 +00002442 } else
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002443 SrcPtr = RV.getAggregateAddr();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002444
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002445 // If the value is offset in memory, apply the offset now.
2446 if (unsigned Offs = ArgInfo.getDirectOffset()) {
2447 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
2448 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002449 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002450 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
2451
2452 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002453
Chris Lattner3dd716c2010-06-28 23:44:11 +00002454 // If the coerce-to type is a first class aggregate, we flatten it and
2455 // pass the elements. Either way is semantically identical, but fast-isel
2456 // and the optimizer generally likes scalar values better than FCAs.
Chris Lattner2192fe52011-07-18 04:24:23 +00002457 if (llvm::StructType *STy =
Chris Lattner15ec3612010-06-29 00:06:42 +00002458 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType())) {
Chandler Carrutha6399a52012-10-10 11:29:08 +00002459 llvm::Type *SrcTy =
2460 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
2461 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
2462 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
2463
2464 // If the source type is smaller than the destination type of the
2465 // coerce-to logic, copy the source value into a temp alloca the size
2466 // of the destination type to allow loading all of it. The bits past
2467 // the source value are left undef.
2468 if (SrcSize < DstSize) {
2469 llvm::AllocaInst *TempAlloca
2470 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
2471 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
2472 SrcPtr = TempAlloca;
2473 } else {
2474 SrcPtr = Builder.CreateBitCast(SrcPtr,
2475 llvm::PointerType::getUnqual(STy));
2476 }
2477
Chris Lattnerceddafb2010-07-05 20:41:41 +00002478 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2479 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerff941a62010-07-28 18:24:28 +00002480 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
2481 // We don't know what we're loading from.
2482 LI->setAlignment(1);
2483 Args.push_back(LI);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002484
2485 // Validate argument match.
2486 checkArgMatches(LI, IRArgNo, IRFuncTy);
Chris Lattner15ec3612010-06-29 00:06:42 +00002487 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00002488 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00002489 // In the simple case, just pass the coerced loaded value.
2490 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
2491 *this));
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002492
2493 // Validate argument match.
2494 checkArgMatches(Args.back(), IRArgNo, IRFuncTy);
Chris Lattner3dd716c2010-06-28 23:44:11 +00002495 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002496
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002497 break;
2498 }
2499
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002500 case ABIArgInfo::Expand:
Chris Lattnerd59d8672011-07-12 06:29:11 +00002501 ExpandTypeToArgs(I->Ty, RV, Args, IRFuncTy);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002502 IRArgNo = Args.size();
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002503 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00002504 }
2505 }
Mike Stump11289f42009-09-09 15:08:12 +00002506
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002507 if (!CallArgs.getCleanupsToDeactivate().empty())
2508 deactivateArgCleanupsBeforeCall(*this, CallArgs);
2509
Chris Lattner4ca97c32009-06-13 00:26:38 +00002510 // If the callee is a bitcast of a function to a varargs pointer to function
2511 // type, check to see if we can remove the bitcast. This handles some cases
2512 // with unprototyped functions.
2513 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
2514 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002515 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
2516 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00002517 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00002518 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00002519
Chris Lattner4ca97c32009-06-13 00:26:38 +00002520 if (CE->getOpcode() == llvm::Instruction::BitCast &&
2521 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00002522 ActualFT->getNumParams() == CurFT->getNumParams() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00002523 ActualFT->getNumParams() == Args.size() &&
2524 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00002525 bool ArgsMatch = true;
2526 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
2527 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
2528 ArgsMatch = false;
2529 break;
2530 }
Mike Stump11289f42009-09-09 15:08:12 +00002531
Chris Lattner4ca97c32009-06-13 00:26:38 +00002532 // Strip the cast if we can get away with it. This is a nice cleanup,
2533 // but also allows us to inline the function at -O0 if it is marked
2534 // always_inline.
2535 if (ArgsMatch)
2536 Callee = CalleeF;
2537 }
2538 }
Mike Stump11289f42009-09-09 15:08:12 +00002539
Daniel Dunbar0ef34792009-09-12 00:59:20 +00002540 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00002541 CodeGen::AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00002542 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
2543 CallingConv, true);
Bill Wendling3087d022012-12-07 23:17:26 +00002544 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00002545 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00002546
John McCallbd309292010-07-06 01:34:17 +00002547 llvm::BasicBlock *InvokeDest = 0;
Bill Wendling5e85be42012-12-30 10:32:17 +00002548 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
2549 llvm::Attribute::NoUnwind))
John McCallbd309292010-07-06 01:34:17 +00002550 InvokeDest = getInvokeDest();
2551
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002552 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00002553 if (!InvokeDest) {
Jay Foad5bd375a2011-07-15 08:37:34 +00002554 CS = Builder.CreateCall(Callee, Args);
Daniel Dunbar12347492009-02-23 17:26:39 +00002555 } else {
2556 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Jay Foad5bd375a2011-07-15 08:37:34 +00002557 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, Args);
Daniel Dunbar12347492009-02-23 17:26:39 +00002558 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00002559 }
Chris Lattnere70a0072010-06-29 16:40:28 +00002560 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00002561 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00002562
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002563 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00002564 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002565
Dan Gohman515a60d2012-02-16 00:57:37 +00002566 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2567 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002568 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002569 AddObjCARCExceptionMetadata(CS.getInstruction());
2570
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002571 // If the call doesn't return, finish the basic block and clear the
2572 // insertion point; this allows the rest of IRgen to discard
2573 // unreachable code.
2574 if (CS.doesNotReturn()) {
2575 Builder.CreateUnreachable();
2576 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00002577
Mike Stump18bb9282009-05-16 07:57:57 +00002578 // FIXME: For now, emit a dummy basic block because expr emitters in
2579 // generally are not ready to handle emitting expressions at unreachable
2580 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002581 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00002582
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002583 // Return a reasonable RValue.
2584 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00002585 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002586
2587 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00002588 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00002589 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002590
John McCall31168b02011-06-15 23:02:42 +00002591 // Emit any writebacks immediately. Arguably this should happen
2592 // after any return-value munging.
2593 if (CallArgs.hasWritebacks())
2594 emitWritebacks(*this, CallArgs);
2595
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002596 switch (RetAI.getKind()) {
John McCall47fb9502013-03-07 21:37:08 +00002597 case ABIArgInfo::Indirect:
Nick Lewycky2d84e842013-10-02 02:29:49 +00002598 return convertTempToRValue(Args[0], RetTy, SourceLocation());
Daniel Dunbard3674e62008-09-11 01:48:57 +00002599
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002600 case ABIArgInfo::Ignore:
Daniel Dunbar01362822009-02-03 06:30:17 +00002601 // If we are ignoring an argument that had a result, make sure to
2602 // construct the appropriate return value for our caller.
Daniel Dunbarc79407f2009-02-05 07:09:07 +00002603 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002604
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002605 case ABIArgInfo::Extend:
2606 case ABIArgInfo::Direct: {
Chris Lattner3517f142011-07-13 03:59:32 +00002607 llvm::Type *RetIRTy = ConvertType(RetTy);
2608 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
John McCall47fb9502013-03-07 21:37:08 +00002609 switch (getEvaluationKind(RetTy)) {
2610 case TEK_Complex: {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002611 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
2612 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
2613 return RValue::getComplex(std::make_pair(Real, Imag));
2614 }
John McCall47fb9502013-03-07 21:37:08 +00002615 case TEK_Aggregate: {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002616 llvm::Value *DestPtr = ReturnValue.getValue();
2617 bool DestIsVolatile = ReturnValue.isVolatile();
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002618
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002619 if (!DestPtr) {
2620 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
2621 DestIsVolatile = false;
2622 }
Eli Friedmanaf9b3252011-05-17 21:08:01 +00002623 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002624 return RValue::getAggregate(DestPtr);
2625 }
John McCall47fb9502013-03-07 21:37:08 +00002626 case TEK_Scalar: {
2627 // If the argument doesn't match, perform a bitcast to coerce it. This
2628 // can happen due to trivial type mismatches.
2629 llvm::Value *V = CI;
2630 if (V->getType() != RetIRTy)
2631 V = Builder.CreateBitCast(V, RetIRTy);
2632 return RValue::get(V);
2633 }
2634 }
2635 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002636 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002637
Anders Carlsson17490832009-12-24 20:40:36 +00002638 llvm::Value *DestPtr = ReturnValue.getValue();
2639 bool DestIsVolatile = ReturnValue.isVolatile();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002640
Anders Carlsson17490832009-12-24 20:40:36 +00002641 if (!DestPtr) {
Daniel Dunbara7566f12010-02-09 02:48:28 +00002642 DestPtr = CreateMemTemp(RetTy, "coerce");
Anders Carlsson17490832009-12-24 20:40:36 +00002643 DestIsVolatile = false;
2644 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002645
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002646 // If the value is offset in memory, apply the offset now.
2647 llvm::Value *StorePtr = DestPtr;
2648 if (unsigned Offs = RetAI.getDirectOffset()) {
2649 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
2650 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002651 StorePtr = Builder.CreateBitCast(StorePtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002652 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2653 }
2654 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002655
Nick Lewycky2d84e842013-10-02 02:29:49 +00002656 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Daniel Dunbar573884e2008-09-10 07:04:09 +00002657 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00002658
Daniel Dunbard3674e62008-09-11 01:48:57 +00002659 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002660 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar613855c2008-09-09 23:27:19 +00002661 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002662
David Blaikie83d382b2011-09-23 05:06:16 +00002663 llvm_unreachable("Unhandled ABIArgInfo::Kind");
Daniel Dunbar613855c2008-09-09 23:27:19 +00002664}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00002665
2666/* VarArg handling */
2667
2668llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
2669 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
2670}