blob: b73fdf468b198ee5bdace1208cf012db18e27e6e [file] [log] [blame]
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001//===--- CGCall.cpp - Encapsulate calling convention details --------------===//
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGCall.h"
Chris Lattnere70a0072010-06-29 16:40:28 +000016#include "ABIInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CGCXXABI.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000018#include "CodeGenFunction.h"
Daniel Dunbarc68897d2008-09-10 00:41:16 +000019#include "CodeGenModule.h"
John McCalla729c622012-02-17 03:33:10 +000020#include "TargetInfo.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000021#include "clang/AST/Decl.h"
Anders Carlssonb15b55c2009-04-03 22:48:58 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000023#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000025#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000026#include "clang/Frontend/CodeGenOptions.h"
Bill Wendling706469b2013-02-28 22:49:57 +000027#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000028#include "llvm/IR/Attributes.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000029#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/InlineAsm.h"
Reid Kleckner314ef7b2014-02-01 00:04:45 +000032#include "llvm/IR/Intrinsics.h"
Eli Friedmanf7456192011-06-15 22:09:18 +000033#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000034using namespace clang;
35using namespace CodeGen;
36
37/***/
38
John McCallab26cfa2010-02-05 21:31:56 +000039static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
40 switch (CC) {
41 default: return llvm::CallingConv::C;
42 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
43 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000044 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davisb5a214e2013-08-30 04:39:01 +000045 case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
46 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000047 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
48 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000049 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Dawn Perchik335e16b2010-09-03 01:29:35 +000050 // TODO: add support for CC_X86Pascal to llvm
John McCallab26cfa2010-02-05 21:31:56 +000051 }
52}
53
John McCall8ee376f2010-02-24 07:14:12 +000054/// Derives the 'this' type for codegen purposes, i.e. ignoring method
55/// qualification.
56/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000057static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
58 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
59 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000060}
61
John McCall8ee376f2010-02-24 07:14:12 +000062/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000063static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
64 return MD->getType()->getCanonicalTypeUnqualified()
65 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000066}
67
68/// Returns the "extra-canonicalized" return type, which discards
69/// qualifiers on the return type. Codegen doesn't care about them,
70/// and it makes ABI code a little easier to be able to assume that
71/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000072static CanQualType GetReturnType(QualType RetTy) {
73 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000074}
75
John McCall8dda7b22012-07-07 06:41:13 +000076/// Arrange the argument and result information for a value of the given
77/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000078const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000079CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000080 // When translating an unprototyped function type, always use a
81 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000082 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Reid Kleckner4982b822014-01-31 22:54:50 +000083 false, None, FTNP->getExtInfo(),
84 RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +000085}
86
John McCall8dda7b22012-07-07 06:41:13 +000087/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +000088/// type, on top of any implicit parameters already stored.
89static const CGFunctionInfo &
90arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool IsInstanceMethod,
91 SmallVectorImpl<CanQualType> &prefix,
92 CanQual<FunctionProtoType> FTP) {
John McCall8dda7b22012-07-07 06:41:13 +000093 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +000094 // FIXME: Kill copy.
Alp Toker9cacbab2014-01-20 20:26:09 +000095 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
96 prefix.push_back(FTP->getParamType(i));
Alp Toker314cc812014-01-25 16:55:45 +000097 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
Reid Kleckner4982b822014-01-31 22:54:50 +000098 return CGT.arrangeLLVMFunctionInfo(resultType, IsInstanceMethod, prefix,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +000099 FTP->getExtInfo(), required);
John McCall8ee376f2010-02-24 07:14:12 +0000100}
101
John McCalla729c622012-02-17 03:33:10 +0000102/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000103/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000104const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000105CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
John McCalla729c622012-02-17 03:33:10 +0000106 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000107 return ::arrangeLLVMFunctionInfo(*this, false, argTypes, FTP);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000108}
109
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000110static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000111 // Set the appropriate calling convention for the Function.
112 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000113 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000114
115 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000116 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000117
Douglas Gregora941dca2010-05-18 16:57:00 +0000118 if (D->hasAttr<ThisCallAttr>())
119 return CC_X86ThisCall;
120
Dawn Perchik335e16b2010-09-03 01:29:35 +0000121 if (D->hasAttr<PascalAttr>())
122 return CC_X86Pascal;
123
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000124 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
125 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
126
Derek Schuffa2020962012-10-16 22:30:41 +0000127 if (D->hasAttr<PnaclCallAttr>())
128 return CC_PnaclCall;
129
Guy Benyeif0a014b2012-12-25 08:53:55 +0000130 if (D->hasAttr<IntelOclBiccAttr>())
131 return CC_IntelOclBicc;
132
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000133 if (D->hasAttr<MSABIAttr>())
134 return IsWindows ? CC_C : CC_X86_64Win64;
135
136 if (D->hasAttr<SysVABIAttr>())
137 return IsWindows ? CC_X86_64SysV : CC_C;
138
John McCallab26cfa2010-02-05 21:31:56 +0000139 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000140}
141
James Molloy6f244b62014-05-09 16:21:39 +0000142static bool isAAPCSVFP(const CGFunctionInfo &FI, const TargetInfo &Target) {
143 switch (FI.getEffectiveCallingConvention()) {
144 case llvm::CallingConv::C:
145 switch (Target.getTriple().getEnvironment()) {
146 case llvm::Triple::EABIHF:
147 case llvm::Triple::GNUEABIHF:
148 return true;
149 default:
150 return false;
151 }
152 case llvm::CallingConv::ARM_AAPCS_VFP:
153 return true;
154 default:
155 return false;
156 }
157}
158
John McCalla729c622012-02-17 03:33:10 +0000159/// Arrange the argument and result information for a call to an
160/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000161/// (Zero value of RD means we don't have any meaningful "this" argument type,
162/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000163/// The member function must be an ordinary function, i.e. not a
164/// constructor or destructor.
165const CGFunctionInfo &
166CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
167 const FunctionProtoType *FTP) {
168 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000169
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000170 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000171 if (RD)
172 argTypes.push_back(GetThisType(Context, RD));
173 else
174 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000175
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000176 return ::arrangeLLVMFunctionInfo(
177 *this, true, argTypes,
178 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000179}
180
John McCalla729c622012-02-17 03:33:10 +0000181/// Arrange the argument and result information for a declaration or
182/// definition of the given C++ non-static member function. The
183/// member function must be an ordinary function, i.e. not a
184/// constructor or destructor.
185const CGFunctionInfo &
186CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000187 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000188 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
189
John McCalla729c622012-02-17 03:33:10 +0000190 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000191
John McCalla729c622012-02-17 03:33:10 +0000192 if (MD->isInstance()) {
193 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000194 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000195 return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
John McCalla729c622012-02-17 03:33:10 +0000196 }
197
John McCall8dda7b22012-07-07 06:41:13 +0000198 return arrangeFreeFunctionType(prototype);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000199}
200
John McCalla729c622012-02-17 03:33:10 +0000201/// Arrange the argument and result information for a declaration
202/// or definition to the given constructor variant.
203const CGFunctionInfo &
204CodeGenTypes::arrangeCXXConstructorDeclaration(const CXXConstructorDecl *D,
205 CXXCtorType ctorKind) {
206 SmallVector<CanQualType, 16> argTypes;
207 argTypes.push_back(GetThisType(Context, D->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000208
209 GlobalDecl GD(D, ctorKind);
210 CanQualType resultType =
211 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000212
John McCall5d865c322010-08-31 07:33:07 +0000213 CanQual<FunctionProtoType> FTP = GetFormalType(D);
214
215 // Add the formal parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000216 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
217 argTypes.push_back(FTP->getParamType(i));
John McCall5d865c322010-08-31 07:33:07 +0000218
Reid Kleckner89077a12013-12-17 19:46:40 +0000219 TheCXXABI.BuildConstructorSignature(D, ctorKind, resultType, argTypes);
220
221 RequiredArgs required =
222 (D->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
223
John McCall8dda7b22012-07-07 06:41:13 +0000224 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
Reid Kleckner4982b822014-01-31 22:54:50 +0000225 return arrangeLLVMFunctionInfo(resultType, true, argTypes, extInfo, required);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000226}
227
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000228/// Arrange a call to a C++ method, passing the given arguments.
229const CGFunctionInfo &
230CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
231 const CXXConstructorDecl *D,
232 CXXCtorType CtorKind,
233 unsigned ExtraArgs) {
234 // FIXME: Kill copy.
235 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000236 for (const auto &Arg : args)
237 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000238
239 CanQual<FunctionProtoType> FPT = GetFormalType(D);
240 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
241 GlobalDecl GD(D, CtorKind);
242 CanQualType ResultType =
243 TheCXXABI.HasThisReturn(GD) ? ArgTypes.front() : Context.VoidTy;
244
245 FunctionType::ExtInfo Info = FPT->getExtInfo();
246 return arrangeLLVMFunctionInfo(ResultType, true, ArgTypes, Info, Required);
247}
248
John McCalla729c622012-02-17 03:33:10 +0000249/// Arrange the argument and result information for a declaration,
250/// definition, or call to the given destructor variant. It so
251/// happens that all three cases produce the same information.
252const CGFunctionInfo &
253CodeGenTypes::arrangeCXXDestructor(const CXXDestructorDecl *D,
254 CXXDtorType dtorKind) {
255 SmallVector<CanQualType, 2> argTypes;
256 argTypes.push_back(GetThisType(Context, D->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000257
258 GlobalDecl GD(D, dtorKind);
259 CanQualType resultType =
260 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
John McCall8ee376f2010-02-24 07:14:12 +0000261
John McCalla729c622012-02-17 03:33:10 +0000262 TheCXXABI.BuildDestructorSignature(D, dtorKind, resultType, argTypes);
John McCall5d865c322010-08-31 07:33:07 +0000263
264 CanQual<FunctionProtoType> FTP = GetFormalType(D);
Alp Toker9cacbab2014-01-20 20:26:09 +0000265 assert(FTP->getNumParams() == 0 && "dtor with formal parameters");
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +0000266 assert(FTP->isVariadic() == 0 && "dtor with formal parameters");
John McCall5d865c322010-08-31 07:33:07 +0000267
John McCall8dda7b22012-07-07 06:41:13 +0000268 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
Reid Kleckner4982b822014-01-31 22:54:50 +0000269 return arrangeLLVMFunctionInfo(resultType, true, argTypes, extInfo,
John McCall8dda7b22012-07-07 06:41:13 +0000270 RequiredArgs::All);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000271}
272
John McCalla729c622012-02-17 03:33:10 +0000273/// Arrange the argument and result information for the declaration or
274/// definition of the given function.
275const CGFunctionInfo &
276CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000277 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000278 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000279 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000280
John McCall2da83a32010-02-26 00:48:12 +0000281 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000282
John McCall2da83a32010-02-26 00:48:12 +0000283 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000284
285 // When declaring a function without a prototype, always use a
286 // non-variadic type.
287 if (isa<FunctionNoProtoType>(FTy)) {
288 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Reid Kleckner4982b822014-01-31 22:54:50 +0000289 return arrangeLLVMFunctionInfo(noProto->getReturnType(), false, None,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000290 noProto->getExtInfo(), RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000291 }
292
John McCall2da83a32010-02-26 00:48:12 +0000293 assert(isa<FunctionProtoType>(FTy));
John McCall8dda7b22012-07-07 06:41:13 +0000294 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000295}
296
John McCalla729c622012-02-17 03:33:10 +0000297/// Arrange the argument and result information for the declaration or
298/// definition of an Objective-C method.
299const CGFunctionInfo &
300CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
301 // It happens that this is the same as a call with no optional
302 // arguments, except also using the formal 'self' type.
303 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
304}
305
306/// Arrange the argument and result information for the function type
307/// through which to perform a send to the given Objective-C method,
308/// using the given receiver type. The receiver type is not always
309/// the 'self' type of the method or even an Objective-C pointer type.
310/// This is *not* the right method for actually performing such a
311/// message send, due to the possibility of optional arguments.
312const CGFunctionInfo &
313CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
314 QualType receiverType) {
315 SmallVector<CanQualType, 16> argTys;
316 argTys.push_back(Context.getCanonicalParamType(receiverType));
317 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000318 // FIXME: Kill copy?
Aaron Ballman43b68be2014-03-07 17:50:17 +0000319 for (const auto *I : MD->params()) {
320 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000321 }
John McCall31168b02011-06-15 23:02:42 +0000322
323 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000324 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
325 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000326
David Blaikiebbafb8a2012-03-11 07:00:24 +0000327 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000328 MD->hasAttr<NSReturnsRetainedAttr>())
329 einfo = einfo.withProducesResult(true);
330
John McCalla729c622012-02-17 03:33:10 +0000331 RequiredArgs required =
332 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
333
Reid Kleckner4982b822014-01-31 22:54:50 +0000334 return arrangeLLVMFunctionInfo(GetReturnType(MD->getReturnType()), false,
335 argTys, einfo, required);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000336}
337
John McCalla729c622012-02-17 03:33:10 +0000338const CGFunctionInfo &
339CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000340 // FIXME: Do we need to handle ObjCMethodDecl?
341 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000342
Anders Carlsson6710c532010-02-06 02:44:09 +0000343 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
John McCalla729c622012-02-17 03:33:10 +0000344 return arrangeCXXConstructorDeclaration(CD, GD.getCtorType());
Anders Carlsson6710c532010-02-06 02:44:09 +0000345
346 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
John McCalla729c622012-02-17 03:33:10 +0000347 return arrangeCXXDestructor(DD, GD.getDtorType());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000348
John McCalla729c622012-02-17 03:33:10 +0000349 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000350}
351
John McCallc818bbb2012-12-07 07:03:17 +0000352/// Arrange a call as unto a free function, except possibly with an
353/// additional number of formal parameters considered required.
354static const CGFunctionInfo &
355arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000356 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000357 const CallArgList &args,
358 const FunctionType *fnType,
359 unsigned numExtraRequiredArgs) {
360 assert(args.size() >= numExtraRequiredArgs);
361
362 // In most cases, there are no optional arguments.
363 RequiredArgs required = RequiredArgs::All;
364
365 // If we have a variadic prototype, the required arguments are the
366 // extra prefix plus the arguments in the prototype.
367 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
368 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000369 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000370
371 // If we don't have a prototype at all, but we're supposed to
372 // explicitly use the variadic convention for unprototyped calls,
373 // treat all of the arguments as required but preserve the nominal
374 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000375 } else if (CGM.getTargetCodeGenInfo()
376 .isNoProtoCallVariadic(args,
377 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000378 required = RequiredArgs(args.size());
379 }
380
Alp Toker314cc812014-01-25 16:55:45 +0000381 return CGT.arrangeFreeFunctionCall(fnType->getReturnType(), args,
John McCallc818bbb2012-12-07 07:03:17 +0000382 fnType->getExtInfo(), required);
383}
384
John McCalla729c622012-02-17 03:33:10 +0000385/// Figure out the rules for calling a function with the given formal
386/// type using the given arguments. The arguments are necessary
387/// because the function might be unprototyped, in which case it's
388/// target-dependent in crazy ways.
389const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000390CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
391 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000392 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 0);
John McCallc818bbb2012-12-07 07:03:17 +0000393}
John McCalla729c622012-02-17 03:33:10 +0000394
John McCallc818bbb2012-12-07 07:03:17 +0000395/// A block function call is essentially a free-function call with an
396/// extra implicit argument.
397const CGFunctionInfo &
398CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
399 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000400 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1);
John McCalla729c622012-02-17 03:33:10 +0000401}
402
403const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000404CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
405 const CallArgList &args,
406 FunctionType::ExtInfo info,
407 RequiredArgs required) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000408 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000409 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000410 for (const auto &Arg : args)
411 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner4982b822014-01-31 22:54:50 +0000412 return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes,
413 info, required);
John McCall8dda7b22012-07-07 06:41:13 +0000414}
415
416/// Arrange a call to a C++ method, passing the given arguments.
417const CGFunctionInfo &
418CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
419 const FunctionProtoType *FPT,
420 RequiredArgs required) {
421 // FIXME: Kill copy.
422 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000423 for (const auto &Arg : args)
424 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
John McCall8dda7b22012-07-07 06:41:13 +0000425
426 FunctionType::ExtInfo info = FPT->getExtInfo();
Reid Kleckner4982b822014-01-31 22:54:50 +0000427 return arrangeLLVMFunctionInfo(GetReturnType(FPT->getReturnType()), true,
428 argTypes, info, required);
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000429}
430
Reid Kleckner4982b822014-01-31 22:54:50 +0000431const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
432 QualType resultType, const FunctionArgList &args,
433 const FunctionType::ExtInfo &info, bool isVariadic) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000434 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000435 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000436 for (auto Arg : args)
437 argTypes.push_back(Context.getCanonicalParamType(Arg->getType()));
John McCalla729c622012-02-17 03:33:10 +0000438
439 RequiredArgs required =
440 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
Reid Kleckner4982b822014-01-31 22:54:50 +0000441 return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes, info,
John McCall8dda7b22012-07-07 06:41:13 +0000442 required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000443}
444
John McCalla729c622012-02-17 03:33:10 +0000445const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Reid Kleckner4982b822014-01-31 22:54:50 +0000446 return arrangeLLVMFunctionInfo(getContext().VoidTy, false, None,
John McCall8dda7b22012-07-07 06:41:13 +0000447 FunctionType::ExtInfo(), RequiredArgs::All);
John McCalla738c252011-03-09 04:27:21 +0000448}
449
John McCalla729c622012-02-17 03:33:10 +0000450/// Arrange the argument and result information for an abstract value
451/// of a given function type. This is the method which all of the
452/// above functions ultimately defer to.
453const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000454CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Reid Kleckner4982b822014-01-31 22:54:50 +0000455 bool IsInstanceMethod,
John McCall8dda7b22012-07-07 06:41:13 +0000456 ArrayRef<CanQualType> argTypes,
457 FunctionType::ExtInfo info,
458 RequiredArgs required) {
John McCall2da83a32010-02-26 00:48:12 +0000459#ifndef NDEBUG
John McCalla729c622012-02-17 03:33:10 +0000460 for (ArrayRef<CanQualType>::const_iterator
461 I = argTypes.begin(), E = argTypes.end(); I != E; ++I)
John McCall2da83a32010-02-26 00:48:12 +0000462 assert(I->isCanonicalAsParam());
463#endif
464
John McCalla729c622012-02-17 03:33:10 +0000465 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCallab26cfa2010-02-05 21:31:56 +0000466
Daniel Dunbare0be8292009-02-03 00:07:12 +0000467 // Lookup or create unique function info.
468 llvm::FoldingSetNodeID ID;
Reid Kleckner4982b822014-01-31 22:54:50 +0000469 CGFunctionInfo::Profile(ID, IsInstanceMethod, info, required, resultType,
470 argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000471
Craig Topper8a13c412014-05-21 05:09:00 +0000472 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000473 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000474 if (FI)
475 return *FI;
476
John McCalla729c622012-02-17 03:33:10 +0000477 // Construct the function info. We co-allocate the ArgInfos.
Reid Kleckner4982b822014-01-31 22:54:50 +0000478 FI = CGFunctionInfo::create(CC, IsInstanceMethod, info, resultType, argTypes,
479 required);
John McCalla729c622012-02-17 03:33:10 +0000480 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000481
John McCalla729c622012-02-17 03:33:10 +0000482 bool inserted = FunctionsBeingProcessed.insert(FI); (void)inserted;
483 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000484
Daniel Dunbar313321e2009-02-03 05:31:23 +0000485 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000486 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000487
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000488 // Loop over all of the computed argument and return value info. If any of
489 // them are direct or extend without a specified coerce type, specify the
490 // default now.
John McCalla729c622012-02-17 03:33:10 +0000491 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000492 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000493 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000494
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000495 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000496 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000497 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000498
John McCalla729c622012-02-17 03:33:10 +0000499 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
500 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000501
Daniel Dunbare0be8292009-02-03 00:07:12 +0000502 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000503}
504
John McCalla729c622012-02-17 03:33:10 +0000505CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Reid Kleckner4982b822014-01-31 22:54:50 +0000506 bool IsInstanceMethod,
John McCalla729c622012-02-17 03:33:10 +0000507 const FunctionType::ExtInfo &info,
508 CanQualType resultType,
509 ArrayRef<CanQualType> argTypes,
510 RequiredArgs required) {
511 void *buffer = operator new(sizeof(CGFunctionInfo) +
512 sizeof(ArgInfo) * (argTypes.size() + 1));
513 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
514 FI->CallingConvention = llvmCC;
515 FI->EffectiveCallingConvention = llvmCC;
516 FI->ASTCallingConvention = info.getCC();
Reid Kleckner4982b822014-01-31 22:54:50 +0000517 FI->InstanceMethod = IsInstanceMethod;
John McCalla729c622012-02-17 03:33:10 +0000518 FI->NoReturn = info.getNoReturn();
519 FI->ReturnsRetained = info.getProducesResult();
520 FI->Required = required;
521 FI->HasRegParm = info.getHasRegParm();
522 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000523 FI->ArgStruct = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000524 FI->NumArgs = argTypes.size();
525 FI->getArgsBuffer()[0].type = resultType;
526 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
527 FI->getArgsBuffer()[i + 1].type = argTypes[i];
528 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000529}
530
531/***/
532
John McCall85dd2c52011-05-15 02:19:42 +0000533void CodeGenTypes::GetExpandedTypes(QualType type,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000534 SmallVectorImpl<llvm::Type*> &expandedTypes) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000535 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(type)) {
536 uint64_t NumElts = AT->getSize().getZExtValue();
537 for (uint64_t Elt = 0; Elt < NumElts; ++Elt)
538 GetExpandedTypes(AT->getElementType(), expandedTypes);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000539 } else if (const RecordType *RT = type->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000540 const RecordDecl *RD = RT->getDecl();
541 assert(!RD->hasFlexibleArrayMember() &&
542 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000543 if (RD->isUnion()) {
544 // Unions can be here only in degenerative cases - all the fields are same
545 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000546 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000547 CharUnits UnionSize = CharUnits::Zero();
548
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000549 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000550 assert(!FD->isBitField() &&
551 "Cannot expand structure with bit-field members.");
552 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
553 if (UnionSize < FieldSize) {
554 UnionSize = FieldSize;
555 LargestFD = FD;
556 }
557 }
558 if (LargestFD)
559 GetExpandedTypes(LargestFD->getType(), expandedTypes);
560 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000561 for (const auto *I : RD->fields()) {
562 assert(!I->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000563 "Cannot expand structure with bit-field members.");
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000564 GetExpandedTypes(I->getType(), expandedTypes);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000565 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000566 }
567 } else if (const ComplexType *CT = type->getAs<ComplexType>()) {
568 llvm::Type *EltTy = ConvertType(CT->getElementType());
569 expandedTypes.push_back(EltTy);
570 expandedTypes.push_back(EltTy);
571 } else
572 expandedTypes.push_back(ConvertType(type));
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000573}
574
Mike Stump11289f42009-09-09 15:08:12 +0000575llvm::Function::arg_iterator
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000576CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
577 llvm::Function::arg_iterator AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000578 assert(LV.isSimple() &&
579 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000580
Bob Wilsone826a2a2011-08-03 05:58:22 +0000581 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
582 unsigned NumElts = AT->getSize().getZExtValue();
583 QualType EltTy = AT->getElementType();
584 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000585 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, Elt);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000586 LValue LV = MakeAddrLValue(EltAddr, EltTy);
587 AI = ExpandTypeFromArgs(EltTy, LV, AI);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000588 }
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000589 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000590 RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000591 if (RD->isUnion()) {
592 // Unions can be here only in degenerative cases - all the fields are same
593 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000594 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000595 CharUnits UnionSize = CharUnits::Zero();
Bob Wilsone826a2a2011-08-03 05:58:22 +0000596
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000597 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000598 assert(!FD->isBitField() &&
599 "Cannot expand structure with bit-field members.");
600 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
601 if (UnionSize < FieldSize) {
602 UnionSize = FieldSize;
603 LargestFD = FD;
604 }
605 }
606 if (LargestFD) {
607 // FIXME: What are the right qualifiers here?
Eli Friedman7f1ff602012-04-16 03:54:45 +0000608 LValue SubLV = EmitLValueForField(LV, LargestFD);
609 AI = ExpandTypeFromArgs(LargestFD->getType(), SubLV, AI);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000610 }
611 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000612 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000613 QualType FT = FD->getType();
614
615 // FIXME: What are the right qualifiers here?
Eli Friedman7f1ff602012-04-16 03:54:45 +0000616 LValue SubLV = EmitLValueForField(LV, FD);
617 AI = ExpandTypeFromArgs(FT, SubLV, AI);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000618 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000619 }
620 } else if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
621 QualType EltTy = CT->getElementType();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000622 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Bob Wilsone826a2a2011-08-03 05:58:22 +0000623 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(RealAddr, EltTy));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000624 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Bob Wilsone826a2a2011-08-03 05:58:22 +0000625 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(ImagAddr, EltTy));
626 } else {
627 EmitStoreThroughLValue(RValue::get(AI), LV);
628 ++AI;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000629 }
630
631 return AI;
632}
633
Chris Lattner895c52b2010-06-27 06:04:18 +0000634/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000635/// accessing some number of bytes out of it, try to gep into the struct to get
636/// at its inner goodness. Dive as deep as possible without entering an element
637/// with an in-memory size smaller than DstSize.
638static llvm::Value *
Chris Lattner895c52b2010-06-27 06:04:18 +0000639EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000640 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000641 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000642 // We can't dive into a zero-element struct.
643 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000644
Chris Lattner2192fe52011-07-18 04:24:23 +0000645 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000646
Chris Lattner1cd66982010-06-27 05:56:15 +0000647 // If the first elt is at least as large as what we're looking for, or if the
648 // first element is the same size as the whole struct, we can enter it.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000649 uint64_t FirstEltSize =
Micah Villmowdd31ca12012-10-08 16:25:52 +0000650 CGF.CGM.getDataLayout().getTypeAllocSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000651 if (FirstEltSize < DstSize &&
Micah Villmowdd31ca12012-10-08 16:25:52 +0000652 FirstEltSize < CGF.CGM.getDataLayout().getTypeAllocSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000653 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000654
Chris Lattner1cd66982010-06-27 05:56:15 +0000655 // GEP into the first element.
656 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000657
Chris Lattner1cd66982010-06-27 05:56:15 +0000658 // If the first element is a struct, recurse.
Chris Lattner2192fe52011-07-18 04:24:23 +0000659 llvm::Type *SrcTy =
Chris Lattner1cd66982010-06-27 05:56:15 +0000660 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000661 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000662 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000663
664 return SrcPtr;
665}
666
Chris Lattner055097f2010-06-27 06:26:04 +0000667/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
668/// are either integers or pointers. This does a truncation of the value if it
669/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000670///
671/// This behaves as if the value were coerced through memory, so on big-endian
672/// targets the high bits are preserved in a truncation, while little-endian
673/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000674static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000675 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000676 CodeGenFunction &CGF) {
677 if (Val->getType() == Ty)
678 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000679
Chris Lattner055097f2010-06-27 06:26:04 +0000680 if (isa<llvm::PointerType>(Val->getType())) {
681 // If this is Pointer->Pointer avoid conversion to and from int.
682 if (isa<llvm::PointerType>(Ty))
683 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000684
Chris Lattner055097f2010-06-27 06:26:04 +0000685 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000686 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000687 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000688
Chris Lattner2192fe52011-07-18 04:24:23 +0000689 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000690 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000691 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000692
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000693 if (Val->getType() != DestIntTy) {
694 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
695 if (DL.isBigEndian()) {
696 // Preserve the high bits on big-endian targets.
697 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +0000698 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
699 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
700
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000701 if (SrcSize > DstSize) {
702 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
703 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
704 } else {
705 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
706 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
707 }
708 } else {
709 // Little-endian targets preserve the low bits. No shifts required.
710 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
711 }
712 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000713
Chris Lattner055097f2010-06-27 06:26:04 +0000714 if (isa<llvm::PointerType>(Ty))
715 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
716 return Val;
717}
718
Chris Lattner1cd66982010-06-27 05:56:15 +0000719
720
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000721/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
722/// a pointer to an object of type \arg Ty.
723///
724/// This safely handles the case when the src type is smaller than the
725/// destination type; in this situation the values of bits which not
726/// present in the src are undefined.
727static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000728 llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000729 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000730 llvm::Type *SrcTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000731 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000732
Chris Lattnerd200eda2010-06-28 22:51:39 +0000733 // If SrcTy and Ty are the same, just do a load.
734 if (SrcTy == Ty)
735 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000736
Micah Villmowdd31ca12012-10-08 16:25:52 +0000737 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000738
Chris Lattner2192fe52011-07-18 04:24:23 +0000739 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000740 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000741 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
742 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000743
Micah Villmowdd31ca12012-10-08 16:25:52 +0000744 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000745
Chris Lattner055097f2010-06-27 06:26:04 +0000746 // If the source and destination are integer or pointer types, just do an
747 // extension or truncation to the desired type.
748 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
749 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
750 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
751 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
752 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000753
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000754 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000755 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000756 // Generally SrcSize is never greater than DstSize, since this means we are
757 // losing bits. However, this can happen in cases where the structure has
758 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000759 //
Mike Stump18bb9282009-05-16 07:57:57 +0000760 // FIXME: Assert that we aren't truncating non-padding bits when have access
761 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000762 llvm::Value *Casted =
763 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000764 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
765 // FIXME: Use better alignment / avoid requiring aligned load.
766 Load->setAlignment(1);
767 return Load;
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000768 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000769
Chris Lattner3fcc7902010-06-27 01:06:27 +0000770 // Otherwise do coercion through memory. This is stupid, but
771 // simple.
772 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Ren84b921f2012-11-28 22:08:52 +0000773 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
774 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
775 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000776 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000777 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
778 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
779 1, false);
Chris Lattner3fcc7902010-06-27 01:06:27 +0000780 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000781}
782
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000783// Function to store a first-class aggregate into memory. We prefer to
784// store the elements rather than the aggregate to be more friendly to
785// fast-isel.
786// FIXME: Do we need to recurse here?
787static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
788 llvm::Value *DestPtr, bool DestIsVolatile,
789 bool LowAlignment) {
790 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +0000791 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000792 dyn_cast<llvm::StructType>(Val->getType())) {
793 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
794 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
795 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
796 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
797 DestIsVolatile);
798 if (LowAlignment)
799 SI->setAlignment(1);
800 }
801 } else {
Bill Wendlingf6af30f2012-03-16 21:45:12 +0000802 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
803 if (LowAlignment)
804 SI->setAlignment(1);
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000805 }
806}
807
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000808/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
809/// where the source and destination may have different types.
810///
811/// This safely handles the case when the src type is larger than the
812/// destination type; the upper bits of the src will be lost.
813static void CreateCoercedStore(llvm::Value *Src,
814 llvm::Value *DstPtr,
Anders Carlsson17490832009-12-24 20:40:36 +0000815 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000816 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000817 llvm::Type *SrcTy = Src->getType();
818 llvm::Type *DstTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000819 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +0000820 if (SrcTy == DstTy) {
821 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
822 return;
823 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000824
Micah Villmowdd31ca12012-10-08 16:25:52 +0000825 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000826
Chris Lattner2192fe52011-07-18 04:24:23 +0000827 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000828 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
829 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
830 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000831
Chris Lattner055097f2010-06-27 06:26:04 +0000832 // If the source and destination are integer or pointer types, just do an
833 // extension or truncation to the desired type.
834 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
835 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
836 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
837 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
838 return;
839 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000840
Micah Villmowdd31ca12012-10-08 16:25:52 +0000841 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000842
Daniel Dunbar313321e2009-02-03 05:31:23 +0000843 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000844 if (SrcSize <= DstSize) {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000845 llvm::Value *Casted =
846 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000847 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000848 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000849 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000850 // Otherwise do coercion through memory. This is stupid, but
851 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000852
853 // Generally SrcSize is never greater than DstSize, since this means we are
854 // losing bits. However, this can happen in cases where the structure has
855 // additional padding, for example due to a user specified alignment.
856 //
857 // FIXME: Assert that we aren't truncating non-padding bits when have access
858 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000859 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
860 CGF.Builder.CreateStore(Src, Tmp);
Manman Ren84b921f2012-11-28 22:08:52 +0000861 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
862 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
863 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000864 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000865 CGF.Builder.CreateMemCpy(DstCasted, Casted,
866 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
867 1, false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000868 }
869}
870
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000871/***/
872
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000873bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000874 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +0000875}
876
Tim Northovere77cc392014-03-29 13:28:05 +0000877bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
878 return ReturnTypeUsesSRet(FI) &&
879 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
880}
881
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000882bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
883 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
884 switch (BT->getKind()) {
885 default:
886 return false;
887 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +0000888 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000889 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +0000890 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000891 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +0000892 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000893 }
894 }
895
896 return false;
897}
898
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000899bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
900 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
901 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
902 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +0000903 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000904 }
905 }
906
907 return false;
908}
909
Chris Lattnera5f58b02011-07-09 17:41:47 +0000910llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +0000911 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
912 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +0000913}
914
Chris Lattnera5f58b02011-07-09 17:41:47 +0000915llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +0000916CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000917
918 bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted;
919 assert(Inserted && "Recursively being processed?");
920
Reid Kleckner37abaca2014-05-09 22:46:15 +0000921 bool SwapThisWithSRet = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000922 SmallVector<llvm::Type*, 8> argTypes;
Craig Topper8a13c412014-05-21 05:09:00 +0000923 llvm::Type *resultType = nullptr;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000924
John McCall85dd2c52011-05-15 02:19:42 +0000925 const ABIArgInfo &retAI = FI.getReturnInfo();
926 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +0000927 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +0000928 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +0000929
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000930 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +0000931 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +0000932 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +0000933 break;
934
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000935 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +0000936 if (retAI.getInAllocaSRet()) {
937 // sret things on win32 aren't void, they return the sret pointer.
938 QualType ret = FI.getReturnType();
939 llvm::Type *ty = ConvertType(ret);
940 unsigned addressSpace = Context.getTargetAddressSpace(ret);
941 resultType = llvm::PointerType::get(ty, addressSpace);
942 } else {
943 resultType = llvm::Type::getVoidTy(getLLVMContext());
944 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000945 break;
946
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000947 case ABIArgInfo::Indirect: {
John McCall85dd2c52011-05-15 02:19:42 +0000948 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
949 resultType = llvm::Type::getVoidTy(getLLVMContext());
950
951 QualType ret = FI.getReturnType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000952 llvm::Type *ty = ConvertType(ret);
John McCall85dd2c52011-05-15 02:19:42 +0000953 unsigned addressSpace = Context.getTargetAddressSpace(ret);
954 argTypes.push_back(llvm::PointerType::get(ty, addressSpace));
Reid Kleckner37abaca2014-05-09 22:46:15 +0000955
956 SwapThisWithSRet = retAI.isSRetAfterThis();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000957 break;
958 }
959
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000960 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +0000961 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000962 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000963 }
Mike Stump11289f42009-09-09 15:08:12 +0000964
John McCallc818bbb2012-12-07 07:03:17 +0000965 // Add in all of the required arguments.
966 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), ie;
967 if (FI.isVariadic()) {
968 ie = it + FI.getRequiredArgs().getNumRequiredArgs();
969 } else {
970 ie = FI.arg_end();
971 }
972 for (; it != ie; ++it) {
John McCall85dd2c52011-05-15 02:19:42 +0000973 const ABIArgInfo &argAI = it->info;
Mike Stump11289f42009-09-09 15:08:12 +0000974
Rafael Espindolafad28de2012-10-24 01:59:00 +0000975 // Insert a padding type to ensure proper alignment.
976 if (llvm::Type *PaddingType = argAI.getPaddingType())
977 argTypes.push_back(PaddingType);
978
John McCall85dd2c52011-05-15 02:19:42 +0000979 switch (argAI.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000980 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000981 case ABIArgInfo::InAlloca:
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000982 break;
983
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000984 case ABIArgInfo::Indirect: {
985 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +0000986 llvm::Type *LTy = ConvertTypeForMem(it->type);
John McCall85dd2c52011-05-15 02:19:42 +0000987 argTypes.push_back(LTy->getPointerTo());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000988 break;
989 }
990
991 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +0000992 case ABIArgInfo::Direct: {
Chris Lattner3dd716c2010-06-28 23:44:11 +0000993 // If the coerce-to type is a first class aggregate, flatten it. Either
994 // way is semantically identical, but fast-isel and the optimizer
995 // generally likes scalar values better than FCAs.
James Molloy6f244b62014-05-09 16:21:39 +0000996 // We cannot do this for functions using the AAPCS calling convention,
997 // as structures are treated differently by that calling convention.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000998 llvm::Type *argType = argAI.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +0000999 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
1000 if (st && !isAAPCSVFP(FI, getTarget())) {
John McCall85dd2c52011-05-15 02:19:42 +00001001 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
1002 argTypes.push_back(st->getElementType(i));
Chris Lattner3dd716c2010-06-28 23:44:11 +00001003 } else {
John McCall85dd2c52011-05-15 02:19:42 +00001004 argTypes.push_back(argType);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001005 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001006 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001007 }
Mike Stump11289f42009-09-09 15:08:12 +00001008
Daniel Dunbard3674e62008-09-11 01:48:57 +00001009 case ABIArgInfo::Expand:
Chris Lattnera5f58b02011-07-09 17:41:47 +00001010 GetExpandedTypes(it->type, argTypes);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001011 break;
1012 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001013 }
1014
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001015 // Add the inalloca struct as the last parameter type.
1016 if (llvm::StructType *ArgStruct = FI.getArgStruct())
1017 argTypes.push_back(ArgStruct->getPointerTo());
1018
Reid Kleckner37abaca2014-05-09 22:46:15 +00001019 if (SwapThisWithSRet)
1020 std::swap(argTypes[0], argTypes[1]);
1021
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001022 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1023 assert(Erased && "Not in set?");
1024
John McCalla729c622012-02-17 03:33:10 +00001025 return llvm::FunctionType::get(resultType, argTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001026}
1027
Chris Lattner2192fe52011-07-18 04:24:23 +00001028llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001029 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001030 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001031
Chris Lattner8806e322011-07-10 00:18:59 +00001032 if (!isFuncTypeConvertible(FPT))
1033 return llvm::StructType::get(getLLVMContext());
1034
1035 const CGFunctionInfo *Info;
1036 if (isa<CXXDestructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +00001037 Info = &arrangeCXXDestructor(cast<CXXDestructorDecl>(MD), GD.getDtorType());
Chris Lattner8806e322011-07-10 00:18:59 +00001038 else
John McCalla729c622012-02-17 03:33:10 +00001039 Info = &arrangeCXXMethodDeclaration(MD);
1040 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001041}
1042
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001043void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbard931a872009-02-02 22:03:45 +00001044 const Decl *TargetDecl,
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001045 AttributeListType &PAL,
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00001046 unsigned &CallingConv,
1047 bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001048 llvm::AttrBuilder FuncAttrs;
1049 llvm::AttrBuilder RetAttrs;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001050
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001051 CallingConv = FI.getEffectiveCallingConvention();
1052
John McCallab26cfa2010-02-05 21:31:56 +00001053 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001054 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001055
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001056 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001057 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001058 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001059 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001060 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001061 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001062 if (TargetDecl->hasAttr<NoReturnAttr>())
1063 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001064 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1065 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001066
1067 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCallbe349de2010-07-08 06:48:12 +00001068 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl31ad7542011-03-13 17:09:40 +00001069 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling207f0532012-12-20 19:27:06 +00001070 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith49af6292013-03-05 08:30:04 +00001071 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1072 // These attributes are not inherited by overloads.
1073 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1074 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001075 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001076 }
1077
Eric Christopherbf005ec2011-08-15 22:38:22 +00001078 // 'const' and 'pure' attribute functions are also nounwind.
1079 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001080 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1081 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001082 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001083 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1084 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001085 }
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001086 if (TargetDecl->hasAttr<MallocAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001087 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001088 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1089 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001090 }
1091
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001092 if (CodeGenOpts.OptimizeSize)
Bill Wendling207f0532012-12-20 19:27:06 +00001093 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
Quentin Colombet5ee5ca12012-10-26 00:29:48 +00001094 if (CodeGenOpts.OptimizeSize == 2)
Bill Wendling207f0532012-12-20 19:27:06 +00001095 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001096 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001097 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001098 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001099 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001100 if (CodeGenOpts.EnableSegmentedStacks &&
1101 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001102 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001103
Bill Wendling2f81db62013-02-22 20:53:29 +00001104 if (AttrOnCallSite) {
1105 // Attributes that should go on the call site only.
1106 if (!CodeGenOpts.SimplifyLibCalls)
1107 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendling706469b2013-02-28 22:49:57 +00001108 } else {
1109 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001110 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001111 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001112 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001113 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001114 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001115 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001116 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001117 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001118 }
1119
Bill Wendlingdabafea2013-03-13 22:24:33 +00001120 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001121 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001122 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001123 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001124 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001125 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001126 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001127 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001128 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001129 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001130 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001131 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001132
Bill Wendlingd8f49502013-08-01 21:41:02 +00001133 if (!CodeGenOpts.StackRealignment)
1134 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendling985d1c52013-02-15 21:30:01 +00001135 }
1136
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001137 QualType RetTy = FI.getReturnType();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001138 unsigned Index = 1;
Reid Kleckner37abaca2014-05-09 22:46:15 +00001139 bool SwapThisWithSRet = false;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001140 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001141 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001142 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001143 if (RetTy->hasSignedIntegerRepresentation())
1144 RetAttrs.addAttribute(llvm::Attribute::SExt);
1145 else if (RetTy->hasUnsignedIntegerRepresentation())
1146 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001147 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001148 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001149 if (RetAI.getInReg())
1150 RetAttrs.addAttribute(llvm::Attribute::InReg);
1151 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001152 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001153 break;
1154
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001155 case ABIArgInfo::InAlloca: {
1156 // inalloca disables readnone and readonly
1157 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1158 .removeAttribute(llvm::Attribute::ReadNone);
1159 break;
1160 }
1161
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001162 case ABIArgInfo::Indirect: {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001163 llvm::AttrBuilder SRETAttrs;
Bill Wendling207f0532012-12-20 19:27:06 +00001164 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001165 if (RetAI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001166 SRETAttrs.addAttribute(llvm::Attribute::InReg);
Reid Kleckner37abaca2014-05-09 22:46:15 +00001167 SwapThisWithSRet = RetAI.isSRetAfterThis();
1168 PAL.push_back(llvm::AttributeSet::get(
1169 getLLVMContext(), SwapThisWithSRet ? 2 : Index, SRETAttrs));
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001170
Reid Kleckner37abaca2014-05-09 22:46:15 +00001171 if (!SwapThisWithSRet)
1172 ++Index;
Daniel Dunbarc2304432009-03-18 19:51:01 +00001173 // sret disables readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001174 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1175 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001176 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001177 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001178
Daniel Dunbard3674e62008-09-11 01:48:57 +00001179 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001180 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001181 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001182
Hal Finkela2347ba2014-07-18 15:52:10 +00001183 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1184 QualType PTy = RefTy->getPointeeType();
1185 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1186 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1187 .getQuantity());
1188 else if (getContext().getTargetAddressSpace(PTy) == 0)
1189 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1190 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001191
Bill Wendlinga7912f82012-10-10 07:36:56 +00001192 if (RetAttrs.hasAttributes())
1193 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001194 AttributeSet::get(getLLVMContext(),
1195 llvm::AttributeSet::ReturnIndex,
1196 RetAttrs));
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001197
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001198 for (const auto &I : FI.arguments()) {
1199 QualType ParamType = I.type;
1200 const ABIArgInfo &AI = I.info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001201 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001202
Reid Kleckner37abaca2014-05-09 22:46:15 +00001203 // Skip over the sret parameter when it comes second. We already handled it
1204 // above.
1205 if (Index == 2 && SwapThisWithSRet)
1206 ++Index;
1207
Rafael Espindolafad28de2012-10-24 01:59:00 +00001208 if (AI.getPaddingType()) {
Bill Wendling290d9522013-01-27 02:46:53 +00001209 if (AI.getPaddingInReg())
1210 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index,
1211 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001212 // Increment Index if there is padding.
1213 ++Index;
1214 }
1215
John McCall39ec71f2010-03-27 00:47:27 +00001216 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1217 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001218 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001219 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001220 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001221 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001222 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001223 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001224 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001225 // FALL THROUGH
James Molloy6f244b62014-05-09 16:21:39 +00001226 case ABIArgInfo::Direct: {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001227 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001228 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001229
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001230 // FIXME: handle sseregparm someday...
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001231
James Molloy6f244b62014-05-09 16:21:39 +00001232 llvm::StructType *STy =
1233 dyn_cast<llvm::StructType>(AI.getCoerceToType());
1234 if (!isAAPCSVFP(FI, getTarget()) && STy) {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001235 unsigned Extra = STy->getNumElements()-1; // 1 will be added below.
Bill Wendlinga7912f82012-10-10 07:36:56 +00001236 if (Attrs.hasAttributes())
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001237 for (unsigned I = 0; I < Extra; ++I)
Bill Wendling290d9522013-01-27 02:46:53 +00001238 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index + I,
1239 Attrs));
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001240 Index += Extra;
1241 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001242 break;
James Molloy6f244b62014-05-09 16:21:39 +00001243 }
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001244 case ABIArgInfo::Indirect:
Rafael Espindola703c47f2012-10-19 05:04:37 +00001245 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001246 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001247
Anders Carlsson20759ad2009-09-16 15:53:40 +00001248 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001249 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001250
Bill Wendlinga7912f82012-10-10 07:36:56 +00001251 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1252
Daniel Dunbarc2304432009-03-18 19:51:01 +00001253 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001254 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1255 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001256 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001257
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001258 case ABIArgInfo::Ignore:
1259 // Skip increment, no matching LLVM parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001260 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001261
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001262 case ABIArgInfo::InAlloca:
1263 // inalloca disables readnone and readonly.
1264 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1265 .removeAttribute(llvm::Attribute::ReadNone);
1266 // Skip increment, no matching LLVM parameter.
1267 continue;
1268
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001269 case ABIArgInfo::Expand: {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001270 SmallVector<llvm::Type*, 8> types;
Mike Stump18bb9282009-05-16 07:57:57 +00001271 // FIXME: This is rather inefficient. Do we ever actually need to do
1272 // anything here? The result should be just reconstructed on the other
1273 // side, so extension should be a non-issue.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001274 getTypes().GetExpandedTypes(ParamType, types);
John McCall85dd2c52011-05-15 02:19:42 +00001275 Index += types.size();
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001276 continue;
1277 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001278 }
Mike Stump11289f42009-09-09 15:08:12 +00001279
Hal Finkela2347ba2014-07-18 15:52:10 +00001280 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1281 QualType PTy = RefTy->getPointeeType();
1282 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1283 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1284 .getQuantity());
1285 else if (getContext().getTargetAddressSpace(PTy) == 0)
1286 Attrs.addAttribute(llvm::Attribute::NonNull);
1287 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001288
Bill Wendlinga7912f82012-10-10 07:36:56 +00001289 if (Attrs.hasAttributes())
Bill Wendling290d9522013-01-27 02:46:53 +00001290 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index, Attrs));
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001291 ++Index;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001292 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001293
1294 // Add the inalloca attribute to the trailing inalloca parameter if present.
1295 if (FI.usesInAlloca()) {
1296 llvm::AttrBuilder Attrs;
1297 Attrs.addAttribute(llvm::Attribute::InAlloca);
1298 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index, Attrs));
1299 }
1300
Bill Wendlinga7912f82012-10-10 07:36:56 +00001301 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001302 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001303 AttributeSet::get(getLLVMContext(),
1304 llvm::AttributeSet::FunctionIndex,
1305 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001306}
1307
John McCalla738c252011-03-09 04:27:21 +00001308/// An argument came in as a promoted argument; demote it back to its
1309/// declared type.
1310static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1311 const VarDecl *var,
1312 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001313 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001314
1315 // This can happen with promotions that actually don't change the
1316 // underlying type, like the enum promotions.
1317 if (value->getType() == varType) return value;
1318
1319 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1320 && "unexpected promotion type");
1321
1322 if (isa<llvm::IntegerType>(varType))
1323 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1324
1325 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1326}
1327
Daniel Dunbard931a872009-02-02 22:03:45 +00001328void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1329 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001330 const FunctionArgList &Args) {
John McCallcaa19452009-07-28 01:00:58 +00001331 // If this is an implicit-return-zero function, go ahead and
1332 // initialize the return value. TODO: it might be nice to have
1333 // a more general mechanism for this that didn't require synthesized
1334 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001335 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001336 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00001337 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001338 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001339 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001340 Builder.CreateStore(Zero, ReturnValue);
1341 }
1342 }
1343
Mike Stump18bb9282009-05-16 07:57:57 +00001344 // FIXME: We no longer need the types from FunctionArgList; lift up and
1345 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001346
Daniel Dunbar613855c2008-09-09 23:27:19 +00001347 // Emit allocs for param decls. Give the LLVM Argument nodes names.
1348 llvm::Function::arg_iterator AI = Fn->arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00001349
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001350 // If we're using inalloca, all the memory arguments are GEPs off of the last
1351 // parameter, which is a pointer to the complete memory area.
Craig Topper8a13c412014-05-21 05:09:00 +00001352 llvm::Value *ArgStruct = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001353 if (FI.usesInAlloca()) {
1354 llvm::Function::arg_iterator EI = Fn->arg_end();
1355 --EI;
1356 ArgStruct = EI;
1357 assert(ArgStruct->getType() == FI.getArgStruct()->getPointerTo());
1358 }
1359
Reid Kleckner37abaca2014-05-09 22:46:15 +00001360 // Name the struct return parameter, which can come first or second.
1361 const ABIArgInfo &RetAI = FI.getReturnInfo();
1362 bool SwapThisWithSRet = false;
1363 if (RetAI.isIndirect()) {
1364 SwapThisWithSRet = RetAI.isSRetAfterThis();
1365 if (SwapThisWithSRet)
1366 ++AI;
Daniel Dunbar613855c2008-09-09 23:27:19 +00001367 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00001368 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001369 llvm::Attribute::NoAlias));
Reid Kleckner37abaca2014-05-09 22:46:15 +00001370 if (SwapThisWithSRet)
1371 --AI; // Go back to the beginning for 'this'.
1372 else
1373 ++AI; // Skip the sret parameter.
Daniel Dunbar613855c2008-09-09 23:27:19 +00001374 }
Mike Stump11289f42009-09-09 15:08:12 +00001375
Hal Finkel82504f02014-07-11 17:35:21 +00001376 // Get the function-level nonnull attribute if it exists.
1377 const NonNullAttr *NNAtt =
1378 CurCodeDecl ? CurCodeDecl->getAttr<NonNullAttr>() : nullptr;
1379
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001380 // Track if we received the parameter as a pointer (indirect, byval, or
1381 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
1382 // into a local alloca for us.
1383 enum ValOrPointer { HaveValue = 0, HavePointer = 1 };
Reid Kleckner8ae16272014-02-01 00:23:22 +00001384 typedef llvm::PointerIntPair<llvm::Value *, 1> ValueAndIsPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001385 SmallVector<ValueAndIsPtr, 16> ArgVals;
1386 ArgVals.reserve(Args.size());
1387
Reid Kleckner739756c2013-12-04 19:23:12 +00001388 // Create a pointer value for every parameter declaration. This usually
1389 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1390 // any cleanups or do anything that might unwind. We do that separately, so
1391 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001392 assert(FI.arg_size() == Args.size() &&
1393 "Mismatch between function signature & arguments.");
Devang Patel68a15252011-03-03 20:13:15 +00001394 unsigned ArgNo = 1;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001395 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Devang Patel68a15252011-03-03 20:13:15 +00001396 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1397 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001398 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001399 QualType Ty = info_it->type;
1400 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001401
John McCalla738c252011-03-09 04:27:21 +00001402 bool isPromoted =
1403 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1404
Rafael Espindolafad28de2012-10-24 01:59:00 +00001405 // Skip the dummy padding argument.
1406 if (ArgI.getPaddingType())
1407 ++AI;
1408
Daniel Dunbard3674e62008-09-11 01:48:57 +00001409 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001410 case ABIArgInfo::InAlloca: {
1411 llvm::Value *V = Builder.CreateStructGEP(
1412 ArgStruct, ArgI.getInAllocaFieldIndex(), Arg->getName());
1413 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
1414 continue; // Don't increment AI!
1415 }
1416
Daniel Dunbar747865a2009-02-05 09:16:39 +00001417 case ABIArgInfo::Indirect: {
Chris Lattner3dd716c2010-06-28 23:44:11 +00001418 llvm::Value *V = AI;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001419
John McCall47fb9502013-03-07 21:37:08 +00001420 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001421 // Aggregates and complex variables are accessed by reference. All we
1422 // need to do is realign the value, if requested
1423 if (ArgI.getIndirectRealign()) {
1424 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1425
1426 // Copy from the incoming argument pointer to the temporary with the
1427 // appropriate alignment.
1428 //
1429 // FIXME: We should have a common utility for generating an aggregate
1430 // copy.
Chris Lattner2192fe52011-07-18 04:24:23 +00001431 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyck705ba072011-01-19 01:58:38 +00001432 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumidd634362011-03-10 14:02:21 +00001433 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1434 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1435 Builder.CreateMemCpy(Dst,
1436 Src,
Ken Dyck705ba072011-01-19 01:58:38 +00001437 llvm::ConstantInt::get(IntPtrTy,
1438 Size.getQuantity()),
Benjamin Krameracc6b4e2010-12-30 00:13:21 +00001439 ArgI.getIndirectAlign(),
1440 false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001441 V = AlignedTemp;
1442 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001443 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001444 } else {
1445 // Load scalar value from indirect argument.
Ken Dyck705ba072011-01-19 01:58:38 +00001446 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001447 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1448 Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001449
1450 if (isPromoted)
1451 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001452 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001453 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001454 break;
1455 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001456
1457 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001458 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001459
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001460 // If we have the trivial case, handle it with no muss and fuss.
1461 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001462 ArgI.getCoerceToType() == ConvertType(Ty) &&
1463 ArgI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001464 assert(AI != Fn->arg_end() && "Argument mismatch!");
1465 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001466
Hal Finkel48d53e22014-07-19 01:41:07 +00001467 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Hal Finkel82504f02014-07-11 17:35:21 +00001468 if ((NNAtt && NNAtt->isNonNull(PVD->getFunctionScopeIndex())) ||
1469 PVD->hasAttr<NonNullAttr>())
1470 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1471 AI->getArgNo() + 1,
1472 llvm::Attribute::NonNull));
1473
Hal Finkel48d53e22014-07-19 01:41:07 +00001474 QualType OTy = PVD->getOriginalType();
1475 if (const auto *ArrTy =
1476 getContext().getAsConstantArrayType(OTy)) {
1477 // A C99 array parameter declaration with the static keyword also
1478 // indicates dereferenceability, and if the size is constant we can
1479 // use the dereferenceable attribute (which requires the size in
1480 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00001481 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00001482 QualType ETy = ArrTy->getElementType();
1483 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
1484 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
1485 ArrSize) {
1486 llvm::AttrBuilder Attrs;
1487 Attrs.addDereferenceableAttr(
1488 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
1489 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1490 AI->getArgNo() + 1, Attrs));
1491 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
1492 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1493 AI->getArgNo() + 1,
1494 llvm::Attribute::NonNull));
1495 }
1496 }
1497 } else if (const auto *ArrTy =
1498 getContext().getAsVariableArrayType(OTy)) {
1499 // For C99 VLAs with the static keyword, we don't know the size so
1500 // we can't use the dereferenceable attribute, but in addrspace(0)
1501 // we know that it must be nonnull.
1502 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
1503 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
1504 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1505 AI->getArgNo() + 1,
1506 llvm::Attribute::NonNull));
1507 }
1508 }
1509
Bill Wendling507c3512012-10-16 05:23:44 +00001510 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001511 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1512 AI->getArgNo() + 1,
1513 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00001514
Chris Lattner7369c142011-07-20 06:29:00 +00001515 // Ensure the argument is the correct type.
1516 if (V->getType() != ArgI.getCoerceToType())
1517 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1518
John McCalla738c252011-03-09 04:27:21 +00001519 if (isPromoted)
1520 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00001521
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001522 if (const CXXMethodDecl *MD =
1523 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001524 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001525 V = CGM.getCXXABI().
1526 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001527 }
1528
Rafael Espindola8778c282012-11-29 16:09:03 +00001529 // Because of merging of function types from multiple decls it is
1530 // possible for the type of an argument to not match the corresponding
1531 // type in the function type. Since we are codegening the callee
1532 // in here, add a cast to the argument type.
1533 llvm::Type *LTy = ConvertType(Arg->getType());
1534 if (V->getType() != LTy)
1535 V = Builder.CreateBitCast(V, LTy);
1536
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001537 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001538 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00001539 }
Mike Stump11289f42009-09-09 15:08:12 +00001540
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001541 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001542
Chris Lattnerff941a62010-07-28 18:24:28 +00001543 // The alignment we need to use is the max of the requested alignment for
1544 // the argument plus the alignment required by our access code below.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001545 unsigned AlignmentToUse =
Micah Villmowdd31ca12012-10-08 16:25:52 +00001546 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerff941a62010-07-28 18:24:28 +00001547 AlignmentToUse = std::max(AlignmentToUse,
1548 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001549
Chris Lattnerff941a62010-07-28 18:24:28 +00001550 Alloca->setAlignment(AlignmentToUse);
Chris Lattnerc401de92010-07-05 20:21:00 +00001551 llvm::Value *V = Alloca;
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001552 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001553
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001554 // If the value is offset in memory, apply the offset now.
1555 if (unsigned Offs = ArgI.getDirectOffset()) {
1556 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1557 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001558 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001559 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1560 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001561
Chris Lattner15ec3612010-06-29 00:06:42 +00001562 // If the coerce-to type is a first class aggregate, we flatten it and
1563 // pass the elements. Either way is semantically identical, but fast-isel
1564 // and the optimizer generally likes scalar values better than FCAs.
James Molloy6f244b62014-05-09 16:21:39 +00001565 // We cannot do this for functions using the AAPCS calling convention,
1566 // as structures are treated differently by that calling convention.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001567 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
James Molloy6f244b62014-05-09 16:21:39 +00001568 if (!isAAPCSVFP(FI, getTarget()) && STy && STy->getNumElements() > 1) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001569 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001570 llvm::Type *DstTy =
1571 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00001572 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001573
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001574 if (SrcSize <= DstSize) {
1575 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1576
1577 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1578 assert(AI != Fn->arg_end() && "Argument mismatch!");
1579 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1580 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
1581 Builder.CreateStore(AI++, EltPtr);
1582 }
1583 } else {
1584 llvm::AllocaInst *TempAlloca =
1585 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1586 TempAlloca->setAlignment(AlignmentToUse);
1587 llvm::Value *TempV = TempAlloca;
1588
1589 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1590 assert(AI != Fn->arg_end() && "Argument mismatch!");
1591 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1592 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
1593 Builder.CreateStore(AI++, EltPtr);
1594 }
1595
1596 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner15ec3612010-06-29 00:06:42 +00001597 }
1598 } else {
1599 // Simple case, just do a coerced store of the argument into the alloca.
1600 assert(AI != Fn->arg_end() && "Argument mismatch!");
Chris Lattner9e748e92010-06-29 00:14:52 +00001601 AI->setName(Arg->getName() + ".coerce");
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001602 CreateCoercedStore(AI++, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00001603 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001604
1605
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001606 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00001607 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001608 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001609 if (isPromoted)
1610 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001611 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1612 } else {
1613 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00001614 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00001615 continue; // Skip ++AI increment, already done.
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001616 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001617
1618 case ABIArgInfo::Expand: {
1619 // If this structure was expanded into multiple arguments then
1620 // we need to create a temporary and reconstruct it from the
1621 // arguments.
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001622 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedmana0544d62011-12-03 04:14:32 +00001623 CharUnits Align = getContext().getDeclAlign(Arg);
1624 Alloca->setAlignment(Align.getQuantity());
1625 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001626 llvm::Function::arg_iterator End = ExpandTypeFromArgs(Ty, LV, AI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001627 ArgVals.push_back(ValueAndIsPtr(Alloca, HavePointer));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001628
1629 // Name the arguments used in expansion and increment AI.
1630 unsigned Index = 0;
1631 for (; AI != End; ++AI, ++Index)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001632 AI->setName(Arg->getName() + "." + Twine(Index));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001633 continue;
1634 }
1635
1636 case ABIArgInfo::Ignore:
1637 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001638 if (!hasScalarEvaluationKind(Ty)) {
1639 ArgVals.push_back(ValueAndIsPtr(CreateMemTemp(Ty), HavePointer));
1640 } else {
1641 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
1642 ArgVals.push_back(ValueAndIsPtr(U, HaveValue));
1643 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001644
1645 // Skip increment, no matching LLVM parameter.
1646 continue;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001647 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001648
1649 ++AI;
Reid Kleckner37abaca2014-05-09 22:46:15 +00001650
1651 if (ArgNo == 1 && SwapThisWithSRet)
1652 ++AI; // Skip the sret parameter.
Daniel Dunbar613855c2008-09-09 23:27:19 +00001653 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001654
1655 if (FI.usesInAlloca())
1656 ++AI;
Daniel Dunbar613855c2008-09-09 23:27:19 +00001657 assert(AI == Fn->arg_end() && "Argument mismatch!");
Reid Kleckner739756c2013-12-04 19:23:12 +00001658
1659 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1660 for (int I = Args.size() - 1; I >= 0; --I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001661 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1662 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001663 } else {
1664 for (unsigned I = 0, E = Args.size(); I != E; ++I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001665 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1666 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001667 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001668}
1669
John McCallffa2c1a2012-01-29 07:46:59 +00001670static void eraseUnusedBitCasts(llvm::Instruction *insn) {
1671 while (insn->use_empty()) {
1672 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
1673 if (!bitcast) return;
1674
1675 // This is "safe" because we would have used a ConstantExpr otherwise.
1676 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
1677 bitcast->eraseFromParent();
1678 }
1679}
1680
John McCall31168b02011-06-15 23:02:42 +00001681/// Try to emit a fused autorelease of a return result.
1682static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1683 llvm::Value *result) {
1684 // We must be immediately followed the cast.
1685 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00001686 if (BB->empty()) return nullptr;
1687 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001688
Chris Lattner2192fe52011-07-18 04:24:23 +00001689 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00001690
1691 // result is in a BasicBlock and is therefore an Instruction.
1692 llvm::Instruction *generator = cast<llvm::Instruction>(result);
1693
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001694 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00001695
1696 // Look for:
1697 // %generator = bitcast %type1* %generator2 to %type2*
1698 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1699 // We would have emitted this as a constant if the operand weren't
1700 // an Instruction.
1701 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1702
1703 // Require the generator to be immediately followed by the cast.
1704 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00001705 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001706
1707 insnsToKill.push_back(bitcast);
1708 }
1709
1710 // Look for:
1711 // %generator = call i8* @objc_retain(i8* %originalResult)
1712 // or
1713 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
1714 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00001715 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001716
1717 bool doRetainAutorelease;
1718
1719 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
1720 doRetainAutorelease = true;
1721 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
1722 .objc_retainAutoreleasedReturnValue) {
1723 doRetainAutorelease = false;
1724
John McCallcfa4e9b2012-09-07 23:30:50 +00001725 // If we emitted an assembly marker for this call (and the
1726 // ARCEntrypoints field should have been set if so), go looking
1727 // for that call. If we can't find it, we can't do this
1728 // optimization. But it should always be the immediately previous
1729 // instruction, unless we needed bitcasts around the call.
1730 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
1731 llvm::Instruction *prev = call->getPrevNode();
1732 assert(prev);
1733 if (isa<llvm::BitCastInst>(prev)) {
1734 prev = prev->getPrevNode();
1735 assert(prev);
1736 }
1737 assert(isa<llvm::CallInst>(prev));
1738 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
1739 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
1740 insnsToKill.push_back(prev);
1741 }
John McCall31168b02011-06-15 23:02:42 +00001742 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00001743 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001744 }
1745
1746 result = call->getArgOperand(0);
1747 insnsToKill.push_back(call);
1748
1749 // Keep killing bitcasts, for sanity. Note that we no longer care
1750 // about precise ordering as long as there's exactly one use.
1751 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
1752 if (!bitcast->hasOneUse()) break;
1753 insnsToKill.push_back(bitcast);
1754 result = bitcast->getOperand(0);
1755 }
1756
1757 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001758 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00001759 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
1760 (*i)->eraseFromParent();
1761
1762 // Do the fused retain/autorelease if we were asked to.
1763 if (doRetainAutorelease)
1764 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
1765
1766 // Cast back to the result type.
1767 return CGF.Builder.CreateBitCast(result, resultType);
1768}
1769
John McCallffa2c1a2012-01-29 07:46:59 +00001770/// If this is a +1 of the value of an immutable 'self', remove it.
1771static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
1772 llvm::Value *result) {
1773 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00001774 const ObjCMethodDecl *method =
1775 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00001776 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001777 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00001778 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001779
1780 // Look for a retain call.
1781 llvm::CallInst *retainCall =
1782 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
1783 if (!retainCall ||
1784 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00001785 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001786
1787 // Look for an ordinary load of 'self'.
1788 llvm::Value *retainedValue = retainCall->getArgOperand(0);
1789 llvm::LoadInst *load =
1790 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
1791 if (!load || load->isAtomic() || load->isVolatile() ||
1792 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
Craig Topper8a13c412014-05-21 05:09:00 +00001793 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001794
1795 // Okay! Burn it all down. This relies for correctness on the
1796 // assumption that the retain is emitted as part of the return and
1797 // that thereafter everything is used "linearly".
1798 llvm::Type *resultType = result->getType();
1799 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
1800 assert(retainCall->use_empty());
1801 retainCall->eraseFromParent();
1802 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
1803
1804 return CGF.Builder.CreateBitCast(load, resultType);
1805}
1806
John McCall31168b02011-06-15 23:02:42 +00001807/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00001808///
1809/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00001810static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
1811 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00001812 // If we're returning 'self', kill the initial retain. This is a
1813 // heuristic attempt to "encourage correctness" in the really unfortunate
1814 // case where we have a return of self during a dealloc and we desperately
1815 // need to avoid the possible autorelease.
1816 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
1817 return self;
1818
John McCall31168b02011-06-15 23:02:42 +00001819 // At -O0, try to emit a fused retain/autorelease.
1820 if (CGF.shouldUseFusedARCCalls())
1821 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
1822 return fused;
1823
1824 return CGF.EmitARCAutoreleaseReturnValue(result);
1825}
1826
John McCall6e1c0122012-01-29 02:35:02 +00001827/// Heuristically search for a dominating store to the return-value slot.
1828static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
1829 // If there are multiple uses of the return-value slot, just check
1830 // for something immediately preceding the IP. Sometimes this can
1831 // happen with how we generate implicit-returns; it can also happen
1832 // with noreturn cleanups.
1833 if (!CGF.ReturnValue->hasOneUse()) {
1834 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00001835 if (IP->empty()) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001836 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
Craig Topper8a13c412014-05-21 05:09:00 +00001837 if (!store) return nullptr;
1838 if (store->getPointerOperand() != CGF.ReturnValue) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001839 assert(!store->isAtomic() && !store->isVolatile()); // see below
1840 return store;
1841 }
1842
1843 llvm::StoreInst *store =
Chandler Carruth4d01fff2014-03-09 03:16:50 +00001844 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00001845 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001846
1847 // These aren't actually possible for non-coerced returns, and we
1848 // only care about non-coerced returns on this code path.
1849 assert(!store->isAtomic() && !store->isVolatile());
1850
1851 // Now do a first-and-dirty dominance check: just walk up the
1852 // single-predecessors chain from the current insertion point.
1853 llvm::BasicBlock *StoreBB = store->getParent();
1854 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1855 while (IP != StoreBB) {
1856 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00001857 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001858 }
1859
1860 // Okay, the store's basic block dominates the insertion point; we
1861 // can do our thing.
1862 return store;
1863}
1864
Adrian Prantl3be10542013-05-02 17:30:20 +00001865void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001866 bool EmitRetDbgLoc,
1867 SourceLocation EndLoc) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001868 // Functions with no result always return void.
Craig Topper8a13c412014-05-21 05:09:00 +00001869 if (!ReturnValue) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001870 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00001871 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001872 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00001873
Dan Gohman481e40c2010-07-20 20:13:52 +00001874 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00001875 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00001876 QualType RetTy = FI.getReturnType();
1877 const ABIArgInfo &RetAI = FI.getReturnInfo();
1878
1879 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001880 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001881 // Aggregrates get evaluated directly into the destination. Sometimes we
1882 // need to return the sret value in a register, though.
1883 assert(hasAggregateEvaluationKind(RetTy));
1884 if (RetAI.getInAllocaSRet()) {
1885 llvm::Function::arg_iterator EI = CurFn->arg_end();
1886 --EI;
1887 llvm::Value *ArgStruct = EI;
1888 llvm::Value *SRet =
1889 Builder.CreateStructGEP(ArgStruct, RetAI.getInAllocaFieldIndex());
1890 RV = Builder.CreateLoad(SRet, "sret");
1891 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001892 break;
1893
Daniel Dunbar03816342010-08-21 02:24:36 +00001894 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00001895 auto AI = CurFn->arg_begin();
1896 if (RetAI.isSRetAfterThis())
1897 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00001898 switch (getEvaluationKind(RetTy)) {
1899 case TEK_Complex: {
1900 ComplexPairTy RT =
Nick Lewycky2d84e842013-10-02 02:29:49 +00001901 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
1902 EndLoc);
Reid Kleckner37abaca2014-05-09 22:46:15 +00001903 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00001904 /*isInit*/ true);
1905 break;
1906 }
1907 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00001908 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00001909 break;
1910 case TEK_Scalar:
1911 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Reid Kleckner37abaca2014-05-09 22:46:15 +00001912 MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00001913 /*isInit*/ true);
1914 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00001915 }
1916 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00001917 }
Chris Lattner726b3d02010-06-26 23:13:19 +00001918
1919 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001920 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001921 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
1922 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001923 // The internal return value temp always will have pointer-to-return-type
1924 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001925
John McCall6e1c0122012-01-29 02:35:02 +00001926 // If there is a dominating store to ReturnValue, we can elide
1927 // the load, zap the store, and usually zap the alloca.
1928 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00001929 // Reuse the debug location from the store unless there is
1930 // cleanup code to be emitted between the store and return
1931 // instruction.
1932 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00001933 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001934 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001935 RV = SI->getValueOperand();
1936 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001937
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001938 // If that was the only use of the return value, nuke it as well now.
1939 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
1940 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00001941 ReturnValue = nullptr;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001942 }
John McCall6e1c0122012-01-29 02:35:02 +00001943
1944 // Otherwise, we have to do a simple load.
1945 } else {
1946 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00001947 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001948 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001949 llvm::Value *V = ReturnValue;
1950 // If the value is offset in memory, apply the offset now.
1951 if (unsigned Offs = RetAI.getDirectOffset()) {
1952 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
1953 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001954 V = Builder.CreateBitCast(V,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001955 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
1956 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001957
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001958 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00001959 }
John McCall31168b02011-06-15 23:02:42 +00001960
1961 // In ARC, end functions that return a retainable type with a call
1962 // to objc_autoreleaseReturnValue.
1963 if (AutoreleaseResult) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001964 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001965 !FI.isReturnsRetained() &&
1966 RetTy->isObjCRetainableType());
1967 RV = emitAutoreleaseOfResult(*this, RV);
1968 }
1969
Chris Lattner726b3d02010-06-26 23:13:19 +00001970 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00001971
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001972 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00001973 break;
1974
1975 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001976 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00001977 }
1978
Alexey Samsonovde443c52014-08-13 00:26:40 +00001979 llvm::Instruction *Ret;
1980 if (RV) {
1981 if (SanOpts->ReturnsNonnullAttribute &&
1982 CurGD.getDecl()->hasAttr<ReturnsNonNullAttr>()) {
1983 SanitizerScope SanScope(this);
1984 llvm::Value *Cond =
1985 Builder.CreateICmpNE(RV, llvm::Constant::getNullValue(RV->getType()));
1986 llvm::Constant *StaticData[] = {
1987 EmitCheckSourceLocation(EndLoc)
1988 };
1989 EmitCheck(Cond, "nonnull_return", StaticData, ArrayRef<llvm::Value *>(),
1990 CRK_Recoverable);
1991 }
1992 Ret = Builder.CreateRet(RV);
1993 } else {
1994 Ret = Builder.CreateRetVoid();
1995 }
1996
Devang Patel65497582010-07-21 18:08:50 +00001997 if (!RetDbgLoc.isUnknown())
1998 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar613855c2008-09-09 23:27:19 +00001999}
2000
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002001static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2002 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2003 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2004}
2005
2006static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty) {
2007 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2008 // placeholders.
2009 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2010 llvm::Value *Placeholder =
2011 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2012 Placeholder = CGF.Builder.CreateLoad(Placeholder);
2013 return AggValueSlot::forAddr(Placeholder, CharUnits::Zero(),
2014 Ty.getQualifiers(),
2015 AggValueSlot::IsNotDestructed,
2016 AggValueSlot::DoesNotNeedGCBarriers,
2017 AggValueSlot::IsNotAliased);
2018}
2019
John McCall32ea9692011-03-11 20:59:21 +00002020void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002021 const VarDecl *param,
2022 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002023 // StartFunction converted the ABI-lowered parameter(s) into a
2024 // local alloca. We need to turn that into an r-value suitable
2025 // for EmitCall.
John McCall32ea9692011-03-11 20:59:21 +00002026 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002027
John McCall32ea9692011-03-11 20:59:21 +00002028 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002029
John McCall23f66262010-05-26 22:34:26 +00002030 // For the most part, we just need to load the alloca, except:
2031 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00002032 // 2) references to non-scalars are pointers directly to the aggregate.
2033 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00002034 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00002035 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00002036 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00002037
2038 // Locals which are references to scalars are represented
2039 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00002040 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00002041 }
2042
Reid Klecknerab2090d2014-07-26 01:34:32 +00002043 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2044 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002045
Nick Lewycky2d84e842013-10-02 02:29:49 +00002046 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002047}
2048
John McCall31168b02011-06-15 23:02:42 +00002049static bool isProvablyNull(llvm::Value *addr) {
2050 return isa<llvm::ConstantPointerNull>(addr);
2051}
2052
2053static bool isProvablyNonNull(llvm::Value *addr) {
2054 return isa<llvm::AllocaInst>(addr);
2055}
2056
2057/// Emit the actual writing-back of a writeback.
2058static void emitWriteback(CodeGenFunction &CGF,
2059 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002060 const LValue &srcLV = writeback.Source;
2061 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002062 assert(!isProvablyNull(srcAddr) &&
2063 "shouldn't have writeback for provably null argument");
2064
Craig Topper8a13c412014-05-21 05:09:00 +00002065 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002066
2067 // If the argument wasn't provably non-null, we need to null check
2068 // before doing the store.
2069 bool provablyNonNull = isProvablyNonNull(srcAddr);
2070 if (!provablyNonNull) {
2071 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2072 contBB = CGF.createBasicBlock("icr.done");
2073
2074 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2075 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2076 CGF.EmitBlock(writebackBB);
2077 }
2078
2079 // Load the value to writeback.
2080 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2081
2082 // Cast it back, in case we're writing an id to a Foo* or something.
2083 value = CGF.Builder.CreateBitCast(value,
2084 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
2085 "icr.writeback-cast");
2086
2087 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002088
2089 // If we have a "to use" value, it's something we need to emit a use
2090 // of. This has to be carefully threaded in: if it's done after the
2091 // release it's potentially undefined behavior (and the optimizer
2092 // will ignore it), and if it happens before the retain then the
2093 // optimizer could move the release there.
2094 if (writeback.ToUse) {
2095 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2096
2097 // Retain the new value. No need to block-copy here: the block's
2098 // being passed up the stack.
2099 value = CGF.EmitARCRetainNonBlock(value);
2100
2101 // Emit the intrinsic use here.
2102 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2103
2104 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002105 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002106
2107 // Put the new value in place (primitively).
2108 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2109
2110 // Release the old value.
2111 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2112
2113 // Otherwise, we can just do a normal lvalue store.
2114 } else {
2115 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2116 }
John McCall31168b02011-06-15 23:02:42 +00002117
2118 // Jump to the continuation block.
2119 if (!provablyNonNull)
2120 CGF.EmitBlock(contBB);
2121}
2122
2123static void emitWritebacks(CodeGenFunction &CGF,
2124 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002125 for (const auto &I : args.writebacks())
2126 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002127}
2128
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002129static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2130 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002131 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002132 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2133 CallArgs.getCleanupsToDeactivate();
2134 // Iterate in reverse to increase the likelihood of popping the cleanup.
2135 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
2136 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
2137 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
2138 I->IsActiveIP->eraseFromParent();
2139 }
2140}
2141
John McCalleff18842013-03-23 02:35:54 +00002142static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2143 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2144 if (uop->getOpcode() == UO_AddrOf)
2145 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002146 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002147}
2148
John McCall31168b02011-06-15 23:02:42 +00002149/// Emit an argument that's being passed call-by-writeback. That is,
2150/// we are passing the address of
2151static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2152 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002153 LValue srcLV;
2154
2155 // Make an optimistic effort to emit the address as an l-value.
2156 // This can fail if the the argument expression is more complicated.
2157 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2158 srcLV = CGF.EmitLValue(lvExpr);
2159
2160 // Otherwise, just emit it as a scalar.
2161 } else {
2162 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
2163
2164 QualType srcAddrType =
2165 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
2166 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
2167 }
2168 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002169
2170 // The dest and src types don't necessarily match in LLVM terms
2171 // because of the crazy ObjC compatibility rules.
2172
Chris Lattner2192fe52011-07-18 04:24:23 +00002173 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00002174 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2175
2176 // If the address is a constant null, just pass the appropriate null.
2177 if (isProvablyNull(srcAddr)) {
2178 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2179 CRE->getType());
2180 return;
2181 }
2182
John McCall31168b02011-06-15 23:02:42 +00002183 // Create the temporary.
2184 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
2185 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002186 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2187 // and that cleanup will be conditional if we can't prove that the l-value
2188 // isn't null, so we need to register a dominating point so that the cleanups
2189 // system will make valid IR.
2190 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2191
John McCall31168b02011-06-15 23:02:42 +00002192 // Zero-initialize it if we're not doing a copy-initialization.
2193 bool shouldCopy = CRE->shouldCopy();
2194 if (!shouldCopy) {
2195 llvm::Value *null =
2196 llvm::ConstantPointerNull::get(
2197 cast<llvm::PointerType>(destType->getElementType()));
2198 CGF.Builder.CreateStore(null, temp);
2199 }
Craig Topper8a13c412014-05-21 05:09:00 +00002200
2201 llvm::BasicBlock *contBB = nullptr;
2202 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002203
2204 // If the address is *not* known to be non-null, we need to switch.
2205 llvm::Value *finalArgument;
2206
2207 bool provablyNonNull = isProvablyNonNull(srcAddr);
2208 if (provablyNonNull) {
2209 finalArgument = temp;
2210 } else {
2211 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2212
2213 finalArgument = CGF.Builder.CreateSelect(isNull,
2214 llvm::ConstantPointerNull::get(destType),
2215 temp, "icr.argument");
2216
2217 // If we need to copy, then the load has to be conditional, which
2218 // means we need control flow.
2219 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00002220 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002221 contBB = CGF.createBasicBlock("icr.cont");
2222 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2223 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2224 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002225 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00002226 }
2227 }
2228
Craig Topper8a13c412014-05-21 05:09:00 +00002229 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00002230
John McCall31168b02011-06-15 23:02:42 +00002231 // Perform a copy if necessary.
2232 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002233 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002234 assert(srcRV.isScalar());
2235
2236 llvm::Value *src = srcRV.getScalarVal();
2237 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2238 "icr.cast");
2239
2240 // Use an ordinary store, not a store-to-lvalue.
2241 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00002242
2243 // If optimization is enabled, and the value was held in a
2244 // __strong variable, we need to tell the optimizer that this
2245 // value has to stay alive until we're doing the store back.
2246 // This is because the temporary is effectively unretained,
2247 // and so otherwise we can violate the high-level semantics.
2248 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2249 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2250 valueToUse = src;
2251 }
John McCall31168b02011-06-15 23:02:42 +00002252 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002253
John McCall31168b02011-06-15 23:02:42 +00002254 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002255 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00002256 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002257 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00002258
2259 // Make a phi for the value to intrinsically use.
2260 if (valueToUse) {
2261 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2262 "icr.to-use");
2263 phiToUse->addIncoming(valueToUse, copyBB);
2264 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2265 originBB);
2266 valueToUse = phiToUse;
2267 }
2268
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002269 condEval.end(CGF);
2270 }
John McCall31168b02011-06-15 23:02:42 +00002271
John McCalleff18842013-03-23 02:35:54 +00002272 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002273 args.add(RValue::get(finalArgument), CRE->getType());
2274}
2275
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002276void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2277 assert(!StackBase && !StackCleanup.isValid());
2278
2279 // Save the stack.
2280 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
2281 StackBase = CGF.Builder.CreateCall(F, "inalloca.save");
2282
2283 // Control gets really tied up in landing pads, so we have to spill the
2284 // stacksave to an alloca to avoid violating SSA form.
2285 // TODO: This is dead if we never emit the cleanup. We should create the
2286 // alloca and store lazily on the first cleanup emission.
2287 StackBaseMem = CGF.CreateTempAlloca(CGF.Int8PtrTy, "inalloca.spmem");
2288 CGF.Builder.CreateStore(StackBase, StackBaseMem);
2289 CGF.pushStackRestore(EHCleanup, StackBaseMem);
2290 StackCleanup = CGF.EHStack.getInnermostEHScope();
2291 assert(StackCleanup.isValid());
2292}
2293
2294void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2295 if (StackBase) {
2296 CGF.DeactivateCleanupBlock(StackCleanup, StackBase);
2297 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
2298 // We could load StackBase from StackBaseMem, but in the non-exceptional
2299 // case we can skip it.
2300 CGF.Builder.CreateCall(F, StackBase);
2301 }
2302}
2303
Reid Kleckner739756c2013-12-04 19:23:12 +00002304void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2305 ArrayRef<QualType> ArgTypes,
2306 CallExpr::const_arg_iterator ArgBeg,
2307 CallExpr::const_arg_iterator ArgEnd,
2308 bool ForceColumnInfo) {
2309 CGDebugInfo *DI = getDebugInfo();
2310 SourceLocation CallLoc;
2311 if (DI) CallLoc = DI->getLocation();
2312
2313 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2314 // because arguments are destroyed left to right in the callee.
2315 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002316 // Insert a stack save if we're going to need any inalloca args.
2317 bool HasInAllocaArgs = false;
2318 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2319 I != E && !HasInAllocaArgs; ++I)
2320 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2321 if (HasInAllocaArgs) {
2322 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2323 Args.allocateArgumentMemory(*this);
2324 }
2325
2326 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00002327 size_t CallArgsStart = Args.size();
2328 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2329 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2330 EmitCallArg(Args, *Arg, ArgTypes[I]);
2331 // Restore the debug location.
2332 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2333 }
2334
2335 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2336 // IR function.
2337 std::reverse(Args.begin() + CallArgsStart, Args.end());
2338 return;
2339 }
2340
2341 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2342 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2343 assert(Arg != ArgEnd);
2344 EmitCallArg(Args, *Arg, ArgTypes[I]);
2345 // Restore the debug location.
2346 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2347 }
2348}
2349
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002350namespace {
2351
2352struct DestroyUnpassedArg : EHScopeStack::Cleanup {
2353 DestroyUnpassedArg(llvm::Value *Addr, QualType Ty)
2354 : Addr(Addr), Ty(Ty) {}
2355
2356 llvm::Value *Addr;
2357 QualType Ty;
2358
Craig Topper4f12f102014-03-12 06:41:41 +00002359 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002360 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2361 assert(!Dtor->isTrivial());
2362 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2363 /*Delegating=*/false, Addr);
2364 }
2365};
2366
2367}
2368
John McCall32ea9692011-03-11 20:59:21 +00002369void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2370 QualType type) {
John McCall31168b02011-06-15 23:02:42 +00002371 if (const ObjCIndirectCopyRestoreExpr *CRE
2372 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002373 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002374 assert(getContext().hasSameType(E->getType(), type));
2375 return emitWritebackArg(*this, args, CRE);
2376 }
2377
John McCall0a76c0c2011-08-26 18:42:59 +00002378 assert(type->isReferenceType() == E->isGLValue() &&
2379 "reference binding to unmaterialized r-value!");
2380
John McCall17054bd62011-08-26 21:08:13 +00002381 if (E->isGLValue()) {
2382 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002383 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002384 }
Mike Stump11289f42009-09-09 15:08:12 +00002385
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002386 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2387
2388 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2389 // However, we still have to push an EH-only cleanup in case we unwind before
2390 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00002391 if (HasAggregateEvalKind &&
2392 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2393 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00002394 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00002395 AggValueSlot Slot;
2396 if (args.isUsingInAlloca())
2397 Slot = createPlaceholderSlot(*this, type);
2398 else
2399 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00002400
2401 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2402 bool DestroyedInCallee =
2403 RD && RD->hasNonTrivialDestructor() &&
2404 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
2405 if (DestroyedInCallee)
2406 Slot.setExternallyDestructed();
2407
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002408 EmitAggExpr(E, Slot);
2409 RValue RV = Slot.asRValue();
2410 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002411
Reid Klecknere39ee212014-05-03 00:33:28 +00002412 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002413 // Create a no-op GEP between the placeholder and the cleanup so we can
2414 // RAUW it successfully. It also serves as a marker of the first
2415 // instruction where the cleanup is active.
2416 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddr(), type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002417 // This unreachable is a temporary marker which will be removed later.
2418 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2419 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002420 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002421 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002422 }
2423
2424 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00002425 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2426 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2427 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00002428 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2429 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2430 } else {
2431 // We can't represent a misaligned lvalue in the CallArgList, so copy
2432 // to an aligned temporary now.
2433 llvm::Value *tmp = CreateMemTemp(type);
2434 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2435 L.getAlignment());
2436 args.add(RValue::getAggregate(tmp), type);
2437 }
Eli Friedmandf968192011-05-26 00:10:27 +00002438 return;
2439 }
2440
John McCall32ea9692011-03-11 20:59:21 +00002441 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00002442}
2443
Dan Gohman515a60d2012-02-16 00:57:37 +00002444// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2445// optimizer it can aggressively ignore unwind edges.
2446void
2447CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2448 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2449 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2450 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2451 CGM.getNoObjCARCExceptionsMetadata());
2452}
2453
John McCall882987f2013-02-28 19:01:20 +00002454/// Emits a call to the given no-arguments nounwind runtime function.
2455llvm::CallInst *
2456CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2457 const llvm::Twine &name) {
2458 return EmitNounwindRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2459}
2460
2461/// Emits a call to the given nounwind runtime function.
2462llvm::CallInst *
2463CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2464 ArrayRef<llvm::Value*> args,
2465 const llvm::Twine &name) {
2466 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2467 call->setDoesNotThrow();
2468 return call;
2469}
2470
2471/// Emits a simple call (never an invoke) to the given no-arguments
2472/// runtime function.
2473llvm::CallInst *
2474CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2475 const llvm::Twine &name) {
2476 return EmitRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2477}
2478
2479/// Emits a simple call (never an invoke) to the given runtime
2480/// function.
2481llvm::CallInst *
2482CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2483 ArrayRef<llvm::Value*> args,
2484 const llvm::Twine &name) {
2485 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2486 call->setCallingConv(getRuntimeCC());
2487 return call;
2488}
2489
2490/// Emits a call or invoke to the given noreturn runtime function.
2491void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2492 ArrayRef<llvm::Value*> args) {
2493 if (getInvokeDest()) {
2494 llvm::InvokeInst *invoke =
2495 Builder.CreateInvoke(callee,
2496 getUnreachableBlock(),
2497 getInvokeDest(),
2498 args);
2499 invoke->setDoesNotReturn();
2500 invoke->setCallingConv(getRuntimeCC());
2501 } else {
2502 llvm::CallInst *call = Builder.CreateCall(callee, args);
2503 call->setDoesNotReturn();
2504 call->setCallingConv(getRuntimeCC());
2505 Builder.CreateUnreachable();
2506 }
Justin Bogner06bd6d02014-01-13 21:24:18 +00002507 PGO.setCurrentRegionUnreachable();
John McCall882987f2013-02-28 19:01:20 +00002508}
2509
2510/// Emits a call or invoke instruction to the given nullary runtime
2511/// function.
2512llvm::CallSite
2513CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2514 const Twine &name) {
2515 return EmitRuntimeCallOrInvoke(callee, ArrayRef<llvm::Value*>(), name);
2516}
2517
2518/// Emits a call or invoke instruction to the given runtime function.
2519llvm::CallSite
2520CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2521 ArrayRef<llvm::Value*> args,
2522 const Twine &name) {
2523 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2524 callSite.setCallingConv(getRuntimeCC());
2525 return callSite;
2526}
2527
2528llvm::CallSite
2529CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2530 const Twine &Name) {
2531 return EmitCallOrInvoke(Callee, ArrayRef<llvm::Value *>(), Name);
2532}
2533
John McCallbd309292010-07-06 01:34:17 +00002534/// Emits a call or invoke instruction to the given function, depending
2535/// on the current state of the EH stack.
2536llvm::CallSite
2537CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00002538 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002539 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00002540 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00002541
Dan Gohman515a60d2012-02-16 00:57:37 +00002542 llvm::Instruction *Inst;
2543 if (!InvokeDest)
2544 Inst = Builder.CreateCall(Callee, Args, Name);
2545 else {
2546 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2547 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2548 EmitBlock(ContBB);
2549 }
2550
2551 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2552 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002553 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002554 AddObjCARCExceptionMetadata(Inst);
2555
2556 return Inst;
John McCallbd309292010-07-06 01:34:17 +00002557}
2558
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002559static void checkArgMatches(llvm::Value *Elt, unsigned &ArgNo,
2560 llvm::FunctionType *FTy) {
2561 if (ArgNo < FTy->getNumParams())
2562 assert(Elt->getType() == FTy->getParamType(ArgNo));
2563 else
2564 assert(FTy->isVarArg());
2565 ++ArgNo;
2566}
2567
Chris Lattnerd59d8672011-07-12 06:29:11 +00002568void CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
Craig Topper5603df42013-07-05 19:34:19 +00002569 SmallVectorImpl<llvm::Value *> &Args,
Chris Lattnerd59d8672011-07-12 06:29:11 +00002570 llvm::FunctionType *IRFuncTy) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002571 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2572 unsigned NumElts = AT->getSize().getZExtValue();
2573 QualType EltTy = AT->getElementType();
2574 llvm::Value *Addr = RV.getAggregateAddr();
2575 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
2576 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, Elt);
Nick Lewycky2d84e842013-10-02 02:29:49 +00002577 RValue EltRV = convertTempToRValue(EltAddr, EltTy, SourceLocation());
Bob Wilsone826a2a2011-08-03 05:58:22 +00002578 ExpandTypeToArgs(EltTy, EltRV, Args, IRFuncTy);
Chris Lattnerd59d8672011-07-12 06:29:11 +00002579 }
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002580 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002581 RecordDecl *RD = RT->getDecl();
2582 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
Eli Friedman7f1ff602012-04-16 03:54:45 +00002583 LValue LV = MakeAddrLValue(RV.getAggregateAddr(), Ty);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002584
2585 if (RD->isUnion()) {
Craig Topper8a13c412014-05-21 05:09:00 +00002586 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002587 CharUnits UnionSize = CharUnits::Zero();
2588
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002589 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002590 assert(!FD->isBitField() &&
2591 "Cannot expand structure with bit-field members.");
2592 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
2593 if (UnionSize < FieldSize) {
2594 UnionSize = FieldSize;
2595 LargestFD = FD;
2596 }
2597 }
2598 if (LargestFD) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002599 RValue FldRV = EmitRValueForField(LV, LargestFD, SourceLocation());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002600 ExpandTypeToArgs(LargestFD->getType(), FldRV, Args, IRFuncTy);
2601 }
2602 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002603 for (const auto *FD : RD->fields()) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002604 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002605 ExpandTypeToArgs(FD->getType(), FldRV, Args, IRFuncTy);
2606 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00002607 }
Eli Friedman95ff7002011-11-15 02:46:03 +00002608 } else if (Ty->isAnyComplexType()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002609 ComplexPairTy CV = RV.getComplexVal();
2610 Args.push_back(CV.first);
2611 Args.push_back(CV.second);
2612 } else {
Chris Lattnerd59d8672011-07-12 06:29:11 +00002613 assert(RV.isScalar() &&
2614 "Unexpected non-scalar rvalue during struct expansion.");
2615
2616 // Insert a bitcast as needed.
2617 llvm::Value *V = RV.getScalarVal();
2618 if (Args.size() < IRFuncTy->getNumParams() &&
2619 V->getType() != IRFuncTy->getParamType(Args.size()))
2620 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(Args.size()));
2621
2622 Args.push_back(V);
2623 }
2624}
2625
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002626/// \brief Store a non-aggregate value to an address to initialize it. For
2627/// initialization, a non-atomic store will be used.
2628static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
2629 LValue Dst) {
2630 if (Src.isScalar())
2631 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
2632 else
2633 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
2634}
2635
2636void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
2637 llvm::Value *New) {
2638 DeferredReplacements.push_back(std::make_pair(Old, New));
2639}
Chris Lattnerd59d8672011-07-12 06:29:11 +00002640
Daniel Dunbard931a872009-02-02 22:03:45 +00002641RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00002642 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00002643 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002644 const CallArgList &CallArgs,
David Chisnall9eecafa2010-05-01 11:15:56 +00002645 const Decl *TargetDecl,
David Chisnallff5f88c2010-05-02 13:41:58 +00002646 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00002647 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002648 SmallVector<llvm::Value*, 16> Args;
Daniel Dunbar613855c2008-09-09 23:27:19 +00002649
2650 // Handle struct-return functions by passing a pointer to the
2651 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00002652 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002653 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002654
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002655 // IRArgNo - Keep track of the argument number in the callee we're looking at.
2656 unsigned IRArgNo = 0;
2657 llvm::FunctionType *IRFuncTy =
2658 cast<llvm::FunctionType>(
2659 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00002660
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002661 // If we're using inalloca, insert the allocation after the stack save.
2662 // FIXME: Do this earlier rather than hacking it in here!
Craig Topper8a13c412014-05-21 05:09:00 +00002663 llvm::Value *ArgMemory = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002664 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
Reid Kleckner9df1d972014-04-10 01:40:15 +00002665 llvm::Instruction *IP = CallArgs.getStackBase();
2666 llvm::AllocaInst *AI;
2667 if (IP) {
2668 IP = IP->getNextNode();
2669 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
2670 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00002671 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00002672 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002673 AI->setUsedWithInAlloca(true);
2674 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
2675 ArgMemory = AI;
2676 }
2677
Chris Lattner4ca97c32009-06-13 00:26:38 +00002678 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00002679 // alloca to hold the result, unless one is given to us.
Craig Topper8a13c412014-05-21 05:09:00 +00002680 llvm::Value *SRetPtr = nullptr;
Reid Kleckner37abaca2014-05-09 22:46:15 +00002681 bool SwapThisWithSRet = false;
2682 if (RetAI.isIndirect() || RetAI.isInAlloca()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002683 SRetPtr = ReturnValue.getValue();
2684 if (!SRetPtr)
2685 SRetPtr = CreateMemTemp(RetTy);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002686 if (RetAI.isIndirect()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002687 Args.push_back(SRetPtr);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002688 SwapThisWithSRet = RetAI.isSRetAfterThis();
2689 if (SwapThisWithSRet)
2690 IRArgNo = 1;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002691 checkArgMatches(SRetPtr, IRArgNo, IRFuncTy);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002692 if (SwapThisWithSRet)
2693 IRArgNo = 0;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002694 } else {
2695 llvm::Value *Addr =
2696 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
2697 Builder.CreateStore(SRetPtr, Addr);
2698 }
Anders Carlsson17490832009-12-24 20:40:36 +00002699 }
Mike Stump11289f42009-09-09 15:08:12 +00002700
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002701 assert(CallInfo.arg_size() == CallArgs.size() &&
2702 "Mismatch between function signature & arguments.");
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002703 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002704 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002705 I != E; ++I, ++info_it) {
2706 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002707 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002708
Reid Kleckner37abaca2014-05-09 22:46:15 +00002709 // Skip 'sret' if it came second.
2710 if (IRArgNo == 1 && SwapThisWithSRet)
2711 ++IRArgNo;
2712
John McCall47fb9502013-03-07 21:37:08 +00002713 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002714
2715 // Insert a padding argument to ensure proper alignment.
2716 if (llvm::Type *PaddingType = ArgInfo.getPaddingType()) {
2717 Args.push_back(llvm::UndefValue::get(PaddingType));
2718 ++IRArgNo;
2719 }
2720
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002721 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002722 case ABIArgInfo::InAlloca: {
2723 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2724 if (RV.isAggregate()) {
2725 // Replace the placeholder with the appropriate argument slot GEP.
2726 llvm::Instruction *Placeholder =
2727 cast<llvm::Instruction>(RV.getAggregateAddr());
2728 CGBuilderTy::InsertPoint IP = Builder.saveIP();
2729 Builder.SetInsertPoint(Placeholder);
2730 llvm::Value *Addr = Builder.CreateStructGEP(
2731 ArgMemory, ArgInfo.getInAllocaFieldIndex());
2732 Builder.restoreIP(IP);
2733 deferPlaceholderReplacement(Placeholder, Addr);
2734 } else {
2735 // Store the RValue into the argument struct.
2736 llvm::Value *Addr =
2737 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
David Majnemer32b57b02014-03-31 16:12:47 +00002738 unsigned AS = Addr->getType()->getPointerAddressSpace();
2739 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
2740 // There are some cases where a trivial bitcast is not avoidable. The
2741 // definition of a type later in a translation unit may change it's type
2742 // from {}* to (%struct.foo*)*.
2743 if (Addr->getType() != MemType)
2744 Addr = Builder.CreateBitCast(Addr, MemType);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002745 LValue argLV = MakeAddrLValue(Addr, I->Ty, TypeAlign);
2746 EmitInitStoreOfNonAggregate(*this, RV, argLV);
2747 }
2748 break; // Don't increment IRArgNo!
2749 }
2750
Daniel Dunbar03816342010-08-21 02:24:36 +00002751 case ABIArgInfo::Indirect: {
Daniel Dunbar747865a2009-02-05 09:16:39 +00002752 if (RV.isScalar() || RV.isComplex()) {
2753 // Make a temporary alloca to pass the argument.
Eli Friedman7e68c882011-06-15 18:26:32 +00002754 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2755 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
2756 AI->setAlignment(ArgInfo.getIndirectAlign());
2757 Args.push_back(AI);
John McCall47fb9502013-03-07 21:37:08 +00002758
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002759 LValue argLV = MakeAddrLValue(Args.back(), I->Ty, TypeAlign);
2760 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002761
2762 // Validate argument match.
2763 checkArgMatches(AI, IRArgNo, IRFuncTy);
Daniel Dunbar747865a2009-02-05 09:16:39 +00002764 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002765 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00002766 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002767 // 1. If the argument is not byval, and we are required to copy the
2768 // source. (This case doesn't occur on any common architecture.)
2769 // 2. If the argument is byval, RV is not sufficiently aligned, and
2770 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00002771 // 3. If the argument is byval, but RV is located in an address space
2772 // different than that of the argument (0).
Eli Friedmanf7456192011-06-15 22:09:18 +00002773 llvm::Value *Addr = RV.getAggregateAddr();
2774 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002775 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyei3832bfd2013-03-10 12:59:00 +00002776 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
2777 const unsigned ArgAddrSpace = (IRArgNo < IRFuncTy->getNumParams() ?
2778 IRFuncTy->getParamType(IRArgNo)->getPointerAddressSpace() : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00002779 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall47fb9502013-03-07 21:37:08 +00002780 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Guy Benyei3832bfd2013-03-10 12:59:00 +00002781 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
2782 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002783 // Create an aligned temporary, and copy to it.
Eli Friedmanf7456192011-06-15 22:09:18 +00002784 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2785 if (Align > AI->getAlignment())
2786 AI->setAlignment(Align);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002787 Args.push_back(AI);
Chad Rosier615ed1a2012-03-29 17:37:10 +00002788 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002789
2790 // Validate argument match.
2791 checkArgMatches(AI, IRArgNo, IRFuncTy);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002792 } else {
2793 // Skip the extra memcpy call.
Eli Friedmanf7456192011-06-15 22:09:18 +00002794 Args.push_back(Addr);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002795
2796 // Validate argument match.
2797 checkArgMatches(Addr, IRArgNo, IRFuncTy);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002798 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002799 }
2800 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002801 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002802
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002803 case ABIArgInfo::Ignore:
2804 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002805
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002806 case ABIArgInfo::Extend:
2807 case ABIArgInfo::Direct: {
2808 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002809 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
2810 ArgInfo.getDirectOffset() == 0) {
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002811 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002812 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002813 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002814 else
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002815 V = Builder.CreateLoad(RV.getAggregateAddr());
2816
Chris Lattner3ce86682011-07-12 04:53:39 +00002817 // If the argument doesn't match, perform a bitcast to coerce it. This
2818 // can happen due to trivial type mismatches.
2819 if (IRArgNo < IRFuncTy->getNumParams() &&
2820 V->getType() != IRFuncTy->getParamType(IRArgNo))
2821 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRArgNo));
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002822 Args.push_back(V);
2823
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002824 checkArgMatches(V, IRArgNo, IRFuncTy);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002825 break;
2826 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002827
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002828 // FIXME: Avoid the conversion through memory if possible.
2829 llvm::Value *SrcPtr;
John McCall47fb9502013-03-07 21:37:08 +00002830 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002831 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall47fb9502013-03-07 21:37:08 +00002832 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002833 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Mike Stump11289f42009-09-09 15:08:12 +00002834 } else
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002835 SrcPtr = RV.getAggregateAddr();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002836
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002837 // If the value is offset in memory, apply the offset now.
2838 if (unsigned Offs = ArgInfo.getDirectOffset()) {
2839 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
2840 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002841 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002842 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
2843
2844 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002845
Chris Lattner3dd716c2010-06-28 23:44:11 +00002846 // If the coerce-to type is a first class aggregate, we flatten it and
2847 // pass the elements. Either way is semantically identical, but fast-isel
2848 // and the optimizer generally likes scalar values better than FCAs.
James Molloy6f244b62014-05-09 16:21:39 +00002849 // We cannot do this for functions using the AAPCS calling convention,
2850 // as structures are treated differently by that calling convention.
2851 llvm::StructType *STy =
2852 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
2853 if (STy && !isAAPCSVFP(CallInfo, getTarget())) {
Chandler Carrutha6399a52012-10-10 11:29:08 +00002854 llvm::Type *SrcTy =
2855 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
2856 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
2857 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
2858
2859 // If the source type is smaller than the destination type of the
2860 // coerce-to logic, copy the source value into a temp alloca the size
2861 // of the destination type to allow loading all of it. The bits past
2862 // the source value are left undef.
2863 if (SrcSize < DstSize) {
2864 llvm::AllocaInst *TempAlloca
2865 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
2866 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
2867 SrcPtr = TempAlloca;
2868 } else {
2869 SrcPtr = Builder.CreateBitCast(SrcPtr,
2870 llvm::PointerType::getUnqual(STy));
2871 }
2872
Chris Lattnerceddafb2010-07-05 20:41:41 +00002873 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2874 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerff941a62010-07-28 18:24:28 +00002875 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
2876 // We don't know what we're loading from.
2877 LI->setAlignment(1);
2878 Args.push_back(LI);
Alexey Samsonov3551e312014-08-13 20:06:24 +00002879
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002880 // Validate argument match.
2881 checkArgMatches(LI, IRArgNo, IRFuncTy);
Chris Lattner15ec3612010-06-29 00:06:42 +00002882 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00002883 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00002884 // In the simple case, just pass the coerced loaded value.
2885 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
2886 *this));
Alexey Samsonov3551e312014-08-13 20:06:24 +00002887
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002888 // Validate argument match.
2889 checkArgMatches(Args.back(), IRArgNo, IRFuncTy);
Chris Lattner3dd716c2010-06-28 23:44:11 +00002890 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002891
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002892 break;
2893 }
2894
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002895 case ABIArgInfo::Expand:
Chris Lattnerd59d8672011-07-12 06:29:11 +00002896 ExpandTypeToArgs(I->Ty, RV, Args, IRFuncTy);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002897 IRArgNo = Args.size();
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002898 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00002899 }
2900 }
Mike Stump11289f42009-09-09 15:08:12 +00002901
Reid Kleckner37abaca2014-05-09 22:46:15 +00002902 if (SwapThisWithSRet)
2903 std::swap(Args[0], Args[1]);
2904
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002905 if (ArgMemory) {
2906 llvm::Value *Arg = ArgMemory;
Reid Klecknerafba553e2014-07-08 02:24:27 +00002907 if (CallInfo.isVariadic()) {
2908 // When passing non-POD arguments by value to variadic functions, we will
2909 // end up with a variadic prototype and an inalloca call site. In such
2910 // cases, we can't do any parameter mismatch checks. Give up and bitcast
2911 // the callee.
2912 unsigned CalleeAS =
2913 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
2914 Callee = Builder.CreateBitCast(
2915 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
2916 } else {
2917 llvm::Type *LastParamTy =
2918 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
2919 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002920#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00002921 // Assert that these structs have equivalent element types.
2922 llvm::StructType *FullTy = CallInfo.getArgStruct();
2923 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
2924 cast<llvm::PointerType>(LastParamTy)->getElementType());
2925 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
2926 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
2927 DE = DeclaredTy->element_end(),
2928 FI = FullTy->element_begin();
2929 DI != DE; ++DI, ++FI)
2930 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002931#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00002932 Arg = Builder.CreateBitCast(Arg, LastParamTy);
2933 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002934 }
2935 Args.push_back(Arg);
2936 }
2937
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002938 if (!CallArgs.getCleanupsToDeactivate().empty())
2939 deactivateArgCleanupsBeforeCall(*this, CallArgs);
2940
Chris Lattner4ca97c32009-06-13 00:26:38 +00002941 // If the callee is a bitcast of a function to a varargs pointer to function
2942 // type, check to see if we can remove the bitcast. This handles some cases
2943 // with unprototyped functions.
2944 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
2945 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002946 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
2947 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00002948 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00002949 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00002950
Chris Lattner4ca97c32009-06-13 00:26:38 +00002951 if (CE->getOpcode() == llvm::Instruction::BitCast &&
2952 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00002953 ActualFT->getNumParams() == CurFT->getNumParams() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00002954 ActualFT->getNumParams() == Args.size() &&
2955 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00002956 bool ArgsMatch = true;
2957 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
2958 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
2959 ArgsMatch = false;
2960 break;
2961 }
Mike Stump11289f42009-09-09 15:08:12 +00002962
Chris Lattner4ca97c32009-06-13 00:26:38 +00002963 // Strip the cast if we can get away with it. This is a nice cleanup,
2964 // but also allows us to inline the function at -O0 if it is marked
2965 // always_inline.
2966 if (ArgsMatch)
2967 Callee = CalleeF;
2968 }
2969 }
Mike Stump11289f42009-09-09 15:08:12 +00002970
Daniel Dunbar0ef34792009-09-12 00:59:20 +00002971 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00002972 CodeGen::AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00002973 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
2974 CallingConv, true);
Bill Wendling3087d022012-12-07 23:17:26 +00002975 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00002976 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00002977
Craig Topper8a13c412014-05-21 05:09:00 +00002978 llvm::BasicBlock *InvokeDest = nullptr;
Bill Wendling5e85be42012-12-30 10:32:17 +00002979 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
2980 llvm::Attribute::NoUnwind))
John McCallbd309292010-07-06 01:34:17 +00002981 InvokeDest = getInvokeDest();
2982
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002983 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00002984 if (!InvokeDest) {
Jay Foad5bd375a2011-07-15 08:37:34 +00002985 CS = Builder.CreateCall(Callee, Args);
Daniel Dunbar12347492009-02-23 17:26:39 +00002986 } else {
2987 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Jay Foad5bd375a2011-07-15 08:37:34 +00002988 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, Args);
Daniel Dunbar12347492009-02-23 17:26:39 +00002989 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00002990 }
Chris Lattnere70a0072010-06-29 16:40:28 +00002991 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00002992 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00002993
Peter Collingbourne41af7c22014-05-20 17:12:51 +00002994 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
2995 !CS.hasFnAttr(llvm::Attribute::NoInline))
2996 Attrs =
2997 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
2998 llvm::Attribute::AlwaysInline);
2999
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003000 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003001 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003002
Dan Gohman515a60d2012-02-16 00:57:37 +00003003 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3004 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003005 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003006 AddObjCARCExceptionMetadata(CS.getInstruction());
3007
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003008 // If the call doesn't return, finish the basic block and clear the
3009 // insertion point; this allows the rest of IRgen to discard
3010 // unreachable code.
3011 if (CS.doesNotReturn()) {
3012 Builder.CreateUnreachable();
3013 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003014
Mike Stump18bb9282009-05-16 07:57:57 +00003015 // FIXME: For now, emit a dummy basic block because expr emitters in
3016 // generally are not ready to handle emitting expressions at unreachable
3017 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003018 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003019
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003020 // Return a reasonable RValue.
3021 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003022 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003023
3024 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00003025 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003026 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003027
John McCall31168b02011-06-15 23:02:42 +00003028 // Emit any writebacks immediately. Arguably this should happen
3029 // after any return-value munging.
3030 if (CallArgs.hasWritebacks())
3031 emitWritebacks(*this, CallArgs);
3032
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003033 // The stack cleanup for inalloca arguments has to run out of the normal
3034 // lexical order, so deactivate it and run it manually here.
3035 CallArgs.freeArgumentMemory(*this);
3036
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003037 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003038 case ABIArgInfo::InAlloca:
John McCall47fb9502013-03-07 21:37:08 +00003039 case ABIArgInfo::Indirect:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003040 return convertTempToRValue(SRetPtr, RetTy, SourceLocation());
Daniel Dunbard3674e62008-09-11 01:48:57 +00003041
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003042 case ABIArgInfo::Ignore:
Daniel Dunbar01362822009-02-03 06:30:17 +00003043 // If we are ignoring an argument that had a result, make sure to
3044 // construct the appropriate return value for our caller.
Daniel Dunbarc79407f2009-02-05 07:09:07 +00003045 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003046
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003047 case ABIArgInfo::Extend:
3048 case ABIArgInfo::Direct: {
Chris Lattner3517f142011-07-13 03:59:32 +00003049 llvm::Type *RetIRTy = ConvertType(RetTy);
3050 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
John McCall47fb9502013-03-07 21:37:08 +00003051 switch (getEvaluationKind(RetTy)) {
3052 case TEK_Complex: {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003053 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
3054 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
3055 return RValue::getComplex(std::make_pair(Real, Imag));
3056 }
John McCall47fb9502013-03-07 21:37:08 +00003057 case TEK_Aggregate: {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003058 llvm::Value *DestPtr = ReturnValue.getValue();
3059 bool DestIsVolatile = ReturnValue.isVolatile();
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003060
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003061 if (!DestPtr) {
3062 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3063 DestIsVolatile = false;
3064 }
Eli Friedmanaf9b3252011-05-17 21:08:01 +00003065 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003066 return RValue::getAggregate(DestPtr);
3067 }
John McCall47fb9502013-03-07 21:37:08 +00003068 case TEK_Scalar: {
3069 // If the argument doesn't match, perform a bitcast to coerce it. This
3070 // can happen due to trivial type mismatches.
3071 llvm::Value *V = CI;
3072 if (V->getType() != RetIRTy)
3073 V = Builder.CreateBitCast(V, RetIRTy);
3074 return RValue::get(V);
3075 }
3076 }
3077 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003078 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003079
Anders Carlsson17490832009-12-24 20:40:36 +00003080 llvm::Value *DestPtr = ReturnValue.getValue();
3081 bool DestIsVolatile = ReturnValue.isVolatile();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003082
Anders Carlsson17490832009-12-24 20:40:36 +00003083 if (!DestPtr) {
Daniel Dunbara7566f12010-02-09 02:48:28 +00003084 DestPtr = CreateMemTemp(RetTy, "coerce");
Anders Carlsson17490832009-12-24 20:40:36 +00003085 DestIsVolatile = false;
3086 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003087
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003088 // If the value is offset in memory, apply the offset now.
3089 llvm::Value *StorePtr = DestPtr;
3090 if (unsigned Offs = RetAI.getDirectOffset()) {
3091 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
3092 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003093 StorePtr = Builder.CreateBitCast(StorePtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003094 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
3095 }
3096 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003097
Nick Lewycky2d84e842013-10-02 02:29:49 +00003098 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Daniel Dunbar573884e2008-09-10 07:04:09 +00003099 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003100
Daniel Dunbard3674e62008-09-11 01:48:57 +00003101 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00003102 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar613855c2008-09-09 23:27:19 +00003103 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003104
David Blaikie83d382b2011-09-23 05:06:16 +00003105 llvm_unreachable("Unhandled ABIArgInfo::Kind");
Daniel Dunbar613855c2008-09-09 23:27:19 +00003106}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003107
3108/* VarArg handling */
3109
3110llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
3111 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
3112}