blob: 22f2467021e1cc07dc6bd8cb859646f38929292c [file] [log] [blame]
Nick Lewycky5d4a7552013-10-01 21:51:38 +00001//===--- CGCall.cpp - Encapsulate calling convention details --------------===//
Daniel Dunbar0dbe2272008-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 Lattnerce933992010-06-29 16:40:28 +000016#include "ABIInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "CGCXXABI.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000018#include "CodeGenFunction.h"
Daniel Dunbarb7688072008-09-10 00:41:16 +000019#include "CodeGenModule.h"
John McCallde5d3c72012-02-17 03:33:10 +000020#include "TargetInfo.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000021#include "clang/AST/Decl.h"
Anders Carlssonf6f8ae52009-04-03 22:48:58 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000023#include "clang/AST/DeclObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/Basic/TargetInfo.h"
Mark Lacey8b549992013-10-30 21:53:58 +000025#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000026#include "clang/Frontend/CodeGenOptions.h"
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +000027#include "llvm/ADT/StringExtras.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000028#include "llvm/IR/Attributes.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/InlineAsm.h"
Bill Wendlingc0dcc2d2013-02-15 21:30:01 +000031#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "llvm/Support/CallSite.h"
Eli Friedman97cb5a42011-06-15 22:09:18 +000033#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000034using namespace clang;
35using namespace CodeGen;
36
37/***/
38
John McCall04a67a62010-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 Gregorf813a2c2010-05-18 16:57:00 +000044 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davise8519c32013-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 Korobeynikov414d8962011-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 Benyei38980082012-12-25 08:53:55 +000049 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Dawn Perchik52fc3142010-09-03 01:29:35 +000050 // TODO: add support for CC_X86Pascal to llvm
John McCall04a67a62010-02-05 21:31:56 +000051 }
52}
53
John McCall0b0ef0a2010-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 McCallead608a2010-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 Dunbar45c25ba2008-09-10 04:01:49 +000060}
61
John McCall0b0ef0a2010-02-24 07:14:12 +000062/// Returns the canonical formal type of the given C++ method.
John McCallead608a2010-02-26 00:48:12 +000063static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
64 return MD->getType()->getCanonicalTypeUnqualified()
65 .getAs<FunctionProtoType>();
John McCall0b0ef0a2010-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 McCallead608a2010-02-26 00:48:12 +000072static CanQualType GetReturnType(QualType RetTy) {
73 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall0b0ef0a2010-02-24 07:14:12 +000074}
75
John McCall0f3d0972012-07-07 06:41:13 +000076/// Arrange the argument and result information for a value of the given
77/// unprototyped freestanding function type.
John McCall0b0ef0a2010-02-24 07:14:12 +000078const CGFunctionInfo &
John McCall0f3d0972012-07-07 06:41:13 +000079CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCallde5d3c72012-02-17 03:33:10 +000080 // When translating an unprototyped function type, always use a
81 // variadic type.
John McCall0f3d0972012-07-07 06:41:13 +000082 return arrangeLLVMFunctionInfo(FTNP->getResultType().getUnqualifiedType(),
Dmitri Gribenko55431692013-05-05 00:41:58 +000083 None, FTNP->getExtInfo(), RequiredArgs(0));
John McCall0b0ef0a2010-02-24 07:14:12 +000084}
85
John McCall0f3d0972012-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 Dunbar541b63b2009-02-02 23:23:47 +000094 // FIXME: Kill copy.
Daniel Dunbar45c25ba2008-09-10 04:01:49 +000095 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
John McCall0f3d0972012-07-07 06:41:13 +000096 prefix.push_back(FTP->getArgType(i));
John McCallde5d3c72012-02-17 03:33:10 +000097 CanQualType resultType = FTP->getResultType().getUnqualifiedType();
John McCall0f3d0972012-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 McCall0f3d0972012-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 McCall0f3d0972012-07-07 06:41:13 +0000115 return arrangeLLVMFunctionInfo(CGT, prefix, FTP, extInfo);
John McCall0b0ef0a2010-02-24 07:14:12 +0000116}
117
John McCallde5d3c72012-02-17 03:33:10 +0000118/// Arrange the argument and result information for a value of the
John McCall0f3d0972012-07-07 06:41:13 +0000119/// given freestanding function type.
John McCall0b0ef0a2010-02-24 07:14:12 +0000120const CGFunctionInfo &
John McCall0f3d0972012-07-07 06:41:13 +0000121CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
John McCallde5d3c72012-02-17 03:33:10 +0000122 SmallVector<CanQualType, 16> argTypes;
John McCall0f3d0972012-07-07 06:41:13 +0000123 return ::arrangeFreeFunctionType(*this, argTypes, FTP);
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000124}
125
John McCall04a67a62010-02-05 21:31:56 +0000126static CallingConv getCallingConventionForDecl(const Decl *D) {
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000127 // Set the appropriate calling convention for the Function.
128 if (D->hasAttr<StdCallAttr>())
John McCall04a67a62010-02-05 21:31:56 +0000129 return CC_X86StdCall;
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000130
131 if (D->hasAttr<FastCallAttr>())
John McCall04a67a62010-02-05 21:31:56 +0000132 return CC_X86FastCall;
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000133
Douglas Gregorf813a2c2010-05-18 16:57:00 +0000134 if (D->hasAttr<ThisCallAttr>())
135 return CC_X86ThisCall;
136
Dawn Perchik52fc3142010-09-03 01:29:35 +0000137 if (D->hasAttr<PascalAttr>())
138 return CC_X86Pascal;
139
Anton Korobeynikov414d8962011-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 Schuff263366f2012-10-16 22:30:41 +0000143 if (D->hasAttr<PnaclCallAttr>())
144 return CC_PnaclCall;
145
Guy Benyei38980082012-12-25 08:53:55 +0000146 if (D->hasAttr<IntelOclBiccAttr>())
147 return CC_IntelOclBicc;
148
John McCall04a67a62010-02-05 21:31:56 +0000149 return CC_C;
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000150}
151
John McCallde5d3c72012-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 Iskhodzhanov8f189a92013-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 McCallde5d3c72012-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 McCall0b0ef0a2010-02-24 07:14:12 +0000162
Anders Carlsson375c31c2009-10-03 19:43:08 +0000163 // Add the 'this' pointer.
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000164 if (RD)
165 argTypes.push_back(GetThisType(Context, RD));
166 else
167 argTypes.push_back(Context.VoidPtrTy);
John McCall0b0ef0a2010-02-24 07:14:12 +0000168
John McCall0f3d0972012-07-07 06:41:13 +0000169 return ::arrangeCXXMethodType(*this, argTypes,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000170 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson375c31c2009-10-03 19:43:08 +0000171}
172
John McCallde5d3c72012-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 Kramere5753592013-09-09 14:48:42 +0000179 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCallfc400282010-09-03 01:26:39 +0000180 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
181
John McCallde5d3c72012-02-17 03:33:10 +0000182 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000183
John McCallde5d3c72012-02-17 03:33:10 +0000184 if (MD->isInstance()) {
185 // The abstract case is perfectly fine.
Mark Lacey25296602013-10-02 20:35:23 +0000186 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000187 return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
John McCallde5d3c72012-02-17 03:33:10 +0000188 }
189
John McCall0f3d0972012-07-07 06:41:13 +0000190 return arrangeFreeFunctionType(prototype);
Anders Carlssonf6f8ae52009-04-03 22:48:58 +0000191}
192
John McCallde5d3c72012-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 Lin3b50e8d2013-06-30 20:40:16 +0000200
201 GlobalDecl GD(D, ctorKind);
202 CanQualType resultType =
203 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000204
John McCallde5d3c72012-02-17 03:33:10 +0000205 TheCXXABI.BuildConstructorSignature(D, ctorKind, resultType, argTypes);
John McCall0b0ef0a2010-02-24 07:14:12 +0000206
John McCall4c40d982010-08-31 07:33:07 +0000207 CanQual<FunctionProtoType> FTP = GetFormalType(D);
208
John McCallde5d3c72012-02-17 03:33:10 +0000209 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, argTypes.size());
210
John McCall4c40d982010-08-31 07:33:07 +0000211 // Add the formal parameters.
212 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
John McCallde5d3c72012-02-17 03:33:10 +0000213 argTypes.push_back(FTP->getArgType(i));
John McCall4c40d982010-08-31 07:33:07 +0000214
John McCall0f3d0972012-07-07 06:41:13 +0000215 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
John McCall0f3d0972012-07-07 06:41:13 +0000216 return arrangeLLVMFunctionInfo(resultType, argTypes, extInfo, required);
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000217}
218
John McCallde5d3c72012-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 Lin3b50e8d2013-06-30 20:40:16 +0000227
228 GlobalDecl GD(D, dtorKind);
229 CanQualType resultType =
230 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
John McCall0b0ef0a2010-02-24 07:14:12 +0000231
John McCallde5d3c72012-02-17 03:33:10 +0000232 TheCXXABI.BuildDestructorSignature(D, dtorKind, resultType, argTypes);
John McCall4c40d982010-08-31 07:33:07 +0000233
234 CanQual<FunctionProtoType> FTP = GetFormalType(D);
235 assert(FTP->getNumArgs() == 0 && "dtor with formal parameters");
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +0000236 assert(FTP->isVariadic() == 0 && "dtor with formal parameters");
John McCall4c40d982010-08-31 07:33:07 +0000237
John McCall0f3d0972012-07-07 06:41:13 +0000238 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
John McCall0f3d0972012-07-07 06:41:13 +0000239 return arrangeLLVMFunctionInfo(resultType, argTypes, extInfo,
240 RequiredArgs::All);
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000241}
242
John McCallde5d3c72012-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 Lattner3eb67ca2009-05-12 20:27:19 +0000247 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonf6f8ae52009-04-03 22:48:58 +0000248 if (MD->isInstance())
John McCallde5d3c72012-02-17 03:33:10 +0000249 return arrangeCXXMethodDeclaration(MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000250
John McCallead608a2010-02-26 00:48:12 +0000251 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCallde5d3c72012-02-17 03:33:10 +0000252
John McCallead608a2010-02-26 00:48:12 +0000253 assert(isa<FunctionType>(FTy));
John McCallde5d3c72012-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 Gribenko55431692013-05-05 00:41:58 +0000259 return arrangeLLVMFunctionInfo(noProto->getResultType(), None,
260 noProto->getExtInfo(), RequiredArgs::All);
John McCallde5d3c72012-02-17 03:33:10 +0000261 }
262
John McCallead608a2010-02-26 00:48:12 +0000263 assert(isa<FunctionProtoType>(FTy));
John McCall0f3d0972012-07-07 06:41:13 +0000264 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000265}
266
John McCallde5d3c72012-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 Dunbar541b63b2009-02-02 23:23:47 +0000288 // FIXME: Kill copy?
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +0000289 for (ObjCMethodDecl::param_const_iterator i = MD->param_begin(),
John McCall0b0ef0a2010-02-24 07:14:12 +0000290 e = MD->param_end(); i != e; ++i) {
John McCallde5d3c72012-02-17 03:33:10 +0000291 argTys.push_back(Context.getCanonicalParamType((*i)->getType()));
John McCall0b0ef0a2010-02-24 07:14:12 +0000292 }
John McCallf85e1932011-06-15 23:02:42 +0000293
294 FunctionType::ExtInfo einfo;
295 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD));
296
David Blaikie4e4d0842012-03-11 07:00:24 +0000297 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000298 MD->hasAttr<NSReturnsRetainedAttr>())
299 einfo = einfo.withProducesResult(true);
300
John McCallde5d3c72012-02-17 03:33:10 +0000301 RequiredArgs required =
302 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
303
John McCall0f3d0972012-07-07 06:41:13 +0000304 return arrangeLLVMFunctionInfo(GetReturnType(MD->getResultType()), argTys,
305 einfo, required);
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000306}
307
John McCallde5d3c72012-02-17 03:33:10 +0000308const CGFunctionInfo &
309CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000310 // FIXME: Do we need to handle ObjCMethodDecl?
311 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000312
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000313 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
John McCallde5d3c72012-02-17 03:33:10 +0000314 return arrangeCXXConstructorDeclaration(CD, GD.getCtorType());
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000315
316 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
John McCallde5d3c72012-02-17 03:33:10 +0000317 return arrangeCXXDestructor(DD, GD.getDtorType());
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000318
John McCallde5d3c72012-02-17 03:33:10 +0000319 return arrangeFunctionDeclaration(FD);
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000320}
321
John McCalle56bb362012-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 Laceyc3f7fd62013-10-10 20:57:00 +0000326 CodeGenModule &CGM,
John McCalle56bb362012-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 Laceyc3f7fd62013-10-10 20:57:00 +0000345 } else if (CGM.getTargetCodeGenInfo()
346 .isNoProtoCallVariadic(args,
347 cast<FunctionNoProtoType>(fnType))) {
John McCalle56bb362012-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 McCallde5d3c72012-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 McCall0f3d0972012-07-07 06:41:13 +0000360CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
361 const FunctionType *fnType) {
Mark Laceyc3f7fd62013-10-10 20:57:00 +0000362 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 0);
John McCalle56bb362012-12-07 07:03:17 +0000363}
John McCallde5d3c72012-02-17 03:33:10 +0000364
John McCalle56bb362012-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 Laceyc3f7fd62013-10-10 20:57:00 +0000370 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1);
John McCallde5d3c72012-02-17 03:33:10 +0000371}
372
373const CGFunctionInfo &
John McCall0f3d0972012-07-07 06:41:13 +0000374CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
375 const CallArgList &args,
376 FunctionType::ExtInfo info,
377 RequiredArgs required) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000378 // FIXME: Kill copy.
John McCallde5d3c72012-02-17 03:33:10 +0000379 SmallVector<CanQualType, 16> argTypes;
380 for (CallArgList::const_iterator i = args.begin(), e = args.end();
Daniel Dunbar725ad312009-01-31 02:19:00 +0000381 i != e; ++i)
John McCallde5d3c72012-02-17 03:33:10 +0000382 argTypes.push_back(Context.getCanonicalParamType(i->Ty));
John McCall0f3d0972012-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 McCall0f3d0972012-07-07 06:41:13 +0000399 return arrangeLLVMFunctionInfo(GetReturnType(FPT->getResultType()),
400 argTypes, info, required);
Daniel Dunbar725ad312009-01-31 02:19:00 +0000401}
402
John McCallde5d3c72012-02-17 03:33:10 +0000403const CGFunctionInfo &
404CodeGenTypes::arrangeFunctionDeclaration(QualType resultType,
405 const FunctionArgList &args,
406 const FunctionType::ExtInfo &info,
407 bool isVariadic) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000408 // FIXME: Kill copy.
John McCallde5d3c72012-02-17 03:33:10 +0000409 SmallVector<CanQualType, 16> argTypes;
410 for (FunctionArgList::const_iterator i = args.begin(), e = args.end();
Daniel Dunbarbb36d332009-02-02 21:43:58 +0000411 i != e; ++i)
John McCallde5d3c72012-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 McCall0f3d0972012-07-07 06:41:13 +0000416 return arrangeLLVMFunctionInfo(GetReturnType(resultType), argTypes, info,
417 required);
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000418}
419
John McCallde5d3c72012-02-17 03:33:10 +0000420const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Dmitri Gribenko55431692013-05-05 00:41:58 +0000421 return arrangeLLVMFunctionInfo(getContext().VoidTy, None,
John McCall0f3d0972012-07-07 06:41:13 +0000422 FunctionType::ExtInfo(), RequiredArgs::All);
John McCalld26bc762011-03-09 04:27:21 +0000423}
424
John McCallde5d3c72012-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 McCall0f3d0972012-07-07 06:41:13 +0000429CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
430 ArrayRef<CanQualType> argTypes,
431 FunctionType::ExtInfo info,
432 RequiredArgs required) {
John McCallead608a2010-02-26 00:48:12 +0000433#ifndef NDEBUG
John McCallde5d3c72012-02-17 03:33:10 +0000434 for (ArrayRef<CanQualType>::const_iterator
435 I = argTypes.begin(), E = argTypes.end(); I != E; ++I)
John McCallead608a2010-02-26 00:48:12 +0000436 assert(I->isCanonicalAsParam());
437#endif
438
John McCallde5d3c72012-02-17 03:33:10 +0000439 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCall04a67a62010-02-05 21:31:56 +0000440
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000441 // Lookup or create unique function info.
442 llvm::FoldingSetNodeID ID;
John McCallde5d3c72012-02-17 03:33:10 +0000443 CGFunctionInfo::Profile(ID, info, required, resultType, argTypes);
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000444
John McCallde5d3c72012-02-17 03:33:10 +0000445 void *insertPos = 0;
446 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000447 if (FI)
448 return *FI;
449
John McCallde5d3c72012-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 Dunbar88c2fa92009-02-03 05:31:23 +0000453
John McCallde5d3c72012-02-17 03:33:10 +0000454 bool inserted = FunctionsBeingProcessed.insert(FI); (void)inserted;
455 assert(inserted && "Recursively being processed?");
Chris Lattner71305cc2011-07-15 05:16:14 +0000456
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000457 // Compute ABI information.
Chris Lattneree5dcd02010-07-29 02:31:05 +0000458 getABIInfo().computeInfo(*FI);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000459
Chris Lattner800588f2010-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 McCallde5d3c72012-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. Spencer9cac4942010-10-19 06:39:39 +0000466
Chris Lattner800588f2010-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 Lattner9cbe4f02011-07-09 17:41:47 +0000470 I->info.setCoerceToType(ConvertType(I->type));
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000471
John McCallde5d3c72012-02-17 03:33:10 +0000472 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
473 assert(erased && "Not in set?");
Chris Lattnerd26c0712011-07-15 06:41:05 +0000474
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000475 return *FI;
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000476}
477
John McCallde5d3c72012-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 Dunbar88c2fa92009-02-03 05:31:23 +0000499}
500
501/***/
502
John McCall42e06112011-05-15 02:19:42 +0000503void CodeGenTypes::GetExpandedTypes(QualType type,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000504 SmallVectorImpl<llvm::Type*> &expandedTypes) {
Bob Wilson194f06a2011-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 Korobeynikoveaf856d2012-04-13 11:22:00 +0000509 } else if (const RecordType *RT = type->getAs<RecordType>()) {
Bob Wilson194f06a2011-08-03 05:58:22 +0000510 const RecordDecl *RD = RT->getDecl();
511 assert(!RD->hasFlexibleArrayMember() &&
512 "Cannot expand structure with flexible array.");
Anton Korobeynikoveaf856d2012-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 Blaikie581deb32012-06-06 20:45:41 +0000521 const FieldDecl *FD = *i;
Anton Korobeynikoveaf856d2012-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 Blaikie581deb32012-06-06 20:45:41 +0000535 assert(!i->isBitField() &&
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000536 "Cannot expand structure with bit-field members.");
David Blaikie581deb32012-06-06 20:45:41 +0000537 GetExpandedTypes(i->getType(), expandedTypes);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000538 }
Bob Wilson194f06a2011-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 Dunbar56273772008-09-17 00:51:38 +0000546}
547
Mike Stump1eb44332009-09-09 15:08:12 +0000548llvm::Function::arg_iterator
Daniel Dunbar56273772008-09-17 00:51:38 +0000549CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
550 llvm::Function::arg_iterator AI) {
Mike Stump1eb44332009-09-09 15:08:12 +0000551 assert(LV.isSimple() &&
552 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar56273772008-09-17 00:51:38 +0000553
Bob Wilson194f06a2011-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 Friedman377ecc72012-04-16 03:54:45 +0000558 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, Elt);
Bob Wilson194f06a2011-08-03 05:58:22 +0000559 LValue LV = MakeAddrLValue(EltAddr, EltTy);
560 AI = ExpandTypeFromArgs(EltTy, LV, AI);
Daniel Dunbar56273772008-09-17 00:51:38 +0000561 }
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000562 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilson194f06a2011-08-03 05:58:22 +0000563 RecordDecl *RD = RT->getDecl();
Anton Korobeynikoveaf856d2012-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 Wilson194f06a2011-08-03 05:58:22 +0000569
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000570 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
571 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +0000572 const FieldDecl *FD = *i;
Anton Korobeynikoveaf856d2012-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 Friedman377ecc72012-04-16 03:54:45 +0000583 LValue SubLV = EmitLValueForField(LV, LargestFD);
584 AI = ExpandTypeFromArgs(LargestFD->getType(), SubLV, AI);
Anton Korobeynikoveaf856d2012-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 Blaikie581deb32012-06-06 20:45:41 +0000589 FieldDecl *FD = *i;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000590 QualType FT = FD->getType();
591
592 // FIXME: What are the right qualifiers here?
Eli Friedman377ecc72012-04-16 03:54:45 +0000593 LValue SubLV = EmitLValueForField(LV, FD);
594 AI = ExpandTypeFromArgs(FT, SubLV, AI);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000595 }
Bob Wilson194f06a2011-08-03 05:58:22 +0000596 }
597 } else if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
598 QualType EltTy = CT->getElementType();
Eli Friedman377ecc72012-04-16 03:54:45 +0000599 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Bob Wilson194f06a2011-08-03 05:58:22 +0000600 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(RealAddr, EltTy));
Eli Friedman377ecc72012-04-16 03:54:45 +0000601 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Bob Wilson194f06a2011-08-03 05:58:22 +0000602 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(ImagAddr, EltTy));
603 } else {
604 EmitStoreThroughLValue(RValue::get(AI), LV);
605 ++AI;
Daniel Dunbar56273772008-09-17 00:51:38 +0000606 }
607
608 return AI;
609}
610
Chris Lattnere7bb7772010-06-27 06:04:18 +0000611/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner08dd2a02010-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 Lattnere7bb7772010-06-27 06:04:18 +0000616EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000617 llvm::StructType *SrcSTy,
Chris Lattnere7bb7772010-06-27 06:04:18 +0000618 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner08dd2a02010-06-27 05:56:15 +0000619 // We can't dive into a zero-element struct.
620 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000621
Chris Lattner2acc6e32011-07-18 04:24:23 +0000622 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000623
Chris Lattner08dd2a02010-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. Spencer9cac4942010-10-19 06:39:39 +0000626 uint64_t FirstEltSize =
Micah Villmow25a6a842012-10-08 16:25:52 +0000627 CGF.CGM.getDataLayout().getTypeAllocSize(FirstElt);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000628 if (FirstEltSize < DstSize &&
Micah Villmow25a6a842012-10-08 16:25:52 +0000629 FirstEltSize < CGF.CGM.getDataLayout().getTypeAllocSize(SrcSTy))
Chris Lattner08dd2a02010-06-27 05:56:15 +0000630 return SrcPtr;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000631
Chris Lattner08dd2a02010-06-27 05:56:15 +0000632 // GEP into the first element.
633 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000634
Chris Lattner08dd2a02010-06-27 05:56:15 +0000635 // If the first element is a struct, recurse.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000636 llvm::Type *SrcTy =
Chris Lattner08dd2a02010-06-27 05:56:15 +0000637 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000638 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattnere7bb7772010-06-27 06:04:18 +0000639 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner08dd2a02010-06-27 05:56:15 +0000640
641 return SrcPtr;
642}
643
Chris Lattner6d11cdb2010-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 Olesen7e9f52f2013-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 Lattner6d11cdb2010-06-27 06:26:04 +0000651static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000652 llvm::Type *Ty,
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000653 CodeGenFunction &CGF) {
654 if (Val->getType() == Ty)
655 return Val;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000656
Chris Lattner6d11cdb2010-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. Spencer9cac4942010-10-19 06:39:39 +0000661
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000662 // Convert the pointer to an integer so we can play with its width.
Chris Lattner77b89b82010-06-27 07:15:29 +0000663 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000664 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000665
Chris Lattner2acc6e32011-07-18 04:24:23 +0000666 llvm::Type *DestIntTy = Ty;
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000667 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner77b89b82010-06-27 07:15:29 +0000668 DestIntTy = CGF.IntPtrTy;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000669
Jakob Stoklund Olesen7e9f52f2013-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. Spencer9cac4942010-10-19 06:39:39 +0000689
Chris Lattner6d11cdb2010-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 Lattner08dd2a02010-06-27 05:56:15 +0000695
696
Daniel Dunbar275e10d2009-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 Lattner2acc6e32011-07-18 04:24:23 +0000704 llvm::Type *Ty,
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000705 CodeGenFunction &CGF) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000706 llvm::Type *SrcTy =
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000707 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000708
Chris Lattner6ae00692010-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. Spencer9cac4942010-10-19 06:39:39 +0000712
Micah Villmow25a6a842012-10-08 16:25:52 +0000713 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000714
Chris Lattner2acc6e32011-07-18 04:24:23 +0000715 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattnere7bb7772010-06-27 06:04:18 +0000716 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner08dd2a02010-06-27 05:56:15 +0000717 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
718 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000719
Micah Villmow25a6a842012-10-08 16:25:52 +0000720 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000721
Chris Lattner6d11cdb2010-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. Spencer9cac4942010-10-19 06:39:39 +0000729
Daniel Dunbarb225be42009-02-03 05:59:18 +0000730 // If load is legal, just bitcast the src pointer.
Daniel Dunbar7ef455b2009-05-13 18:54:26 +0000731 if (SrcSize >= DstSize) {
Mike Stumpf5408fe2009-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 Dunbar7ef455b2009-05-13 18:54:26 +0000735 //
Mike Stumpf5408fe2009-05-16 07:57:57 +0000736 // FIXME: Assert that we aren't truncating non-padding bits when have access
737 // to that information.
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000738 llvm::Value *Casted =
739 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbar386621f2009-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 Dunbar275e10d2009-02-02 19:06:38 +0000744 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000745
Chris Lattner35b21b82010-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 Renf51c61c2012-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 Ren060f34d2012-11-28 22:29:41 +0000752 // FIXME: Use better alignment.
Manman Renf51c61c2012-11-28 22:08:52 +0000753 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
754 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
755 1, false);
Chris Lattner35b21b82010-06-27 01:06:27 +0000756 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000757}
758
Eli Friedmanbadea572011-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 Lattner2acc6e32011-07-18 04:24:23 +0000767 if (llvm::StructType *STy =
Eli Friedmanbadea572011-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 Wendling08212632012-03-16 21:45:12 +0000778 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
779 if (LowAlignment)
780 SI->setAlignment(1);
Eli Friedmanbadea572011-05-17 21:08:01 +0000781 }
782}
783
Daniel Dunbar275e10d2009-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 Carlssond2490a92009-12-24 20:40:36 +0000791 bool DstIsVolatile,
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000792 CodeGenFunction &CGF) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000793 llvm::Type *SrcTy = Src->getType();
794 llvm::Type *DstTy =
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000795 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattner6ae00692010-06-28 22:51:39 +0000796 if (SrcTy == DstTy) {
797 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
798 return;
799 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000800
Micah Villmow25a6a842012-10-08 16:25:52 +0000801 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000802
Chris Lattner2acc6e32011-07-18 04:24:23 +0000803 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattnere7bb7772010-06-27 06:04:18 +0000804 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
805 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
806 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000807
Chris Lattner6d11cdb2010-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. Spencer9cac4942010-10-19 06:39:39 +0000816
Micah Villmow25a6a842012-10-08 16:25:52 +0000817 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000818
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000819 // If store is legal, just bitcast the src pointer.
Daniel Dunbarfdf49862009-06-05 07:58:54 +0000820 if (SrcSize <= DstSize) {
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000821 llvm::Value *Casted =
822 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbar386621f2009-02-07 02:46:03 +0000823 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanbadea572011-05-17 21:08:01 +0000824 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000825 } else {
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000826 // Otherwise do coercion through memory. This is stupid, but
827 // simple.
Daniel Dunbarfdf49862009-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 Dunbar275e10d2009-02-02 19:06:38 +0000835 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
836 CGF.Builder.CreateStore(Src, Tmp);
Manman Renf51c61c2012-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 Ren060f34d2012-11-28 22:29:41 +0000840 // FIXME: Use better alignment.
Manman Renf51c61c2012-11-28 22:08:52 +0000841 CGF.Builder.CreateMemCpy(DstCasted, Casted,
842 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
843 1, false);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000844 }
845}
846
Daniel Dunbar56273772008-09-17 00:51:38 +0000847/***/
848
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000849bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000850 return FI.getReturnInfo().isIndirect();
Daniel Dunbarbb36d332009-02-02 21:43:58 +0000851}
852
Daniel Dunbardacf9dd2010-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 McCall64aa4b32013-04-16 22:48:15 +0000859 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000860 case BuiltinType::Double:
John McCall64aa4b32013-04-16 22:48:15 +0000861 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000862 case BuiltinType::LongDouble:
John McCall64aa4b32013-04-16 22:48:15 +0000863 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000864 }
865 }
866
867 return false;
868}
869
Anders Carlssoneea64802011-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 McCall64aa4b32013-04-16 22:48:15 +0000874 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlssoneea64802011-10-31 16:27:11 +0000875 }
876 }
877
878 return false;
879}
880
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000881llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCallde5d3c72012-02-17 03:33:10 +0000882 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
883 return GetFunctionType(FI);
John McCallc0bf4622010-02-23 00:48:20 +0000884}
885
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000886llvm::FunctionType *
John McCallde5d3c72012-02-17 03:33:10 +0000887CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Chris Lattner71305cc2011-07-15 05:16:14 +0000888
889 bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted;
890 assert(Inserted && "Recursively being processed?");
891
Chris Lattner5f9e2722011-07-23 10:55:15 +0000892 SmallVector<llvm::Type*, 8> argTypes;
Chris Lattner2acc6e32011-07-18 04:24:23 +0000893 llvm::Type *resultType = 0;
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000894
John McCall42e06112011-05-15 02:19:42 +0000895 const ABIArgInfo &retAI = FI.getReturnInfo();
896 switch (retAI.getKind()) {
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000897 case ABIArgInfo::Expand:
John McCall42e06112011-05-15 02:19:42 +0000898 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000899
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000900 case ABIArgInfo::Extend:
Daniel Dunbar46327aa2009-02-03 06:17:37 +0000901 case ABIArgInfo::Direct:
John McCall42e06112011-05-15 02:19:42 +0000902 resultType = retAI.getCoerceToType();
Daniel Dunbar46327aa2009-02-03 06:17:37 +0000903 break;
904
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000905 case ABIArgInfo::Indirect: {
John McCall42e06112011-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 Lattner2acc6e32011-07-18 04:24:23 +0000910 llvm::Type *ty = ConvertType(ret);
John McCall42e06112011-05-15 02:19:42 +0000911 unsigned addressSpace = Context.getTargetAddressSpace(ret);
912 argTypes.push_back(llvm::PointerType::get(ty, addressSpace));
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000913 break;
914 }
915
Daniel Dunbar11434922009-01-26 21:26:08 +0000916 case ABIArgInfo::Ignore:
John McCall42e06112011-05-15 02:19:42 +0000917 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar11434922009-01-26 21:26:08 +0000918 break;
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000919 }
Mike Stump1eb44332009-09-09 15:08:12 +0000920
John McCalle56bb362012-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 McCall42e06112011-05-15 02:19:42 +0000929 const ABIArgInfo &argAI = it->info;
Mike Stump1eb44332009-09-09 15:08:12 +0000930
Rafael Espindolae4aeeaa2012-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 McCall42e06112011-05-15 02:19:42 +0000935 switch (argAI.getKind()) {
Daniel Dunbar11434922009-01-26 21:26:08 +0000936 case ABIArgInfo::Ignore:
937 break;
938
Chris Lattner800588f2010-07-29 06:26:06 +0000939 case ABIArgInfo::Indirect: {
940 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000941 llvm::Type *LTy = ConvertTypeForMem(it->type);
John McCall42e06112011-05-15 02:19:42 +0000942 argTypes.push_back(LTy->getPointerTo());
Chris Lattner800588f2010-07-29 06:26:06 +0000943 break;
944 }
945
946 case ABIArgInfo::Extend:
Chris Lattner1ed72672010-07-29 06:44:09 +0000947 case ABIArgInfo::Direct: {
Chris Lattnerce700162010-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 Lattner9cbe4f02011-07-09 17:41:47 +0000951 llvm::Type *argType = argAI.getCoerceToType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000952 if (llvm::StructType *st = dyn_cast<llvm::StructType>(argType)) {
John McCall42e06112011-05-15 02:19:42 +0000953 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
954 argTypes.push_back(st->getElementType(i));
Chris Lattnerce700162010-06-28 23:44:11 +0000955 } else {
John McCall42e06112011-05-15 02:19:42 +0000956 argTypes.push_back(argType);
Chris Lattnerce700162010-06-28 23:44:11 +0000957 }
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +0000958 break;
Chris Lattner1ed72672010-07-29 06:44:09 +0000959 }
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000961 case ABIArgInfo::Expand:
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000962 GetExpandedTypes(it->type, argTypes);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000963 break;
964 }
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000965 }
966
Chris Lattner71305cc2011-07-15 05:16:14 +0000967 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
968 assert(Erased && "Not in set?");
969
John McCallde5d3c72012-02-17 03:33:10 +0000970 return llvm::FunctionType::get(resultType, argTypes, FI.isVariadic());
Daniel Dunbar3913f182008-09-09 23:48:28 +0000971}
972
Chris Lattner2acc6e32011-07-18 04:24:23 +0000973llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall4c40d982010-08-31 07:33:07 +0000974 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlssonecf282b2009-11-24 05:08:52 +0000975 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000976
Chris Lattnerf742eb02011-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 McCallde5d3c72012-02-17 03:33:10 +0000982 Info = &arrangeCXXDestructor(cast<CXXDestructorDecl>(MD), GD.getDtorType());
Chris Lattnerf742eb02011-07-10 00:18:59 +0000983 else
John McCallde5d3c72012-02-17 03:33:10 +0000984 Info = &arrangeCXXMethodDeclaration(MD);
985 return GetFunctionType(*Info);
Anders Carlssonecf282b2009-11-24 05:08:52 +0000986}
987
Daniel Dunbara0a99e02009-02-02 23:43:58 +0000988void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbar88b53962009-02-02 22:03:45 +0000989 const Decl *TargetDecl,
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000990 AttributeListType &PAL,
Bill Wendling94236e72013-02-22 00:13:35 +0000991 unsigned &CallingConv,
992 bool AttrOnCallSite) {
Bill Wendling0d583392012-10-15 20:36:26 +0000993 llvm::AttrBuilder FuncAttrs;
994 llvm::AttrBuilder RetAttrs;
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000995
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000996 CallingConv = FI.getEffectiveCallingConvention();
997
John McCall04a67a62010-02-05 21:31:56 +0000998 if (FI.isNoReturn())
Bill Wendling72390b32012-12-20 19:27:06 +0000999 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCall04a67a62010-02-05 21:31:56 +00001000
Anton Korobeynikov1102f422009-04-04 00:49:24 +00001001 // FIXME: handle sseregparm someday...
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001002 if (TargetDecl) {
Rafael Espindola67004152011-10-12 19:51:18 +00001003 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +00001004 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001005 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +00001006 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith7586a6e2013-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 McCall9c0c1f32010-07-08 06:48:12 +00001011 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001012 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling72390b32012-12-20 19:27:06 +00001013 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith3c5cd152013-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 Smith7586a6e2013-01-30 05:45:05 +00001018 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCall9c0c1f32010-07-08 06:48:12 +00001019 }
1020
Eric Christopher041087c2011-08-15 22:38:22 +00001021 // 'const' and 'pure' attribute functions are also nounwind.
1022 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling72390b32012-12-20 19:27:06 +00001023 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1024 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopher041087c2011-08-15 22:38:22 +00001025 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling72390b32012-12-20 19:27:06 +00001026 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1027 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopher041087c2011-08-15 22:38:22 +00001028 }
Ryan Flynn76168e22009-08-09 20:07:29 +00001029 if (TargetDecl->hasAttr<MallocAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +00001030 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001031 }
1032
Chandler Carruth2811ccf2009-11-12 17:24:48 +00001033 if (CodeGenOpts.OptimizeSize)
Bill Wendling72390b32012-12-20 19:27:06 +00001034 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
Quentin Colombet90467682012-10-26 00:29:48 +00001035 if (CodeGenOpts.OptimizeSize == 2)
Bill Wendling72390b32012-12-20 19:27:06 +00001036 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
Chandler Carruth2811ccf2009-11-12 17:24:48 +00001037 if (CodeGenOpts.DisableRedZone)
Bill Wendling72390b32012-12-20 19:27:06 +00001038 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruth2811ccf2009-11-12 17:24:48 +00001039 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling72390b32012-12-20 19:27:06 +00001040 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Devang Patel24095da2009-06-04 23:32:02 +00001041
Bill Wendling93e4bff2013-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 Wendlingbe9e8bf2013-02-28 22:49:57 +00001046 } else {
1047 // Attributes that should go on the function, but not the call site.
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001048 if (!CodeGenOpts.DisableFPElim) {
Bill Wendling4159f052013-03-13 22:24:33 +00001049 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001050 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendling4159f052013-03-13 22:24:33 +00001051 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendlingfae228b2013-08-22 21:16:51 +00001052 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001053 } else {
Bill Wendling4159f052013-03-13 22:24:33 +00001054 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendlingfae228b2013-08-22 21:16:51 +00001055 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001056 }
1057
Bill Wendling4159f052013-03-13 22:24:33 +00001058 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001059 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendling4159f052013-03-13 22:24:33 +00001060 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001061 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendling4159f052013-03-13 22:24:33 +00001062 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001063 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendling4159f052013-03-13 22:24:33 +00001064 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001065 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendling4159f052013-03-13 22:24:33 +00001066 FuncAttrs.addAttribute("use-soft-float",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001067 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendling45ccf282013-07-22 20:15:41 +00001068 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling8d230b42013-07-12 22:26:07 +00001069 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlingcab4a092013-07-25 00:32:41 +00001070
Bill Wendling1cf9ab82013-08-01 21:41:02 +00001071 if (!CodeGenOpts.StackRealignment)
1072 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendlingc0dcc2d2013-02-15 21:30:01 +00001073 }
1074
Daniel Dunbara0a99e02009-02-02 23:43:58 +00001075 QualType RetTy = FI.getReturnType();
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001076 unsigned Index = 1;
Daniel Dunbarb225be42009-02-03 05:59:18 +00001077 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001078 switch (RetAI.getKind()) {
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001079 case ABIArgInfo::Extend:
Jakob Stoklund Olesen5baefa82013-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 Olesen90f9ec02013-06-05 03:00:09 +00001084 // FALL THROUGH
Daniel Dunbar46327aa2009-02-03 06:17:37 +00001085 case ABIArgInfo::Direct:
Jakob Stoklund Olesen90f9ec02013-06-05 03:00:09 +00001086 if (RetAI.getInReg())
1087 RetAttrs.addAttribute(llvm::Attribute::InReg);
1088 break;
Chris Lattner800588f2010-07-29 06:26:06 +00001089 case ABIArgInfo::Ignore:
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001090 break;
1091
Rafael Espindolab48280b2012-07-31 02:44:24 +00001092 case ABIArgInfo::Indirect: {
Bill Wendling0d583392012-10-15 20:36:26 +00001093 llvm::AttrBuilder SRETAttrs;
Bill Wendling72390b32012-12-20 19:27:06 +00001094 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
Rafael Espindolab48280b2012-07-31 02:44:24 +00001095 if (RetAI.getInReg())
Bill Wendling72390b32012-12-20 19:27:06 +00001096 SRETAttrs.addAttribute(llvm::Attribute::InReg);
Bill Wendling603571a2012-10-10 07:36:56 +00001097 PAL.push_back(llvm::
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001098 AttributeSet::get(getLLVMContext(), Index, SRETAttrs));
Rafael Espindolab48280b2012-07-31 02:44:24 +00001099
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001100 ++Index;
Daniel Dunbar0ac86f02009-03-18 19:51:01 +00001101 // sret disables readnone and readonly
Bill Wendling72390b32012-12-20 19:27:06 +00001102 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1103 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001104 break;
Rafael Espindolab48280b2012-07-31 02:44:24 +00001105 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001106
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001107 case ABIArgInfo::Expand:
David Blaikieb219cfc2011-09-23 05:06:16 +00001108 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001109 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001110
Bill Wendling603571a2012-10-10 07:36:56 +00001111 if (RetAttrs.hasAttributes())
1112 PAL.push_back(llvm::
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001113 AttributeSet::get(getLLVMContext(),
1114 llvm::AttributeSet::ReturnIndex,
1115 RetAttrs));
Anton Korobeynikov1102f422009-04-04 00:49:24 +00001116
Mike Stump1eb44332009-09-09 15:08:12 +00001117 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
Daniel Dunbar88c2fa92009-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 Wendling0d583392012-10-15 20:36:26 +00001121 llvm::AttrBuilder Attrs;
Anton Korobeynikov1102f422009-04-04 00:49:24 +00001122
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00001123 if (AI.getPaddingType()) {
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001124 if (AI.getPaddingInReg())
1125 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index,
1126 llvm::Attribute::InReg));
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00001127 // Increment Index if there is padding.
1128 ++Index;
1129 }
1130
John McCalld8e10d22010-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 Dunbar7f6890e2011-02-10 18:10:07 +00001133 // sense to do it here because parameters are so messed up.
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001134 switch (AI.getKind()) {
Chris Lattner800588f2010-07-29 06:26:06 +00001135 case ABIArgInfo::Extend:
Douglas Gregor575a1c92011-05-20 16:38:50 +00001136 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling72390b32012-12-20 19:27:06 +00001137 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001138 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling72390b32012-12-20 19:27:06 +00001139 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattner800588f2010-07-29 06:26:06 +00001140 // FALL THROUGH
1141 case ABIArgInfo::Direct:
Rafael Espindolab48280b2012-07-31 02:44:24 +00001142 if (AI.getInReg())
Bill Wendling72390b32012-12-20 19:27:06 +00001143 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindolab48280b2012-07-31 02:44:24 +00001144
Chris Lattner800588f2010-07-29 06:26:06 +00001145 // FIXME: handle sseregparm someday...
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001146
Chris Lattner2acc6e32011-07-18 04:24:23 +00001147 if (llvm::StructType *STy =
Rafael Espindolab48280b2012-07-31 02:44:24 +00001148 dyn_cast<llvm::StructType>(AI.getCoerceToType())) {
1149 unsigned Extra = STy->getNumElements()-1; // 1 will be added below.
Bill Wendling603571a2012-10-10 07:36:56 +00001150 if (Attrs.hasAttributes())
Rafael Espindolab48280b2012-07-31 02:44:24 +00001151 for (unsigned I = 0; I < Extra; ++I)
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001152 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index + I,
1153 Attrs));
Rafael Espindolab48280b2012-07-31 02:44:24 +00001154 Index += Extra;
1155 }
Chris Lattner800588f2010-07-29 06:26:06 +00001156 break;
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001157
Daniel Dunbar11e383a2009-02-05 08:00:50 +00001158 case ABIArgInfo::Indirect:
Rafael Espindola0b4cc952012-10-19 05:04:37 +00001159 if (AI.getInReg())
Bill Wendling72390b32012-12-20 19:27:06 +00001160 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola0b4cc952012-10-19 05:04:37 +00001161
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001162 if (AI.getIndirectByVal())
Bill Wendling72390b32012-12-20 19:27:06 +00001163 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001164
Bill Wendling603571a2012-10-10 07:36:56 +00001165 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1166
Daniel Dunbar0ac86f02009-03-18 19:51:01 +00001167 // byval disables readnone and readonly.
Bill Wendling72390b32012-12-20 19:27:06 +00001168 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1169 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001170 break;
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001171
Daniel Dunbar11434922009-01-26 21:26:08 +00001172 case ABIArgInfo::Ignore:
1173 // Skip increment, no matching LLVM parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00001174 continue;
Daniel Dunbar11434922009-01-26 21:26:08 +00001175
Daniel Dunbar56273772008-09-17 00:51:38 +00001176 case ABIArgInfo::Expand: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001177 SmallVector<llvm::Type*, 8> types;
Mike Stumpf5408fe2009-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 Lattner9cbe4f02011-07-09 17:41:47 +00001181 getTypes().GetExpandedTypes(ParamType, types);
John McCall42e06112011-05-15 02:19:42 +00001182 Index += types.size();
Daniel Dunbar56273772008-09-17 00:51:38 +00001183 continue;
1184 }
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001185 }
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Bill Wendling603571a2012-10-10 07:36:56 +00001187 if (Attrs.hasAttributes())
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001188 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index, Attrs));
Daniel Dunbar56273772008-09-17 00:51:38 +00001189 ++Index;
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001190 }
Bill Wendling603571a2012-10-10 07:36:56 +00001191 if (FuncAttrs.hasAttributes())
Bill Wendling75d37b42012-10-15 07:31:59 +00001192 PAL.push_back(llvm::
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001193 AttributeSet::get(getLLVMContext(),
1194 llvm::AttributeSet::FunctionIndex,
1195 FuncAttrs));
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001196}
1197
John McCalld26bc762011-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 Lattner2acc6e32011-07-18 04:24:23 +00001203 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalld26bc762011-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 Dunbar88b53962009-02-02 22:03:45 +00001218void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1219 llvm::Function *Fn,
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001220 const FunctionArgList &Args) {
John McCall0cfeb632009-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 McCallf5ebf9b2013-05-03 07:33:41 +00001225 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCall0cfeb632009-07-28 01:00:58 +00001226 if (FD->hasImplicitReturnZero()) {
1227 QualType RetTy = FD->getResultType().getUnqualifiedType();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001228 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001229 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCall0cfeb632009-07-28 01:00:58 +00001230 Builder.CreateStore(Zero, ReturnValue);
1231 }
1232 }
1233
Mike Stumpf5408fe2009-05-16 07:57:57 +00001234 // FIXME: We no longer need the types from FunctionArgList; lift up and
1235 // simplify.
Daniel Dunbar5251afa2009-02-03 06:02:10 +00001236
Daniel Dunbar17b708d2008-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 Stump1eb44332009-09-09 15:08:12 +00001239
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001240 // Name the struct return argument.
Daniel Dunbardacf9dd2010-07-14 23:39:36 +00001241 if (CGM.ReturnTypeUsesSRet(FI)) {
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001242 AI->setName("agg.result");
Bill Wendling89530e42013-01-23 06:15:10 +00001243 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1244 AI->getArgNo() + 1,
1245 llvm::Attribute::NoAlias));
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001246 ++AI;
1247 }
Mike Stump1eb44332009-09-09 15:08:12 +00001248
Daniel Dunbar4b5f0a42009-02-04 21:17:21 +00001249 assert(FI.arg_size() == Args.size() &&
1250 "Mismatch between function signature & arguments.");
Devang Patel093ac462011-03-03 20:13:15 +00001251 unsigned ArgNo = 1;
Daniel Dunbarb225be42009-02-03 05:59:18 +00001252 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Devang Patel093ac462011-03-03 20:13:15 +00001253 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1254 i != e; ++i, ++info_it, ++ArgNo) {
John McCalld26bc762011-03-09 04:27:21 +00001255 const VarDecl *Arg = *i;
Daniel Dunbarb225be42009-02-03 05:59:18 +00001256 QualType Ty = info_it->type;
1257 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001258
John McCalld26bc762011-03-09 04:27:21 +00001259 bool isPromoted =
1260 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1261
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00001262 // Skip the dummy padding argument.
1263 if (ArgI.getPaddingType())
1264 ++AI;
1265
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001266 switch (ArgI.getKind()) {
Daniel Dunbar1f745982009-02-05 09:16:39 +00001267 case ABIArgInfo::Indirect: {
Chris Lattnerce700162010-06-28 23:44:11 +00001268 llvm::Value *V = AI;
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +00001269
John McCall9d232c82013-03-07 21:37:08 +00001270 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +00001271 // Aggregates and complex variables are accessed by reference. All we
1272 // need to do is realign the value, if requested
1273 if (ArgI.getIndirectRealign()) {
1274 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1275
1276 // Copy from the incoming argument pointer to the temporary with the
1277 // appropriate alignment.
1278 //
1279 // FIXME: We should have a common utility for generating an aggregate
1280 // copy.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001281 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyckfe710082011-01-19 01:58:38 +00001282 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumic95a8fc2011-03-10 14:02:21 +00001283 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1284 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1285 Builder.CreateMemCpy(Dst,
1286 Src,
Ken Dyckfe710082011-01-19 01:58:38 +00001287 llvm::ConstantInt::get(IntPtrTy,
1288 Size.getQuantity()),
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +00001289 ArgI.getIndirectAlign(),
1290 false);
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +00001291 V = AlignedTemp;
1292 }
Daniel Dunbar1f745982009-02-05 09:16:39 +00001293 } else {
1294 // Load scalar value from indirect argument.
Ken Dyckfe710082011-01-19 01:58:38 +00001295 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001296 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1297 Arg->getLocStart());
John McCalld26bc762011-03-09 04:27:21 +00001298
1299 if (isPromoted)
1300 V = emitArgumentDemotion(*this, Arg, V);
Daniel Dunbar1f745982009-02-05 09:16:39 +00001301 }
Devang Patel093ac462011-03-03 20:13:15 +00001302 EmitParmDecl(*Arg, V, ArgNo);
Daniel Dunbar1f745982009-02-05 09:16:39 +00001303 break;
1304 }
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001305
1306 case ABIArgInfo::Extend:
Daniel Dunbar46327aa2009-02-03 06:17:37 +00001307 case ABIArgInfo::Direct: {
Akira Hatanaka4ba3fd42012-01-09 19:08:06 +00001308
Chris Lattner800588f2010-07-29 06:26:06 +00001309 // If we have the trivial case, handle it with no muss and fuss.
1310 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner117e3f42010-07-30 04:02:24 +00001311 ArgI.getCoerceToType() == ConvertType(Ty) &&
1312 ArgI.getDirectOffset() == 0) {
Chris Lattner800588f2010-07-29 06:26:06 +00001313 assert(AI != Fn->arg_end() && "Argument mismatch!");
1314 llvm::Value *V = AI;
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001315
Bill Wendlinga6375562012-10-16 05:23:44 +00001316 if (Arg->getType().isRestrictQualified())
Bill Wendling89530e42013-01-23 06:15:10 +00001317 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1318 AI->getArgNo() + 1,
1319 llvm::Attribute::NoAlias));
John McCalld8e10d22010-03-27 00:47:27 +00001320
Chris Lattnerb13eab92011-07-20 06:29:00 +00001321 // Ensure the argument is the correct type.
1322 if (V->getType() != ArgI.getCoerceToType())
1323 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1324
John McCalld26bc762011-03-09 04:27:21 +00001325 if (isPromoted)
1326 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00001327
Nick Lewycky5d4a7552013-10-01 21:51:38 +00001328 if (const CXXMethodDecl *MD =
1329 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00001330 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5d4a7552013-10-01 21:51:38 +00001331 V = CGM.getCXXABI().
1332 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00001333 }
1334
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00001335 // Because of merging of function types from multiple decls it is
1336 // possible for the type of an argument to not match the corresponding
1337 // type in the function type. Since we are codegening the callee
1338 // in here, add a cast to the argument type.
1339 llvm::Type *LTy = ConvertType(Arg->getType());
1340 if (V->getType() != LTy)
1341 V = Builder.CreateBitCast(V, LTy);
1342
Devang Patel093ac462011-03-03 20:13:15 +00001343 EmitParmDecl(*Arg, V, ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +00001344 break;
Daniel Dunbar8b979d92009-02-10 00:06:49 +00001345 }
Mike Stump1eb44332009-09-09 15:08:12 +00001346
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001347 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001348
Chris Lattnerdeabde22010-07-28 18:24:28 +00001349 // The alignment we need to use is the max of the requested alignment for
1350 // the argument plus the alignment required by our access code below.
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001351 unsigned AlignmentToUse =
Micah Villmow25a6a842012-10-08 16:25:52 +00001352 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerdeabde22010-07-28 18:24:28 +00001353 AlignmentToUse = std::max(AlignmentToUse,
1354 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001355
Chris Lattnerdeabde22010-07-28 18:24:28 +00001356 Alloca->setAlignment(AlignmentToUse);
Chris Lattner121b3fa2010-07-05 20:21:00 +00001357 llvm::Value *V = Alloca;
Chris Lattner117e3f42010-07-30 04:02:24 +00001358 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001359
Chris Lattner117e3f42010-07-30 04:02:24 +00001360 // If the value is offset in memory, apply the offset now.
1361 if (unsigned Offs = ArgI.getDirectOffset()) {
1362 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1363 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001364 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner117e3f42010-07-30 04:02:24 +00001365 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1366 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001367
Chris Lattner309c59f2010-06-29 00:06:42 +00001368 // If the coerce-to type is a first class aggregate, we flatten it and
1369 // pass the elements. Either way is semantically identical, but fast-isel
1370 // and the optimizer generally likes scalar values better than FCAs.
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001371 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
1372 if (STy && STy->getNumElements() > 1) {
Micah Villmow25a6a842012-10-08 16:25:52 +00001373 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001374 llvm::Type *DstTy =
1375 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmow25a6a842012-10-08 16:25:52 +00001376 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001377
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001378 if (SrcSize <= DstSize) {
1379 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1380
1381 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1382 assert(AI != Fn->arg_end() && "Argument mismatch!");
1383 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1384 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
1385 Builder.CreateStore(AI++, EltPtr);
1386 }
1387 } else {
1388 llvm::AllocaInst *TempAlloca =
1389 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1390 TempAlloca->setAlignment(AlignmentToUse);
1391 llvm::Value *TempV = TempAlloca;
1392
1393 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1394 assert(AI != Fn->arg_end() && "Argument mismatch!");
1395 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1396 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
1397 Builder.CreateStore(AI++, EltPtr);
1398 }
1399
1400 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner309c59f2010-06-29 00:06:42 +00001401 }
1402 } else {
1403 // Simple case, just do a coerced store of the argument into the alloca.
1404 assert(AI != Fn->arg_end() && "Argument mismatch!");
Chris Lattner225e2862010-06-29 00:14:52 +00001405 AI->setName(Arg->getName() + ".coerce");
Chris Lattner117e3f42010-07-30 04:02:24 +00001406 CreateCoercedStore(AI++, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner309c59f2010-06-29 00:06:42 +00001407 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001408
1409
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001410 // Match to what EmitParmDecl is expecting for this type.
John McCall9d232c82013-03-07 21:37:08 +00001411 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001412 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
John McCalld26bc762011-03-09 04:27:21 +00001413 if (isPromoted)
1414 V = emitArgumentDemotion(*this, Arg, V);
Daniel Dunbar8b29a382009-02-04 07:22:24 +00001415 }
Devang Patel093ac462011-03-03 20:13:15 +00001416 EmitParmDecl(*Arg, V, ArgNo);
Chris Lattnerce700162010-06-28 23:44:11 +00001417 continue; // Skip ++AI increment, already done.
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001418 }
Chris Lattner800588f2010-07-29 06:26:06 +00001419
1420 case ABIArgInfo::Expand: {
1421 // If this structure was expanded into multiple arguments then
1422 // we need to create a temporary and reconstruct it from the
1423 // arguments.
Eli Friedman1bb94a42011-11-03 21:39:02 +00001424 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedman6da2c712011-12-03 04:14:32 +00001425 CharUnits Align = getContext().getDeclAlign(Arg);
1426 Alloca->setAlignment(Align.getQuantity());
1427 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Eli Friedman1bb94a42011-11-03 21:39:02 +00001428 llvm::Function::arg_iterator End = ExpandTypeFromArgs(Ty, LV, AI);
1429 EmitParmDecl(*Arg, Alloca, ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +00001430
1431 // Name the arguments used in expansion and increment AI.
1432 unsigned Index = 0;
1433 for (; AI != End; ++AI, ++Index)
Chris Lattner5f9e2722011-07-23 10:55:15 +00001434 AI->setName(Arg->getName() + "." + Twine(Index));
Chris Lattner800588f2010-07-29 06:26:06 +00001435 continue;
1436 }
1437
1438 case ABIArgInfo::Ignore:
1439 // Initialize the local variable appropriately.
John McCall9d232c82013-03-07 21:37:08 +00001440 if (!hasScalarEvaluationKind(Ty))
Devang Patel093ac462011-03-03 20:13:15 +00001441 EmitParmDecl(*Arg, CreateMemTemp(Ty), ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +00001442 else
Devang Patel093ac462011-03-03 20:13:15 +00001443 EmitParmDecl(*Arg, llvm::UndefValue::get(ConvertType(Arg->getType())),
1444 ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +00001445
1446 // Skip increment, no matching LLVM parameter.
1447 continue;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001448 }
Daniel Dunbar56273772008-09-17 00:51:38 +00001449
1450 ++AI;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001451 }
1452 assert(AI == Fn->arg_end() && "Argument mismatch!");
1453}
1454
John McCall77fe6cd2012-01-29 07:46:59 +00001455static void eraseUnusedBitCasts(llvm::Instruction *insn) {
1456 while (insn->use_empty()) {
1457 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
1458 if (!bitcast) return;
1459
1460 // This is "safe" because we would have used a ConstantExpr otherwise.
1461 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
1462 bitcast->eraseFromParent();
1463 }
1464}
1465
John McCallf85e1932011-06-15 23:02:42 +00001466/// Try to emit a fused autorelease of a return result.
1467static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1468 llvm::Value *result) {
1469 // We must be immediately followed the cast.
1470 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
1471 if (BB->empty()) return 0;
1472 if (&BB->back() != result) return 0;
1473
Chris Lattner2acc6e32011-07-18 04:24:23 +00001474 llvm::Type *resultType = result->getType();
John McCallf85e1932011-06-15 23:02:42 +00001475
1476 // result is in a BasicBlock and is therefore an Instruction.
1477 llvm::Instruction *generator = cast<llvm::Instruction>(result);
1478
Chris Lattner5f9e2722011-07-23 10:55:15 +00001479 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCallf85e1932011-06-15 23:02:42 +00001480
1481 // Look for:
1482 // %generator = bitcast %type1* %generator2 to %type2*
1483 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1484 // We would have emitted this as a constant if the operand weren't
1485 // an Instruction.
1486 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1487
1488 // Require the generator to be immediately followed by the cast.
1489 if (generator->getNextNode() != bitcast)
1490 return 0;
1491
1492 insnsToKill.push_back(bitcast);
1493 }
1494
1495 // Look for:
1496 // %generator = call i8* @objc_retain(i8* %originalResult)
1497 // or
1498 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
1499 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
1500 if (!call) return 0;
1501
1502 bool doRetainAutorelease;
1503
1504 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
1505 doRetainAutorelease = true;
1506 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
1507 .objc_retainAutoreleasedReturnValue) {
1508 doRetainAutorelease = false;
1509
John McCallf9fdcc02012-09-07 23:30:50 +00001510 // If we emitted an assembly marker for this call (and the
1511 // ARCEntrypoints field should have been set if so), go looking
1512 // for that call. If we can't find it, we can't do this
1513 // optimization. But it should always be the immediately previous
1514 // instruction, unless we needed bitcasts around the call.
1515 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
1516 llvm::Instruction *prev = call->getPrevNode();
1517 assert(prev);
1518 if (isa<llvm::BitCastInst>(prev)) {
1519 prev = prev->getPrevNode();
1520 assert(prev);
1521 }
1522 assert(isa<llvm::CallInst>(prev));
1523 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
1524 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
1525 insnsToKill.push_back(prev);
1526 }
John McCallf85e1932011-06-15 23:02:42 +00001527 } else {
1528 return 0;
1529 }
1530
1531 result = call->getArgOperand(0);
1532 insnsToKill.push_back(call);
1533
1534 // Keep killing bitcasts, for sanity. Note that we no longer care
1535 // about precise ordering as long as there's exactly one use.
1536 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
1537 if (!bitcast->hasOneUse()) break;
1538 insnsToKill.push_back(bitcast);
1539 result = bitcast->getOperand(0);
1540 }
1541
1542 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001543 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCallf85e1932011-06-15 23:02:42 +00001544 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
1545 (*i)->eraseFromParent();
1546
1547 // Do the fused retain/autorelease if we were asked to.
1548 if (doRetainAutorelease)
1549 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
1550
1551 // Cast back to the result type.
1552 return CGF.Builder.CreateBitCast(result, resultType);
1553}
1554
John McCall77fe6cd2012-01-29 07:46:59 +00001555/// If this is a +1 of the value of an immutable 'self', remove it.
1556static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
1557 llvm::Value *result) {
1558 // This is only applicable to a method with an immutable 'self'.
John McCallbd9b65a2012-07-31 00:33:55 +00001559 const ObjCMethodDecl *method =
1560 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCall77fe6cd2012-01-29 07:46:59 +00001561 if (!method) return 0;
1562 const VarDecl *self = method->getSelfDecl();
1563 if (!self->getType().isConstQualified()) return 0;
1564
1565 // Look for a retain call.
1566 llvm::CallInst *retainCall =
1567 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
1568 if (!retainCall ||
1569 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
1570 return 0;
1571
1572 // Look for an ordinary load of 'self'.
1573 llvm::Value *retainedValue = retainCall->getArgOperand(0);
1574 llvm::LoadInst *load =
1575 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
1576 if (!load || load->isAtomic() || load->isVolatile() ||
1577 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
1578 return 0;
1579
1580 // Okay! Burn it all down. This relies for correctness on the
1581 // assumption that the retain is emitted as part of the return and
1582 // that thereafter everything is used "linearly".
1583 llvm::Type *resultType = result->getType();
1584 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
1585 assert(retainCall->use_empty());
1586 retainCall->eraseFromParent();
1587 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
1588
1589 return CGF.Builder.CreateBitCast(load, resultType);
1590}
1591
John McCallf85e1932011-06-15 23:02:42 +00001592/// Emit an ARC autorelease of the result of a function.
John McCall77fe6cd2012-01-29 07:46:59 +00001593///
1594/// \return the value to actually return from the function
John McCallf85e1932011-06-15 23:02:42 +00001595static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
1596 llvm::Value *result) {
John McCall77fe6cd2012-01-29 07:46:59 +00001597 // If we're returning 'self', kill the initial retain. This is a
1598 // heuristic attempt to "encourage correctness" in the really unfortunate
1599 // case where we have a return of self during a dealloc and we desperately
1600 // need to avoid the possible autorelease.
1601 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
1602 return self;
1603
John McCallf85e1932011-06-15 23:02:42 +00001604 // At -O0, try to emit a fused retain/autorelease.
1605 if (CGF.shouldUseFusedARCCalls())
1606 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
1607 return fused;
1608
1609 return CGF.EmitARCAutoreleaseReturnValue(result);
1610}
1611
John McCallf48f7962012-01-29 02:35:02 +00001612/// Heuristically search for a dominating store to the return-value slot.
1613static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
1614 // If there are multiple uses of the return-value slot, just check
1615 // for something immediately preceding the IP. Sometimes this can
1616 // happen with how we generate implicit-returns; it can also happen
1617 // with noreturn cleanups.
1618 if (!CGF.ReturnValue->hasOneUse()) {
1619 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1620 if (IP->empty()) return 0;
1621 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
1622 if (!store) return 0;
1623 if (store->getPointerOperand() != CGF.ReturnValue) return 0;
1624 assert(!store->isAtomic() && !store->isVolatile()); // see below
1625 return store;
1626 }
1627
1628 llvm::StoreInst *store =
1629 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->use_back());
1630 if (!store) return 0;
1631
1632 // These aren't actually possible for non-coerced returns, and we
1633 // only care about non-coerced returns on this code path.
1634 assert(!store->isAtomic() && !store->isVolatile());
1635
1636 // Now do a first-and-dirty dominance check: just walk up the
1637 // single-predecessors chain from the current insertion point.
1638 llvm::BasicBlock *StoreBB = store->getParent();
1639 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1640 while (IP != StoreBB) {
1641 if (!(IP = IP->getSinglePredecessor()))
1642 return 0;
1643 }
1644
1645 // Okay, the store's basic block dominates the insertion point; we
1646 // can do our thing.
1647 return store;
1648}
1649
Adrian Prantlfa6b0792013-05-02 17:30:20 +00001650void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001651 bool EmitRetDbgLoc,
1652 SourceLocation EndLoc) {
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001653 // Functions with no result always return void.
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001654 if (ReturnValue == 0) {
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001655 Builder.CreateRetVoid();
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001656 return;
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001657 }
Daniel Dunbar21fcc8f2010-06-30 21:27:58 +00001658
Dan Gohman4751a532010-07-20 20:13:52 +00001659 llvm::DebugLoc RetDbgLoc;
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001660 llvm::Value *RV = 0;
1661 QualType RetTy = FI.getReturnType();
1662 const ABIArgInfo &RetAI = FI.getReturnInfo();
1663
1664 switch (RetAI.getKind()) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001665 case ABIArgInfo::Indirect: {
John McCall9d232c82013-03-07 21:37:08 +00001666 switch (getEvaluationKind(RetTy)) {
1667 case TEK_Complex: {
1668 ComplexPairTy RT =
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001669 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
1670 EndLoc);
John McCall9d232c82013-03-07 21:37:08 +00001671 EmitStoreOfComplex(RT,
1672 MakeNaturalAlignAddrLValue(CurFn->arg_begin(), RetTy),
1673 /*isInit*/ true);
1674 break;
1675 }
1676 case TEK_Aggregate:
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001677 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall9d232c82013-03-07 21:37:08 +00001678 break;
1679 case TEK_Scalar:
1680 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
1681 MakeNaturalAlignAddrLValue(CurFn->arg_begin(), RetTy),
1682 /*isInit*/ true);
1683 break;
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001684 }
1685 break;
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001686 }
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001687
1688 case ABIArgInfo::Extend:
Chris Lattner800588f2010-07-29 06:26:06 +00001689 case ABIArgInfo::Direct:
Chris Lattner117e3f42010-07-30 04:02:24 +00001690 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
1691 RetAI.getDirectOffset() == 0) {
Chris Lattner800588f2010-07-29 06:26:06 +00001692 // The internal return value temp always will have pointer-to-return-type
1693 // type, just do a load.
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001694
John McCallf48f7962012-01-29 02:35:02 +00001695 // If there is a dominating store to ReturnValue, we can elide
1696 // the load, zap the store, and usually zap the alloca.
1697 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl7c731f52013-05-30 18:12:23 +00001698 // Reuse the debug location from the store unless there is
1699 // cleanup code to be emitted between the store and return
1700 // instruction.
1701 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantlfa6b0792013-05-02 17:30:20 +00001702 RetDbgLoc = SI->getDebugLoc();
Chris Lattner800588f2010-07-29 06:26:06 +00001703 // Get the stored value and nuke the now-dead store.
Chris Lattner800588f2010-07-29 06:26:06 +00001704 RV = SI->getValueOperand();
1705 SI->eraseFromParent();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001706
Chris Lattner800588f2010-07-29 06:26:06 +00001707 // If that was the only use of the return value, nuke it as well now.
1708 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
1709 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
1710 ReturnValue = 0;
1711 }
John McCallf48f7962012-01-29 02:35:02 +00001712
1713 // Otherwise, we have to do a simple load.
1714 } else {
1715 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner35b21b82010-06-27 01:06:27 +00001716 }
Chris Lattner800588f2010-07-29 06:26:06 +00001717 } else {
Chris Lattner117e3f42010-07-30 04:02:24 +00001718 llvm::Value *V = ReturnValue;
1719 // If the value is offset in memory, apply the offset now.
1720 if (unsigned Offs = RetAI.getDirectOffset()) {
1721 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
1722 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001723 V = Builder.CreateBitCast(V,
Chris Lattner117e3f42010-07-30 04:02:24 +00001724 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
1725 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001726
Chris Lattner117e3f42010-07-30 04:02:24 +00001727 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner35b21b82010-06-27 01:06:27 +00001728 }
John McCallf85e1932011-06-15 23:02:42 +00001729
1730 // In ARC, end functions that return a retainable type with a call
1731 // to objc_autoreleaseReturnValue.
1732 if (AutoreleaseResult) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001733 assert(getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001734 !FI.isReturnsRetained() &&
1735 RetTy->isObjCRetainableType());
1736 RV = emitAutoreleaseOfResult(*this, RV);
1737 }
1738
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001739 break;
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001740
Chris Lattner800588f2010-07-29 06:26:06 +00001741 case ABIArgInfo::Ignore:
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001742 break;
1743
1744 case ABIArgInfo::Expand:
David Blaikieb219cfc2011-09-23 05:06:16 +00001745 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001746 }
1747
Daniel Dunbar21fcc8f2010-06-30 21:27:58 +00001748 llvm::Instruction *Ret = RV ? Builder.CreateRet(RV) : Builder.CreateRetVoid();
Devang Pateld3f265d2010-07-21 18:08:50 +00001749 if (!RetDbgLoc.isUnknown())
1750 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001751}
1752
John McCall413ebdb2011-03-11 20:59:21 +00001753void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001754 const VarDecl *param,
1755 SourceLocation loc) {
John McCall27360712010-05-26 22:34:26 +00001756 // StartFunction converted the ABI-lowered parameter(s) into a
1757 // local alloca. We need to turn that into an r-value suitable
1758 // for EmitCall.
John McCall413ebdb2011-03-11 20:59:21 +00001759 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall27360712010-05-26 22:34:26 +00001760
John McCall413ebdb2011-03-11 20:59:21 +00001761 QualType type = param->getType();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001762
John McCall27360712010-05-26 22:34:26 +00001763 // For the most part, we just need to load the alloca, except:
1764 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall9d232c82013-03-07 21:37:08 +00001765 // 2) references to non-scalars are pointers directly to the aggregate.
1766 // I don't know why references to scalars are different here.
John McCall413ebdb2011-03-11 20:59:21 +00001767 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall9d232c82013-03-07 21:37:08 +00001768 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall413ebdb2011-03-11 20:59:21 +00001769 return args.add(RValue::getAggregate(local), type);
John McCall27360712010-05-26 22:34:26 +00001770
1771 // Locals which are references to scalars are represented
1772 // with allocas holding the pointer.
John McCall413ebdb2011-03-11 20:59:21 +00001773 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall27360712010-05-26 22:34:26 +00001774 }
1775
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001776 args.add(convertTempToRValue(local, type, loc), type);
John McCall27360712010-05-26 22:34:26 +00001777}
1778
John McCallf85e1932011-06-15 23:02:42 +00001779static bool isProvablyNull(llvm::Value *addr) {
1780 return isa<llvm::ConstantPointerNull>(addr);
1781}
1782
1783static bool isProvablyNonNull(llvm::Value *addr) {
1784 return isa<llvm::AllocaInst>(addr);
1785}
1786
1787/// Emit the actual writing-back of a writeback.
1788static void emitWriteback(CodeGenFunction &CGF,
1789 const CallArgList::Writeback &writeback) {
John McCallb6a60792013-03-23 02:35:54 +00001790 const LValue &srcLV = writeback.Source;
1791 llvm::Value *srcAddr = srcLV.getAddress();
John McCallf85e1932011-06-15 23:02:42 +00001792 assert(!isProvablyNull(srcAddr) &&
1793 "shouldn't have writeback for provably null argument");
1794
1795 llvm::BasicBlock *contBB = 0;
1796
1797 // If the argument wasn't provably non-null, we need to null check
1798 // before doing the store.
1799 bool provablyNonNull = isProvablyNonNull(srcAddr);
1800 if (!provablyNonNull) {
1801 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
1802 contBB = CGF.createBasicBlock("icr.done");
1803
1804 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1805 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
1806 CGF.EmitBlock(writebackBB);
1807 }
1808
1809 // Load the value to writeback.
1810 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
1811
1812 // Cast it back, in case we're writing an id to a Foo* or something.
1813 value = CGF.Builder.CreateBitCast(value,
1814 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
1815 "icr.writeback-cast");
1816
1817 // Perform the writeback.
John McCallb6a60792013-03-23 02:35:54 +00001818
1819 // If we have a "to use" value, it's something we need to emit a use
1820 // of. This has to be carefully threaded in: if it's done after the
1821 // release it's potentially undefined behavior (and the optimizer
1822 // will ignore it), and if it happens before the retain then the
1823 // optimizer could move the release there.
1824 if (writeback.ToUse) {
1825 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
1826
1827 // Retain the new value. No need to block-copy here: the block's
1828 // being passed up the stack.
1829 value = CGF.EmitARCRetainNonBlock(value);
1830
1831 // Emit the intrinsic use here.
1832 CGF.EmitARCIntrinsicUse(writeback.ToUse);
1833
1834 // Load the old value (primitively).
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001835 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCallb6a60792013-03-23 02:35:54 +00001836
1837 // Put the new value in place (primitively).
1838 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
1839
1840 // Release the old value.
1841 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
1842
1843 // Otherwise, we can just do a normal lvalue store.
1844 } else {
1845 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
1846 }
John McCallf85e1932011-06-15 23:02:42 +00001847
1848 // Jump to the continuation block.
1849 if (!provablyNonNull)
1850 CGF.EmitBlock(contBB);
1851}
1852
1853static void emitWritebacks(CodeGenFunction &CGF,
1854 const CallArgList &args) {
1855 for (CallArgList::writeback_iterator
1856 i = args.writeback_begin(), e = args.writeback_end(); i != e; ++i)
1857 emitWriteback(CGF, *i);
1858}
1859
Reid Kleckner9b601952013-06-21 12:45:15 +00001860static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
1861 const CallArgList &CallArgs) {
1862 assert(CGF.getTarget().getCXXABI().isArgumentDestroyedByCallee());
1863 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
1864 CallArgs.getCleanupsToDeactivate();
1865 // Iterate in reverse to increase the likelihood of popping the cleanup.
1866 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
1867 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
1868 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
1869 I->IsActiveIP->eraseFromParent();
1870 }
1871}
1872
John McCallb6a60792013-03-23 02:35:54 +00001873static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
1874 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
1875 if (uop->getOpcode() == UO_AddrOf)
1876 return uop->getSubExpr();
1877 return 0;
1878}
1879
John McCallf85e1932011-06-15 23:02:42 +00001880/// Emit an argument that's being passed call-by-writeback. That is,
1881/// we are passing the address of
1882static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
1883 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCallb6a60792013-03-23 02:35:54 +00001884 LValue srcLV;
1885
1886 // Make an optimistic effort to emit the address as an l-value.
1887 // This can fail if the the argument expression is more complicated.
1888 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
1889 srcLV = CGF.EmitLValue(lvExpr);
1890
1891 // Otherwise, just emit it as a scalar.
1892 } else {
1893 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
1894
1895 QualType srcAddrType =
1896 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
1897 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
1898 }
1899 llvm::Value *srcAddr = srcLV.getAddress();
John McCallf85e1932011-06-15 23:02:42 +00001900
1901 // The dest and src types don't necessarily match in LLVM terms
1902 // because of the crazy ObjC compatibility rules.
1903
Chris Lattner2acc6e32011-07-18 04:24:23 +00001904 llvm::PointerType *destType =
John McCallf85e1932011-06-15 23:02:42 +00001905 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
1906
1907 // If the address is a constant null, just pass the appropriate null.
1908 if (isProvablyNull(srcAddr)) {
1909 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
1910 CRE->getType());
1911 return;
1912 }
1913
John McCallf85e1932011-06-15 23:02:42 +00001914 // Create the temporary.
1915 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
1916 "icr.temp");
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00001917 // Loading an l-value can introduce a cleanup if the l-value is __weak,
1918 // and that cleanup will be conditional if we can't prove that the l-value
1919 // isn't null, so we need to register a dominating point so that the cleanups
1920 // system will make valid IR.
1921 CodeGenFunction::ConditionalEvaluation condEval(CGF);
1922
John McCallf85e1932011-06-15 23:02:42 +00001923 // Zero-initialize it if we're not doing a copy-initialization.
1924 bool shouldCopy = CRE->shouldCopy();
1925 if (!shouldCopy) {
1926 llvm::Value *null =
1927 llvm::ConstantPointerNull::get(
1928 cast<llvm::PointerType>(destType->getElementType()));
1929 CGF.Builder.CreateStore(null, temp);
1930 }
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00001931
John McCallf85e1932011-06-15 23:02:42 +00001932 llvm::BasicBlock *contBB = 0;
John McCallb6a60792013-03-23 02:35:54 +00001933 llvm::BasicBlock *originBB = 0;
John McCallf85e1932011-06-15 23:02:42 +00001934
1935 // If the address is *not* known to be non-null, we need to switch.
1936 llvm::Value *finalArgument;
1937
1938 bool provablyNonNull = isProvablyNonNull(srcAddr);
1939 if (provablyNonNull) {
1940 finalArgument = temp;
1941 } else {
1942 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1943
1944 finalArgument = CGF.Builder.CreateSelect(isNull,
1945 llvm::ConstantPointerNull::get(destType),
1946 temp, "icr.argument");
1947
1948 // If we need to copy, then the load has to be conditional, which
1949 // means we need control flow.
1950 if (shouldCopy) {
John McCallb6a60792013-03-23 02:35:54 +00001951 originBB = CGF.Builder.GetInsertBlock();
John McCallf85e1932011-06-15 23:02:42 +00001952 contBB = CGF.createBasicBlock("icr.cont");
1953 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
1954 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
1955 CGF.EmitBlock(copyBB);
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00001956 condEval.begin(CGF);
John McCallf85e1932011-06-15 23:02:42 +00001957 }
1958 }
1959
John McCallb6a60792013-03-23 02:35:54 +00001960 llvm::Value *valueToUse = 0;
1961
John McCallf85e1932011-06-15 23:02:42 +00001962 // Perform a copy if necessary.
1963 if (shouldCopy) {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001964 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCallf85e1932011-06-15 23:02:42 +00001965 assert(srcRV.isScalar());
1966
1967 llvm::Value *src = srcRV.getScalarVal();
1968 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
1969 "icr.cast");
1970
1971 // Use an ordinary store, not a store-to-lvalue.
1972 CGF.Builder.CreateStore(src, temp);
John McCallb6a60792013-03-23 02:35:54 +00001973
1974 // If optimization is enabled, and the value was held in a
1975 // __strong variable, we need to tell the optimizer that this
1976 // value has to stay alive until we're doing the store back.
1977 // This is because the temporary is effectively unretained,
1978 // and so otherwise we can violate the high-level semantics.
1979 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
1980 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
1981 valueToUse = src;
1982 }
John McCallf85e1932011-06-15 23:02:42 +00001983 }
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00001984
John McCallf85e1932011-06-15 23:02:42 +00001985 // Finish the control flow if we needed it.
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00001986 if (shouldCopy && !provablyNonNull) {
John McCallb6a60792013-03-23 02:35:54 +00001987 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCallf85e1932011-06-15 23:02:42 +00001988 CGF.EmitBlock(contBB);
John McCallb6a60792013-03-23 02:35:54 +00001989
1990 // Make a phi for the value to intrinsically use.
1991 if (valueToUse) {
1992 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
1993 "icr.to-use");
1994 phiToUse->addIncoming(valueToUse, copyBB);
1995 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
1996 originBB);
1997 valueToUse = phiToUse;
1998 }
1999
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00002000 condEval.end(CGF);
2001 }
John McCallf85e1932011-06-15 23:02:42 +00002002
John McCallb6a60792013-03-23 02:35:54 +00002003 args.addWriteback(srcLV, temp, valueToUse);
John McCallf85e1932011-06-15 23:02:42 +00002004 args.add(RValue::get(finalArgument), CRE->getType());
2005}
2006
John McCall413ebdb2011-03-11 20:59:21 +00002007void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2008 QualType type) {
John McCallf85e1932011-06-15 23:02:42 +00002009 if (const ObjCIndirectCopyRestoreExpr *CRE
2010 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith7edf9e32012-11-01 22:30:59 +00002011 assert(getLangOpts().ObjCAutoRefCount);
John McCallf85e1932011-06-15 23:02:42 +00002012 assert(getContext().hasSameType(E->getType(), type));
2013 return emitWritebackArg(*this, args, CRE);
2014 }
2015
John McCall8affed52011-08-26 18:42:59 +00002016 assert(type->isReferenceType() == E->isGLValue() &&
2017 "reference binding to unmaterialized r-value!");
2018
John McCallcec52f02011-08-26 21:08:13 +00002019 if (E->isGLValue()) {
2020 assert(E->getObjectKind() == OK_Ordinary);
Richard Smithd4ec5622013-06-12 23:38:09 +00002021 return args.add(EmitReferenceBindingToExpr(E), type);
John McCallcec52f02011-08-26 21:08:13 +00002022 }
Mike Stump1eb44332009-09-09 15:08:12 +00002023
Reid Kleckner9b601952013-06-21 12:45:15 +00002024 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2025
2026 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2027 // However, we still have to push an EH-only cleanup in case we unwind before
2028 // we make it to the call.
2029 if (HasAggregateEvalKind &&
2030 CGM.getTarget().getCXXABI().isArgumentDestroyedByCallee()) {
2031 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2032 if (RD && RD->hasNonTrivialDestructor()) {
2033 AggValueSlot Slot = CreateAggTemp(type, "agg.arg.tmp");
2034 Slot.setExternallyDestructed();
2035 EmitAggExpr(E, Slot);
2036 RValue RV = Slot.asRValue();
2037 args.add(RV, type);
2038
2039 pushDestroy(EHCleanup, RV.getAggregateAddr(), type, destroyCXXObject,
2040 /*useEHCleanupForArray*/ true);
2041 // This unreachable is a temporary marker which will be removed later.
2042 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2043 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
2044 return;
2045 }
2046 }
2047
2048 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedman55d48482011-05-26 00:10:27 +00002049 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2050 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2051 assert(L.isSimple());
Eli Friedmand39083d2013-06-11 01:08:22 +00002052 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2053 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2054 } else {
2055 // We can't represent a misaligned lvalue in the CallArgList, so copy
2056 // to an aligned temporary now.
2057 llvm::Value *tmp = CreateMemTemp(type);
2058 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2059 L.getAlignment());
2060 args.add(RValue::getAggregate(tmp), type);
2061 }
Eli Friedman55d48482011-05-26 00:10:27 +00002062 return;
2063 }
2064
John McCall413ebdb2011-03-11 20:59:21 +00002065 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson0139bb92009-04-08 20:47:54 +00002066}
2067
Dan Gohmanb49bd272012-02-16 00:57:37 +00002068// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2069// optimizer it can aggressively ignore unwind edges.
2070void
2071CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2072 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2073 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2074 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2075 CGM.getNoObjCARCExceptionsMetadata());
2076}
2077
John McCallbd7370a2013-02-28 19:01:20 +00002078/// Emits a call to the given no-arguments nounwind runtime function.
2079llvm::CallInst *
2080CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2081 const llvm::Twine &name) {
2082 return EmitNounwindRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2083}
2084
2085/// Emits a call to the given nounwind runtime function.
2086llvm::CallInst *
2087CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2088 ArrayRef<llvm::Value*> args,
2089 const llvm::Twine &name) {
2090 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2091 call->setDoesNotThrow();
2092 return call;
2093}
2094
2095/// Emits a simple call (never an invoke) to the given no-arguments
2096/// runtime function.
2097llvm::CallInst *
2098CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2099 const llvm::Twine &name) {
2100 return EmitRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2101}
2102
2103/// Emits a simple call (never an invoke) to the given runtime
2104/// function.
2105llvm::CallInst *
2106CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2107 ArrayRef<llvm::Value*> args,
2108 const llvm::Twine &name) {
2109 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2110 call->setCallingConv(getRuntimeCC());
2111 return call;
2112}
2113
2114/// Emits a call or invoke to the given noreturn runtime function.
2115void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2116 ArrayRef<llvm::Value*> args) {
2117 if (getInvokeDest()) {
2118 llvm::InvokeInst *invoke =
2119 Builder.CreateInvoke(callee,
2120 getUnreachableBlock(),
2121 getInvokeDest(),
2122 args);
2123 invoke->setDoesNotReturn();
2124 invoke->setCallingConv(getRuntimeCC());
2125 } else {
2126 llvm::CallInst *call = Builder.CreateCall(callee, args);
2127 call->setDoesNotReturn();
2128 call->setCallingConv(getRuntimeCC());
2129 Builder.CreateUnreachable();
2130 }
2131}
2132
2133/// Emits a call or invoke instruction to the given nullary runtime
2134/// function.
2135llvm::CallSite
2136CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2137 const Twine &name) {
2138 return EmitRuntimeCallOrInvoke(callee, ArrayRef<llvm::Value*>(), name);
2139}
2140
2141/// Emits a call or invoke instruction to the given runtime function.
2142llvm::CallSite
2143CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2144 ArrayRef<llvm::Value*> args,
2145 const Twine &name) {
2146 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2147 callSite.setCallingConv(getRuntimeCC());
2148 return callSite;
2149}
2150
2151llvm::CallSite
2152CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2153 const Twine &Name) {
2154 return EmitCallOrInvoke(Callee, ArrayRef<llvm::Value *>(), Name);
2155}
2156
John McCallf1549f62010-07-06 01:34:17 +00002157/// Emits a call or invoke instruction to the given function, depending
2158/// on the current state of the EH stack.
2159llvm::CallSite
2160CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +00002161 ArrayRef<llvm::Value *> Args,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002162 const Twine &Name) {
John McCallf1549f62010-07-06 01:34:17 +00002163 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallf1549f62010-07-06 01:34:17 +00002164
Dan Gohmanb49bd272012-02-16 00:57:37 +00002165 llvm::Instruction *Inst;
2166 if (!InvokeDest)
2167 Inst = Builder.CreateCall(Callee, Args, Name);
2168 else {
2169 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2170 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2171 EmitBlock(ContBB);
2172 }
2173
2174 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2175 // optimizer it can aggressively ignore unwind edges.
David Blaikie4e4d0842012-03-11 07:00:24 +00002176 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohmanb49bd272012-02-16 00:57:37 +00002177 AddObjCARCExceptionMetadata(Inst);
2178
2179 return Inst;
John McCallf1549f62010-07-06 01:34:17 +00002180}
2181
Chris Lattner70855442011-07-12 04:46:18 +00002182static void checkArgMatches(llvm::Value *Elt, unsigned &ArgNo,
2183 llvm::FunctionType *FTy) {
2184 if (ArgNo < FTy->getNumParams())
2185 assert(Elt->getType() == FTy->getParamType(ArgNo));
2186 else
2187 assert(FTy->isVarArg());
2188 ++ArgNo;
2189}
2190
Chris Lattner811bf362011-07-12 06:29:11 +00002191void CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
Craig Topper6b9240e2013-07-05 19:34:19 +00002192 SmallVectorImpl<llvm::Value *> &Args,
Chris Lattner811bf362011-07-12 06:29:11 +00002193 llvm::FunctionType *IRFuncTy) {
Bob Wilson194f06a2011-08-03 05:58:22 +00002194 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2195 unsigned NumElts = AT->getSize().getZExtValue();
2196 QualType EltTy = AT->getElementType();
2197 llvm::Value *Addr = RV.getAggregateAddr();
2198 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
2199 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, Elt);
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002200 RValue EltRV = convertTempToRValue(EltAddr, EltTy, SourceLocation());
Bob Wilson194f06a2011-08-03 05:58:22 +00002201 ExpandTypeToArgs(EltTy, EltRV, Args, IRFuncTy);
Chris Lattner811bf362011-07-12 06:29:11 +00002202 }
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002203 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilson194f06a2011-08-03 05:58:22 +00002204 RecordDecl *RD = RT->getDecl();
2205 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
Eli Friedman377ecc72012-04-16 03:54:45 +00002206 LValue LV = MakeAddrLValue(RV.getAggregateAddr(), Ty);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002207
2208 if (RD->isUnion()) {
2209 const FieldDecl *LargestFD = 0;
2210 CharUnits UnionSize = CharUnits::Zero();
2211
2212 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2213 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00002214 const FieldDecl *FD = *i;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002215 assert(!FD->isBitField() &&
2216 "Cannot expand structure with bit-field members.");
2217 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
2218 if (UnionSize < FieldSize) {
2219 UnionSize = FieldSize;
2220 LargestFD = FD;
2221 }
2222 }
2223 if (LargestFD) {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002224 RValue FldRV = EmitRValueForField(LV, LargestFD, SourceLocation());
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002225 ExpandTypeToArgs(LargestFD->getType(), FldRV, Args, IRFuncTy);
2226 }
2227 } else {
2228 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2229 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00002230 FieldDecl *FD = *i;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002231
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002232 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002233 ExpandTypeToArgs(FD->getType(), FldRV, Args, IRFuncTy);
2234 }
Bob Wilson194f06a2011-08-03 05:58:22 +00002235 }
Eli Friedmanca3d3fc2011-11-15 02:46:03 +00002236 } else if (Ty->isAnyComplexType()) {
Bob Wilson194f06a2011-08-03 05:58:22 +00002237 ComplexPairTy CV = RV.getComplexVal();
2238 Args.push_back(CV.first);
2239 Args.push_back(CV.second);
2240 } else {
Chris Lattner811bf362011-07-12 06:29:11 +00002241 assert(RV.isScalar() &&
2242 "Unexpected non-scalar rvalue during struct expansion.");
2243
2244 // Insert a bitcast as needed.
2245 llvm::Value *V = RV.getScalarVal();
2246 if (Args.size() < IRFuncTy->getNumParams() &&
2247 V->getType() != IRFuncTy->getParamType(Args.size()))
2248 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(Args.size()));
2249
2250 Args.push_back(V);
2251 }
2252}
2253
2254
Daniel Dunbar88b53962009-02-02 22:03:45 +00002255RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002256 llvm::Value *Callee,
Anders Carlssonf3c47c92009-12-24 19:25:24 +00002257 ReturnValueSlot ReturnValue,
Daniel Dunbarc0ef9f52009-02-20 18:06:48 +00002258 const CallArgList &CallArgs,
David Chisnalldd5c98f2010-05-01 11:15:56 +00002259 const Decl *TargetDecl,
David Chisnall4b02afc2010-05-02 13:41:58 +00002260 llvm::Instruction **callOrInvoke) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00002261 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002262 SmallVector<llvm::Value*, 16> Args;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002263
2264 // Handle struct-return functions by passing a pointer to the
2265 // location that we would like to return into.
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002266 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb225be42009-02-03 05:59:18 +00002267 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002268
Chris Lattner70855442011-07-12 04:46:18 +00002269 // IRArgNo - Keep track of the argument number in the callee we're looking at.
2270 unsigned IRArgNo = 0;
2271 llvm::FunctionType *IRFuncTy =
2272 cast<llvm::FunctionType>(
2273 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump1eb44332009-09-09 15:08:12 +00002274
Chris Lattner5db7ae52009-06-13 00:26:38 +00002275 // If the call returns a temporary with struct return, create a temporary
Anders Carlssond2490a92009-12-24 20:40:36 +00002276 // alloca to hold the result, unless one is given to us.
Daniel Dunbardacf9dd2010-07-14 23:39:36 +00002277 if (CGM.ReturnTypeUsesSRet(CallInfo)) {
Anders Carlssond2490a92009-12-24 20:40:36 +00002278 llvm::Value *Value = ReturnValue.getValue();
2279 if (!Value)
Daniel Dunbar195337d2010-02-09 02:48:28 +00002280 Value = CreateMemTemp(RetTy);
Anders Carlssond2490a92009-12-24 20:40:36 +00002281 Args.push_back(Value);
Chris Lattner70855442011-07-12 04:46:18 +00002282 checkArgMatches(Value, IRArgNo, IRFuncTy);
Anders Carlssond2490a92009-12-24 20:40:36 +00002283 }
Mike Stump1eb44332009-09-09 15:08:12 +00002284
Daniel Dunbar4b5f0a42009-02-04 21:17:21 +00002285 assert(CallInfo.arg_size() == CallArgs.size() &&
2286 "Mismatch between function signature & arguments.");
Daniel Dunbarb225be42009-02-03 05:59:18 +00002287 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00002288 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Daniel Dunbarb225be42009-02-03 05:59:18 +00002289 I != E; ++I, ++info_it) {
2290 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanc6d07822011-05-02 18:05:27 +00002291 RValue RV = I->RV;
Daniel Dunbar56273772008-09-17 00:51:38 +00002292
John McCall9d232c82013-03-07 21:37:08 +00002293 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00002294
2295 // Insert a padding argument to ensure proper alignment.
2296 if (llvm::Type *PaddingType = ArgInfo.getPaddingType()) {
2297 Args.push_back(llvm::UndefValue::get(PaddingType));
2298 ++IRArgNo;
2299 }
2300
Daniel Dunbar56273772008-09-17 00:51:38 +00002301 switch (ArgInfo.getKind()) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00002302 case ABIArgInfo::Indirect: {
Daniel Dunbar1f745982009-02-05 09:16:39 +00002303 if (RV.isScalar() || RV.isComplex()) {
2304 // Make a temporary alloca to pass the argument.
Eli Friedman70cbd2a2011-06-15 18:26:32 +00002305 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2306 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
2307 AI->setAlignment(ArgInfo.getIndirectAlign());
2308 Args.push_back(AI);
John McCall9d232c82013-03-07 21:37:08 +00002309
2310 LValue argLV =
2311 MakeAddrLValue(Args.back(), I->Ty, TypeAlign);
Chris Lattner70855442011-07-12 04:46:18 +00002312
Daniel Dunbar1f745982009-02-05 09:16:39 +00002313 if (RV.isScalar())
John McCall9d232c82013-03-07 21:37:08 +00002314 EmitStoreOfScalar(RV.getScalarVal(), argLV, /*init*/ true);
Daniel Dunbar1f745982009-02-05 09:16:39 +00002315 else
John McCall9d232c82013-03-07 21:37:08 +00002316 EmitStoreOfComplex(RV.getComplexVal(), argLV, /*init*/ true);
Chris Lattner70855442011-07-12 04:46:18 +00002317
2318 // Validate argument match.
2319 checkArgMatches(AI, IRArgNo, IRFuncTy);
Daniel Dunbar1f745982009-02-05 09:16:39 +00002320 } else {
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002321 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyeid436c992013-03-10 12:59:00 +00002322 // however, we need one in three cases:
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002323 // 1. If the argument is not byval, and we are required to copy the
2324 // source. (This case doesn't occur on any common architecture.)
2325 // 2. If the argument is byval, RV is not sufficiently aligned, and
2326 // we cannot force it to be sufficiently aligned.
Guy Benyeid436c992013-03-10 12:59:00 +00002327 // 3. If the argument is byval, but RV is located in an address space
2328 // different than that of the argument (0).
Eli Friedman97cb5a42011-06-15 22:09:18 +00002329 llvm::Value *Addr = RV.getAggregateAddr();
2330 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmow25a6a842012-10-08 16:25:52 +00002331 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyeid436c992013-03-10 12:59:00 +00002332 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
2333 const unsigned ArgAddrSpace = (IRArgNo < IRFuncTy->getNumParams() ?
2334 IRFuncTy->getParamType(IRArgNo)->getPointerAddressSpace() : 0);
Eli Friedman97cb5a42011-06-15 22:09:18 +00002335 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall9d232c82013-03-07 21:37:08 +00002336 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Guy Benyeid436c992013-03-10 12:59:00 +00002337 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
2338 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002339 // Create an aligned temporary, and copy to it.
Eli Friedman97cb5a42011-06-15 22:09:18 +00002340 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2341 if (Align > AI->getAlignment())
2342 AI->setAlignment(Align);
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002343 Args.push_back(AI);
Chad Rosier649b4a12012-03-29 17:37:10 +00002344 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Chris Lattner70855442011-07-12 04:46:18 +00002345
2346 // Validate argument match.
2347 checkArgMatches(AI, IRArgNo, IRFuncTy);
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002348 } else {
2349 // Skip the extra memcpy call.
Eli Friedman97cb5a42011-06-15 22:09:18 +00002350 Args.push_back(Addr);
Chris Lattner70855442011-07-12 04:46:18 +00002351
2352 // Validate argument match.
2353 checkArgMatches(Addr, IRArgNo, IRFuncTy);
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002354 }
Daniel Dunbar1f745982009-02-05 09:16:39 +00002355 }
2356 break;
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00002357 }
Daniel Dunbar1f745982009-02-05 09:16:39 +00002358
Daniel Dunbar11434922009-01-26 21:26:08 +00002359 case ABIArgInfo::Ignore:
2360 break;
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002361
Chris Lattner800588f2010-07-29 06:26:06 +00002362 case ABIArgInfo::Extend:
2363 case ABIArgInfo::Direct: {
2364 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner117e3f42010-07-30 04:02:24 +00002365 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
2366 ArgInfo.getDirectOffset() == 0) {
Chris Lattner70855442011-07-12 04:46:18 +00002367 llvm::Value *V;
Chris Lattner800588f2010-07-29 06:26:06 +00002368 if (RV.isScalar())
Chris Lattner70855442011-07-12 04:46:18 +00002369 V = RV.getScalarVal();
Chris Lattner800588f2010-07-29 06:26:06 +00002370 else
Chris Lattner70855442011-07-12 04:46:18 +00002371 V = Builder.CreateLoad(RV.getAggregateAddr());
2372
Chris Lattner21ca1fd2011-07-12 04:53:39 +00002373 // If the argument doesn't match, perform a bitcast to coerce it. This
2374 // can happen due to trivial type mismatches.
2375 if (IRArgNo < IRFuncTy->getNumParams() &&
2376 V->getType() != IRFuncTy->getParamType(IRArgNo))
2377 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRArgNo));
Chris Lattner70855442011-07-12 04:46:18 +00002378 Args.push_back(V);
2379
Chris Lattner70855442011-07-12 04:46:18 +00002380 checkArgMatches(V, IRArgNo, IRFuncTy);
Chris Lattner800588f2010-07-29 06:26:06 +00002381 break;
2382 }
Daniel Dunbar11434922009-01-26 21:26:08 +00002383
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00002384 // FIXME: Avoid the conversion through memory if possible.
2385 llvm::Value *SrcPtr;
John McCall9d232c82013-03-07 21:37:08 +00002386 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanc6d07822011-05-02 18:05:27 +00002387 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall9d232c82013-03-07 21:37:08 +00002388 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
2389 if (RV.isScalar()) {
2390 EmitStoreOfScalar(RV.getScalarVal(), SrcLV, /*init*/ true);
2391 } else {
2392 EmitStoreOfComplex(RV.getComplexVal(), SrcLV, /*init*/ true);
2393 }
Mike Stump1eb44332009-09-09 15:08:12 +00002394 } else
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00002395 SrcPtr = RV.getAggregateAddr();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002396
Chris Lattner117e3f42010-07-30 04:02:24 +00002397 // If the value is offset in memory, apply the offset now.
2398 if (unsigned Offs = ArgInfo.getDirectOffset()) {
2399 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
2400 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002401 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner117e3f42010-07-30 04:02:24 +00002402 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
2403
2404 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002405
Chris Lattnerce700162010-06-28 23:44:11 +00002406 // If the coerce-to type is a first class aggregate, we flatten it and
2407 // pass the elements. Either way is semantically identical, but fast-isel
2408 // and the optimizer generally likes scalar values better than FCAs.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002409 if (llvm::StructType *STy =
Chris Lattner309c59f2010-06-29 00:06:42 +00002410 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType())) {
Chandler Carruthf82232c2012-10-10 11:29:08 +00002411 llvm::Type *SrcTy =
2412 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
2413 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
2414 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
2415
2416 // If the source type is smaller than the destination type of the
2417 // coerce-to logic, copy the source value into a temp alloca the size
2418 // of the destination type to allow loading all of it. The bits past
2419 // the source value are left undef.
2420 if (SrcSize < DstSize) {
2421 llvm::AllocaInst *TempAlloca
2422 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
2423 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
2424 SrcPtr = TempAlloca;
2425 } else {
2426 SrcPtr = Builder.CreateBitCast(SrcPtr,
2427 llvm::PointerType::getUnqual(STy));
2428 }
2429
Chris Lattner92826882010-07-05 20:41:41 +00002430 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2431 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerdeabde22010-07-28 18:24:28 +00002432 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
2433 // We don't know what we're loading from.
2434 LI->setAlignment(1);
2435 Args.push_back(LI);
Chris Lattner70855442011-07-12 04:46:18 +00002436
2437 // Validate argument match.
2438 checkArgMatches(LI, IRArgNo, IRFuncTy);
Chris Lattner309c59f2010-06-29 00:06:42 +00002439 }
Chris Lattnerce700162010-06-28 23:44:11 +00002440 } else {
Chris Lattner309c59f2010-06-29 00:06:42 +00002441 // In the simple case, just pass the coerced loaded value.
2442 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
2443 *this));
Chris Lattner70855442011-07-12 04:46:18 +00002444
2445 // Validate argument match.
2446 checkArgMatches(Args.back(), IRArgNo, IRFuncTy);
Chris Lattnerce700162010-06-28 23:44:11 +00002447 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002448
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00002449 break;
2450 }
2451
Daniel Dunbar56273772008-09-17 00:51:38 +00002452 case ABIArgInfo::Expand:
Chris Lattner811bf362011-07-12 06:29:11 +00002453 ExpandTypeToArgs(I->Ty, RV, Args, IRFuncTy);
Chris Lattner70855442011-07-12 04:46:18 +00002454 IRArgNo = Args.size();
Daniel Dunbar56273772008-09-17 00:51:38 +00002455 break;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002456 }
2457 }
Mike Stump1eb44332009-09-09 15:08:12 +00002458
Reid Kleckner9b601952013-06-21 12:45:15 +00002459 if (!CallArgs.getCleanupsToDeactivate().empty())
2460 deactivateArgCleanupsBeforeCall(*this, CallArgs);
2461
Chris Lattner5db7ae52009-06-13 00:26:38 +00002462 // If the callee is a bitcast of a function to a varargs pointer to function
2463 // type, check to see if we can remove the bitcast. This handles some cases
2464 // with unprototyped functions.
2465 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
2466 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002467 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
2468 llvm::FunctionType *CurFT =
Chris Lattner5db7ae52009-06-13 00:26:38 +00002469 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2acc6e32011-07-18 04:24:23 +00002470 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump1eb44332009-09-09 15:08:12 +00002471
Chris Lattner5db7ae52009-06-13 00:26:38 +00002472 if (CE->getOpcode() == llvm::Instruction::BitCast &&
2473 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattnerd6bebbf2009-06-23 01:38:41 +00002474 ActualFT->getNumParams() == CurFT->getNumParams() &&
Fariborz Jahanianc0ddef22011-03-01 17:28:13 +00002475 ActualFT->getNumParams() == Args.size() &&
2476 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner5db7ae52009-06-13 00:26:38 +00002477 bool ArgsMatch = true;
2478 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
2479 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
2480 ArgsMatch = false;
2481 break;
2482 }
Mike Stump1eb44332009-09-09 15:08:12 +00002483
Chris Lattner5db7ae52009-06-13 00:26:38 +00002484 // Strip the cast if we can get away with it. This is a nice cleanup,
2485 // but also allows us to inline the function at -O0 if it is marked
2486 // always_inline.
2487 if (ArgsMatch)
2488 Callee = CalleeF;
2489 }
2490 }
Mike Stump1eb44332009-09-09 15:08:12 +00002491
Daniel Dunbarca6408c2009-09-12 00:59:20 +00002492 unsigned CallingConv;
Devang Patel761d7f72008-09-25 21:02:23 +00002493 CodeGen::AttributeListType AttributeList;
Bill Wendling94236e72013-02-22 00:13:35 +00002494 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
2495 CallingConv, true);
Bill Wendling785b7782012-12-07 23:17:26 +00002496 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendling94236e72013-02-22 00:13:35 +00002497 AttributeList);
Mike Stump1eb44332009-09-09 15:08:12 +00002498
John McCallf1549f62010-07-06 01:34:17 +00002499 llvm::BasicBlock *InvokeDest = 0;
Bill Wendling01ad9542012-12-30 10:32:17 +00002500 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
2501 llvm::Attribute::NoUnwind))
John McCallf1549f62010-07-06 01:34:17 +00002502 InvokeDest = getInvokeDest();
2503
Daniel Dunbard14151d2009-03-02 04:32:35 +00002504 llvm::CallSite CS;
John McCallf1549f62010-07-06 01:34:17 +00002505 if (!InvokeDest) {
Jay Foad4c7d9f12011-07-15 08:37:34 +00002506 CS = Builder.CreateCall(Callee, Args);
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00002507 } else {
2508 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Jay Foad4c7d9f12011-07-15 08:37:34 +00002509 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, Args);
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00002510 EmitBlock(Cont);
Daniel Dunbarf4fe0f02009-02-20 18:54:31 +00002511 }
Chris Lattnerce933992010-06-29 16:40:28 +00002512 if (callOrInvoke)
David Chisnall4b02afc2010-05-02 13:41:58 +00002513 *callOrInvoke = CS.getInstruction();
Daniel Dunbarf4fe0f02009-02-20 18:54:31 +00002514
Daniel Dunbard14151d2009-03-02 04:32:35 +00002515 CS.setAttributes(Attrs);
Daniel Dunbarca6408c2009-09-12 00:59:20 +00002516 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbard14151d2009-03-02 04:32:35 +00002517
Dan Gohmanb49bd272012-02-16 00:57:37 +00002518 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2519 // optimizer it can aggressively ignore unwind edges.
David Blaikie4e4d0842012-03-11 07:00:24 +00002520 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohmanb49bd272012-02-16 00:57:37 +00002521 AddObjCARCExceptionMetadata(CS.getInstruction());
2522
Daniel Dunbard14151d2009-03-02 04:32:35 +00002523 // If the call doesn't return, finish the basic block and clear the
2524 // insertion point; this allows the rest of IRgen to discard
2525 // unreachable code.
2526 if (CS.doesNotReturn()) {
2527 Builder.CreateUnreachable();
2528 Builder.ClearInsertionPoint();
Mike Stump1eb44332009-09-09 15:08:12 +00002529
Mike Stumpf5408fe2009-05-16 07:57:57 +00002530 // FIXME: For now, emit a dummy basic block because expr emitters in
2531 // generally are not ready to handle emitting expressions at unreachable
2532 // points.
Daniel Dunbard14151d2009-03-02 04:32:35 +00002533 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +00002534
Daniel Dunbard14151d2009-03-02 04:32:35 +00002535 // Return a reasonable RValue.
2536 return GetUndefRValue(RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002537 }
Daniel Dunbard14151d2009-03-02 04:32:35 +00002538
2539 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerffbb15e2009-10-05 13:47:21 +00002540 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002541 CI->setName("call");
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00002542
John McCallf85e1932011-06-15 23:02:42 +00002543 // Emit any writebacks immediately. Arguably this should happen
2544 // after any return-value munging.
2545 if (CallArgs.hasWritebacks())
2546 emitWritebacks(*this, CallArgs);
2547
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00002548 switch (RetAI.getKind()) {
John McCall9d232c82013-03-07 21:37:08 +00002549 case ABIArgInfo::Indirect:
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002550 return convertTempToRValue(Args[0], RetTy, SourceLocation());
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00002551
Daniel Dunbar11434922009-01-26 21:26:08 +00002552 case ABIArgInfo::Ignore:
Daniel Dunbar0bcc5212009-02-03 06:30:17 +00002553 // If we are ignoring an argument that had a result, make sure to
2554 // construct the appropriate return value for our caller.
Daniel Dunbar13e81732009-02-05 07:09:07 +00002555 return GetUndefRValue(RetTy);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002556
Chris Lattner800588f2010-07-29 06:26:06 +00002557 case ABIArgInfo::Extend:
2558 case ABIArgInfo::Direct: {
Chris Lattner6af13f32011-07-13 03:59:32 +00002559 llvm::Type *RetIRTy = ConvertType(RetTy);
2560 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
John McCall9d232c82013-03-07 21:37:08 +00002561 switch (getEvaluationKind(RetTy)) {
2562 case TEK_Complex: {
Chris Lattner800588f2010-07-29 06:26:06 +00002563 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
2564 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
2565 return RValue::getComplex(std::make_pair(Real, Imag));
2566 }
John McCall9d232c82013-03-07 21:37:08 +00002567 case TEK_Aggregate: {
Chris Lattner800588f2010-07-29 06:26:06 +00002568 llvm::Value *DestPtr = ReturnValue.getValue();
2569 bool DestIsVolatile = ReturnValue.isVolatile();
Daniel Dunbar11434922009-01-26 21:26:08 +00002570
Chris Lattner800588f2010-07-29 06:26:06 +00002571 if (!DestPtr) {
2572 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
2573 DestIsVolatile = false;
2574 }
Eli Friedmanbadea572011-05-17 21:08:01 +00002575 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
Chris Lattner800588f2010-07-29 06:26:06 +00002576 return RValue::getAggregate(DestPtr);
2577 }
John McCall9d232c82013-03-07 21:37:08 +00002578 case TEK_Scalar: {
2579 // If the argument doesn't match, perform a bitcast to coerce it. This
2580 // can happen due to trivial type mismatches.
2581 llvm::Value *V = CI;
2582 if (V->getType() != RetIRTy)
2583 V = Builder.CreateBitCast(V, RetIRTy);
2584 return RValue::get(V);
2585 }
2586 }
2587 llvm_unreachable("bad evaluation kind");
Chris Lattner800588f2010-07-29 06:26:06 +00002588 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002589
Anders Carlssond2490a92009-12-24 20:40:36 +00002590 llvm::Value *DestPtr = ReturnValue.getValue();
2591 bool DestIsVolatile = ReturnValue.isVolatile();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002592
Anders Carlssond2490a92009-12-24 20:40:36 +00002593 if (!DestPtr) {
Daniel Dunbar195337d2010-02-09 02:48:28 +00002594 DestPtr = CreateMemTemp(RetTy, "coerce");
Anders Carlssond2490a92009-12-24 20:40:36 +00002595 DestIsVolatile = false;
2596 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002597
Chris Lattner117e3f42010-07-30 04:02:24 +00002598 // If the value is offset in memory, apply the offset now.
2599 llvm::Value *StorePtr = DestPtr;
2600 if (unsigned Offs = RetAI.getDirectOffset()) {
2601 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
2602 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002603 StorePtr = Builder.CreateBitCast(StorePtr,
Chris Lattner117e3f42010-07-30 04:02:24 +00002604 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2605 }
2606 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002607
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002608 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Daniel Dunbar639ffe42008-09-10 07:04:09 +00002609 }
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00002610
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00002611 case ABIArgInfo::Expand:
David Blaikieb219cfc2011-09-23 05:06:16 +00002612 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002613 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00002614
David Blaikieb219cfc2011-09-23 05:06:16 +00002615 llvm_unreachable("Unhandled ABIArgInfo::Kind");
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002616}
Daniel Dunbarb4094ea2009-02-10 20:44:09 +00002617
2618/* VarArg handling */
2619
2620llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
2621 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
2622}